答:
This is an inconsistency in the implementation of TreeSet<E>, bordering on the bug. The code will ignore custom comparator when the number of items in the collection that you pass to removeAll is greater than or equal to the number of items in the set.

The inconsistency is caused by a small optimization: if you look at the implementation of removeAll, which is inherited from AbstractSet, the optimization goes as follows:

```<code>public boolean removeAll(Collection<?> c) {
    boolean modified = false;

    if (size() > c.size()) {
        for (Iterator<?> i = c.iterator(); i.hasNext(); )
            modified |= remove(i.next());
    } else {
        for (Iterator<?> i = iterator(); i.hasNext(); ) {
            if (c.contains(i.next())) {
                i.remove();
                modified = true;
            }
        }
    }
    return modified;
}
</code>```

you can see that the behavior is different when c has fewer items than this set (top branch) vs. when it has as many or more items (bottom branch).

Top branch uses the comparator associated with this set, while the bottom branch uses equals for comparison c.contains(i.next()) - all in the same method!

You can demonstrate this behavior by adding a few extra elements to the original tree set:

```<code>s.addAll(Arrays.asList("x", "z", "a", "b"));
</code>```

Now the output for both test cases becomes identical, because remove(i.next()) utilizes the comparator of the set.

Title: AbstractSet.removeAll() method not working properly

Body:
This is an inconsistency in the implementation of TreeSet<E>, bordering on the bug. The code will ignore custom comparator when the number of items in the collection that you pass to removeAll is greater than or equal to the number of items in the set.

The inconsistency is caused by a small optimization: if you look at the implementation of removeAll, which is inherited from AbstractSet, the optimization goes as follows:

public boolean removeAll(Collection<?> c) {
    boolean modified = false;

    if (size() > c.size()) {
        for (Iterator<?> i = c.iterator(); i.hasNext(); )
            modified |= remove(i.next());
    } else {
        for (Iterator<?> i = iterator(); i.hasNext(); ) {
            if (c.contains(i.next())) {
                i.remove();
                modified = true;
            }
        }
    }
    return modified;
}

you can see that the behavior is different when c has fewer items than this set (top branch) vs. when it has as many or more items (bottom branch).

Top branch uses the comparator associated with this set, while the bottom branch uses equals for comparison c.contains(i.next()) - all in the same method!

You can demonstrate this behavior by adding a few extra elements to the original tree set:

s.addAll(Arrays.asList("x", "z", "a", "b"));

Now the output for both test cases becomes identical, because remove(i.next()) utilizes the comparator of the set.


来源: stackexchange

问:
Reassign / Update Variables
I've tried searching all over the web but could only find how to reassign cell values.

A little background for my code:

The input sheet contains data in columns A through U, but columns R and S are purposefully empty. I need to set & sort the Data Range from columns A through Q ONLY, and the number of rows may change every time I run the code (so the row index needs to be dynamic). When I run my code, the variable does not update, and I don't get any errors. Why is the code not updating my variable for input data. Any help would be greatly appreciated!

Thanks!

```<code>function SortUpdate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);
  for(var i = 9; i<=(15);i++){
     inputData.sort({column: i, ascending: false});
  }
}
</code>```

答:
So far you have assigned two different ranges to inputData but you have not collected any data.  Take a look at the range.getValues() function here.

```<code>function SortUpdate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();//This returns a range not data
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);//The inputData variable has received two assignments which one do you want?  Both are ranges and do not have any data.
  for(var i = 9; i<=(15);i++){
     inputData.sort({column: i, ascending: false});
  }
}
</code>```

It would be helpful to see some of your data.

I looked at the range.sort command and some of the examples and I'm wondering if you don't think that it was intended to be used like this:

```<code>inputData.sort([{column: 9 ascending: false},{column: 10, ascending: false},{column: 11, ascending: false},{column: 12 , ascending: false},{column: 13, ascending: false},{column: 14, ascending: false},{column: 15, ascending: false}]);
</code>```

I put the command into the function like below.  You won't be able to get this to run because I'm using some of my own utilities to store a global variable in an array in a file so that I can toggle the ascending argument between true and false every time I run it. But this is what it looks like and it definitely is sorting columns A through Q not including the header row.

```<code>function SortUpdate()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();//This returns a range not data
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);//The inputData variable has received two assignments which one do you want?
  var dirA=myUtilities.getArrayByName('Params');
  inputData.sort([{column: 9, ascending: dirA.state=='true'},{column: 10, ascending: dirA.state=='true'},{column: 11, ascending: dirA.state=='true'},{column: 12 , ascending: dirA.state=='true'},{column: 13, ascending: dirA.state=='true'},{column: 14, ascending: dirA.state=='true'},{column: 15, ascending: dirA.state=='true'}]);
  dirA['state'] = (dirA['state']=='true')?false:true;
  myUtilities.saveArray('Params', 'DICT', dirA);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reassign / Update Variables

Body:
I've tried searching all over the web but could only find how to reassign cell values.

A little background for my code:

The input sheet contains data in columns A through U, but columns R and S are purposefully empty. I need to set & sort the Data Range from columns A through Q ONLY, and the number of rows may change every time I run the code (so the row index needs to be dynamic). When I run my code, the variable does not update, and I don't get any errors. Why is the code not updating my variable for input data. Any help would be greatly appreciated!

Thanks!

function SortUpdate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);
  for(var i = 9; i<=(15);i++){
     inputData.sort({column: i, ascending: false});
  }
}

Body:
So far you have assigned two different ranges to inputData but you have not collected any data.  Take a look at the range.getValues() function here.

function SortUpdate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();//This returns a range not data
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);//The inputData variable has received two assignments which one do you want?  Both are ranges and do not have any data.
  for(var i = 9; i<=(15);i++){
     inputData.sort({column: i, ascending: false});
  }
}

It would be helpful to see some of your data.

I looked at the range.sort command and some of the examples and I'm wondering if you don't think that it was intended to be used like this:

inputData.sort([{column: 9 ascending: false},{column: 10, ascending: false},{column: 11, ascending: false},{column: 12 , ascending: false},{column: 13, ascending: false},{column: 14, ascending: false},{column: 15, ascending: false}]);

I put the command into the function like below.  You won't be able to get this to run because I'm using some of my own utilities to store a global variable in an array in a file so that I can toggle the ascending argument between true and false every time I run it. But this is what it looks like and it definitely is sorting columns A through Q not including the header row.

function SortUpdate()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var input = ss.getSheetByName("Input");
  var inputData = input.getDataRange();//This returns a range not data
  var lastRow = inputData.getNumRows();
  inputData = input.getRange(2, 1, lastRow, 17);//The inputData variable has received two assignments which one do you want?
  var dirA=myUtilities.getArrayByName('Params');
  inputData.sort([{column: 9, ascending: dirA.state=='true'},{column: 10, ascending: dirA.state=='true'},{column: 11, ascending: dirA.state=='true'},{column: 12 , ascending: dirA.state=='true'},{column: 13, ascending: dirA.state=='true'},{column: 14, ascending: dirA.state=='true'},{column: 15, ascending: dirA.state=='true'}]);
  dirA['state'] = (dirA['state']=='true')?false:true;
  myUtilities.saveArray('Params', 'DICT', dirA);
}


问:
Validate after creating PDF/A
I am creating a PDF/A from a Postscript using Ghostcript 9.14.

I have a .kfp file which is used to validate the output PDF/A document. Is there any way to validate the generated PDF/A document with the .kfp validator using ghostscript?

答:
There is a PDF/A validator in development called veraPDF, a result of the Preforma program, a project funded by the EU. As far as I know, it does not use the .kfp validator, but it does validate your PDF/A - sees if it is conform the different flavours of PDF/A.

Hope this can help.

Title: Validate after creating PDF/A


问:
Seq2seq embedding with pretrained word2vec
I know this question has been posted before but looking at the answers I cant figure out how to do this. I want to use pretrained vectors for the encoder inputs in tensorflow seq2seq embedding (the translate example in tensorflow tutorials).
I know in the core_rnn_cell_imp.py file it initiates the embedding using the following code:

```<code>embedding = vs.get_variable(
            "embedding", [self._embedding_classes, self._embedding_size],
            initializer=initializer,
            dtype=data_type)
</code>```

But how can I overwrite this embedding with array X:

```<code> X = np.ndarray(shape=(20,10), dtype='f') # lets say I want to replace the embedding with this pretrained array

    with tf.variable_scope("embedding_rnn_seq2seq"):
      with tf.variable_scope("embedding_wrapper"):
        sess.run(tf.assign(embedding, X))
</code>```

After I created the model, I ran the above code, just before the training and I get the following error:

```<code>global name 'embedding' is not defined
</code>```

How should I fix this? Sorry I'm new to tensorflow.

答:
just see
chatbot.py

```<code> def loadEmbedding(self, sess):
        """ Initialize embeddings with pre-trained word2vec vectors
        Will modify the embedding weights of the current loaded model
        Uses the GoogleNews pre-trained values (path hardcoded)
        """
……
</code>```

I think this is useful.

Body:
I know this question has been posted before but looking at the answers I cant figure out how to do this. I want to use pretrained vectors for the encoder inputs in tensorflow seq2seq embedding (the translate example in tensorflow tutorials).
I know in the core_rnn_cell_imp.py file it initiates the embedding using the following code:

embedding = vs.get_variable(
            "embedding", [self._embedding_classes, self._embedding_size],
            initializer=initializer,
            dtype=data_type)

But how can I overwrite this embedding with array X:

 X = np.ndarray(shape=(20,10), dtype='f') # lets say I want to replace the embedding with this pretrained array

    with tf.variable_scope("embedding_rnn_seq2seq"):
      with tf.variable_scope("embedding_wrapper"):
        sess.run(tf.assign(embedding, X))

After I created the model, I ran the above code, just before the training and I get the following error:

global name 'embedding' is not defined

How should I fix this? Sorry I'm new to tensorflow.

Body:
just see
chatbot.py

 def loadEmbedding(self, sess):
        """ Initialize embeddings with pre-trained word2vec vectors
        Will modify the embedding weights of the current loaded model
        Uses the GoogleNews pre-trained values (path hardcoded)
        """
……

I think this is useful.


问:
Javascript convert stringified array of objects into array of objects
I have the following variable (given to me through a HTTP response, hence the string):

```<code>var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'
</code>```

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

```<code>[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n
</code>```

How can I parse this string into an array of javascript objects?

答:
Since your string is not valid JSON (it lacks quotes around property keys), you cannot parse it using JSON.parse. If you can control the response, you should change it to return:

```<code>[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]
</code>```

Working Demo:

var result = '[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]'

console.log(JSON.parse(result))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%; }</code>```

Body:
I have the following variable (given to me through a HTTP response, hence the string):

var result = '[{name: "John"}, {name: "Alice"}, {name: "Lily"}]'

In reality there are more objects and each object has more properties, but you get the idea.

When trying JSON.parse(result) I get the following error:

[{name: "John"}, {name: "Alice"}, {name: "Lily"}]
  ^

SyntaxError: Unexpected token n

How can I parse this string into an array of javascript objects?

Body:
Since your string is not valid JSON (it lacks quotes around property keys), you cannot parse it using JSON.parse. If you can control the response, you should change it to return:

[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]

Working Demo:

var result = '[{"name": "John"}, {"name": "Alice"}, {"name": "Lily"}]'

console.log(JSON.parse(result))

.as-console-wrapper { min-height: 100%; }


问:
Why is this caterpillar algorithm O(n^2) not O(n^3)?
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

```<code>        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z < A.Length && A[x] + A[y] > A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }
</code>```

答:
Here is my take on explaining this.

First of all, you can't talk about complexity when n is small. The definition itself of complexity says that complexity only "means something" when n tends to infinity. For example, bubble sort on an array with 3 elements may seem like O(n).

With that taken out of the equation, here's about your algorithm:

Variable z is declared inside x-loop, not y-loop, therefore z will not be reinitialised every time y-loop is completed. What that means is that z will increase to A.length only once in each pass of x-loop. Once z reaches A.length, it won't increase any more and therefore it doesn't depend on the y-loop. I hope this explanation is adequate and that this problem is clearer to you now.

Body:
Can someone explain why this algorithm is O(n^2)? According to this, it's O(n^2).
The reason why I think it's O(n^3) is because outer loop (for x) runs n times, inner loop (for y) runs n-1 times, and in the worst scenario e.g. A = [8, 100, 101, 102, 103, 104, 105, 106, 107], the while loop (for z) will run n-2 times hence overall O(n^3).

For completeness, A is a sorted array with positive elements, a triplet (x, y, z) is a triangle if A[x] + A[y] > A[z]. Find how many triangles can be built from A.

        int TrianglesCount(int[] A)
        {
            int result = 0;
            for (int x = 0; x < A.Length; x++)
            {
                int z = x + 2;
                for (int y = x + 1; y < A.Length; y++)
                {
                    while (z  A[z])
                        z++;
                    result += z - y - 1;
                }
            }
            return result;
        }


问:
Why Doesn't Closing A Tab Delete A Session Cookie?
I'm using session-based cookies with my website. To my complete surprise, I noticed if I set a session cookie (not a persistent cookie), close a tab, and then reconnect to the site, the session cookies are still there. That's not what I would have expected, actually. I would have expected the session cookies to be deleted.

If you close the browser, a session cookie is deleted, so why not closing a tab to have the same result?

Therefore, I'm using PHP5 and jQuery. Is there anything I can do such that when a tab is closed I can fix this session issue? Unfortunately the onbeforeunload event on the BODY tag is not useful here because when you click away from a page it fires that event, not just closing a tab.

答: Session web storage can be used instead of cookies if you need to depend on tab closure.</p>

OwnerDisplayName: Volomike


问:
How do i record the occurances of 'Y' in a txt file in Python 3.2
I'm trying to record how many times the letter Y appears in the 6th column of a .txt file and assign that to a variable. How would I go about doing that? Thx in advance!

.txt file:

```<code>119,29/12/15,18:00,Ripley,Magnitude,Y,Magnitude
120,30/12/15,18:00,Jenkins,Kes,Y,Kes
121,31/12/15,18:00,Big Boss,Ingsoc,Y,Ingsoc
122,01/01/16,18:00,Einstein100,RNGesus,,
123,02/01/16,18:00,Macho Man,Napoleon Wilson,,
124,03/01/16,18:00,Dennis,Billy Casper,,
</code>```

I've set the whole file to a variable and have created variables for each column in the file.

```<code>    NextRecord = data[x]
    Number = NextRecord[0]
    Date = NextRecord[1]
    Time = NextRecord[2]
    P1Nickname = NextRecord[3]
    P2Nickname = NextRecord[4]
    Status = NextRecord[5]
</code>```

答:
You should try using the csv module:

```<code>import csv

counter = 0
with open("data.csv","r") as fi:
    inCsv = csv.reader(fi,delimiter=',')
    for row in inCsv:
        if (row[5].strip() == 'Y'):
            counter += 1
print ("Y count: " + str(counter))
</code>```

Body:
I'm trying to record how many times the letter Y appears in the 6th column of a .txt file and assign that to a variable. How would I go about doing that? Thx in advance!

.txt file:

119,29/12/15,18:00,Ripley,Magnitude,Y,Magnitude
120,30/12/15,18:00,Jenkins,Kes,Y,Kes
121,31/12/15,18:00,Big Boss,Ingsoc,Y,Ingsoc
122,01/01/16,18:00,Einstein100,RNGesus,,
123,02/01/16,18:00,Macho Man,Napoleon Wilson,,
124,03/01/16,18:00,Dennis,Billy Casper,,

I've set the whole file to a variable and have created variables for each column in the file.

    NextRecord = data[x]
    Number = NextRecord[0]
    Date = NextRecord[1]
    Time = NextRecord[2]
    P1Nickname = NextRecord[3]
    P2Nickname = NextRecord[4]
    Status = NextRecord[5]

Body:
You should try using the csv module:

import csv

counter = 0
with open("data.csv","r") as fi:
    inCsv = csv.reader(fi,delimiter=',')
    for row in inCsv:
        if (row[5].strip() == 'Y'):
            counter += 1
print ("Y count: " + str(counter))


问:
python map vs list comprehsnion
I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

```<code>def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))
</code>```

This code does not work for the following example:

```<code>print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214
</code>```

However, a similar function crafted as:

```<code>def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))
</code>```

Returns the correct answer

```<code>print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214
</code>```

Shouldn't

```<code>map(int, numbers)
</code>```

be the same as

```<code>[int(number) for number in numbers]
</code>```

Why do the two functions not return the same values?

答:
Why do the two functions not return the same values?

Because the function you involve in map does not work in place.

when you write

```<code>def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)    ## DOES NOT WORK IN PLACE
    ## So ADD THE LINE BELOW
    numbers = map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))
</code>```

you must somewhere reassign numbers like so

```<code>numbers = map(int, numbers)
</code>```

Title: python map vs list comprehsnion

Body:
I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

This code does not work for the following example:

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214

However, a similar function crafted as:

def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))

Returns the correct answer

print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214

Shouldn't

map(int, numbers)

be the same as

[int(number) for number in numbers]

Why do the two functions not return the same values?

Body:
Why do the two functions not return the same values?

Because the function you involve in map does not work in place.

when you write

def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)    ## DOES NOT WORK IN PLACE
    ## So ADD THE LINE BELOW
    numbers = map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

you must somewhere reassign numbers like so

numbers = map(int, numbers)


问:
Crash when adding Firebase for Google Ads in gradle
I am trying to add in an older project google ads banner, but when I add to the Grandle the Firebase and run the app it crashes:

This is my gradle:

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion '25.0.2'

defaultConfig {
    applicationId "com...."
    minSdkVersion 15
    targetSdkVersion 22
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.google.firebase:firebase-ads:10.2.0'
compile 'com.android.support:support-v4:22.2.0'
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
compile files('libs/pinch-0.8.jar')
compile files('libs/signpost-commonshttp4-1.2.1.1.jar')
compile files('libs/signpost-core-1.2.1.1.jar')
compile files('libs/signpost-jetty6-1.2.1.1.jar')
compile files('libs/twitter4j-async-3.0.3.jar')
compile files('libs/twitter4j-core-3.0.3.jar')
compile files('libs/twitter4j-examples-3.0.3.jar')
}
apply plugin: 'com.google.gms.google-services'
</code>```

and this is the error message

The first version of the project was developed with Eclipse.

答: This is because firebase uses new version of android support lib while actionbarsherlock relies on old version.  If you still want to use actionbarsherlock you will need to make some changes into it, see here</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to add in an older project google ads banner, but when I add to the Grandle the Firebase and run the app it crashes:

This is my gradle:

apply plugin: 'com.android.application'

android {
compileSdkVersion 22
buildToolsVersion '25.0.2'

defaultConfig {
    applicationId "com...."
    minSdkVersion 15
    targetSdkVersion 22
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}
}

dependencies {
compile 'com.google.firebase:firebase-ads:10.2.0'
compile 'com.android.support:support-v4:22.2.0'
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
compile files('libs/pinch-0.8.jar')
compile files('libs/signpost-commonshttp4-1.2.1.1.jar')
compile files('libs/signpost-core-1.2.1.1.jar')
compile files('libs/signpost-jetty6-1.2.1.1.jar')
compile files('libs/twitter4j-async-3.0.3.jar')
compile files('libs/twitter4j-core-3.0.3.jar')
compile files('libs/twitter4j-examples-3.0.3.jar')
}
apply plugin: 'com.google.gms.google-services'

and this is the error message

The first version of the project was developed with Eclipse.


问:
How to include resource files in Theos makefile?
I made a fully functional tweak with theos and I need to use an image file
in it , the code for getting the image is correct (tested on Xcode) .
but the image isn't included in the final DEB file .

and I have this makefile :

```<code>SDKVERSION=6.0
include theos/makefiles/common.mk
include theos/makefiles/tweak.mk

TWEAK_NAME = MyTweak
MyTweak_FRAMEWORKS = Foundation  CoreGraphics UIKit
MyTweak_FILES = Tweak.xm image.png

include $(THEOS_MAKE_PATH)/tweak.mk
</code>```

But when I try to compile I get :

```<code> No rule to make target `obj/image.png.o', needed by `obj/MyTweak.dylib'.  Stop.
</code>```

what can I do to include it ??

(Sorry for bad syntax , asking from iphone).

答: In addition to the posted answer, it's common practice to place bundles in "/Library/Application Support/" rather than "/Library/MobileSubstrate/DynamicLibraries/"</p>

Body:
I made a fully functional tweak with theos and I need to use an image file
in it , the code for getting the image is correct (tested on Xcode) .
but the image isn't included in the final DEB file .

and I have this makefile :

SDKVERSION=6.0
include theos/makefiles/common.mk
include theos/makefiles/tweak.mk

TWEAK_NAME = MyTweak
MyTweak_FRAMEWORKS = Foundation  CoreGraphics UIKit
MyTweak_FILES = Tweak.xm image.png

include $(THEOS_MAKE_PATH)/tweak.mk

But when I try to compile I get :

 No rule to make target `obj/image.png.o', needed by `obj/MyTweak.dylib'.  Stop.

what can I do to include it ??

(Sorry for bad syntax , asking from iphone).


问:
Symfony instance fails to see directories as writable
I've been filtering through google to try to find an answer to this, but I still can't find one that fixes my issue.  I have migrated a website to a new server.  The framework is Symfony 2.8 on php5.6 using Nginx and PHP-FPM.

Here is a screenshot of the config.php page.

To resolve this, i've tried...

Changing the user for Nginx and php-fpm to both the user I log in with and Nginx, both didn't work

I've opened up the privileges on the cache and log folder to 777 within the app folder, and that didn't work, nope.

I've tried assigning the cache and logs folder to nginx:nginx, no go.

I've manually assigned app.php, app_dev.php, and the console file to have the umask(0000) and umask(0002), nope.

Restarted the Nginx service and php-fpm service after each change, nodda.

I've restarted the entire server thinking something might be stuck, but you guessed it. No!

That leaves me here.  I've gone through everything that I can think of and it baffles me that Symfony still won't recognize the directory as writable.  It seems like the most simple thing, but... nope.

Anything will help, please pass anything along.

答:
You should read this to setup you directories permissions http://symfony.com/doc/current/setup/file_permissions.html

I always go for the point 3. with Debian/Apache, Unfortunately i never tried it with nginx.


问:
wpf need to transfer info from one textbox to another
hi guys im trying to create a button which can take my information from one textbox to another but i the informationer is in Contactformula.xaml and i need it over to Mainwindow.xaml hope u understand what i mean here is the code...

```<code>    Mainwindow.xaml.cs

    namespace debug
    {

        public partial class MainWindow : Window
        {

            public ContactFormula CF = new ContactFormula();

            public object Frame { get; private set; }

            public MainWindow()
            {
                InitializeComponent();
            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {

                ContactFormula win2 = new ContactFormula();
                win2.Show();

            }

    ContactFormula.xaml.cs

namespace debug
{
    /// <summary>
    /// Interaction logic for ContactFormula.xaml
    /// </summary>
    public partial class ContactFormula : Window
    {

        public ContactFormula()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
        }
    }
</code>```

and here is a screenshot of the program so maybe u understand me better

答:
Try making the list of contacts a static property in a static class, that way you can get or add contacts from anywhere in the program.

```<code>public static class Session
{
    public static List<Contact> Contacts = new List<Contact>();
}
</code>```

you can add contacts from any page using:

```<code>        Session.Contacts.Add(contact);
</code>```

Body:
hi guys im trying to create a button which can take my information from one textbox to another but i the informationer is in Contactformula.xaml and i need it over to Mainwindow.xaml hope u understand what i mean here is the code...

    Mainwindow.xaml.cs

    namespace debug
    {

        public partial class MainWindow : Window
        {

            public ContactFormula CF = new ContactFormula();

            public object Frame { get; private set; }

            public MainWindow()
            {
                InitializeComponent();
            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {

                ContactFormula win2 = new ContactFormula();
                win2.Show();

            }

    ContactFormula.xaml.cs

namespace debug
{
    ///
    /// Interaction logic for ContactFormula.xaml
    ///
    public partial class ContactFormula : Window
    {

        public ContactFormula()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
        }
    }

and here is a screenshot of the program so maybe u understand me better

Body:
Try making the list of contacts a static property in a static class, that way you can get or add contacts from anywhere in the program.

public static class Session
{
    public static List<Contact> Contacts = new List<Contact>();
}

you can add contacts from any page using:

        Session.Contacts.Add(contact);


问:
Files generated with precompile are not compiled
During dotnet build, it seems that generated files created during the precompile tasks are not used and the build failed.

precompile cannot be used for files generation? The documention is pretty light about it.

or do I have to deal with a delay to be sure that files are correctly writed on disk ?

Project.json:

```<code>{
  "name": "Service",
  "version": "0.0.1",

  "dependencies": {
    ...
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  },
  "scripts": {
    "precompile": "%project:Directory%/protogen.bat"
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  }
}
</code>```

Thanks

答:
I assume you don't have this problem anymore, but to save time for anyone running into this issue, here is what is going on:

The problem is a bug in the dotnet tool where source files generated by a precompile command aren't included in the list of files to compile. See #1475 and #3807.

It was fixed by PR#4680. Upgrading to a newer version of .NET Core should fix it.

Body:
During dotnet build, it seems that generated files created during the precompile tasks are not used and the build failed.

precompile cannot be used for files generation? The documention is pretty light about it.

or do I have to deal with a delay to be sure that files are correctly writed on disk ?

Project.json:

{
  "name": "Service",
  "version": "0.0.1",

  "dependencies": {
    ...
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  },
  "scripts": {
    "precompile": "%project:Directory%/protogen.bat"
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  }
}

Thanks


问:
How to convert from CString to PCWSTR
I have the following method :

```<code>    VariantFromString(strXMLPath ,vXMLSource);
</code>```

and the signature of the method is:

```<code>HRESULT VariantFromString(PCWSTR wszValue, VARIANT &Variant);
</code>```

Now while I am passing a CString as below:

```<code>char cCurrentPath[FILENAME_MAX];

        if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
            {
                return errno;
            }
CString strXMLPath = cCurrentPath;
strXMLPath += XMLFILE;
VariantFromString(strXMLPath ,vXMLSource);
</code>```

I am getting the error: Can not Convert from CString to PCWSTR

答:
You really should be using Unicode (wchar_t instead of char). That is how the OS operates internally, and would prevent having to constantly convert between char types like this.

But in this scenario, you could use CString::AllocSysString to convert it to a BSTR, which is compatible with PCWSTR. Just make sure it gets freed with SysFreeString.

[edit]
For example, you could change your function to:

```<code>VARIANT VariantFromString(const CString& str)
{
    VARIANT ret;
    ret.vt = VT_BSTR;
    ret.bstrVal = str.AllocSysString();
    return ret;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to convert from CString to PCWSTR

Body:
I have the following method :

    VariantFromString(strXMLPath ,vXMLSource);

and the signature of the method is:

HRESULT VariantFromString(PCWSTR wszValue, VARIANT &Variant);

Now while I am passing a CString as below:

char cCurrentPath[FILENAME_MAX];

        if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
            {
                return errno;
            }
CString strXMLPath = cCurrentPath;
strXMLPath += XMLFILE;
VariantFromString(strXMLPath ,vXMLSource);

I am getting the error: Can not Convert from CString to PCWSTR

Body:
You really should be using Unicode (wchar_t instead of char). That is how the OS operates internally, and would prevent having to constantly convert between char types like this.

But in this scenario, you could use CString::AllocSysString to convert it to a BSTR, which is compatible with PCWSTR. Just make sure it gets freed with SysFreeString.

[edit]
For example, you could change your function to:

VARIANT VariantFromString(const CString& str)
{
    VARIANT ret;
    ret.vt = VT_BSTR;
    ret.bstrVal = str.AllocSysString();
    return ret;
}


问:
I can load static files locally with 'runserver' but not in production
I can load static files locally with 'runserver' but not in production.
I successfully manage to load templates in production, but not static files.

in the .html page I included the lines:

```<code><!DOCTYPE html>
{% load staticfiles %}
</code>```

...
...

```<code><img src="{% static "images/mypic.jpg" %}" alt="this pic" />
</code>```

my settings in settings.py include these lines

```<code>BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'
</code>```

and in urls.py I have:

```<code>from django.conf.urls.static import static
</code>```

and

```<code>urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^pages/', include('pages.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'about^$', views.about, name='about'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

I've been trying for hours, any idea why I can't access them?

答:
(WRONG!!!)

I solved the problem by adding:

```<code>+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

to both my app urls.py and the main urls.py

Body:
I can load static files locally with 'runserver' but not in production.
I successfully manage to load templates in production, but not static files.

in the .html page I included the lines:

<!DOCTYPE html>
{% load staticfiles %}

...
...

my settings in settings.py include these lines

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [STATIC_DIR, ]
STATIC_URL = '/static/'

and in urls.py I have:

from django.conf.urls.static import static

and

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^pages/', include('pages.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'about^$', views.about, name='about'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

I've been trying for hours, any idea why I can't access them?

Body:
(WRONG!!!)

I solved the problem by adding:

+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

to both my app urls.py and the main urls.py


问:
DATEDIFF in DataSet Query Builder
How do I use DATEDIFF in query builder? I am trying to calculate the age upon insertion.

I have this working insert code done in SqlQuery

```<code>    INSERT INTO [dbo].[Employee]
           ([FirstName]
           ,[MiddleName]
           ,[LastName]
           ,[Age]
           ,[Gender]
           ,[Birthday]
           ,[PositionID]
           ,[Status]
           ,[ContactNumber]
           ,[Photo]
           ,[Password])
VALUES
           ('Lovenia'
           ,'Celestial'
           ,'Roman'
           ,(SELECT DATEDIFF(hour,'5-28-1998',GETDATE())/8766)
           ,'Male'
           ,'01-28-1998'
           ,'2'
           ,'Employed'
           ,'09128773636'
           ,null
           ,'somepassword')
GO
</code>```

And then when I convert it to Query Builder, an error pops out and says no subqueries allowed

here is the code in QueryBuilder

```<code>    INSERT INTO Employee
                         (FirstName, MiddleName, LastName, Age, Gender, Birthday, PositionID, Status, ContactNumber, Photo, Password)
VALUES        (@FirstName,@MiddleName,@LastName, (Select DATEDIFF('hour',@Birthday, GETDATE()) / 8766),@Gender,@Birthday,@PositionID,@Status,@ContactNumber,@Photo,@Password)
</code>```

I removed the select statement and left out just DATEDIFF(hour,'5-28-1998',GETDATE())/8766

But still gets an error

I read that DATEDIFF() isn't supported in Query builder, so are there any alternative way (similar to DATEDIFF()) to calculate the age?

答:
Nevermind, I figured it out

The error was at DATEDIFF()'s parameter 1, i removed the qoutes and changed it to hh, also fixed the conversion from string to date :D

Here's the code

```<code>INSERT INTO Employee (FirstName, MiddleName, LastName, Age, Gender, Birthday, PositionID, Status, ContactNumber, Photo, Password)
VALUES        (@FirstName,@MiddleName,@LastName, DATEDIFF(hh, CONVERT(varchar(30),@Birthday, 102), GETDATE()) / 8766,@Gender,@Birthday,@PositionID,@Status,@ContactNumber,@Photo,@Password)
</code>```

Title: DATEDIFF in DataSet Query Builder

Body:
How do I use DATEDIFF in query builder? I am trying to calculate the age upon insertion.

I have this working insert code done in SqlQuery

    INSERT INTO [dbo].[Employee]
           ([FirstName]
           ,[MiddleName]
           ,[LastName]
           ,[Age]
           ,[Gender]
           ,[Birthday]
           ,[PositionID]
           ,[Status]
           ,[ContactNumber]
           ,[Photo]
           ,[Password])
VALUES
           ('Lovenia'
           ,'Celestial'
           ,'Roman'
           ,(SELECT DATEDIFF(hour,'5-28-1998',GETDATE())/8766)
           ,'Male'
           ,'01-28-1998'
           ,'2'
           ,'Employed'
           ,'09128773636'
           ,null
           ,'somepassword')
GO

And then when I convert it to Query Builder, an error pops out and says no subqueries allowed

here is the code in QueryBuilder

    INSERT INTO Employee
                         (FirstName, MiddleName, LastName, Age, Gender, Birthday, PositionID, Status, ContactNumber, Photo, Password)
VALUES        (@FirstName,@MiddleName,@LastName, (Select DATEDIFF('hour',@Birthday, GETDATE()) / 8766),@Gender,@Birthday,@PositionID,@Status,@ContactNumber,@Photo,@Password)

I removed the select statement and left out just DATEDIFF(hour,'5-28-1998',GETDATE())/8766

But still gets an error

I read that DATEDIFF() isn't supported in Query builder, so are there any alternative way (similar to DATEDIFF()) to calculate the age?

Body:
Nevermind, I figured it out

The error was at DATEDIFF()'s parameter 1, i removed the qoutes and changed it to hh, also fixed the conversion from string to date :D

Here's the code

INSERT INTO Employee (FirstName, MiddleName, LastName, Age, Gender, Birthday, PositionID, Status, ContactNumber, Photo, Password)
VALUES        (@FirstName,@MiddleName,@LastName, DATEDIFF(hh, CONVERT(varchar(30),@Birthday, 102), GETDATE()) / 8766,@Gender,@Birthday,@PositionID,@Status,@ContactNumber,@Photo,@Password)


问:
Managing collision detection in games
So my question isn't about the how-to of collision detection, but is more of a broad 'what code should own collision detection'. I've written some game in the past(relatively simple 2D Flash games) and it got me thinking of which code should own collision detection?

Let me clarify - say in a game I have a group of enemies and a group of projectiles the player has fired. So in the past I've had say an EnemyManager class, that every frame updates the positions of the enemies and likewise for the player projectiles had a PlayerProjectilesManager class that moved around the bullets. That's cool - everything is fine and dandy. But then, I decide I want the bullets to affect the enemies(crazy I know!). So that means somewhere in the code I need to:

Figure out which bullets and enemies are colliding(I don't care how for this question)

Figure out the response to each collision

So basically what I've done in the past is just have the EnemyManager class take 'ownership' of the collisions, and during its update loop it finds the player bullets that collide with enemy bullets(i.e. Step 1) and also calls code for both objects to handle the collision (e.g. the enemy losses health, the bullet disappears) (i.e. Step 2). So I've given control of the collision detection and collision 'reaction' to the EnemyManager.

A couple comments about that:

It feels vary arbitrary to me that the EnemyManager is in 'control' instead of the PlayerProjectilesManager

Both collision detection and collision 'reaction' are handled by the same owner, this isn't a requirement from my point of view

What's forming in my mind is a 3rd party entity managing collision detection. For instance have a CollisionManager which has code that know's which other Managers need to have collisions detected. That leads to other questions like what interfaces do the 'Managers' need to expose for efficient collision detection without exposing too many innards to the CollisionManager. Then I suppose the CollisionManager what broadcast some sort of an event, containing which 2 objects collided etc... and perhaps the EnemyManager/PlayerProjectilesManager could separately listen for these events and react accordingly and separately. Starting to make sense in my mind. :)

Thoughts? Almost every game has collision detection, so I'm sure this has been discussed before. :)

答:
this is a nice question. Personally, I would not complicate it so much by using "Managers". Let's say we have a GameEngine, which runs the game in its main loop. This main loop could consist of 3 steps: get the user input, update the state of all objects in the game (based on the user input) and finally draw everything again on the screen.

Everything about the collision detection is done in the second step - when updating the objects' state. Let's say all objects in the game are stored in a pool. This includes the player, the bullets, the enemies and even the world (if you'd like the world to be affected as well somehow). All the different objects could have some common properties - they could be Drawable, Movable, Collidable e.t.c. (think like implementing an interface or extending a base class to have these properties)

For each of these properties I would have a class that do something with all the objects in the pool. Like Mover.moveAll(objectsFromPool). This will move all objects, which are Movable.
The same for collision detection -> after we've relocated the objects with the Mover, then we check for collision with CollisionDetector.cehckAll(objectsFromPool). This checkAll() method will do the actual collision detection between the objects themselves, knowing their coordinates. If an object is Collidable, the CollisionDetector will invoke its method onCollide(withOtherObject) and then the object itself reacts properly, depending what other object hit it. Let's say, if the player is touched by the enemy body, they will both step back for example. If a bullet is hits by another bullet - they will both be marked for deletion. If the enemy is hit by a bullet, then some damage will happen and the bullet will be marked for deletion. All these reactions should be in the corresponding objects themselves.The collision detector applies its algorithms to detect collision between any two objects and then invokes their onCollide(withOtherObjct) method.
If an object is not Collidable, it will be simply ignored by the CollisionDetector (for examples rain particles or dust are not Collidable).

I hope I managed to express myself correct :)

Title: Managing collision detection in games


问:
NodeJS ways to increase server performance in case of large number of connections and bulk of data
I am in between building a web application for showing vehicles position in a map view, AngularJS as front end and Node.js as the server for real-time updating of the map. The events are coming from a middleware application to Node server, the server then has to apply some logic there to broadcast the data to the needed connected clients.

Coming to the question- the issue what I am currently facing is that, there comes around 20K vehicle data at a single time to the Node server, the Node server then has to decide to which connected clients should the data updated.This is achieving by looping each data against each connected client's map bounds.If the incoming data bounds are within the connected client's bounds that particular data will be emitted to that client. So this entire process will take more time if there have 1K clients and 20K data.

Are there any ways to reduce this server overload by using any node techniques?

What I have tried: I read through node clusters, but I think it deals with distributing connections across multiple workers. Is this a way for resolving my issue?

The sample code snippet is as follows:

Node server side logic

```<code>users // user array eg: array(userSocketId1,userSocketId2);

bounds //each user's bounds array eg:array({userSocketId1:boundsValue},{userSocketId2:boundsValue2});

app.post('/addObject',  (req, res) => {
 for (var k = 0; k < Object.keys(req.body).length; k++) {
  var point=[{'lat':req.body[k].lat,'lng':req.body[k].lng,'message':req.body[k].message,'id':req.body[k].id}];
  for (var i = 0; i < users.length; i++) {
    var userBounds  = bounds[users[i]];
    if(typeof userBounds!=='undefined'){
      var inbounds    = inBounds(point[0],userBounds); // check whether current vehicle's bounds within user's bounds
      var user        = users[i];
      if(inbounds){
      io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
      }
    }
  }
}
res.send('Event received in Node Server');
});
</code>```

Client-side logic for plotting vehicle info to map

```<code> socket.on('updateMap', function(msg){
    L.marker([msg.lat, msg.lng]).addTo(map);
 });
</code>```

答:
Here your performance player is Mongo

how?

If you are using multiple objects like

```<code>Customer=>{...} l times
Clients=>{...} m times
data=>{client_id:'something',...} n times
</code>```

then you need looping each data and checks in it. which is equal to l * m  * n

here is the trick that save alot of things

```<code>Customer:{
     _id:Object('someid')
    ,client:{
        _id:Object('someid'),
         data:{
                 ...
                }
             }
          }
</code>```

It will decrease the looping factor and gives result in l * (no of clients inside)* (no of data inside).

Body:
I am in between building a web application for showing vehicles position in a map view, AngularJS as front end and Node.js as the server for real-time updating of the map. The events are coming from a middleware application to Node server, the server then has to apply some logic there to broadcast the data to the needed connected clients.

Coming to the question- the issue what I am currently facing is that, there comes around 20K vehicle data at a single time to the Node server, the Node server then has to decide to which connected clients should the data updated.This is achieving by looping each data against each connected client's map bounds.If the incoming data bounds are within the connected client's bounds that particular data will be emitted to that client. So this entire process will take more time if there have 1K clients and 20K data.

Are there any ways to reduce this server overload by using any node techniques?

What I have tried: I read through node clusters, but I think it deals with distributing connections across multiple workers. Is this a way for resolving my issue?

The sample code snippet is as follows:

Node server side logic

users // user array eg: array(userSocketId1,userSocketId2);

bounds //each user's bounds array eg:array({userSocketId1:boundsValue},{userSocketId2:boundsValue2});

app.post('/addObject',  (req, res) => {
 for (var k = 0; k < Object.keys(req.body).length; k++) {
  var point=[{'lat':req.body[k].lat,'lng':req.body[k].lng,'message':req.body[k].message,'id':req.body[k].id}];
  for (var i = 0; i < users.length; i++) {
    var userBounds  = bounds[users[i]];
    if(typeof userBounds!=='undefined'){
      var inbounds    = inBounds(point[0],userBounds); // check whether current vehicle's bounds within user's bounds
      var user        = users[i];
      if(inbounds){
      io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
      }
    }
  }
}
res.send('Event received in Node Server');
});

Client-side logic for plotting vehicle info to map

 socket.on('updateMap', function(msg){
    L.marker([msg.lat, msg.lng]).addTo(map);
 });

Body:
Here your performance player is Mongo

how?

If you are using multiple objects like

Customer=>{...} l times
Clients=>{...} m times
data=>{client_id:'something',...} n times

then you need looping each data and checks in it. which is equal to l * m  * n

here is the trick that save alot of things

Customer:{
     _id:Object('someid')
    ,client:{
        _id:Object('someid'),
         data:{
                 ...
                }
             }
          }

It will decrease the looping factor and gives result in l * (no of clients inside)* (no of data inside).


问:
Create designer.cs file from ResXRersourcewriter generated resource file
I got a programm that generates .resx resource files. Those resource files are used in other projects, that isnt in the same solution as the project that generates the resource files.

I wonder now, if its possible to generate a designer.cs file from the resource file, so that you can access the resources directly without using the resxresourcereader.

答:
You can also do this in code:
(Taken from here: msdn)

```<code> StreamWriter sw = new StreamWriter(@".\DemoResources.cs");
  string[] errors = null;
  CSharpCodeProvider provider = new CSharpCodeProvider();
  CodeCompileUnit code = StronglyTypedResourceBuilder.Create("Demo.resx", "DemoResources",
                                                             "DemoApp", provider,
                                                             false, out errors);
  if (errors.Length > 0)
     foreach (var error in errors)
        Console.WriteLine(error);

  provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
  sw.Close();
</code>```

You need to reference system.design.dll

Body:
You can also do this in code:
(Taken from here: msdn)

 StreamWriter sw = new StreamWriter(@".\DemoResources.cs");
  string[] errors = null;
  CSharpCodeProvider provider = new CSharpCodeProvider();
  CodeCompileUnit code = StronglyTypedResourceBuilder.Create("Demo.resx", "DemoResources",
                                                             "DemoApp", provider,
                                                             false, out errors);
  if (errors.Length > 0)
     foreach (var error in errors)
        Console.WriteLine(error);

  provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
  sw.Close();

You need to reference system.design.dll


问:
Converting date format from d/m/y time to d/m/y
I have data input coming in the form of d/m/y time eg: "3/27/2017 1:20:15 AM" and I want to just have d/m/y to display 3/27/2017.

I have seen different techniques on how to achieve this and have tried 3 different types however I recieve NA as the new output and for the later I get the "Error in charToDate(x) :
  character string is not in a standard unambiguous format"
error.

Here is an my example code:

```<code>df <- data.frame(Date = "3/27/2017 1:20:15 AM")

df$Date <- as.POSIXct(as.character(df$Date), format = "%d/%m/%Y")

df$Date <- as.Date(df$Date, "%d/%m/%Y")

df$Date <- format(as.Date(df$Date), "%d/%m/%Y")
</code>```

答:
Looks like you want format = %m/%d/%Y instead of %d/%m/%Y.

If specialized date formats are still giving you problems with the time after that, you can first use strsplit() to break up the character string on spaces, then grab the first item to get just the date.

```<code>date <- "3/27/2017 1:20:15 AM"
date <- strsplit(date," ")
date <- unlist(date)[1]
date <- as.POSIXct(date,format="%m/%d/%Y")
</code>```

Body:
I have data input coming in the form of d/m/y time eg: "3/27/2017 1:20:15 AM" and I want to just have d/m/y to display 3/27/2017.

I have seen different techniques on how to achieve this and have tried 3 different types however I recieve NA as the new output and for the later I get the "Error in charToDate(x) :
  character string is not in a standard unambiguous format"
error.

Here is an my example code:

df <- data.frame(Date = "3/27/2017 1:20:15 AM")

df$Date <- as.POSIXct(as.character(df$Date), format = "%d/%m/%Y")

df$Date <- as.Date(df$Date, "%d/%m/%Y")

df$Date <- format(as.Date(df$Date), "%d/%m/%Y")

Body:
Looks like you want format = %m/%d/%Y instead of %d/%m/%Y.

If specialized date formats are still giving you problems with the time after that, you can first use strsplit() to break up the character string on spaces, then grab the first item to get just the date.

date <- "3/27/2017 1:20:15 AM"
date <- strsplit(date," ")
date <- unlist(date)[1]
date <- as.POSIXct(date,format="%m/%d/%Y")


问:
Does the order of fields in C# matter?
This question is inspired by Jon Skeet's answer:
Is there a c# equivalent to c++'s access-modifier regions

He makes a comment that it is possible for the order of fields in a file to matter. I am guessing that this has to do with the order that the fields are initialized, but I think it's a dangerous enough thing to code based on this side effect that it warranted its own question and discussion.

Are there other thoughts around how the order of fields within your code file could be manipulated and what impact that might have?

答:
I was primarily thinking about the order of initialization, yes - particularly for static fields. For instance (with public fields just for simplicity of demonstration):

```<code>using System;

class First
{
    static int a = 10;
    public static int b = CalculateB();
    static int c = 5;

    static int CalculateB()
    {
        return a*c;
    }
}

class Second
{
    static int a = 10;
    static int c = 5;
    public static int b = CalculateB();

    static int CalculateB()
    {
        return a*c;
    }
}

class Test
{
    static void Main()
    {
        Console.WriteLine("First.b: {0}, Second.b: {1}",
                          First.b, Second.b);
    }
}
</code>```

The order of initialization is defined in the spec to be the textual order in which the variables are declared - but it becomes undefined when two variables are in different files contributing to a partial class.

Mehrdad's answer is another good one: anything where physical layout is important will quite possibly be affected by declaration order.

OwnerDisplayName: Josh

Title: Does the order of fields in C# matter?

LastEditorDisplayName: Mehrdad Afshari

Body:
I was primarily thinking about the order of initialization, yes - particularly for static fields. For instance (with public fields just for simplicity of demonstration):

using System;

class First
{
    static int a = 10;
    public static int b = CalculateB();
    static int c = 5;

    static int CalculateB()
    {
        return a*c;
    }
}

class Second
{
    static int a = 10;
    static int c = 5;
    public static int b = CalculateB();

    static int CalculateB()
    {
        return a*c;
    }
}

class Test
{
    static void Main()
    {
        Console.WriteLine("First.b: {0}, Second.b: {1}",
                          First.b, Second.b);
    }
}

The order of initialization is defined in the spec to be the textual order in which the variables are declared - but it becomes undefined when two variables are in different files contributing to a partial class.

Mehrdad's answer is another good one: anything where physical layout is important will quite possibly be affected by declaration order.

OwnerDisplayName: Jon Skeet


问:
Hibernate or JPA?
With Spring 3.0 is it recommended to use hibernate or JPA.What are the advantages and disadvantages of both of them when used with Spring 3.0 ?

Note : We are also suppose to use it with Spring Data Access.

答:
It depends on our application.

If you are not sure that you will never need to change your persistence provider, it is strongly recommended to use JPA (2.0)

If you are sure that you never will change your persistence provider, than I recommend using JPA (2.0) too. But (only) in this case you have the possibility to use a proprietary feature of you choosen JPA-Provider, if you have a problem not solved by standard JPA. -- But use it wise, if you choose this way once, it is hard to go back!

Of course JPA is just an API - so you need an implementation of it. -- I used Hibernate as JPA provider, but mainly because I am allways in the second scenario (will never change it), and I needed additional features like Hibernate-Search and Envers.

Title: Hibernate or JPA?


问:
change color of tab on sheets in a workbook based on date
I have a workbook that holds work orders(a different one on each sheet) that are time sensitive. At times there can be any where from 5 to 25 sheets in this workbook. In Cell H15 of each sheet is the due date of the work order. I am trying to set up a vba that when the workbook is opened it will check the date and change the tab of the sheets to red on the last day it is due to be done. I have a code that I thought was correct but is not working. I was told to try using (Private Sub Workbook_Open() ) but I can not seem to get the right coding so it checks all the sheets.

thank you,

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

   With ActiveSheet
      If Range("H15").Value = Date Then
         .Tab.ColorIndex = 3 'Red

      End If
   End With
End Sub
</code>```

答:
Try this, in the ThisWorkbook module (and remove the worksheet change code). (In response to Jeeped's comment, the tab colour is removed everywhere else.)</p>

```<code>Private Sub Workbook_Open()

Dim ws As Worksheet

For Each ws In Worksheets
    If ws.Range("H15").Value = Date Then
       ws.Tab.ColorIndex = 3
    Else
       ws.Tab.ColorIndex = xlColorIndexNone
    End If
Next ws

End Sub
</code>```

Body:
I have a workbook that holds work orders(a different one on each sheet) that are time sensitive. At times there can be any where from 5 to 25 sheets in this workbook. In Cell H15 of each sheet is the due date of the work order. I am trying to set up a vba that when the workbook is opened it will check the date and change the tab of the sheets to red on the last day it is due to be done. I have a code that I thought was correct but is not working. I was told to try using (Private Sub Workbook_Open() ) but I can not seem to get the right coding so it checks all the sheets.

thank you,

Private Sub Worksheet_Change(ByVal Target As Range)

   With ActiveSheet
      If Range("H15").Value = Date Then
         .Tab.ColorIndex = 3 'Red

      End If
   End With
End Sub

Body:
Try this, in the ThisWorkbook module (and remove the worksheet change code). (In response to Jeeped's comment, the tab colour is removed everywhere else.)

Private Sub Workbook_Open()

Dim ws As Worksheet

For Each ws In Worksheets
    If ws.Range("H15").Value = Date Then
       ws.Tab.ColorIndex = 3
    Else
       ws.Tab.ColorIndex = xlColorIndexNone
    End If
Next ws

End Sub


问:
can asset folder be accessed by the user when the apk is installed?
For example i have an android program which contains important files in the assets folder , can the user who installed the apk access the assets folder or not ? for hacking purpose

答: Anyone can decompile your app and can see a lot of things including your assets. .apk file is just an compressed file which can be extracted easily.</p>


问:
python map vs list comprehsnion
I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

```<code>def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))
</code>```

This code does not work for the following example:

```<code>print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214
</code>```

However, a similar function crafted as:

```<code>def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))
</code>```

Returns the correct answer

```<code>print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214
</code>```

Shouldn't

```<code>map(int, numbers)
</code>```

be the same as

```<code>[int(number) for number in numbers]
</code>```

Why do the two functions not return the same values?

答:
In your high_and_low method, map(int, numbers) is not being assigned to a value.

```<code>def high_and_low(numbers):
    numbers = numbers.split(' ')
    numbers = map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))
</code>```

Also, map returns an iterator in Python 3.x. Your min(numbers) will error because max will exhaust the iterator and throw a ValueError due to an empty sequence. So you need to convert it to a list

```<code>def high_and_low(numbers):
    numbers = numbers.split(' ')
    numbers = list(map(int, numbers))
    return str(max(numbers)) + ' ' + str(min(numbers))
</code>```

Title: python map vs list comprehsnion

Body:
I am trying to return the min and max of a string of numbers, ie. ("1 2 3 4 5 6")

The code that I came up with is as follows

def high_and_low(numbers):
    numbers = numbers.split(' ')
    map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

This code does not work for the following example:

print(high_and_low("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
6 -214

However, a similar function crafted as:

def min_and_max(numbers):
    nn = [int(s) for s in numbers.split(' ')]
    return "%i %i" % (max(nn),min(nn))

Returns the correct answer

print(min_and_max("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6"))
542 -214

Shouldn't

map(int, numbers)

be the same as

[int(number) for number in numbers]

Why do the two functions not return the same values?

Body:
In your high_and_low method, map(int, numbers) is not being assigned to a value.

def high_and_low(numbers):
    numbers = numbers.split(' ')
    numbers = map(int, numbers)
    return str(max(numbers)) + ' ' + str(min(numbers))

Also, map returns an iterator in Python 3.x. Your min(numbers) will error because max will exhaust the iterator and throw a ValueError due to an empty sequence. So you need to convert it to a list

def high_and_low(numbers):
    numbers = numbers.split(' ')
    numbers = list(map(int, numbers))
    return str(max(numbers)) + ' ' + str(min(numbers))


问:
Using RSA encryption, how can i find d
I am using the euclidean algorithm when i have p = 163, q = 311 and e = 281. Here is what i have so far

```<code>N = p * q = 50693
Totient Symbol(n) = 162 x 310 = 50220

1.  50220 = 178(281) + 202
2.  281 = 1 (202) + 79
3.  202 = 2 (79) + 44
4.  79 = 1 (44) + 35
5.  44 = 1 (35) + 9
6.  35 = 3 (9) + 8
7.  9 = 1 (8) + 1
8.  8 = 8 (1) + 0
</code>```

I then move on to back substitution

```<code>A.  9 = 1 (8) + 1   === 1 = 9-1(8)
B.  8 = 35 – 3(9)
C.  1 = 1(9)-1(35-3(9))  -
D.  1 = 3(9) – 1(35) + 1(9)   add similar items
E.  1 = 4(9) -1(35)

9 = 44 – 1(35)
1 = 4 (44-1(35)) – 1(35)
1 = 4(44)-4(35)-1(35)

1 = 4(44) – 5(35)
</code>```

Take value next to 35 (5), subtract it from totient
50220 – 5 = 50215
d = 50215

This is wrong as i used an online calc to verify . Can anyone point me in the right direction here, i think the back substituion is wrong

答:
There are two different ways to calculate RSA d values, the φ (phi / totient) method, and the λ (lambda / least common multiple) method. While the original RSA paper (and RFC 2313) use phi, modern implementations (and RFC 2437) use lambda.

The totient value is easy: (p-1)(q-1) = 50220.
For lambda(p-1, q-1) we need to first compute GCD(p-1, q-1), the example uses the subtraction form of the Euclidian algorithm:

```<code>GCD(162, 310)
GCD(162, 148)
GCD(14, 148)
GCD(14, 134)
GCD(14, 120)
GCD(14, 106)
GCD(14, 92)
GCD(14, 78)
GCD(14, 64)
GCD(14, 50)
GCD(14, 36)
GCD(14, 22)
GCD(14, 8)
GCD(6, 8)
GCD(6, 2)
GCD(4, 2)
GCD(2, 2)
GCD = 2
</code>```

The least common multiple of (a, b) is a * b / GCD(a, b). So the lambda value is the totient / GCD, or 25110.

Now, to compute dPhi = ModInv(e, phi) or dLambda = ModInv(e, lambda) we can use the Extended Euclidean Algorithm:

```<code>ModInverse(281, 50220)
  r=50220, newR=281, t=    0, newT=    1
  r=  281, newR=202, t=    1, newT= -178
  r=  202, newR= 79, t= -178, newT=  179
  r=   79, newR= 44, t=  179, newT= -536
  r=   44, newR= 35, t= -536, newT=  715
  r=   35, newR=  9, t=  715, newT=-1251
  r=    9, newR=  8, t=-1251, newT= 4468
  r=    8, newR=  1, t= 4468, newT=-5719
  r=    1, newR=  0, t=-5719, newT=50220
  Correcting the sign of t
  dPhi = 44501

ModInverse(281, 25110)
  r=25110, newR=281, t=    0, newT=    1
  r=  281, newR=101, t=    1, newT=  -89
  r=  101, newR= 79, t=  -89, newT=  179
  r=   79, newR= 22, t=  179, newT= -268
  r=   22, newR= 13, t= -268, newT=  983
  r=   13, newR=  9, t=  983, newT=-1251
  r=    9, newR=  4, t=-1251, newT= 2234
  r=    4, newR=  1, t= 2234, newT=-5719
  r=    1, newR=  0, t=-5719, newT=25110
  Correcting the sign of t
  dLambda = 19391
</code>```

You seem to have done the descending step of the Extended Euclidean Algorithm correctly, but being unfamiliar with the back-propogation calculation (as opposed to the inline form) I don't see where you made a value or arithmetic error.

Title: Using RSA encryption, how can i find d

Body:
I am using the euclidean algorithm when i have p = 163, q = 311 and e = 281. Here is what i have so far

N = p * q = 50693
Totient Symbol(n) = 162 x 310 = 50220

1.  50220 = 178(281) + 202
2.  281 = 1 (202) + 79
3.  202 = 2 (79) + 44
4.  79 = 1 (44) + 35
5.  44 = 1 (35) + 9
6.  35 = 3 (9) + 8
7.  9 = 1 (8) + 1
8.  8 = 8 (1) + 0

I then move on to back substitution

A.  9 = 1 (8) + 1   === 1 = 9-1(8)
B.  8 = 35 – 3(9)
C.  1 = 1(9)-1(35-3(9))  -
D.  1 = 3(9) – 1(35) + 1(9)   add similar items
E.  1 = 4(9) -1(35)

9 = 44 – 1(35)
1 = 4 (44-1(35)) – 1(35)
1 = 4(44)-4(35)-1(35)

1 = 4(44) – 5(35)

Take value next to 35 (5), subtract it from totient
50220 – 5 = 50215
d = 50215

This is wrong as i used an online calc to verify . Can anyone point me in the right direction here, i think the back substituion is wrong

Body:
There are two different ways to calculate RSA d values, the φ (phi / totient) method, and the λ (lambda / least common multiple) method. While the original RSA paper (and RFC 2313) use phi, modern implementations (and RFC 2437) use lambda.

The totient value is easy: (p-1)(q-1) = 50220.
For lambda(p-1, q-1) we need to first compute GCD(p-1, q-1), the example uses the subtraction form of the Euclidian algorithm:

GCD(162, 310)
GCD(162, 148)
GCD(14, 148)
GCD(14, 134)
GCD(14, 120)
GCD(14, 106)
GCD(14, 92)
GCD(14, 78)
GCD(14, 64)
GCD(14, 50)
GCD(14, 36)
GCD(14, 22)
GCD(14, 8)
GCD(6, 8)
GCD(6, 2)
GCD(4, 2)
GCD(2, 2)
GCD = 2

The least common multiple of (a, b) is a * b / GCD(a, b). So the lambda value is the totient / GCD, or 25110.

Now, to compute dPhi = ModInv(e, phi) or dLambda = ModInv(e, lambda) we can use the Extended Euclidean Algorithm:

ModInverse(281, 50220)
  r=50220, newR=281, t=    0, newT=    1
  r=  281, newR=202, t=    1, newT= -178
  r=  202, newR= 79, t= -178, newT=  179
  r=   79, newR= 44, t=  179, newT= -536
  r=   44, newR= 35, t= -536, newT=  715
  r=   35, newR=  9, t=  715, newT=-1251
  r=    9, newR=  8, t=-1251, newT= 4468
  r=    8, newR=  1, t= 4468, newT=-5719
  r=    1, newR=  0, t=-5719, newT=50220
  Correcting the sign of t
  dPhi = 44501

ModInverse(281, 25110)
  r=25110, newR=281, t=    0, newT=    1
  r=  281, newR=101, t=    1, newT=  -89
  r=  101, newR= 79, t=  -89, newT=  179
  r=   79, newR= 22, t=  179, newT= -268
  r=   22, newR= 13, t= -268, newT=  983
  r=   13, newR=  9, t=  983, newT=-1251
  r=    9, newR=  4, t=-1251, newT= 2234
  r=    4, newR=  1, t= 2234, newT=-5719
  r=    1, newR=  0, t=-5719, newT=25110
  Correcting the sign of t
  dLambda = 19391

You seem to have done the descending step of the Extended Euclidean Algorithm correctly, but being unfamiliar with the back-propogation calculation (as opposed to the inline form) I don't see where you made a value or arithmetic error.


问:
How to get the subdomain value from a url?
how can I get the subdomain value in rails, is there a built-in way to do this?

e.g.

```<code>test123.example.com
</code>```

I want the test123 part of the url.

答:
You can use the SubdomainFu plugin. This plugin gives you a method current_subdomain which returns the current_subdomain of your app.

You can also have a look at this Railscast

UPDATE

You can also use request.subdomains this will give you an array of subdomains.

Body:
how can I get the subdomain value in rails, is there a built-in way to do this?

e.g.

test123.example.com

I want the test123 part of the url.


问:
Windows Batch: automated Dataimport from USB-Drive
I wrote a script that should detect when an USB-Devices is mounted (I:) and when the text database on the harddrive is not empty it should copy the data in an new generated textfile on drive C: with an unique name. After the operationit should delete the database and create an new empty one.

I got two problems I am not able to resolve. The first file contains all datas as intended. After that the database is deleted and new created. But in the second run the size is still the old one so all operations are repeated. Altough the database is empty.

Second Problem is, the if condition seems not to work. The brakets are always executed.

```<code>@echo off

:loop
if exist I:\ (
    :GETTEMPNAME
        set TMPFILE=UL%DATE%_%RANDOM%
        if exist "%TMPFILE%" GOTO :GETTEMPNAME
    echo %TMPFILE%

    echo success
    I:
    set size=0
    call :filesize "I:\database.txt"
    echo file size is %size%

    set sizelimit = 6
    if "%size%" GTR "%sizelimit%" (
        echo greater
        C:
        cd C:\SaveData
        type NUL > %TMPFILE%.txt
        echo S:OK; >> %TMPFILE%.txt

        echo accessing data
        I:

        for /F "tokens=*" %%A in (database.txt) do (
        C:
        echo %%A >> %TMPFILE%.txt
        I:
        )
        C:
        echo E:OK >> %TMPFILE%.txt
        I:
        del "database.txt"
        type NUL > database.txt

    )

    ping 127.0.0.1 -n 40 > 0

) else (
    echo waiting for data
    ping 127.0.0.1 -n 40 > NUL
)

goto loop

:: set filesize of 1st argument in %size% variable, and return
:filesize
  set size=%~z1
</code>```

Here is the log from the cmd:

Any help is appreciated!
Thanks

答:
I have rewritten your script and assumed C:\SaveData\ as the intended location for your output text file, please change it if my assumption was incorrect.

@Echo Off

:Loop
If Not Exist I:\ (Echo=Waiting for data ...
    Timeout 40 /NoBreak>Nul
    GoTo Loop)
CD /D I:\
If Not Exist "database.txt" Exit/B
Echo=Success
SetLocal

:GetTempName
Set "TmpFile=C:\SaveData\UL%DATE%_%RANDOM%.txt"
If Exist "%TmpFile%" GoTo GetTempName
Set "SizeLimit=6"
For %%A In ("database.txt") Do Set "Size=%%~zA"
Echo=File size is %Size%
If %Size% Gtr %SizeLimit% (Echo=Greater
    Echo=S:OK;>"%TmpFile%"
    Echo=Accessing data ...
    Type "database.txt">>"%TmpFile%"
    Echo=E:OK>>"%TmpFile%"
    Type Nul>"database.txt")
EndLocal
Timeout 40 /NoBreak>Nul
GoTo Loop
```

Body:
I wrote a script that should detect when an USB-Devices is mounted (I:) and when the text database on the harddrive is not empty it should copy the data in an new generated textfile on drive C: with an unique name. After the operationit should delete the database and create an new empty one.

I got two problems I am not able to resolve. The first file contains all datas as intended. After that the database is deleted and new created. But in the second run the size is still the old one so all operations are repeated. Altough the database is empty.

Second Problem is, the if condition seems not to work. The brakets are always executed.

@echo off

:loop
if exist I:\ (
    :GETTEMPNAME
        set TMPFILE=UL%DATE%_%RANDOM%
        if exist "%TMPFILE%" GOTO :GETTEMPNAME
    echo %TMPFILE%

    echo success
    I:
    set size=0
    call :filesize "I:\database.txt"
    echo file size is %size%

    set sizelimit = 6
    if "%size%" GTR "%sizelimit%" (
        echo greater
        C:
        cd C:\SaveData
        type NUL > %TMPFILE%.txt
        echo S:OK; >> %TMPFILE%.txt

        echo accessing data
        I:

        for /F "tokens=*" %%A in (database.txt) do (
        C:
        echo %%A >> %TMPFILE%.txt
        I:
        )
        C:
        echo E:OK >> %TMPFILE%.txt
        I:
        del "database.txt"
        type NUL > database.txt

    )

    ping 127.0.0.1 -n 40 > 0

) else (
    echo waiting for data
    ping 127.0.0.1 -n 40 > NUL
)

goto loop

:: set filesize of 1st argument in %size% variable, and return
:filesize
  set size=%~z1

Here is the log from the cmd:

Any help is appreciated!
Thanks


问:
window bat file not working with german umlauts
I am creating a .bat file from java program:

```<code> final OutputStreamWriter fop = new OutputStreamWriter( new FileOutputStream( "test.bat" ), Charset.forName( "UTF8" ) );
</code>```

and executing it using Runtime.getRuntime().exec();
        in directory  (C:\usr\testdir)

```<code>@echo off
cd C:\usr\testdir
echo "hello"
</code>```

The Above bat file execute successfully.
But When I change the Directory path containing German umlauts it gives me error.:
The system cannot find the path specified
where dir path (C:\usr\wÖrkingÄÜÖ) and ./bat will be the same :

```<code>@echo off
cd C:\usr\wÖrkingÄÜÖ
echo "hello"
</code>```

SO the issue is the path containing umlauts.After Google help I add chcp 652001 at the top of bat file to change the pageCode but the issue still remain the same . Can any one help me what I am missing??

答:
You should use 65001, not 652001. Try this:

```<code>CHCP 65001
@echo off
cd C:\usr\wÖrkingÄÜÖ
echo "hello"
</code>```

This should force the batch file to use the UTF-8 character set which should support umlauts.

Body:
I am creating a .bat file from java program:

 final OutputStreamWriter fop = new OutputStreamWriter( new FileOutputStream( "test.bat" ), Charset.forName( "UTF8" ) );

and executing it using Runtime.getRuntime().exec();
        in directory  (C:\usr\testdir)

@echo off
cd C:\usr\testdir
echo "hello"

The Above bat file execute successfully.
But When I change the Directory path containing German umlauts it gives me error.:
The system cannot find the path specified
where dir path (C:\usr\wÖrkingÄÜÖ) and ./bat will be the same :

@echo off
cd C:\usr\wÖrkingÄÜÖ
echo "hello"

SO the issue is the path containing umlauts.After Google help I add chcp 652001 at the top of bat file to change the pageCode but the issue still remain the same . Can any one help me what I am missing??

Body:
You should use 65001, not 652001. Try this:

CHCP 65001
@echo off
cd C:\usr\wÖrkingÄÜÖ
echo "hello"

This should force the batch file to use the UTF-8 character set which should support umlauts.


问:
How to use let variable across example blocks without reinitiating the let block?
I want to create FactoryGirl object and use across groups without re-initiating let block multiple times. There should be only one user created in Database. How can i achieve it?

```<code>describe MyCLass do
  let(:adm) { FactoryGirl.create(:user) }

  describe "test for" do
    #want to use :adm here
  end

  describe "test2 for" do
    #want to use :adm here
  end

  describe "test3" do
    #want to use :adm here
  end
end
</code>```

*I am new to RSpec

答:
Best bet is to not use a let for this but instead a before :all:

```<code>describe MyCLass do
  before :all do
    @adm = FactoryGirl.create(:user)
  end

  describe "test for" do
    @adm.methods_to_test
  end

  describe "test2 for" do
    @adm.methods_to_test
  end

  describe "test3" do
    @adm.methods_to_test
  end
end
</code>```

With that said, this is likely not a good idea since it will create interdependent tests which is not what you want! Each test should run in isolation without modified state between tests. Having a "global" user instance will likely cause flapping tests due to test order issues.

Body:
I want to create FactoryGirl object and use across groups without re-initiating let block multiple times. There should be only one user created in Database. How can i achieve it?

describe MyCLass do
  let(:adm) { FactoryGirl.create(:user) }

  describe "test for" do
    #want to use :adm here
  end

  describe "test2 for" do
    #want to use :adm here
  end

  describe "test3" do
    #want to use :adm here
  end
end

*I am new to RSpec

Body:
Best bet is to not use a let for this but instead a before :all:

describe MyCLass do
  before :all do
    @adm = FactoryGirl.create(:user)
  end

  describe "test for" do
    @adm.methods_to_test
  end

  describe "test2 for" do
    @adm.methods_to_test
  end

  describe "test3" do
    @adm.methods_to_test
  end
end

With that said, this is likely not a good idea since it will create interdependent tests which is not what you want! Each test should run in isolation without modified state between tests. Having a "global" user instance will likely cause flapping tests due to test order issues.


问:
Php Simple HTML DOM Parser - how to work with block repeats
I have blocks of
 but without attributes. After that go blocks of
 without attributes.

Structure of this looked like this:

```<code><h2></h2>
<p></p>
<p></p>
<p></p>
<h2></h2>
<p></p>
<p></p>
<h2></h2>
<p></p>
</code>```

I'm using Php Simple HTML DOM Parser. I want to get data from
 block, after that get all
 to another
 and so on.

But all
 must be connected to
 which go after them. I thought to use key => value (example
 =>
,
,... and another
) but I am not sure how to do this.

Also, I know about next_sibling(), but don't know how to use it in loop. I did 2 variables, 1st has all
, 2nd has
. I thought it can be useful for my goal. Here is the code:

```<code>$test = file_get_html('url');
foreach($test->find('h2') as $test2) {
  echo $test2 . '<br>';
  foreach($test->find('p') as $test3) {
    echo $test3 .'<br>';
  }
}
</code>```

答:
Answer of my question here. I hope it can help somebody!)    </p>

```<code> `foreach ($html->find('.div') as $div)
    {
        if(!$next=$div->next_sibling()) continue;
            if($next->tag==='h2')
            {
                $h2 =$next;
                echo $h2;

                while ($h2 = $h2->next_sibling())
                {
                    if(!$h2->tag=='p') break;
                    {
                        $p =$h2;
                        echo $p;
                    }
                }
                while ($h2 = $h2->next_sibling())
                {
                    if(!$h2->tag=='table') break;
                    {
                        $tab =$h2;
                        echo $tab;
                    }
                }
                while ($h2 = $h2->next_sibling())
                {
                    if(!$h2->tag=='ul') break;
                    {
                        $ul =$h2;
                        echo $ul;
                    }
                }
            }
            else continue;
    }`
</code>```

Body:
I have blocks of
 but without attributes. After that go blocks of
 without attributes.

Structure of this looked like this:

I'm using Php Simple HTML DOM Parser. I want to get data from
 block, after that get all
 to another
 and so on.

But all
 must be connected to
 which go after them. I thought to use key => value (example
 =>
,
,... and another
) but I am not sure how to do this.

Also, I know about next_sibling(), but don't know how to use it in loop. I did 2 variables, 1st has all
, 2nd has
. I thought it can be useful for my goal. Here is the code:

$test = file_get_html('url');
foreach($test->find('h2') as $test2) {
  echo $test2 . '
';
  foreach($test->find('p') as $test3) {
    echo $test3 .'
';
  }
}

Body:
Answer of my question here. I hope it can help somebody!)

 `foreach ($html->find('.div') as $div)
    {
        if(!$next=$div->next_sibling()) continue;
            if($next->tag==='h2')
            {
                $h2 =$next;
                echo $h2;

                while ($h2 = $h2->next_sibling())
                {
                    if(!$h2->tag=='p') break;
                    {
                        $p =$h2;
                        echo $p;
                    }
                }
                while ($h2 = $h2->next_sibling())
                {
                    if(!$h2->tag=='table') break;
                    {
                        $tab =$h2;
                        echo $tab;
                    }
                }
                while ($h2 = $h2->next_sibling())
                {
                    if(!$h2->tag=='ul') break;
                    {
                        $ul =$h2;
                        echo $ul;
                    }
                }
            }
            else continue;
    }`


问:
Find if an element has a children begins with certain x JQuery
I want to select all the child elements that has a class name begins with a certain string, or at least know if that parent has this kind of children:

HTML:

```<code><div class="myParent">
    <div class="good_child_1">
    </div>
    <div class="bad_child_1">
    </div>
    <div class="good_child_2">
    </div>
    <div class="bad_child_2">
    </div>
    <div class="very_bad_child_23452345">
    </div>
</div>
</code>```

i want a JQuery code to select all children that start with "good_child",
code should be something like this:

JS:

```<code>var all_good_childs = $(".myParent").find('[class^="good_child"]');
if (!all_good_childs.length)
{
    //do something
}
</code>```

but it didn't work, any suggestions?

答:
```<code>$(function() {
    console.log($("div[class^='good_child']"));
});
</code>```

Body:
I want to select all the child elements that has a class name begins with a certain string, or at least know if that parent has this kind of children:

HTML:

i want a JQuery code to select all children that start with "good_child",
code should be something like this:

JS:

var all_good_childs = $(".myParent").find('[class^="good_child"]');
if (!all_good_childs.length)
{
    //do something
}

but it didn't work, any suggestions?


问:
Sql query too slow - looking for alternative way to write it
I have this mysql query that does what it needs to but it takes a really long time to load the content where as my other queries run perfectly fine and quick. Is there a better way to do it? I just want it to load faster. Here is my query:</p>

```<code>SELECT
    DISTINCT( # Without this I get too many results
        CONCAT_WS(' ',
            MONTHNAME(a.DateTimeViewed),
            YEAR(a.DateTimeViewed)
        )
    ) AS ViewedDate, # Displays as "January 2017" (example)
    (
        SELECT COUNT(b.ViewID)
        FROM views b
        WHERE
            MONTH(b.DateTimeViewed) = MONTH(a.DateTimeViewed) AND
            YEAR(b.DateTimeViewed) = YEAR(a.DateTimeViewed)
    ) as TotalViews
FROM views a
    WHERE a.DateTimeViewed >= date_sub(now(), interval 6 month)
    ORDER BY YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC
</code>```

答:
You are working too hard.

```<code>SELECT  CONCAT_WS(' ', MONTHNAME(a.DateTimeViewed), YEAR(a.DateTimeViewed)
                 ) AS ViewedDate,
        COUNT(*) as TotalViews
    FROM  views a
    WHERE  a.DateTimeViewed >= date_sub(now(), interval 6 month)
    ORDER BY  YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC
</code>```

Since you are backing up 6 months from this instant, you are getting the count for only part of the first month.  Perhaps you want to change one line:

```<code>WHERE a.DateTimeViewed >= CONCAT(LEFT(CURDATE() - INTERVAL 6 MONTH, 7), '-01')
</code>```

COUNT(*) is the usual way to count rows.  COUNT(x) does the same, but adds on the effort to filter out rows with x IS NULL.

Body:
I have this mysql query that does what it needs to but it takes a really long time to load the content where as my other queries run perfectly fine and quick. Is there a better way to do it? I just want it to load faster. Here is my query:

SELECT
    DISTINCT( # Without this I get too many results
        CONCAT_WS(' ',
            MONTHNAME(a.DateTimeViewed),
            YEAR(a.DateTimeViewed)
        )
    ) AS ViewedDate, # Displays as "January 2017" (example)
    (
        SELECT COUNT(b.ViewID)
        FROM views b
        WHERE
            MONTH(b.DateTimeViewed) = MONTH(a.DateTimeViewed) AND
            YEAR(b.DateTimeViewed) = YEAR(a.DateTimeViewed)
    ) as TotalViews
FROM views a
    WHERE a.DateTimeViewed >= date_sub(now(), interval 6 month)
    ORDER BY YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC

Body:
You are working too hard.

SELECT  CONCAT_WS(' ', MONTHNAME(a.DateTimeViewed), YEAR(a.DateTimeViewed)
                 ) AS ViewedDate,
        COUNT(*) as TotalViews
    FROM  views a
    WHERE  a.DateTimeViewed >= date_sub(now(), interval 6 month)
    ORDER BY  YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC

Since you are backing up 6 months from this instant, you are getting the count for only part of the first month.  Perhaps you want to change one line:

WHERE a.DateTimeViewed >= CONCAT(LEFT(CURDATE() - INTERVAL 6 MONTH, 7), '-01')

COUNT(*) is the usual way to count rows.  COUNT(x) does the same, but adds on the effort to filter out rows with x IS NULL.


问:
Dynamically bind the data-bind attribute in Knockout
I want to bind the data-bind attribute dynamically.

Please check this link https://jsfiddle.net/km89jfyp/5/

```<code>/km89jfyp/5/
</code>```

答:
ko.applyBindingAccessorsToNode takes the name of a binding to apply as a string so you can use that to dynamically apply a binding. You can use it from your javascript in an event, or you can make a custom binding to use it inside your html. A custom binding might look something like this:

```<code>ko.bindingHandlers.applyBinding = {
  init: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {
    var bindingName = ko.unwrap(valueAccessor());
    var target = ko.unwrap(allBindingsAccessor().bindingTarget);
    if (bindingName) {
      var binding = {};
      binding[bindingName] = function() {
        return target;
      };

      ko.applyBindingAccessorsToNode(element, binding, bindingContext);
    }
  }
}
</code>```

You would use it in a binding like:

Your code still leaves me with a lot of questions so I can't be sure this will work for you. The sample you linked has a lot of issues besides just the binding so I had to make some assumptions to fix errors and get it working, but here's an example based on your code: jsFiddle

Body:
I want to bind the data-bind attribute dynamically.

Please check this link https://jsfiddle.net/km89jfyp/5/

/km89jfyp/5/

Body:
ko.applyBindingAccessorsToNode takes the name of a binding to apply as a string so you can use that to dynamically apply a binding. You can use it from your javascript in an event, or you can make a custom binding to use it inside your html. A custom binding might look something like this:

ko.bindingHandlers.applyBinding = {
  init: function(element, valueAccessor, allBindingsAccessor, data, bindingContext) {
    var bindingName = ko.unwrap(valueAccessor());
    var target = ko.unwrap(allBindingsAccessor().bindingTarget);
    if (bindingName) {
      var binding = {};
      binding[bindingName] = function() {
        return target;
      };

      ko.applyBindingAccessorsToNode(element, binding, bindingContext);
    }
  }
}

You would use it in a binding like: <span data-bind="applyBinding: MyBinding, bindingTarget: myValue"></span>

Your code still leaves me with a lot of questions so I can't be sure this will work for you. The sample you linked has a lot of issues besides just the binding so I had to make some assumptions to fix errors and get it working, but here's an example based on your code: jsFiddle


问:
yii2 registering JS files to a View
I have A.php view file in /views/A/ folder.
And I have A.js js file in /views/A/ folder
Please help me register js file in view file.

As I understand I must write
$this->registerJsFile('path/to/file.js'); in view file.

But (Question A) I get method registerJsFile is not found in a class  message from PHPStorm.

Also (Question B) what should I write in path considering both files are in the same folder /views/A/ ?

答:
If you register a js file by:

```<code>$this->registerJsFile("@web/js/all.js");
</code>```

This will work but you will not be able to use jQuery. Because this file all.js is loaded before jQuery. To load after jQuery we make it depend it on 'yii\web\YiiAsset' or on \yii\web\JqueryAsset . So it will be loaded after jQuery.js. Example:

```<code>$this->registerJsFile("@web/js/all.js",[
    'depends' => [
        \yii\web\JqueryAsset::className()
    ]
]);
</code>```

So What is difference between \yii\web\JqueryAsset and \yii\web\YiiAsset?

In jQueryAsset the js file will load after jQuery.js and in YiiAsset the js file will load after yii.js file.

If you want to create your own custom Asset Bundle:

```<code><?php
namespace frontend\components;
use yii;

use yii\web\AssetBundle;
class CustomAssets extends AssetBundle
{
    public $css = [
        "path/to/css/file.css"
    ];
    public $js = [
        "path/to/js/file.js"
    ];
    public $depends = [
    ];
}
</code>```

Title: yii2 registering JS files to a View

Body:
If you register a js file by:

$this->registerJsFile("@web/js/all.js");

This will work but you will not be able to use jQuery. Because this file all.js is loaded before jQuery. To load after jQuery we make it depend it on 'yii\web\YiiAsset' or on \yii\web\JqueryAsset . So it will be loaded after jQuery.js. Example:

$this->registerJsFile("@web/js/all.js",[
    'depends' => [
        \yii\web\JqueryAsset::className()
    ]
]);

So What is difference between \yii\web\JqueryAsset and \yii\web\YiiAsset?

In jQueryAsset the js file will load after jQuery.js and in YiiAsset the js file will load after yii.js file.

If you want to create your own custom Asset Bundle:

<?php
namespace frontend\components;
use yii;

use yii\web\AssetBundle;
class CustomAssets extends AssetBundle
{
    public $css = [
        "path/to/css/file.css"
    ];
    public $js = [
        "path/to/js/file.js"
    ];
    public $depends = [
    ];
}


问:
Applying lock on HashMap
I have a HashMap which is static and three threads which try to access HashMap simultaneously from their corresponding class`s.

each thread task is get list value of a specified key, process some operations on the list(modify the list). and put the processed list in HashMap.

I want to make other threads trying to access the HashMap wait until current thread finishes the processing and modifying the HashMap.

in some situation, the flow is like this,

thread A is retrieved HashMap, while Thread A is processing on the list of HashMap, other Thread B retrieves the HashMap and starts its processing.

Actual behaviour has to be like:

    Thread A -> retrieves HashMap -> process -> put value in HashMap.
    Thread B -> retrieves HashMap -> process -> put value in HashMap.
    Thread C -> retrieves HashMap -> process -> put value in HashMap.

logic :

apply lock on HashMap

retrieve.

process.

put into HashMap.

release lock.

help me in converting the logic to code, or any suggestions are accepted with smile.

答:
You can either use ConcurrentHashMap as suggested above or use class level locks.What I mean by it is by using synchronized keyword on static method.eg

```<code>public class SynchronizedExample extends Thread {
    static HashMap map = new HashMap();
    public synchronized static void execute() {
        //Modify and read HashMap
    }

    public void run() {
            execute();
    }
}
</code>```

Also as others mentioned it will incur performance bottlenecks if you use synchronized methods, depends on how atomic functions you make.
Also you can check class level locks vs object level locks(Although its almost same, but do check that.)

Title: Applying lock on HashMap

Body:
You can either use ConcurrentHashMap as suggested above or use class level locks.What I mean by it is by using synchronized keyword on static method.eg

public class SynchronizedExample extends Thread {
    static HashMap map = new HashMap();
    public synchronized static void execute() {
        //Modify and read HashMap
    }

    public void run() {
            execute();
    }
}

Also as others mentioned it will incur performance bottlenecks if you use synchronized methods, depends on how atomic functions you make.
Also you can check class level locks vs object level locks(Although its almost same, but do check that.)


问:
Selenium WebDriver C# Attached with already open Chrome Browser
I am using WebDriver C# for Chrome Automation. I want to attach driver to already opened Chrome Instance.

I am struggling since long time; I hope here I got correct and proper answer.

答: As far as I know, attaching to an existing browser is not possible, and there are not plans to implement that functionality: https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/18.</p>


问:
TemplateSyntaxError trying to use cut filter in template tag in Django
I am trying to set a link href as part of the current URL path in my Django view template. But I am currently getting the error

Could not parse some characters:
  request.get_full_path|()||cut:'?thumbnail=true'

This is my code

```<code>{% if 'thumbnail' in 'request.get_full_path()' %}
    <a href="{{ request.get_full_path()|cut:'?thumbnail=true' }}">Link</a>
{% endif %}
</code>```

Why am I getting this error? Can I use the cut filter this way?

Thanks

答:
Do not call functions like you do in python code. Instead do this:</p>

```<code>{{ request.get_full_path|cut:'?thumbnail=true' }}
</code>```

Body:
I am trying to set a link href as part of the current URL path in my Django view template. But I am currently getting the error

Could not parse some characters:
  request.get_full_path|()||cut:'?thumbnail=true'

This is my code

{% if 'thumbnail' in 'request.get_full_path()' %}
    Link
{% endif %}

Why am I getting this error? Can I use the cut filter this way?

Thanks

Body:
Do not call functions like you do in python code. Instead do this:

{{ request.get_full_path|cut:'?thumbnail=true' }}