问:
rock paper scissors stuck in while loop
I am making rock, paper, scissors.

After 3 wins or losses, I want it to leave the while loop but it keeps running.

```<code>##################
# import modules #
##################

from random import randint

# Declaration of variables #

pcCounter, counter = 0, 0
choice = ""
pc = 0

################
# Main program #
################
print("Welcome to Dags Rock,Paper,Scissors")
print("We will be playing a best out of 5")
choice = input("Select rock, paper or scissors")

while counter != 3 or pcCounter != 3:
    if choice == "rock" or choice == "Rock":
        pc = randint(1,3)
        if pc == 1:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have lost, Paper beats rock")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have won, rock beats scissors")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
    elif choice == "paper" or choice == "Paper":
        pc = randint(1,3)
        if pc == 1:
            print("You have won, paper beats rock")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have lost, scissors beats paper")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
    else:
        pc = randint(1,3)
        if pc == 1:
            print("You have lost, rock beats scissors")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have won, scissors beats paper")
            Counter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
#Checks if you won or lost
if counter == 3:
    print("Congratz you won :)")
else:
    print("Darn you lost :(")enter code here
</code>```

答:
Your while test isn't right.  Change:

```<code>while counter != 3 or pcCounter != 3:
</code>```

to:

```<code>while counter != 3 and pcCounter != 3:
</code>```

You want to continue the loop only if neither counter is 3.

Title: rock paper scissors stuck in while loop

Body:
I am making rock, paper, scissors.

After 3 wins or losses, I want it to leave the while loop but it keeps running.

##################
# import modules #
##################

from random import randint

# Declaration of variables #

pcCounter, counter = 0, 0
choice = ""
pc = 0

################
# Main program #
################
print("Welcome to Dags Rock,Paper,Scissors")
print("We will be playing a best out of 5")
choice = input("Select rock, paper or scissors")

while counter != 3 or pcCounter != 3:
    if choice == "rock" or choice == "Rock":
        pc = randint(1,3)
        if pc == 1:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have lost, Paper beats rock")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have won, rock beats scissors")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
    elif choice == "paper" or choice == "Paper":
        pc = randint(1,3)
        if pc == 1:
            print("You have won, paper beats rock")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have lost, scissors beats paper")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
    else:
        pc = randint(1,3)
        if pc == 1:
            print("You have lost, rock beats scissors")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have won, scissors beats paper")
            Counter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
#Checks if you won or lost
if counter == 3:
    print("Congratz you won :)")
else:
    print("Darn you lost :(")enter code here

Body:
Your while test isn't right.  Change:

while counter != 3 or pcCounter != 3:

to:

while counter != 3 and pcCounter != 3:

You want to continue the loop only if neither counter is 3.


来源: stackexchange

问:
How to use skew only in the parent element?
Is there any way to use skew only in a parent element?
I need to create something like a 'diamond' as a mask and the child elements can't be affected. There is no way, in this case, to use png as a mask.
Thanks in advance!</p>

答:
the only way to achieve this is to take the child element out of the document flow using position:absolute; and putting an equal negative degree skew on the child.

The problem with this is that you will now have to resize your parent manually.

ContentLicense: CC BY-SA 3.0


问:
How to check if a username exists in a text file via File/FileWriter/Scanner classes
I'm not sure what I'm doing wrong because after running the program in my main class, it completely skips over the

```<code>while(usernameCheck.hasNext()){
    //code...
}
</code>```

loop even though I purposely put a username that's already in my "accounts.txt" file. I also tried the contains() method but obviously if I put lets say "John1" and "John" is already in my accounts.txt file, it won't accept it

```<code>import java.util.Scanner;
import java.io.*;

public class CreateAccount {

public static void newAccount() throws IOException{

    Scanner keyboard = new Scanner(System.in);
    FileWriter fw = new FileWriter("accounts.txt",true);
    PrintWriter pw = new PrintWriter(fw);

    System.out.println("Please enter a username: ");
    String user = keyboard.nextLine();

    File file = new File("accounts.txt");
    Scanner usernameCheck = new Scanner(file);

    while(usernameCheck.hasNext()){
        String existingUsername = usernameCheck.nextLine();

        if(user.equalsIgnoreCase(existingUsername)){

            System.out.println("Username already exists");
            System.out.println("Please enter a username: ");
            user = keyboard.nextLine();
        }
    }

    System.out.println("Please enter a password: ");
    String pass = keyboard.nextLine();

    System.out.println("Account created!");
</code>```

*** After reading my code I realize I also have another problem: Even if I do create a username that doesn't exist in my "accounts.txt" class, it'll keep repeating the prompt that a username already exists because of the hasNext() method. What can I do about this?

答:
I threw this in and tested it. It finds a name for me. What I would guess is happening is your file path is not true.

```<code> File file = new File("accounts.txt");
</code>```

Start by finding the full path of this text file. put the full path in, and then see how you can make the path more relative.

I hope this helps.

Body:
I'm not sure what I'm doing wrong because after running the program in my main class, it completely skips over the

while(usernameCheck.hasNext()){
    //code...
}

loop even though I purposely put a username that's already in my "accounts.txt" file. I also tried the contains() method but obviously if I put lets say "John1" and "John" is already in my accounts.txt file, it won't accept it

import java.util.Scanner;
import java.io.*;

public class CreateAccount {

public static void newAccount() throws IOException{

    Scanner keyboard = new Scanner(System.in);
    FileWriter fw = new FileWriter("accounts.txt",true);
    PrintWriter pw = new PrintWriter(fw);

    System.out.println("Please enter a username: ");
    String user = keyboard.nextLine();

    File file = new File("accounts.txt");
    Scanner usernameCheck = new Scanner(file);

    while(usernameCheck.hasNext()){
        String existingUsername = usernameCheck.nextLine();

        if(user.equalsIgnoreCase(existingUsername)){

            System.out.println("Username already exists");
            System.out.println("Please enter a username: ");
            user = keyboard.nextLine();
        }
    }

    System.out.println("Please enter a password: ");
    String pass = keyboard.nextLine();

    System.out.println("Account created!");

*** After reading my code I realize I also have another problem: Even if I do create a username that doesn't exist in my "accounts.txt" class, it'll keep repeating the prompt that a username already exists because of the hasNext() method. What can I do about this?

Body:
I threw this in and tested it. It finds a name for me. What I would guess is happening is your file path is not true.

 File file = new File("accounts.txt");

Start by finding the full path of this text file. put the full path in, and then see how you can make the path more relative.

I hope this helps.


问:
Mapbox GL JS: Style is not done loading
I have a map wher we can classically switch from one style to another, streets to satellite for example.

I want to be informed that the style is loaded to then add a layer.

According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.

That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.

My code is:

```<code>mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v10',
    center: [5,45.5],
    zoom: 7
});

map.on('load', function () {

    loadRegionMask();
});

map.on('styledataloading', function (styledata) {

    if (map.isStyleLoaded()) {
        loadRegionMask();
    }
});

$('#typeMap').on('click', function switchLayer(layer) {
    var layerId = layer.target.control.id;

    switch (layerId) {
        case 'streets':
            map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
        break;

        case 'satellite':
            map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
        break;
    }
});

function loadJSON(callback) {

  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");

  xobj.open('GET', 'regions.json', true);

  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

function loadRegionMask() {

  loadJSON(function(response) {

    var geoPoints_JSON = JSON.parse(response);

    map.addSource("region-boundaries", {
      'type': 'geojson',
      'data': geoPoints_JSON,
    });

    map.addLayer({
        'id': 'region-fill',
        'type': 'fill',
        'source': "region-boundaries",
        'layout': {},
        'paint': {
            'fill-color': '#C4633F',
            'fill-opacity': 0.5
        },
        "filter": ["==", "$type", "Polygon"]
    });
  });
}
</code>```

And the error is:

```<code>Uncaught Error: Style is not done loading
    at t._checkLoaded (mapbox-gl.js:308)
    at t.addSource (mapbox-gl.js:308)
    at e.addSource (mapbox-gl.js:390)
    at map.js:92 (map.addSource("region-boundaries",...)
    at XMLHttpRequest.xobj.onreadystatechange (map.js:63)
</code>```

Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?

答:
Use the style.load event. It will trigger once each time a new style loads.

```<code>map.on('style.load', function() {
    addLayer();
});
</code>```

Title: Mapbox GL JS: Style is not done loading

Body:
I have a map wher we can classically switch from one style to another, streets to satellite for example.

I want to be informed that the style is loaded to then add a layer.

According to the doc, I tried to wait that the style being loaded to add a layer based on a GEOJson dataset.

That works perfectly when the page is loaded which fires map.on('load') but I get an error when I just change the style, so when adding layer from map.on('styledataloading'), and I even get memory problems in Firefox.

My code is:

mapboxgl.accessToken = 'pk.token';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v10',
    center: [5,45.5],
    zoom: 7
});

map.on('load', function () {

    loadRegionMask();
});

map.on('styledataloading', function (styledata) {

    if (map.isStyleLoaded()) {
        loadRegionMask();
    }
});

$('#typeMap').on('click', function switchLayer(layer) {
    var layerId = layer.target.control.id;

    switch (layerId) {
        case 'streets':
            map.setStyle('mapbox://styles/mapbox/' + layerId + '-v10');
        break;

        case 'satellite':
            map.setStyle('mapbox://styles/mapbox/satellite-streets-v9');
        break;
    }
});

function loadJSON(callback) {

  var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");

  xobj.open('GET', 'regions.json', true);

  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

function loadRegionMask() {

  loadJSON(function(response) {

    var geoPoints_JSON = JSON.parse(response);

    map.addSource("region-boundaries", {
      'type': 'geojson',
      'data': geoPoints_JSON,
    });

    map.addLayer({
        'id': 'region-fill',
        'type': 'fill',
        'source': "region-boundaries",
        'layout': {},
        'paint': {
            'fill-color': '#C4633F',
            'fill-opacity': 0.5
        },
        "filter": ["==", "$type", "Polygon"]
    });
  });
}

And the error is:

Uncaught Error: Style is not done loading
    at t._checkLoaded (mapbox-gl.js:308)
    at t.addSource (mapbox-gl.js:308)
    at e.addSource (mapbox-gl.js:390)
    at map.js:92 (map.addSource("region-boundaries",...)
    at XMLHttpRequest.xobj.onreadystatechange (map.js:63)

Why do I get this error whereas I call loadRegionMask() after testing that the style is loaded?

Body:
Use the style.load event. It will trigger once each time a new style loads.

map.on('style.load', function() {
    addLayer();
});


问:
Logistic regression sklearn - train and apply model
I'm new to machine learning and trying Sklearn for the first time. I have two dataframes, one with data to train a logistic regression model (with 10-fold cross-validation) and another one to predict classes ('0,1') using that model.
Here's my code so far using bits of tutorials I found on Sklearn docs and on the Web:

```<code>import pandas as pd
import numpy as np
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.preprocessing import normalize
from sklearn.preprocessing import scale
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn import metrics

# Import dataframe with training data
df = pd.read_csv('summary_44.csv')
cols = df.columns.drop('num_class') # Data to use (num_class is the column with the classes)

# Import dataframe with data to predict
df_pred = pd.read_csv('new_predictions.csv')

# Scores
df_data = df.ix[:,:-1].values

# Target
df_target = df.ix[:,-1].values

# Values to predict
df_test = df_pred.ix[:,:-1].values

# Scores' names
df_data_names = cols.values

# Scaling
X, X_pred, y = scale(df_data), scale(df_test), df_target

# Define number of folds
kf = KFold(n_splits=10)
kf.get_n_splits(X) # returns the number of splitting iterations in the cross-validator

# Logistic regression normalizing variables
LogReg = LogisticRegression()

# 10-fold cross-validation
scores = [LogReg.fit(X[train], y[train]).score(X[test], y[test]) for train, test in kf.split(X)]
print scores

# Predict new
novel = LogReg.predict(X_pred)
</code>```

Is this the correct way to implement a Logistic Regression?
I know that the fit() method should be used after cross-validation in order to train the model and use it for predictions. However, since I called fit() inside a list comprehension I really don't know if my model was "fitted" and can be used to make predictions.

答:
I general things are okay, but there are some problems.

Scaling

```<code>X, X_pred, y = scale(df_data), scale(df_test), df_target
</code>```

You scale training and test data independently, which isn't correct. Both datasets must be scaled with the same scaler. "Scale" is a simple function, but it is better to use something else, for example StandardScaler.

```<code>scaler = StandardScaler()
scaler.fit(df_data)
X = scaler.transform(df_data)
X_pred = scaler.transform(df_test)
</code>```

Cross-validation and predicting.
How your code works? You split data 10 times into train and hold-out set; 10 times fit model on train set and calculate score on hold-out set. This way you get cross-validation scores, but the model is fitted only on a part of data. So it would be better to fit model on the whole dataset and then make a prediction:

```<code>LogReg.fit(X, y)
novel = LogReg.predict(X_pred)
</code>```

I want to notice that there are advanced technics like stacking and boosting, but if you learn using sklearn, then it is better to stick to the basics.

Body:
I'm new to machine learning and trying Sklearn for the first time. I have two dataframes, one with data to train a logistic regression model (with 10-fold cross-validation) and another one to predict classes ('0,1') using that model.
Here's my code so far using bits of tutorials I found on Sklearn docs and on the Web:

import pandas as pd
import numpy as np
import sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.preprocessing import normalize
from sklearn.preprocessing import scale
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn import metrics

# Import dataframe with training data
df = pd.read_csv('summary_44.csv')
cols = df.columns.drop('num_class') # Data to use (num_class is the column with the classes)

# Import dataframe with data to predict
df_pred = pd.read_csv('new_predictions.csv')

# Scores
df_data = df.ix[:,:-1].values

# Target
df_target = df.ix[:,-1].values

# Values to predict
df_test = df_pred.ix[:,:-1].values

# Scores' names
df_data_names = cols.values

# Scaling
X, X_pred, y = scale(df_data), scale(df_test), df_target

# Define number of folds
kf = KFold(n_splits=10)
kf.get_n_splits(X) # returns the number of splitting iterations in the cross-validator

# Logistic regression normalizing variables
LogReg = LogisticRegression()

# 10-fold cross-validation
scores = [LogReg.fit(X[train], y[train]).score(X[test], y[test]) for train, test in kf.split(X)]
print scores

# Predict new
novel = LogReg.predict(X_pred)

Is this the correct way to implement a Logistic Regression?
I know that the fit() method should be used after cross-validation in order to train the model and use it for predictions. However, since I called fit() inside a list comprehension I really don't know if my model was "fitted" and can be used to make predictions.

Body:
I general things are okay, but there are some problems.

Scaling

X, X_pred, y = scale(df_data), scale(df_test), df_target

You scale training and test data independently, which isn't correct. Both datasets must be scaled with the same scaler. "Scale" is a simple function, but it is better to use something else, for example StandardScaler.

scaler = StandardScaler()
scaler.fit(df_data)
X = scaler.transform(df_data)
X_pred = scaler.transform(df_test)

Cross-validation and predicting.
How your code works? You split data 10 times into train and hold-out set; 10 times fit model on train set and calculate score on hold-out set. This way you get cross-validation scores, but the model is fitted only on a part of data. So it would be better to fit model on the whole dataset and then make a prediction:

LogReg.fit(X, y)
novel = LogReg.predict(X_pred)

I want to notice that there are advanced technics like stacking and boosting, but if you learn using sklearn, then it is better to stick to the basics.


问:
In a modal what is the standard way to get image height after it is opened?
I'm using a modal to display a gallery of images.  When a thumbnail is clicked the full version of the image is displayed.  I need to determine the height of the image immediately after the modal is opened but I'm having trouble getting the correct value on the first click. On the second click my function returns the correct height.  What is the standard way to solve a problem like this?

Example

In the simplified example below a "click" event opens the modal and the function measureHeight gets the height property.  The first time I click the button it gives me a tiny number.  The second time I click the same button it gives me the correct number. I believe this is because the image is in the cache the 2nd time.

```<code>window.addEventListener("click", measureHeight);

function measureHeight() {
    var unitHeight = window.getComputedStyle(document.getElementById('target')).height;
}
</code>```

答:
The easiest way to set the height/width without preloading the images would be to get a list of images from a server that also return height/width.

So, we would make a request to the server and display a thumb for each image.

Let's assume this is how the json is returned:

```<code>[
    {
        thumb: '/img/thumb/1.jpg',
        src: '/img/large/1.jpg',
        width: 100,
        height: 100
    },
    {
        thumb: '/img/thumb/2.jpg',
        src: '/img/large/2.jpg',
        width: 200,
        height: 200
    },
    {
        thumb: '/img/thumb/3.jpg',
        src: '/img/large/3.jpg',
        width: 300,
        height: 300
    }
]
</code>```

We can then use this:

```<code>// Fetch a list of images and there info
let req = fetch('/get/image/list')
let json = await req.json()

// Loop through the resulting list of items
json.forEach(image => {
    // Create a thumbnail with attributes that describe the larger image
    let thumb = document.createElement('img')
    thumb.src = image.thumb
    thumb.setAttribute('orig-width', image.width)
    thumb.setAttribute('orig-height', image.height)
    thumb.setAttribute('orig-src', image.src)

    // Here is where we would add an event listener to the thumbnail
    thumb.addEventListener('click', e => {
        let clickTarget = e.currentTarget
        let width = clickTarget.getAttribute('orig-width')
        let height = clickTarget.getAttribute('orig-height')
        let src = clickTarget.getAttribute('orig-src')

        // Here is where you would resize
        let target = document.getElementById('target')
        target.style.height = height + 'px';

        // Next you load the image into the target
        let img = document.createElement('img')
        img.src = src
        target.appendChild(img)
    })

    // Finally add the clickable item to the document
    document.appendChild(thumb)
})
</code>```

That is a decent method for setting height/width.

If you don't have a server, you will need to hand code the html elements and put the height/width data in manually. You can then get the thumbs like this (make sure to add the class to all the thumb images):

```<code>let thumbs = document.querySelectorAll('.thumb')
</code>```

Body:
I'm using a modal to display a gallery of images.  When a thumbnail is clicked the full version of the image is displayed.  I need to determine the height of the image immediately after the modal is opened but I'm having trouble getting the correct value on the first click. On the second click my function returns the correct height.  What is the standard way to solve a problem like this?

Example

In the simplified example below a "click" event opens the modal and the function measureHeight gets the height property.  The first time I click the button it gives me a tiny number.  The second time I click the same button it gives me the correct number. I believe this is because the image is in the cache the 2nd time.

window.addEventListener("click", measureHeight);

function measureHeight() {
    var unitHeight = window.getComputedStyle(document.getElementById('target')).height;
}

Body:
The easiest way to set the height/width without preloading the images would be to get a list of images from a server that also return height/width.

So, we would make a request to the server and display a thumb for each image.

Let's assume this is how the json is returned:

[
    {
        thumb: '/img/thumb/1.jpg',
        src: '/img/large/1.jpg',
        width: 100,
        height: 100
    },
    {
        thumb: '/img/thumb/2.jpg',
        src: '/img/large/2.jpg',
        width: 200,
        height: 200
    },
    {
        thumb: '/img/thumb/3.jpg',
        src: '/img/large/3.jpg',
        width: 300,
        height: 300
    }
]

We can then use this:

// Fetch a list of images and there info
let req = fetch('/get/image/list')
let json = await req.json()

// Loop through the resulting list of items
json.forEach(image => {
    // Create a thumbnail with attributes that describe the larger image
    let thumb = document.createElement('img')
    thumb.src = image.thumb
    thumb.setAttribute('orig-width', image.width)
    thumb.setAttribute('orig-height', image.height)
    thumb.setAttribute('orig-src', image.src)

    // Here is where we would add an event listener to the thumbnail
    thumb.addEventListener('click', e => {
        let clickTarget = e.currentTarget
        let width = clickTarget.getAttribute('orig-width')
        let height = clickTarget.getAttribute('orig-height')
        let src = clickTarget.getAttribute('orig-src')

        // Here is where you would resize
        let target = document.getElementById('target')
        target.style.height = height + 'px';

        // Next you load the image into the target
        let img = document.createElement('img')
        img.src = src
        target.appendChild(img)
    })

    // Finally add the clickable item to the document
    document.appendChild(thumb)
})

That is a decent method for setting height/width.

If you don't have a server, you will need to hand code the html elements and put the height/width data in manually. You can then get the thumbs like this (make sure to add the class to all the thumb images):

let thumbs = document.querySelectorAll('.thumb')


问:
Getting reference to an exception in finally block in an iterator
Is there any way to get a reference to an exception inside a finally block in an iterator function or property that allow try..finally but not try..catch?

I'm not going to use it to change or mess with the control flow, but would like to be able to get a reference to the exception in the finally block anyway (if one was thrown), in order to read from it and possibly add stuff to the Data member.

I understand that due to nature of the compiler generated classes from iterators, it is probably not possible/allowed for the same reason why try..catch around a yield statement is not allowed in the first place. But I'm still hoping that there is maybe be some way (or even ugly trick) to get hold of the exception anyway.

Simplified example:

```<code>IEnumerable<SomeClass> Something
get
{
  try
  {
    throw new SomeException();
    yield return new SomeClass();
  }
  finally
  {
    Exception ex = ... // <= TODO - get hold of the exception here [if one was thrown]...
  }
}
</code>```

答:
This is a very interesting question.

Recall that in Linq, a lot of standard operators are provided that effectively chain together. There currently isn't one that lets you wrap custom exception handling around an inner sequence.

So my suggestion is to write a new one that allows you to specify an action that handles any exception that occurs during the execution of IEnumerator.MoveNext:

```<code>public static class EnumerableExceptions
{
    public static IEnumerable<TItem> Catch<TItem, TEx>(
        this IEnumerable<TItem> source,
        Action<TEx> handler) where TEx : Exception
    {
        using (var enumerator = source.GetEnumerator())
        {
            for (; ; )
            {
                try
                {
                    if (!enumerator.MoveNext())
                        yield break;
                }
                catch (TEx x)
                {
                    handler(x);
                    yield break;
                }

                yield return enumerator.Current;
            }
        }
    }
}
</code>```

So now supposing we had this:

```<code>public class NastyException : Exception { }

public static IEnumerable<String> StringYielder()
{
    yield return "apple";
    yield return "banana";

    throw new NastyException();

    yield return "oracle";
    yield return "grapefruit";
    yield return "microsoft";
}
</code>```

We'd like to be able to wrap all the body in a try/catch, which is sadly illegal. But what we can do is wrap the generated sequence:

```<code>public static IEnumerable<String> LoggingStringYielder()
{
    return StringYielder().Catch(
        (NastyException ex) =>
            Console.WriteLine("Exception caught: " + ex.StackTrace));
}
</code>```

That is, I get a sequence by calling the "raw" StringYielder method, and then I apply the new Catch operator to it, specifying what to do if a certain exception type occurs. Here I'm just going to print the stack trace.

So if I do this:

```<code>foreach (var str in LoggingStringYielder())
    Console.WriteLine(str);
</code>```

The program completes without crashing, and the output is:

```<code>apple
banana
Exception caught:    at ConsoleApplication7.Program.<StringYielder>.. blah
</code>```

So although you can't put a try catch around the code inside the original iterator method, you can now "wrap" it around the outside of that iterator method. It's like a non-intrusive way of injecting exception handling around the code between each yield return.

Bonus update!

To be really picky about the way I worded that last sentence:

Firstly you can throw before the first yield return and it is treated the same way, as that code executes in the first call to MoveNext. So "... the code before each..." would have been more accurate than "... the code between each...".

Secondly, a yield return may accept an expression that has to be evaluated, and which may throw during evaluation. That should be regarded as code that executes before the yield return occurs, even though syntactically it appears after it.

ContentLicense: CC BY-SA 2.5

Body:
Is there any way to get a reference to an exception inside a finally block in an iterator function or property that allow try..finally but not try..catch?

I'm not going to use it to change or mess with the control flow, but would like to be able to get a reference to the exception in the finally block anyway (if one was thrown), in order to read from it and possibly add stuff to the Data member.

I understand that due to nature of the compiler generated classes from iterators, it is probably not possible/allowed for the same reason why try..catch around a yield statement is not allowed in the first place. But I'm still hoping that there is maybe be some way (or even ugly trick) to get hold of the exception anyway.

Simplified example:

IEnumerable<SomeClass> Something
get
{
  try
  {
    throw new SomeException();
    yield return new SomeClass();
  }
  finally
  {
    Exception ex = ... // <= TODO - get hold of the exception here [if one was thrown]...
  }
}

Body:
This is a very interesting question.

Recall that in Linq, a lot of standard operators are provided that effectively chain together. There currently isn't one that lets you wrap custom exception handling around an inner sequence.

So my suggestion is to write a new one that allows you to specify an action that handles any exception that occurs during the execution of IEnumerator.MoveNext:

public static class EnumerableExceptions
{
    public static IEnumerable<TItem> Catch<TItem, TEx>(
        this IEnumerable<TItem> source,
        Action<TEx> handler) where TEx : Exception
    {
        using (var enumerator = source.GetEnumerator())
        {
            for (; ; )
            {
                try
                {
                    if (!enumerator.MoveNext())
                        yield break;
                }
                catch (TEx x)
                {
                    handler(x);
                    yield break;
                }

                yield return enumerator.Current;
            }
        }
    }
}

So now supposing we had this:

public class NastyException : Exception { }

public static IEnumerable<String> StringYielder()
{
    yield return "apple";
    yield return "banana";

    throw new NastyException();

    yield return "oracle";
    yield return "grapefruit";
    yield return "microsoft";
}

We'd like to be able to wrap all the body in a try/catch, which is sadly illegal. But what we can do is wrap the generated sequence:

public static IEnumerable<String> LoggingStringYielder()
{
    return StringYielder().Catch(
        (NastyException ex) =>
            Console.WriteLine("Exception caught: " + ex.StackTrace));
}

That is, I get a sequence by calling the "raw" StringYielder method, and then I apply the new Catch operator to it, specifying what to do if a certain exception type occurs. Here I'm just going to print the stack trace.

So if I do this:

foreach (var str in LoggingStringYielder())
    Console.WriteLine(str);

The program completes without crashing, and the output is:

apple
banana
Exception caught:    at ConsoleApplication7.Program.<StringYielder>.. blah

So although you can't put a try catch around the code inside the original iterator method, you can now "wrap" it around the outside of that iterator method. It's like a non-intrusive way of injecting exception handling around the code between each yield return.

Bonus update!

To be really picky about the way I worded that last sentence:

Firstly you can throw before the first yield return and it is treated the same way, as that code executes in the first call to MoveNext. So "... the code before each..." would have been more accurate than "... the code between each...".

Secondly, a yield return may accept an expression that has to be evaluated, and which may throw during evaluation. That should be regarded as code that executes before the yield return occurs, even though syntactically it appears after it.


问:
What does runtime implementation of interace for System.Array class mean in .Net?
From the documentation:

[...] the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools.

Is this available to c# developers. I mean can I provide run time implementation to any interface on a class?

答:
Yes, arrays are special and behave exactly as linked documentation says.

No, you can't add arbitrary (or even specific) interfaces to classes at run-time unless you are creating your own implementation of CLR.

Note that there are many ways to mimic behavior of adding interfaces like extension methods or wrapping objects with proxy classes but there is no true way to add interface to a class dynamically.


问:
how to separated One column to two with cases
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

```<code> select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number
</code>```

答:
Your original query would output the strings 'soaking in' or 'soaking out', but what is needed in those case expressions (after then) is the column [Qty] and it is that value which will be returned from the case expression.

What I don't know is which table [Qty] comes from but I assume it is the detail table (b) otherwise there isn't much point in joining that detail table.

```<code>SELECT
      a.[Doc_Type]
    , a.[batch]
    , CASE a.[Doc_Type] WHEN 'BB' THEN b.Qty END [soaking out]
    , CASE a.[Doc_Type] WHEN 'AA' THEN b.Qty END [soaking in]
FROM Transaction_Hdr a
JOIN Transaction_dtl b ON a.Doc_Number = b.Doc_Number
ORDER BY
      a.[Doc_Type]
    , a.[batch]
</code>```

But: a "detail" table and a "header" table usually indicates many rows of detail for a single header. So you might need a SUM() and GROUP BY

```<code>SELECT
      h.[Doc_Type]
    , h.[batch]
    , SUM(CASE h.[Doc_Type] WHEN 'BB' THEN d.Qty END) [soaking out]
    , SUM(CASE h.[Doc_Type] WHEN 'AA' THEN d.Qty END) [soaking in]
FROM Transaction_Hdr h
JOIN Transaction_dtl d ON h.Doc_Number = d.Doc_Number
GROUP BY
      h.[Doc_Type]
    , h.[batch]
ORDER BY
      h.[Doc_Type]
    , h.[batch]
</code>```

Note I have now used aliases "h" = "header" and "d" = "detail" as I am really not keen of aliases that rely on a sequence within the query (as that sequence can get messed with very easily). I find it way easier for an alias to easily identify its associated table by "first letter of each word in a table's name" or similar.

Body:
I have a table and I would want to separate the data to multiple columns, how i can do it ?

I tried this:

 select a.[batch],a.[Doc_Type],
    Soaking Out =
      CASE a.[Doc_Type]
         WHEN 'BB' THEN 'Soaking Out'
      END,

        Soaking In =
      CASE a.[Doc_Type]
         WHEN 'AA' THEN 'Soaking In'
      END,

     FROM Transaction_Hdr a JOIN Transaction_dtl b
on a.Doc_Number=b.Doc_Number

Body:
Your original query would output the strings 'soaking in' or 'soaking out', but what is needed in those case expressions (after then) is the column [Qty] and it is that value which will be returned from the case expression.

What I don't know is which table [Qty] comes from but I assume it is the detail table (b) otherwise there isn't much point in joining that detail table.

SELECT
      a.[Doc_Type]
    , a.[batch]
    , CASE a.[Doc_Type] WHEN 'BB' THEN b.Qty END [soaking out]
    , CASE a.[Doc_Type] WHEN 'AA' THEN b.Qty END [soaking in]
FROM Transaction_Hdr a
JOIN Transaction_dtl b ON a.Doc_Number = b.Doc_Number
ORDER BY
      a.[Doc_Type]
    , a.[batch]

But: a "detail" table and a "header" table usually indicates many rows of detail for a single header. So you might need a SUM() and GROUP BY

SELECT
      h.[Doc_Type]
    , h.[batch]
    , SUM(CASE h.[Doc_Type] WHEN 'BB' THEN d.Qty END) [soaking out]
    , SUM(CASE h.[Doc_Type] WHEN 'AA' THEN d.Qty END) [soaking in]
FROM Transaction_Hdr h
JOIN Transaction_dtl d ON h.Doc_Number = d.Doc_Number
GROUP BY
      h.[Doc_Type]
    , h.[batch]
ORDER BY
      h.[Doc_Type]
    , h.[batch]

Note I have now used aliases "h" = "header" and "d" = "detail" as I am really not keen of aliases that rely on a sequence within the query (as that sequence can get messed with very easily). I find it way easier for an alias to easily identify its associated table by "first letter of each word in a table's name" or similar.


问:
Look if points at given coordinates are True in a matrix
I have a numpy matrix A of size MxN of bool type.
Than I have an array B of ROWSx2 that contains, in each row, a pair of coordinates x,y. I would like to find the list of coordinates of the matrix A whose index is contained in the array A and whose value is equal to True.
I try with this command but it returns a 3d dimensional array and I don't understand why:</p>

```<code>intersections = A[A[B] == True]
</code>```

答:
IIUC you can index into the A with B with a tuple version or a sliced version to get the mask of the valid coordinates in B, like so -

```<code>mask = A[tuple(B.T)] #or A[B[:,0], B[:,1]]
</code>```

Then, index into B for the valid coordinates -

```<code>out = B[mask]
</code>```

Sample run -

```<code>In [43]: A
Out[43]:
array([[False,  True,  True,  True,  True],
       [ True,  True,  True, False,  True],
       [False, False, False,  True, False],
       [ True,  True,  True, False,  True],
       [False,  True, False,  True,  True],
       [False,  True,  True,  True,  True]], dtype=bool)

In [44]: B
Out[44]:
array([[5, 4],
       [1, 3],
       [4, 4],
       [5, 4]])

In [45]: mask = A[tuple(B.T)]

# Mask of valid B coordinates
In [47]: mask
Out[47]: array([ True, False,  True,  True], dtype=bool)

In [46]: B[mask]
Out[46]:
array([[5, 4],  # [1,3] gone because A[1,3] = False
       [4, 4],
       [5, 4]])
</code>```

Body:
I have a numpy matrix A of size MxN of bool type.
Than I have an array B of ROWSx2 that contains, in each row, a pair of coordinates x,y. I would like to find the list of coordinates of the matrix A whose index is contained in the array A and whose value is equal to True.
I try with this command but it returns a 3d dimensional array and I don't understand why:

intersections = A[A[B] == True]

Body:
IIUC you can index into the A with B with a tuple version or a sliced version to get the mask of the valid coordinates in B, like so -

mask = A[tuple(B.T)] #or A[B[:,0], B[:,1]]

Then, index into B for the valid coordinates -

out = B[mask]

Sample run -

In [43]: A
Out[43]:
array([[False,  True,  True,  True,  True],
       [ True,  True,  True, False,  True],
       [False, False, False,  True, False],
       [ True,  True,  True, False,  True],
       [False,  True, False,  True,  True],
       [False,  True,  True,  True,  True]], dtype=bool)

In [44]: B
Out[44]:
array([[5, 4],
       [1, 3],
       [4, 4],
       [5, 4]])

In [45]: mask = A[tuple(B.T)]

# Mask of valid B coordinates
In [47]: mask
Out[47]: array([ True, False,  True,  True], dtype=bool)

In [46]: B[mask]
Out[46]:
array([[5, 4],  # [1,3] gone because A[1,3] = False
       [4, 4],
       [5, 4]])


问:
Count max occurence of character in pandas dataframe
Im looking to find the max amount of ! in a dataframe and im not 100% sure if i have the right code:</p>

```<code>finefoods_df['Review'].max().count("!")
</code>```

答:
Use str.count and then find its max:

```<code>finefoods_df['Review'].str.count('!').max()
</code>```

Demo

```<code>df
         A
0      hi!
1  hello!!
2   bye!!!

df.A.str.count('!')

0    1
1    2
2    3
Name: A, dtype: int64

df.A.str.count('!').max()
3
</code>```

Body:
Im looking to find the max amount of ! in a dataframe and im not 100% sure if i have the right code:

finefoods_df['Review'].max().count("!")

Body:
Use str.count and then find its max:

finefoods_df['Review'].str.count('!').max()

Demo

df
         A
0      hi!
1  hello!!
2   bye!!!

df.A.str.count('!')

0    1
1    2
2    3
Name: A, dtype: int64

df.A.str.count('!').max()
3


问:
REACT router not working inside child components
I am new to REACT. I have created a REACT project which has three routes as show below

```<code><Route exact path="/" component={Welcome} />
<Route path="/list" render={()=> (
  <UserList store={store} />
)} />
<Route path="/create" render={({history})=> (
  <CreateUser store={store} history={history} />
)} />
</code>```

But when i move the Route to a child component, it stopped working, I moved the code below to my listcomponent.

```<code><Route path="/create" render={({history})=> (
  <CreateUser store={store} history={history} />
)} />
</code>```

After this the link redirects to /create but the component is not getting loaded.

help much appreciated.

Entire App Component

```<code>class App extends Component {
  render() {
    return (
      <div className="App">
        <br />
        <div>
          <Link to="/">Home</Link> |
          <Link to="/list">User List</Link> |
          <Link to="/create">Add User</Link> |
        </div>
        <br />
        <Route exact path="/" component={Welcome} />
        <Route path="/list" render={()=> (
          <UserList store={store} />
        )} />
        <Route path="/create" render={({history})=> (
          <CreateUser store={store} history={history} />
        )} />
        <Route path="/edit/:id" render={({history, match}) => (
          <EditUser store={store} history={history} match={match} />
        )}/>
      </div>
    );
  }
}
</code>```

Now when i move the CreateUser route to my editUser component like shown below.

```<code>render() {
    return <div>
        <form onSubmit={this.updateUser}>
            <input type="text"name="username" ref={(input)=>this.usernameTxt = input} placeholder="Username" /><br />
            <input type="text"name="location" ref={(input)=>this.locationTxt = input} placeholder="Location" /><br />
            <button>Update user</button>
        </form>
        <Route path="/create" render={({history})=> (
            <CreateUser store={store} history={history} />
        )} />
    </div>
}
</code>```

Now it will stop showing the createform

答:
You dont have to pass the history prop to the component of the
  router.By default this prop will be passed by the react router.

I used redux as my store in this following example.You dont have to pass the store  to  every component to access the store.Just add the provider with your store as the prop to the root of your component.

For working example

https://codesandbox.io/s/9jvz19949r

Body:
I am new to REACT. I have created a REACT project which has three routes as show below

<Route exact path="/" component={Welcome} />
<Route path="/list" render={()=> (
  <UserList store={store} />
)} />
<Route path="/create" render={({history})=> (
  <CreateUser store={store} history={history} />
)} />

But when i move the Route to a child component, it stopped working, I moved the code below to my listcomponent.

<Route path="/create" render={({history})=> (
  <CreateUser store={store} history={history} />
)} />

After this the link redirects to /create but the component is not getting loaded.

help much appreciated.

Entire App Component

class App extends Component {
  render() {
    return (

          <Link to="/">Home</Link> |
          <Link to="/list">User List</Link> |
          <Link to="/create">Add User</Link> |

        <Route exact path="/" component={Welcome} />
        <Route path="/list" render={()=> (
          <UserList store={store} />
        )} />
        <Route path="/create" render={({history})=> (
          <CreateUser store={store} history={history} />
        )} />
        <Route path="/edit/:id" render={({history, match}) => (
          <EditUser store={store} history={history} match={match} />
        )}/>

    );
  }
}

Now when i move the CreateUser route to my editUser component like shown below.

render() {
    return

        <form onSubmit={this.updateUser}>
            <input type="text"name="username" ref={(input)=>this.usernameTxt = input} placeholder="Username" />

            <input type="text"name="location" ref={(input)=>this.locationTxt = input} placeholder="Location" />

            <button>Update user</button>
        </form>
        <Route path="/create" render={({history})=> (
            <CreateUser store={store} history={history} />
        )} />

}

Now it will stop showing the createform


问:
Java Socket Programming in Overrided Start Function
I am new to using JavaFx and its functionality. I am creating a 2 player checkers game that is played by local connection. I understand that in JavaFX you do not need a main class because the @Override on the start function basically serves as your main. Right now I have my connection trying to be made in that start function but it keeps spitting back java.net.BindException and java.lang.RuntimeException every time I try. I looked at my ports and it is not in use. I commented out the connection portion of the code and the app was able to run. Are you not able to connect in the start function?

Client Code:

```<code> @Override
   public void start(Stage primaryStage) throws Exception, ClassNotFoundException, IOException,UnknownHostException {
       Scene scene1 = new Scene(createContent());
       primaryStage.setTitle("Client Side");
       primaryStage.setScene(scene1);
       primaryStage.show();

       socket = new Socket("127.0.0.1",1337);

       boolean end = false;
       boolean turn = true;
       Serializable ObjectInputStream;
        ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
        Serializable ObjectOutputStream;
        ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
        Scanner scan = new Scanner(socket.getInputStream());
        PrintStream p = new PrintStream(socket.getOutputStream());
       do
       {

        while(turn == true)
           {
               temp1 = scan.nextInt();
               temp2 = scan.nextInt();
               Checker check = (Checker) I.readObject();
               check.relocate(temp1, temp2);
               turn = false;
           }
           while(turn == false)
           {

               p.println(sendX);
               p.println(sendY);
               o.writeObject(sendO);
               turn = true;

           }

       }while(end == false);

   }
</code>```

Server Code is just reverse of that:

```<code>   @Override
   public void start(Stage primaryStage) throws Exception,
   ClassNotFoundException, IOException,UnknownHostException {
   Scene scene = new Scene(createContent());
   primaryStage.setTitle("Server Side");
   primaryStage.setScene(scene);
   primaryStage.show();

   serverSocket = new ServerSocket(1337);
   Socket socket = serverSocket.accept();
   boolean end = false;
   boolean turn = true;
   Serializable ObjectInputStream;
   Serializable ObjectOutputStream;
    ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
    ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
    Scanner scan = new Scanner(socket.getInputStream());
    PrintStream p = new PrintStream(socket.getOutputStream());
   do
   {

    while(turn == true)
       {
        p.println(sendX);
        p.println(sendY);
        o.writeObject(sendO);
        turn = false;
       }
       while(turn == false)
       {

        temp1 = scan.nextInt();
        temp2 = scan.nextInt();
        Checker check = (Checker) I.readObject();
        check.relocate(temp1, temp2);
        turn = true;

       }

   }while(end == false);

   }
</code>```

答:
you can try to have another process bound to the same port.

TCPView (Windows only) from Windows Sysinternals is my favorite app whenever I have a JVM_BIND error. It shows which processes are listening to which port. It also provides a convenient context menu to either kill the process or close the connection that is getting in the way.

Body:
I am new to using JavaFx and its functionality. I am creating a 2 player checkers game that is played by local connection. I understand that in JavaFX you do not need a main class because the @Override on the start function basically serves as your main. Right now I have my connection trying to be made in that start function but it keeps spitting back java.net.BindException and java.lang.RuntimeException every time I try. I looked at my ports and it is not in use. I commented out the connection portion of the code and the app was able to run. Are you not able to connect in the start function?

Client Code:

 @Override
   public void start(Stage primaryStage) throws Exception, ClassNotFoundException, IOException,UnknownHostException {
       Scene scene1 = new Scene(createContent());
       primaryStage.setTitle("Client Side");
       primaryStage.setScene(scene1);
       primaryStage.show();

       socket = new Socket("127.0.0.1",1337);

       boolean end = false;
       boolean turn = true;
       Serializable ObjectInputStream;
        ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
        Serializable ObjectOutputStream;
        ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
        Scanner scan = new Scanner(socket.getInputStream());
        PrintStream p = new PrintStream(socket.getOutputStream());
       do
       {

        while(turn == true)
           {
               temp1 = scan.nextInt();
               temp2 = scan.nextInt();
               Checker check = (Checker) I.readObject();
               check.relocate(temp1, temp2);
               turn = false;
           }
           while(turn == false)
           {

               p.println(sendX);
               p.println(sendY);
               o.writeObject(sendO);
               turn = true;

           }

       }while(end == false);

   }

Server Code is just reverse of that:

   @Override
   public void start(Stage primaryStage) throws Exception,
   ClassNotFoundException, IOException,UnknownHostException {
   Scene scene = new Scene(createContent());
   primaryStage.setTitle("Server Side");
   primaryStage.setScene(scene);
   primaryStage.show();

   serverSocket = new ServerSocket(1337);
   Socket socket = serverSocket.accept();
   boolean end = false;
   boolean turn = true;
   Serializable ObjectInputStream;
   Serializable ObjectOutputStream;
    ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
    ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
    Scanner scan = new Scanner(socket.getInputStream());
    PrintStream p = new PrintStream(socket.getOutputStream());
   do
   {

    while(turn == true)
       {
        p.println(sendX);
        p.println(sendY);
        o.writeObject(sendO);
        turn = false;
       }
       while(turn == false)
       {

        temp1 = scan.nextInt();
        temp2 = scan.nextInt();
        Checker check = (Checker) I.readObject();
        check.relocate(temp1, temp2);
        turn = true;

       }

   }while(end == false);

   }


问:
A network-related or instance-specific error occurred while establishing a connection to SQL Server
```<code>A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
</code>```

when i upload my site on webserver and connect with remote sqlserver2005 using connection string....

```<code><connectionStrings>
    <remove name="ConnectionString"/>
    <add name="ConnectionString" connectionString="Data Source=69.16.253.19,1433;Initial Catalog=vb_usa;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</code>```

it produces the following errr --
you can see error in my webpage :

http://vbi.volvobusesindia.com

it shows an error above ..

i m using aspnetdb.mdf in my website in APP_Data Folder... features i use in my website is Login Control, Password recovery, signup control...

答:
See the guide in this site http://www.connectionstrings.com/sql-server-2005

In particular look at the section on that page titled "Attach a database file, located in the data directory, on connect to a local SQL Server Express instance"

The format is:

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;
  Database=dbname;Trusted_Connection=Yes;

Basically, you need to connect to the SQL Express instance installed on the web server and point it to where your database file is located.

Body:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

when i upload my site on webserver and connect with remote sqlserver2005 using connection string....

<connectionStrings>
    <remove name="ConnectionString"/>
    <add name="ConnectionString" connectionString="Data Source=69.16.253.19,1433;Initial Catalog=vb_usa;Persist Security Info=True;User ID=username;Password=password" providerName="System.Data.SqlClient"/>
  </connectionStrings>

it produces the following errr --
you can see error in my webpage :

http://vbi.volvobusesindia.com

it shows an error above ..

i m using aspnetdb.mdf in my website in APP_Data Folder... features i use in my website is Login Control, Password recovery, signup control...


问:
Django ModuleNotFoundError
I can't make a simple Django project work at all. I get the same error as listed in this question which I found:

Python/Django =- ModuleNotFoundError: No module named 'restaurants'

The only difference for me is that it says "No module named entries". This doesn't seem to have a resolution and I don't understand the comment on it either.

My directory structure is like this:

```<code>app
|- manage.py
|- app
    |- __init__.py
    |- entries
    |    |- __init__.py
    |    |- apps.py
    |    |- models.py
    |    |- views.py
    |    |- admin.py
    |    |- tests.py
    |    |- migrations - __init__.py
    |
    |- urls.py
    |- settings.py
    |- __pycache__
    |- wsgi.py
</code>```

I have added the entries app to the INSTALLED_APPS list in settings.py. But from there it just seems to run into a problem.

I have been trying to work this out for ages and I just don't get it (even though it is probably easy).

UPDATE
This is the exact stacktrace I am getting:

```<code>Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'entries'
</code>```

Update 2:
This is my INSTALLED_APPS:

```<code>INSTALLED_APPS = [
    'rest_framework',
    'entries.apps.EntriesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
</code>```

I have tried using just entries as well. Which gives the same error.

答:
It looks like your entries directory is in the wrong place.  You should move it up one level, so it's app/entries instead of app/app/entries.

(You are correct that 'entries.apps.EntriesConfig' is a valid way to add to INSTALLED_APPS.)

Title: Django ModuleNotFoundError

Body:
I can't make a simple Django project work at all. I get the same error as listed in this question which I found:

Python/Django =- ModuleNotFoundError: No module named 'restaurants'

The only difference for me is that it says "No module named entries". This doesn't seem to have a resolution and I don't understand the comment on it either.

My directory structure is like this:

app
|- manage.py
|- app
    |- __init__.py
    |- entries
    |    |- __init__.py
    |    |- apps.py
    |    |- models.py
    |    |- views.py
    |    |- admin.py
    |    |- tests.py
    |    |- migrations - __init__.py
    |
    |- urls.py
    |- settings.py
    |- __pycache__
    |- wsgi.py

I have added the entries app to the INSTALLED_APPS list in settings.py. But from there it just seems to run into a problem.

I have been trying to work this out for ages and I just don't get it (even though it is probably easy).

UPDATE
This is the exact stacktrace I am getting:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute
    django.setup()
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/Users/maximus/.virtualenvs/piglet/lib/python3.6/site-packages/django/apps/config.py", line 94, in create
    module = import_module(entry)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'entries'

Update 2:
This is my INSTALLED_APPS:

INSTALLED_APPS = [
    'rest_framework',
    'entries.apps.EntriesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

I have tried using just entries as well. Which gives the same error.


问:
How to specify a cache validator for PNG files in .htaccess?
I would like to cache all images and videos on the website for at least a month at user cache to speed up the loading process.

But the http://gtmetrix.com Speed Report gives me following error:

The following resources are missing a cache validator. Resources that
  do not specify a cache validator cannot be refreshed efficiently.
  Specify a Last-Modified or ETag header to enable cache validation for
  the following resources:

// all *.png files currently on my page listed here //

Expiration times:

```<code>### CACHING ###
<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresDefault "access plus 1 month"
# cache.appcache needs re-requests in FF 3.6 (thx Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest "access plus 0 seconds"
  ExpiresByType text/html "access plus 0 seconds"
  ExpiresByType text/xml "access plus 0 seconds"
  ExpiresByType application/xml "access plus 0 seconds"
  ExpiresByType application/json "access plus 0 seconds"
  ExpiresByType application/rss+xml "access plus 1 hour"
# media: favicon, images, video, audio
  ExpiresByType image/x-icon "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"
# htc files  (css3pie)
  ExpiresByType text/x-component "access plus 1 month"
# webfonts
  ExpiresByType font/truetype "access plus 1 month"
  ExpiresByType font/opentype "access plus 1 month"
  ExpiresByType application/x-font-woff "access plus 1 month"
  ExpiresByType image/svg+xml "access plus 1 month"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
# css and javascript
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType application/javascript "access plus 1 week"
  ExpiresByType text/javascript "access plus 1 week"
</code>```

Cache control:

```<code>  <IfModule mod_headers.c>
    <FilesMatch "\.(ico|pdf|flv|jpe?g|png|gif|swf|ogg)$">
      Header set Cache-Control "max-age=2592000, public"
      Header unset Last-Modified
      Header unset ETag
      FileETag None
    </FilesMatch>
    <FilesMatch "\.(css)$">
      Header set Cache-Control "max-age=604800, public"
    </FilesMatch>
    <FilesMatch "\.(js)$">
      Header set Cache-Control "max-age=604800, private"
    </FilesMatch>
    <FilesMatch "\.(xml|txt)$">
      Header set Cache-Control "max-age=216000, public, must-revalidate"
    </FilesMatch>
    <FilesMatch "\.(x?html?|php)$">
      Header set Cache-Control "max-age=1, private, must-revalidate"
    </FilesMatch>
    <FilesMatch "\.(eot|font.css|otf|ttc|ttf|woff)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
  </IfModule>
</IfModule>
### / CACHING ###
</code>```

What can I do to fix it?

BTW i found this: htaccess 'Header unset Last-Modified' caching issue but it looks like the guy doesn't have a problem with images

答:
Given this warning:

Specify a Last-Modified or ETag header to enable cache
validation for the following resource

I suspect these lines in your config is the culprit:

Header unset Last-Modified

Header unset ETag

FileETag None

Your config is removing the header info used for cache validation.

Body:
I would like to cache all images and videos on the website for at least a month at user cache to speed up the loading process.

But the http://gtmetrix.com Speed Report gives me following error:

The following resources are missing a cache validator. Resources that
  do not specify a cache validator cannot be refreshed efficiently.
  Specify a Last-Modified or ETag header to enable cache validation for
  the following resources:

// all *.png files currently on my page listed here //

Expiration times:

### CACHING ###
<IfModule mod_expires.c>
  ExpiresActive on
  ExpiresDefault "access plus 1 month"
# cache.appcache needs re-requests in FF 3.6 (thx Remy ~Introducing HTML5)
  ExpiresByType text/cache-manifest "access plus 0 seconds"
  ExpiresByType text/html "access plus 0 seconds"
  ExpiresByType text/xml "access plus 0 seconds"
  ExpiresByType application/xml "access plus 0 seconds"
  ExpiresByType application/json "access plus 0 seconds"
  ExpiresByType application/rss+xml "access plus 1 hour"
# media: favicon, images, video, audio
  ExpiresByType image/x-icon "access plus 1 month"
  ExpiresByType image/gif "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType image/jpg "access plus 1 month"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType video/ogg "access plus 1 month"
  ExpiresByType audio/ogg "access plus 1 month"
  ExpiresByType video/mp4 "access plus 1 month"
  ExpiresByType video/webm "access plus 1 month"
# htc files  (css3pie)
  ExpiresByType text/x-component "access plus 1 month"
# webfonts
  ExpiresByType font/truetype "access plus 1 month"
  ExpiresByType font/opentype "access plus 1 month"
  ExpiresByType application/x-font-woff "access plus 1 month"
  ExpiresByType image/svg+xml "access plus 1 month"
  ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
# css and javascript
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType application/javascript "access plus 1 week"
  ExpiresByType text/javascript "access plus 1 week"

Cache control:

  <IfModule mod_headers.c>
    <FilesMatch "\.(ico|pdf|flv|jpe?g|png|gif|swf|ogg)$">
      Header set Cache-Control "max-age=2592000, public"
      Header unset Last-Modified
      Header unset ETag
      FileETag None
    </FilesMatch>
    <FilesMatch "\.(css)$">
      Header set Cache-Control "max-age=604800, public"
    </FilesMatch>
    <FilesMatch "\.(js)$">
      Header set Cache-Control "max-age=604800, private"
    </FilesMatch>
    <FilesMatch "\.(xml|txt)$">
      Header set Cache-Control "max-age=216000, public, must-revalidate"
    </FilesMatch>
    <FilesMatch "\.(x?html?|php)$">
      Header set Cache-Control "max-age=1, private, must-revalidate"
    </FilesMatch>
    <FilesMatch "\.(eot|font.css|otf|ttc|ttf|woff)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
  </IfModule>
</IfModule>
### / CACHING ###

What can I do to fix it?

BTW i found this: htaccess 'Header unset Last-Modified' caching issue but it looks like the guy doesn't have a problem with images


问:
Can't get :after transition to work
I can't seem to get the opacity transition to work on an :after pseudo-element, but the same transition on the :before element works perfectly fine. Any help is appreciated!</p>

```<code>.top-nav li a:hover:after {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 0.2s;
    margin-left: 10px;
}

.top-nav li a:after {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-left: 10px;
    position: absolute;
}

.top-nav li a:hover:before {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 0.2s;
    margin-right: 10px;
}

.top-nav li a:before {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-right: 10px;
}
</code>```

答:
It's Working try to give width to li then It will display

.top-nav li a:hover:after {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 2s;
    margin-left: 10px;

}

.top-nav li a:after {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-left: 10px;
    position: absolute;
}

.top-nav li a:hover:before {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 0.2s;
    margin-right: 10px;
}

.top-nav li a:before {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-right: 10px;
}

.top-nav {
  list-style: none;
}
.top-nav li {
  float: left;
  position: relative;
  background:white;
  width:85px;
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="top-nav">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul></code>```

Title: Can't get :after transition to work

Body:
I can't seem to get the opacity transition to work on an :after pseudo-element, but the same transition on the :before element works perfectly fine. Any help is appreciated!

.top-nav li a:hover:after {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 0.2s;
    margin-left: 10px;
}

.top-nav li a:after {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-left: 10px;
    position: absolute;
}

.top-nav li a:hover:before {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 0.2s;
    margin-right: 10px;
}

.top-nav li a:before {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-right: 10px;
}

Body:
It's Working try to give width to li then It will display

.top-nav li a:hover:after {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 2s;
    margin-left: 10px;

}

.top-nav li a:after {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-left: 10px;
    position: absolute;
}

.top-nav li a:hover:before {
    content: "/";
    display: inline-block;
    opacity: 1;
    transition: opacity 0.2s;
    margin-right: 10px;
}

.top-nav li a:before {
    content: "/";
    display: inline-block;
    opacity: 0;
    transition: opacity 0.2s;
    margin-right: 10px;
}

.top-nav {
  list-style: none;
}
.top-nav li {
  float: left;
  position: relative;
  background:white;
  width:85px;
  text-align:center;
}

<ul class="top-nav">
<li><a href="#">One</a></li>
<li><a href="#">Two</a></li>
<li><a href="#">Three</a></li>
<li><a href="#">Four</a></li>
</ul>


问:
rock paper scissors stuck in while loop
I am making rock, paper, scissors.

After 3 wins or losses, I want it to leave the while loop but it keeps running.

```<code>##################
# import modules #
##################

from random import randint

# Declaration of variables #

pcCounter, counter = 0, 0
choice = ""
pc = 0

################
# Main program #
################
print("Welcome to Dags Rock,Paper,Scissors")
print("We will be playing a best out of 5")
choice = input("Select rock, paper or scissors")

while counter != 3 or pcCounter != 3:
    if choice == "rock" or choice == "Rock":
        pc = randint(1,3)
        if pc == 1:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have lost, Paper beats rock")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have won, rock beats scissors")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
    elif choice == "paper" or choice == "Paper":
        pc = randint(1,3)
        if pc == 1:
            print("You have won, paper beats rock")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have lost, scissors beats paper")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
    else:
        pc = randint(1,3)
        if pc == 1:
            print("You have lost, rock beats scissors")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have won, scissors beats paper")
            Counter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
#Checks if you won or lost
if counter == 3:
    print("Congratz you won :)")
else:
    print("Darn you lost :(")enter code here
</code>```

答:
In your else condition why is counter variable with capital 'C'? shouldn't it be counter?</p>

```<code>else:
        pc = randint(1,3)
        if pc == 1:
            print("You have lost, rock beats scissors")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have won, scissors beats paper")
            Counter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
</code>```

Title: rock paper scissors stuck in while loop

Body:
I am making rock, paper, scissors.

After 3 wins or losses, I want it to leave the while loop but it keeps running.

##################
# import modules #
##################

from random import randint

# Declaration of variables #

pcCounter, counter = 0, 0
choice = ""
pc = 0

################
# Main program #
################
print("Welcome to Dags Rock,Paper,Scissors")
print("We will be playing a best out of 5")
choice = input("Select rock, paper or scissors")

while counter != 3 or pcCounter != 3:
    if choice == "rock" or choice == "Rock":
        pc = randint(1,3)
        if pc == 1:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have lost, Paper beats rock")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have won, rock beats scissors")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
    elif choice == "paper" or choice == "Paper":
        pc = randint(1,3)
        if pc == 1:
            print("You have won, paper beats rock")
            counter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have lost, scissors beats paper")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
    else:
        pc = randint(1,3)
        if pc == 1:
            print("You have lost, rock beats scissors")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have won, scissors beats paper")
            Counter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")
#Checks if you won or lost
if counter == 3:
    print("Congratz you won :)")
else:
    print("Darn you lost :(")enter code here

Body:
In your else condition why is counter variable with capital 'C'? shouldn't it be counter?

else:
        pc = randint(1,3)
        if pc == 1:
            print("You have lost, rock beats scissors")
            pcCounter += 1
            choice = input("Enter either rock, paper or scissors")
        elif pc == 2:
            print("You have won, scissors beats paper")
            Counter += 1
            choice = input("Enter either rock, paper or scissors")
        else:
            print("You have tied")
            choice = input("Enter either rock, paper or scissors")


问:
Possible to Geo-tag Photos using iPhone ImagePicker?
When calling the ImagePicker to take a picture the user is not prompted to allow their location to be used to geo-tag the photo as with the native Camera app.  Is it possible to turn on or build geo-tagging into the ImagePicker?</p>

答:
Well, you could simply get the photo via the ImagePicker, then prompt the user to approve getting their location (something you have to do anyway) and then store both image and location in your own object.

I don't believe the Picker by itself embeds lat/long in the image. That's likely something happening elsewhere in the Camera app.

You could check using this lib though:

http://code.google.com/p/iphone-exif/downloads/list

Good Luck!

OwnerDisplayName: Jared Brown

OwnerDisplayName: Genericrich


问:
Android - Get Location Only One Time
i need to get the current user location on an android app, so i've read some tutorials and samples on the web, but i see that in all the examples, the location is retrived from a "onLocationChange" that mean that every time the location change, the code in the "onLocationChange" is executed.

i need only to get the user location at the moment the app is started.

Thanks for your help!

答:
You can get the last know location using the code below. It gets the location providers and loops over the array backwards. i.e starts with GPS, if no GPS then gets network location. You can call this method whenever you need to get the location.</p>

```<code>private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break                 out the loop*/
Location l = null;

for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
</code>```

Title: Android - Get Location Only One Time

Body:
You can get the last know location using the code below. It gets the location providers and loops over the array backwards. i.e starts with GPS, if no GPS then gets network location. You can call this method whenever you need to get the location.

private double[] getGPS() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);

/* Loop over the array backwards, and if you get an accurate location, then break                 out the loop*/
Location l = null;

for (int i=providers.size()-1; i>=0; i--) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) break;
}

double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}


问:
$.ajax() in success doesn't update div with div from another file (the same id name)
I have two files html, both have div with the same name id = example. I'd like use $.ajax() to load content from second file and put instead current text in div in first file. Problem is that $(data).find('#example') doesn't return element #example. I know this error is in that I'm using the same id's name but after all I want to download this div from another file, so I do not understand. Can anyone explain?

index.html:

```<code><nav>
    <ul>
        <li><a href="index.html">home</a></li>
        <li><a href="contact.html">contact</a></li>
    </ul>
</nav>
<div id="example">one one one one </div>
</code>```

contact.html:

```<code><nav>
    <ul>
        <li><a href="index.html">home</a></li>
        <li><a href="contact.html">products</a></li>
    </ul>
</nav>
<div id="example">one one one one </div>
</code>```

$('nav a').on('click', function(e){
    e.preventDefault();
    var url = this.href;

    $.ajax({
        type: "POST",
        url: url,
        success: function(date){
            $('#example').html($(date).find('#example'));
      }
   });
 });    ```

答:
$('nav a').on('click', function(e){
    e.preventDefault();
    var url = this.href;

    $.ajax({
        type: "POST",
        url: url,
        success: function(response){
            $('#example').html($(response.data).find('#example'));
      }
   });
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

https://gitlab.com/Piterden/mcmp-pyro/blob/1.0/addons/default/defr/mcmp-theme/resources/js/theme/init.js#L144

Body:
I have two files html, both have div with the same name id = example. I'd like use $.ajax() to load content from second file and put instead current text in div in first file. Problem is that $(data).find('#example') doesn't return element #example. I know this error is in that I'm using the same id's name but after all I want to download this div from another file, so I do not understand. Can anyone explain?

index.html:

home

contact

one one one one

contact.html:

home

products

one one one one

$('nav a').on('click', function(e){
    e.preventDefault();
    var url = this.href;

    $.ajax({
        type: "POST",
        url: url,
        success: function(date){
            $('#example').html($(date).find('#example'));
      }
   });
 });

Body:
$('nav a').on('click', function(e){
    e.preventDefault();
    var url = this.href;

    $.ajax({
        type: "POST",
        url: url,
        success: function(response){
            $('#example').html($(response.data).find('#example'));
      }
   });
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

https://gitlab.com/Piterden/mcmp-pyro/blob/1.0/addons/default/defr/mcmp-theme/resources/js/theme/init.js#L144


问:
Comparing multiple database row values with Laravel Eloquent / MySQL
I'm using Laravel for my project and have a MySQL table as follows:

```<code>| User_id | technology | years_experience |
| 1       | PHP        |  4               |
| 2       | AngularJS  |  2               |
| 1       | HTML       |  2               |
</code>```

At the moment I'm using a standard where query which only supports one criteria

```<code>Table::where([
['technology', '=', 'PHP'],
['years_experience', '>', 2]
])->get()->pluck('user_id');
</code>```

How can I filter and group results by User_id if I wanted to retrieve all User_ids with PHP > 2 AND HTML > 1?

答:
haven't tested this, but ideally i guess this is what you need</p>

```<code>Table::where('technology', '=', 'PHP')->andWhere('years_experience', '>', 2)->get()->pluck('user_id')->andWhere('user_id','=',ANYUSERID)->groupBy('user_id')->get(['user_id','technology','years_experience']);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Laravel for my project and have a MySQL table as follows:

| User_id | technology | years_experience |
| 1       | PHP        |  4               |
| 2       | AngularJS  |  2               |
| 1       | HTML       |  2               |

At the moment I'm using a standard where query which only supports one criteria

Table::where([
['technology', '=', 'PHP'],
['years_experience', '>', 2]
])->get()->pluck('user_id');

How can I filter and group results by User_id if I wanted to retrieve all User_ids with PHP > 2 AND HTML > 1?

Body:
haven't tested this, but ideally i guess this is what you need

Table::where('technology', '=', 'PHP')->andWhere('years_experience', '>', 2)->get()->pluck('user_id')->andWhere('user_id','=',ANYUSERID)->groupBy('user_id')->get(['user_id','technology','years_experience']);


问:
API URL call with PHP and cURL
I'm hoping someone can help me out.

I have an API call using this URL.

```<code>https://192.168.11.234:4444/webconsole/APIController?reqxml=<Request><Login<Username>XXXXX</Username><Password>XXXXX></Password></Login><Get><User><Username>manager</Username></User></Get></Request>
</code>```

This works fine and returns an XML as expected.

However I'm attempting to do the same thing with PHP and cURL.

I have very little experience with cURL

So far I've tried variations of this but I get no response. only a blank page.  wondering if maybe someone could help me out.

```<code><?php
$input_xml = '<Request><Login><Username>XXXX</Username><Password>XXXX</Password></Login><Get><User></User></Get></Request>';
$url = "https://192.168.11.234:4444/webconsole/APIController";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POSTFIELDS,
            "reqxml=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);

$array_data = json_decode(json_encode(simplexml_load_string($data)), true);

print_r('```');
print_r($array_data);
print_r('```');
?>
</code>```

I will admit I have not worked with cURL much, so I may be way off.

答:
I love you guys(or gals)
This works:

```<code><?php
$input_xml = '<Request><Login><Username>XXXXX</Username><Password>XXXXXX</Password></Login><Get><User></User></Get></Request>';
$url = "https://192.168.11.234:4444/webconsole/APIController";
$ch = curl_init();
$headers = [
    "Content-type: text/xml;charset=\"utf-8\"",
    "Accept: text/xml",
    "Content-length: ".strlen($xml_data)
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_URL, $url."?reqxml=" . urlencode($input_xml));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
           if (curl_error($ch)) {
           echo 'error:' . curl_error($ch);
            }
        $data = curl_exec($ch);
        var_dump($data);
        curl_close($ch);

        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

        print_r('```');
        print_r($array_data);
        print_r('```');
?>
</code>```

Thought I was close, setting the correct headers, and changing:

```<code>curl_setopt($ch, CURLOPT_URL, $url);
</code>```

To:

```<code>curl_setopt($ch, CURLOPT_URL, $url."?reqxml=" . urlencode($input_xml));
</code>```

Is what helped. Thanks much for the help!

Title: API URL call with PHP and cURL

Body:
I'm hoping someone can help me out.

I have an API call using this URL.

https://192.168.11.234:4444/webconsole/APIController?reqxml=<Request><Login<Username>XXXXX</Username><Password>XXXXX></Password></Login><Get><User><Username>manager</Username></User></Get></Request>

This works fine and returns an XML as expected.

However I'm attempting to do the same thing with PHP and cURL.

I have very little experience with cURL

So far I've tried variations of this but I get no response. only a blank page.  wondering if maybe someone could help me out.

<?php
$input_xml = '<Request><Login><Username>XXXX</Username><Password>XXXX</Password></Login><Get><User></User></Get></Request>';
$url = "https://192.168.11.234:4444/webconsole/APIController";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_POSTFIELDS,
            "reqxml=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);

$array_data = json_decode(json_encode(simplexml_load_string($data)), true);

print_r('
');
print_r($array_data);
print_r('
');
?>

I will admit I have not worked with cURL much, so I may be way off.

Body:
I love you guys(or gals)
This works:

<?php
$input_xml = '<Request><Login><Username>XXXXX</Username><Password>XXXXXX</Password></Login><Get><User></User></Get></Request>';
$url = "https://192.168.11.234:4444/webconsole/APIController";
$ch = curl_init();
$headers = [
    "Content-type: text/xml;charset=\"utf-8\"",
    "Accept: text/xml",
    "Content-length: ".strlen($xml_data)
];

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_URL, $url."?reqxml=" . urlencode($input_xml));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
           if (curl_error($ch)) {
           echo 'error:' . curl_error($ch);
            }
        $data = curl_exec($ch);
        var_dump($data);
        curl_close($ch);

        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

        print_r('<pre>');
        print_r($array_data);
        print_r('</pre>');
?>

Thought I was close, setting the correct headers, and changing:

curl_setopt($ch, CURLOPT_URL, $url);

To:

curl_setopt($ch, CURLOPT_URL, $url."?reqxml=" . urlencode($input_xml));

Is what helped. Thanks much for the help!


问:
CakePHP 3 Http Client timeout error handling
I'm trying to use the CakePHP 3 Http Client to check urls for their response status code (404, 301, 200 etc)

```<code>$http = new Client();
$response = $http->get($links[$i]['url'],[],['timeout' => '10']);
$links[$i]['http_status'] = $response->statusCode();
</code>```

However, if I come across a url that timesout, the entire script fails.  I'm having trouble figuring out how to add error handling so that if it does timeout, I can log it and move on.

Any ideas?

答:
The solution was to use try/catch.  I had tried this initially but missed the \ before Exception on the catch</p>

```<code>try {
    // code
} catch (\Exception $e) {
    // error
}
</code>```

Body:
I'm trying to use the CakePHP 3 Http Client to check urls for their response status code (404, 301, 200 etc)

$http = new Client();
$response = $http->get($links[$i]['url'],[],['timeout' => '10']);
$links[$i]['http_status'] = $response->statusCode();

However, if I come across a url that timesout, the entire script fails.  I'm having trouble figuring out how to add error handling so that if it does timeout, I can log it and move on.

Any ideas?

Body:
The solution was to use try/catch.  I had tried this initially but missed the \ before Exception on the catch

try {
    // code
} catch (\Exception $e) {
    // error
}


问:
Implementing an offline chat using MQTT
I am creating a group chat app and was wondering how I can save the messages received while one of the users was offline. Ex. User A, User B, User C are in a group chat, User B goes offline (loses connection), how do I have it so that when he joins back he recieves the messages between User A and User C while he was gone?. Is this even possible with MQTT or do I have to save the messages in a database?</p>

答: I figured it out if anyone is interested. I set my cleanSession to false so it wouldn't create a new session on reconnection, also make sure to keep the client's id is the same because that is what it is saved under in the queue. </p>

Title: Implementing an offline chat using MQTT