Q:

What should the system be deleting automatically that it already isn't?

So this question got me thinking...
We have several automatic processes in place for cleaning up cruft, deleting questions that are very unlikely to help anyone else. They're fairly conservative though; an awful lot of lousy questions hang around much longer, occasionally cropping up to annoy folks and attract angst. That's not good for anyone.
The most recent updates to these rules were discussed and implemented here: Turbocharging the Roomba: solutions for premature deletion - but the rest of those rules haven't been updated in over three years.
I think it's high time to revisit the criteria used for these, and try to identify areas for improvement - the goal being to get rid of a much higher volume of useless questions without the need to manually close and delete them. Here's what I'm thinking:
If a question is more than 30 days old, and...

has a score of -1 or less, with no votes in the past 30 days
has no answers with a score > 0
is not locked

...it will be automatically deleted.
Notes on these criteria: the goal is to identify lackluster questions that never attracted an answer useful to someone else. The 30-day vote moratorium addresses a long-time complaint that the existing criteria allowed any downvoter to very quickly delete old questions with little time for review or correction on the part of the author.
Here's a SEDE query to give you an idea of the questions I'm talking about: http://data.stackexchange.com/stackoverflow/query/205342 (returns 100 semi-random questions meeting these criteria)
If a question has been closed for more than 30 days, and...

has a score of 0 or less
is not locked
has no answers with a score > 1
has no pending reopen votes

...it will be automatically deleted.
Notes on these criteria: the goal here is to identify closed questions that have neither particularly valuable answers and are unlikely to be re-opened. As such, we dispense with the logic that preserves answers with 1 vote or an accept mark that will stay deletion at 9 days. Downvoted duplicates are also added to the mix.
Here's a SEDE query to give you an idea of the questions I'm talking about: http://data.stackexchange.com/stackoverflow/query/205349  (returns 100 semi-random questions meeting these criteria)
To give you an idea of the sort of volume this would involve, I looked at the questions posted on Friday May 30th:

8881 questions were posted that day.
291 questions posted that day were closed that day.
429 questions posted that day were eventually closed.
961 questions posted that day currently score less than 0.
7665 questions posted that day are still visible on the site as I type this.
607 questions posted that day would be deleted if the new criteria were put into place.

That's another 7% of questions for that day that'd be removed immediately, with no work required from the folks on the site - no need to close them, no need to run them through the wringer here on meta or in chat, no need to do anything but just vote and then ignore them and let the system do its thing. In total, something north of 140K questions would be removed immediately if this were implemented, representing a rather large number of things that fell through the cracks.
As we continue to work on systems for emphasizing quality over crap, this sort of automatic cleanup system will become an increasingly-important method for keeping the underside of the proverbial rug from becoming too dusty.
Thoughts?

A:

Old zero scores with comments
These are questions that got duped, or solved elsewhere and ignored, or homework that passed its due date. Sometimes they have answers, or a few comments. The 365-day script will not delete a post that has an answer, or two or more comments.
Change this to a sliding scale. More comments can keep it around longer, but if it's 0 score with six comments, let that get cleaned up too.
A query to play with this: Questions where comments prevent deletion --- there are a lot of these questions that are sitting there, closed (sometimes not), low views, 0 score... and two comments. The first one is "What have you tried?" and the second one is saying "have you looked at ...?"
Scope of the nearly abandoned questions
To get an idea of the scope of this, duplicate:yes answers:0 score:0 shows us that there are about 15k questions that are dups that have no answers and no score.  The only thing keeping them around is the comments.
Removing the duplicate check, we get answers:0 score:0 which is 613k questions... or about 600 unclosed unanswered questions.  Going to unanswered tab we get 1,806,898 questions that have no upovted answers... or worded another way, about 1/3rd of the questions that have no answers with votes have 0 score and 0 answers with only comments on them.  Half of these questions haven't been active this year.
The only thing keeping these questions around is the comments and that they are not negatively scored.
For this, I do have a specific idea to consider:

Start the timer ticking at six months instead of a year.
Each month beyond that the threshold for the number of comments is increased by one.

Thus, a question with 0 score, 0 answers and 2 comments today would never be deleted; I'm suggesting deleting it at 7 months.  If it had 10 comments, that's 9 months more it could stick around to get clarified, but it should get deleted too if not.
Consider also - if the original poster of the question is deleted, just delete it at six months as they will never come back to read the comments to expand on the question. No one has cared to try to fix the question since then.
Sure, you might be deleting some questions that may someday get a good answer.  But you're also clogging up the space of people looking for good questions to answer.  The Wisdom of the Ancients doesn't help.
If someone has the same question, they can ask it... its unlikely they'll ever find the duplicate in that mess, and it can't be duped to it anyways (no up voted answer).
Locked migration stubs
This is a favorite of mine. The sequence goes:

Question asked on another site
Question migrated here
... time passes ...
Question closed

At this point, it's a rejected migration, so it gets locked. But nothing deletes rejected migrations. (The 30-day script deletes the question on the other site). As it's locked, the scripts won't even touch it. As it's locked, the 10ks can't delete it either.
Low view meh duplicates
How much traffic do the questions that get duped to something bring? Especially the (currently) 410 questions linked to the Java NPE question. You get the couple of FGITW answers on it and the answer is over there, and closed to keep more people from trying to answer it (I hope the dup hammer is helping)... but now it's a closed question with 0 score, 100 views after a year... and five answers (one of which was accepted)... and no one will ever find it.
For questions that have over 50 duplicates to them, delete the questions the duplicates that have the fewest views. 50 is still a lot, but it will save the 10ks lots of votes to delete trying to get that 410 down to 50.
More aggressive deleting of 'one up vote' closed questions.
I've got a query that I'll sometimes poke and do some light janitorial work. Cliff questions (v2).
Pick a month, and the results that you get back are things that can be deleted with a single downvote (or two sometimes). It finds lots of things that have really short answers with very few views. Someone did an up vote on the answer and... well, it's sticking around until someone downvotes it. Yea, someone found the answer 'helpful'... but a bunch of people said the question is very poor and it's been closed.
Consider, if the question is low view, has over five net downvotes (-11 +2 is a net -9) to the question for every up vote to the answers, has answers that have a length of less than 500 bytes, and possibly something about the quality filters here too (though a lot of these questions are 'code dump, I have a problem' that appear to get by the quality filters...)... delete it. Note: this says nothing about an accepted answer... the asker clicked the checkmark and that's keeping it from getting deleted by scripts forever.

As to the specific proposal, consider the additional criteria:

has never been undeleted

This may not be a bad thing for the other roomba scripts... It's fun watching moderators fight with Community sometimes, but when you want to get something done it's very frustrating. And maybe allow 10k votes to undelete the questions too? But that's getting into another can of worms.

A:

So this question got me thinking...

I think you are about to make a mistake, nothing you are proposing here would have stopped that from going wrong.  The real problem with that junk question was that it was not closed yet.  It didn't get closed until two months after it was posted.  And only because the OP drew attention to it.
I didn't list that systemic failure because I didn't think it was relevant for that particular question.  It was so bad that (probably) most SO users knew how to avoid looking at it.  The question title was bad enough to waive that red flag.  It is a pretty serious problem, there is only a mechanism to get rid of lousy questions.  The really bad ones stay around unclosed.  Both because SO users know how to avoid them.  And because the close dialog doesn't list decent options for them, it is only suitable for half-way decent attempts at asking a question.
So, please, don't start deleting questions that have answers, that doesn't solve anything.  What went fundamentally wrong next with that junk question is that it got re-activated.  Forcing users to look at it again.  The worse the question, the more likely that mishap.
There's only one domino you have to remove to stop that from falling over repeatedly.  Apply the rules you came up with to suppress re-activating the question.  And don't stop there, you can make much more sweeping rules:

if the question has less than 50 words then nobody wants to look at it again
if an edit just removes a tag then nobody wants to look at it again
if an edit changes 5 words or less then nobody wants to look at it again
if an editor is editing questions at less than 5 minutes intervals then nobody wants to look at them again

A:

My answer isn't really covering more things that should be deleted, but more of a "let's find a way to plug the abuse" method, since you're already looking at updating the criteria.

with no votes in the past 30 days

That's a step in the right direction, but I feel like it doesn't really cover the abuse. It's sad when someone comes along and downvotes a question and then all of a sudden it's eligible for automatic deletion at the next cleanup cycle. But the same can be said about anything. Downvote an answer back to zero? Oh, now the entire question is eligible for automated cleanup. I would propose you expand that criteria and make it more general. Make it so that all criteria must have been met for at least 30 days.
So for your first example, it'd be questions which have:

A negative score for at least 30 days;
No answers with a score > 0 for at least 30 days;
This prevent someone from down-voting an answer to make a question immediately eligible for clean-up. All of the answers will need to have been zero-score or lower for a full 30 days before making the question eligible.
Had no up-votes in the past 30 days;
Since the question has to have had a negative score for at least 30 days already, we have safely eliminated the "down-vote it to make it instantly eligible" abuse avenue. Here, we are saying that if it has received an up-vote in the past 30 days, it may still be valuable and should be kept around for a bit longer just in case. If it's only continuing to receive down-votes, though, there's no point in delaying its deletion any further.
Food for thought: This could potentially be extended to cover its answers as well. So any up-vote on the question or its answers would prevent automated deletion.
Not been locked within the past 30 days.
While probably much less common, locks tend to mean that something was happening to the question recently. It might be safer to keep something like that hanging around for a bit longer, just in case.

I'd also place emphasis on not having any active reopen votes in the past 30 days for the second example.
I think the expanded criteria will reinforce the idea of automated deletions while also preventing the "instant auto-delete eligibility" abuse. It shows that the question is bad and literally nothing has happened on it in the last month, and it's safe to say it can be deleted.


Q:

Disallowed Key Characters ajax response

I am creating a JSON object dynamically and when I send it via an ajax POST I get Disallowed Key Characters as the response. I know that my object is ok because I can create the SAME EXACT object manually and it sends fine. I tried escape() on all of my strings before adding them to the obj but that did not work either.
Am I missing something?
This is my post
$.ajax({
    type: 'POST',

    url: 'http://localhost/test',
    data: obj,
    dataType : 'JSON',
    success: function(){
        console.log('nice');
    }
});

I am using the same obj as in this post
Add to JSON without knowing its structure

A:

It turns out that this error was caused by CI's input library. On line 215 you will find _clean_input_keys function which uses preg_match() to disallow certain characters in your keys. So when you send JSON around and php recieves it as an array it can throw an error.
To fix this you can either extend the library or edit the CI core.


Q:

Design and Security Architecture - where should IPS/IDS be placed?

I am a system architecture working on projects - mostly CDN related projects - and I am currently a bit confused about where the IPS/IDS should be placed. We have a NGINX-based webserver for the edge which is being protected and monitored with NAXSI as its WAF. All servers are using SELinux, and they are using firewalld as their system firewall. Requests should be directly sent to the NGINX edge-server, and I am trying so hard to avoid network dumps.
The question is, where should the IPS/IDS be placed. Should it be on the edge-server itself or it should be on another machine? Performance is the most essential consideration that we should have.
|          |
|          |                            --->> OTHER SERVERS
| FIREWALL |                           /
|          |                          /
|          |  ---->>>    NGINX EDGE  ------>> OTHER SERVERS
|          |                          \
|          |                           \
|          |                            --->> OTHER SERVERS
|          |
|          |   should IPS be on NGINX EDGE? Or should I add another
|          |   machine in front of NGINX EDGE - Closer to Firewall ?

A:

Not far from a matter of taste... More exactly it really depends on too many factors to allow a definitive answer. Just some hints:

the sooner is better if you want to be warned against attacks against the edge server or the firewall itself
after the edge can be better if you have very high traffic to avoid a bottleneck at the IDS/IPS
after the edge can make sense if you have HTTPS traffic decrypted at the edge level and want to analyse it

But you could also imagine a Network IDS close to the firewall for non TLS encrypted traffic and Host IDS on the application servers for the TLS encrypted part


Q:

Cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements

Take the following code snippet (has to be run in cargo, so you can add the serde feature to num-bigint):
use num_bigint::BigInt;
use serde_derive::Deserialize;
use std::collections::HashMap;

#[derive(Debug, Deserialize)]
pub struct Trade<'a> {
    pub id: &'a str,
    pub price: BigInt,
    pub quantity: BigInt,
}

#[derive(Debug, Deserialize)]
pub struct TradeTable<'a> {
    pub trades: Vec<Trade<'a>>,
}

fn main() {
    let mut ether_trades: Vec<Trade> = Vec::new();
    ether_trades.push(Trade {
        id: "#1",
        price: BigInt::from(100),
        quantity: BigInt::from(2)
    });

    let mut trades: HashMap<&str, Vec<Trade>> = HashMap::new();
    trades.insert("ETH", ether_trades);
    println!("trades: {}", trades);
}

It yields this error when compiling:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements

And this note:
note: first, the lifetime cannot outlive the lifetime `'de` as defined on the impl at 34:17...

Now, I understand that I need to make 'a live shorter than 'de, but how can I do that? I don't know where the 'de lifetime is defined. I tried to use a colon like this:
'de: 'a

But that didn't work.

A:

Please check that one
TL;DR
#[derive(Debug, Deserialize)]
pub struct TradeTable<'a> {
    #[serde(borrow)]
    pub trades: Vec<Trade<'a>>,
}


Q:

Installing Python and OpenCV on Win10 64-bit

I want to install Python and use OpenCV with it. I am on a Windows 10 Laptop. 64-bit OS.
I am beyond confused about which version of Python and corresponding version of OpenCV to use; and how to install it.
Can someone post a small guide on how to get things working? I have been trying for weeks.

A:

I have a working configuration of Python 3.5.2 and OpenCV 3.1.0 on my Windows 10.
Download and install Python from:
https://www.python.org/downloads/windows/
For OpenCV, follow:
http://docs.opencv.org/3.1.0/d3/d52/tutorial_windows_install.html


Q:

Have there been any duels where both duelers were wielding Valyrian steel?

Valyrian steel is supposed to be a very good material to make weapons with, and to grant great advantage in combat. But have there been any duels where both duelers were wielding Valyrian steel?

A:

Aegor "Bittersteel" Rivers vs Brynden "Bloodraven" Rivers
Bittersteel wielded Aegon's blade Blackfyre while Bloodraven wielded Visenya's blade, Dark Sister:
Note: In the above, I’m speaking of Aegon I Targaryen, first King of Westeros. Below the quote talks about Aegon Blackfyre, a son of the bastard, Daemon Blackfyre. Bittersteel is Aegor Rivers

The rebellion ended at the Redgrass Field, nigh on a year later. Some have written of the boldness of the men who fought with Daemon, and others of their treason. But for all their valor in the field and their enmity against Daeron, theirs was a lost cause. Daemon and his eldest sons, Aegon and Aemon, were brought down beneath the withering fall of arrows sent by Brynden Rivers and his private guards, the Raven's Teeth. This was followed by Bittersteel's mad charge, with Blackfyre in his hand, as he attempted to rally Daemon's forces. Meeting with Bloodraven in the midst of the charge, a mighty duel ensued, which left Bloodraven blinded in one eye and sent Bittersteel fleeing.
The World of Ice and Fire, The Targaryen Kings: Daeron II

A quote from The Sworn Sword indicates Bloodraven was indeed wielding Dark Sister at the time.

Six years ago in King's Landing, Dunk had seen him with his own two eyes, as he rode a pale horse up the Street of Steel with fifty Raven's Teeth behind him. That was before King Aerys had ascended to the Iron Throne and made him the Hand, but even so he cut a striking figure, garbed in smoke and scarlet with Dark Sister on his hip.
The Sworn Sword

Although it was known that Bloodraven preferred his longbow made of weirwood, that would've been useless to him in a mighty duel against a prominent warrior.

Daemon I Targaryen vs Ser Gwayne Corbray of the Kingsguard
As indicated elsewhere, before the prior duel, and in the same battle, Daemon I Blackfyre duelled Ser Gwayne Corbray of the Kingsguard. Daemon I Blackfyre wielded Aegon's blade Blackfyre while Gwayne Corbray wielded Lady Forlorn, the ancestral sword of House Corbray.

Daemon was the Warrior himself that day. No man could stand before him. He broke Lord Arryn's van to pieces and slew the Knight of Ninestars and Wild Wyl Waynwood before coming up against Ser Gwayne Corbray of the Kingsguard.
The Sworn Sword

Also, Bloodraven and Daemon Blackfyre wield swords of Valyrian steel, as does Ser Gwayne Corbray of the Kingsguard, also prominent in the battle.
So Spake Martin - Concerning the Great Bastards

A:

If we considered that Lady Forlorn is Valyrian steel, yes.
During the First Blackfyre Rebellion, a duel opposed Daemon I Blackfyre (wielding Blackfyre) to Ser Gwayne Corbray (wielding Lady Forlorn) of the Kingsguard.

Daemon was the Warrior himself that day. No man could stand before him. He broke Lord Arryn's van to pieces and slew the Knight of Ninestars and Wild Wyl Waynwood before coming up against Ser Gwayne Corbray of the Kingsguard. For near an hour they danced together on their horses, wheeling and circling and slashing as men died all around them. It's said that whenever Blackfyre and Lady Forlorn clashed, you could hear the sound for a league around. It was half a song and half a scream, they say. But when at last the Lady faltered, Blackfyre clove through Ser Gwayne's helm and left him blind and bleeding.
The Sworn Sword

A:

Probably yes, but only one (that we know about).
From this forum post:

In the first Blackfyre rebellion, Gwayne Corbray dueled Daemon Blackfyre, which was known to be the only duel in history where both combatants wielded Valyrian steel.

The description of the duel from The Sworn Sword:

Daemon was the Warrior himself that day. No man could stand before him. He broke Lord Arryn's van to pieces and slew the Knight of Ninestars and Wild Wyl Waynwood before coming up against Ser Gwayne Corbray of the Kingsguard. For near an hour they danced together on their horses, wheeling and circling and slashing as men died all around them. It's said that whenever Blackfyre and Lady Forlorn clashed, you could hear the sound for a league around. It was half a song and half a scream, they say.

Daemon Blackfyre's sword Blackfyre was Valyrian steel, and Gwayne Corbray's sword Lady Forlorn is confirmed in at least semi-canon sources to be Valyrian steel.


Q:

SQL Server: loading database file

I'm using SQL Server 2008. I should be able to "connect" to a user-specified database file (mdf) (using the AttachDbFilename section of the connection string) and save a copy of the selected file. I also have to work with the contents of the database.
If I got it right, a single mdf file represents a complete database with tables, stored procedures, etc. But then, if I have two files with the same name in different folders (one in the DATA folder of SQL Server and the other in the root of C:), and I try to load the file under C: I get an error stating that a database already exists with that name.
I renamed the file under C:, but now I'm getting an error:

"CREATE FILE encountered operating system error 5(failed to retrieve
  text for this error. Reason: 15105) while attempting to open or create
  physical file 'C:/myDatabaseFile_log.ldf'.   Could not open new
  database 'C:/MYDATABASEFILE.MDF'. CREATE DATABASE is aborted.   An
  attempt attach an auto-named database for file 'C:/myDatabaseFile.mdf'
  failed. A database with the same name exists or specified file cannot
  be opened, or it is located on UNC share."

Please note: I'm trying to OPEN the database and not trying to create it.
So what am I doing wrong? Did I misunderstand something? How do these database file work (I mean, how to use them)?

A:

You seem to be under the impression that databases are like Word documents or text files, to be opened and closed at will within an application instance.  This isn't how it works.
Instead, there is typically exactly one instance of the database server program (you could install multiple instances, but it's not like running two copies of a normal program).  You can think of it more as if your databases must be registered inside this server instance, and you can only register one database with a given name for the server.  What happens from the server's perspective when you attach to an MDF file is that a new database is created (the CREATE DATABASE command is executed) and told to use this MDF file for the schema and data.
I suggest you get Sql Server Management Studio and connect to the server running on your local system.  You'll likely find there's already a database there with name you want.

A:

What worked from us was - user running the SQL 2008 Service didn't have permission on the folder specified.


Q:

Hibernate TABLE is not mapped

I receive this error
11:55:43,125 INFO  [org.hibernate.impl.SessionFactoryObjectFactory] (MSC service thread 1-16) Not binding factory to JNDI, no JNDI name configured
11:55:43,215 ERROR [stderr] (MSC service thread 1-16) org.hibernate.hql.ast.QuerySyntaxException: ServerSettings is not mapped [from ServerSettings as ss]
11:55:43,215 ERROR [stderr] (MSC service thread 1-16)   at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:181)
11:55:43,215 ERROR [stderr] (MSC service thread 1-16)   at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
11:55:43,216 ERROR [stderr] (MSC service thread 1-16)   at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)

When attempting to deploy my application.
My class is called ServerSettings.java - it looks like
static public ServerSettings GetServerSettings() throws Exception
{
    List retList = null;
    ServerSettings ss = null;
    try {
        Session hsession = HibernateUtil.currentSession();
        retList = hsession.createQuery("from ServerSettings as ss").list();
        if (retList == null || retList.size() <= 0)
            return null;
        ss = (ServerSettings) retList.get(0);
    }
    finally
    {
        HibernateUtil.closeSession();
    }
    return ss;

our persistence.xml looks like
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
   xmlns="http://java.sun.com/xml/ns/persistence"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
   <persistence-unit name="primary">

  <jta-data-source>java:jboss/datasources/MySqlDS</jta-data-source>
  <properties>
     <!-- Properties for Hibernate -->
     <!-- <sproperty name="hibernate.hbm2ddl.auto" value="create-drop" /> -->
     <!-- <property name="hibernate.show_sql" value="false" /> -->
  </properties>

We also have a hibernate.cfg.xml

   <session-factory>
      <property name="datasourceName">java:jboss/datasources/MySqlDS</property>
      <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

   </session-factory>

</hibernate-configuration>

and a ServerSettings.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
        <class name="com.mycompanyServerSettings" table="server_settings">
        <id name="serverSettingsID" type="integer" column="server_settings_id">
            <generator class="identity" />
        </id>
        <version  name="updateCounter" column="update_counter"/>
        <property name="changedDate" type="timestamp" column="changed_date"/>
        <property name="changedBy" type="string" column="changed_by"/>
        <property name="createdDate" type="timestamp" column="created_date"/>
        <property name="createdBy" type="string" column="created_by"/>
        <property name="status" type="string" column="status"/>

        <property name="defaultJmsQueueName" type="string" column="default_jms_queue_name"   />
        <property name="defaultJmsQueueURL" type="string" column="default_jms_queue_url"   />
        <property name="emailServer" type="string" column="email_server"   />
        <property name="emailFromAddress" type="string" column="email_from_address"   />
        <property name="emailUser" type="string" column="email_user"   />
        <property name="emailPassword" type="string" column="email_password"   />
        <property name="defaultJMSQueueID" type="string" column="default_jms_queue_id"   />
        <property name="useEncryption" type="integer" column="use_encryption"   />

</class>

Usually this error is caused when using table name instead of class name in hql - but that's not the case here.  Also this was working previously in JBoss AS5 - I'm moving it to JBoss AS7.  Any advice?

A:

<class name="com.mycompanyServerSettings"
                          ^-- A dot is missing here

Moreover, the ServerSettings.hbm.xml isn't referenced in the main hibernate.cfg.xml file. You should have such an element in the session-factory element:
<mapping resource="com/mycompany/ServerSettings.hbm.xml"/>


Q:

How to add HTML content at select2 dropdown box

I've used Select2 plugin for tag input. Here is the fiddle of my basic work. I need showing "used number" of each options/tags at dropdown box like this way:

I've created a class for that number in my CSS (.used-number). But, I don't understand how can I add that number for each options at my HTML file. Is there a way to add those something like this(or any other way):
$(".tag").select2({
     data:[{tag: 'red',text:'3',className: 'used-number'},{tag: 'green',text:'12',className: 'used-number'},{tag: 'blue',text:'5', className: 'used-number'},{tag: 'black',text:'7'}]
});

});

A:

The tags array must contain objects with the keys id and text. You can add more keys if you need (for your case, I've added the key qt that represents the number).
To add HTML to the option you need to change the default formatResult function. With the following code, the numbers appear to the tags that exist (that is, the tags passed to the select2). For the options created on the fly, the number will not appear.
$(".tag").select2({
    tags:[
        {id: "red", text: "red", qt: 3},
        {id: "green", text: "green", qt: 12},
        {id: "blue", text: "blue", qt: 5},
        {id: "black", text: "black", qt: 7}
    ],
    formatResult: function(result) {
        if (result.qt === undefined) {
            return result.text;
        }

        return result.text
            + ""
            + result.qt
            + "";
    }
});

See the forked fiddle.


Q:

How can I ask for root password but perform the action at a later time?

I have a python script that I would like to add a "Shutdown when done" feature to.
I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).
I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.
Any ideas how I can achieve this?
Thanks in advance,
Ashy.

A:

Instead of chmod u+sing the shutdown command, allowing passwordless sudo access to that command would be better..
As for allowing shutdown at the end of the script, I suppose you could run the entire script with sudo, then drop privileges to the initial user at the start of the script?

A:

gksudo should have a timeout, I believe it's from the time you last executed a gksudo command.
So I think I'd just throw out a "gksudo echo meh" or something every minute.  Should reset the timer and keep you active until you reboot.


Q:

SSIS: Inserting int32, string variable values into SQL table

I have a SSIS package which has a Execute SQL task, where I am using the following statement which is not working. Could you please explain me why?
INSERT INTO SSIS.FIIN_FilesInfo
    (FIIN_PKIN_package_id, FIIN_package_connection_string, FIIN_created_date)
SELECT '" +  @[User::package_id]] + "' AS Expr1, '" + @[User::package_connection_string]+ "' AS Expr2, GETDATE() AS Expr3

Here,
FIIN_PKIN_package_id is int32 data type
FIIN_package_connection_string is string data type
It works if I insert only string values using the variable mapping. But it does not work if I try to insert int32 and string value then using variable mapping it does not. That is why I am trying this way. Many thanks in advance.
Note: With variable mapping I was using this query:
INSERT INTO SSIS.FIIN_FilesInfo
    (FIIN_PKIN_package_id, FIIN_package_connection_string, FIIN_created_date)
VALUES (?,?, GETDATE())

A:

You have to convert the int32 variable to a string.
In SSIS you can just put the type (enclosed in parenthesis) to which you want to convert the variable before the variable; in case of string you also have to specify the maximum number of chars.
If your int32 is @[User::package_id] then use (DT_WSTR, 10)@[User::package_id]; remember to adjust number 10 to the maximum expected number of chars.


Q:

Boolean loop combined with JOptionPane Java

I would love to share my code. But in my university the code gets tested for "cheating".
But here is my code in simplier form.
public static String readin() {
    boolean error = false;
    do {
        string stringin;
        stringin = JOptionPane.showInputDialog(null, "Please enter a number");
        switch (stringin.length()) {
            case 0:
                JOptionPane.showMessageDialog(null, "Error Please repeat");
                error = true;

            case 1:
                return stringin;
        }
        return null;
    } while (error == true);
}

This Code is really in it's simpliest form. I know that for this case it would be smarter to set the while to JOptionPane is empty or something. Since in my code are like 12 different error cases. I want to use the boolean. Please: the return null will never occur in the real code.
But the real problem I have: It works perfectly fine besides: if he repeats the loop he doesn't give me the chance to type a new stringin in.
How can i do this?
Also I am sorry for my faults in english.
EDIT:
All your helps fixed my problems! Thank you very much! I love this forum!

A:

Try with break before case 1 (@Tuxxy_Thang) and remove return null; before while (error); and put after.
public static String readin(){
    boolean error=false;
    do{
        string stringin;
        stringin=JOptionPane.showInputDialog(null,"Please enter a number");
        switch (stringin.length()){
            case 0: JOptionPane.showMessageDialog(null, "Error Please repeat");
                error=true;
                break;
            case 1: return stringin;
        }
    } while (error);
    return null;
}


Q:

How to handle javascript action and submit form action on a same button

In my form, I am trying to run one javascript function to compare 2 textbox values. also, In that same button, i am trying to perform submit action to save the form data to DB and redirect to next page. JS function works fine, it generates alert for wrong input, but as soon as I click on alert. It is redirecting to next page without saving form data to DB. Can anyone tell me how to stop this?
I want to do:

Compare 2 textbox values; if they are the same form should submit and save to DB(working)
If values are not matching then show alert(working), but it on clicking "ok" it should not redirect until the values are right for both textboxes.

JSFiddle

function check(){

  var fistInput = document.getElementById("total").value;
  alert(fistInput);
  var secondInput = document.getElementById("amount").value;

  if(fistInput === secondInput)
  {
    alert("Good");
  }
  else if(fistInput > secondInput)
  {
    alert("Please input correct value");
  }
  else
  {
    alert("Please input correct value");
  }

}
 <form class="form-horizontal" action="print-receipt.php" method="post" name="myform" autocomplete="off" >
  <input type="text" id="total" placeholder="Total Amount"  name="total" required>
  <input type="text"  id="amount"  placeholder="Total"   name="amount">
  <button  type="submit" name="submit" onclick="check()" >Submit</button>
</form>

A:

Use event.preventDefault() when form data is invalid, to prevent the form from being submitted.
Instead of onclick on your type='submit' button, use onsubmit handler on your <from> element. You can pass an event to your function like this:
<form onsubmit='check(this)'></form>

function check(event){

  var fistInput = document.getElementById("total").value;
  alert(fistInput);
  var secondInput = document.getElementById("amount").value;

  if(fistInput === secondInput)
  {
    alert("Good");
  }
  else if(fistInput > secondInput)
  {
    event.preventDefault();
    alert("Please input correct value");
  }
  else
  {
    event.preventDefault();
    alert("Please input correct value");
  }

}
 <form class="form-horizontal" action="print-receipt.php" method="post" name="myform" autocomplete="off" onsubmit="check(this)">
  <input type="text" id="total" placeholder="Total Amount"  name="total" required>
  <input type="text"  id="amount"  placeholder="Total"   name="amount">
  <button  type="submit" name="submit"  >Submit</button>
</form>


Q:

enumerateKeysAndObjectsUsingBlock: can I be sure it is called on the same thread?

Lately I am using enumerateKeysAndObjectsUsingBlock: and today I have hesitated when one of my colleague at work place pointed out that this enumeration method can be called from separate thread and my code may not work as expected. He even suggested I should use fast enumeration. Problem is I really like enumerateKeysAndObjectsUsingBlock: and dislike fast enumeration due to its nature when it comes to dictionary.
my method looked as following
- (NSArray *)someMethod
{
    __block NSMutableArray *myArray = [NSMutableArray array];

    [self.myDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [myArray addObject:obj];
    }

    return myArray;
}

Can I be sure that myArray will always return the expected values (assuming self.myDictionary is not empty) and it will be always called on the same thread as the someMethod?
I am aware there is a method enumerateKeysAndObjectsWithOptions:usingBlock: and calling it with NSEnumerationConcurrent option will run enumeration simultaneously on multiple threads.
But I can't find any documentation regarding enumerateKeysAndObjectsUsingBlock.
The same refers to enumerateObjectsUsingBlock: used on array.

A:

As you observe, unless you call enumerateKeysAndObjectsWithOptions with the NSEnumerationConcurrent option, you can be assured that they won't be performed concurrently. As to whether the non-concurrent rendition of enumerateKeysAndObjects runs on the same thread or not (though, I'd wager it does), it doesn't really matter if it didn't run on the same queue because this is run synchronously with respect to the thread that you called the enumeration method. Bottom line, your coworker's thread-related concerns are without merit.
I would note, though, that in my anecdotal testing, these enumeration methods are slower than fast enumeration. If speed is of paramount interest (e.g. especially if using huge dictionaries/arrays), then you might want to employ fast enumeration. In most scenarios, though, the difference is not material.


Q:

Sequence's Discrete Fourier Transform method

So I have a sequence
{gk}^5, k=0 = {1, 0, 4, -1, 0, 0}

and I am to generate the Fourier sequence from that one. What I'm doing is simply using the formula:
Gk = gk * e^(-j2pi * n*k/T) where T = 6, n = 0...5 € Z

and to open up the previous formula because I'm sure it might look a bit confusing with the symbols I'm using/trying to use, here's how I generated G(0):
G(0) = g(0)*e^-j2pi*0*0/6) + 0 + g(2) * e^(-j2pi*0*2/6) - e^(-j2pi*0*3/6) + 0 + 0
= 1 + 4 * e^0 - 1
= 4

and for G(1)
G(1) = g(0)*e^-j2pi*0*1/6) + 0 + g(2) * e^(-j2pi*1*2/6) - e^(-j2pi*1*3/6) + 0 + 0
= 1 + 4(cos(2pi/3)-j*sin(2pi/3)) -(cos(pi)-j*sin(pi))
= 1 - 2 + 1 + 2*sqrt(2)j
= 2*sqrt(2)j

And this is the logic I'm using to calculate the DFT, but for some reason just about every online calculator regarding DFT is giving a different answer when compared to mine and other online DFT calculators, so I'm a little bit lost here.
Is there some glaring problem with how I'm trying to calculate the DFT or is this how it's supposed to go?

A:

If we use Gnu Octave (and probably also if we use Matlab), the commands:
exp(-2*pi*1i*(0:5)'*(0:5)/6)*[1,0,4,-1,0,0]'

conforms with
fft([1,0,4,-1,0,0]')

which is the built in Fast-Fourier routine. Both give:
 4.00000 + 0.00000i
 0.00000 - 3.46410i
-2.00000 + 3.46410i
 6.00000 + 0.00000i
-2.00000 - 3.46410i
 0.00000 + 3.46410i

In excess of this it is important to know that there exist different definitions, for example can the normalization be different (constant multiplication).
You can take a look at the matrix
exp(-2*pi*1i*(0:5)'*(0:5)/6)

To see the coefficients in the sums too see if you got the coefficients right in the calculations.
Disrete Fourier Transform - Wikipedia ( compare Unitaire transformatie vs first expressions, there is a difference of a factor $\frac{1}{\sqrt{N}}$, where $N$ number of samples. )
Also Wolfram Alpha's answer seems to be using backwards phase (plus instead of minus in exponent) in excess to the normalization factor $1/\sqrt{6}$.


Q:

In terms of programming, what do semantics mean?

This is a sentence from Eric Lippert's blog:

Given that unfortunate situation, it
  makes sense to emphasize the storage
  mechanism first, and then the
  semantics second.

It's easy to get a dictionary definition of what "semantic" means but what does it mean in terms of computer jargon?

A:

but what does it mean in terms of computer jargon?

Essentially the same thing. Example:
x = 5;

The above is the syntax (representation). The meaning (i.e. the semantics) of this term is to assign the value 5 to a symbol (variable, whatever) called x. Different languages offer different syntaxes to provide the same semantics. For example, the above assignment would be written as
x := 5;

in Pascal, and as
x <- 5

in several other languages. In all cases, the meaning is essentially the same. But sometimes, the same syntaxes can also have different meanings, depending on the language and/or context. VB for example redefines the equals operator to mean two different things. First, an assignment, just as above.
Secondly, in the following code sippet, rather than assigning, it takes the meaning of comparing two values:
If x = 5 Then Console.WriteLine("x is 5")

A:

The dictionary definition applies.
Semantics is (are?) all about the meaning of words.
For example, if you use the .NET type KeyValuePair to represent something OTHER than a key and value, you've got a semantic problem. It may work... it may be the best solution, but it isn't semantically accurate.
This is exactly what he's talking about in that blog post. We list return types first in C-like languages, but really the return comes last. That's semantically inaccurate.

A:

Semantics is WHAT we mean the program should do. Sytax is language-specific constraint on how we express the semantics.
In theory, as long as a program's semantics are correct, it doesn't matter what language was used to write it.


Q:

A really good RichTextBox alternative for .NET

I'm writing a Windows .NET app that needs a WYSIWYG text editor control that can

display images inline with the text
output the text with it's formatting into HTML, XML or something similar (other than RTF)
preferably free but commercial is fine

A:

The mshtml control (Internet Explorer engine control) will work. You can display images inline, output the text to HTML, and is free.
You can turn on edit mode by setting designMode = true. Here's a good article detailing how to do that.
Another alternative is to use one of the WPF controls. The WPF RichTextBox is far more powerful than than WinForms RichTextBox. The WPF RTB can be output to a number of different formats and is highly extensible.


Q:

Why was my question closed as not constructive?

This question: Can HTML5 games be wrapped in SWF files? was closed earlier, as 'not constructive'.
I was asking what seemed to be a legitimate question relating to a tool that might be able to package an HTML5 game/webapp into a SWF file for easy access.
To clarify, my question was about any HTML5 application, not just games, and how they could be packaged for desktop/browser usage via a SWF file.
What may have resulted in my question being closed, other than going in the reverse direction of what's typically asked (SWF->HTML5)?

A:

Your question was closed as "not constructive":

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

Emphasis mine.
This closure reason has problems - one of the biggest is its wording: that's being fixed. One of the main uses of not constructive isn't obvious from reading the text. Questions asking for software recommendations are generally closed as NC.
You asked:

Is there any project capable of wrapping my pages and scripts into a swf?

Where the only reasonable response is a list of such projects. That was a common response at the dawn of the network, and it didn't work out well. Lists go out of date. Debates break out - Foo is better than Bar. So, this happened, and the rules were tightened.
You might have a better shot if you provide more detail. You don't have much right now. Review what tools you've tried, and why the Frobnitz project, which every right-thinking developer knows is the right tool for the job, won't work for you because of specific reasons A and B and C. Review the blog post I linked to. Give more to bite into.


Q:

Updating multiple model attributes incrementally

I've recently started looking into Ruby on Rails, and I've set up a basic system to scan an parse and XML datasource, storing the elements in a MySQL database.
I'm intending to run the script as a rake task at set intervals to detect data changes, I'm scanning data from multiple regions and currently have two database tables set up, Product and Product Info.
Product stores data that's persistent across all regions, data which isn't persistent such as name and price are stored in the ProductInfo table along with the region locale.
In order to detect changes I have defined touch: true in the ProductInfoController to ensure that the Product's updated_at column is changed if the ProductInfo is changed during the XML data parsing.
To update the values I am using find_or_initialize_by to catch any existing records, and then I am calling update, passing in all the attributes from the XML datasource. If none of the attributes change the updated_at column for the record is not altered on the ProductInfo table, however it is still altered in the Product table.
product = Product.find_or_initialize_by(guid: xml.guid)
product.update(category: xml.category)

product_info = ProductInfo.find_or_initialize_by(product_id: product.id, locale: xml.locale)
product_info.update(name: xml.name, price: xml.price)

So the issue is that the touch is called whenever save is called on the model, this occurs in the update call. Is there an alternate call I could use, or a better way to set these attributes? Or, is there a better way to update the attributes incrementally?

A:

Rather than using .update() I have changed the code to use .update_attributes, this allows for me to check if the object has changed using .has_changed?, as suggested by @icicle. I can then perform appropriate actions prior to committing the changes with .save.


Q:

Lubin-Tate modules and different uniformizers

Suppose I have a local field $\mathcal{O}_K$ and two different prime elements $\pi$ and $\overline{\pi},$ i.e they differ by a unit $\overline{\pi} = u \pi$ for some $u \in \mathcal{O}_K^{\times}$ not equal to $1.$  Let us suppose I have a Lubin Tate module $F_\pi$ for the prime element $\pi$ and a Lubin-Tate module $F_{\overline{\pi}}$ for $\overline{\pi}.$ I have heard it been claimed that in this case, $F_{\overline{\pi}}$ and $F_{\pi}$ are never isomorphic. Is there an easy way to see why this is true?

A:

Another way of seeing this is by way of the totally ramified extension $\mathcal L_\pi$ generated by the torsion points of $F_\pi$ over $K$. In $K$, $\pi$ is the only prime element that’s the norm from every finite extension of $K$ in $\mathcal L_\pi$. Isomorphic formal modules give the same totally ramified field, and so the same universal norm $\pi$.


Q:

Closed form expression or asymptotic expansion for (periodic) generalized harmonic numbers?

In contrast with the series $\sum_{k=1}^n k$ and $\sum_{k=1}^n1$, there does not (as far as I know) exist a pure closed form expression (or a nice asymptotic expansion other than the Euler-Maclaurin expansion?) for the generalized harmonic numbers (and in fact the defining series for the Riemann zeta function) $$H_{s}(n)=\sum_{k=1}^n \frac{1}{k^s}\tag{1}$$ with $s\in\mathbb C$ (in particular $\Re(s)=\sigma\in(0,1)$).
My question is however whether there might exist a closed form expression (or maybe an asymptotic expansion other than the Euler-Maclaurin expansion?) of which I call 'periodic generalized harmonic numbers' $P_{\sigma,t}(n)$ and $Q_{\sigma,t}(n)$ (however an expression for one of them would suffice) in which  $$P_{\sigma,t}(n)=\sum_{k=1}^n \frac{\cos(t\ln(k))}{k^\sigma}\tag{2a}$$ and $$Q_{\sigma,t}(n)=\sum_{k=1}^n \frac{\sin(t\ln(k))}{k^\sigma}\tag{2b}$$ with $t\in\mathbb R$ and (in particular) $\sigma\in(0,1)$.
The reason why I'm not immediately interested in the Euler-Maclaurin expansion of the three concerning series is that all these expansions involve a complicated expression (involving Bernoulli numbers and derivatives of the concerning terms) which is in fact used to define the Riemann zeta function in some way.
I'm in particular looking for a method to derive information from the Riemann zeta function by using another type of asymptotic expansion or even the closed form of the defining series (1) or preferably the (maybe more nicely behaving) 'splitted versions' (2a) and (2b). Is e.g. Fourier analysis an obvious direction to think of?
See for my motivation for this matter also in 4.1.2 of http://fse.studenttheses.ub.rug.nl/19062/1/bMATH_2019_vanderReijdenIS.pdf.

A:

Since
$$\sum\limits_{k=1}^n \dfrac{e^{ib\ln k}}{k^a} = \sum\limits_{k=1}^n \dfrac{k^{ib}}{k^a} = \sum\limits_{k=1}^n\dfrac1{k^{a-ib}} = H_{a-ib}(n),$$
then
$$P_{a,b}(n) = \Re H_{a-ib}(n),\quad Q_{a,b}(n) = \Im H_{a-ib}(n).$$
Is known that
$$H_z(n) = \zeta(z) - \zeta(z,n+1),$$
where $\zeta(z)$ is the Riemann zeta function and $\zeta(z,k)$ is the Hurwitz zeta function.
This allows to choose the most suitable presentation for the goal function.
For example, can be used the integral presentation in the form of
$$\zeta(z,n+1) = \dfrac1{\Gamma(z)}\int\limits_0^\infty \dfrac{t^{z-1}}{1-e^{-t}}\,e^{-(n+1)t}\,dt$$
and similarly for Riemann zeta (case $n=-1$).
The periodicity of Hurwitz zeta can be used in the representation of
$$\zeta(z, n+1) = 2(2\pi)^{z-1}\Gamma(1-z)\left(\sin\frac{\pi z}2\sum\limits_{k=1}^{\infty} \cos 2\pi(n+1)k) + \cos\frac{\pi z}2\sum\limits_{k=1}^{\infty} \sin2\pi(n+1)k)\right)$$
(also look there).


Q:

Compare SQL Data

I'm trying to check with a query if there are two different users in a giveaway.
How could I do this?
Row
1 - $250.00 - NY
2 - $200.00 - DC

I'd like to somehow be able to make the query check for every row and check if there are two different users in the table. Since there is User 1 and User 2 in this table it should then return 2 because there are two different users in the database, if there are 3 return 3 etc.
Is there any syntax I could use for this, or any idea on how this could be done?

A:

I don't know your table structure but use DISTINCT and it will return a list of unique values (one name of each).
SELECT DISTINCT name FROM users

If you wanted to count the number of entries then alter your statement to
SELECT COUNT(DISTINCT name) FROM users


Q:

Tuning XGboost parameters In R

I am trying to tune parameters using the caret package in R but get a
Error in train.default(x = as.matrix(df_train %>% select(-c(Response,  :
  The tuning parameter grid should have columns nrounds, lambda, alpha

whenever I try to train the model, even though the columns nrounds, lambda, and alpha are there.
library(caret)
library(xgboost)
library(readr)
library(dplyr)
library(tidyr)

 xgb_grid_1 <- expand.grid(
  nrounds= 2400,
  eta=c(0.01,0.001,0.0001),
  lambda = 1,
  alpha =0
)

xgb_trcontrol <- trainControl(
  method="cv",
  number = 5,
  verboseIter = TRUE,
  returnData=FALSE,
  returnResamp = "all",
  allowParallel = TRUE,

)

xgb_train_1 <- train(
  x = as.matrix(df_train %>% select(-c(Response, Id))),
  y= df_train$Response,
 trControl = xgb_trcontrol,
 tuneGrid = xgb_grid_1,
 method="xgbLinear"
)

A:

The problem lies in your xgb_grid_1. If you remove the line eta it will work.
Standard tuning options with xgboost and caret are "nrounds", "lambda" and "alpha". Not eta. use the modelLookup function to see which model parameters are available. If you want to use eta as well, you will have to create your own caret model to use this extra parameter in tuning as well.
modelLookup("xgbLinear")
      model parameter                 label forReg forClass probModel
1 xgbLinear   nrounds # Boosting Iterations   TRUE     TRUE      TRUE
2 xgbLinear    lambda     L2 Regularization   TRUE     TRUE      TRUE
3 xgbLinear     alpha     L2 Regularization   TRUE     TRUE      TRUE


Q:

ssh is insisting on reading the password from the console rather than stdin

This is what I'm doing:
  ssh_ = new Process();
  ssh_.StartInfo.FileName = SshProvider;
  ssh_.StartInfo.Arguments = "-t -t " + Environment.UserName + "@" + serverName_;
  ssh_.StartInfo.UseShellExecute = false;
  ssh_.StartInfo.RedirectStandardInput = true;
  ssh_.StartInfo.RedirectStandardOutput = true;
  ssh_.StartInfo.RedirectStandardError = true;
  ssh_.StartInfo.CreateNoWindow = true;
  ssh_.Start();
  new Thread(new ThreadStart(ReadStdOut)).Start();
  new Thread(new ThreadStart(ReadStdErr)).Start();

I want to read the password prompt from stdout (or stderr) and write the password into stdin, but ssh is writing and reading from the console from which I started my mono app.  I don't understand why that is, since I have redirected those streams in the code above.

A:

ssh does not read from stdin. This is very intentional behavior designed specifically to prevent people from trying to pass in passwords from scripts or other programs. They do not have a flag to disable this behavior; there is no way to change it.
The intended way to perform automated logins is to use the private/public key mechanism to bypass the password prompt. The high level steps to do that are:

Run ssh-keygen on the client to create a public-private key pair.
Add the contents of the public key file (e.g. ~/.ssh/id_rsa.pub) to the server's authorized hosts file (e.g. ~/.ssh/authorized_keys2).

By doing this you authorize the client to connect to the server using its keys so there is no password needed.

A:

I should be using a C# SSH library like SharpSSH or Granados, rather than trying to interact with another process.


Q:

Converted From VB.NET to C# - Not Returning Values Correctly

The original VB.net, which is working perfectly:
Declare Function HolderName Lib "myCard.dll" (ByVal buf As String) As Integer
Declare Function Photo Lib "myCard.dll" (ByRef photo As Byte) As Integer

...

buff = Space(200) : res = HolderName(buff)
ShowMsg("HolderName():" & IIf(res = 0, "OK:" & Trim(buff), "FAIL"))

photobuf = New Byte(4096) {}
res = Photo(photobuf(0))
ShowMsg("Photo():" & IIf(res = 0, "OK", "FAIL"))
If res = 0 Then
    Dim ms As New MemoryStream(photobuf)
    picImage.Image = Image.FromStream(ms)
End If

The converted code now in C# (using http://converter.telerik.com/)
using System.Runtime.InteropServices;

...

[DllImport("myCard.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int HolderName(String dBuff);

[DllImport("myCard.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int Photo(ref byte photo);

//...

buff = new String(' ', 200);
res = HolderName(buff);
// buff remains UNALTERED!
ShowMsg("HolderName():" + (res == 0 ? "OK:" + Strings.Trim(buff) : "FAIL"));

photobuf = new byte[4096];
res = Photo(ref photobuf[0]);
ShowMsg("Photo():" + (res == 0 ? "OK" : "FAIL"));

// photobuf successfully receives the data bytes from Photo function
if (res == 0)
{
    MemoryStream ms = new MemoryStream(photobuf);
    picImage.Image = Image.FromStream(ms);
}

The problem is buff remains unaltered even though the HolderName function actually returns some values (watched using USB Monitor).  Why is this happening and how can I fix it?

A:

Looks like this code started life in VB6.  It could work in that language, but grave trouble today.  Both [DllImport] declarations are wrong.
You let the native HolderName() function modify the content of a string.  That's illegal, strings in .NET are immutable.  You must declare the argument as StringBuilder instead.  And set its Capacity high enough before you make the call.  Beware that it is a risky function, you can't tell it to avoid writing beyond the allocated capacity.
When it does it corrupts the GC heap, very nasty problem to debug.
The problem with Photo() is that its argument is actually byte[], no ref.  Tends to work by accident, a very common accident.  But the big, big problem is that the pinvoke marshaller doesn't know that the array needs to be pinned.  When the garbage collector runs while Photo() is running, it will jerk the floor mat and move the array elsewhere.  Photo() doesn't know and keeps using the old address.
When it does it corrupts the GC heap, very nasty problem to debug.
Otherwise no fantastic reason why it would work in VB.NET but not in C#.  I suspect a framework change as a better explanation.  But a necessary starting point certainly is to eliminate the bugs, these kind of corruption problems are very hard to reason through.

A:

Finally, I answered my own question. StringBuilder is the answer! Here's the codes...
        [DllImport("mykaddll.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        public static extern int HolderName([Out] StringBuilder dBuff);

        //....

        StringBuilder sbBuff = new StringBuilder(200);
        res = HolderName(sbBuff);
        buf = sbBuff.ToString().Trim();
        ShowMsg("HolderName():" + (res == 0 ? "OK:" + buf : "FAIL"));


Q:

How can i remove a blank space at the top of a table in libgdx

I have been trying to remove a blank space at the beginning of a libgdx table (it is a table inside a table inside a scrollPane).
The only thing I have found on the matter is to remove the line
setFillParent(true);

And I dont have that anywhere in my code
here is my adding to the table
colorTable.add(colorTitleBar).width(350).height(120);
colorTable.row();
colorTable.add(colorChoices).width(350).height(120);
colorTable.pack();

Here is a screen shot of the problem it is in the colors table

Can anybody help me with this?

A:

You can do it like this:
// set padTop if you want to leave some space at the top
colorTable.add(colorTitleBar).width(350).height(120).expandY().top().padTop(...);
colorTable.row();

And take a look at LibGDX wiki for Table


Q:

Help removing appended data

Hello I am using jquery to do some ajax that calls in some data from a database, on the mouseover and element the method runs and I get the expected results, however when I then mouse over another element, the method runs again, however I need to delete the first lot of data from the screen first, this is what I have so far,
$("a.contentlink").mouseover(function(){
        var url = $(this).attr("href");
        $.ajax ({
            url: url,
            type: "POST",
            success : function (html) {
                $('#abstract').append(html);
            }
        });
    });

Can anyone help?

A:

You need to call the empty method first, which removes all children from the matched elements.
For example:
$('#abstract').empty();

Alternatively, you can call the html function, which replaces the contents of the matched element with a string of HTML.
For example:
$('#abstract').html(html);


Q:

How do I save the file name in the database

When I add a new record in a database using a form, I also can upload an image. These two are not linked together; record goes in database and the image goes in an folder on my desktop, so to know which image belongs to which record, I want to put the filename in a column. How do i approach this?
Im using PlayFramework 2.4, Scala, H2 Database and Anorm for my Project

A:

In your html form you need to have an input tag of file type, something like:
<input type="file" name="picture">

And in your scala method Controller, where you are getting the form submit, something like:
def save = Action(parse.multipartFormData) { request =>
  request.body.file("picture").map { picture =>
    import java.io.File
    val filename = picture.filename
    println(filename)
   Ok("saved")
}


Q:

Problem with jQuery script - Wont auto cycle images

Im using the following script:
http://chocoslider.alandawi.com.ar/index_en.html
Its perfect because its compatible with so many browser versions. However Im having problems getting the images to cycle automatically.
I've set the following:
$(window).load(function() {
    $('#slider').chocoslider({
        auto:true,
        autoPause:false,
        speedStrip:500,
        effect:'random',
        numberStrips:15,
        sliderDelay:6000,
        transparencytitle:1.0,
        controlNavigation:true
        });
});

However I cannot get the images to cycle automatically? Can anyone see why that might be?
Ive set it all up here: http://dan.ms/index2.php
Would some one take a look?

A:

This Choco-Slider plug-in doesn't seem to work very well. For example, the slider on the plug-in's homepage doesn't cycle automatically either, even though it's initialized with $('#slider').chocoslider(); and according to its source code, auto defaults to true.
In fact, auto seems to do the exact opposite of what it sounds like. As a test, I modified the plug-in-homepage's script to be $('#slider').chocoslider({ auto: false });, and lo and behold, it started cycling automatically.
So If I were you I'd

Set auto to false.
Set a higher sliderDelay than 10, since it's in milliseconds. (Your pasted snippet has 6000, but the page you linked to has sliderDelay:10.)
Find a better plug-in.


Q:

Qual a diferença entre ponteiro para vetor e ponteiro para variável?

int A;
int* pA = 1;
int Vect[2] = {1,2};
int* pVect;

pA = &A;
*pA = 2;

pVect = Vect;
pVect[0] = 10;

No caso eu tenho um ponteiro para uma variável e depois para um vetor, e quero alterar seus valores pelo ponteiro. Por que existe essa divergência na passagem dos endereços (na variável eu tenho que usar o & e no vetor não precisa)? Isso é próprio da linguagem C?
Pelo que sei de ponteiro, ele aponta para o endereço de memória daquela variável obtido pelo &, mas pra vetor não precisa do &.

A:

Se considerar que um vetor é uma variável, nesse ponto não tem diferença.
Um ponteiro aponta para um endereço de memória, ponto. O endereço pode ser obtido de diversas formas. Uma delas é um apontamento para um vetor. Você pode acessar um vetor por um ponteiro de forma natural. A variável que acessa um vetor é um ponteiro. Sendo um ponteiro não tem porque usar o operador de "endereço de" (&).
Veja mais:

Arrays são ponteiros?
Qual o significado do operador "&" (e comercial) na linguagem C?
Operador & e * nas funções
Como uma variável é apontada para um ponteiro?
Diferença entre array de char e ponteiro de char
Ponteiro de char ou array de char?
O que é ponteiro para ponteiro?
Existe algum problema em atribuir um valor a um ponteiro?
Se array é o mesmo que ponteiro, por que um precisa ser copiado para uma variável e outro não precisa?


Q:

how to find distance from polyline in android?

How to find distance from polyline in google map in android using map apiV2 ? I want to find distance when user start moving from one location to another .
I used the Calculate distance in meters when you know longitude and latitude in java but it takes distance between two lat-long not as per user
moves in map. Please help me if anyone knows how to find distance using polyline.

A:

For finding distance from your polyline you  can use PolyUtil class which contains one method distanceToLine .
 implementation'com.google.maps.android:android-maps-utils:0.5+'
add this library in your build.gradle.
For more you can use Google map utility class
https://developers.google.com/maps/documentation/android-api/utility/


Q:

passing the value of r variable inside latex equation to display in kable

I have to display output of r variable inside a latex equation inside a kable cell.
When I use the below
data2$Physics<-c('$\\frac{7}{20}$')

It displays properly inside a kable cell.
But the problem is when I want to pass an r variable, I tried the below all fails:
data2$Physics<-c('$\\frac{`r phy`}{20}$')

data2$Physics<-c('$\\frac{\\Sexpr{phy}{20}$')

Any help please

A:

You are already in an R code chunk, you don't need inline R code.  Just paste in the value:
data2$Physics <- paste0('$\\frac{', phy, '}{20}$')

If you want to control the format of phy, you can use sprintf.  For example, if phy is 3.141593 but you only want two decimals to show, use
data2$Physics <- sprintf('$\\frac{%.2f}{20}$', phy)

The value in phy is formatted according to the C-style format %.2f and embedded in the string.


Q:

python help separating lists in a text file

I have a text file with hundreds of lists stored in a text file. How could i separate the lists and then store them as lists and search for the smallest second value between the lists. I am open to any new ways of tackling this problem. Here is the first few 'lists' and my attempt to separate them
var line1=[["Apr 02 2014 01: +0",0.6,"295"],["Apr 03 2014 01: +0",0.641,"245"],["Apr 04 2014 01: +0",0.625,"246"],["Apr 05 2014 01: +0",0.665,"267"],["Apr 06 2014 01: +0",0.632,"226"],["Apr 07 2014 01: +0",0.672,"170"],["Apr 08 2014 01: +0",0.655,"147"],["Apr 09 2014 01: +0",0.654,"121"],["Apr 10 2014 01: +0",0.62,"136"],["Apr 11 2014 01: +0",0.629,"176"],["Apr 12 2014 01: +0",0.68,"190"],["Apr 13 2014 01: +0",0.677,"176"],["Apr 14 2014 01: +0",0.73,"153"],["Apr 15 2014 01: +0",0.587,"148"],["Apr 16 2014 01: +0",0.591,"134"],["Apr 17 2014 01: +0",0.612,"148"],["Apr 18 2014 01: +0",0.593,"142"],["Apr 19 2014 01: +0",0.612,"153"],["Apr 20 2014 01: +0",0.654,"203"],["Apr 21 2014 01: +0",0.713,"156"],["Apr 22 2014 01: +0",0.711,"153"],["Apr 23 2014 01: +0",0.625,"128"],["Apr 24 2014 01: +0",0.629,"122"],["Apr 25 2014 01: +0",0.603,"139"],["Apr 26 2014 01: +0",0.6,"169"],["Apr 27 2014 01: +0",0.589,"177"],["Apr 28 2014 01: +0",0.585,"132"],["Apr 29 2014 01: +0",0.612,"120"],["Apr 30 2014 01: +0",0.626,"116"],["May 01 2014 01: +0",0.57,"142"]

and my attempt to separate them
with open('test.txt','r') as csvfile:
  writer=csv.reader(csvfile,delimeter=' , ',quotechar=csv.QUOTE_MINIMAL)
    for row in writer:
      print ','.join(row)

A:

Ok, assuming this is representative input as far as format is concerned:
var line1=[["Apr 02 2014 01: +0",0.6,"295"],["Apr 03 2014 01: +0",0.641,"245"]];

Then you could do the following:
import json

with open('test.txt', 'r') as datafile:
    data = datafile.read()

json_str = data.split('=', 1)[1].rstrip(';\n\r ')
my_data = json.loads(json_str)

for row in my_data:
    print row

print "Minimum by second value"
print min(my_data, key=lambda x: x[1])

Which will print:
[u'Apr 02 2014 01: +0', 0.6, u'295']
[u'Apr 03 2014 01: +0', 0.641, u'245']
Minimum by second value
[u'Apr 02 2014 01: +0', 0.6, u'295']


Q:

read coordinate text file for regionprop usage - Matlab

I have a coordinate text file and I wish to read it into a regionprop. I wish to use the regionprop for few analysis like Centroid. How can I do it?
Code:
filename = fullfile('E:/outline.txt');

fileID = fopen(filename);
C = textscan(fileID,'%d %d');
fclose(fileID);

stats = regionprops(C,'Centroid')

coordinate text file content is as follow:
88  10
87  11
87  12
88  13
88  14
92  21
93  22
93  23
94  24
95  25
100 33
101 34
102 34
103 34
103 33
103 32
103 31
103 30
103 29
103 28
103 27
102 26
102 25
101 24
101 23
100 22
100 21
100 20
99  19
99  18
94  12
93  12
92  12
91  11
90  11
89  10
88  10

A:

Why don't you just use centroid, which was introduced in 2017b?
[x,y] = centroid(C);

If you are insistent on regionprops (which is slower, and less accurate than operating on the polygon directly) then you are misunderstanding how region props works.  Region props works on images.  You need to first create an image, then pass the image to region props.
bw = roipoly(zeros(120), C(:,1), C(:,2));
stats = regionprops(bw);


Q:

What is int (*) [ someValue] in c++?

I am just learning c++ in my college.
I tried to compile the code from GitHub to solve Rubiks cube. And i got a error on the following line of code:
  Table = int (*)[Cube::Move::NumberOfClockwiseQuarterTurnMoves] // the cast

The error message is:
MoveTable.cpp   [Error] expected primary-expression before 'int'

I used dev-c++ IDE to compile and I am not familiar with int(*)[].
Please someone tell me what is it and how can i correct that?
I did some research and found this. Is it same as my question? It seems a bit different. And I am not asking for int *(int*)=constant like asked here.
Edit: I forgot to include full statement before i.e.
Table = (int (*)[Cube::NumberOfClockwiseQuarterTurnMoves] )// the cast
    (new int[TableSize*Cube::NumberOfClockwiseQuarterTurnMoves]);

And I got these errors.
    [Error] expected primary-expression before 'int'
    [Error] expected ')' before 'int'

A:

In short
The answer to your question title is:  int(*)[someConstant] corresponds to a type that is a pointer to a table of someConstant items each  of type int.
All the details
In C++ a valid statement ends with a semi-column, so there is a part missing in the statement.  In addition the comment shows that this is only the cast part.
In the original project file on GitHub, the full statement is:
Table = (int (*)[Cube::Move::NumberOfClockwiseQuarterTurnMoves]) // the cast
        (new int[TableSize*Cube::Move::NumberOfClockwiseQuarterTurnMoves]); // the allocation

This cast means that the pointer that will be returned by the expression is to be handled as a pointer to a table of NumberOfClockwiseQuarterTurnMoves integers, even if in reality a pointer to a larger table is returned by the new expression.
Removing the bracket before the before the int as in you did makes this an invalid statement, because  int (*)[Cube::Move::NumberOfClockwiseQuarterTurnMoves] is a type, and it's not allowed to use a type like this in an expression without the correct casting operator.  The compiler therefore tells you that it expects a real expression (that will provide a real value).
P.S.: this has indeed nothing to do with questions related to int (*)() which refer to a function pointer to function returning an int


Q:

starting smartcard programming

How could one get started with smartcards programming? I am asking here about all the toolkit he needs in order to get started: books, tutorials, hardware etc.
I am planning in playing around with a couple of smartcards programmers and I am pretty new to this field.
Edit: I am mostly interested in programmers that play nice with Unix-like operating systems. Also, I am not sure how this works ... but I would like to program them in C/C++

A:

Whenever I've needed to access smart cards for use in security applications it has been via either:

Microsoft CryptoAPI
a PKCS#11 library for the card.

To access a card using the Microsoft CryptoAPI a card specific Cryptographic Service Providers (CSP) is needed. The CSP sits under the CryptoAPI layer.
If you are developing on Unix/Linux using 'C/C++', however, then you will probably want to take a look at the PKCS#11 standard from RSA. The standard specifies a 'C' API called Cryptoki (Cryptographic Token Interface) which gives a common abstraction above all types of crypto devices. Nearly all smart card vendors provide a PKCS#11 library for their cards that you can program against using the Cryptoki API.
If you want to access the smart card/reader at a lower level you can use APIs such as PC/SC or CT-API.

PC/SC defacto standard for smart card access implemented on Windows, Linux and Mac OS X
CT-API provides only very minimal functionality; not very suitable for modern apps.

If you are interested in writing Java applets that run on smart cards then you probably want to look http://java.sun.com/javacard/
Resources that may be of use

OpenSC is a set of libraries and tools for smart cards. It is designed to work with PKCS#11 supporting cards. OpenCT provides drivers for card readers, and tokens that are comprised of both a card and a reader (ie. usb tokens, and other ’complete’ devices).
http://www.linuxnet.com/ MUSCLE - The movement for use of smart cards in a linux environment
PKCS#15 - Cryptographic Token Information Format Standard
Smart Card Handbook
A presentation on PKCS#11given at the RSA conf in 2009.
PyKCS11 A Python wrapper around PKCS#11. These type of wrappers can provide a simpler higher level interface than working directly at Cryptoki level.
Smart Card Alliance

A:

Java is beginning to get a huge grip in the SmartCard market, pushed by very big players (like IBM).
There are entire countries where people are carrying a Java Card in their pocket. For example there are more than 10 millions Belgium citizens whose (mandatory-to-have-with-them) national ID card is a Java Card running the BELPIC "applet".
If I'm not mistaken the entire Brazilian health care system is also based on Java Card(s).
Regarding SmartCard and Linux, here's the Linux SmartCard howto (note that that howto is full of the "Java" keyword everywhere):
http://www.faqs.org/docs/Linux-HOWTO/Smart-Card-HOWTO.html
Then there's a .pdf called "Exploring SmartCards" from June 2008 which takes a look at the big mess that the "SmartCard" world is and that basically starts by explaining that "SmartCard" is about as descriptive as saying "computer": that is, not very descriptive ; )


Q:

Different types of Nevuah

What are the differences between the "typical" navi's prophecy, Moshe Rabbeinu's prophecy, and Bil'am HaRasha's prophecy?
 (Answers with sources [and preferably links to sources] only please!)

A:

Typical navi:

sees prophetic visions only in a dream state (Rambam, Hil. Yesodei Hatorah 7:2)
becomes terrified and physically weak from the experience (ibid.)
sees a metaphorical vision, from which he or she then deduces the actual meaning (ibid. 7:3). This is because their prophecy comes to them via an angel (ibid. 7:6) - or as the Gemara puts it (Yevamos 49b), "in an unclear mirror."
has to prepare himself (or herself) for prophecy (ibid. 7:4), and therefore may lead a normal family life (ibid. 7:6).

Moshe Rabbeinu (ibid. 7:6):

receives prophecy while in full control of his senses
is able to converse with G-d without being overwhelmed, like someone talking with another person
is told the actual content of the message directly by G-d - he "sees" Him as though "in a clear mirror"
can receive prophecy at any time, and therefore must be permanently separated from his wife.

Bil'am Harasha:

was not really a navi at all, but a sorcerer (Josh. 13:22 thus calls him הקוסם). However, to honor the Jewish People, Hashem first appeared to him at night, then later via an angel, and finally during the daytime. All of this was only temporary, though, and afterwards he reverted to his former status. (Ramban to Num. 22:31; see also Sanhedrin 106a)
even when he did receive prophecy, Hashem was (so to speak) "embarrassed" to do so, and therefore allowed it to happen only at night (Rashi to Num. 22:8). Further on, Hashem's appearances to him are depicted with the word ויקר, which suggests an "accidental," shameful, unclean experience. (Rashi to Num. 23:4)
would fall to the ground from the intensity of the experience, because he was uncircumcised. (Rashi to Num. 24:4) (Rashi here may be disputing Rambam's statement, above, that this is true of all Jewish prophets too, except Moshe.)


Q:

RSA public key infrastructure

Suppose there is a message that is signed using RSA and I want to verify the signature on a remote device.
The message is generated and then signed using the private key PRIV1. The following message is sent to the remote device : {message , PUB1 , Signature}
The remote device then verifies the RSA signature using PUB1 and accepts the message. in order to prevent an adversary to generate its own message and sign it using its private key (lets call this pair PRIV2,PUB2) and then sending the same bundle : {message , PUB2 , Signature} which will be accepted by the remote device, most of the implementations use PKI in a form of a CA that issues a certificate for the public key.
I was introduced to a different public key verification approach ,
assuming the remote device is a sources limited embedded device that has a secured way to get a public key digest value from the device vendor (which is the only party sending the messages) and store it in a secured location and that most of the messages are signed with the same key- once a message is received the device will compare the stored digest to the digest of the public key in the message , if they are equal then it will proceed with the authentication and if not , it will abort the operation.
Under the given assumptions , does this scheme is as secured as using PKI in the form of CA issuing certificates for the public key ?

A:

No, your "local trust" idea is definitively NOT as secure as the tried and tested PKI process that has been in place for decades and trusted by every major party globally requiring encryption.
For one basic reason: corruption of the local store. If a malicious actor can change the local store, then the local machine will trust anything. The whole point to a neutral 3rd party is to prevent this type of localised problem.


Q:

Seaborn subplots give n highest bars different color

I am creating a group of barplots using seaborn.FacetGrid. I'd also like to color in the n highest bars of each of these subplots. How do I do that? The code below generates regular subplots of bar graphs.
import seaborn as sns
import numpy as np
np.random.seed(0)
df = pd.DataFrame({'Category': ['A','B', 'C'], 'Variable A': np.random.choice(5,3), 'Variable B':np.random.choice(5,3), 'Variable C': np.random.choice(5,3)})
g = sns.FacetGrid(df.melt(id_vars = 'Category'), col = 'Category', col_wrap = 1, height =1.7, aspect =5)
g.map(sns.barplot,'variable','value')

In this example, how would I color the two highest bars per subplot in a different color (e.g. orange) than the rest (e.g. blue)?

A:

I would argue that, if you want an output that's more customizable than what seaborn allows, you're probably better off not using seaborn at all and doing the plot directly using matplotlib's functions...
But anyway, here's a solution that works for your test scenario:
np.random.seed(0)
df = pd.DataFrame({'Category': ['A','B', 'C'], 'Variable A': np.random.choice(5,3), 'Variable B':np.random.choice(5,3), 'Variable C': np.random.choice(5,3)})
g = sns.FacetGrid(df.melt(id_vars = 'Category'), col = 'Category', col_wrap = 1, height =1.7, aspect =5)
g.map(sns.barplot,'variable','value')

top_N = 2
color = 'orange'
for ax in g.axes:
    heights = [p.get_height() for p in ax.patches]
    top = np.argsort(heights)[-top_N:]
    for p in [ax.patches[i] for i in top]:
        p.set_facecolor(color)


Q:

Pandas; calculate mean and append mean to original frame

I have a pandas DataFrame where the first column is a country label and the second column contains a number. Most countries are in the list multiple times. In want to do 2 operations:

Calculate the mean for every country
Append the mean of every country as a third column

A:

Perform a groupby by 'Country' and use transform to apply a function to that group which will return an index aligned to the original df
df.groupby('Country').transform('mean')

See the online docs: http://pandas.pydata.org/pandas-docs/stable/groupby.html#transformation


Q:

How to get corresponding data from different arrays

I have 2 arrays that have corresponding data, one has 20 names and another 20 grades, Im asking the user to enter a name and then taking the name and matching it up to the grades file and returning the grade, how would I go about doing that.
Ive tried doing something like this then returning g which refers to grade and getName refers to the name input from the user.  Also getName is a string and g is an int array.
getName.length() = g.length;

Would I have to scan through the grades file to find that exact line with the corresponding grade? Im not really sure how to achieve this.

A:

Since your question does not provide the relevant data, I'll try to answer your question with my own variable names, and you can cross check my code with yours.
Assuming the names are stored in the String array names[], and the marks are in the int array marks[], and getName contains the name to be found,
int FoundMarks = 0;
for(int i = 0; i < names.length; i++)
{
    if(names[i].equalsIgnoreCase(getName))
    {
        FoundMarks = marks[i];
        break;
    }
}
System.out.println("Marks of "+getName+": "+FoundMarks);

This is a simple Linear Search which takes each individual name of names and checks if the user is searching for that particular one. If found, then the marks of that person is stored in FoundMarks, and the looping stops.
This type of searching algorithm will be incredibly useful in almost all array related operations.
I repeat, the variable names might be different than yours, but the core logic remains the same.


Q:

Creating a Browse Button with TKinter

I'm writing some code where the user needs to be able to select a file that the program will run on. I have created a browse button that allows the user to select a file but when you hit 'okay' the rest of the program doesn't realize that there has been an input. The file name should also automatically be entered in he browse bar after the file has been selected. Any suggestions?
from Tkinter import *

class Window:

def __init__(self, master):

    #Browse Bar
    csvfile=Label(root, text="File").grid(row=1, column=0)
    bar=Entry(master).grid(row=1, column=1)

    #Buttons
    y=7
    self.cbutton= Button(root, text="OK", command=master.destroy)       #closes window
    y+=1
    self.cbutton.grid(row=10, column=3, sticky = W + E)
    self.bbutton= Button(root, text="Browse", command=self.browsecsv)
    self.bbutton.grid(row=1, column=3)

#-------------------------------------------------------------------------------------#
def browsecsv(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw()
    filename = askopenfilename()

#-------------------------------------------------------------------------------------#
import csv

with open('filename', 'rb') as csvfile:
    logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    rownum=0

    for row in logreader:
        NumColumns = len(row)
        rownum += 1

    Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)]

csvfile.close()

root = Tk()
window=Window(root)
root.mainloop()

A:

you can also use tkFileDialog..
import Tkinter,tkFileDialog

root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
if file != None:
    data = file.read()
    file.close()
    print "I got %d bytes from this file." % len(data)

A:

filename = askopenfilename() is only known in this scope, you have to return it or use it in any way.
See this site for more examples:
    Tkinter.Button(self, text='Browse', command=self.askopenfile)

...
    def askopenfile(self):
        return tkFileDialog.askopenfile(mode='r', **self.file_opt)

EDIT
Bryan Oakley is right of course! That is what I meant when i said "use it in any way" ;)
At one point you choose a filename, at anoter you simply use filename.
How about this?
from Tkinter import *
import csv

class Window:
def __init__(self, master):
    self.filename=""
    csvfile=Label(root, text="File").grid(row=1, column=0)
    bar=Entry(master).grid(row=1, column=1)

    #Buttons
    y=7
    self.cbutton= Button(root, text="OK", command=self.process_csv)
    y+=1
    self.cbutton.grid(row=10, column=3, sticky = W + E)
    self.bbutton= Button(root, text="Browse", command=self.browsecsv)
    self.bbutton.grid(row=1, column=3)

def browsecsv(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw()
    self.filename = askopenfilename()

def process_csv(self):
    if self.filename:
        with open(self.filename, 'rb') as csvfile:
            logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
            rownum=0

            for row in logreader:
                NumColumns = len(row)
                rownum += 1

            Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)]

root = Tk()
window=Window(root)
root.mainloop()

There is still a lot to do with that, but at least you don't try to open a file before having determined its name.


Q:

informal text to Html in CKEDITOR

i have String Like As below :
alert(tempstr);//"<b> Testing </b>"

now I want create a ckeditor node with this string
NewElem=CKEDITOR.dom.element.createFromHtml(tempstr);

or
NewElem.setHtml(tempstr);

Both are Assigning just as a Text.
may be using replace (< to < ) and  (> to>) is possible.my thought is that is not a proper code. Any Other proper code to Assign as Html string?.

A:

Both methods accept HTML, not an encoded HTML. So you should find a way to decode HTML in tempstr. The easiest solution is to use replace method:
var newElement = CKEDITOR.dom.element.createFromHtml(
    tempstr.replace( /</gi, '<' ).replace( />/gi, '>' )
);


Q:

Normalizer and centralizer are equivalent when $p$ is the smallest prime dividing $|G|$

Let $p$ be the smallest prime dividing $|G|$, and suppose that some $P \in \mathsf{Syl}_p(G)$ is cyclic. Prove that $N_G(P) = C_G(P)$.
So I let $G=p^\alpha m$ $p$ does not divide $m$. P is cyclic, hence is abelian, so I get that $P \leq C_G(P) \leq N_G(P)$.
p is the smallest prime dividing the order of $G$, hence every prime divisor of $m$ is greater than $p$.
I also carried out the normal computation of Sylow theorem where $n_p$ is congruent to 1 mod p, and $n_p$  divides $m$.
I also tried looking at the index of $N_G(P), C_G(P)$ and tried to show that this equals to $1$ but got stuck there.
Any suggestion are welcome!

A:

You're on the right track.  Since $C_G(P)$ contains $P$, and $P$ is a Sylow $p$-subgroup, it follows that the index $[N_G(P),C_G(P)]$ is prime to $p$, and divisible only by primes greater than $p$.  But, the quotient group $N_G(P)/C_G(P)$ embeds in the automorphism group of $P$. (The action of $N_G(P)$ on $P$ by conjugation furnishes a homomorphism $N_G(P)\to\operatorname{Aut}P$ with kernel equal to $C_G(P)$; this is sometimes called the "N/C Lemma".)  But as $P$ is cyclic, the prime divisors of $\operatorname{Aut}P$ do not exceed $P$, so $N_G(P)/C_G(P)$ must be trivial.
For the last step, recall that the automorphism group of a cyclic group $C_{p^n}$ of prime power order $p^n$ is isomorphic to $C_{p^{n-1}(p-1)}$, for odd $p$; and, for $p=2$ and $n>2$, the automorphism group is $C_2\times C_{2^{n-2}}$.  (And, $\operatorname{Aut}(C_4)\cong C_2$ while $\operatorname{Aut}(C_2)$ is trivial.)


Q:

Creating a custom CFType

Is it possible to create opaque types not derived from CFTypeRef which can be retained/released with CFRetain/CFRelease? Or how do I derive a new type from a CFType?

A:

I've never done this, but it is possible using private API. In all likelihood it will be dependent on a specific dot release of OS X, since the CF runtime could change from release to release.  In any case, CF is open source so I took a look at what CFRuntime does.  I was happy to see Apple included an example:
// ========================= EXAMPLE =========================

// Example: EXRange -- a "range" object, which keeps the starting
//       location and length of the range. ("EX" as in "EXample").

// ---- API ----

typedef const struct __EXRange * EXRangeRef;

CFTypeID EXRangeGetTypeID(void);

EXRangeRef EXRangeCreate(CFAllocatorRef allocator, uint32_t location, uint32_t length);

uint32_t EXRangeGetLocation(EXRangeRef rangeref);
uint32_t EXRangeGetLength(EXRangeRef rangeref);

// ---- implementation ----

#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFString.h>

struct __EXRange {
    CFRuntimeBase _base;
    uint32_t _location;
    uint32_t _length;
};

static Boolean __EXRangeEqual(CFTypeRef cf1, CFTypeRef cf2) {
    EXRangeRef rangeref1 = (EXRangeRef)cf1;
    EXRangeRef rangeref2 = (EXRangeRef)cf2;
    if (rangeref1->_location != rangeref2->_location) return false;
    if (rangeref1->_length != rangeref2->_length) return false;
    return true;
}

static CFHashCode __EXRangeHash(CFTypeRef cf) {
    EXRangeRef rangeref = (EXRangeRef)cf;
    return (CFHashCode)(rangeref->_location + rangeref->_length);
}

static CFStringRef __EXRangeCopyFormattingDesc(CFTypeRef cf, CFDictionaryRef formatOpts) {
    EXRangeRef rangeref = (EXRangeRef)cf;
    return CFStringCreateWithFormat(CFGetAllocator(rangeref), formatOpts,
        CFSTR("[%u, %u)"),
        rangeref->_location,
        rangeref->_location + rangeref->_length);
}

static CFStringRef __EXRangeCopyDebugDesc(CFTypeRef cf) {
    EXRangeRef rangeref = (EXRangeRef)cf;
    return CFStringCreateWithFormat(CFGetAllocator(rangeref), NULL,
        CFSTR("<EXRange %p [%p]>{loc = %u, len = %u}"),
        rangeref,
        CFGetAllocator(rangeref),
        rangeref->_location,
        rangeref->_length);
}

static void __EXRangeEXRangeFinalize(CFTypeRef cf) {
    EXRangeRef rangeref = (EXRangeRef)cf;
    // nothing to finalize
}

static CFTypeID _kEXRangeID = _kCFRuntimeNotATypeID;

static CFRuntimeClass _kEXRangeClass = {0};

/* Something external to this file is assumed to call this
 * before the EXRange class is used.
 */
void __EXRangeClassInitialize(void) {
    _kEXRangeClass.version = 0;
    _kEXRangeClass.className = "EXRange";
    _kEXRangeClass.init = NULL;
    _kEXRangeClass.copy = NULL;
    _kEXRangeClass.finalize = __EXRangeEXRangeFinalize;
    _kEXRangeClass.equal = __EXRangeEqual;
    _kEXRangeClass.hash = __EXRangeHash;
    _kEXRangeClass.copyFormattingDesc = __EXRangeCopyFormattingDesc;
    _kEXRangeClass.copyDebugDesc = __EXRangeCopyDebugDesc;
    _kEXRangeID = _CFRuntimeRegisterClass((const CFRuntimeClass * const)&_kEXRangeClass);
}

CFTypeID EXRangeGetTypeID(void) {
    return _kEXRangeID;
}

EXRangeRef EXRangeCreate(CFAllocatorRef allocator, uint32_t location, uint32_t length) {
    struct __EXRange *newrange;
    uint32_t extra = sizeof(struct __EXRange) - sizeof(CFRuntimeBase);
    newrange = (struct __EXRange *)_CFRuntimeCreateInstance(allocator, _kEXRangeID, extra, NULL);
    if (NULL == newrange) {
    return NULL;
    }
    newrange->_location = location;
    newrange->_length = length;
    return (EXRangeRef)newrange;
}

uint32_t EXRangeGetLocation(EXRangeRef rangeref) {
    return rangeref->_location;
}

uint32_t EXRangeGetLength(EXRangeRef rangeref) {
    return rangeref->_length;
}

#endif

A:

CoreFoundation itself does not provide any such mechanism, but all Cocoa objects will work with CFRetain and CFRelease. So the only supported answer is: Create a class based on Foundation and CoreFoundation will recognize it as a CFTypeRef.


Q:

Python xlwt module, hide grid

I'm trying to hide grid on successfully generated .xls with 2 sheets included. I read the xlwt doc and among other properties that can be set on xlwt-related objects, there is show_grid function included. I was trying following, but it doesn't change anything:
with open(os.path.join('sheet1_test.csv'), 'rb') as cf:
    reader = csv.reader(cf)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                sheet1.write(c, r, col, easyxf(
                'font: name Arial;',
                'show_grid: off'
                ))

I appreciate any help.

A:

Tweaking the first example here:
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
worksheet.show_grid = False # "show_grid" is a property of the worksheet!
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
workbook.save('Excel_Workbook.xls')

You can see that show_grid is a property of the worksheet, not a cell option for easyxf.
(show_grid turns off the grid in the worksheet)


Q:

WP_Query ordering by "rand" and "name"?

I am using Wordpress and for the posts on my homepage, I want them to get ordered both randomly and by name. What I mean is, I want to show different posts on my home page each time, yet ordered by their names. I changed the WP_Query args from my theme files as below, but it didn't work. I'm getting unrelated results for a reason I can't understand.
#setup wp_query
$args = array(
    'posts_per_page' => $postsperpage,
    'orderby' => array( 'rand', 'title' ),
    'order'   => 'DESC',
);

Is there any way to make that possible?
p.s. I am honestly sick of those who downvote the questions irrelevantly. I wouldn't have asked the question should i had found a solution on the internet. If you have a logical reason please either warn me or edit my post instead of blindly downvoting it.

A:

As documented:

orderby (string | array) - Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed.

So:
$args = array(
    'orderby' => array( 'rand', 'name' ),
    'order'   => 'DESC',
);

But I don't think this will get you the result you desire. You will most probably have to only use rand with posts_per_page setting to get your desired number of posts. Fetch all posts and sort these by name afterwards.
Example:
$args = array(
    'orderby' => 'rand',
);
// get X random posts (10 by default)
$result = new WP_query( $args );

// sort these posts by post_title
usort( $result->posts, function($a, $b) {
    if ( $a->post_title == $b->post_title )
        return 0;
    return ($a->post_title < $b->post_title) ? -1 : 1;
} );

// Start the loop with posts from the result.
while ( $result->have_posts() ) : $result->the_post();
    // do your stuff in the loop
}


Q:

Is it sutable to use Spring Cloud DataFlow to orchestrate long running external batch jobs inside infinite running apps?

We have String Batch applications with triggers defined in each app.
Each Batch application runs tens of similar jobs with different parameters and is able to do that with 1400 MiB per app.
We use Spring Batch Admin, which is deprecated years ago, to launch individual job and to get brief overview what is going in jobs. Migration guide recommends to replace Spring Batch Admin with Spring Cloud DataFlow.
Spring Cloud DataFlow  docs says about grabbing jar from Maven repo and running it with some parameters. I don't like idea to wait 20 sec for application downloading, 2 min to application launching and all that security/certificates/firewall issues (how can I download proprietary jar across intranets?).
I'd like to register existing applications in Spring Cloud DataFlow  via IP/port and pass job definitions to Spring Batch applications and monitor executions (including ability to stop job). Is Spring Cloud DataFlow usable for that?

A:

Few things to unpack here. Here's an attempt at it.

Spring Cloud DataFlow docs says about grabbing jar from Maven repo and running it with some parameters. I don't like idea to wait 20 sec for application downloading, 2 min to application launching and all that security/certificates/firewall issues

Yes, there's an App resolution process. However, once downloaded, we would reuse the App from Maven cache.
As for the 2mins bootstrapping window, it is up to Boot and the number of configuration objects, and of course, your business logic. Maybe all that in your case is 2mins.

how can I download proprietary jar across intranets?

There's an option to resolve artifacts from a Maven artifactory hosted behind the firewall through proxies - we have users on this model for proprietary JARs.

Each Batch application runs tens of similar jobs with different parameters and is able to do that with 1400 MiB per app.

You may want to consider the Composed Task feature. It not only provides the ability to launch child Tasks as Direct Acyclic Graphs, but it also allows transitions based on exit-codes at each node, to further split and branch to launch more Tasks. All this, of course, is automatically recorded at each execution level for further tracking and monitoring from the SCDF Dashboard.

I'd like to register existing applications in Spring Cloud DataFlow via IP/port and pass job definitions to Spring Batch applications and monitor executions (including ability to stop job).

As far as the batch-jobs are wrapped into Spring Cloud Task Apps, yes, you'd be able to register them in SCDF and use it in the DSL or drag & drop them into the visual canvas, to create coherent data pipelines. We have a few "batch-job as task" samples here and here.


Q:

Overlapping dropdown menu

I have a clickable drop down menu, after putting a border on dropbtn class, my dropdown dropdown-content menu overlaps with the dropdown button border dropbtn.
I can add margin-top:15px to dropdown-content class to fix this but is there any way to set this automatically?
Example JSFiddle

A:

you can use jQuery to achieve the desired effect:
$(document).ready(function() {
  $(".dropdown-content").css("margin-top", $(".dropbtn").css("border-width"));
});

which sets the margin-top of .dropdown-content to the value of border-width of .dropbtn.
here is a preview: jsfiddle.net/rrxmw3b3/1/


Q:

Proving this is a partial order ($\subseteq$)

So the question is:
Prove for any set $S$, the relation $\subseteq$ is a partial order on $P(S)$, the power set of $S$.
I see no relevance of mentioning the power set of $S$, as the proof just uses simple set laws and algebra to show antisymmetry, transitivity and reflexivity. Am I missing something?
My solution:
Suppose $A \in P(S)$. Then $A \subseteq A$ by definition (this is true in general anyway).
Suppose $A,B \in P(S)$ such that $A\subseteq B$ and $B \subseteq A$. Then $A=B$ (by letting $x$ be an element in $A$, showing it belongs in $B$ and vice versa) (which would be true regardless of the power set anyway)
Suppose $A,B,C \in P(S)$ and $A\subseteq B$ and $B\subseteq C$ then $A\subseteq C$ by doing the same method as above.
I'm not sure why they needed to mention the power set.

A:

Your proof is correct, and you are also correct that there was no use of the fact that you were within a power set. However, the question did need to mention some set on which to define the ordering $\subseteq$. The power set of some arbitrary set is a perfectly good choice.