问:
What to do with a danger of literal types?
I translate a big JS project to TS project and noticed something. For example I have a module, which looks like this:

WinConstants.ts

```<code>export = {
  "no_win":0,
  "win":1,
  "big_win":2,
  "mega_win":3
}
</code>```

I want to make it really constant, so I restrict it like this:

WinConstants.ts

```<code>class WinConstants{
  readonly no_win:0;
  readonly win:1;
  readonly big_win:2;
  readonly mega_win:3;
}

export = new WinConstants();
</code>```

Pretty cool huh? Done with it, now go translate next module. Right? Not so fast. I forgot to replace ":"s with "="s and TypeScript does not warn me about it. All values are now undefined. It may go under the radar until I see it in runtime... Welcome back to JS uncertainty! The whole point of translating things to TS, when you rely on compiler's errors, just cancelled itself...  If there had been no literal types, this would have never happened, because literal numbers in this case wouldn't have been types.

So what to do? Don't get me wrong, I love literal types, they help a lot, but the syntax is now against me. These kind of things may go unnoticed not only when I translate, but when I write something and accidentally put : in JSON style rather than = sign.

Any ideas?

答:
Neither your first, nor your second approach are good, as you are exporting a constant object or an instance of a class.

You should use an enum for this (more info).

```<code>export enum WinConstants {
  NO_WIN = 0,
  WIN = 1,
  BIG_WIN = 2,
  MEGA_WIN = 3
}
</code>```

Body:
I translate a big JS project to TS project and noticed something. For example I have a module, which looks like this:

WinConstants.ts

export = {
  "no_win":0,
  "win":1,
  "big_win":2,
  "mega_win":3
}

I want to make it really constant, so I restrict it like this:

WinConstants.ts

class WinConstants{
  readonly no_win:0;
  readonly win:1;
  readonly big_win:2;
  readonly mega_win:3;
}

export = new WinConstants();

Pretty cool huh? Done with it, now go translate next module. Right? Not so fast. I forgot to replace ":"s with "="s and TypeScript does not warn me about it. All values are now undefined. It may go under the radar until I see it in runtime... Welcome back to JS uncertainty! The whole point of translating things to TS, when you rely on compiler's errors, just cancelled itself...  If there had been no literal types, this would have never happened, because literal numbers in this case wouldn't have been types.

So what to do? Don't get me wrong, I love literal types, they help a lot, but the syntax is now against me. These kind of things may go unnoticed not only when I translate, but when I write something and accidentally put : in JSON style rather than = sign.

Any ideas?

Body:
Neither your first, nor your second approach are good, as you are exporting a constant object or an instance of a class.

You should use an enum for this (more info).

export enum WinConstants {
  NO_WIN = 0,
  WIN = 1,
  BIG_WIN = 2,
  MEGA_WIN = 3
}


来源: stackexchange

问:
Weka 3.7 and 3.6 / No suitable driver found for
There seems to be several postings about using Weka as an implementation for programs, but there are only few seem to be related to using Weka 3.7/3.6 with a database for data mining purposes.

I referred to Weka's web site. (http://weka.wikispaces.com/Databases)

In order to connect Weka and a DB, what I've done are...

1)Download JDBC Driver for MySQL (mysql-connector-java-5.1.34-bin.jar)

2)Set CLASSPATH as "C:\Program Files\Weka-3-7\mysql-connector-java-5.1.34-bin.jar" for the user's environmental variable

3)Open the RunWeka.ini file and changed the last line into "cp=%CLASSPATH%;C:\Program Files\Weka-3-7\mysql-connector-java-5.1.34-bin.jar"
(I referred to "http://blog.ahughes.org/?p=347")

However, Weka 3.7 still produces the No suitable driver error. I tried it by using Weka 3.6, but in vain.

The Weka's web site above seems to provide a little old information, and some information doesn't seem to be related to Weka 3.6 or above.

I would appreciate if you would give any insight.

EDIT

(WEKA & MySQL Setup a connection)
This person seems to have encountered an identical issue, but following the answer of this page didn't solve my issue...

答:
According to the Troubleshooting section of the database configuration there are 3 possible errors that can give you the 'No suitable driver exception'.

Your JDBC driver is not set in the CLASSPATH. Finding out if this is the issue can be accomplished by executing the command 'java weka.core.SystemInfo' via the SimpleCLI. If the property 'java.class.path' has only the entry './weka.jar' then you can simply set the CLASSPATH environmental variable to ".;C:/PATH_TO_JDBC.jar". Rerun the above command and in the 'java.class.path' you should see now 'java.class.path: ./weka.jar;.;C:/PATH_TO_JDBC.jar'

The jdbcDriver property is either mispelled or you have used it multiple times in the DatabaseUtils.props (it must be unique)

The jdbcURL property is either mispelled or you have used it multiple times in the DatabaseUtils.props (it must be unique)

A final note: if you are using Weka (>= 3.7.2) then you must place the DatabaseUtils.props file under the 'C:\Users\USERNAME\wekafiles\props'

ContentLicense: CC BY-SA 3.0


问:
Is there any other way to mock SharedPreferences for Android tests?
I'm writing UI tests for Android app with Espresso. But there is a problem, that it's impossible to mock SharedPreferences data. I've found some workarounds, but they are using dependency injection (Dagger2 primary).

Is there any way I can mock prefs without any dependency injections?
Maybe exists another testing framework suitable for it?

Edit:
I need to mock SharedPreferences in instrumented, not unit tests.

答:
Check out Robolectric. Then you'd do this:

```<code>SharedPreferences sharedPreferences = Robolectric.application
      .getSharedPreferences("you_custom_pref_name", Context.MODE_PRIVATE);
</code>```

From the official website:

Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds.

Body:
Check out Robolectric. Then you'd do this:

SharedPreferences sharedPreferences = Robolectric.application
      .getSharedPreferences("you_custom_pref_name", Context.MODE_PRIVATE);

From the official website:

Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds.


问:
javascript skip duplicate permutation from array
I have an array with permutations but I need to remove duplicate permutations.

Permutations for 3 different digits is always 6 ways, so 345 and 453 are the same number. 497, 479 and 749 likewise would be considered the same number.

Also, 128, 281, 812, 182, 218 and 821 are all the same number.

It means I need to keep any only one permutation from 128, 281, 812, 182, 218 and 821 all others should be removed from the array.

Like if array has 497, 479, 749, 128, 281, 812, 182, 218, 821

output should be : 497, 128

答:
You first need to make an outer loop that loops throuhg all the items once.

Then you need a loop that loops through already existing items.
In that inner loop you test the current outer loop item against an inner loop item.

You need to sort the individual characters/numbers so they are all the same.

You can do that by

converting the number to string,

then split it on every character,

sort it,

join it back to string

and then compare them.

Things that are not an anagram can be pushed to the already existing items.

//Test wether something is an anagram
function isAnagram(word1, word2) {
  var str1 = (word1 + "").split('').sort().join('').trim();
  var str2 = (word2 + "").split('').sort().join('').trim();
  return str1 === str2;
}
// testing array
var arr = [42, 48, 84, 128, 281, 812, 182, 218, 821];
// result array
var approved = [];
// loop through all items
for (var c = 0; c < arr.length; c++) {
  var test = arr[c];
  var good = true;
  // loop through all already approved items.
  for (var i = 0; i < approved.length; i++) {
    var against = approved[i];
    // if it's an anagram, don't add it.
    if (isAnagram(test, against)) {
      good = false;
      break;
    }
  }
  // if it wasn't flagged as an anagram, add it to approved.
  if (good) {
    approved.push(test);
  }
}
console.log(approved);```
</div>
</div>
</p>

<p>To get a bit more brevity and keep it all in one function call without external variables you can do:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// testing array
var arr = [42, 48, 84, 128, 281, 812, 182, 218, 821];

var result = arr.reduce(function(exists, test) {
        if(!Array.isArray(exists)) {
           exists = [exists];
        }
        if(exists.filter(function(against) {
               var str1 = (test + "").split('').sort().join('').trim();
               var str2 = (against + "").split('').sort().join('').trim();
               return str1 === str2;
           }).length === 0) {
            exists.push(test);
        }
        return exists;
    });

console.log(result);</code>```

Body:
You first need to make an outer loop that loops throuhg all the items once.

Then you need a loop that loops through already existing items.
In that inner loop you test the current outer loop item against an inner loop item.

You need to sort the individual characters/numbers so they are all the same.

You can do that by

converting the number to string,

then split it on every character,

sort it,

join it back to string

and then compare them.

Things that are not an anagram can be pushed to the already existing items.

//Test wether something is an anagram
function isAnagram(word1, word2) {
  var str1 = (word1 + "").split('').sort().join('').trim();
  var str2 = (word2 + "").split('').sort().join('').trim();
  return str1 === str2;
}
// testing array
var arr = [42, 48, 84, 128, 281, 812, 182, 218, 821];
// result array
var approved = [];
// loop through all items
for (var c = 0; c < arr.length; c++) {
  var test = arr[c];
  var good = true;
  // loop through all already approved items.
  for (var i = 0; i < approved.length; i++) {
    var against = approved[i];
    // if it's an anagram, don't add it.
    if (isAnagram(test, against)) {
      good = false;
      break;
    }
  }
  // if it wasn't flagged as an anagram, add it to approved.
  if (good) {
    approved.push(test);
  }
}
console.log(approved);

To get a bit more brevity and keep it all in one function call without external variables you can do:

// testing array
var arr = [42, 48, 84, 128, 281, 812, 182, 218, 821];

var result = arr.reduce(function(exists, test) {
        if(!Array.isArray(exists)) {
           exists = [exists];
        }
        if(exists.filter(function(against) {
               var str1 = (test + "").split('').sort().join('').trim();
               var str2 = (against + "").split('').sort().join('').trim();
               return str1 === str2;
           }).length === 0) {
            exists.push(test);
        }
        return exists;
    });

console.log(result);


问:
Is it possible to compile/link to occi with gcc on HPUX?
We have Oracle 11 running on HP-UX 11.31 and gcc 4.4.3. It seems that there is no way to link to occi, because it was built with aCC. Is there any workaround for this?

I had the silly idea that I could somehow build a library that basically proxied the connection - build the library with aCC in some way that could be linked to by gcc. Is this possible?

答:
No, there isn't a way around that.

Different C compilers have interchangeable code using a standard ABI.  You can mix and match their object code more or less with impunity.

However, different C++ compilers have a variety of different conventions that mean that their object code is not compatible.  These relate to class layout (especially in multiple inheritance hierarchies and the dreaded 'diamond-of-death'), but also in name mangling conventions and exception handling.  The name mangling schemes are deliberately made different so that you cannot accidentally link objects from one compiler with another.

Generally, if libraries are built using a C++ compiler, you have to link your code using the same - or at least a compatible - C++ compiler.  And that almost invariably means a compiler from the same family.  For example, you might be able to use G++ 4.5.0 even if the code was built with G++ 4.4.2.  However, you won't be able to mix aCC with G++.

ContentLicense: CC BY-SA 2.5


问:
Python- if statement evaluation pattern
what the heck is the if statement doing?

```<code>>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])
</code>```

and this will result in ['e', 'f']

I dont know that the if is doing.

答:
You're basically saying:

Remove the first element of the list (del(list[0])) while i divided by 2 is greater than zero (i/2)

Since it's not true in the first two cycles, you're left with the last two elements. Because 0/2 and 1/2 returns 0 since they're integers.

Title: Python- if statement evaluation pattern

Body:
what the heck is the if statement doing?

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])

and this will result in ['e', 'f']

I dont know that the if is doing.


问:
NodeJS Google Maps API Waiting
```<code>for(i =0; i < data.length; i++){
                console.log("i is " + i);
                 var test= data[i].payload.id;
                console.log(test);
              if(recentarray.indexOf(test)==-1){
                recentarray.push(test);
              each_device_recent_long.push(data[i].payload.long);
              each_device_recent_lat.push(data[i].payload.lat);
              each_device_recent_id.push(data[i].payload.id);
              var address;
              googleMapsClient.reverseGeocode({
                //address: '1600 Amphitheatre Parkway, Mountain View, CA'
                latlng: [ each_device_recent_lat[i], each_device_recent_long[i]]
              }, function(err, response) {
                if (!err) {
                  console.log("here are the results from google");
                  console.log(response.json.results[0].formatted_address);
                  address = response.json.results[0].formatted_address;
                  //res.render('sigfox-logs', { print_recent_array: print_recent_array});
                }
              });
                print_recent_array.push([data[i].payload.id,data[i].payload.long,data[i].payload.lat,address]);
              }
            }
            res.render('sigfox-logs', {title:'Item Locations',
                                      entries:data,
                                      sensorLong:recent_long,
                                      sensorLat: recent_lat,
                                      each_device_recent_long:  each_device_recent_long,
                                      each_device_recent_lat:   each_device_recent_lat,
                                      each_device_recent_id :each_device_recent_id,
                                    print_recent_array: print_recent_array  });
</code>```

I am trying to make an API call to google maps reverse geoencoding service. This is all working fine,  but it is taking a while to get the info back from google and the information rendered out to the HTML is "undefined" despite the fact that the placenames are showing in the console log, after the page has been rendered.

I know it has to do with callbacks and I have investigated the "request" library but it seems that the googleMapsClient object will be easier to deal with as the site grows.

Can someone help me find a way to make the res.render wait until the info has come back from the google API?
Thanks.

答:
to me it looks like your code isn't account for the asynchronous nonblocking nature of Node Js.

The approach needs to be

Figure out all the requests you need ot make

Make said requests

wait for them all to return

if the results don't include the request information you will need to reconcile against the request (this may be difficult)

format your response to the http response

using a promise for this: googleMapsClient.reverseGeocode will help immensely. Convert it to a promise (reverseGeocodePromise)

```<code>var localeTupleArray = zip(each_device_recent_lat, each_device_recent_long)
var promises = map(
    reverseGeocodePromise,
    localeTupleArray
)

all(promises).then(function(responses) {

})
</code>```

where converting to a

converting to a promise

map

zip

all

are left as an exercise for the programmer

Title: NodeJS Google Maps API Waiting

Body:
for(i =0; i < data.length; i++){
                console.log("i is " + i);
                 var test= data[i].payload.id;
                console.log(test);
              if(recentarray.indexOf(test)==-1){
                recentarray.push(test);
              each_device_recent_long.push(data[i].payload.long);
              each_device_recent_lat.push(data[i].payload.lat);
              each_device_recent_id.push(data[i].payload.id);
              var address;
              googleMapsClient.reverseGeocode({
                //address: '1600 Amphitheatre Parkway, Mountain View, CA'
                latlng: [ each_device_recent_lat[i], each_device_recent_long[i]]
              }, function(err, response) {
                if (!err) {
                  console.log("here are the results from google");
                  console.log(response.json.results[0].formatted_address);
                  address = response.json.results[0].formatted_address;
                  //res.render('sigfox-logs', { print_recent_array: print_recent_array});
                }
              });
                print_recent_array.push([data[i].payload.id,data[i].payload.long,data[i].payload.lat,address]);
              }
            }
            res.render('sigfox-logs', {title:'Item Locations',
                                      entries:data,
                                      sensorLong:recent_long,
                                      sensorLat: recent_lat,
                                      each_device_recent_long:  each_device_recent_long,
                                      each_device_recent_lat:   each_device_recent_lat,
                                      each_device_recent_id :each_device_recent_id,
                                    print_recent_array: print_recent_array  });

I am trying to make an API call to google maps reverse geoencoding service. This is all working fine,  but it is taking a while to get the info back from google and the information rendered out to the HTML is "undefined" despite the fact that the placenames are showing in the console log, after the page has been rendered.

I know it has to do with callbacks and I have investigated the "request" library but it seems that the googleMapsClient object will be easier to deal with as the site grows.

Can someone help me find a way to make the res.render wait until the info has come back from the google API?
Thanks.

Body:
to me it looks like your code isn't account for the asynchronous nonblocking nature of Node Js.

The approach needs to be

Figure out all the requests you need ot make

Make said requests

wait for them all to return

if the results don't include the request information you will need to reconcile against the request (this may be difficult)

format your response to the http response

using a promise for this: googleMapsClient.reverseGeocode will help immensely. Convert it to a promise (reverseGeocodePromise)

var localeTupleArray = zip(each_device_recent_lat, each_device_recent_long)
var promises = map(
    reverseGeocodePromise,
    localeTupleArray
)

all(promises).then(function(responses) {

})

where converting to a

converting to a promise

map

zip

all

are left as an exercise for the programmer


问:
How to create a custom DateTime in php?
Hi here I have a scenario that i have two strings in two variables,

```<code>$a = '2017-03-09';
$b = '16:00';
</code>```

these are like date part and time part of datetime in php
i want to join these part and create a datetime
and want to perform diff operation , for example i have created this datetime as a variable $custom_datetime

my output should be as

```<code>$interval = $custom_datetime->diff(date());
die($interval->format('%H:%I:%s'));
</code>```

this operation should give a proper time difference but i am unable to make this $custom_datetime

答:
This is an example of what you are trying to achieve :

```<code> $day_part = '2017-03-09';
 $hour_part = '16:00';
 $format = 'Y-m-d H:i';
 $datetime = DateTime::createFromFormat($format, $day_part.' '.$hour_part);
 echo "Format: $format; " . $datetime->format('Y-m-d H:i:s') . "\n";

 $interval = $datetime->diff(new DateTime());

 echo "<br>";
 echo "Interval :".$interval->format('%H:%I:%s');
</code>```

The documentation is right here;

Check this link to run the code;

Good Luck

Title: How to create a custom DateTime in php?

Body:
Hi here I have a scenario that i have two strings in two variables,

$a = '2017-03-09';
$b = '16:00';

these are like date part and time part of datetime in php
i want to join these part and create a datetime
and want to perform diff operation , for example i have created this datetime as a variable $custom_datetime

my output should be as

$interval = $custom_datetime->diff(date());
die($interval->format('%H:%I:%s'));

this operation should give a proper time difference but i am unable to make this $custom_datetime

Body:
This is an example of what you are trying to achieve :

 $day_part = '2017-03-09';
 $hour_part = '16:00';
 $format = 'Y-m-d H:i';
 $datetime = DateTime::createFromFormat($format, $day_part.' '.$hour_part);
 echo "Format: $format; " . $datetime->format('Y-m-d H:i:s') . "\n";

 $interval = $datetime->diff(new DateTime());

 echo "<br>";
 echo "Interval :".$interval->format('%H:%I:%s');

The documentation is right here;

Check this link to run the code;

Good Luck


问:
Linq to objects List in list
I have a list of movies

```<code>List<Movie> MovieList
</code>```

and I have a list of selected categories

```<code>List<string> SelCat
</code>```

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?

答:
```<code>   var SelectedCategories = List<string>();//list of selected categories

from movie in MovieList
join selCat in Categories.Where(SelectedCategories.Contains(selCat.Category)
on movie.category equals selCat.category
select movie
</code>```

Title: Linq to objects List in list

Body:
I have a list of movies

List<Movie> MovieList

and I have a list of selected categories

List<string> SelCat

And say I want to select from the movie list where it matches 2 categories, like the SQL statement below:

SELECT * FROM MovieList WHERE MovieList.Category = 'Action' AND MovieList.Category = 'Drama'

I can get kinda close with linq like so:

var q = (from b in MovieList where b.Categories.Any(p=> SelCat.Contains(p)) select b);

But it acts like an OR query, not an AND. I want it to select all movies that have a category of action and drama.

BTW: Movie.Categories is a List of string. AND Movie.Categories must contain items in the SelCat.

How do I achieve this with Linq to Objects?


Title: R extract text with regex and save to vectors. For loop across multiple directories

Body:
I have a list of files (result.file.names)

str(files)
chr [1:100] "bootstrap1/results_outfile1.txt" "bootstrap1/results_outfile2.txt" "bootstrap1/results_outfile3.txt" ...

files contain this type of text:

    {u'likelihood': -40563.03277, u'ml_tree': u'(cretaceaPI631721:0.01986343369712553764,((marinaPI516711:0.00342486721337833871,marinaPI419391:0.00439557045406125009):0.02057525413645854007,(prostrataPI577445:0.01814072969763430923,((rhodopeaW619154:0.01102506287325524803,rhodopeaSA43026:0.00988925069197059761):0.00474817094454488275,sativaglomerataPI577567:0.01961388465250675159):0.00161938724432756135):0.00384093064837489435):0.00445211181667617192,truncatulaW64996:0.03326867403662570749):0.0;', u'partitions': {u'1': {u'alpha': 0.02, u'rates': [0.669133, 3.027675, 0.703665, 0.839487, 3.419337, 1.0], u'name': u'gene6', u'frequencies': [0.292, 0.157, 0.175, 0.376]}, u'0': {u'alpha': 0.02, u'rates': [1.339908, 4.287687, 0.779025, 0.969835, 3.515225, 1.0], u'name': u'gene2', u'frequencies': [0.303, 0.164, 0.196, 0.337]}, u'3': {u'alpha': 0.02, u'rates': [0.546239, 2.327466, 0.694809, 0.626631, 2.03728, 1.0], u'name': u'gene20B', u'frequencies': [0.294, 0.165, 0.186, 0.356]}, u'2': {u'alpha': 0.02, u'rates': [0.791557, 4.292835, 0.810393, 1.104181, 2.854274, 1.0], u'name': u'gene20A', u'frequencies': [0.299, 0.171, 0.173, 0.356]}, u'5': {u'alpha': 0.02, u'rates': [0.801513, 2.664222, 0.685992, 1.465601, 3.70961, 1.0], u'name': u'gene35', u'frequencies': [0.294, 0.155, 0.189, 0.362]}, u'4': {u'alpha': 0.02, u'rates': [0.666665, 3.932293, 1.012807, 0.631296, 2.635027, 1.0], u'name': u'gene28', u'frequencies': [0.298, 0.173, 0.181, 0.348]}, u'7': {u'alpha': 0.02, u'rates': [0.834878, 3.467245, 0.990482, 1.038981, 4.405174, 1.0], u'name': u'gene44', u'frequencies': [0.284, 0.152, 0.183, 0.381]}, u'6': {u'alpha': 0.02, u'rates': [0.79724, 3.092797, 0.663377, 0.987096, 2.309744, 1.0], u'name': u'gene41', u'frequencies': [0.296, 0.166, 0.178, 0.361]}, u'9': {u'alpha': 0.02, u'rates': [0.988022, 2.859719, 0.731658, 0.978527, 3.139754, 1.0], u'name': u'gene60', u'frequencies': [0.285, 0.16, 0.182, 0.374]}, u'8': {u'alpha': 0.02, u'rates': [0.940118, 1.667166, 0.581149, 0.308618, 1.912549, 1.0], u'name': u'gene49', u'frequencies': [0.291, 0.163, 0.182, 0.365]}}}
{u'likelihood': -4216.778335, u'ml_tree': u'((cretaceaPI631721:0.02585480855056009053,(marinaPI516711:0.00302287739988804476,marinaPI419391:0.00492764788913652510):0.01886326220937559889):0.00569811409029884631,(sativaglomerataPI577567:0.02386936810593148425,((rhodopeaW619154:0.01021163111000199936,rhodopeaSA43026:0.00951101466387962655):0.01010166362035459613,prostrataPI577445:0.02085983976718608704):0.00193049473998346973):0.00244017359086532359,truncatulaW64996:0.03071445596771318898):0.0;', u'partitions': {u'0': {u'alpha': 0.02, u'rates': [1.028417, 4.306698, 1.161761, 1.016902, 3.754074, 1.0], u'name': u'gene54', u'frequencies': [0.287, 0.168, 0.193, 0.352]}}}

I would like to extract text (the number after {u'likelihood':) from them and save each hit from each file in a different vector.
I tried this with a for loop

wd <- getwd()
dirs <- dir(wd, pattern="bootstrap[[:alnum:]]*$")

for (d in dirs){
  files <- file.path(d, paste0("results_outfile",1:11, ".txt"))
  for (f in files){
    lines <- readLines(f)
    likelihoods <- regmatches(lines, gregexpr("'likelihood':\\s*\\K[^,]+", text, perl=TRUE))
    results <- paste("results",f,sep="")
    assign(results, likelihoods)
}
}

but I get a error

Error in as.character(text) :    cannot coerce type 'closure' to
  vector of type 'character'

I am not also entirely sure that my for loop is correct

Body:
You may use the following PCRE regex based approach to extract the values between 'likelihood': and a comma:

lines <- readLines(textConnection("{u'likelihood': -40563.03277, u'ml_tree': u'(cretaceaPI631721:0.01986343369712553764,((marinaPI516711:0.00342486721337833871,marinaPI419391:0.00439557045406125009):0.02057525413645854007,(prostrataPI577445:0.01814072969763430923,((rhodopeaW619154:0.01102506287325524803,rhodopeaSA43026:0.00988925069197059761):0.00474817094454488275,sativaglomerataPI577567:0.01961388465250675159):0.00161938724432756135):0.00384093064837489435):0.00445211181667617192,truncatulaW64996:0.03326867403662570749):0.0;', u'partitions': {u'1': {u'alpha': 0.02, u'rates': [0.669133, 3.027675, 0.703665, 0.839487, 3.419337, 1.0], u'name': u'gene6', u'frequencies': [0.292, 0.157, 0.175, 0.376]}, u'0': {u'alpha': 0.02, u'rates': [1.339908, 4.287687, 0.779025, 0.969835, 3.515225, 1.0], u'name': u'gene2', u'frequencies': [0.303, 0.164, 0.196, 0.337]}, u'3': {u'alpha': 0.02, u'rates': [0.546239, 2.327466, 0.694809, 0.626631, 2.03728, 1.0], u'name': u'gene20B', u'frequencies': [0.294, 0.165, 0.186, 0.356]}, u'2': {u'alpha': 0.02, u'rates': [0.791557, 4.292835, 0.810393, 1.104181, 2.854274, 1.0], u'name': u'gene20A', u'frequencies': [0.299, 0.171, 0.173, 0.356]}, u'5': {u'alpha': 0.02, u'rates': [0.801513, 2.664222, 0.685992, 1.465601, 3.70961, 1.0], u'name': u'gene35', u'frequencies': [0.294, 0.155, 0.189, 0.362]}, u'4': {u'alpha': 0.02, u'rates': [0.666665, 3.932293, 1.012807, 0.631296, 2.635027, 1.0], u'name': u'gene28', u'frequencies': [0.298, 0.173, 0.181, 0.348]}, u'7': {u'alpha': 0.02, u'rates': [0.834878, 3.467245, 0.990482, 1.038981, 4.405174, 1.0], u'name': u'gene44', u'frequencies': [0.284, 0.152, 0.183, 0.381]}, u'6': {u'alpha': 0.02, u'rates': [0.79724, 3.092797, 0.663377, 0.987096, 2.309744, 1.0], u'name': u'gene41', u'frequencies': [0.296, 0.166, 0.178, 0.361]}, u'9': {u'alpha': 0.02, u'rates': [0.988022, 2.859719, 0.731658, 0.978527, 3.139754, 1.0], u'name': u'gene60', u'frequencies': [0.285, 0.16, 0.182, 0.374]}, u'8': {u'alpha': 0.02, u'rates': [0.940118, 1.667166, 0.581149, 0.308618, 1.912549, 1.0], u'name': u'gene49', u'frequencies': [0.291, 0.163, 0.182, 0.365]}}}
{u'likelihood': -4216.778335, u'ml_tree': u'((cretaceaPI631721:0.02585480855056009053,(marinaPI516711:0.00302287739988804476,marinaPI419391:0.00492764788913652510):0.01886326220937559889):0.00569811409029884631,(sativaglomerataPI577567:0.02386936810593148425,((rhodopeaW619154:0.01021163111000199936,rhodopeaSA43026:0.00951101466387962655):0.01010166362035459613,prostrataPI577445:0.02085983976718608704):0.00193049473998346973):0.00244017359086532359,truncatulaW64996:0.03071445596771318898):0.0;', u'partitions': {u'0': {u'alpha': 0.02, u'rates': [1.028417, 4.306698, 1.161761, 1.016902, 3.754074, 1.0], u'name': u'gene54', u'frequencies': [0.287, 0.168, 0.193, 0.352]}}}"))
likelihoods <- regmatches(lines, gregexpr("'likelihood':\\s*\\K[^,]+", lines, perl=TRUE))
likelihoods
## => [[1]]
##    [1] "-40563.03277"
##
##    [[2]]
##    [1] "-4216.778335"

See the online R demo

Pattern details:

'likelihood': - match  a literal substring 'likelihood':

\\s* - 0 or more whitespaces

\\K - omit the text matched so far

[^,]+ - (this is what you will get in return) 1 or more chars other than ,


问:
do while loop ignores my bool flag variable c++
If userList[i].CheckUser(username, password) returns false then it enters the else condition and I get the output "User Does Not Exist! Try Again Enter username and password" that line then gets stuck in an infinite loop and I cant figure out why, I mean the program re-enters the do-while loop again so I don't see how the loop would carry over?</p>

```<code>int main()
{
    LoadUsersFromDatabase();
    bool flag;
    string username;
    int password;
do{
    cout << "Enter username and password: ";
    cin >> username >> password;
    for (int i = 0; i < numOfUsers; i++)
        if (userList[i].CheckUser(username, password) == true)
        {
            if (userList[i].GetUserType() == 'A')
            {
                ProcessAssistantMenu();
            }
            else if (userList[i].GetUserType() == 'M')
            {
                ProcessManagerMenu();
            }
        }
        else
                cout << "\rUser Does Not Exist! Try Again! ";
                flag = false;
  } while(flag == false);
return 0;
}
</code>```

答:
You are always setting your flag = false.

I'm guessing you want to do this:

```<code>else{
    cout << "\rUser Does Not Exist! Try Again! ";
    flag = false;
}
</code>```

And as Alex points out, you're not setting it true in the first place.

Body:
If userList[i].CheckUser(username, password) returns false then it enters the else condition and I get the output "User Does Not Exist! Try Again Enter username and password" that line then gets stuck in an infinite loop and I cant figure out why, I mean the program re-enters the do-while loop again so I don't see how the loop would carry over?

int main()
{
    LoadUsersFromDatabase();
    bool flag;
    string username;
    int password;
do{
    cout << "Enter username and password: ";
    cin >> username >> password;
    for (int i = 0; i < numOfUsers; i++)
        if (userList[i].CheckUser(username, password) == true)
        {
            if (userList[i].GetUserType() == 'A')
            {
                ProcessAssistantMenu();
            }
            else if (userList[i].GetUserType() == 'M')
            {
                ProcessManagerMenu();
            }
        }
        else
                cout << "\rUser Does Not Exist! Try Again! ";
                flag = false;
  } while(flag == false);
return 0;
}

Body:
You are always setting your flag = false.

I'm guessing you want to do this:

else{
    cout << "\rUser Does Not Exist! Try Again! ";
    flag = false;
}

And as Alex points out, you're not setting it true in the first place.


问:
How can I build a condition based query in Laravel?
I can do this in Code Igniter:

```<code>$this->db->select();
$this->from->('node');
if ($published == true)
{
    $this->db->where('published', 'true');
}
if (isset($year))
{
    $this->db->where('year >', $year);
}
$this->db->get();
</code>```

How can this code be translated so that it works in Laravel?

答:
for eloquent query i used following that executes only if where condition has value</p>

```<code>->where(function($query) use ($value_id)
                    {

                            if ( ! is_null($value_id))
                                $query->where('vehicle_details.transport_type_id', $value_id);

                    })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I can do this in Code Igniter:

$this->db->select();
$this->from->('node');
if ($published == true)
{
    $this->db->where('published', 'true');
}
if (isset($year))
{
    $this->db->where('year >', $year);
}
$this->db->get();

How can this code be translated so that it works in Laravel?

Body:
for eloquent query i used following that executes only if where condition has value

->where(function($query) use ($value_id)
                    {

                            if ( ! is_null($value_id))
                                $query->where('vehicle_details.transport_type_id', $value_id);

                    })


问:
Django Form Not Validating
I want to implement forgot password functionality. In my verification code function, form is not validating.
Here is my Views File:

```<code>def getVerCode(request):
    if (request.method == 'POST'):
        form = VerCodeForm(request.POST)
        print(form.errors)
        if (form.is_valid()):
            print('VALID')
            code = request.POST.get('verCode', '')
            print('GETVERCODE : ', verCode)
            if (code == verCode):
                pass
            return HttpResponseRedirect('/custom/GetPassword', {'form': form})
    else:
        form = VerCodeForm()
    return render_to_response('EmailVerification.html', {'form': form})
</code>```

Template:

```<code>{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css' %}" />

{% block body %}
    <div class = "formArea"> {% csrf_token %}
        <label> Enter the verification code sent to your email account: </label>
        {{ hidden_email }}
        <div class="formFields">
            <form method="POST">
                <input type="text" name = "email" size="50"> </input>
                {{ form.verCode.errors }}
                <input type="submit" value="Submit">
            </form>
        </div>
    </div>
{% endblock %}
</code>```

Form:

```<code>class VerCodeForm(forms.Form):
    verCode = forms.CharField(max_length = 10)
</code>```

I tried to print the form.errors:

It says
This Field is Required!

答:
You did not name your input on your template correctly. It should be:</p>

```<code><input type="email" size="50" name="verCode"> </input>
</code>```

Title: Django Form Not Validating

Body:
I want to implement forgot password functionality. In my verification code function, form is not validating.
Here is my Views File:

def getVerCode(request):
    if (request.method == 'POST'):
        form = VerCodeForm(request.POST)
        print(form.errors)
        if (form.is_valid()):
            print('VALID')
            code = request.POST.get('verCode', '')
            print('GETVERCODE : ', verCode)
            if (code == verCode):
                pass
            return HttpResponseRedirect('/custom/GetPassword', {'form': form})
    else:
        form = VerCodeForm()
    return render_to_response('EmailVerification.html', {'form': form})

Template:

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="{% static 'FormStyle.css' %}" />

{% block body %}

 {% csrf_token %}
         Enter the verification code sent to your email account:
        {{ hidden_email }}

            <form method="POST">
                <input type="text" name = "email" size="50"> </input>
                {{ form.verCode.errors }}
                <input type="submit" value="Submit">
            </form>

{% endblock %}

Form:

class VerCodeForm(forms.Form):
    verCode = forms.CharField(max_length = 10)

I tried to print the form.errors:

It says
This Field is Required!

Body:
You did not name your input on your template correctly. It should be:

<input type="email" size="50" name="verCode"> </input>


问:
C# Linq .Find() return many results
I am trying to create a simple search function for my application. I am using Linq's .Find() method to search through a list of objects. It all works very well, the only problem I'm currently having is that I only get the first result. I know for a fact that there are more than one results to be had, but I only get one. Here is my code:

```<code>case 5: {
    //Search for Price

    Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);
    if (searchResult != null) {
        //Present Result
        searchTable.Rows.Add(convertIDValue(searchResult.getProductID()), searchResult.getTitle(), searchResult.getYear(), searchResult.getAmount(), searchResult.getPrice());
    }
    else {
        MessageBox.Show("No product with that price", "0 results");
    }

    break;
}
</code>```

I thought I could change Product searchResult into List<Product> searchResults in order to get a list of Products, then loop through that list. But that gave me an error saying:

Cannot implicitly convert type '.Product' to 'System.Collections.Generic.List<.Product>

Is there any way to get Linq's .Find() to return multiple results?

答:
Microsoft explains the "Find()" method :"Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List."

I would suggest you to use this Where() method from Linq extension.

Don't forget to import "using System.Linq" in your current class.

Title: C# Linq .Find() return many results

Body:
I am trying to create a simple search function for my application. I am using Linq's .Find() method to search through a list of objects. It all works very well, the only problem I'm currently having is that I only get the first result. I know for a fact that there are more than one results to be had, but I only get one. Here is my code:

case 5: {
    //Search for Price

    Product searchResult = tempList.Find(x => x.getPrice() == searchPrice);
    if (searchResult != null) {
        //Present Result
        searchTable.Rows.Add(convertIDValue(searchResult.getProductID()), searchResult.getTitle(), searchResult.getYear(), searchResult.getAmount(), searchResult.getPrice());
    }
    else {
        MessageBox.Show("No product with that price", "0 results");
    }

    break;
}

I thought I could change Product searchResult into List<Product> searchResults in order to get a list of Products, then loop through that list. But that gave me an error saying:

Cannot implicitly convert type '.Product' to 'System.Collections.Generic.List<.Product>

Is there any way to get Linq's .Find() to return multiple results?


问:
Subprocess not retaining all environment variables
I have a tcsh shell script that sets up all the necessary environment including PYTHONPATH, which then run an executable at the end of it. I also have a python script that gets sent to the shell script as an input. So the following works perfectly fine when it is ran from Terminal:

path to shell script path to python script

Now, the problem occurs when I want to do the same thing from a subprocess. The python script fails to be ran since it cannot find many of the modules that's already supposed to be set via the shell script. And clearly, the PYTHONPATH ends up having many missing paths compared to the parent environment the subprocess was ran from or the shell script itself! It seems like the subprocess does not respect the environment the shell script sets up.

I've tried all sorts of things already but none help!

cmd = [shell_script_path, py_script_path]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=os.environ.copy())

It makes no difference if env is not given either!

Any idea how to fix this?!

答:
Knowing the subprocess inherits all the parent process environment and they are supposed to be ran under same environment, making the shell script to not setup any environment, fixed it.

This solves the environment being retained, but now the problem is, the process just hangs! (it does not happen when it is ran directly from shell)


问:
why is ng-model not checking default radio button?
Below is the fiddle i am working:

http://jsfiddle.net/3c0dxf4d/

The ng-model has an object and the ng-value maps to object, why is my default value {"id":1,"name":"Bill"}
 not getting selected by default.

答:
Because you've put the initial value to
$scope.currentCustomer = {
        "id": 1,
        "name": "Bill"
    };

Just remove or change it.
Please check following code please.

app.controller("ctrl", function ($scope) {
    $scope.customers = [{
        "id": 1,
        "name": "Bill"
    }, {
        "id": 2,
        "name": "Bob"
    }, {
        "id": 3,
        "name": "Biff"
    }];
    $scope.customer = {};

```<code>*$scope.currentCustomer = {
    "id": 1,
    "name": "Bill"
};*
</code>```

})

Body:
Because you've put the initial value to
$scope.currentCustomer = {
        "id": 1,
        "name": "Bill"
    };

Just remove or change it.
Please check following code please.

app.controller("ctrl", function ($scope) {
    $scope.customers = [{
        "id": 1,
        "name": "Bill"
    }, {
        "id": 2,
        "name": "Bob"
    }, {
        "id": 3,
        "name": "Biff"
    }];
    $scope.customer = {};

*$scope.currentCustomer = {
    "id": 1,
    "name": "Bill"
};*

})


问:
Remove Installed Directory after uninstallation of Windows Application
I have created setup file(msi) for my windows application using install shield. The problem is when i uninstall the application from control panel,except 2 files remaining files got removed from installed directory. But i want to have the whole installed directory to be removed. Any help is appreciated.</p>

答:
Please check, whether the component is shared, if it is shared for no reason.

Please set the shared to No.

Still it is not deleted, create a custom action to delete the files.

For more details refer below

https://msdn.microsoft.com/en-us/library/windows/desktop/aa371199(v=vs.85).aspx


问:
Changing occurrences of one pattern to another
grep -R \"\/web *
gives me some occurrences which i want to change to
\"\$\/web

How can I do this?

答:
In vim:</p>

```<code>:set hidden
:args *
:argdo %s/"web/"$web/g
:wqa
</code>```

Body:
In vim:

:set hidden
:args *
:argdo %s/"web/"$web/g
:wqa


问:
Using jQuery "click" function on an element echoed by php
I'm making a forum and I want the user panel to change whenever a user is logged in. So by default it says "Sign in or register." But when a user is logged in it says their name and an option to log out.

The idea is that when they click sign out jQuery will ask for a confirm and if its true they will be redirected to ?logout=true where php handles the rest.

The problem is that jQuery just won't work on the element echoed by php.

Here is the PHP:

```<code><div id="userbar">
    <span id="userPanel">User Panel</span>
    <?php
        if (isset($_SESSION['signedIn'])) {
            echo '
                <a href="#" class="logout">Sign Out</a>
                <span id="welcome">
                    Hello, <b><a href="#" class="sessName">' . $_SESSION["username"] . '
                </b></a></span>
            ';
        } else {
            echo '
                <a href="signin.php" class="signIn">Sign In</a>
                <a href="signup.php" class="register">Register</a>
            ';
        }
    ?>
</div>
</code>```

And here is the jQuery:

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>

<script type="text/javascript">

    $(".logout").click(function(){
        var exit = confirm("Are you sure you would like to sing out?");

        if (exit == true) {
            window.location("header.php?logout=true");
        }

        return false;
    });

</script>
</code>```

答:
First, you need to update your jquery is too old.

this the final function i create, you can try it.

       function alertLogOut(){
            var exit = confirm("Are you sure you would like to sing out?");
            if (exit == true) {
                window.location.href="header.php?logout=true";
            }
            return false;
        };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
Sign Out</code>```

Body:
I'm making a forum and I want the user panel to change whenever a user is logged in. So by default it says "Sign in or register." But when a user is logged in it says their name and an option to log out.

The idea is that when they click sign out jQuery will ask for a confirm and if its true they will be redirected to ?logout=true where php handles the rest.

The problem is that jQuery just won't work on the element echoed by php.

Here is the PHP:

    User Panel
    <?php
        if (isset($_SESSION['signedIn'])) {
            echo '
                Sign Out

                    Hello, ' . $_SESSION["username"] . '

            ';
        } else {
            echo '
                Sign In
                Register
            ';
        }
    ?>

And here is the jQuery:

Body:
First, you need to update your jquery is too old.

this the final function i create, you can try it.

       function alertLogOut(){
            var exit = confirm("Are you sure you would like to sing out?");
            if (exit == true) {
                window.location.href="header.php?logout=true";
            }
            return false;
        };

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<a href="#" class="logout" onclick="alertLogOut();">Sign Out</a>


答:
```<code>Product searchResult =
</code>```

means you are declaring one element. The thing you need is a collection of products, like:

```<code>IEnumerable<product> searchResult  =
</code>```

The easiest way to do it is to  change Find() to where():

```<code>IEnumerable<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice);
</code>```

this will create some collection of product's. It will be easier to maintain as a list, so:

```<code>list<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).toList();
</code>```

Read about IEnumerable interface :)

Title: C# Linq .Find() return many results

Body:
Product searchResult =

means you are declaring one element. The thing you need is a collection of products, like:

IEnumerable<product> searchResult  =

The easiest way to do it is to  change Find() to where():

IEnumerable<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice);

this will create some collection of product's. It will be easier to maintain as a list, so:

list<product> searchResult = tempList.Where(x => x.getPrice() == searchPrice).toList();

Read about IEnumerable interface :)


问:
How to annotate a read-only array?
In flowtype, an object can be made immutable by making it sealed and denoting properties to be covariant.

How to annotate a flowtype parameter that cannot be manipulated?

答:
Use $ReadOnlyArray<T>, e.g.

```<code>(values: $ReadOnlyArray<ValueType>) => {}
</code>```

For more information, refer to the discussion in https://github.com/facebook/flow/issues/3502#issuecomment-286259843.

Title: How to annotate a read-only array?

Body:
Use $ReadOnlyArray<T>, e.g.

(values: $ReadOnlyArray<ValueType>) => {}

For more information, refer to the discussion in https://github.com/facebook/flow/issues/3502#issuecomment-286259843.


问:
unable to set result from ajax success to div html in mvc
I have the below code, I'm calling an action and getting a partialviewresult in ajax success.

But I'm unable to set the html to the div-Graph, but I'm getting undefined in alert; alert( $('#div-Graph').html()); The entire html is disappearing...

Any idea on this?

$(document).ready(function () {
        $('#ChartTypes').change(function () {

```<code>        var selectedID = $(this).val();
        $.ajax({
            url: '/charts/GetChart/4',
            type: 'GET',
            success: function (result) {
                debugger    ;
                $('#div-Graph').html(result.toString());
                alert( $('#div-Graph').html());
            }
        });

    });
});
</code>```

Kindly let me know if you need any more code parts. Tried a lot for a solution :(

Thanks
Ragesh

答:
You can directly append it to the class/id like this.  You can't display the whole div inside the alert box.</p>

```<code>  success: function (result) {
       alert(result);
       var res = JSON.stringify(result);
      $('#div-Graph').append(res);
  }
</code>```

Body:
I have the below code, I'm calling an action and getting a partialviewresult in ajax success.

But I'm unable to set the html to the div-Graph, but I'm getting undefined in alert; alert( $('#div-Graph').html()); The entire html is disappearing...

Any idea on this?

$(document).ready(function () {
        $('#ChartTypes').change(function () {

        var selectedID = $(this).val();
        $.ajax({
            url: '/charts/GetChart/4',
            type: 'GET',
            success: function (result) {
                debugger    ;
                $('#div-Graph').html(result.toString());
                alert( $('#div-Graph').html());
            }
        });

    });
});

Kindly let me know if you need any more code parts. Tried a lot for a solution :(

Thanks
Ragesh

Body:
You can directly append it to the class/id like this.  You can't display the whole div inside the alert box.

  success: function (result) {
       alert(result);
       var res = JSON.stringify(result);
      $('#div-Graph').append(res);
  }


问:
WKWebView custom long press menu works but with some major issues
When the user long presses a link an alert controller appears with the options:

Open

Open in New Tab

Copy

There are two problems currently:

If the user performs a long press before the WKWebView has finished the navigation the default (Safari's) alert controller appears.

If the user lifts his finger after the popup animation occurs somehow the WKWebView registers it as a tap and navigates to that link while the alert controller is still displayed on screen.

There are three parts to this mechanism.

Firstly,

After the WKWebView has finished the navigation a javascript is injected to the page that disables the default alert controller.

```<code>- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [_webView evaluateJavaScript:@"document.body.style.webkitTouchCallout='none';"
               completionHandler:^(id result, NSError *error){

                   NSLog(@"Javascript: {%@, %@}", result, error.description);
               }];
}
</code>```

Secondly,

A UILongPressGestureRecognizer is added to the WKWebView and implemented so that it finds the attributes of the elements based on the location of the touch.

```<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)longPress:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {

        _shouldCancelNavigation = YES;

        CGPoint touchLocation = [longPressGestureRecognizer locationInView:_webView];

        NSString *javascript = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Javascript" ofType:@"js"]
                                                         encoding:NSUTF8StringEncoding
                                                            error:nil];

        [_webView evaluateJavaScript:javascript
                   completionHandler:^(id result, NSError *error){

                       NSLog(@"Javascript: {%@, %@}", result, error.description);
                   }];

        [_webView evaluateJavaScript:[NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%f,%f);", touchLocation.x, touchLocation.y]
                   completionHandler:^(id result, NSError *error){

                       NSLog(@"Javascript: {%@, %@}", result, error.description);

                       NSString *tags = (NSString *)result;

                       if ([tags containsString:@",A,"]) {

                           [_webView evaluateJavaScript:[NSString stringWithFormat:@"MyAppGetHREFAttributeAtPoint(%f,%f);", touchLocation.x, touchLocation.y]
                                      completionHandler:^(id result, NSError *error){

                                          NSLog(@"Javascript: {%@, %@}", result, error.description);

                                          NSString *urlString = (NSString *)result;

                                          [_delegate webView:self didLongPressAtTouchLocation:touchLocation URL:[NSURL URLWithString:urlString]];
                                      }];

                           return;
                       }

                       if ([tags containsString:@",IMG,"]) {

                           [_webView evaluateJavaScript:[NSString stringWithFormat:@"MyAppGetSRCAttributeAtPoint(%f,%f);", touchLocation.x, touchLocation.y]
                                      completionHandler:^(id result, NSError *error){

                                          NSLog(@"Javascript: {%@, %@}", result, error.description);

                                          NSString *urlString = (NSString *)result;

                                          [_delegate webView:self didLongPressAtTouchLocation:touchLocation imageWithSourceURL:[NSURL URLWithString:urlString]];
                                      }];

                           return;
                       }
                   }];
    }
}
</code>```

Lastly,

The delegate method that presents the alert controller is implemented on the main ViewController.

My solution to the second problem has been to add a boolean value shouldCancelNavigation that is YES when the alert controller has been presented and NO when it has been dismissed.

```<code>- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if (_shouldCancelNavigation) {

        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else {

        decisionHandler(WKNavigationActionPolicyAllow);
    }
}
</code>```

Interestingly enough there are many examples on the web where links DO NOT require a policy decision. They just happen with no way for me to stop them.

Example: http://www.dribbble.com

Source: http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/comment-page-3/

Source 2: https://github.com/mozilla-mobile/firefox-ios/pull/61

EDIT:

This solves the 2nd problem but I'm not sure it won't break something somewhere else.

```<code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if ([otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {

        otherGestureRecognizer.enabled = NO;

        otherGestureRecognizer.enabled = YES;
    }

    return YES;
}
</code>```

EDIT 2:

It does actually create a problem... You can no longer select text since the code above resets the internal long press gesture recognizers.

EDIT 3:

If I remove my implementation completely (all 3 steps) and let the default alert controller kick in every time I long press a link the 2nd problem gets solved.

There's something about Apple's alert controller that prevents the WKWebView from navigating after you lift your finger.

答:
If I am not wrong, In the second part :

```<code>- (void)longPress:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {

//Rest of your code ...
    }
}
</code>```

You are injecting javascript to disable system dialog. Now after press ends, WKWebview already recieved event triggered from the web link. Since it is too late, why don't you try to check condition for longPressGestureRecognizer.state is equal to  UIGestureRecognizerStateEnded instead.

Hence it changes to below code.

```<code>    if (longPressGestureRecognizer.state == UIGestureRecognizerStateEnded) {

       //Rest of your code ...
    }
</code>```

I have not tested this code yet. Would be happier if it works.

Body:
When the user long presses a link an alert controller appears with the options:

Open

Open in New Tab

Copy

There are two problems currently:

If the user performs a long press before the WKWebView has finished the navigation the default (Safari's) alert controller appears.

If the user lifts his finger after the popup animation occurs somehow the WKWebView registers it as a tap and navigates to that link while the alert controller is still displayed on screen.

There are three parts to this mechanism.

Firstly,

After the WKWebView has finished the navigation a javascript is injected to the page that disables the default alert controller.

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [_webView evaluateJavaScript:@"document.body.style.webkitTouchCallout='none';"
               completionHandler:^(id result, NSError *error){

                   NSLog(@"Javascript: {%@, %@}", result, error.description);
               }];
}

Secondly,

A UILongPressGestureRecognizer is added to the WKWebView and implemented so that it finds the attributes of the elements based on the location of the touch.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)longPress:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {

        _shouldCancelNavigation = YES;

        CGPoint touchLocation = [longPressGestureRecognizer locationInView:_webView];

        NSString *javascript = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Javascript" ofType:@"js"]
                                                         encoding:NSUTF8StringEncoding
                                                            error:nil];

        [_webView evaluateJavaScript:javascript
                   completionHandler:^(id result, NSError *error){

                       NSLog(@"Javascript: {%@, %@}", result, error.description);
                   }];

        [_webView evaluateJavaScript:[NSString stringWithFormat:@"MyAppGetHTMLElementsAtPoint(%f,%f);", touchLocation.x, touchLocation.y]
                   completionHandler:^(id result, NSError *error){

                       NSLog(@"Javascript: {%@, %@}", result, error.description);

                       NSString *tags = (NSString *)result;

                       if ([tags containsString:@",A,"]) {

                           [_webView evaluateJavaScript:[NSString stringWithFormat:@"MyAppGetHREFAttributeAtPoint(%f,%f);", touchLocation.x, touchLocation.y]
                                      completionHandler:^(id result, NSError *error){

                                          NSLog(@"Javascript: {%@, %@}", result, error.description);

                                          NSString *urlString = (NSString *)result;

                                          [_delegate webView:self didLongPressAtTouchLocation:touchLocation URL:[NSURL URLWithString:urlString]];
                                      }];

                           return;
                       }

                       if ([tags containsString:@",IMG,"]) {

                           [_webView evaluateJavaScript:[NSString stringWithFormat:@"MyAppGetSRCAttributeAtPoint(%f,%f);", touchLocation.x, touchLocation.y]
                                      completionHandler:^(id result, NSError *error){

                                          NSLog(@"Javascript: {%@, %@}", result, error.description);

                                          NSString *urlString = (NSString *)result;

                                          [_delegate webView:self didLongPressAtTouchLocation:touchLocation imageWithSourceURL:[NSURL URLWithString:urlString]];
                                      }];

                           return;
                       }
                   }];
    }
}

Lastly,

The delegate method that presents the alert controller is implemented on the main ViewController.

My solution to the second problem has been to add a boolean value shouldCancelNavigation that is YES when the alert controller has been presented and NO when it has been dismissed.

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    if (_shouldCancelNavigation) {

        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else {

        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

Interestingly enough there are many examples on the web where links DO NOT require a policy decision. They just happen with no way for me to stop them.

Example: http://www.dribbble.com

Source: http://www.icab.de/blog/2010/07/11/customize-the-contextual-menu-of-uiwebview/comment-page-3/

Source 2: https://github.com/mozilla-mobile/firefox-ios/pull/61

EDIT:

This solves the 2nd problem but I'm not sure it won't break something somewhere else.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if ([otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {

        otherGestureRecognizer.enabled = NO;

        otherGestureRecognizer.enabled = YES;
    }

    return YES;
}

EDIT 2:

It does actually create a problem... You can no longer select text since the code above resets the internal long press gesture recognizers.

EDIT 3:

If I remove my implementation completely (all 3 steps) and let the default alert controller kick in every time I long press a link the 2nd problem gets solved.

There's something about Apple's alert controller that prevents the WKWebView from navigating after you lift your finger.

Body:
If I am not wrong, In the second part :

- (void)longPress:(UILongPressGestureRecognizer *)longPressGestureRecognizer
{
    if (longPressGestureRecognizer.state == UIGestureRecognizerStateBegan) {

//Rest of your code ...
    }
}

You are injecting javascript to disable system dialog. Now after press ends, WKWebview already recieved event triggered from the web link. Since it is too late, why don't you try to check condition for longPressGestureRecognizer.state is equal to  UIGestureRecognizerStateEnded instead.

Hence it changes to below code.

    if (longPressGestureRecognizer.state == UIGestureRecognizerStateEnded) {

       //Rest of your code ...
    }

I have not tested this code yet. Would be happier if it works.


答: If 'i' is equals to, or bigger than 2, it deletes the first element of the list. 0 is equivalent to false, and 1 or more, is equivalent to true.</p>

Title: Python- if statement evaluation pattern

Body:
what the heck is the if statement doing?

>>> list = ['a', 'b', 'c', 'd', 'e', 'f']
>>> for i in xrange(len(list)):
...   if i / 2:
...     del(list[0])

and this will result in ['e', 'f']

I dont know that the if is doing.


问:
"Servers" view missing from Eclipse Indigo
I'm trying to configure Tomcat with Eclipse Indigo, but the "Servers" view is missing. That being said, I had to follow this tutorial on how to configure Tomcat with Eclipse Indigo using plugins. The plugins work, but I would like to find out why the "Servers" view is missing in the first place.

Eclipse specs:

```<code>Version: 3.7.1.r37x_v20110729-9gF7UHOxFtniV7mI3T556iZN9AU8bEZ1lHMcVK
Build id: M20110909-1335
</code>```

Tomcat specs:

```<code>Server version: Apache Tomcat/7.0.22
Server built: Sep 27 2011 09:40:50
Server number: 7.0.22.0
OS Name: Windows XP
OS Version: 5.1
Architecture: x86
JVM Version: 1.6.0_20-b02
</code>```

OS specs:

```<code>Microsoft Windows XP
Professional
Version 2002
Service Pack 3
</code>```

And if it matters, this is the tutorial I was originally following.

答:
If you use Eclipse Neon please follow this steps.

Help -> Install New Software

Choose "Neon - http://download.eclipse.org/releases/neon" site

Expand "Web, XML, and Java EE and OSGi Enterprise Development"

Select JST Server Adapters and JST Server Adapters Extentions

Restart Eclipse.

Body:
I'm trying to configure Tomcat with Eclipse Indigo, but the "Servers" view is missing. That being said, I had to follow this tutorial on how to configure Tomcat with Eclipse Indigo using plugins. The plugins work, but I would like to find out why the "Servers" view is missing in the first place.

Eclipse specs:

Version: 3.7.1.r37x_v20110729-9gF7UHOxFtniV7mI3T556iZN9AU8bEZ1lHMcVK
Build id: M20110909-1335

Tomcat specs:

Server version: Apache Tomcat/7.0.22
Server built: Sep 27 2011 09:40:50
Server number: 7.0.22.0
OS Name: Windows XP
OS Version: 5.1
Architecture: x86
JVM Version: 1.6.0_20-b02

OS specs:

Microsoft Windows XP
Professional
Version 2002
Service Pack 3

And if it matters, this is the tutorial I was originally following.


问:
Add filter for every query over certain entity in EF
I would like to add a filter to every query fired on my User entity to filter on IsSystemUser == false.

I had see examples using IDbCommandTreeInterceptor and IDbCommandInterceptor, and there is also a chance to override method Executing(DbCommand command, IEnumerable<DbContext> interceptionContext) on the DbContext child class, but it's unclear to me how to achieve this.

What is the easier approach to add a filter to every query fired over Users entity to filter data based on my IsSystemUser property?

答:
Disclaimer: I'm the owner of the project Entity Framework Plus

EF+ Query Filter allow you to add a filter to every queries.

```<code>// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

ctx.Filter<IUser>(q => q.Where(x => !x.IsSystemUser ));

// SELECT * FROM Customers WHERE IsSystemUser = FALSE
var list = ctx.Customers.ToList();
</code>```

Wiki: EF+ Query Filter

Body:
Disclaimer: I'm the owner of the project Entity Framework Plus

EF+ Query Filter allow you to add a filter to every queries.

// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

ctx.Filter<IUser>(q => q.Where(x => !x.IsSystemUser ));

// SELECT * FROM Customers WHERE IsSystemUser = FALSE
var list = ctx.Customers.ToList();

Wiki: EF+ Query Filter


问:
Project Euler with C++ - compiler won't process after 100 x 101
I've started working with C++ and was fiddling around with some problems on projecteuler.net.

I'm on question #4 and here's my code:

algorithm to check whether the number is a palindrome:

```<code>bool forwardCheck(long posPal){
long n = posPal;
long rev = 0;
long dig;

    while (posPal > 0){
        dig = posPal % 10;
        rev = rev * 10 + dig;
        posPal = posPal % 10;
    }

    return n == rev;
}
</code>```

main program:

```<code>int main(){
long palindrome;

cout << "We are finding the largest palindrome made from two 3-digit numbers.\n"
     << "Calculating...\nCalculating...\nDone!\n";

for (long i = 100; i < 1000; i++){
    for (long j = 100; j < 1000; j++){
        long mult = i * j;
            if (forwardCheck(mult)){
                palindrome = mult;
                //testing function above
                cout << mult << " is a palindrome!\n";
            } else
                //testing function above
                cout << mult << " is not a palindrome...\n";
    }
}

cout << "The largest palindrome composed of two 3 digit numbers is: " << palindrome
     << endl;

return 0;
}
</code>```

I'm using X11 on OS X as my compiler with g++ and my problem is that, using the code above, the numbers get to 101,000 as the multiple and then stops and stalls after that.  My question is:

Why is it doing this?  Am I approaching this inefficiently?

I realize that an alternative is to start from long = 999 and iterate downwards but I've coded but it gets stuck after the "Done!" statement (yes, I know it's a bit ambitious to program that in before the algorithm has run but I like to be optimistic. :)

By stuck and stalls, I mean that the CPU usage spikes but nothing is written to the console.

As a general side note:

Is there a way I can debug through the console, i.e. have it tell me what it's doing similar to echo in windows command prompt?  I'm new to OS X too...

答:
seems that it should be
posPal = posPal / 10

e.g. starting with 123 you want to use 3 for building an inverse number and to move to 12

Body:
I've started working with C++ and was fiddling around with some problems on projecteuler.net.

I'm on question #4 and here's my code:

algorithm to check whether the number is a palindrome:

bool forwardCheck(long posPal){
long n = posPal;
long rev = 0;
long dig;

    while (posPal > 0){
        dig = posPal % 10;
        rev = rev * 10 + dig;
        posPal = posPal % 10;
    }

    return n == rev;
}

main program:

int main(){
long palindrome;

cout << "We are finding the largest palindrome made from two 3-digit numbers.\n"
     << "Calculating...\nCalculating...\nDone!\n";

for (long i = 100; i < 1000; i++){
    for (long j = 100; j < 1000; j++){
        long mult = i * j;
            if (forwardCheck(mult)){
                palindrome = mult;
                //testing function above
                cout << mult << " is a palindrome!\n";
            } else
                //testing function above
                cout << mult << " is not a palindrome...\n";
    }
}

cout << "The largest palindrome composed of two 3 digit numbers is: " << palindrome
     << endl;

return 0;
}

I'm using X11 on OS X as my compiler with g++ and my problem is that, using the code above, the numbers get to 101,000 as the multiple and then stops and stalls after that.  My question is:

Why is it doing this?  Am I approaching this inefficiently?

I realize that an alternative is to start from long = 999 and iterate downwards but I've coded but it gets stuck after the "Done!" statement (yes, I know it's a bit ambitious to program that in before the algorithm has run but I like to be optimistic. :)

By stuck and stalls, I mean that the CPU usage spikes but nothing is written to the console.

As a general side note:

Is there a way I can debug through the console, i.e. have it tell me what it's doing similar to echo in windows command prompt?  I'm new to OS X too...


问:
How to present view controller behind another view controller?
I am trying to present two view controllers. I'm trying to avoid presenting one after the other as this doesn't give a good user experience.

I'm using storyboards / segues to present the view controllers, each embedded in navigation controllers.

The behaviour should be:

View Controller 1 presents view controller 2 - but when view controller 2 dismisses I'd like view controller 3 to be the one showing to the user. And ideally an ability to also dismiss to view controller 1.

I understand I can accomplish this with child views. But I'd ideally like to learn how it can be done by manipulating the navigation stack.

答:
Presenting viewController in the ViewDidLoad() is really a bad idea.

You can present VC3 and add VC1.view and VC2.view as a subview of VC3's view and later you can remove VC1.view and VC2.view as you want and behaviour will be same as you are expecting.


问:
Is it possible to force file downloads in browsers with angularjs?
I'm have developed a SPA (Single Page Application) with AngularJS and I'm trying to force a pdf file download with AngularJS.

By the moment I only can open de pdf file in a new tab with the next code.

HTML view:

```<code><a ng-click="download()"></a>
</code>```

Controller:

```<code>$scope.download = function(){
    $window.open('/cv.pdf', '_blank');
};
</code>```

Is there any way to force the pdf download in the browser?

You can see this example in the following URLs:

www.juanmanuellopezpazos.es/curriculum (HTML View)

www.juanmanuellopezpazos.es/Curriculum.pdf (pdf file whose download I want to force)

答:
Finally I got the solution with @kierandotco answer. The best way is something like this:

The download HTML5 attribute and target attribute with _self value do the trick.

Body:
I'm have developed a SPA (Single Page Application) with AngularJS and I'm trying to force a pdf file download with AngularJS.

By the moment I only can open de pdf file in a new tab with the next code.

HTML view:

Controller:

$scope.download = function(){
    $window.open('/cv.pdf', '_blank');
};

Is there any way to force the pdf download in the browser?

You can see this example in the following URLs:

www.juanmanuellopezpazos.es/curriculum (HTML View)

www.juanmanuellopezpazos.es/Curriculum.pdf (pdf file whose download I want to force)

Body:
Finally I got the solution with @kierandotco answer. The best way is something like this:

<a href="host/file.pdf" download target="_self"></a>

The download HTML5 attribute and target attribute with _self value do the trick.


问:
How to get arguments from two lists which makes the value of any function maximum?
```<code>any_func=lambda x,y:x/(y+1)
list1=[1,2,3,4,5,6,7,8]
list2=[4,5,6,7,9,2,3,5,7,8]
</code>```

I have two lists list1 and list2,I want to Step 1:get element pair from the two lists which makes the function any_func has maximum value, and step2: then remove these two elements from original lists, continue step 1 and step 2 until list1 or list2 is empty,summation of all results of any_func.
Is there any trick with python?

答:
I hope I understood well from your question. The trick that I used is to construct a sort of matrix:

```<code>I = [ list1[ 0] , list1[ 0] , ... , list1[ 0] , list1[ 1] , list1[ 1] , ... ]
J = [ list2[ 0] , list2[ 1] , ... , list2[-1] , list2[ 0] , list2[ 1] , ... ]
</code>```

which is evaluated. The result is stored in one list. The only thing that then remains is to reconstuct the original indices, whereby we use the fact that we know that list2 is repeated for each item of list1.

Here is what I made of it:

```<code># some function to evaluate
any_func = lambda x,y : x/(y+1)

# some input data
list1 = [1,2,3,4,5,6,7,8]
list2 = [4,5,6,7,9,2,3,5,7,8]
total = 0.

# loop until one of the lists is empty
while len(list1)>0 and len(list2)>0:

  # construct a lists of all combinations of "list1" and "list2", evaluate func.
  list_func = [any_func(i,j) for i in list1 for j in list2]
  # find the index of the maximum and trace back to list-index
  idx_max   = max(enumerate(list_func),key=lambda x:x[1])[0]
  idx_2     = idx_max%len(list2)
  idx_1     = int((idx_max-idx_2)/len(list2))
  # add to the requested summation
  total    += list1[idx_1]+list2[idx_2]
  # take elements for lists
  list1     = list1[:idx_1]+list1[idx_1+1:]
  list2     = list2[:idx_2]+list2[idx_2+1:]

print('list1 = ',list1)
print('list1 = ',list2)
</code>```

P.S. I didn't understand what you meant by ",summation of all results of any_func". Please try to write as clearly as possible.

Body:
any_func=lambda x,y:x/(y+1)
list1=[1,2,3,4,5,6,7,8]
list2=[4,5,6,7,9,2,3,5,7,8]

I have two lists list1 and list2,I want to Step 1:get element pair from the two lists which makes the function any_func has maximum value, and step2: then remove these two elements from original lists, continue step 1 and step 2 until list1 or list2 is empty,summation of all results of any_func.
Is there any trick with python?

Body:
I hope I understood well from your question. The trick that I used is to construct a sort of matrix:

I = [ list1[ 0] , list1[ 0] , ... , list1[ 0] , list1[ 1] , list1[ 1] , ... ]
J = [ list2[ 0] , list2[ 1] , ... , list2[-1] , list2[ 0] , list2[ 1] , ... ]

which is evaluated. The result is stored in one list. The only thing that then remains is to reconstuct the original indices, whereby we use the fact that we know that list2 is repeated for each item of list1.

Here is what I made of it:

# some function to evaluate
any_func = lambda x,y : x/(y+1)

# some input data
list1 = [1,2,3,4,5,6,7,8]
list2 = [4,5,6,7,9,2,3,5,7,8]
total = 0.

# loop until one of the lists is empty
while len(list1)>0 and len(list2)>0:

  # construct a lists of all combinations of "list1" and "list2", evaluate func.
  list_func = [any_func(i,j) for i in list1 for j in list2]
  # find the index of the maximum and trace back to list-index
  idx_max   = max(enumerate(list_func),key=lambda x:x[1])[0]
  idx_2     = idx_max%len(list2)
  idx_1     = int((idx_max-idx_2)/len(list2))
  # add to the requested summation
  total    += list1[idx_1]+list2[idx_2]
  # take elements for lists
  list1     = list1[:idx_1]+list1[idx_1+1:]
  list2     = list2[:idx_2]+list2[idx_2+1:]

print('list1 = ',list1)
print('list1 = ',list2)

P.S. I didn't understand what you meant by ",summation of all results of any_func". Please try to write as clearly as possible.


问:
Convering json data to Java script array
i have code above which gets data from a database and then place in in json form to make it readable in java script.
 the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],

"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();

Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];

Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];

in java script. Does Any one know how i can do this.

$query = mysqli_query($conn,"SELECT * FROM car_models");

// Loop the DB result
while(($result = mysqli_fetch_array($query))) {

```<code>// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){

    // Create array for current user
    $data[$result['Brand']] = array();

}

// Add the current race time to the array (do not need to use the float)
</code>```

$data[$result['Brand']][] = $result['Model'];

}

//json data
json_encode($data);

答:
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console

`
 //json data
var brandAvailable =
console.log(brandAvailable);

"`

Body:
i have code above which gets data from a database and then place in in json form to make it readable in java script.
 the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],

"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();

Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];

Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];

in java script. Does Any one know how i can do this.

$query = mysqli_query($conn,"SELECT * FROM car_models");

// Loop the DB result
while(($result = mysqli_fetch_array($query))) {

// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){

    // Create array for current user
    $data[$result['Brand']] = array();

}

// Add the current race time to the array (do not need to use the float)

$data[$result['Brand']][] = $result['Model'];

}

//json data
json_encode($data);


问:
Nvarchar value overflowing an int column where there is no int column?
How is my nvarchar value overflowing an int column when I'm not defining any int values?

I'm getting the following error when I run my stored procedure:

```<code>The conversion of the nvarchar value '17191925814' overflowed an int column.
</code>```

The statement I was trying to execute:

```<code>EXECUTE [dbo].[updateUser] @status = 'active', ..... ,@srcID = '17191925814'
</code>```

The problem is that I never define that value as an int. It is always handled as a string, as far as I can tell. In my stored procedure the @srcID parameter is defined as an nvarchar(255):

```<code>CREATE PROCEDURE [dbo].[updateUser] ... , @srcID nvarchar(255), ...
</code>```

And within that stored procedure, I try to UPDATE a value in a column that is also defined as nvarchar(255):

```<code>IF @srcID NOT IN ('', '0') AND @srcID IS NOT NULL
    UPDATE [dbo].[Users] SET [Source System ID] = @srcID WHERE ...
ELSE IF @srcID = '0'
    UPDATE [dbo].[Users] SET [Source System ID] = '' WHERE ...
</code>```

The target table:

```<code>CREATE TABLE [dbo].[Users] ( ..., [Source System ID] [nvarchar](255) NULL, ...)
</code>```

Where, or why, is SQL Server trying to convert '17191925814' to an int, and how can I prevent it?

Edit: I've included the full code of the stored procedure where the parameter @srcID appears.

答:
This doesn't want to be specific answer (I agree with Gordon, Zohar and Damien), but should be difficult to write in a comment.
Follow a "reduced" procedure to show the case.
I hope it can help you as a method when you have similar problems (always try to reduce the scope), and serve as a confirmation of what Gordon, Zohar and other (I know, there is no need of confirmation as they have great reputation :-) already said:

```<code>CREATE TABLE X ( SourceSystemID nvarchar(255) NULL);
INSERT INTO X VALUES ('17191925814');
GO
CREATE PROCEDURE Upd_X @srcID NVARCHAR(255)
AS
BEGIN
IF @srcID NOT IN ('', '0') AND @srcID IS NOT NULL    UPDATE X SET SourceSystemID = @srcID
ELSE IF @srcID = '0' UPDATE X SET SourceSystemID = ''
END
;
GO
SELECT * FROM X
EXEC Upd_X '17191925814';
SELECT * FROM X;
</code>```

Output:

```<code>SourceSystemID
---------------
17191925814

SourceSystemID
-----------------------------------------
17191925814
</code>```

Body:
How is my nvarchar value overflowing an int column when I'm not defining any int values?

I'm getting the following error when I run my stored procedure:

The conversion of the nvarchar value '17191925814' overflowed an int column.

The statement I was trying to execute:

EXECUTE [dbo].[updateUser] @status = 'active', ..... ,@srcID = '17191925814'

The problem is that I never define that value as an int. It is always handled as a string, as far as I can tell. In my stored procedure the @srcID parameter is defined as an nvarchar(255):

CREATE PROCEDURE [dbo].[updateUser] ... , @srcID nvarchar(255), ...

And within that stored procedure, I try to UPDATE a value in a column that is also defined as nvarchar(255):

IF @srcID NOT IN ('', '0') AND @srcID IS NOT NULL
    UPDATE [dbo].[Users] SET [Source System ID] = @srcID WHERE ...
ELSE IF @srcID = '0'
    UPDATE [dbo].[Users] SET [Source System ID] = '' WHERE ...

The target table:

CREATE TABLE [dbo].[Users] ( ..., [Source System ID] [nvarchar](255) NULL, ...)

Where, or why, is SQL Server trying to convert '17191925814' to an int, and how can I prevent it?

Edit: I've included the full code of the stored procedure where the parameter @srcID appears.

Body:
This doesn't want to be specific answer (I agree with Gordon, Zohar and Damien), but should be difficult to write in a comment.
Follow a "reduced" procedure to show the case.
I hope it can help you as a method when you have similar problems (always try to reduce the scope), and serve as a confirmation of what Gordon, Zohar and other (I know, there is no need of confirmation as they have great reputation :-) already said:

CREATE TABLE X ( SourceSystemID nvarchar(255) NULL);
INSERT INTO X VALUES ('17191925814');
GO
CREATE PROCEDURE Upd_X @srcID NVARCHAR(255)
AS
BEGIN
IF @srcID NOT IN ('', '0') AND @srcID IS NOT NULL    UPDATE X SET SourceSystemID = @srcID
ELSE IF @srcID = '0' UPDATE X SET SourceSystemID = ''
END
;
GO
SELECT * FROM X
EXEC Upd_X '17191925814';
SELECT * FROM X;

Output:

SourceSystemID
---------------
17191925814

SourceSystemID
-----------------------------------------
17191925814


问:
strings.xml special characters in multilingual
Hey,
I've developed an application with french and english translation.
A guy sent me the strings.xml in polish language and in UTF-8 format (cause there are many characters i can't read).
I can open it with notepad with no problem, but Eclipse replace all the special characters by another one (a sort of square)
an idea ?</p>

答:
You can specify the encoding on a per file basis in Eclipse by selecting the properties of the file. Specify the correct file encoding from the dropbox. (in your case UTF-8)

you can also specify a default encoding in the eclipse preferences (content types).


问:
MySQL Get Different services for each IP
I have the following table:

```<code>|    **IP**   | **PORT** | **SERVICE** | **VERSION** |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  443 |   HTTP  |   1.2   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  443 |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
| 3.4.5.6 |  443 |   HTTP  |   1.2   |
| 0.0.0.1 |  25  |   SMTP  |   b     |
| 0.0.0.2 |  443 |   HTTP  |   1.2   |
</code>```

And I want to get a list of the different services by port, service and version between some of the IPs, for example the result for the IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6 should be similar to the following: As the rest of the services on those IPs are the same port, service and version.

Different services for IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6:

```<code>|    IP   | PORT | SERVICE | VERSION |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
</code>```

Not sure how to get them on a Query.

Thanks in advance

答: Can you try by applying group's on IP and SERVICE columns.</p>

Body:
I have the following table:

|    **IP**   | **PORT** | **SERVICE** | **VERSION** |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  443 |   HTTP  |   1.2   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  443 |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
| 3.4.5.6 |  443 |   HTTP  |   1.2   |
| 0.0.0.1 |  25  |   SMTP  |   b     |
| 0.0.0.2 |  443 |   HTTP  |   1.2   |

And I want to get a list of the different services by port, service and version between some of the IPs, for example the result for the IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6 should be similar to the following: As the rest of the services on those IPs are the same port, service and version.

Different services for IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6:

|    IP   | PORT | SERVICE | VERSION |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |

Not sure how to get them on a Query.

Thanks in advance


问:
Navigation drawer in multiple activities
I know this question has been asked multiple times. But my concern is different.

Using Mr. Tamada Tutorial I've created a NavigaionActivity and multiple fragments to replace in FrameLayout. It's working fine.

Now, after selecting any option in a fragment, another activity gets open.

I want the same Navigation menu in that Activity.

Navigation view -- fragments -- Activity (display navigation view here)

What I tried:

use the xml code of displaying Navigation view in that activity.
(DrawerLayout, CoordinatorLayout, AppBarLayout etc)

Then in Activity.java, on click of menu item diverting to the Navigation Activity.

Code:

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    ....>

    <android.support.design.widget.CoordinatorLayout
    ....>

         <android.support.design.widget.AppBarLayout
         ....>

             <android.support.v7.widget.Toolbar
             .... />

         </android.support.design.widget.AppBarLayout>

         <LinearLayout
         .... /> <!-- main content of this Acitivity-->

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
      .... />
</android.support.v4.widget.DrawerLayout>
</code>```

Activity.java:

```<code>public void dashboard(MenuItem item) {
    Bundle bundle = new Bundle();
    bundle.putString("fragment", Constant.DASHBOARD_FRAGMENT);
    UtilityClass.newActivity(this, NavigationActivity.class, bundle);
}
</code>```

And handling the call on Navigation Activity. It is doing the task but code isn't re-usable

Create a separate layout file for Navigation and include it in the Activity. But, this is replacing the main content. Here only included Navigation is visible.

Is there any other way to do it?

答:
Downvoters - here the solution is..

Create an xml file which will have DrawerLayout and NavigationView (one can use the xml given in Question, without the main content) - navigation.xml

As suggested in many answers "create a BaseActivity which extends AppCompatActivity. And inflate navigation.xml.

```<code>public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        View view = View.inflate(this, R.layout.navigation, null);

        // view declarations
        DrawerLayout drawer = (DrawerLayout) view.findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) view.findViewById(R.id.nav_view);
        ...... }}
</code>```

In whichever Activity you wanna use this NavigationMenu, extend BaseActivity for that class.

```<code>GraphActivity extends BaseActivity { .... }
</code>```

In GraphActivity.xml add the NavigationMenu code. You can't just include the navigation.xml it will disable the current xml widgets.

Done!

Body:
I know this question has been asked multiple times. But my concern is different.

Using Mr. Tamada Tutorial I've created a NavigaionActivity and multiple fragments to replace in FrameLayout. It's working fine.

Now, after selecting any option in a fragment, another activity gets open.

I want the same Navigation menu in that Activity.

Navigation view -- fragments -- Activity (display navigation view here)

What I tried:

use the xml code of displaying Navigation view in that activity.
(DrawerLayout, CoordinatorLayout, AppBarLayout etc)

Then in Activity.java, on click of menu item diverting to the Navigation Activity.

Code:

XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    ....>

    <android.support.design.widget.CoordinatorLayout
    ....>

         <android.support.design.widget.AppBarLayout
         ....>

             <android.support.v7.widget.Toolbar
             .... />

         </android.support.design.widget.AppBarLayout>

         <LinearLayout
         .... />

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
      .... />
</android.support.v4.widget.DrawerLayout>

Activity.java:

public void dashboard(MenuItem item) {
    Bundle bundle = new Bundle();
    bundle.putString("fragment", Constant.DASHBOARD_FRAGMENT);
    UtilityClass.newActivity(this, NavigationActivity.class, bundle);
}

And handling the call on Navigation Activity. It is doing the task but code isn't re-usable

Create a separate layout file for Navigation and include it in the Activity. But, this is replacing the main content. Here only included Navigation is visible.

Is there any other way to do it?

Body:
Downvoters - here the solution is..

Create an xml file which will have DrawerLayout and NavigationView (one can use the xml given in Question, without the main content) - navigation.xml

As suggested in many answers "create a BaseActivity which extends AppCompatActivity. And inflate navigation.xml.

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        View view = View.inflate(this, R.layout.navigation, null);

        // view declarations
        DrawerLayout drawer = (DrawerLayout) view.findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) view.findViewById(R.id.nav_view);
        ...... }}

In whichever Activity you wanna use this NavigationMenu, extend BaseActivity for that class.

GraphActivity extends BaseActivity { .... }

In GraphActivity.xml add the NavigationMenu code. You can't just include the navigation.xml it will disable the current xml widgets.

Done!


问:
Firebase Android - How to generate Facebook hash key. Package name and signing-certificate fingerprint do not match
I got the this error after signing in to facebook with firebase in my android app.

Authentication failed: com.google.firebase.FirebaseExeption: An internal error has occured.

Package name and signing-certificate fingerprint do not match.

I have a sha fingerprint in my firebase console and correct package name.
I have uploaded the app to Beta test, and I think I need a release sha key. But I don't know how to create it.

Any help ?

答:
I found the answer.

I had to use this command:

```<code>keytool -exportcert -alias androiddebugkey -keystore ~/YOUR/PATH/TO/KEYSTORE -list -v
</code>```

and set the KEYSTORE path to my .jdk file in my project.

(The .jdk file is generated when creating a signed APK)

Here is how I did it

Instructions:

First: type this in the Terminal window(Mac) to generate debug.keystore

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

I recomend not to chang the alias.

Use "android" as passoword.

Leave the debug.keystore file in the .android folder

Second: Before we can retrive the hash key for release we need to create a .jdk file. You can do this by Android Studio -> "Build"-tab -> "Generate signed APK". Or if you are developing a Cordova app you can create a .jdk file by typing this in your project directory:

keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias

After creating the .jdk file you can create a release hash for facebook.

Third: type this in the terminal:

```<code>keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64
</code>```

And change YOUR_RELEASE_KEY_ALIAS to what ever alias you gave the .jdk file and set the "YOUR_RELEASE_KEY_PATH" to the destination of the .jdk file. Some thing like this: ~/apps/myApp/myApp.jdk

At the end it might look like this:

```<code>keytool -exportcert -alias myApp -keystore ~/apps/myApp/myApp.jdk | openssl sha1 -binary | openssl base64
</code>```

Body:
I found the answer.

I had to use this command:

keytool -exportcert -alias androiddebugkey -keystore ~/YOUR/PATH/TO/KEYSTORE -list -v

and set the KEYSTORE path to my .jdk file in my project.

(The .jdk file is generated when creating a signed APK)

Here is how I did it

Instructions:

First: type this in the Terminal window(Mac) to generate debug.keystore

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

I recomend not to chang the alias.

Use "android" as passoword.

Leave the debug.keystore file in the .android folder

Second: Before we can retrive the hash key for release we need to create a .jdk file. You can do this by Android Studio -> "Build"-tab -> "Generate signed APK". Or if you are developing a Cordova app you can create a .jdk file by typing this in your project directory:

keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias

After creating the .jdk file you can create a release hash for facebook.

Third: type this in the terminal:

keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64

And change YOUR_RELEASE_KEY_ALIAS to what ever alias you gave the .jdk file and set the "YOUR_RELEASE_KEY_PATH" to the destination of the .jdk file. Some thing like this: ~/apps/myApp/myApp.jdk

At the end it might look like this:

keytool -exportcert -alias myApp -keystore ~/apps/myApp/myApp.jdk | openssl sha1 -binary | openssl base64