问:
Remove woocommerce duplicate taxonomy page links?
I am having an issue with duplicate content, which seems to be an out of the box issue with woocommerce. For example, our SEO company is complaining because of duplicate content because you can go to:

```<code>http://localhost/wp7/product-category/clothing/hoodies/
</code>```

but you can also go to

```<code>http://localhost/wp7/product-category/hoodies/
</code>```

So clothing is the parent taxonomy of hoodies. Is there a filter/code to make it so that you won't be able to navigate to just the child taxonomy link, but only allow http://www.example.com/product-category/parent/child?

Any help on this would be greatly appreciated.

Kind regards, and thanks!

答:
I was able to work through this, with this solution. Which seems to work beautifully. Not sure of the repercussions in the woocommerce eco system, but it definitely works on the frontend.</p>

```<code>/**
 * Disallow duplicate Woocommerce taxonomy links
 * |- Redirects http://www.example.com/product_cat/child to http://www.example.com/product_cat/parent/child
 */
add_action('template_redirect', function ($query) {
    global $wp;
    $productCatTaxonomy = 'product_cat';

    if (is_tax($productCatTaxonomy)) {
        $current_url = add_query_arg($wp->query_string, '', home_url($wp->request));
        $current_args = parse_url($current_url);
        $currentTerm = get_term_by('slug', get_query_var('term'), $productCatTaxonomy);

        if (isset($current_args['query']) && !stristr($current_args['query'], '%2f')) {
            $currentParentTerm = (isset($currentTerm->parent) && $currentTerm->term_id) ? get_term_by('id', $currentTerm->parent, $productCatTaxonomy) : 0;

            if ($currentParentTerm) {
                $childTermLink = (isset($currentTerm->term_id) && $currentTerm->term_id) ? get_term_link($currentTerm->term_id, $productCatTaxonomy) : 0;

                if ($childTermLink) {
                    wp_redirect($childTermLink);
                    die();
                }
            }
        }
    }

    return $query;
});
</code>```

Body:
I am having an issue with duplicate content, which seems to be an out of the box issue with woocommerce. For example, our SEO company is complaining because of duplicate content because you can go to:

http://localhost/wp7/product-category/clothing/hoodies/

but you can also go to

http://localhost/wp7/product-category/hoodies/

So clothing is the parent taxonomy of hoodies. Is there a filter/code to make it so that you won't be able to navigate to just the child taxonomy link, but only allow http://www.example.com/product-category/parent/child?

Any help on this would be greatly appreciated.

Kind regards, and thanks!

Body:
I was able to work through this, with this solution. Which seems to work beautifully. Not sure of the repercussions in the woocommerce eco system, but it definitely works on the frontend.

/**
 * Disallow duplicate Woocommerce taxonomy links
 * |- Redirects http://www.example.com/product_cat/child to http://www.example.com/product_cat/parent/child
 */
add_action('template_redirect', function ($query) {
    global $wp;
    $productCatTaxonomy = 'product_cat';

    if (is_tax($productCatTaxonomy)) {
        $current_url = add_query_arg($wp->query_string, '', home_url($wp->request));
        $current_args = parse_url($current_url);
        $currentTerm = get_term_by('slug', get_query_var('term'), $productCatTaxonomy);

        if (isset($current_args['query']) && !stristr($current_args['query'], '%2f')) {
            $currentParentTerm = (isset($currentTerm->parent) && $currentTerm->term_id) ? get_term_by('id', $currentTerm->parent, $productCatTaxonomy) : 0;

            if ($currentParentTerm) {
                $childTermLink = (isset($currentTerm->term_id) && $currentTerm->term_id) ? get_term_link($currentTerm->term_id, $productCatTaxonomy) : 0;

                if ($childTermLink) {
                    wp_redirect($childTermLink);
                    die();
                }
            }
        }
    }

    return $query;
});


来源: stackexchange

问:
Simple variable reference
So I'm currently trying make a simple rpg game, it's my first time so I'm learning haha, but my question is that, I am trying to reference a variable in another class I have for the player's choice of their class. P.S. I couldn't figure out what to look up so I'm sorry if this is a repeat question.

this is the main

```<code>public static void main(String[] args) {
    Scanner inputRace =  new Scanner(System.in);
    player player1 = new player(race.valueOf(inputRace), profession.ranger);
}
</code>```

and here is the race class I'm trying to reference

```<code>public enum race {
    orc, elf, human, dwarf
}
</code>```

So all I'm trying to do is be able to take the user's input and do like race.("whatever their choice is"), but I haven't been able to figure it out. Thanks for any help and sorry if it's confusing.

答:
If I understand correctly, you need to get race.orc if the user enters orc, and henceforth.

You're on the right track, you just need to input the String from the user, like

```<code>String s = inputRace.next();
player player1 = new player(race.valueOf(s), profession.ranger);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Simple variable reference

Body:
So I'm currently trying make a simple rpg game, it's my first time so I'm learning haha, but my question is that, I am trying to reference a variable in another class I have for the player's choice of their class. P.S. I couldn't figure out what to look up so I'm sorry if this is a repeat question.

this is the main

public static void main(String[] args) {
    Scanner inputRace =  new Scanner(System.in);
    player player1 = new player(race.valueOf(inputRace), profession.ranger);
}

and here is the race class I'm trying to reference

public enum race {
    orc, elf, human, dwarf
}

So all I'm trying to do is be able to take the user's input and do like race.("whatever their choice is"), but I haven't been able to figure it out. Thanks for any help and sorry if it's confusing.

Body:
If I understand correctly, you need to get race.orc if the user enters orc, and henceforth.

You're on the right track, you just need to input the String from the user, like

String s = inputRace.next();
player player1 = new player(race.valueOf(s), profession.ranger);


问:
Android application giving a weird error in Eclipse
i put this question in this forum because i am not sure whether this is an eclipse error or an Android error.
yesterday i created an Android application using Google Maps and GPS on Eclipse and it build and ran successfully however today i wanted to do some modification to the code so i started eclipse but it gave me an error.

```<code>SDK parse failed
</code>```

if i try to run it. it says the apk cannot find. how can that be happened? the same application ran successfully on the same environment yesterday. i am using Ubuntu 10.04

Thanks !!

答: There is a problem with your project, as evidenced by the red x icon on your project title bar shown in the image above. Right-click your project, choose Properties and go through all your properties to make sure they are all still valid. It might be a reference to one of the jar files.</p>

ContentLicense: CC BY-SA 2.5

Body:
i put this question in this forum because i am not sure whether this is an eclipse error or an Android error.
yesterday i created an Android application using Google Maps and GPS on Eclipse and it build and ran successfully however today i wanted to do some modification to the code so i started eclipse but it gave me an error.

SDK parse failed

if i try to run it. it says the apk cannot find. how can that be happened? the same application ran successfully on the same environment yesterday. i am using Ubuntu 10.04

Thanks !!


问:
While true loop function
To my understanding, a while loop can be done this way :

```<code>while (true) {
    // run this code
    if (condition satisfies)
        break; // return;
}
</code>```

So I took it and I put in the following main function below, my problem is that when I put a printf statement after I meet the condition ( 5 or more ), it stops and doesn't display anything, and if I put nothing but the break statement it works and it loops through 5 different customers! am I missing anything about the while true loop or is this the way it works ?

```<code>int main ()
{
    displayMenu();
    while (true)
    {
        int gasType,gallonsAmount,carWashOption,customerAmount ;
        float gasPrices[SIZE]={2.99,3.099,3.199,3.299}, washPrices[SIZE]=
        {3.50,3.00,3.00,2.50}, perGallonRate,perWashRate,total;
        float totalSum,totalGallonSum;
        gasType = getGasType();
        gallonsAmount = getGallons();
        carWashOption = getCarWash();
        perGallonRate = getGallonRate(gasPrices, gasType);
        if (carWashOption == 'Y')
        {
            perWashRate = getWashRate( washPrices, gasType );
            total = calcAmount(gallonsAmount, perGallonRate, perWashRate,&totalSum, &totalGallonSum);
        }
        else
        {
            perWashRate = 0;
            total = calcAmount(gallonsAmount, perGallonRate, perWashRate,&totalSum, &totalGallonSum);
        }
        customerAmount++;// once we reach a total of 5 customers(Assume its the end of the day), the loop will break and give me a summary.
        if (customerAmount >= 5)
            printf("totalSum: %.2f ", totalSum ,totalGallonSum);
            break;
    }

    return 0;
}
</code>```

答:
```<code> if (customerAmount >= 5)
    printf("totalSum: %.2f ", totalSum , totalGallonSum  );
    break;
</code>```

break is not part of if.So the very first time your loop ends.
Use braces.

```<code> if (customerAmount >= 5)
 {
    printf("totalSum: %.2f ", totalSum , totalGallonSum  );
    break;
  }
</code>```

Title: While true loop function

Body:
To my understanding, a while loop can be done this way :

while (true) {
    // run this code
    if (condition satisfies)
        break; // return;
}

So I took it and I put in the following main function below, my problem is that when I put a printf statement after I meet the condition ( 5 or more ), it stops and doesn't display anything, and if I put nothing but the break statement it works and it loops through 5 different customers! am I missing anything about the while true loop or is this the way it works ?

int main ()
{
    displayMenu();
    while (true)
    {
        int gasType,gallonsAmount,carWashOption,customerAmount ;
        float gasPrices[SIZE]={2.99,3.099,3.199,3.299}, washPrices[SIZE]=
        {3.50,3.00,3.00,2.50}, perGallonRate,perWashRate,total;
        float totalSum,totalGallonSum;
        gasType = getGasType();
        gallonsAmount = getGallons();
        carWashOption = getCarWash();
        perGallonRate = getGallonRate(gasPrices, gasType);
        if (carWashOption == 'Y')
        {
            perWashRate = getWashRate( washPrices, gasType );
            total = calcAmount(gallonsAmount, perGallonRate, perWashRate,&totalSum, &totalGallonSum);
        }
        else
        {
            perWashRate = 0;
            total = calcAmount(gallonsAmount, perGallonRate, perWashRate,&totalSum, &totalGallonSum);
        }
        customerAmount++;// once we reach a total of 5 customers(Assume its the end of the day), the loop will break and give me a summary.
        if (customerAmount >= 5)
            printf("totalSum: %.2f ", totalSum ,totalGallonSum);
            break;
    }

    return 0;
}

Body:
 if (customerAmount >= 5)
    printf("totalSum: %.2f ", totalSum , totalGallonSum  );
    break;

break is not part of if.So the very first time your loop ends.
Use braces.

 if (customerAmount >= 5)
 {
    printf("totalSum: %.2f ", totalSum , totalGallonSum  );
    break;
  }


答:
In other to access input data you must use scanner methods like next, nextInt, nextDouble etc.

In your case you are looking for string so it should look like this:

```<code>try {
    Race race = Race.valueOf( inputRace.next() ); // next returns string
    Player player1 = new Player(race, profession.ranger);
} catch ( IllegalArgumentException ex ) {
    System.err.println( "That race doesn't exsist" );
}
</code>```

Note that I used upper case for Race and Player, this is standard way of naming your classes.

Also you should put your code in some kind of loop until he doesn't write correct race.

Title: Simple variable reference

Body:
In other to access input data you must use scanner methods like next, nextInt, nextDouble etc.

In your case you are looking for string so it should look like this:

try {
    Race race = Race.valueOf( inputRace.next() ); // next returns string
    Player player1 = new Player(race, profession.ranger);
} catch ( IllegalArgumentException ex ) {
    System.err.println( "That race doesn't exsist" );
}

Note that I used upper case for Race and Player, this is standard way of naming your classes.

Also you should put your code in some kind of loop until he doesn't write correct race.


问:
setAttribute function in a-animations attributes with a-frame does not work
i tried so far changing a-animation element attributes in a-frame like :

```<code>   setAttribute('dur',5000);
</code>```

or

```<code>   setAttribute('to',{x: 0, y: 0, z: 1});
</code>```

but it never play the animation and the type of value is [object Object], i tried also setting the stringified value of vec3  type like 'x y z' but it never play with the new updated values in the browser !

答:
Have you tried:

```<code>setAttribute('to',{x:0; y:0; z:1});
</code>```

?

Body:
i tried so far changing a-animation element attributes in a-frame like :

   setAttribute('dur',5000);

or

   setAttribute('to',{x: 0, y: 0, z: 1});

but it never play the animation and the type of value is [object Object], i tried also setting the stringified value of vec3  type like 'x y z' but it never play with the new updated values in the browser !

Body:
Have you tried:

setAttribute('to',{x:0; y:0; z:1});

?


问:
Upgrading app to iPhone 4: how to get touches to give low-res screen values
I am currently in the process of testing an OpenGL ES app with iPhone 4. I developed the app initially on an iPhone 3G and in the 3G simulator, using this project as a starting point rather than apple's, which I couldn't understand. I see now that this may have been a mistake.

When I tried to play the game on the iPhone 4, the touch events are giving a high-resolution output (ie x from 0-639, y from 0-959) rather than the low res touch points that my game needs (that is, x:0-319, y:0-479). I have looked at several apple example projects such as GLPaint, and this only seems to give low res touch points, but I can't see what the difference is between that project and mine.

Any help anyone can give would be much appreciated, this is for a project that is due in a few days' time! (I know, how could I not test it on iPhone 4 or even the simulator! But, you live, you learn...)

答:
As has happened every time I have posted something on SO, I figured out the answer shortly afterwards, so I am posting it in case someone as skittish and worrisome as me runs into this problem.

I was passing the touch information from my GLView to the GLViewController I had defined, and this was dealing with the touch information. It was making a CGPoint for each touch, by getting a touch point using this message to the UITouch object:

```<code>CGPoint touchPoint = [touch locationInView:self.view];
</code>```

The problem seems to be that the GLViewController was getting the location of the touch in a UIView object, not a GLView subclassing of this object. So, assuming glView is a property of type GLView of GLViewController, if you change the code to

```<code>CGPoint touchPoint = [touch locationInView:self.glView];
</code>```

Everything works fine. Silly mistake eh, but it's all good learning.

I hope someone else who has this problem can profit from my mad panic... :-)

Body:
As has happened every time I have posted something on SO, I figured out the answer shortly afterwards, so I am posting it in case someone as skittish and worrisome as me runs into this problem.

I was passing the touch information from my GLView to the GLViewController I had defined, and this was dealing with the touch information. It was making a CGPoint for each touch, by getting a touch point using this message to the UITouch object:

CGPoint touchPoint = [touch locationInView:self.view];

The problem seems to be that the GLViewController was getting the location of the touch in a UIView object, not a GLView subclassing of this object. So, assuming glView is a property of type GLView of GLViewController, if you change the code to

CGPoint touchPoint = [touch locationInView:self.glView];

Everything works fine. Silly mistake eh, but it's all good learning.

I hope someone else who has this problem can profit from my mad panic... :-)


Title: python / pandas from timetable to timedate dataframe

Body:
i have a set of data like this:

    Unnamed: 0  0:30  1:00  1:30  2:00  2:30  3:00  3:30  4:00  4:30  ...   \
0   2016-01-01  26.9  26.4  26.9  26.1  26.4  26.7  26.5  25.5  25.4  ...
1   2016-01-02  26.8  25.9  25.7  26.0  25.2  25.3  25.6  25.0  25.1  ...
2   2016-01-03  25.6  25.4  25.2  25.5  24.5  24.5  24.9  24.6  24.3  ...
3   2016-01-04  24.9  24.2  23.7  23.5  23.4  23.4  23.6  23.3  23.7  ...
..         ...   ...   ...   ...   ...   ...   ...   ...   ...   ...  ...
361 2016-12-27  15.6  15.5  15.5  15.7  16.1  16.2  16.3  16.2  16.2  ...
362 2016-12-28  15.3  15.7  16.3  16.4  16.2  16.1  16.3  16.1  16.2  ...
363 2016-12-29  15.9  16.3  16.1  16.4  16.4  16.2  16.1  16.1  15.9  ...
364 2016-12-30  16.2  16.3  16.3  16.3  16.2  16.3  16.3  16.3  16.3  ...
365 2016-12-31  16.1  16.0  16.2  16.3  16.2  16.2  16.3  16.3  16.3  ...

that I would like to rearrange with date+time for each value at each row. something like:

0   2016-01-01 0:30 26.9
1   2016-01-01 1:00 26.4
2   2016-01-01 1:30 26.9
3   2016-01-01 2:00 26.1

but i haven't a clue how to append the values into a new dataframe without iterating (which is very slow as i have several big data-sets)

i tried something like

df = pd.DataFrame(index = data['Unnamed: 0'] + ' ' + data.columns[1:len(data.columns)])

but this isn't right - it is the data structure that i don't get i think

ideas? thanks

Body:
@A-Za-z's answer was my first thought... but if you wanted the new index values to be timestamps that include the time elements from the columns...

set_index to get dates into index so I can grab all the values easily

turn columns into time deltas

turn index into date times

use numpy broadcasting to generate all timestamps

construct new series with raveld values and timestamps

d1 = df.set_index('Unnamed: 0')

td = pd.to_timedelta(d1.columns + ':00').values
ts = pd.to_datetime(d1.index).values

pd.Series(
    d1.values.ravel(),
    (ts[:, None] + td).ravel()
)

Output:

2016-01-01 00:30:00    26.9
2016-01-01 01:00:00    26.4
2016-01-01 01:30:00    26.9
2016-01-01 02:00:00    26.1
2016-01-01 02:30:00    26.4
2016-01-01 03:00:00    26.7
2016-01-01 03:30:00    26.5
2016-01-01 04:00:00    25.5
2016-01-01 04:30:00    25.4
2016-01-02 00:30:00    26.8
2016-01-02 01:00:00    25.9
2016-01-02 01:30:00    25.7
2016-01-02 02:00:00    26.0
2016-01-02 02:30:00    25.2
2016-01-02 03:00:00    25.3
2016-01-02 03:30:00    25.6
2016-01-02 04:00:00    25.0
2016-01-02 04:30:00    25.1
2016-01-03 00:30:00    25.6
2016-01-03 01:00:00    25.4
2016-01-03 01:30:00    25.2
2016-01-03 02:00:00    25.5
2016-01-03 02:30:00    24.5
2016-01-03 03:00:00    24.5
2016-01-03 03:30:00    24.9
2016-01-03 04:00:00    24.6
2016-01-03 04:30:00    24.3
2016-01-04 00:30:00    24.9
2016-01-04 01:00:00    24.2
2016-01-04 01:30:00    23.7
                       ...
2016-12-28 03:30:00    16.3
2016-12-28 04:00:00    16.1
2016-12-28 04:30:00    16.2
2016-12-29 00:30:00    15.9
2016-12-29 01:00:00    16.3
2016-12-29 01:30:00    16.1
2016-12-29 02:00:00    16.4
2016-12-29 02:30:00    16.4
2016-12-29 03:00:00    16.2
2016-12-29 03:30:00    16.1
2016-12-29 04:00:00    16.1
2016-12-29 04:30:00    15.9
2016-12-30 00:30:00    16.2
2016-12-30 01:00:00    16.3
2016-12-30 01:30:00    16.3
2016-12-30 02:00:00    16.3
2016-12-30 02:30:00    16.2
2016-12-30 03:00:00    16.3
2016-12-30 03:30:00    16.3
2016-12-30 04:00:00    16.3
2016-12-30 04:30:00    16.3
2016-12-31 00:30:00    16.1
2016-12-31 01:00:00    16.0
2016-12-31 01:30:00    16.2
2016-12-31 02:00:00    16.3
2016-12-31 02:30:00    16.2
2016-12-31 03:00:00    16.2
2016-12-31 03:30:00    16.3
2016-12-31 04:00:00    16.3
2016-12-31 04:30:00    16.3
Length: 81, dtype: float64


问:
Meteor-coverage seems to show executed statements as not covered
I'm using the meteor-coverage package (version 1.1.4) with mocha (version 2.4.5_6) and meteor version 1.4.4.1 on Ubuntu 14.04 LTS. I have been able to produce very pretty test coverage reports, but it seems that for the client-side tests something is amiss. In order to send the coverage data to localhost:3000/coverage I have created a function called sendCoverage() which I import in my .tests.js files:

```<code>export const sendCoverage = function sendCoverage() {
    Meteor.sendCoverage(function(stats,err) {console.log(stats,err);});
};
</code>```

I call this function after a block of mocha tests:

```<code>after (function () {
    sendCoverage();
});
</code>```

Now, this produces test coverage reports in my localhost:3000/coverage page, but it seems as though it does not display the coverage properly. For example, I see that some statements are executed, but are highlighted in red and flagged as not covered. For example:

It seems as though the statements get executed 11 and 12 times, respectively. However, they are not flagged as being covered and in my reports the percentage of statement coverage reflects this.

Does anyone know what I may be doing wrong and/or have experience with client-side code coverage and the meteor-coverage package?

Thanks!

Post-solution edit

It seems I've got it working now. The percentages on Codacy match the percentages in my html report. Looking at the html report more closely, it seems the coverage numbers were correct after all. It was simply the drill down that was showing odd behavior. So, the conclusion is that it worked after all, but it took Codacy's second opinion to confirm this to me. My new approach will be to create lcov coverage reports with spacejam (see Ser's answer below) and export these to an external service like Codacy, Codecov or SonarQube.

Thanks Serut for the input!

答:
I am the author of meteor-coverage. Glad to see that the package runs well on your app!

First, I don't think the way your are collecting coverage and saving reports is optimized: don't create an utils with a function to save the coverage. You can save the coverage on each file just by using (assuming  Meteor.sendCoverage always exists on test).

```<code>after (function () {
    Meteor.sendCoverage(()=>{});
});
</code>```

On the other hand, you should not write any code in your test file in order to save coverage. The test runner can do that for you like what I added on the spacejam fork. You can try to export the html and the lcov report using serut/spacejam.

I think the lcov format is more reliable than the html report. If I look at some coverage report of the client side code from meteor-coverage, everything looks coherent. Try to send the lcov file to an Code Quality platform like Sonar, Codecov or Codacy. I hope it will fix the line problem, which may be related to istanbul and its html report generation.

Body:
I'm using the meteor-coverage package (version 1.1.4) with mocha (version 2.4.5_6) and meteor version 1.4.4.1 on Ubuntu 14.04 LTS. I have been able to produce very pretty test coverage reports, but it seems that for the client-side tests something is amiss. In order to send the coverage data to localhost:3000/coverage I have created a function called sendCoverage() which I import in my .tests.js files:

export const sendCoverage = function sendCoverage() {
    Meteor.sendCoverage(function(stats,err) {console.log(stats,err);});
};

I call this function after a block of mocha tests:

after (function () {
    sendCoverage();
});

Now, this produces test coverage reports in my localhost:3000/coverage page, but it seems as though it does not display the coverage properly. For example, I see that some statements are executed, but are highlighted in red and flagged as not covered. For example:

It seems as though the statements get executed 11 and 12 times, respectively. However, they are not flagged as being covered and in my reports the percentage of statement coverage reflects this.

Does anyone know what I may be doing wrong and/or have experience with client-side code coverage and the meteor-coverage package?

Thanks!

Post-solution edit

It seems I've got it working now. The percentages on Codacy match the percentages in my html report. Looking at the html report more closely, it seems the coverage numbers were correct after all. It was simply the drill down that was showing odd behavior. So, the conclusion is that it worked after all, but it took Codacy's second opinion to confirm this to me. My new approach will be to create lcov coverage reports with spacejam (see Ser's answer below) and export these to an external service like Codacy, Codecov or SonarQube.

Thanks Serut for the input!

Body:
I am the author of meteor-coverage. Glad to see that the package runs well on your app!

First, I don't think the way your are collecting coverage and saving reports is optimized: don't create an utils with a function to save the coverage. You can save the coverage on each file just by using (assuming  Meteor.sendCoverage always exists on test).

after (function () {
    Meteor.sendCoverage(()=>{});
});

On the other hand, you should not write any code in your test file in order to save coverage. The test runner can do that for you like what I added on the spacejam fork. You can try to export the html and the lcov report using serut/spacejam.

I think the lcov format is more reliable than the html report. If I look at some coverage report of the client side code from meteor-coverage, everything looks coherent. Try to send the lcov file to an Code Quality platform like Sonar, Codecov or Codacy. I hope it will fix the line problem, which may be related to istanbul and its html report generation.


问:
Receiving Firebase Notifications in Foreground but not Background
I've tried everything to get the alerts to pop up while in the background. I receive the data when app is open or while launching. Because I receive the notifications I'm assuming it's in my AppDelegate code or perhaps something wrong in my .plist??? I've followed a few of the standard tutorials on firebase notifications, all this code is from those tutorials.</p>

```<code>import UIKit
import CoreData
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
            // For iOS 10 data message (sent via FCM
            Messaging.messaging().delegate = self
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Override point for customization after application launch.

        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)),
                                                         name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        return true
    }

    func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("refreshed token")
    }

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

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

      //  Messaging.messaging().disconnect()
       // print("Disconnected from FCM.")
    }

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

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

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "firetail")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    @objc private func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    func connectToFcm() {
        // Won't connect since there is no token
        guard InstanceID.instanceID().token() != nil else {
            return
        }

        // Disconnect previous FCM connection if it exists.
        Messaging.messaging().disconnect()

        Messaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")
            } else {
                print("Connected to FCM.")
            }
        }
    }

    public func application(received remoteMessage: MessagingRemoteMessage) {

        print(remoteMessage.appData)
    }

}
</code>```

答: Be sure to send your messages through Firebase with the high priority setting instead of the standard/default priority.</p>

Body:
I've tried everything to get the alerts to pop up while in the background. I receive the data when app is open or while launching. Because I receive the notifications I'm assuming it's in my AppDelegate code or perhaps something wrong in my .plist??? I've followed a few of the standard tutorials on firebase notifications, all this code is from those tutorials.

import UIKit
import CoreData
import Firebase
import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()
        if #available(iOS 10.0, *) {
            // For iOS 10 display notification (sent via APNS)
            UNUserNotificationCenter.current().delegate = self
            let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
            UNUserNotificationCenter.current().requestAuthorization(
                options: authOptions,
                completionHandler: {_, _ in })
            // For iOS 10 data message (sent via FCM
            Messaging.messaging().delegate = self
        } else {
            let settings: UIUserNotificationSettings =
                UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }

        application.registerForRemoteNotifications()

        // Override point for customization after application launch.

        NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification(_:)),
                                                         name: NSNotification.Name.InstanceIDTokenRefresh, object: nil)

        return true
    }

    func application(application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Messaging.messaging().apnsToken = deviceToken
    }

    func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) {
        print("refreshed token")
    }

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

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

      //  Messaging.messaging().disconnect()
       // print("Disconnected from FCM.")
    }

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

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

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        // Saves changes in the application's managed object context before the application terminates.
        self.saveContext()
    }

    // MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "firetail")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
    @objc private func tokenRefreshNotification(_ notification: Notification) {
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")
        }

        // Connect to FCM since connection may have failed when attempted before having a token.
        connectToFcm()
    }

    func connectToFcm() {
        // Won't connect since there is no token
        guard InstanceID.instanceID().token() != nil else {
            return
        }

        // Disconnect previous FCM connection if it exists.
        Messaging.messaging().disconnect()

        Messaging.messaging().connect { (error) in
            if error != nil {
                print("Unable to connect with FCM. \(error?.localizedDescription ?? "")")
            } else {
                print("Connected to FCM.")
            }
        }
    }

    public func application(received remoteMessage: MessagingRemoteMessage) {

        print(remoteMessage.appData)
    }

}


问:
Bootstrap Input-Group Multiple Textbox Widths
I have 2 textboxes in an input-group, seperated by an input-group-addon span. My problem is, I want textbox 1 to be wider than textbox 2. Textbox 1 is supposed to be the phone number (larger) and textbox 2 is an extension number (slimmer). I have a fiddle below:

https://jsfiddle.net/Lhhj7f5d/

```<code><div class="col-xs-6">
 <div class="input-group">
  <input class="form-control" type="tel" placeholder="Phone Number" />
  <span class="input-group-addon">Ext.</span>
  <input class="form-control" type="text" placeholder="Extension"/>
 </div>
</div>
</code>```

Thanks!

答:
You need to put your input tag inside a div with col-xs-*.

#phoneField .col-xs-3{
  padding:0;
}
#phoneField .col-xs-3::after{
  content: "-";
  position:absolute;
  margin:5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
 <head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-xs-6">
  <div id="phoneField" class="input-group">
   <div class="col-xs-3">
    <input class="form-control" type="text" placeholder="Ext" maxlength="3"/>
    </div>
   <div class="col-xs-9">
    <input class="form-control" type="tel" placeholder="Phone Number" maxlength="10"/>
    </div>
   </div>
</div>
</body>
</html></code>```

Body:
I have 2 textboxes in an input-group, seperated by an input-group-addon span. My problem is, I want textbox 1 to be wider than textbox 2. Textbox 1 is supposed to be the phone number (larger) and textbox 2 is an extension number (slimmer). I have a fiddle below:

https://jsfiddle.net/Lhhj7f5d/

  <input class="form-control" type="tel" placeholder="Phone Number" />
  Ext.
  <input class="form-control" type="text" placeholder="Extension"/>

Thanks!

Body:
You need to put your input tag inside a div with col-xs-*.

#phoneField .col-xs-3{
  padding:0;
}
#phoneField .col-xs-3::after{
  content: "-";
  position:absolute;
  margin:5px;
}

<!DOCTYPE html>
<html>
 <head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-xs-6">
  <div id="phoneField" class="input-group">
   <div class="col-xs-3">
    <input class="form-control" type="text" placeholder="Ext" maxlength="3"/>
    </div>
   <div class="col-xs-9">
    <input class="form-control" type="tel" placeholder="Phone Number" maxlength="10"/>
    </div>
   </div>
</div>
</body>
</html>


问:
Cocoapods ReactiveKit swift compiler error
I am trying to add ReactiveKit To my Xcode project with CocoaPods.

That is my pods file:

```<code>platform :ios, '8.0'
source 'https://github.com/CocoaPods/Specs.git'
target '<my-proj-name-here>' do
    use_frameworks!
    pod 'SideMenu'
    pod 'ReactiveKit'
    pod 'Bond'
end
</code>```

I ran the following lines from command line:

```<code>pod cache clean --all
pod deintegrate
pod install
</code>```

Tons of errors are shown:

答:
I wasn't enough familiar with cocapods.
The following commands have solved it:

Reinstalling:

```<code>sudo gem install cocoapods
</code>```

Updating Packages ("pod install" doesn't install the latest)

```<code>pod update
</code>```

Body:
I am trying to add ReactiveKit To my Xcode project with CocoaPods.

That is my pods file:

platform :ios, '8.0'
source 'https://github.com/CocoaPods/Specs.git'
target '<my-proj-name-here>' do
    use_frameworks!
    pod 'SideMenu'
    pod 'ReactiveKit'
    pod 'Bond'
end

I ran the following lines from command line:

pod cache clean --all
pod deintegrate
pod install

Tons of errors are shown:

Body:
I wasn't enough familiar with cocapods.
The following commands have solved it:

Reinstalling:

sudo gem install cocoapods

Updating Packages ("pod install" doesn't install the latest)

pod update


问:
Migrating play Framework from 2.2 to 2.5. Its there a short way? Or 2.2-> 2.3 -> 2.4 -> 2.5
We have a play-java webapp. We're planning to migrate to play 2.5.

Is there a shortcut or do we have to go through multistep process.

答:
Just did that for a Java project. Took me one week of pain and sorrow.

The result? A code full of patches (to make it work with the new dependency injection system) that takes longer to compile and throws random out of memory exceptions if you try to compile it on VMs with less than 1GB of RAM (like the small EC2 instances from AWS).

I miss the lightweight and developer friendly framework that I fell in love with...


问:
$localStorage gives value in one state and is undefined in another state
I'm defining two states finance.payment and finance.ppm where finance is already a state

This is the payment.js file

angular.module('erpSaarangFrontendApp')
.config(function ($stateProvider) {
    $stateProvider
      .state('finance.payment', {
        url: '/payments',
        templateUrl: 'views/finance/payment.html',
        controller: 'FinancePaymentCtrl',
        authenticate: true
      });
  })
  .controller('FinancePaymentCtrl',['$scope', '$http','Upload','cloudinary', '$localStorage', '$state', function ($scope, $http, $upload, cloudinary, $localStorage, $state) {

      var config = {
                  headers:{
                    'Authorization' : "Bearer "+ $localStorage.auth_token,
                }
             };

             console.log($localStorage.auth_token);
             }]);```
</div>
</div>
</p>

<p>The console output for payment.js is </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>y1kw3j9lhb7rj4ld8rzwkhe0a9xymwlv</code>```

This is ppm.js file

angular.module('erpSaarangFrontendApp')
.config(function ($stateProvider) {
    $stateProvider
      .state('finance.ppm', {
        url: '/prizemoney',
        templateUrl: 'views/finance/ppm.html',
        controller: 'FinancePpmCtrl',
        authenticate: true
      });
  })
  .controller('FinancePpmCtrl',['$scope','$http','Upload','cloudinary','$location','$localStorage','$state', function ($scope, $http, $upload, cloudinary, $localStorage, $state) {

          var config = {
                  headers:{
                    'Authorization' : "Bearer "+ $localStorage.auth_token,
                }
             };

             console.log($localStorage.auth_token);
}]);```
</div>
</div>
</p>

<p>The console output for ppm.js is</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>undefined</code>```

When i print the $localStorage for payment.js , i get this -

Object { $default: $default(), $reset: $reset(), $sync: $sync(), $apply: $apply(), $supported: $supported(), auth_token: "y1kw3j9lhb7rj4ld8rzwkhe0a9xymwlv", member: Object, _id: 8190 }```
</div>
</div>
</p>

<p>But when i print the $localStorage for ppm.js , i get this -</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Object { $$protocol: "http", $$host: "localhost", $$port: 9000, $$parse: LocationHashbangUrl/this.$$parse(), $$compose: LocationHashbangUrl/this.$$compose(), $$parseLinkUrl: LocationHashbangUrl/this.$$parseLinkUrl(), $$path: "/finance/prizemoney", $$search: Object, $$hash: "", $$url: "/finance/prizemoney", 4 more… }</code>```

I don't understand, how $localStorage is varying ? and also why auth_token is undefined in ppm.js whereas it has a value in payment.js

答:
@robin: In ppm.js file, you injected $localStorage at 6 position but, in function it is on 5th position.

Position of injection and passing inside the function should be same.

So, actually $localStorage is getting parameter in function is actually getting passed as $location

Body:
I'm defining two states finance.payment and finance.ppm where finance is already a state

This is the payment.js file

angular.module('erpSaarangFrontendApp')
.config(function ($stateProvider) {
    $stateProvider
      .state('finance.payment', {
        url: '/payments',
        templateUrl: 'views/finance/payment.html',
        controller: 'FinancePaymentCtrl',
        authenticate: true
      });
  })
  .controller('FinancePaymentCtrl',['$scope', '$http','Upload','cloudinary', '$localStorage', '$state', function ($scope, $http, $upload, cloudinary, $localStorage, $state) {

      var config = {
                  headers:{
                    'Authorization' : "Bearer "+ $localStorage.auth_token,
                }
             };

             console.log($localStorage.auth_token);
             }]);

The console output for payment.js is

y1kw3j9lhb7rj4ld8rzwkhe0a9xymwlv

This is ppm.js file

angular.module('erpSaarangFrontendApp')
.config(function ($stateProvider) {
    $stateProvider
      .state('finance.ppm', {
        url: '/prizemoney',
        templateUrl: 'views/finance/ppm.html',
        controller: 'FinancePpmCtrl',
        authenticate: true
      });
  })
  .controller('FinancePpmCtrl',['$scope','$http','Upload','cloudinary','$location','$localStorage','$state', function ($scope, $http, $upload, cloudinary, $localStorage, $state) {

          var config = {
                  headers:{
                    'Authorization' : "Bearer "+ $localStorage.auth_token,
                }
             };

             console.log($localStorage.auth_token);
}]);

The console output for ppm.js is

undefined

When i print the $localStorage for payment.js , i get this -

Object { $default: $default(), $reset: $reset(), $sync: $sync(), $apply: $apply(), $supported: $supported(), auth_token: "y1kw3j9lhb7rj4ld8rzwkhe0a9xymwlv", member: Object, _id: 8190 }

But when i print the $localStorage for ppm.js , i get this -

Object { $$protocol: "http", $$host: "localhost", $$port: 9000, $$parse: LocationHashbangUrl/this.$$parse(), $$compose: LocationHashbangUrl/this.$$compose(), $$parseLinkUrl: LocationHashbangUrl/this.$$parseLinkUrl(), $$path: "/finance/prizemoney", $$search: Object, $$hash: "", $$url: "/finance/prizemoney", 4 more… }

I don't understand, how $localStorage is varying ? and also why auth_token is undefined in ppm.js whereas it has a value in payment.js


问:
How to calculate distance from user location to annotation and show it in a label
I have a label in my detailView i want to calculate distance from the current user location ( will update if user moves ) to a certain annotation .

And show the distance in that label

E.g : "3.6 km from your location "

答:
I recommend using extensions. Lets say you have your own class for Annotations (if you don't, just use MKAnnotation instead of "YourAnnotationClass") - you want to extend it with calculated property distanceToUsersCurrentLocation. Obviously, to access user's current location you need to import CoreLocation.

```<code>import UIKit
import CoreLocation

public class ViewController { //class where you need to set the label's text

    //your code here

    }
}

extension YouAnnotationClass {
    var distanceToUsersCurrentLocation: Double {
        let manager = CLLocationManager() //location manager for user's current location
        let destinationCoordinates = CLLocation(latitude: self.latitude, longitude: self.longitude) //coordinates for destinastion
        let selfCoordinates = CLLocation(latitude: (manager.location?.coordinate.latitude)!, longitude: (manager.location?.coordinate.longitude)!) //user's location
        return selfCoordinates.distance(from: destinationCoordinates) //return distance in **meters**
}
</code>```

Everytime you access distanceToUsersCurrentLocation within this class, you'll get distance in meters. I hope this helped with your problem

Body:
I recommend using extensions. Lets say you have your own class for Annotations (if you don't, just use MKAnnotation instead of "YourAnnotationClass") - you want to extend it with calculated property distanceToUsersCurrentLocation. Obviously, to access user's current location you need to import CoreLocation.

import UIKit
import CoreLocation

public class ViewController { //class where you need to set the label's text

    //your code here

    }
}

extension YouAnnotationClass {
    var distanceToUsersCurrentLocation: Double {
        let manager = CLLocationManager() //location manager for user's current location
        let destinationCoordinates = CLLocation(latitude: self.latitude, longitude: self.longitude) //coordinates for destinastion
        let selfCoordinates = CLLocation(latitude: (manager.location?.coordinate.latitude)!, longitude: (manager.location?.coordinate.longitude)!) //user's location
        return selfCoordinates.distance(from: destinationCoordinates) //return distance in **meters**
}

Everytime you access distanceToUsersCurrentLocation within this class, you'll get distance in meters. I hope this helped with your problem


问:
Sobel algorithm
I am trying to implement Sobel algorithm in order to detect the edges from an image.

I wrote the following code:

```<code>        bmp = new Bitmap(pictureBox1.Image);

        int[][] sobelx = {new int[] {-1, 0, 1},
                          new int[] {-2, 0, 2},
                          new int[] {-1, 0, 1}};

        int[][] sobely = {new int[] {-1, -2, -1},
                          new int[] { 0, 0, 0},
                          new int[] { 1, 2, 1}};

        for (int i = 1; i < bmp.Width - 1; i++)
        {
            for (int j = 1; j < bmp.Height - 1; j++)
            {int dx = bmp.GetPixel(i - 1, j - 1).R * sobelx[0][0] + bmp.GetPixel(i, j - 1).R * sobelx[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobelx[0][2]
                       + bmp.GetPixel(i - 1, j).R * sobelx[1][0] + bmp.GetPixel(i, j).R * sobelx[1][1] + bmp.GetPixel(i + 1, j).R * sobelx[1][2]
                       + bmp.GetPixel(i - 1, j + 1).R * sobelx[2][0] + bmp.GetPixel(i, j + 1).R * sobelx[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobelx[2][2];

                int dy = bmp.GetPixel(i - 1, j - 1).R * sobely[0][0] + bmp.GetPixel(i, j - 1).R * sobely[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobely[0][2]
                       + bmp.GetPixel(i - 1, j).R * sobely[1][0] + bmp.GetPixel(i, j).R * sobely[1][1] + bmp.GetPixel(i + 1, j).R * sobely[1][2]
                       + bmp.GetPixel(i - 1, j + 1).R * sobely[2][0] + bmp.GetPixel(i, j + 1).R * sobely[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobely[2][2];
                double derivata = Math.Sqrt((dx * dx) + (dy * dy));

                if (derivata > 255)
                {
                    bmp.SetPixel(i, j, Color.White);
                }
                else
                {
                    bmp.SetPixel(i, j, Color.FromArgb(255, (int)derivata, (int)derivata, (int)derivata));
                }
            }
        }

        pictureBox2.Image = bmp;
</code>```

But the resulted image is mostly white.
This is the original image:

This is the transformed image:

I don't know what I am doing wrong. Could anyone help me?

Thank you in advanced!

答:
Use another bitmap for saving the output as follows:</p>

```<code>            Bitmap res = new Bitmap(bmp.Width, bmp.Height);
            int[][] sobelx = {new int[] {-1, 0, 1},
                          new int[] {-2, 0, 2},
                          new int[] {-1, 0, 1}};

            int[][] sobely = {new int[] {-1, -2, -1},
                          new int[] { 0, 0, 0},
                          new int[] { 1, 2, 1}};

            for (int i = 1; i < bmp.Width - 1; i++)
            {
                for (int j = 1; j < bmp.Height - 1; j++)
                {
                    int dx = bmp.GetPixel(i - 1, j - 1).R * sobelx[0][0] + bmp.GetPixel(i, j - 1).R * sobelx[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobelx[0][2]
                              + bmp.GetPixel(i - 1, j).R * sobelx[1][0] + bmp.GetPixel(i, j).R * sobelx[1][1] + bmp.GetPixel(i + 1, j).R * sobelx[1][2]
                              + bmp.GetPixel(i - 1, j + 1).R * sobelx[2][0] + bmp.GetPixel(i, j + 1).R * sobelx[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobelx[2][2];

                    int dy = bmp.GetPixel(i - 1, j - 1).R * sobely[0][0] + bmp.GetPixel(i, j - 1).R * sobely[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobely[0][2]
                           + bmp.GetPixel(i - 1, j).R * sobely[1][0] + bmp.GetPixel(i, j).R * sobely[1][1] + bmp.GetPixel(i + 1, j).R * sobely[1][2]
                           + bmp.GetPixel(i - 1, j + 1).R * sobely[2][0] + bmp.GetPixel(i, j + 1).R * sobely[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobely[2][2];
                    double derivata = Math.Sqrt((dx * dx) + (dy * dy));

                    if (derivata > 255)
                    {
                        res.SetPixel(i, j, Color.White);
                    }
                    else
                    {
                        res.SetPixel(i, j, Color.FromArgb(255, (int)derivata, (int)derivata, (int)derivata));
                    }
                }
            }
</code>```

Title: Sobel algorithm

Body:
I am trying to implement Sobel algorithm in order to detect the edges from an image.

I wrote the following code:

        bmp = new Bitmap(pictureBox1.Image);

        int[][] sobelx = {new int[] {-1, 0, 1},
                          new int[] {-2, 0, 2},
                          new int[] {-1, 0, 1}};

        int[][] sobely = {new int[] {-1, -2, -1},
                          new int[] { 0, 0, 0},
                          new int[] { 1, 2, 1}};

        for (int i = 1; i < bmp.Width - 1; i++)
        {
            for (int j = 1; j < bmp.Height - 1; j++)
            {int dx = bmp.GetPixel(i - 1, j - 1).R * sobelx[0][0] + bmp.GetPixel(i, j - 1).R * sobelx[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobelx[0][2]
                       + bmp.GetPixel(i - 1, j).R * sobelx[1][0] + bmp.GetPixel(i, j).R * sobelx[1][1] + bmp.GetPixel(i + 1, j).R * sobelx[1][2]
                       + bmp.GetPixel(i - 1, j + 1).R * sobelx[2][0] + bmp.GetPixel(i, j + 1).R * sobelx[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobelx[2][2];

                int dy = bmp.GetPixel(i - 1, j - 1).R * sobely[0][0] + bmp.GetPixel(i, j - 1).R * sobely[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobely[0][2]
                       + bmp.GetPixel(i - 1, j).R * sobely[1][0] + bmp.GetPixel(i, j).R * sobely[1][1] + bmp.GetPixel(i + 1, j).R * sobely[1][2]
                       + bmp.GetPixel(i - 1, j + 1).R * sobely[2][0] + bmp.GetPixel(i, j + 1).R * sobely[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobely[2][2];
                double derivata = Math.Sqrt((dx * dx) + (dy * dy));

                if (derivata > 255)
                {
                    bmp.SetPixel(i, j, Color.White);
                }
                else
                {
                    bmp.SetPixel(i, j, Color.FromArgb(255, (int)derivata, (int)derivata, (int)derivata));
                }
            }
        }

        pictureBox2.Image = bmp;

But the resulted image is mostly white.
This is the original image:

This is the transformed image:

I don't know what I am doing wrong. Could anyone help me?

Thank you in advanced!

Body:
Use another bitmap for saving the output as follows:

            Bitmap res = new Bitmap(bmp.Width, bmp.Height);
            int[][] sobelx = {new int[] {-1, 0, 1},
                          new int[] {-2, 0, 2},
                          new int[] {-1, 0, 1}};

            int[][] sobely = {new int[] {-1, -2, -1},
                          new int[] { 0, 0, 0},
                          new int[] { 1, 2, 1}};

            for (int i = 1; i < bmp.Width - 1; i++)
            {
                for (int j = 1; j < bmp.Height - 1; j++)
                {
                    int dx = bmp.GetPixel(i - 1, j - 1).R * sobelx[0][0] + bmp.GetPixel(i, j - 1).R * sobelx[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobelx[0][2]
                              + bmp.GetPixel(i - 1, j).R * sobelx[1][0] + bmp.GetPixel(i, j).R * sobelx[1][1] + bmp.GetPixel(i + 1, j).R * sobelx[1][2]
                              + bmp.GetPixel(i - 1, j + 1).R * sobelx[2][0] + bmp.GetPixel(i, j + 1).R * sobelx[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobelx[2][2];

                    int dy = bmp.GetPixel(i - 1, j - 1).R * sobely[0][0] + bmp.GetPixel(i, j - 1).R * sobely[0][1] + bmp.GetPixel(i + 1, j - 1).R * sobely[0][2]
                           + bmp.GetPixel(i - 1, j).R * sobely[1][0] + bmp.GetPixel(i, j).R * sobely[1][1] + bmp.GetPixel(i + 1, j).R * sobely[1][2]
                           + bmp.GetPixel(i - 1, j + 1).R * sobely[2][0] + bmp.GetPixel(i, j + 1).R * sobely[2][1] + bmp.GetPixel(i + 1, j + 1).R * sobely[2][2];
                    double derivata = Math.Sqrt((dx * dx) + (dy * dy));

                    if (derivata > 255)
                    {
                        res.SetPixel(i, j, Color.White);
                    }
                    else
                    {
                        res.SetPixel(i, j, Color.FromArgb(255, (int)derivata, (int)derivata, (int)derivata));
                    }
                }
            }


问:
how to use real function of inheritance class when it's in pointer c++
```<code>class A{
public:
    int aaa;
    A(){aaa=0};
    void print() const;
};
class B : public A{
public:
    int bbb;
    B(){aaa=0,bbb=12};
    void print() const;
};

void A::print() const{
    cout << aaa << endl;
}
void B::print() const{
    cout << bbb << endl;
}

int main(){
    A *ptr[2];
    ptr[0]=new B();
    ptr->print(); //it will show 0 from aaa but how to show 12 from bbb.
}
</code>```

I want to show 12 (in class B : public A) not 0 in class A.
Someone know much of pointer and inheritance and polymorphism please help me to know how thanks!

答: You must make the function virtual. Use keyword virtual in the function definition

Body:
class A{
public:
    int aaa;
    A(){aaa=0};
    void print() const;
};
class B : public A{
public:
    int bbb;
    B(){aaa=0,bbb=12};
    void print() const;
};

void A::print() const{
    cout << aaa << endl;
}
void B::print() const{
    cout << bbb << endl;
}

int main(){
    A *ptr[2];
    ptr[0]=new B();
    ptr->print(); //it will show 0 from aaa but how to show 12 from bbb.
}

I want to show 12 (in class B : public A) not 0 in class A.
Someone know much of pointer and inheritance and polymorphism please help me to know how thanks!


问:
Migrating a project from C# to Java
With some changes in the staffing at the office, the levels of C# expertise has dropped off precipitously and there are now more Java developers. It has gotten to the point where the higher-ups are considering moving an existing .NET project written in C# into the Java world.

Aside from the obvious problem of starting completely from scratch what are the possible ways that this company can accomplish a successful move of development on a project from .NET C# into Java?

答:
Possibly you could use jni4net - opensource bridge ?
Or list of other options I know.</p>

Title: Migrating a project from C# to Java


问:
How to display superscript dynamic values in dynamically created table using javascript
```<code><script>
    var a = new Array();
    var table1 = document.createElement('table');
    for(i=0;i<10;i++)
    {
        j = i.toString();
        a = 2+j.sup();
    }

    for(tableIndex=0;tableIndex<10;tableIndex++)
    {
        var td1 = document.createElement('td');
        var text1 = document.createTextNode(a[tableIndex]);
        td1.appendChild(text1);
        tr.appendChild(td1);
        td1.style.borderStyle = "solid";
        td1.style.padding = "10px";
    }
    table1.appendChild(tr);
</script>
</code>```

In this script, I have created dynamic table and i want value inside row to be superscript of 2.But it is not getting displayed properly,it shows something like "2 sup 0 sup close" tags.

答: As explained by the MDN, the sup function is very deprecated. I suggest you wrap your number in a , add a sup class and use css to style it.

Body: As explained by the MDN, the sup function is very deprecated. I suggest you wrap your number in a <span></span>, add a sup class and use css to style it.


问:
Importing SQL to SQLite
I have a database in sql format, and I need to make an sqlite copy in order to add it in an Android App I'm making.

So far, I haven't got anything working for me. I tried to import the sql into SQLite Database Browser but it doesn't import properly, it always gives out an error statement. I tried creating a database then import the tables but it crashed.

I tried using sqlite3 via Terminal (I'm using a Mac if that would make any difference), however the .import FILE TABLE format doesn't work, it says: "Error: no such table: TABLE". I tried creating an empty table using "create table test42" then ".import test.sql test42 and variants but it says "Error: near "test": Syntax error".

I'm stuck.

Any help would greatly help. Thanks.

答:
I have just found one Solution.
Firstly You just need to Open your MySql File and Remove extra text.After that In SQliteDb Browser You need to create a Database Which must contain Table or Same column which MySQl file have.After that, Open or Import that(Mysql) file in SQlite DB Browser. It will successfully Convert into Sqlite database.
For More Help or Procedure.. See this Tutorial:
https://youtu.be/UcAHsm9iwpw
Thanks</p>

Title: Importing SQL to SQLite


问:
Attempt to present alertcontroller whose view is not in window hierarchy
I'm getting the following error in Swift 3:

```<code>Attempt to present alertcontroller whose view is not in window hierarchy
</code>```

I have already referred to other posts on this topic to no avail. More specifically, I've implemented the change suggested in this post: AlertController is not in the window hierarchy

and I'm still receiving the same error.

What I've done is:

Create an AlertHelper.swift helper class:

```<code>class AlertHelper {
</code>```

func showAlert(fromController controller: UIViewController) {
    let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert)
    controller.present(alert, animated: true, completion: nil)
}
}

In my View Controller, under a function which is called when a button is pressed, I check to see if an email address entered by a user is already stored in my Firebase database, and if so, I try to present an "Email already in use" alert from the AlertHelper class:

```<code>Auth.auth().createUser(withEmail: email, password: password) { (user, error)     in
        if error != nil {
            if let errCode = AuthErrorCode(rawValue: error!._code) {
                switch errCode {
                case .emailAlreadyInUse:
                    let alert = AlertHelper()
                    alert.showAlert(fromController: self)
                    return
                default:
                    print("other error")
                }
            }
        }
        else {
            // Inputs user email into database
            self.ref.child("Users").child((user?.uid)!).setValue(["Email": email, "Location": ""])
            self.performSegue(withIdentifier: "todorm", sender: self)
        }
    }
</code>```

The database stuff works, the only thing that isn't appearing is the alert. Any ideas? Thanks!!

答:
It's sort of a strange practice to subclass your alert into a separate class.

You should try making a method in your ViewController class

```<code>func showAlert() {
   let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert)
   self.present(alert, animated: true, completion: nil)
}
</code>```

Call the method using:

```<code>self.showAlert()
</code>```

Body:
I'm getting the following error in Swift 3:

Attempt to present alertcontroller whose view is not in window hierarchy

I have already referred to other posts on this topic to no avail. More specifically, I've implemented the change suggested in this post: AlertController is not in the window hierarchy

and I'm still receiving the same error.

What I've done is:

Create an AlertHelper.swift helper class:

class AlertHelper {

func showAlert(fromController controller: UIViewController) {
    let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert)
    controller.present(alert, animated: true, completion: nil)
}
}

In my View Controller, under a function which is called when a button is pressed, I check to see if an email address entered by a user is already stored in my Firebase database, and if so, I try to present an "Email already in use" alert from the AlertHelper class:

Auth.auth().createUser(withEmail: email, password: password) { (user, error)     in
        if error != nil {
            if let errCode = AuthErrorCode(rawValue: error!._code) {
                switch errCode {
                case .emailAlreadyInUse:
                    let alert = AlertHelper()
                    alert.showAlert(fromController: self)
                    return
                default:
                    print("other error")
                }
            }
        }
        else {
            // Inputs user email into database
            self.ref.child("Users").child((user?.uid)!).setValue(["Email": email, "Location": ""])
            self.performSegue(withIdentifier: "todorm", sender: self)
        }
    }

The database stuff works, the only thing that isn't appearing is the alert. Any ideas? Thanks!!

Body:
It's sort of a strange practice to subclass your alert into a separate class.

You should try making a method in your ViewController class

func showAlert() {
   let alert = UIAlertController(title: "Please Try Again", message: "Email Already In Use", preferredStyle: .alert)
   self.present(alert, animated: true, completion: nil)
}

Call the method using:

self.showAlert()


答:
Use virtual functions. In other terms:

```<code>class A{
public:
    int aaa;
    A(){aaa=0;};
    virtual void print() const;
};
</code>```

Title: how to use real function of inheritance class when it's in pointer c++

Body:
Use virtual functions. In other terms:

class A{
public:
    int aaa;
    A(){aaa=0;};
    virtual void print() const;
};


问:
Save periodically with AJAX
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

```<code>var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});
</code>```

答:
Try this:

$(document).on("keyup", "#target", function() {
     var counter = $('#counter');
     if (parseInt(counter.val()) > 30) {
         counter.val("0");
         console.log("Send Ajax");
     }
     counter.val(function(i, val) { return +val+1 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="target" placeholder="Target">
<input type="text" id="counter" value="0"></code>```

Or:

var counter = 0;
$(document).on("keyup", "#target", function() {
     if (counter > 30) {
         counter = 0;
         console.log("Send Ajax");
     }
     counter++;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="target" placeholder="Target"></code>```

Title: Save periodically with AJAX

Body:
I'd like to write a code that will save content of an element either after some many characters have been typed or once so often.

I will call ajax function and send content to a script to save in the background. Just not sure how to get that count going. Here's if I count to 30, but how would it look if it were continuous typing, i.e. every 30 chars?

var count = 0;

$(document).on("keyup", "#target", function(count) {
     if (count > 30) {
         $.ajax({
             ...
         });
     }
     count++;
});

Body:
Try this:

$(document).on("keyup", "#target", function() {
     var counter = $('#counter');
     if (parseInt(counter.val()) > 30) {
         counter.val("0");
         console.log("Send Ajax");
     }
     counter.val(function(i, val) { return +val+1 });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="target" placeholder="Target">
<input type="text" id="counter" value="0">

Or:

var counter = 0;
$(document).on("keyup", "#target", function() {
     if (counter > 30) {
         counter = 0;
         console.log("Send Ajax");
     }
     counter++;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="target" placeholder="Target">


问:
How do I test services in polymer?
I'm writing a polymer app and have a service that is used by polymer elements. I want to test this service but can't figure out how.

Here's what I have in the service:

```<code><script src="../../webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../web-component-tester/browser.js"></script>

<link rel="import" href="../test-service.html">

<script>
define('test-service', () => {
  class TestService {
    constructor(componentA, componentB) {
      this.componentA = componentA;
      this.componentB = componentB;
    }
  }
  return TestService;
});
</script>
</code>```

How can I test this? If I try simply including the .html file I don't have access to TestService.

答:
This is the full html of an example test. Basically add your test-service tag via test-fixture and then see if it work appropriately.

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>test-service test</title>

    <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../../web-component-tester/browser.js"></script>

    <link rel="import" href="../test-service.html">
</head>
<body>

<test-fixture id="BasicTestFixture">
    <template>
        <test-service></test-service>
    </template>
</test-fixture>

<script>
    suite('test-service', function() {

        test('instantiating the element with default properties works', function() {
            let testService = fixture('BasicTestFixture');
            assert.equal(testService.apiUrl, 'http://myapi.domain.com');
            // possible something like
            // let addResult = testService.addElement(...);
            // assert.equals(addResult, '{"result": "success"}');
        });

    });
</script>

</body>
</html>
</code>```

Title: How do I test services in polymer?

Body:
I'm writing a polymer app and have a service that is used by polymer elements. I want to test this service but can't figure out how.

Here's what I have in the service:

<link rel="import" href="../test-service.html">

How can I test this? If I try simply including the .html file I don't have access to TestService.

Body:
This is the full html of an example test. Basically add your test-service tag via test-fixture and then see if it work appropriately.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">

    <title>test-service test</title>

    <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../../web-component-tester/browser.js"></script>

    <link rel="import" href="../test-service.html">
</head>
<body>

<test-fixture id="BasicTestFixture">
    <template>
        <test-service></test-service>
    </template>
</test-fixture>

<script>
    suite('test-service', function() {

        test('instantiating the element with default properties works', function() {
            let testService = fixture('BasicTestFixture');
            assert.equal(testService.apiUrl, 'http://myapi.domain.com');
            // possible something like
            // let addResult = testService.addElement(...);
            // assert.equals(addResult, '{"result": "success"}');
        });

    });
</script>

</body>
</html>


问:
Ignore text length on score calculation Elasticsearch
I am working with ES 5. Using Nest 5 on C#.
I have an index for a Person in my ES solution. This person has a First Name, Last Name fields between others.

For these fields I am using a "Whitespace" tokenizer with "trim" and "lowercase" token filters.
I implemented a search in wich I look by these 2 fields. The problem I am having is with the score calculation. This is just an example to ilustrate the problem:

If I search by "Lucas Gonzales"
And I have 2 documents where

Document 1:
FirstName = "Lucas"
LastName = "Perez"

Document 2:
FirstName = "Lucas Juan Jose"
LastName = "Gonzales de Perez Almeida",

Even when document 2 has the 2 terms (Lucas and Gonzales) the first one is return first.
When I see the query with the explanation on kibana I notice that for document 2, the score is lower because the text length is greater.

What I want to do is to get first the document that has more terms matchs, regarless of the text length (or any other criteria). So for this example the second document will have 2 terms that match, "Lucas" and "Gonzales", so it should be return first.

Is there a good way to do this? taking into account that my person model has around 20 properties and the query needs to run fast.

答:
You should disable norms for your fields in order to eliminate the impact of fields length. Here is an example of the mapping:

```<code>PUT my_index/_mapping/my_type
{
    "properties": {
        "firstName": {
            "type": "text",
            "norms": {
                "enabled": false
            }
        },
        "lastName": {
            "type": "text",
            "norms": {
                "enabled": false
            }
        }
    }
}
</code>```

or, in case of NEST client, here is an attribute mapping

```<code>class Sample
{
    [Text(Norms = false)]
    public string FirstName { get; set; }

    [Text(Norms = false)]
    public string LastName { get; set; }
}

client.CreateIndex(indexName,
    create => create.Mappings(
        mappings => mappings.Map<Sample>(
            map => map.AutoMap()
        )
    )
);
</code>```

Body:
You should disable norms for your fields in order to eliminate the impact of fields length. Here is an example of the mapping:

PUT my_index/_mapping/my_type
{
    "properties": {
        "firstName": {
            "type": "text",
            "norms": {
                "enabled": false
            }
        },
        "lastName": {
            "type": "text",
            "norms": {
                "enabled": false
            }
        }
    }
}

or, in case of NEST client, here is an attribute mapping

class Sample
{
    [Text(Norms = false)]
    public string FirstName { get; set; }

    [Text(Norms = false)]
    public string LastName { get; set; }
}

client.CreateIndex(indexName,
    create => create.Mappings(
        mappings => mappings.Map<Sample>(
            map => map.AutoMap()
        )
    )
);


答:
Make the function virtual which will delay the binding of function name to its body.

```<code>virtual void print() const;
</code>```

Body:
Make the function virtual which will delay the binding of function name to its body.

virtual void print() const;


问:
how to display the English DisplayName in .net core view instead of the localized string
i have a .net core project where in one of my views i have to display the
DisplayName  in English and in Arabic in the same view
only i get one language as the view have localized resource file </p>

<p>i created an extension method which take the model and return the DisplayName  metadata
actually my method and the original @html helper return one language
here the method i hope some one can modify it so it return the original English metadata instead of the localized value </p>

```<code>using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using System;
using System.Linq.Expressions;

namespace iSee.IHtmlHelpers
{

    public static class HtmlExtensions
    {
        public static IHtmlContent DisplayNameForEn<TModel, TValue>(
            this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression
        )
        {
            var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, htmlHelper.ViewData, htmlHelper.MetadataProvider);
            var metadata = modelExplorer.Metadata;
            var DisplayName = metadata.DisplayName;
            return new HtmlString(DisplayName);
        }
    }
}
</code>```

答:
You could do it with code like the example below.

```<code>public static IHtmlContent DisplayNameFor<TModel, TValue>(
        this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression,CultureInfo culture
    )
    {
        if (culture == null)
        {
            culture = CultureInfo.CurrentCulture;
        }
        var displayAttribute = (expression.Body as MemberExpression)?.Member.GetCustomAttributes()
            .FirstOrDefault(tt => tt is DisplayAttribute) as DisplayAttribute;
        if (displayAttribute == null)
        {
            return new HtmlString("");
        }
        var resourceType = displayAttribute.ResourceType;
        var name = displayAttribute.Name;
        if(resourceType == null)
        {
          return new HtmlString(name);
        }
        var resourceManager = new global::System.Resources.ResourceManager(resourceType);
        var displayName = resourceManager.GetString(name, culture);
        return new HtmlString(displayName);
    }
</code>```

In general you want to take the DisplayAttribute.ResourceType and the DisplayAttribute.Name then use the Resource Manager along with the culture info of the language you want to translate it.

EDIT 2:

A possible Exception on .NET Core would be due to the changes on how the .resx files are used in .NET Core. Making the method above more suitable for .NET Framework applications and the IStringLocalizer<T> solution from the first EDIT more suitable for the ASP.NET Core

EDIT:

You can also use the IStringLocalizer<T> feature of ASP.NET Core find some reference here: Globalization and Localization. For example you could update the above method to use the IStringLocalizer

```<code>var culture = new CultureInfo("en-gb");
var localizer = factory.Create(typeof(Startup));
var specificLoc = localizer.WithCulture(culture);
</code>```

Body:
i have a .net core project where in one of my views i have to display the
DisplayName  in English and in Arabic in the same view
only i get one language as the view have localized resource file

i created an extension method which take the model and return the DisplayName  metadata
actually my method and the original @html helper return one language
here the method i hope some one can modify it so it return the original English metadata instead of the localized value

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using System;
using System.Linq.Expressions;

namespace iSee.IHtmlHelpers
{

    public static class HtmlExtensions
    {
        public static IHtmlContent DisplayNameForEn<TModel, TValue>(
            this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression
        )
        {
            var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, htmlHelper.ViewData, htmlHelper.MetadataProvider);
            var metadata = modelExplorer.Metadata;
            var DisplayName = metadata.DisplayName;
            return new HtmlString(DisplayName);
        }
    }
}

Body:
You could do it with code like the example below.

public static IHtmlContent DisplayNameFor<TModel, TValue>(
        this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression,CultureInfo culture
    )
    {
        if (culture == null)
        {
            culture = CultureInfo.CurrentCulture;
        }
        var displayAttribute = (expression.Body as MemberExpression)?.Member.GetCustomAttributes()
            .FirstOrDefault(tt => tt is DisplayAttribute) as DisplayAttribute;
        if (displayAttribute == null)
        {
            return new HtmlString("");
        }
        var resourceType = displayAttribute.ResourceType;
        var name = displayAttribute.Name;
        if(resourceType == null)
        {
          return new HtmlString(name);
        }
        var resourceManager = new global::System.Resources.ResourceManager(resourceType);
        var displayName = resourceManager.GetString(name, culture);
        return new HtmlString(displayName);
    }

In general you want to take the DisplayAttribute.ResourceType and the DisplayAttribute.Name then use the Resource Manager along with the culture info of the language you want to translate it.

EDIT 2:

A possible Exception on .NET Core would be due to the changes on how the .resx files are used in .NET Core. Making the method above more suitable for .NET Framework applications and the IStringLocalizer<T> solution from the first EDIT more suitable for the ASP.NET Core

EDIT:

You can also use the IStringLocalizer<T> feature of ASP.NET Core find some reference here: Globalization and Localization. For example you could update the above method to use the IStringLocalizer

var culture = new CultureInfo("en-gb");
var localizer = factory.Create(typeof(Startup));
var specificLoc = localizer.WithCulture(culture);


问:
How to listen to mouse hold event?
I know mousedown is when user press the mouse, mouseup is when user release the mouse. But I want to listen the event after user press the mouse and hold it until it release. Any ideas?

答:
var setint  = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
   clearInterval(setint);
   val = 0;
   setint = setInterval(function () {
       $("#putdata").val(++val);
        console.log("mousehold");
   },50);
});
$('#hold').on("mouseleave mouseup", function () {
   val = 0;
   $("#putdata").val(val);
   clearInterval(setint);
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />
</body>
<html></code>```

ContentLicense: CC BY-SA 4.0

Title: How to listen to mouse hold event?

Body:
var setint  = '';
$(document).ready(function() {
var val = 0;
$('#hold').on('mousedown',function (e) {
   clearInterval(setint);
   val = 0;
   setint = setInterval(function () {
       $("#putdata").val(++val);
        console.log("mousehold");
   },50);
});
$('#hold').on("mouseleave mouseup", function () {
   val = 0;
   $("#putdata").val(val);
   clearInterval(setint);
});
});

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="putdata" />
<input type="button" value="mouse-hold" id="hold" />
</body>
<html>


问:
Python requests .get() from multiple pages?
I'm learning how to webscrape with python and I'm wondering if it's possible to grab two pages with requests.get() so that I don't  have to make two separate calls and variables. For example:

```<code>r1 = requests.get("page1")
r2 = requests.get("page2")

pg1 = BeautifulSoup(r1.content, "html.parser")
pg2 = BeautifulSoup(r2.content, "html.parser")
</code>```

As you can see there's repeated code. Any way around this? Thanks!

答:
I like the grequests library for fetching multiple URLS at one time, instead of requests. Especially when dealing with alot of URLS or a single URL with many sub-pages.

```<code>import grequests
urls = ['http://google.com', 'http://yahoo.com', 'http://bing.com']
unsent_request = (grequests.get(url) for url in urls)

results = grequests.map(unsent_request)
</code>```

After this, results can be processed however you need. This works well with JSON data: results[0] = first URL data, results[1] = second URL data, etc..

more can be found here

Body:
I'm learning how to webscrape with python and I'm wondering if it's possible to grab two pages with requests.get() so that I don't  have to make two separate calls and variables. For example:

r1 = requests.get("page1")
r2 = requests.get("page2")

pg1 = BeautifulSoup(r1.content, "html.parser")
pg2 = BeautifulSoup(r2.content, "html.parser")

As you can see there's repeated code. Any way around this? Thanks!

Body:
I like the grequests library for fetching multiple URLS at one time, instead of requests. Especially when dealing with alot of URLS or a single URL with many sub-pages.

import grequests
urls = ['http://google.com', 'http://yahoo.com', 'http://bing.com']
unsent_request = (grequests.get(url) for url in urls)

results = grequests.map(unsent_request)

After this, results can be processed however you need. This works well with JSON data: results[0] = first URL data, results[1] = second URL data, etc..

more can be found here


问:
SQLite unique constraint on multiple column without order
I need help on a problem in my table definitions : I have a table which will be defined, for example, like this :

id, primary key

friend0_id, foreign key on table users

friend1_id, foreign key on table users

The problem is I do not want to have multiple times the couple (friend0_id, friend1_id), whatever the order the are in the table.

I tried to define an UNIQUE constraint on the couple (friend0_id, friend1_id), but the columns order defined in the constraint (here friend0_id, THEN friend1_id) matters. So :

```<code>| id | friend0_id | friend1_id |
|----|------------|------------|
| 1  |      3     |      4     | -> OK
| 2  |      4     |      3     | -> OK, as the columns order in index matters
| 3  |      3     |      4     | -> Not OK, constraint prevent this
</code>```

I would like the id 2 and 3 in the example to be disallowed, but I can't figure how. Do you have some tips for me ?

Thank you,
naccyde

答:
As @mu too short mentioned, the way is to use (greatest(friend0_id, friend1_id), least(friend0_id, friend1_id)), so, now I have a working 2 columns order free unique constraint. I did it in SQLite this way (which could not be the better) :

Create a trigger which set min(friend0_id, friend1_id) to friend0 and max(friend0_id, friend1_id) to friend1 :

```<code>CREATE TRIGGER friend_fixed_id_order_trigger
AFTER INSERT ON friends
BEGIN UPDATE friends
  SET
    friend0_id = min(NEW.friend0_id, NEW.friend1_id),
    friend1_id = max(NEW.friend0_id, NEW.friend1_id)
  WHERE friends.id = NEW.id;
END
</code>```

Then, set a unique constraint on the couple (friend0_id, friend1_id) :

```<code>CREATE UNIQUE INDEX `friends_unique_relation_index`
ON `contacts` (`friend0_id` ,`friend1_id`)
</code>```

And it works !

EDIT : If someone need this tip, do not forget to create an update trigger too, otherwise an update request could break the mechanism.

Body:
I need help on a problem in my table definitions : I have a table which will be defined, for example, like this :

id, primary key

friend0_id, foreign key on table users

friend1_id, foreign key on table users

The problem is I do not want to have multiple times the couple (friend0_id, friend1_id), whatever the order the are in the table.

I tried to define an UNIQUE constraint on the couple (friend0_id, friend1_id), but the columns order defined in the constraint (here friend0_id, THEN friend1_id) matters. So :

| id | friend0_id | friend1_id |
|----|------------|------------|
| 1  |      3     |      4     | -> OK
| 2  |      4     |      3     | -> OK, as the columns order in index matters
| 3  |      3     |      4     | -> Not OK, constraint prevent this

I would like the id 2 and 3 in the example to be disallowed, but I can't figure how. Do you have some tips for me ?

Thank you,
naccyde

Body:
As @mu too short mentioned, the way is to use (greatest(friend0_id, friend1_id), least(friend0_id, friend1_id)), so, now I have a working 2 columns order free unique constraint. I did it in SQLite this way (which could not be the better) :

Create a trigger which set min(friend0_id, friend1_id) to friend0 and max(friend0_id, friend1_id) to friend1 :

CREATE TRIGGER friend_fixed_id_order_trigger
AFTER INSERT ON friends
BEGIN UPDATE friends
  SET
    friend0_id = min(NEW.friend0_id, NEW.friend1_id),
    friend1_id = max(NEW.friend0_id, NEW.friend1_id)
  WHERE friends.id = NEW.id;
END

Then, set a unique constraint on the couple (friend0_id, friend1_id) :

CREATE UNIQUE INDEX `friends_unique_relation_index`
ON `contacts` (`friend0_id` ,`friend1_id`)

And it works !

EDIT : If someone need this tip, do not forget to create an update trigger too, otherwise an update request could break the mechanism.


问:
Conditionally binding dropdownlist in asp.net
I have a string in this particular format

```<code>string LogInIDs = 124,345, 876 | 765,322, 98 | 565,99
</code>```

All the numbers in the string are Unique LogIn ID. Using the Pipe symbol, the grouping is done of id's. Now, Suppose the LogInID is 345, then i need to bind other numbers (in this case 124 & 876) which are in the group in a dropdown. The below function is what i have made to retrieve the other numbers.

Can anybody come up with any better idea or suggestion

```<code>public static List<string> RetrieveAffCodes(string LogInIDs , string LogInID)
{
    List<string> _finale = new List<string>();

    string[] sep1 = new string[1];
    sep1[0] = "|";

    int count = LogInIDs.Count(x => x == '|');
    string[] groups = new string[count + 1];
    groups = LogInIDs.Split(sep1, StringSplitOptions.RemoveEmptyEntries);

    foreach (string g in groups)
    {
        string p = g;
        string[] sep2 = new string[1];
        sep2[0] = ",";
        int counter = p.Count(x => x == ',');
        string[] final_list = new string[counter + 1];
        final_list = p.Split(sep2, StringSplitOptions.RemoveEmptyEntries);

        foreach (string _f in final_list)
        {
            if (_f.Trim() == LogInID)
            {
          _finale =  AddLogInIDs(final_list, final_list.Count());
            }
        }
    }
    return _finale;
}

private static List<string> AddLogInIDs(string[] final_list, int p)
{
    List<string> _finale = new List<string>();
    foreach (var item in final_list)
    {
        _finale.Add(item.Trim());
    }
    return _finale;
}
</code>```

Any suggestions will be embraced.

Thanks for your time and patience.

Note: The string will be expanding up to 200 groups

答:
try this..</p>

```<code>    public static List<string> RetrieveAffCodes(string logInIDs, string logInID)
    {
        return logInIDs
        .Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Where(a => a.Split(',').Any(c => c.Trim().Equals(logInID)))
        .Select(a => a.Split(',').ToList()).FirstOrDefault();
    }
</code>```

Body:
I have a string in this particular format

string LogInIDs = 124,345, 876 | 765,322, 98 | 565,99

All the numbers in the string are Unique LogIn ID. Using the Pipe symbol, the grouping is done of id's. Now, Suppose the LogInID is 345, then i need to bind other numbers (in this case 124 & 876) which are in the group in a dropdown. The below function is what i have made to retrieve the other numbers.

Can anybody come up with any better idea or suggestion

public static List<string> RetrieveAffCodes(string LogInIDs , string LogInID)
{
    List<string> _finale = new List<string>();

    string[] sep1 = new string[1];
    sep1[0] = "|";

    int count = LogInIDs.Count(x => x == '|');
    string[] groups = new string[count + 1];
    groups = LogInIDs.Split(sep1, StringSplitOptions.RemoveEmptyEntries);

    foreach (string g in groups)
    {
        string p = g;
        string[] sep2 = new string[1];
        sep2[0] = ",";
        int counter = p.Count(x => x == ',');
        string[] final_list = new string[counter + 1];
        final_list = p.Split(sep2, StringSplitOptions.RemoveEmptyEntries);

        foreach (string _f in final_list)
        {
            if (_f.Trim() == LogInID)
            {
          _finale =  AddLogInIDs(final_list, final_list.Count());
            }
        }
    }
    return _finale;
}

private static List<string> AddLogInIDs(string[] final_list, int p)
{
    List<string> _finale = new List<string>();
    foreach (var item in final_list)
    {
        _finale.Add(item.Trim());
    }
    return _finale;
}

Any suggestions will be embraced.

Thanks for your time and patience.

Note: The string will be expanding up to 200 groups

Body:
try this..

    public static List<string> RetrieveAffCodes(string logInIDs, string logInID)
    {
        return logInIDs
        .Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
        .Where(a => a.Split(',').Any(c => c.Trim().Equals(logInID)))
        .Select(a => a.Split(',').ToList()).FirstOrDefault();
    }