问:
FingerprintManagerCompat isHardwareDetected return false in targetAPI 25
Both method isHardwareDetected() and hasEnrolledFingerprints() always return false. I found that target API 24 works fine, so this is problem just for 25. I would like to use the latest API but it's not possible without working fingerprint.

Activity

```<code>    FingerprintManagerCompat from = FingerprintManagerCompat.from(getApplication());
    boolean hardwareDetected = from.isHardwareDetected();
    boolean b = from.hasEnrolledFingerprints();
</code>```

app.gradle

```<code>android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.tkuhn.myapplication"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.2.0'
testCompile 'junit:junit:4.12'
}
</code>```

答:
The issues with the newer support libraries come from the fact that they are now actively checking the devices system features to include FEATURE_FINGERPRINT. It seems like the affected devices do not have this feature specified in their configs even though they have a fingerprint sensor. That's a fault on the device manufacturers side.

This is the check in FingerprintManagerCompat that will return false

```<code>  if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {  /**/  }
</code>```

You could try Reprint or RxFingerpring as alternative solutions.

Body:
Both method isHardwareDetected() and hasEnrolledFingerprints() always return false. I found that target API 24 works fine, so this is problem just for 25. I would like to use the latest API but it's not possible without working fingerprint.

Activity

    FingerprintManagerCompat from = FingerprintManagerCompat.from(getApplication());
    boolean hardwareDetected = from.isHardwareDetected();
    boolean b = from.hasEnrolledFingerprints();

app.gradle

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.tkuhn.myapplication"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.2.0'
testCompile 'junit:junit:4.12'
}

Body:
The issues with the newer support libraries come from the fact that they are now actively checking the devices system features to include FEATURE_FINGERPRINT. It seems like the affected devices do not have this feature specified in their configs even though they have a fingerprint sensor. That's a fault on the device manufacturers side.

This is the check in FingerprintManagerCompat that will return false

  if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {  /**/  }

You could try Reprint or RxFingerpring as alternative solutions.


来源: stackexchange

问:
show error message if code not working
I have an array of Ip addresses belonging to switches and i am using snmpwalk on that array of ip addresses.
if i was to unplug one switch then the ip address corresponding to that switch in the array will not execute.The ip address will still be present in the array it just won't be able to execute. How would i write up a code to show an error/echo error massage if this happens but still execute the other ip addresses?

This is my code:

```<code><?php
$dbconnect = new mysqli('localhost', 'root', '', 'name');

$results   = array();
$secondRow = array();

foreach ($switchArray as $key => $value) {

    $results = snmpwalk($value, "public", ".1.3.6.1.2.1.17.4.3.1.1");

    foreach ($results as $secondResults) {
        $secondResults = str_replace(" ", "", $secondResults);
        $secondResults = str_replace("Hex-STRING:", "", $secondResults);
        $secondResults = str_replace("STRING:", "", $secondResults);
        $secondResults = str_replace("INTEGER:", "", $secondResults);

        $secondArray[] = $secondResults;

    }

}

echo "looping through results of the ip";
echo "```";
print_r($secondArray);
echo "```";

?>
</code>```

答:
snmpwalk returns false on failure, so you could just check for that value first and log/echo the error then continue the array iteration.

```<code><?php
$dbconnect = new mysqli('localhost', 'root', '', 'name');

$results   = array();
$secondRow = array();

foreach ($switchArray as $key => $value) {

    $results = snmpwalk($value, "public", ".1.3.6.1.2.1.17.4.3.1.1");

    // check for error and continue
    if (false === $results) {
        echo "$value unreachable <br>".PHP_EOL;
        continue;
    }

    foreach ($results as $secondResults) {
        $secondResults = str_replace(" ", "", $secondResults);
        $secondResults = str_replace("Hex-STRING:", "", $secondResults);
        $secondResults = str_replace("STRING:", "", $secondResults);
        $secondResults = str_replace("INTEGER:", "", $secondResults);

        $secondArray[] = $secondResults;

    }

}

echo "looping through results of the ip";
echo "```";
print_r($secondArray);
echo "```";
</code>```

ContentLicense: CC BY-SA 3.0

Title: show error message if code not working

Body:
I have an array of Ip addresses belonging to switches and i am using snmpwalk on that array of ip addresses.
if i was to unplug one switch then the ip address corresponding to that switch in the array will not execute.The ip address will still be present in the array it just won't be able to execute. How would i write up a code to show an error/echo error massage if this happens but still execute the other ip addresses?

This is my code:

<?php
$dbconnect = new mysqli('localhost', 'root', '', 'name');

$results   = array();
$secondRow = array();

foreach ($switchArray as $key => $value) {

    $results = snmpwalk($value, "public", ".1.3.6.1.2.1.17.4.3.1.1");

    foreach ($results as $secondResults) {
        $secondResults = str_replace(" ", "", $secondResults);
        $secondResults = str_replace("Hex-STRING:", "", $secondResults);
        $secondResults = str_replace("STRING:", "", $secondResults);
        $secondResults = str_replace("INTEGER:", "", $secondResults);

        $secondArray[] = $secondResults;

    }

}

echo "looping through results of the ip";
echo "
";
print_r($secondArray);
echo "
";

?>

Body:
snmpwalk returns false on failure, so you could just check for that value first and log/echo the error then continue the array iteration.

<?php
$dbconnect = new mysqli('localhost', 'root', '', 'name');

$results   = array();
$secondRow = array();

foreach ($switchArray as $key => $value) {

    $results = snmpwalk($value, "public", ".1.3.6.1.2.1.17.4.3.1.1");

    // check for error and continue
    if (false === $results) {
        echo "$value unreachable <br>".PHP_EOL;
        continue;
    }

    foreach ($results as $secondResults) {
        $secondResults = str_replace(" ", "", $secondResults);
        $secondResults = str_replace("Hex-STRING:", "", $secondResults);
        $secondResults = str_replace("STRING:", "", $secondResults);
        $secondResults = str_replace("INTEGER:", "", $secondResults);

        $secondArray[] = $secondResults;

    }

}

echo "looping through results of the ip";
echo "<pre>";
print_r($secondArray);
echo "</pre>";


问:
Karma Jasmine PhantomJS- PhantomJS have not captured in 60000 ms
In Package JSON, I have tried many different versions of karma-phantomjs-launcher, phantomjs, including phantomjs-prebuilt.

Current Package JSON
  "devDependencies": {
    "jasmine-core": "^2.5.2",
    "karma": "^1.6.0",
    "karma-jasmine": "^1.1.0",
    "karma-phantomjs-launcher": "^0.1.1",
    "phantomjs": "^1.9.20"
  }

In all cases I get "PhantomJS have not captured in 60000 ms"  It tries twice, then gives up.

I am on Windows 10, running from command line in WebStorm.  However, I get same errors in Visual Studio Code.

What is the problem? Karma starts, Karma finds files, PhantomJS starts, but does not capture.

I've seen suggestions to set localhost in hosts file and checking whether karma port 9876 is already in use.  Nothing seems to work.

Please advise.
Thanks

答:
From this thread https://github.com/karma-runner/karma-phantomjs-launcher/issues/84

Go to C:\Windows\System32\drivers\etc\hosts or /etc/hosts (if you're on Linux)

Add 127.0.0.1 localhost to your host file and it works!


问:
NullReferenceException changing the logic within the statement
I have the following piece of code.

```<code>(!string.IsNullOrEmpty(billInfo.BillingMethod) || (!billInfo.BillingMethod.Equals(bill) && bill != null)
</code>```

I understand that I'm getting a null reference exception because more than likely its comparing a null value within the equals method. However I'm confused on how to change the logic so I still end up with the same result without using a method.

答:
You need to check everything that could be null. I just assume billInfo could be null too. Also The order of the statements is important here.</p>

```<code>(billInfo != null && !string.IsNullOrEmpty(billInfo.BillingMethod) || (bill != null && !billInfo.BillingMethod?.Equals(bill))
</code>```

Body:
I have the following piece of code.

(!string.IsNullOrEmpty(billInfo.BillingMethod) || (!billInfo.BillingMethod.Equals(bill) && bill != null)

I understand that I'm getting a null reference exception because more than likely its comparing a null value within the equals method. However I'm confused on how to change the logic so I still end up with the same result without using a method.

Body:
You need to check everything that could be null. I just assume billInfo could be null too. Also The order of the statements is important here.

(billInfo != null && !string.IsNullOrEmpty(billInfo.BillingMethod) || (bill != null && !billInfo.BillingMethod?.Equals(bill))


问:
Error Running Pyinstaller (Python)
I have this code, it generates a webmap with folium, it reads some files and plot some lines on the map.

I want to share my program with a group of people who don't know anything about python, so I want to create an .exe file.
I'm on python 3.6.1 with the lastest development version of pyinstaller, but I am getting an error when i try to run the exe file.

NotImplementedError: Can't perform this operation for unregistered loader type
Failed to execute script map_generator

Does anybody know what can I do? maybe any other packeges for doing this?

Thank you everybody

```<code>import folium
import pandas
from fastkml import kml

def get_group(elev):
    if elev in range(0,1000):
        group = cero
    elif elev in range(1000,2000):
        group = mil
    elif elev in range(2000,3000):
        group = dosmil
    elif elev in range(3000,4000):
        group = tresmil
    elif elev in range(4000,5000):
        group = cuatromil
    elif elev in range(5000,6000):
        group = cincomil
    elif elev in range(6000,7000):
        group = seismil
    elif elev in range(7000,8000):
        group = sietemil
    elif elev in range(8000,9000):
        group = ochomil
    elif elev in range(9000,10000):
        group = nuevemil
    elif elev in range(10000,11000):
        group = diezmil
    elif elev in range(11000,12000):
        group = oncemil
    elif elev in range(12000,13000):
        group = docemil
    elif elev in range(13000,14000):
        group = trecemil
    elif elev in range(14000,15000):
        group = catorcemil
    elif elev in range(15000,16000):
        group = quincemil
    elif elev in range(16000,17000):
        group = dieciseismil
    elif elev in range(17000,18000):
        group = diecisietemil
    elif elev in range(18000,19000):
        group = dieciochomil
    elif elev in range(19000,20000):
        group = diecinuevemil
    else:
        group = veintemil
    return group

def colorear(elev):
    if elev in range(0,1000):
        color = '#5d005e'
    elif elev in range(1000,2000):
        color = '#950096'
    elif elev in range(2000,3000):
        color = '#fd00ff'
    elif elev in range(3000,4000):
        color = '#16005c'
    elif elev in range(4000,5000):
        color = '#240198'
    elif elev in range(5000,6000):
        color = '#4f21e3'
    elif elev in range(6000,7000):
        color = '#06334f'
    elif elev in range(7000,8000):
        color = '#115e8d'
    elif elev in range(8000,9000):
        color = '#28aeff'
    elif elev in range(9000,10000):
        color = '#045e45'
    elif elev in range(10000,11000):
        color = '#299c7d'
    elif elev in range(11000,12000):
        color = '#083c00'
    elif elev in range(12000,13000):
        color = '#128700'
    elif elev in range(13000,14000):
        color = '#359826'
    elif elev in range(14000,15000):
        color = '#33fd14'
    elif elev in range(15000,16000):
        color = '#777e07'
    elif elev in range(16000,17000):
        color = '#c0cc06'
    elif elev in range(17000,18000):
        color = '#eaf62a'
    elif elev in range(18000,19000):
        color = '#ff8100'
    elif elev in range(19000,20000):
        color = '#b00000'
    else:
        color = '#ff2e2e'
    return color

map = folium.Map(location=[-13.537638,-71.943920], zoom_start=6, tiles='Stamen Terrain', control_scale=True)

cero = folium.FeatureGroup(name = '0 ft')
mil = folium.FeatureGroup(name = '1000 ft')
dosmil = folium.FeatureGroup(name = '2000 ft')
tresmil = folium.FeatureGroup(name = '3000 ft')
cuatromil = folium.FeatureGroup(name = '4000 ft')
cincomil = folium.FeatureGroup(name = '5000 ft')
seismil = folium.FeatureGroup(name = '6000 ft')
sietemil = folium.FeatureGroup(name = '7000 ft')
ochomil = folium.FeatureGroup(name = '8000 ft')
nuevemil = folium.FeatureGroup(name = '9000 ft')
diezmil = folium.FeatureGroup(name = '10000 ft')
oncemil = folium.FeatureGroup(name = '11000 ft')
docemil = folium.FeatureGroup(name = '12000 ft')
trecemil = folium.FeatureGroup(name = '13000 ft')
catorcemil = folium.FeatureGroup(name = '14000 ft')
quincemil = folium.FeatureGroup(name = '15000 ft')
dieciseismil = folium.FeatureGroup(name = '16000 ft')
diecisietemil = folium.FeatureGroup(name = '17000 ft')
dieciochomil = folium.FeatureGroup(name = '18000 ft')
diecinuevemil = folium.FeatureGroup(name = '19000 ft')
veintemil = folium.FeatureGroup(name = '20000 ft')
ruta = folium.FeatureGroup(name = 'ruta')

k = kml.KML()
k.from_string(open("ruta.kml").read())
features = list(k.features())
folders = list(features[0].features())
placemarks = list(folders[0].features())
coordenadas_ruta = placemarks[0].geometry.coords
flight_path = list()
for coordenada in coordenadas_ruta:
    coor = (coordenada[1],coordenada[0])
    flight_path.append(coor)
ruta.add_child(folium.PolyLine(locations = flight_path))

geojson = pandas.read_json('topo.geojson')
for linea in geojson['features']:
    grupo = get_group(int(linea['properties']['ELEVATION'][:linea['properties']['ELEVATION'].find(' ')]))
    coors = linea['geometry']['coordinates']
    (folium.PolyLine(locations=coors,latlon=False, weight=6,color=colorear(int(linea['properties']['ELEVATION'][:linea['properties']['ELEVATION'].find(' ')])))).add_to(grupo)

m = pandas.read_csv('picos.csv')
for id,altitud,latitud,longitud in zip(m['ID'],m['ALT'],m['LAT'],m['LON']):
    grupo = get_group(altitud)
    folium.RegularPolygonMarker(location=[latitud,longitud], popup=folium.Popup(str(altitud)+' ft'),
                   fill_color=colorear(altitud), number_of_sides=3, radius=10).add_to(grupo)

map.add_child(cero)
map.add_child(mil)
map.add_child(dosmil)
map.add_child(tresmil)
map.add_child(cuatromil)
map.add_child(cincomil)
map.add_child(seismil)
map.add_child(sietemil)
map.add_child(ochomil)
map.add_child(nuevemil)
map.add_child(diezmil)
map.add_child(oncemil)
map.add_child(docemil)
map.add_child(trecemil)
map.add_child(catorcemil)
map.add_child(quincemil)
map.add_child(dieciseismil)
map.add_child(diecisietemil)
map.add_child(dieciochomil)
map.add_child(diecinuevemil)
map.add_child(veintemil)
map.add_child(ruta)

map.add_child(folium.LayerControl())

map.save('mapa.html')
</code>```

答: Try adding an empty file called __init__.py in the directory that contains your code. This allows Python to consider your directory a package.

Title: Error Running Pyinstaller (Python)

Body:
I have this code, it generates a webmap with folium, it reads some files and plot some lines on the map.

I want to share my program with a group of people who don't know anything about python, so I want to create an .exe file.
I'm on python 3.6.1 with the lastest development version of pyinstaller, but I am getting an error when i try to run the exe file.

NotImplementedError: Can't perform this operation for unregistered loader type
Failed to execute script map_generator

Does anybody know what can I do? maybe any other packeges for doing this?

Thank you everybody

import folium
import pandas
from fastkml import kml

def get_group(elev):
    if elev in range(0,1000):
        group = cero
    elif elev in range(1000,2000):
        group = mil
    elif elev in range(2000,3000):
        group = dosmil
    elif elev in range(3000,4000):
        group = tresmil
    elif elev in range(4000,5000):
        group = cuatromil
    elif elev in range(5000,6000):
        group = cincomil
    elif elev in range(6000,7000):
        group = seismil
    elif elev in range(7000,8000):
        group = sietemil
    elif elev in range(8000,9000):
        group = ochomil
    elif elev in range(9000,10000):
        group = nuevemil
    elif elev in range(10000,11000):
        group = diezmil
    elif elev in range(11000,12000):
        group = oncemil
    elif elev in range(12000,13000):
        group = docemil
    elif elev in range(13000,14000):
        group = trecemil
    elif elev in range(14000,15000):
        group = catorcemil
    elif elev in range(15000,16000):
        group = quincemil
    elif elev in range(16000,17000):
        group = dieciseismil
    elif elev in range(17000,18000):
        group = diecisietemil
    elif elev in range(18000,19000):
        group = dieciochomil
    elif elev in range(19000,20000):
        group = diecinuevemil
    else:
        group = veintemil
    return group

def colorear(elev):
    if elev in range(0,1000):
        color = '#5d005e'
    elif elev in range(1000,2000):
        color = '#950096'
    elif elev in range(2000,3000):
        color = '#fd00ff'
    elif elev in range(3000,4000):
        color = '#16005c'
    elif elev in range(4000,5000):
        color = '#240198'
    elif elev in range(5000,6000):
        color = '#4f21e3'
    elif elev in range(6000,7000):
        color = '#06334f'
    elif elev in range(7000,8000):
        color = '#115e8d'
    elif elev in range(8000,9000):
        color = '#28aeff'
    elif elev in range(9000,10000):
        color = '#045e45'
    elif elev in range(10000,11000):
        color = '#299c7d'
    elif elev in range(11000,12000):
        color = '#083c00'
    elif elev in range(12000,13000):
        color = '#128700'
    elif elev in range(13000,14000):
        color = '#359826'
    elif elev in range(14000,15000):
        color = '#33fd14'
    elif elev in range(15000,16000):
        color = '#777e07'
    elif elev in range(16000,17000):
        color = '#c0cc06'
    elif elev in range(17000,18000):
        color = '#eaf62a'
    elif elev in range(18000,19000):
        color = '#ff8100'
    elif elev in range(19000,20000):
        color = '#b00000'
    else:
        color = '#ff2e2e'
    return color

map = folium.Map(location=[-13.537638,-71.943920], zoom_start=6, tiles='Stamen Terrain', control_scale=True)

cero = folium.FeatureGroup(name = '0 ft')
mil = folium.FeatureGroup(name = '1000 ft')
dosmil = folium.FeatureGroup(name = '2000 ft')
tresmil = folium.FeatureGroup(name = '3000 ft')
cuatromil = folium.FeatureGroup(name = '4000 ft')
cincomil = folium.FeatureGroup(name = '5000 ft')
seismil = folium.FeatureGroup(name = '6000 ft')
sietemil = folium.FeatureGroup(name = '7000 ft')
ochomil = folium.FeatureGroup(name = '8000 ft')
nuevemil = folium.FeatureGroup(name = '9000 ft')
diezmil = folium.FeatureGroup(name = '10000 ft')
oncemil = folium.FeatureGroup(name = '11000 ft')
docemil = folium.FeatureGroup(name = '12000 ft')
trecemil = folium.FeatureGroup(name = '13000 ft')
catorcemil = folium.FeatureGroup(name = '14000 ft')
quincemil = folium.FeatureGroup(name = '15000 ft')
dieciseismil = folium.FeatureGroup(name = '16000 ft')
diecisietemil = folium.FeatureGroup(name = '17000 ft')
dieciochomil = folium.FeatureGroup(name = '18000 ft')
diecinuevemil = folium.FeatureGroup(name = '19000 ft')
veintemil = folium.FeatureGroup(name = '20000 ft')
ruta = folium.FeatureGroup(name = 'ruta')

k = kml.KML()
k.from_string(open("ruta.kml").read())
features = list(k.features())
folders = list(features[0].features())
placemarks = list(folders[0].features())
coordenadas_ruta = placemarks[0].geometry.coords
flight_path = list()
for coordenada in coordenadas_ruta:
    coor = (coordenada[1],coordenada[0])
    flight_path.append(coor)
ruta.add_child(folium.PolyLine(locations = flight_path))

geojson = pandas.read_json('topo.geojson')
for linea in geojson['features']:
    grupo = get_group(int(linea['properties']['ELEVATION'][:linea['properties']['ELEVATION'].find(' ')]))
    coors = linea['geometry']['coordinates']
    (folium.PolyLine(locations=coors,latlon=False, weight=6,color=colorear(int(linea['properties']['ELEVATION'][:linea['properties']['ELEVATION'].find(' ')])))).add_to(grupo)

m = pandas.read_csv('picos.csv')
for id,altitud,latitud,longitud in zip(m['ID'],m['ALT'],m['LAT'],m['LON']):
    grupo = get_group(altitud)
    folium.RegularPolygonMarker(location=[latitud,longitud], popup=folium.Popup(str(altitud)+' ft'),
                   fill_color=colorear(altitud), number_of_sides=3, radius=10).add_to(grupo)

map.add_child(cero)
map.add_child(mil)
map.add_child(dosmil)
map.add_child(tresmil)
map.add_child(cuatromil)
map.add_child(cincomil)
map.add_child(seismil)
map.add_child(sietemil)
map.add_child(ochomil)
map.add_child(nuevemil)
map.add_child(diezmil)
map.add_child(oncemil)
map.add_child(docemil)
map.add_child(trecemil)
map.add_child(catorcemil)
map.add_child(quincemil)
map.add_child(dieciseismil)
map.add_child(diecisietemil)
map.add_child(dieciochomil)
map.add_child(diecinuevemil)
map.add_child(veintemil)
map.add_child(ruta)

map.add_child(folium.LayerControl())

map.save('mapa.html')


问:
C# : Wait for n miliseconds, and test a boolean every n/m milliseconds
I have to test a boolean every 250ms, max 2 seconds, and stop when it's true.

Tried this, but Thread.Sleep isn't a good solution for me because it's freezing my software, and waiting for even more won't change anything because the boolean won't change while it's frozen.

```<code>bool onLine = false;
Stopwatch chrono = new Stopwatch();
chrono.Start();
while (chrono.ElapsedMilliseconds < 2000)
{
    if (!State().Equals(Online))
    {
        System.Threading.Thread.Sleep(250);
    }
    else
    {
        onLine = true;
        operationCompleted();
        break;
    }
}
if (!onLine)
{
    MessageBox.Show("Error");
}
</code>```

I don't know how to make the tests in an event raised by a timer if someone has a correct implementation?

答:
Not sure what it looks like in WPF, but here is how it would be done in WinForms.  Note that the button handler has been marked with async:

```<code>private async void button1_Click(object sender, EventArgs e)
{
    bool onLine = false;
    Stopwatch chrono = new Stopwatch();
    await (Task.Run(new Action(() =>
    {
        chrono.Start();
        while (chrono.ElapsedMilliseconds < 2000)
        {
            if (!State().Equals(Online))
            {
                System.Threading.Thread.Sleep(250);
            }
            else
            {
                onLine = true;
                break;
            }
        }
    })));

    if (onLine)
    {
        operationCompleted();
    }
    else
    {
        MessageBox.Show("Error");
    }
}
</code>```

Body:
I have to test a boolean every 250ms, max 2 seconds, and stop when it's true.

Tried this, but Thread.Sleep isn't a good solution for me because it's freezing my software, and waiting for even more won't change anything because the boolean won't change while it's frozen.

bool onLine = false;
Stopwatch chrono = new Stopwatch();
chrono.Start();
while (chrono.ElapsedMilliseconds < 2000)
{
    if (!State().Equals(Online))
    {
        System.Threading.Thread.Sleep(250);
    }
    else
    {
        onLine = true;
        operationCompleted();
        break;
    }
}
if (!onLine)
{
    MessageBox.Show("Error");
}

I don't know how to make the tests in an event raised by a timer if someone has a correct implementation?

Body:
Not sure what it looks like in WPF, but here is how it would be done in WinForms.  Note that the button handler has been marked with async:

private async void button1_Click(object sender, EventArgs e)
{
    bool onLine = false;
    Stopwatch chrono = new Stopwatch();
    await (Task.Run(new Action(() =>
    {
        chrono.Start();
        while (chrono.ElapsedMilliseconds < 2000)
        {
            if (!State().Equals(Online))
            {
                System.Threading.Thread.Sleep(250);
            }
            else
            {
                onLine = true;
                break;
            }
        }
    })));

    if (onLine)
    {
        operationCompleted();
    }
    else
    {
        MessageBox.Show("Error");
    }
}


问:
Python: Using getpass with argparse
I've had a look around, but couldn't find anything.

Basically I was wondering if it was possible to use getpass.getpass() with argparse.

At the moment I have the following as a work around, I was just wondering if there was a better way:

```<code>import argparse
import getpass

parser = argparse.ArgumentParser(description="Some description")
parser.add_argument('-p', metavar="password", default="foobarblah123", help="password for user (default to prompt user)")
...
parsed_args = parser.parse_args()
args = vars(parsed_args)
user_pass = args['p']
if user_pass == "foobarblah123":
  user_pass = getpass.getpass()
</code>```

I'm pretty sure this is not the best way to handle this, however, there is a requirement to have a command line option for the password ... best practice or not.

Thanks.

答:
Here's what I came up with for prompting for a password that's pretty minimal (Python 3 code):

```<code>import argparse
import getpass

class Password:

    DEFAULT = 'Prompt if not specified'

    def __init__(self, value):
        if value == self.DEFAULT:
            value = getpass.getpass('LDAP Password: ')
        self.value = value

    def __str__(self):
        return self.value

parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-u', '--username', help='Specify username',
    default=getpass.getuser())
parser.add_argument('-p', '--password', type=Password, help='Specify password',
    default=Password.DEFAULT)
args = parser.parse_args()

print(args.username, args.password)
</code>```

Usage example:

```<code>$ python ~/Desktop/example.py -h
usage: example.py [-h] [-u USERNAME] [-p PASSWORD]

optional arguments:
  -h, --help            show this help message and exit
  -u USERNAME, --username USERNAME
                        Specify username (default: gavinr)
  -p PASSWORD, --password PASSWORD
                        Specify password (default: Prompt if not specified)

$ python ~/Desktop/example.py -p foo
gavinr foo

$ python ~/Desktop/example.py
LDAP Password:
gavinr foo
</code>```

Title: Python: Using getpass with argparse

Body:
I've had a look around, but couldn't find anything.

Basically I was wondering if it was possible to use getpass.getpass() with argparse.

At the moment I have the following as a work around, I was just wondering if there was a better way:

import argparse
import getpass

parser = argparse.ArgumentParser(description="Some description")
parser.add_argument('-p', metavar="password", default="foobarblah123", help="password for user (default to prompt user)")
...
parsed_args = parser.parse_args()
args = vars(parsed_args)
user_pass = args['p']
if user_pass == "foobarblah123":
  user_pass = getpass.getpass()

I'm pretty sure this is not the best way to handle this, however, there is a requirement to have a command line option for the password ... best practice or not.

Thanks.

Body:
Here's what I came up with for prompting for a password that's pretty minimal (Python 3 code):

import argparse
import getpass

class Password:

    DEFAULT = 'Prompt if not specified'

    def __init__(self, value):
        if value == self.DEFAULT:
            value = getpass.getpass('LDAP Password: ')
        self.value = value

    def __str__(self):
        return self.value

parser = argparse.ArgumentParser(
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-u', '--username', help='Specify username',
    default=getpass.getuser())
parser.add_argument('-p', '--password', type=Password, help='Specify password',
    default=Password.DEFAULT)
args = parser.parse_args()

print(args.username, args.password)

Usage example:

$ python ~/Desktop/example.py -h
usage: example.py [-h] [-u USERNAME] [-p PASSWORD]

optional arguments:
  -h, --help            show this help message and exit
  -u USERNAME, --username USERNAME
                        Specify username (default: gavinr)
  -p PASSWORD, --password PASSWORD
                        Specify password (default: Prompt if not specified)

$ python ~/Desktop/example.py -p foo
gavinr foo

$ python ~/Desktop/example.py
LDAP Password:
gavinr foo


问:
pgadmin 4 1.4/1.5 not launching on windows
I installed pgadmin 4 1.5 desktop on windows 10, but when I try launching it, I can see the splash screen, then it disappear and nothing more append.

In the task manager, I can see it running, and consuming CPU in the first seconds, but the UI never show up.

I have the same problem on pgadmin 4 1.4, but weirdly, 1.3 works well.

As 1.3 works, I will use it, but if anyone know what is happening, I will appreciate help.

Thank you

答:
I found some help here :
http://www.postgresql-archive.org/pgAdmin-4-v1-3-fails-to-load-td5951102.html

I downloaded this 1.5 version and it launched normally, btw I didn't check if everything is running as expected :
https://developer.pgadmin.org/~dpage/pgadmin4-1.5-x86.exe

hope it helps


答:
Here's an example using a threading timer:</p>

```<code>public class Foo
{
    public System.Threading.Timer EventTimer
    {
        get;
        set;
    }

    public long TimingInterval
    {
        get;
        set;
    }
    public Foo()
    {
        EventTimer = new System.Threading.Timer(new TimerCallback(Foo.DoCheck),
            this,
            this.TimingInterval,
            this.TimingInterval);
    }
    public void DoCheck()
    {
        //do check here
    }
</code>```

Title: C# : Wait for n miliseconds, and test a boolean every n/m milliseconds

Body:
Here's an example using a threading timer:

public class Foo
{
    public System.Threading.Timer EventTimer
    {
        get;
        set;
    }

    public long TimingInterval
    {
        get;
        set;
    }
    public Foo()
    {
        EventTimer = new System.Threading.Timer(new TimerCallback(Foo.DoCheck),
            this,
            this.TimingInterval,
            this.TimingInterval);
    }
    public void DoCheck()
    {
        //do check here
    }


问:
Visual Basic in excel drop down list population based on a key
I have been attempting to create a drop down list on a worksheet that populates based on the entry in a different cell i.e

```<code>ws1-------------------------------
|numbers|dropdowns               |
|123    |->123 associations list |
|456    |->456 associations list |
----------------------------------

ws2----------------------
|123    | tttttt | 9000 |
|123    | kkkkkk | 8000 |
|123    | hhhhhh | 7000 |
|456    | yyyyyy | 6000 |
|456    | uuuuuu | 5000 |
-------------------------
</code>```

so that when 123 or 456 is typed into the numbers cell, the drop down list populates from the associated cells in ws2 i.e

"typed by user"| "auto populates list"

|456           | yyyyyy-6000      |

- uuuuuu-5000

then the user can select yyyyyy or uuuuuu and the cell would populate with the character cell value from the list selection.

答:
Being that the second column needs to find multiple values associated with a single repeated value from the fist column i use this function

```<code>=INDEX(ASP!$D2:$D$2048,SMALL _
(INDEX((Sheet1!AH$2=ASP!$A2:$A$2048)*
(MATCH(ROW(ASP!$A2:$A$2048),ROW(ASP!$A2:$A$2048)))+ _
(Sheet1!AH$2<>ASP!$A2:$A$2048)*2048,0,0),ROW($A1)))
</code>```

and drag it down for a reasonable amount of rows based on the program limitations. This is a nasty function that can take seconds to complete based on the range of cells being looked at.

i.e if you just use "ASP!A:A" instead of  "ASP!A2:A2028" this ends up running n^2 indexing calls and takes forever.

Then i use

```<code>=VLOOKUP(AI2,ASP!$D:$G,4,0)
</code>```

to populate the next set of columns based on what the first set finds

Then i use

```<code>=IFERROR(CONCATENATE(AI2,"|",AJ2),"")
</code>```

to put the second and third columns together so that both data points are present when the list dropdown is used.

after this i just use data validation lists and populate them with the values in the last column, using the IFERROR to make the cells in the list that dont have any data points related to them appear blank. and i use an on_change event to go through the currently changed value in the list column to split the concat up and only populate the cell with the desired value.

The point of this is so that a user will not have to look through multiple pages of the excel workbook to select the appropriate data point to fill in on a submission page they can just type in the initially desired category then the list will show available options and the amount that these options are present in.

Body:
I have been attempting to create a drop down list on a worksheet that populates based on the entry in a different cell i.e

ws1-------------------------------
|numbers|dropdowns               |
|123    |->123 associations list |
|456    |->456 associations list |
----------------------------------

ws2----------------------
|123    | tttttt | 9000 |
|123    | kkkkkk | 8000 |
|123    | hhhhhh | 7000 |
|456    | yyyyyy | 6000 |
|456    | uuuuuu | 5000 |
-------------------------

so that when 123 or 456 is typed into the numbers cell, the drop down list populates from the associated cells in ws2 i.e

"typed by user"| "auto populates list"

|456           | yyyyyy-6000      |

- uuuuuu-5000

then the user can select yyyyyy or uuuuuu and the cell would populate with the character cell value from the list selection.

Body:
Being that the second column needs to find multiple values associated with a single repeated value from the fist column i use this function

=INDEX(ASP!$D2:$D$2048,SMALL _
(INDEX((Sheet1!AH$2=ASP!$A2:$A$2048)*
(MATCH(ROW(ASP!$A2:$A$2048),ROW(ASP!$A2:$A$2048)))+ _
(Sheet1!AH$2<>ASP!$A2:$A$2048)*2048,0,0),ROW($A1)))

and drag it down for a reasonable amount of rows based on the program limitations. This is a nasty function that can take seconds to complete based on the range of cells being looked at.

i.e if you just use "ASP!A:A" instead of  "ASP!A2:A2028" this ends up running n^2 indexing calls and takes forever.

Then i use

=VLOOKUP(AI2,ASP!$D:$G,4,0)

to populate the next set of columns based on what the first set finds

Then i use

=IFERROR(CONCATENATE(AI2,"|",AJ2),"")

to put the second and third columns together so that both data points are present when the list dropdown is used.

after this i just use data validation lists and populate them with the values in the last column, using the IFERROR to make the cells in the list that dont have any data points related to them appear blank. and i use an on_change event to go through the currently changed value in the list column to split the concat up and only populate the cell with the desired value.

The point of this is so that a user will not have to look through multiple pages of the excel workbook to select the appropriate data point to fill in on a submission page they can just type in the initially desired category then the list will show available options and the amount that these options are present in.


问:
Fetching videos from auto generated channel in YouTube api
Im trying to get all videos from YouTube auto-generated channel (AKA Topic).
I let my users add a link to the YT channel and I am sending the channel ID to retrieve videos.

On regular case, when the channel is NOT auto-generate I am using this endpoint:
https://www.googleapis.com/youtube/v3/channels?part=snippet&channelId={channel_id}&key={key}

This endpoint return a list of videos that posted into this channel.
The problem with topic is that the list of videos return empty...

example for this following request:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCYF2FotHeGO6cNcldrTHN1g&key={YOUR_API_KEY}

```<code>{
 "kind": "youtube#searchListResponse",
 "etag": "\"3enKTWw-I-yugKAPnlrhH5U04vQ/Zi7b6FbLUH9xd8vhDiVs3zpfKLs\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"3enKTWw-I-yugKAPnlrhH5U04vQ/dkWBa22byHoKTpuDJQLPs5T6ndg\"",
   "id": {
    "kind": "youtube#channel",
    "channelId": "UCYF2FotHeGO6cNcldrTHN1g"
   },
   "snippet": {
    "publishedAt": "2013-12-21T05:18:21.000Z",
    "channelId": "UCYF2FotHeGO6cNcldrTHN1g",
    "title": "Manchester United F.C. - Topic",
    "description": "Manchester United Football Club is an English football club based in Old Trafford, Greater Manchester. The club was formed as Newton Heath LYR Football ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/i/YF2FotHeGO6cNcldrTHN1g/1.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/i/YF2FotHeGO6cNcldrTHN1g/mq1.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/i/YF2FotHeGO6cNcldrTHN1g/hq1.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  }
 ]
}
</code>```

Any idea how to get Topic videos?

Thanks

答: auto generated channels has not videos. They have only playlists with videos from other channels. so you have to look for playlists.</p>

Body:
Im trying to get all videos from YouTube auto-generated channel (AKA Topic).
I let my users add a link to the YT channel and I am sending the channel ID to retrieve videos.

On regular case, when the channel is NOT auto-generate I am using this endpoint:
https://www.googleapis.com/youtube/v3/channels?part=snippet&channelId={channel_id}&key={key}

This endpoint return a list of videos that posted into this channel.
The problem with topic is that the list of videos return empty...

example for this following request:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCYF2FotHeGO6cNcldrTHN1g&key={YOUR_API_KEY}

{
 "kind": "youtube#searchListResponse",
 "etag": "\"3enKTWw-I-yugKAPnlrhH5U04vQ/Zi7b6FbLUH9xd8vhDiVs3zpfKLs\"",
 "pageInfo": {
  "totalResults": 1,
  "resultsPerPage": 5
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"3enKTWw-I-yugKAPnlrhH5U04vQ/dkWBa22byHoKTpuDJQLPs5T6ndg\"",
   "id": {
    "kind": "youtube#channel",
    "channelId": "UCYF2FotHeGO6cNcldrTHN1g"
   },
   "snippet": {
    "publishedAt": "2013-12-21T05:18:21.000Z",
    "channelId": "UCYF2FotHeGO6cNcldrTHN1g",
    "title": "Manchester United F.C. - Topic",
    "description": "Manchester United Football Club is an English football club based in Old Trafford, Greater Manchester. The club was formed as Newton Heath LYR Football ...",
    "thumbnails": {
     "default": {
      "url": "https://i.ytimg.com/i/YF2FotHeGO6cNcldrTHN1g/1.jpg"
     },
     "medium": {
      "url": "https://i.ytimg.com/i/YF2FotHeGO6cNcldrTHN1g/mq1.jpg"
     },
     "high": {
      "url": "https://i.ytimg.com/i/YF2FotHeGO6cNcldrTHN1g/hq1.jpg"
     }
    },
    "channelTitle": "",
    "liveBroadcastContent": "none"
   }
  }
 ]
}

Any idea how to get Topic videos?

Thanks


问:
Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss
I am trying to create a git repository on my web host and clone it on my computer. Here's what I did:

I created a repository on the remote server.

I generated a key pair: ssh-keygen -t dsa.

I added my key to ssh-agent.

I copied to the server public key in ~/.ssh.

And then, after an attempt to run the command git clone ssh://user@host/path-to-repository, I get an error:

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

  fatal: Could not read from remote repository.

  Please make sure you have the correct access rights and the repository exists.

What does that mean?

答:
You either follow above approach or this one

Create the config file in the .ssh directory and add these line.

```<code>host xxx.xxx
 Hostname xxx.xxx
 IdentityFile ~/.ssh/id_rsa
 User xxx
 KexAlgorithms +diffie-hellman-group1-sha1
</code>```

Body:
You either follow above approach or this one

Create the config file in the .ssh directory and add these line.

host xxx.xxx
 Hostname xxx.xxx
 IdentityFile ~/.ssh/id_rsa
 User xxx
 KexAlgorithms +diffie-hellman-group1-sha1


问:
Passing big complex arrays from Python to C++ - what's my best option?
2017/06/13 EDIT:
I tried using boost as was suggested, but after spending more than 3 days trying to get it to compile and link, and failing, I decided that the stupid painful way was probably the fastest and less painfull.... so now my code just saves a mess of gigantic text files (splitting arrays and the complex/ imaginary parts of the numbers across files) that C++ then reads. Elegant... no.... effective... yes.

I have some scientific code, currently written in Python, that is being slowed down by a numerical 3d integration step within a loop. To overcome this I am re-writing this particular step in C++. (Cython etc is not an option).

Long story short: I want to transfer several very large arrays of complex numbers from the python code to the C++ integrator as conveniently and painlessly as possible. I could do this manually and painfully using text or binary files - but before I embark on this, I was wondering if I have any better options?

I'm using visual studio for C++ and anaconda for python (not my choice!)

Is there any file format or method that would make it quick and convenient to save an array of complex numbers from python and then recreate it in C++?

Many thanks,
Ben

答:
Note added in edit.
As mentioned in the comments, python itself, being an interpreted language, has little potential for computational efficiency. So in order to make python scripts efficient, one must use modules which aren't all interpreted, but under the hood call compiled (and optimized) code written in, say, C/C++. This is exactly what numpy does for you, in particular for operations on whole arrays.

Therefore, the first step towards efficient python scripts is the usage of numpy. Only the second step is to try to use your own compiled (and optimized) code. Therefore, I have assumed in my example below that you were using numpy to store the array of complex numbers. Everything else would be ill-advised.

There are various ways in which you can access python's original data from within a C/C++ program. I personally have done this with boost.Python, but must warn you that the documentation and support are lousy at best: you're pretty much on your own (and stack overflow, of course).

For example your C++ file may look like this

```<code>// file.cc
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>

namespace p = boost::python;
namespace n = p::numpy;

n::ndarray func(const n::ndarray&input, double control_variable)
{
  /*
     your code here, see documentation for boost python
     you pass almost any python variable, doesn't have to be numpy stuff
  */
}

BOOST_PYTHON_MODULE(module_name)
{
  Py_Initialize();
  n::initialize();   // only needed if you use numpy in the interface
  p::def("function", func, "doc-string");
}
</code>```

to compile this, you may use a python script such as

```<code># setup.py

from distutils.core import setup
from distutils.extension import Extension

module_name = Extension(
    'module_name',
    extra_compile_args=['-std=c++11','-stdlib=libc++','-I/some/path/','-march=native'],
    extra_link_args=['-stdlib=libc++'],
    sources=['file.cc'],
    libraries=['boost_python','boost_numpy'])

setup(
    name='module_name',
    version='0.1',
    ext_modules=[module_name])
</code>```

and run it as python setup.py build, which will create an appropriate .so file in a sub-directory of build, which you can import from python.

Body:
Note added in edit.
As mentioned in the comments, python itself, being an interpreted language, has little potential for computational efficiency. So in order to make python scripts efficient, one must use modules which aren't all interpreted, but under the hood call compiled (and optimized) code written in, say, C/C++. This is exactly what numpy does for you, in particular for operations on whole arrays.

Therefore, the first step towards efficient python scripts is the usage of numpy. Only the second step is to try to use your own compiled (and optimized) code. Therefore, I have assumed in my example below that you were using numpy to store the array of complex numbers. Everything else would be ill-advised.

There are various ways in which you can access python's original data from within a C/C++ program. I personally have done this with boost.Python, but must warn you that the documentation and support are lousy at best: you're pretty much on your own (and stack overflow, of course).

For example your C++ file may look like this

// file.cc
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>

namespace p = boost::python;
namespace n = p::numpy;

n::ndarray func(const n::ndarray&input, double control_variable)
{
  /*
     your code here, see documentation for boost python
     you pass almost any python variable, doesn't have to be numpy stuff
  */
}

BOOST_PYTHON_MODULE(module_name)
{
  Py_Initialize();
  n::initialize();   // only needed if you use numpy in the interface
  p::def("function", func, "doc-string");
}

to compile this, you may use a python script such as

# setup.py

from distutils.core import setup
from distutils.extension import Extension

module_name = Extension(
    'module_name',
    extra_compile_args=['-std=c++11','-stdlib=libc++','-I/some/path/','-march=native'],
    extra_link_args=['-stdlib=libc++'],
    sources=['file.cc'],
    libraries=['boost_python','boost_numpy'])

setup(
    name='module_name',
    version='0.1',
    ext_modules=[module_name])

and run it as python setup.py build, which will create an appropriate .so file in a sub-directory of build, which you can import from python.


问:
Rails: How to "publish" a website
So, I am almost done with my website. I created it using ruby on rails on the Cloud9 IDE. Is there a way to publish it? To go on it, a user has to be signed on Cloud9 and then I need to run the code on the terminal...

```<code>rails server -b $IP -p $PORT
</code>```

How would I be able to publish my website? I am very new to rails and I have no idea.

答:
To publish your website you need to host it somewhere.

There are multiple ways to do this. For instance you can use Heroku. They provide PaaS (Platform as a service), which means they will handle the installation of the app for you and the maintenance of the virtual machine it resides (updates and whatnot).

Heroku also gives you a very nice admin view for the status of your app, online log display and some other goodies.

Another alternative would be Amazon Web Services, DigitalOcean or Linode (among many others!). They provide IaaS(Infrastructure as a Service). They only give you a virtual machine with your choice of operating system, you will have to manually publish your app and provide manual maintenance of the VM and pretty much anything including the database itself.

Using Heroku would be your best choice for the moment as they are very straightforward with the publishing part. Once you get the grip you can go to the other platforms for customization.

Title: Rails: How to "publish" a website

Body:
So, I am almost done with my website. I created it using ruby on rails on the Cloud9 IDE. Is there a way to publish it? To go on it, a user has to be signed on Cloud9 and then I need to run the code on the terminal...

rails server -b $IP -p $PORT

How would I be able to publish my website? I am very new to rails and I have no idea.


问:
Can i pop to Specific ViewController?
I am using navigation based application. I push First ViewController to Second ViewController and from Second ViewController to Third ViewController. Now I want to pop from Third ViewController to First ViewController.I am performing this task using the below code but my application crashed.

Please any body give me some proper guidelines. I can't use pop to rootViewController because it's different viewController. Thanks in advance...

In Third ViewControler i have written this:

```<code>FirstViewCtr *x=[[FirstViewCtr alloc] initWithNibName:@"FirstViewCtr" bundle:nil];
[self.navigationController popToViewController:x animated:NO];
</code>```

答:
Quick and safe Swift 3 version:

```<code>if let vc = navigationController.viewControllers.filter({ $0 is SpecificViewControllerClass }).first {
  navigationController.popToViewController(vc, animated: true)
}
</code>```

Title: Can i pop to Specific ViewController?

Body:
I am using navigation based application. I push First ViewController to Second ViewController and from Second ViewController to Third ViewController. Now I want to pop from Third ViewController to First ViewController.I am performing this task using the below code but my application crashed.

Please any body give me some proper guidelines. I can't use pop to rootViewController because it's different viewController. Thanks in advance...

In Third ViewControler i have written this:

FirstViewCtr *x=[[FirstViewCtr alloc] initWithNibName:@"FirstViewCtr" bundle:nil];
[self.navigationController popToViewController:x animated:NO];

Body:
Quick and safe Swift 3 version:

if let vc = navigationController.viewControllers.filter({ $0 is SpecificViewControllerClass }).first {
  navigationController.popToViewController(vc, animated: true)
}


问:
Is it possible to handle jQuery Mobile events in Meteor?
I want to implement a swipe-left & swipe-right event on Bootstrap list item in Meteor. Meteor uses Cordova for providing WebView for mobile app development. I wonder if it is possible to handle jQuery Mobile events like swipe, touch-hold etc. in Blaze which is Meteor's front-end library?
The following is a basic example from Meteor official TO-DO tutorial sample.

The tasks.html file is:

```<code><template name="task">
    <li class="{{#if checked}} checked {{/if}}"> <!-- set the CSS for a checked task -->
        <input type="checkbox" checked="{{checked}}">
        {{#if isOwner}}
            <button class="toggle-private">
                {{#if private}}
                    Private
                {{else}}
                    Public
                {{/if}}
            </button>
        {{/if}}

        <span class="text">{{text}}</span>
        <span class="createdBy">
            {{#if createdBy}}
                by  {{createdBy}}
            {{else}}
                by  anonymous user
            {{/if}}
        </span>
        <a class="js-delete-task" id="deletetask" href="#" >
            <i class="fa fa-trash-o pull-right" aria-hidden="true"></i>
        </a>
    </li>
</template>
</code>```

And this is its Blaze/JavaScript counterpart, tasks.js;

```<code>Template.task.helpers({
    isOwner: function () {
        console.log(`this.createdBy is ${this.createdBy}`);
        return (this.createdBy === Meteor.user().username);
    },
    private: function () {
        return this.private;
    }
});

Template.task.events({
    'click .js-check-task': function(event, template){
        if(this._id) {
            console.log("Check the task, converting to: ", !this.checked);
            Meteor.call('tasks.check', this._id, this.checked);
        }
    },
    'click .js-delete-task': function(event, template){
        console.log("Deleting the task: ", this._id);
        if(this._id) {
            console.log(`Calling deleteTask()`);
            Meteor.call('tasks.delete', this._id);
        }
    },

    'click .toggle-private': function(event, template) {
        console.log(`Toggling private`);
        if(this._id) {
            console.log(`Calling task.togglePrivate`);
            if (this.private === null || this.private === undefined)
                Meteor.call('tasks.setPrivate', this._id, false);
            else
                Meteor.call('tasks.setPrivate', this._id, this.private);
        }
    }
});
</code>```

I am seeking a way to implement the mobile swipe left/right event on the list items. If user swipes left a list item (a task) I want to display the forward or delete icons, etc.

答: I've found a nice package providing support for mobile touch events in Meteor, Blaze. Here it is; https://atmospherejs.com/chriswessels/hammer.</p>

Body:
I want to implement a swipe-left & swipe-right event on Bootstrap list item in Meteor. Meteor uses Cordova for providing WebView for mobile app development. I wonder if it is possible to handle jQuery Mobile events like swipe, touch-hold etc. in Blaze which is Meteor's front-end library?
The following is a basic example from Meteor official TO-DO tutorial sample.

The tasks.html file is:

<template name="task">

        <input type="checkbox" checked="{{checked}}">
        {{#if isOwner}}
            <button class="toggle-private">
                {{#if private}}
                    Private
                {{else}}
                    Public
                {{/if}}
            </button>
        {{/if}}

        {{text}}

            {{#if createdBy}}
                by  {{createdBy}}
            {{else}}
                by  anonymous user
            {{/if}}

</template>

And this is its Blaze/JavaScript counterpart, tasks.js;

Template.task.helpers({
    isOwner: function () {
        console.log(`this.createdBy is ${this.createdBy}`);
        return (this.createdBy === Meteor.user().username);
    },
    private: function () {
        return this.private;
    }
});

Template.task.events({
    'click .js-check-task': function(event, template){
        if(this._id) {
            console.log("Check the task, converting to: ", !this.checked);
            Meteor.call('tasks.check', this._id, this.checked);
        }
    },
    'click .js-delete-task': function(event, template){
        console.log("Deleting the task: ", this._id);
        if(this._id) {
            console.log(`Calling deleteTask()`);
            Meteor.call('tasks.delete', this._id);
        }
    },

    'click .toggle-private': function(event, template) {
        console.log(`Toggling private`);
        if(this._id) {
            console.log(`Calling task.togglePrivate`);
            if (this.private === null || this.private === undefined)
                Meteor.call('tasks.setPrivate', this._id, false);
            else
                Meteor.call('tasks.setPrivate', this._id, this.private);
        }
    }
});

I am seeking a way to implement the mobile swipe left/right event on the list items. If user swipes left a list item (a task) I want to display the forward or delete icons, etc.


问:
Android SingleChoice AlertDialog is not working properly

Can anyone help me please ? I want to remove the space (mentioned in the picture) between the choice circles and choice text for each item. I mean I'm going to stick the text of each choice to the circles . For this I have one method that is recalled in onCreate() method . Tnx in advance . Here is my code:

```<code>  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= 17)
    {
        Locale fa = new Locale ( "fa" );
        Locale.setDefault ( fa );

        Configuration config = new Configuration ();
        config.locale = fa;
        getApplicationContext ().getResources ().updateConfiguration ( config, getApplicationContext ().getResources ().getDisplayMetrics () );
    }
   //fa is a Rtl language
    getWindow ().setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );

    alert();
}

 public void alert() {
    final AlertDialog.Builder ad = new AlertDialog.Builder(this);
    ad.setTitle(" چته ؟ ");
    ad.setCancelable(false);

    ad.setSingleChoiceItems(mylist, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "you choose : " + mylist[which], Toast.LENGTH_SHORT).show();
        }
    });
    ad.setPositiveButton(" تایید ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "you confirm", Toast.LENGTH_SHORT).show();
        }

    });

    ad.setNegativeButton(" انصراف ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "you canceled it", Toast.LENGTH_SHORT).show();
        }
    });
    final AlertDialog alertDialog = ad.create();
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            Button pos = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            Button neg = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
             alertDialog.getWindow().setLayout(1000,800);
            pos.setTextSize(18f);
            neg.setTextSize(18f);

        }
    });

   alertDialog.show();
}
</code>```

答:
By looking on other questions on stackoverflow I found this answer that may help you.
Then adjust gravity and padding to achieve the wanted result.</p>

Body:
Can anyone help me please ? I want to remove the space (mentioned in the picture) between the choice circles and choice text for each item. I mean I'm going to stick the text of each choice to the circles . For this I have one method that is recalled in onCreate() method . Tnx in advance . Here is my code:

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (Build.VERSION.SDK_INT >= 17)
    {
        Locale fa = new Locale ( "fa" );
        Locale.setDefault ( fa );

        Configuration config = new Configuration ();
        config.locale = fa;
        getApplicationContext ().getResources ().updateConfiguration ( config, getApplicationContext ().getResources ().getDisplayMetrics () );
    }
   //fa is a Rtl language
    getWindow ().setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN );

    alert();
}

 public void alert() {
    final AlertDialog.Builder ad = new AlertDialog.Builder(this);
    ad.setTitle(" چته ؟ ");
    ad.setCancelable(false);

    ad.setSingleChoiceItems(mylist, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "you choose : " + mylist[which], Toast.LENGTH_SHORT).show();
        }
    });
    ad.setPositiveButton(" تایید ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "you confirm", Toast.LENGTH_SHORT).show();
        }

    });

    ad.setNegativeButton(" انصراف ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getApplicationContext(), "you canceled it", Toast.LENGTH_SHORT).show();
        }
    });
    final AlertDialog alertDialog = ad.create();
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            Button pos = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
            Button neg = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
             alertDialog.getWindow().setLayout(1000,800);
            pos.setTextSize(18f);
            neg.setTextSize(18f);

        }
    });

   alertDialog.show();
}


问:
Efficient memory usage with numpy masked arrays
I have a large ndarray X (roughly (1e3, 1e3, 1e3)), where I want to do manipulations of X including and not including particular elements of the 0th axis (for each element of the 1st and 2nd axes).  i.e. there are (1e3, 1e3) elements which I want to (at times) mask in or out.

The simplest thing to do would be to construct a masked array like,

```<code>Z = np.zeros_like(X, dtype=bool)
# assume `inds` is some indexing array which will target
#    the particular (1e3 x 1e3) elements I'm interested in
Z[inds] = True
Y = np.ma.masked_array(X, mask=Z)
</code>```

But this uses an extra gigabyte of memory just for the masking array.
Is there any way to do this without constructing a second 10^9 element array of masks?  For example, is it possible to construct a sparse-matrix for the mask?

答:
If you just want to take "clean" slices, as opposed to only taking some elements from some "rows", then you could use numeric indices instead of a mask.

E.g.:

```<code>arr = np.array([[[1,2,3,4], [5,6,7,8]], [[9,8,9,8], [7,6,7,6]]])
sub_idx = np.array([0,2])
sub_arr = arr[:, :, sub_idx]
</code>```

This is a copy of a subset of arr, namely the 0th and 2nd "slices" in the last dimension:

```<code>array([[[1, 3],
        [5, 7]],

       [[9, 9],
        [7, 7]]])
</code>```

Note that the array that defines which indexes to use is only one-dimensional, severely reducing its memory requirements. (Though of course the copy still takes up a significant chunk of memory in your case.)

Also note that this gives you a copy, so any changes you make to the result (sub_arr) do not manifest in the original array. To do that, you'd have to copy the array back over:

```<code>sub_arr[:] = 0 # Manipulate the values
arr[sub_idx] = sub_arr
</code>```

Body:
I have a large ndarray X (roughly (1e3, 1e3, 1e3)), where I want to do manipulations of X including and not including particular elements of the 0th axis (for each element of the 1st and 2nd axes).  i.e. there are (1e3, 1e3) elements which I want to (at times) mask in or out.

The simplest thing to do would be to construct a masked array like,

Z = np.zeros_like(X, dtype=bool)
# assume `inds` is some indexing array which will target
#    the particular (1e3 x 1e3) elements I'm interested in
Z[inds] = True
Y = np.ma.masked_array(X, mask=Z)

But this uses an extra gigabyte of memory just for the masking array.
Is there any way to do this without constructing a second 10^9 element array of masks?  For example, is it possible to construct a sparse-matrix for the mask?

Body:
If you just want to take "clean" slices, as opposed to only taking some elements from some "rows", then you could use numeric indices instead of a mask.

E.g.:

arr = np.array([[[1,2,3,4], [5,6,7,8]], [[9,8,9,8], [7,6,7,6]]])
sub_idx = np.array([0,2])
sub_arr = arr[:, :, sub_idx]

This is a copy of a subset of arr, namely the 0th and 2nd "slices" in the last dimension:

array([[[1, 3],
        [5, 7]],

       [[9, 9],
        [7, 7]]])

Note that the array that defines which indexes to use is only one-dimensional, severely reducing its memory requirements. (Though of course the copy still takes up a significant chunk of memory in your case.)

Also note that this gives you a copy, so any changes you make to the result (sub_arr) do not manifest in the original array. To do that, you'd have to copy the array back over:

sub_arr[:] = 0 # Manipulate the values
arr[sub_idx] = sub_arr


问:
How to mix AppDelegate with Swift 3 and Objective-c
I`m new in iOS development.

I have the next problem, the principal language for the app is Objective-c I want to delegate functions written on Swift 3, how can I do that ?

I hope you can help me.

答:
Maybe creating new project in swift for getting template for AppDelegate, and then using swift code for any manipulation in future:</p>

```<code>    @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}
</code>```

Body:
Maybe creating new project in swift for getting template for AppDelegate, and then using swift code for any manipulation in future:

    @UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

}


问:
Java: Using Array.sort() error - java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
I am trying to write a program for my course that sorts an array of objects.

Does anyone know why I am getting this error? Snippets of code included below!

Student object

```<code>/* Class for storing students */
public class Student {
  private String name;
  private int mark;

  //Constructor
  public Student(String gName, int gMark) {
    name = gName;
    mark = gMark;
  }

  //Get Mark
    public int getMark() {
    return mark;
  }
  //Compare to
   public int compareTo(Student gStudent) {
    return this.mark - (int) gStudent.getMark();
  }
</code>```

}

And putting these students in the array marks (of student objects);

```<code>  //Create array
    Student[] marks = new Student[numberOfMarks];

    //Input for each student
    for (int cItem = 0; cItem < numberOfMarks; cItem++) {
        System.out.print("Please enter student number "+(cItem + 1)+"'s name: ");
        String cName = markScanner.nextLine();
        System.out.print("Please enter "+cName+"'s mark: ");
        int cMark = markScanner.nextInt();
        //Skip line
        markScanner.nextLine();
        marks[cItem] = new Student(cName, cMark);
    }
</code>```

However the sort doesn't seem to work

```<code>//Sorting
Arrays.sort(marks);
</code>```

And produces the error:

```<code>Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    at MarkAnalysis.main(MarkAnalysis.java:33)
</code>```

And produce the error

答:
```<code>public class Student implements Comparable<Student> { }
</code>```

Also, your compareTo() method is a bit unorthodox. Typically, you want something along these lines:

```<code>     public int compareTo(Student gStudent) {
        if(this.mark > gStudent.getMark()) return 1;
        if(this.mark < gStudent.getMark()) return -1;
        return 0;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to write a program for my course that sorts an array of objects.

Does anyone know why I am getting this error? Snippets of code included below!

Student object

/* Class for storing students */
public class Student {
  private String name;
  private int mark;

  //Constructor
  public Student(String gName, int gMark) {
    name = gName;
    mark = gMark;
  }

  //Get Mark
    public int getMark() {
    return mark;
  }
  //Compare to
   public int compareTo(Student gStudent) {
    return this.mark - (int) gStudent.getMark();
  }

}

And putting these students in the array marks (of student objects);

  //Create array
    Student[] marks = new Student[numberOfMarks];

    //Input for each student
    for (int cItem = 0; cItem < numberOfMarks; cItem++) {
        System.out.print("Please enter student number "+(cItem + 1)+"'s name: ");
        String cName = markScanner.nextLine();
        System.out.print("Please enter "+cName+"'s mark: ");
        int cMark = markScanner.nextInt();
        //Skip line
        markScanner.nextLine();
        marks[cItem] = new Student(cName, cMark);
    }

However the sort doesn't seem to work

//Sorting
Arrays.sort(marks);

And produces the error:

Exception in thread "main" java.lang.ClassCastException: Student cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    at MarkAnalysis.main(MarkAnalysis.java:33)

And produce the error

Body:
public class Student implements Comparable<Student> { }

Also, your compareTo() method is a bit unorthodox. Typically, you want something along these lines:

     public int compareTo(Student gStudent) {
        if(this.mark > gStudent.getMark()) return 1;
        if(this.mark < gStudent.getMark()) return -1;
        return 0;
    }


问:
Emailing in vb.net - SMTP server issues, or anonymous emailing?
I've got an emailing system in my application which I have used fine and have seen it working.

The customer has also managed to send emails using the program, however, once they've paid for the application, they're then selling it on to other customers.

They've just taken it in to test with the first customer and they're having troubles sending emails, so I investigated the error log and saw the following message:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [BN6PR2201CA0027.namprd22.prod.outlook.com]

Now, after Googling this exact error message, the top result was this question, in which it's clear to see that the OP was trying to send a message from an email address that was hard-coded as "emailaddress". However, that isn't the case for me.

My code is as follows:

```<code>  recipient = eMail

        Smtp_Server.UseDefaultCredentials = False
        Smtp_Server.Credentials = New Net.NetworkCredential(senderAdd, senderPass)
        Smtp_Server.EnableSsl = False
        Smtp_Server.Host = SMTPserver

        AddHandler Smtp_Server.SendCompleted, AddressOf sendComplete

    e_mail = New MailMessage()
    e_mail.From = New MailAddress(senderAdd)
    e_mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess
    e_mail.To.Add(eMail)
    e_mail.Subject = subj
    e_mail.IsBodyHtml = False
    e_mail.Body = bod

 Smtp_Server.SendAsync(e_mail, userState)
</code>```

Is there anything in here which would be causing this error? If so, what is it?
The variables are all set from a database table, and if there are any null values then the system will pop a message box to alert the user of this and then exit the subroutine and not send the email, so it's not an issue with null values - The only thing I can think of is that the credentials are wrong, but they've supposedly been verified by 3 different people as correct.

答:
You might need to specify the domain.  Use this constructor of the NetworkCredential class and pass in the domain.

```<code>Smtp_Server.Credentials = New Net.NetworkCredential(senderAdd, senderPass, "expectedDomainName")
</code>```

Difficult to say for sure though because we can't reproduce this issue under your same conditions.

Body:
I've got an emailing system in my application which I have used fine and have seen it working.

The customer has also managed to send emails using the program, however, once they've paid for the application, they're then selling it on to other customers.

They've just taken it in to test with the first customer and they're having troubles sending emails, so I investigated the error log and saw the following message:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [BN6PR2201CA0027.namprd22.prod.outlook.com]

Now, after Googling this exact error message, the top result was this question, in which it's clear to see that the OP was trying to send a message from an email address that was hard-coded as "emailaddress". However, that isn't the case for me.

My code is as follows:

  recipient = eMail

        Smtp_Server.UseDefaultCredentials = False
        Smtp_Server.Credentials = New Net.NetworkCredential(senderAdd, senderPass)
        Smtp_Server.EnableSsl = False
        Smtp_Server.Host = SMTPserver

        AddHandler Smtp_Server.SendCompleted, AddressOf sendComplete

    e_mail = New MailMessage()
    e_mail.From = New MailAddress(senderAdd)
    e_mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess
    e_mail.To.Add(eMail)
    e_mail.Subject = subj
    e_mail.IsBodyHtml = False
    e_mail.Body = bod

 Smtp_Server.SendAsync(e_mail, userState)

Is there anything in here which would be causing this error? If so, what is it?
The variables are all set from a database table, and if there are any null values then the system will pop a message box to alert the user of this and then exit the subroutine and not send the email, so it's not an issue with null values - The only thing I can think of is that the credentials are wrong, but they've supposedly been verified by 3 different people as correct.

Body:
You might need to specify the domain.  Use this constructor of the NetworkCredential class and pass in the domain.

Smtp_Server.Credentials = New Net.NetworkCredential(senderAdd, senderPass, "expectedDomainName")

Difficult to say for sure though because we can't reproduce this issue under your same conditions.


问:
TabLayout with ViewPager not working as expected
There is 3 TabLayout with ViewPager in my application.

If I swipe for change Tabs then it behaves strangely.

Below is the scenario.

Let's say 3 Tabs A, B, C.

Default Tab A will open when I start App.

Go to B From A - Works OK.

Go to A From B - Works Ok.

Go To B From A - Works Ok.

Go To C From B - Works Ok.

Now Problem Starts here.

Go To B From C - It will Load A and B Both but display Only B.

Why A and B loads if I come from C ??

Below is my code.

```<code>private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ViewPagerAdapter adapter;

toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FragmentOpen(), "OPEN");
        adapter.addFragment(new FragmentClose(), "CLOSE");
        adapter.addFragment(new FragmentTest(), "TEST");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
</code>```

I want to load Tabs every time.

For that, I use below code.

```<code>viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(adapter != null){
                    adapter.getItem(position).onResume();
                }
                Toast.makeText(getApplicationContext(), "Page Selected", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
</code>```

But it will always load both tabs when I came from C.

What I want is: only Tab B must load when came from C, not Both.

答:
its Default behavior of ViewPager if you are in A then it loads B
  also and when your reach B it will Load C and A also is Loaded now
  when to reach at C its destroy the View of A and now when you come
  again to B it will Load A again, in a simple way ViewPager Maintain
  the One Next and One previous state of View by Default.

to Overcome this you should use ViewPager.setOffscreenPageLimit(number) here number is the count of page to load Simulationally for Next and Previous View.

Body:
There is 3 TabLayout with ViewPager in my application.

If I swipe for change Tabs then it behaves strangely.

Below is the scenario.

Let's say 3 Tabs A, B, C.

Default Tab A will open when I start App.

Go to B From A - Works OK.

Go to A From B - Works Ok.

Go To B From A - Works Ok.

Go To C From B - Works Ok.

Now Problem Starts here.

Go To B From C - It will Load A and B Both but display Only B.

Why A and B loads if I come from C ??

Below is my code.

private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    ViewPagerAdapter adapter;

toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

private void setupViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new FragmentOpen(), "OPEN");
        adapter.addFragment(new FragmentClose(), "CLOSE");
        adapter.addFragment(new FragmentTest(), "TEST");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

I want to load Tabs every time.

For that, I use below code.

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if(adapter != null){
                    adapter.getItem(position).onResume();
                }
                Toast.makeText(getApplicationContext(), "Page Selected", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

But it will always load both tabs when I came from C.

What I want is: only Tab B must load when came from C, not Both.


问:
Passport-jwt different tokens same result
I'm having a problem setting up my first project using passport and jwt. Using Postman I tried to sign in with different accounts but if I try to return the req.user object, it returns the same user's infos. otherwise, if I try to log jwt_payload it's right (different user's information). Can anyone explain me why? (I insert the option session: false)

my jwt strategy function:

```<code>var confStrategy = function(passport) {
  passport.use( new JwtStrategy( opts, function(jwt_payload,done) {
      User.findOne({id: jwt_payload.sub},function(err,user) {

          if(err) return done(err,none);
          if(user) {
            done(null,user);
          } else {
            done(null,false);
          }
      });
  }));
};
</code>```

the app.js snippet

```<code>app.use(passport.initialize());
passConf.confStrategy(passport);

app.get('/api/:name',passport.authenticate('jwt', { session: false }),function(req,res) {
  console.log(req.user);
  res.send('Hello ' + req.user.email);
});
</code>```

答:
You need to check the code that generates JWT token, whatever payload you set during JWT generation time. You will get same Payload with same name when JWTStrategy decode's it. (as you are getting same user every time, check if it is hard coded or not)

Below line generates JWT token

```<code>var token = jwt.sign({uid: user.id}, secretOrKey, {expiresIn: 6000});
</code>```

Below is the JWT strategy code.

```<code>passport.use(new JwtStrategy(jwtOptions, function(_payload, _next) {
  var done = false;
  if((_payload.uid)) {
   //Do something
  }
}));
</code>```

You need to keep the name same (in above case it is uid)

Body:
I'm having a problem setting up my first project using passport and jwt. Using Postman I tried to sign in with different accounts but if I try to return the req.user object, it returns the same user's infos. otherwise, if I try to log jwt_payload it's right (different user's information). Can anyone explain me why? (I insert the option session: false)

my jwt strategy function:

var confStrategy = function(passport) {
  passport.use( new JwtStrategy( opts, function(jwt_payload,done) {
      User.findOne({id: jwt_payload.sub},function(err,user) {

          if(err) return done(err,none);
          if(user) {
            done(null,user);
          } else {
            done(null,false);
          }
      });
  }));
};

the app.js snippet

app.use(passport.initialize());
passConf.confStrategy(passport);

app.get('/api/:name',passport.authenticate('jwt', { session: false }),function(req,res) {
  console.log(req.user);
  res.send('Hello ' + req.user.email);
});

Body:
You need to check the code that generates JWT token, whatever payload you set during JWT generation time. You will get same Payload with same name when JWTStrategy decode's it. (as you are getting same user every time, check if it is hard coded or not)

Below line generates JWT token

var token = jwt.sign({uid: user.id}, secretOrKey, {expiresIn: 6000});

Below is the JWT strategy code.

passport.use(new JwtStrategy(jwtOptions, function(_payload, _next) {
  var done = false;
  if((_payload.uid)) {
   //Do something
  }
}));

You need to keep the name same (in above case it is uid)


问:
Extract PDB and executable files from a symbol server using a crash dump
I'm able to debug almost any crash dump that my large organization generates because all symbols and relevant executables are stored compressed in a central symbol store location. There's never a problem until I need to send the crash dump along with all its relevant pdb's and executable files outside the company to debug a third party library.

The last time I did this, I had to perform a lot of trial and error to collect the files I needed from the symbol store, which is mostly machine organized and not very human readable. It would be great if I could open the crash dump and have Visual Studio extract and save out all the files I need from the symbol store to another folder so I can send it off for analysis.

Know of any way this can be done?

答:
I don't know a solution for Visual Studio. However, this problem can be solved with WinDbg or SymChk from the Debugging Tools for Windows which are provided by Microsoft for free.

According to my knowledge, a symbol server does only store PDBs and not executables, so the following instructions are for PDBs only.

There is a command for WinDbg, !SaveAllModules, which might work for saving all DLLs and executables which are present in the dump file. I don't have a lot experience with it.

Steps in WinDbg

On a machine with Internet connection and connection to your company's symbol server

Open the crash dump in WinDbg

Set up the symbols, e.g. add your company symbol server and the Microsoft symbol server. For the cache location, choose an empty directory.

run the commands .reload /f and ld*

This will download all available symbols into the defined directory.

Steps for SymChk

On a machine with Internet connection and connection to your company's symbol server

From a command line prompt, run

```<code>symchk /id <dumpfile>.dmp /s srv*x:\symbols\*http://msdl.microsoft.com/download/symbols /od
</code>```

Where

/id is for "input dump"

/s defines the symbol path. Make sure you get the syntax right. Don't forget to include your company symbol server

/od is for "output details" (verbose mode) to display any problems

Body:
I don't know a solution for Visual Studio. However, this problem can be solved with WinDbg or SymChk from the Debugging Tools for Windows which are provided by Microsoft for free.

According to my knowledge, a symbol server does only store PDBs and not executables, so the following instructions are for PDBs only.

There is a command for WinDbg, !SaveAllModules, which might work for saving all DLLs and executables which are present in the dump file. I don't have a lot experience with it.

Steps in WinDbg

On a machine with Internet connection and connection to your company's symbol server

Open the crash dump in WinDbg

Set up the symbols, e.g. add your company symbol server and the Microsoft symbol server. For the cache location, choose an empty directory.

run the commands .reload /f and ld*

This will download all available symbols into the defined directory.

Steps for SymChk

On a machine with Internet connection and connection to your company's symbol server

From a command line prompt, run

symchk /id <dumpfile>.dmp /s srv*x:\symbols\*http://msdl.microsoft.com/download/symbols /od

Where

/id is for "input dump"

/s defines the symbol path. Make sure you get the syntax right. Don't forget to include your company symbol server

/od is for "output details" (verbose mode) to display any problems