问:
python - How to jump os.system() process
I run a Rpi W (Rbian Jessie), like a timelapse countdown system with the following script that permit to take picture every minute and sleep when a button is turned off. The program check the button each 5 seconds.

```<code># This Python file uses the following encoding: utf-8

from time import sleep
from picamera import PiCamera
import os
import time
import RPi.GPIO as GPIO
import picamera
import datetime as dt

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
os.system('sudo python /home/pi/log.py')
check = GPIO.input(17)

while check == 0: #si l'état initial du bouton = 0
        check = GPIO.input(17)
        print(check)
        sleep(5)

while check == 1: #si l'état initial = 1

        with picamera.PiCamera() as camera:
                camera.resolution = (1280, 720)
                sleep(1)
                t1 = dt.datetime.now().strftime('-%d_%m_%Y-%H_%M_%S')
                t2 = 'IMG'+ t1
                camera.capture('/home/pi/Pictures/%s.jpg' % t2)
                print('Captured %s' % t2)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(4)
        check = GPIO.input(17)
        print(check)

    while check == 0: #si l'état initial du bouton = 0
            check = GPIO.input(17)
            print(check)
            sleep(5)
</code>```

I'm sure the script is an abomination...

But that I want to do is : call another script named log.py (monitor T° and time/min). However, the main script is stoping after the line : #os.system('sudo python /home/pi/log.py')... The script is running ok without this line.

Can someone know something about?

答:
Use:

```<code> os.system('sudo python /home/pi/log.py &')
</code>```

The & forks the process.

Body:
I run a Rpi W (Rbian Jessie), like a timelapse countdown system with the following script that permit to take picture every minute and sleep when a button is turned off. The program check the button each 5 seconds.

# This Python file uses the following encoding: utf-8

from time import sleep
from picamera import PiCamera
import os
import time
import RPi.GPIO as GPIO
import picamera
import datetime as dt

GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
os.system('sudo python /home/pi/log.py')
check = GPIO.input(17)

while check == 0: #si l'état initial du bouton = 0
        check = GPIO.input(17)
        print(check)
        sleep(5)

while check == 1: #si l'état initial = 1

        with picamera.PiCamera() as camera:
                camera.resolution = (1280, 720)
                sleep(1)
                t1 = dt.datetime.now().strftime('-%d_%m_%Y-%H_%M_%S')
                t2 = 'IMG'+ t1
                camera.capture('/home/pi/Pictures/%s.jpg' % t2)
                print('Captured %s' % t2)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(5)
        check = GPIO.input(17)
        print(check)
        sleep(4)
        check = GPIO.input(17)
        print(check)

    while check == 0: #si l'état initial du bouton = 0
            check = GPIO.input(17)
            print(check)
            sleep(5)

I'm sure the script is an abomination...

But that I want to do is : call another script named log.py (monitor T° and time/min). However, the main script is stoping after the line : #os.system('sudo python /home/pi/log.py')... The script is running ok without this line.

Can someone know something about?

Body:
Use:

 os.system('sudo python /home/pi/log.py &')

The & forks the process.


来源: stackexchange

问:
in a select statement - how to include a filter after a function b4 the from clause
I want to select the top sales person by 'location & Product' combination.
1st I Sort & Rank, then I sum for "Location & Product", then I want to drop all but the top sales person by "Location & Product" such that the query result contains only The Top Salesperson by "Location & Product" with the total sales for each "Location & Product" combination.

The one part I don't have is the "select Rank = 1" - adding a "where" clause after "From" does not work:

```<code>Select Location, Product, Sales, Salesperson
       row_number() OVER (PARTITION BY concat(Location,Product) ORDER BY Sales desc) AS Rank,
       Sum(Sales) OVER(PARTITION BY concat(Location,Product)) AS Salesbylocprod
From Table A
</code>```

答:
You can use a subquery.  Also, you don't need to concatenate keys for the partition by:

```<code>Select Location, Product, Sales, Salesperson, Salesbylocprod
from (select a.*
             row_number() over (partition by Location, Product order by Sales desc) as seqnum,
             sum(Sales) over (partition by Location, Product) as Salesbylocprod
      From Table A
     ) a
where seqnum = 1;
</code>```

Note that I changed the name of the column from rank to seqnum.  rank would sort of imply that it is calculated using the rank() function.  That is different from row_number() so the name is misleading.

ContentLicense: CC BY-SA 3.0

Body:
I want to select the top sales person by 'location & Product' combination.
1st I Sort & Rank, then I sum for "Location & Product", then I want to drop all but the top sales person by "Location & Product" such that the query result contains only The Top Salesperson by "Location & Product" with the total sales for each "Location & Product" combination.

The one part I don't have is the "select Rank = 1" - adding a "where" clause after "From" does not work:

Select Location, Product, Sales, Salesperson
       row_number() OVER (PARTITION BY concat(Location,Product) ORDER BY Sales desc) AS Rank,
       Sum(Sales) OVER(PARTITION BY concat(Location,Product)) AS Salesbylocprod
From Table A

Body:
You can use a subquery.  Also, you don't need to concatenate keys for the partition by:

Select Location, Product, Sales, Salesperson, Salesbylocprod
from (select a.*
             row_number() over (partition by Location, Product order by Sales desc) as seqnum,
             sum(Sales) over (partition by Location, Product) as Salesbylocprod
      From Table A
     ) a
where seqnum = 1;

Note that I changed the name of the column from rank to seqnum.  rank would sort of imply that it is calculated using the rank() function.  That is different from row_number() so the name is misleading.


问:
What does "throw new NotImplementedException();" do exactly?
I have a class 'b' that inherits from class 'a'.  In class 'a' there is some code that performs an action if an event is not null.  I need that code to fire in class 'b' during specific times in the application.  So in 'b' I subscribed to a new Handler(event).

If I leave the autogenerated event 'as is' in class 'b' with the throw new NotImplementedException(); line, the code works/runs as expected.  As soon as I remove the thow exception, the application no longer works as expected.

So, what is the throw new NotImplementedException doing besides throwing the exception?

I realize I'm probably trying to solve my coding problem the wrong way at this point, and I am sure I will find a better way to do it (I'm still learning), but my question remains.  Why does that line change the outcome of code?

EDIT:
I reallize I wan't very specific with my code.  Unfortunately, because of strict policies, I can't be.  I have in class 'a' an if statement.

```<code>if (someEvent != null)
</code>```

When the code 'works', the if statement is returning true.  When it isn't working as expected, it is returning 'false'.  In class 'b', the only time the application 'works' (or the if statement returns true), is when I have the throw new NotImplementedException(); line in class 'b's event method that is autogenerated when I attached the new event.

答:
NotImplementedException is simply an exception that is used when the code for what you're trying to do isn't written yet. It's often used in snippets as a placeholder until you fill in the body of whatever has been generated with actual code.

It's good practice to use a NotImplementedException as opposed to an empty block of code, because it will very clearly throw an error alerting you that section of your code isn't complete yet. If it was blank, then the method might run and nothing would happen, and that's a pain to debug sometimes.

Body:
I have a class 'b' that inherits from class 'a'.  In class 'a' there is some code that performs an action if an event is not null.  I need that code to fire in class 'b' during specific times in the application.  So in 'b' I subscribed to a new Handler(event).

If I leave the autogenerated event 'as is' in class 'b' with the throw new NotImplementedException(); line, the code works/runs as expected.  As soon as I remove the thow exception, the application no longer works as expected.

So, what is the throw new NotImplementedException doing besides throwing the exception?

I realize I'm probably trying to solve my coding problem the wrong way at this point, and I am sure I will find a better way to do it (I'm still learning), but my question remains.  Why does that line change the outcome of code?

EDIT:
I reallize I wan't very specific with my code.  Unfortunately, because of strict policies, I can't be.  I have in class 'a' an if statement.

if (someEvent != null)

When the code 'works', the if statement is returning true.  When it isn't working as expected, it is returning 'false'.  In class 'b', the only time the application 'works' (or the if statement returns true), is when I have the throw new NotImplementedException(); line in class 'b's event method that is autogenerated when I attached the new event.


问:
remove emoticons in R using tm package
I'm using the tm package to clean up a Twitter Corpus. However, the package is unable to clean up emoticons.

Here's a replicated code:

```<code>July4th_clean <- tm_map(July4th_clean, content_transformer(tolower))
Error in FUN(content(x), ...) : invalid input 'RT ElleJohnson Love of country is encircling the globes ������������������ july4thweekend July4th FourthOfJuly IndependenceDay NotAvailableOnIn' in 'utf8towcs'
</code>```

Can someone point me in the right direction to remove the emoticons using the tm package?

Thank you,

Luis

答:
you can try this function

```<code>iconv(July4th_clean, "latin1", "ASCII", sub="")
</code>```

Duplicate issue, see post

Title: remove emoticons in R using tm package

Body:
I'm using the tm package to clean up a Twitter Corpus. However, the package is unable to clean up emoticons.

Here's a replicated code:

July4th_clean <- tm_map(July4th_clean, content_transformer(tolower))
Error in FUN(content(x), ...) : invalid input 'RT ElleJohnson Love of country is encircling the globes ������������������ july4thweekend July4th FourthOfJuly IndependenceDay NotAvailableOnIn' in 'utf8towcs'

Can someone point me in the right direction to remove the emoticons using the tm package?

Thank you,

Luis

Body:
you can try this function

iconv(July4th_clean, "latin1", "ASCII", sub="")

Duplicate issue, see post


问:
Avoiding type conflicts with dplyr::case_when
I am trying to use dplyr::case_when within dplyr::mutate to create a new variable where I set some values to missing and recode other values simultaneously.

However, if I try to set values to NA, I get an error saying that we cannot create the variable new because NAs are logical:

Error in mutate_impl(.data, dots) :

    Evaluation error: must be type double, not logical.

Is there a way to set values to NA in a non-logical vector in a data frame using this?

```<code>library(dplyr)

# Create data
df <- data.frame(old = 1:3)

# Create new variable
df <- df %>% dplyr::mutate(new = dplyr::case_when(old == 1 ~ 5,
                                                  old == 2 ~ NA,
                                                  TRUE ~ old))

# Desired output
c(5, NA, 3)
</code>```

答:
As said in ?case_when:

All RHSs must evaluate to the same type of vector.

You actually have two possibilities:

1) Create new as a numeric vector

```<code>df <- df %>% mutate(new = case_when(old == 1 ~ 5,
                                    old == 2 ~ NA_real_,
                                    TRUE ~ as.numeric(old)))
</code>```

Note that NA_real_ is the numeric version of NA, and that you must convert old to numeric because you created it as an integer in your original dataframe.

You get:

```<code>str(df)
# 'data.frame': 3 obs. of  2 variables:
# $ old: int  1 2 3
# $ new: num  5 NA 3
</code>```

2) Create new as an integer vector

```<code>df <- df %>% mutate(new = case_when(old == 1 ~ 5L,
                                    old == 2 ~ NA_integer_,
                                    TRUE ~ old))
</code>```

Here, 5L forces 5 into the integer type, and NA_integer_ is the integer version of NA.

So this time new is integer:

```<code>str(df)
# 'data.frame': 3 obs. of  2 variables:
# $ old: int  1 2 3
# $ new: int  5 NA 3
</code>```

Body:
I am trying to use dplyr::case_when within dplyr::mutate to create a new variable where I set some values to missing and recode other values simultaneously.

However, if I try to set values to NA, I get an error saying that we cannot create the variable new because NAs are logical:

Error in mutate_impl(.data, dots) :

    Evaluation error: must be type double, not logical.

Is there a way to set values to NA in a non-logical vector in a data frame using this?

library(dplyr)

# Create data
df <- data.frame(old = 1:3)

# Create new variable
df <- df %>% dplyr::mutate(new = dplyr::case_when(old == 1 ~ 5,
                                                  old == 2 ~ NA,
                                                  TRUE ~ old))

# Desired output
c(5, NA, 3)

Body:
As said in ?case_when:

All RHSs must evaluate to the same type of vector.

You actually have two possibilities:

1) Create new as a numeric vector

df <- df %>% mutate(new = case_when(old == 1 ~ 5,
                                    old == 2 ~ NA_real_,
                                    TRUE ~ as.numeric(old)))

Note that NA_real_ is the numeric version of NA, and that you must convert old to numeric because you created it as an integer in your original dataframe.

You get:

str(df)
# 'data.frame': 3 obs. of  2 variables:
# $ old: int  1 2 3
# $ new: num  5 NA 3

2) Create new as an integer vector

df <- df %>% mutate(new = case_when(old == 1 ~ 5L,
                                    old == 2 ~ NA_integer_,
                                    TRUE ~ old))

Here, 5L forces 5 into the integer type, and NA_integer_ is the integer version of NA.

So this time new is integer:

str(df)
# 'data.frame': 3 obs. of  2 variables:
# $ old: int  1 2 3
# $ new: int  5 NA 3


问:
Android Push Email Applicaition
I wanna write a application with push email capablity. Can some one guide me over the same ?</p>

ContentLicense: CC BY-SA 2.5

Title: Android Push Email Applicaition

Body: Check this http://code.google.com/p/k9mail/


问:
Python: Apply an aggregating function to a variable by an aggregating dimension and select columns
I assume, I have a pandas DataFrame with variables V1, V2, V3. I want to do the following aggregation procedure
    myData.groupby("V1“, as_index=False)["V2"].sum()
and then display this result together with variable V3 (if possible in one step!). How can I do this, any suggestions? Thanks!

Edit:
From the original data frame:

```<code>V1    V2    V3
 1     2     4
 2     1     3
 1     4     1
</code>```

I would like to receive:

```<code>V1    V2         V3
 1     **6**     4
 2     1         3
 1     **6**     1
</code>```

So keeping V3 as it is. Can anyone help:)?

答:
Setup

Consider the dataframe myData

```<code>myData = pd.DataFrame(dict(V1=[1, 1, 2, 2], V2=[2] * 4, V3=[3] * 4))

   V1  V2  V3
0   1   2   3
1   1   2   3
2   2   2   3
3   2   2   3
</code>```

Option 1

groupby and agg

In my opinion, the most idiomatic way to perform this task.

```<code>myData.groupby('V1', as_index=False).agg('sum')

   V1  V2  V3
0   1   4   6
1   2   4   6
</code>```

Option 2

set_index and sum w/ level

This also works but is a bit awkward with the setting and resetting of the index.

```<code>myData.set_index('V1').sum(level='V1').reset_index()

   V1  V2  V3
0   1   4   6
1   2   4   6
</code>```

Option 3

np.unique and np.bincount

As a matter of perspective, we can begin to appreciate what pandas offers us in terms of api.  If performance is a must, you can sometimes (but not always) decrease your execution time but you also assume the responsibility of handling many nuances pandas does for you.  And again, almost always, the code is less transparent.

```<code>u, f = np.unique(myData.V1.values, return_inverse=True)

pd.DataFrame(dict(
        V1=u,
        V2=np.bincount(f, myData.V2.values),
        V3=np.bincount(f, myData.V3.values)
    )).astype(myData.dtypes)

   V1  V2  V3
0   1   4   6
1   2   4   6
</code>```

Timing

```<code>%timeit myData.groupby('V1', as_index=False).agg('sum')
%timeit myData.set_index('V1').sum(level='V1').reset_index()

1000 loops, best of 3: 1.54 ms per loop
1000 loops, best of 3: 1.52 ms per loop

%%timeit
u, f = np.unique(myData.V1.values, return_inverse=True)

pd.DataFrame(dict(
        V1=u,
        V2=np.bincount(f, myData.V2.values),
        V3=np.bincount(f, myData.V3.values)
    )).astype(myData.dtypes)

1000 loops, best of 3: 654 µs per loop
</code>```

Body:
I assume, I have a pandas DataFrame with variables V1, V2, V3. I want to do the following aggregation procedure
    myData.groupby("V1“, as_index=False)["V2"].sum()
and then display this result together with variable V3 (if possible in one step!). How can I do this, any suggestions? Thanks!

Edit:
From the original data frame:

V1    V2    V3
 1     2     4
 2     1     3
 1     4     1

I would like to receive:

V1    V2         V3
 1     **6**     4
 2     1         3
 1     **6**     1

So keeping V3 as it is. Can anyone help:)?

Body:
Setup

Consider the dataframe myData

myData = pd.DataFrame(dict(V1=[1, 1, 2, 2], V2=[2] * 4, V3=[3] * 4))

   V1  V2  V3
0   1   2   3
1   1   2   3
2   2   2   3
3   2   2   3

Option 1

groupby and agg

In my opinion, the most idiomatic way to perform this task.

myData.groupby('V1', as_index=False).agg('sum')

   V1  V2  V3
0   1   4   6
1   2   4   6

Option 2

set_index and sum w/ level

This also works but is a bit awkward with the setting and resetting of the index.

myData.set_index('V1').sum(level='V1').reset_index()

   V1  V2  V3
0   1   4   6
1   2   4   6

Option 3

np.unique and np.bincount

As a matter of perspective, we can begin to appreciate what pandas offers us in terms of api.  If performance is a must, you can sometimes (but not always) decrease your execution time but you also assume the responsibility of handling many nuances pandas does for you.  And again, almost always, the code is less transparent.

u, f = np.unique(myData.V1.values, return_inverse=True)

pd.DataFrame(dict(
        V1=u,
        V2=np.bincount(f, myData.V2.values),
        V3=np.bincount(f, myData.V3.values)
    )).astype(myData.dtypes)

   V1  V2  V3
0   1   4   6
1   2   4   6

Timing

%timeit myData.groupby('V1', as_index=False).agg('sum')
%timeit myData.set_index('V1').sum(level='V1').reset_index()

1000 loops, best of 3: 1.54 ms per loop
1000 loops, best of 3: 1.52 ms per loop

%%timeit
u, f = np.unique(myData.V1.values, return_inverse=True)

pd.DataFrame(dict(
        V1=u,
        V2=np.bincount(f, myData.V2.values),
        V3=np.bincount(f, myData.V3.values)
    )).astype(myData.dtypes)

1000 loops, best of 3: 654 µs per loop


问:
jquery.mention Default Text
I am trying to implement jquery.mentions for sugesting users in the system when entering the @ sign.

All is working well, with an Ajax query being used to populate the list.

However, for editing existing comments I am struggling.

I have set the default text to a valid value that was generated previously, but it does not display correctly.

The value rendered is

```<code>@[Peter Jones](contact:200)
</code>```

which displays as Peter Jones

If I set this to the default text, it is displayed as @Peter Jones (showing the @ sign)

Is this a bug? Does anybody have a fix?

My code is as follows

```<code>$(function () {

    $('textarea.mention').mentionsInput({
        defaultValue  : '@[Peter Jones](contact:200)',
        onDataRequest:function (mode, query, callback) {
            $.getJSON('Ajax/GetUserTags.php', function(responseData) {
            responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
            callback.call(this, responseData);
            });
        }
    });

    $('.get-syntax-text').click(function() {
      $('textarea.mention').mentionsInput('val', function(text) {
        alert(text);
      });
    });

    $('.get-mentions').click(function() {
      $('textarea.mention').mentionsInput('getMentions', function(data) {
        alert(JSON.stringify(data));
      });
    }) ;

  });
</code>```

答:
I looked in the jquery.mentionsinput and adjusted the resetInput function.

When setting the newMentionText, I have removed the Match[1] element which is the @ sign.

```<code>    function resetInput(currentVal) {
        mentionsCollection = [];
        var mentionText = utils.htmlEncode(currentVal);
        var regex = new RegExp("(" + settings.triggerChar + ")\\[(.*?)\\]\\((.*?):(.*?)\\)", "gi");
        var match, newMentionText = mentionText;
        while ((match = regex.exec(mentionText)) != null) {
            //alert(match[0] + "\n" + match[1] + "\n" + match[2]);
            //newMentionText = newMentionText.replace(match[0], match[1] + match[2]);
            newMentionText = newMentionText.replace(match[0], match[2]);
            mentionsCollection.push({ 'id': match[4], 'type': match[3], 'value': match[2], 'trigger': match[1] });
        }
        elmInputBox.val(newMentionText);
        updateValues();
    }
</code>```

Tested with multiple tags and all works OK.

Title: jquery.mention Default Text

Body:
I am trying to implement jquery.mentions for sugesting users in the system when entering the @ sign.

All is working well, with an Ajax query being used to populate the list.

However, for editing existing comments I am struggling.

I have set the default text to a valid value that was generated previously, but it does not display correctly.

The value rendered is

@[Peter Jones](contact:200)

which displays as Peter Jones

If I set this to the default text, it is displayed as @Peter Jones (showing the @ sign)

Is this a bug? Does anybody have a fix?

My code is as follows

$(function () {

    $('textarea.mention').mentionsInput({
        defaultValue  : '@[Peter Jones](contact:200)',
        onDataRequest:function (mode, query, callback) {
            $.getJSON('Ajax/GetUserTags.php', function(responseData) {
            responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
            callback.call(this, responseData);
            });
        }
    });

    $('.get-syntax-text').click(function() {
      $('textarea.mention').mentionsInput('val', function(text) {
        alert(text);
      });
    });

    $('.get-mentions').click(function() {
      $('textarea.mention').mentionsInput('getMentions', function(data) {
        alert(JSON.stringify(data));
      });
    }) ;

  });

Body:
I looked in the jquery.mentionsinput and adjusted the resetInput function.

When setting the newMentionText, I have removed the Match[1] element which is the @ sign.

    function resetInput(currentVal) {
        mentionsCollection = [];
        var mentionText = utils.htmlEncode(currentVal);
        var regex = new RegExp("(" + settings.triggerChar + ")\\[(.*?)\\]\\((.*?):(.*?)\\)", "gi");
        var match, newMentionText = mentionText;
        while ((match = regex.exec(mentionText)) != null) {
            //alert(match[0] + "\n" + match[1] + "\n" + match[2]);
            //newMentionText = newMentionText.replace(match[0], match[1] + match[2]);
            newMentionText = newMentionText.replace(match[0], match[2]);
            mentionsCollection.push({ 'id': match[4], 'type': match[3], 'value': match[2], 'trigger': match[1] });
        }
        elmInputBox.val(newMentionText);
        updateValues();
    }

Tested with multiple tags and all works OK.


问:
why am I getting type errors when hovering over map after layers are set?
I have a map that I'm building here:  https://www.jsnippet.net/snippet/1437/

It's a drawingmanager solution, where I can draw a circle, square, or polygon.  Not multiple layers, just one.

THe polygon placement is working perfectly (although I'm trying to figure out deleting a polygon vertice), but my problem truly is the console.

after placing a polygon, circle, or rectangle, I started receiving hovering errors on the map:

```<code>Uncaught TypeError: Cannot read property 'Sa' of null
    at UV.<anonymous> (onion.js:59)
    at Object._.A.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&libraries=drawing&callback=initMap:102)
    at UV.handleEvent (onion.js:63)
    at jy._.k.de (map.js:44)
    at Object._.A.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&libraries=drawing&callback=initMap:102)
    at hq.<anonymous> (common.js:132)
    at Object._.A.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&libraries=drawing&callback=initMap:102)
    at nq (common.js:87)
    at hq.<anonymous> (common.js:192)
    at hq.<anonymous> (common.js:192)
</code>```

This error occurs when I hover over the map, and when I move the mouse, it continues to show.  I don't know how to figure this out.  any wisdom would be greatly appreciated.

Thanks.

UPDATE #1:

I tested against multiple browsers (Opera, Firefox, IE, and Chrome), I am getting the same response plus the following error:

```<code>Uncaught TypeError: JSON.parse is not a function
    at lW (onion.js:29)
    at OV.<anonymous> (onion.js:59)
    at Object._.z.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&v=3&libraries=drawing&callback=initMap:102)
    at OV.handleEvent (onion.js:63)
    at hy._.k.be (map.js:44)
    at Object._.z.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&v=3&libraries=drawing&callback=initMap:102)
    at aq.<anonymous> (common.js:135)
    at Object._.z.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&v=3&libraries=drawing&callback=initMap:102)
    at gq (common.js:90)
    at aq.<anonymous> (common.js:200)
</code>```

Now, I'm not calling JSON.parse specifically, but it sounds like I'm doing it incidentally.  Where?  and how do I fix it?  Thanks!

答:
You have made a very nice mistake in this function:

```<code>function setJSON(Shape) {
  console.log(Shape.type);
  if (Shape.type === "circle") {
    return '{"type":"' + Shape.type + '", "lat":"' + Shape.getCenter().lat() + '", "lng":"' + Shape.getCenter().lng() + '", "radius":"' + Shape.getRadius() + '"  }';
  }
  if (Shape.type === "rectangle") {
    return '{"type":"' + Shape.type + ', "start":"' + Shape.getBounds().getNorthEast() + '", "end":"' + Shape.getBounds().getSouthWest() + '"}';
  }
  if (Shape.type === "polygon") {
    //eturn '{"type":"'+ Shape.type +'"}' + Shape.getPaths();
    vertice = Shape.getPath();
    console.log("vertice count:  " + vertice.getLength());

/* HERE */
           JSON = '{"type":"' + Shape.type + '", "coordinates": "';
/* ^^^  */

    vertice.forEach(function(xy, i) {
      JSON = JSON + xy.lat() + ' ' + xy.lng() + ', ';
    });

    JSON = JSON.slice(0, -2) + '"}';
    return JSON;
  }

  return 0
}
</code>```

You're overriding the global JSON object, so JSON do not have its methods anymore.

Fix it by declaring variable whithin the function scope:

var JSON = '{"type":"' + Shape.type + '", "coordinates": "';

https://www.jsnippet.net/snippet/1440/

Even better rename it to myJSON or whatever.

And better avoid global names like JSON, window, document etc. So you'll avoid a confusion.

Body:
I have a map that I'm building here:  https://www.jsnippet.net/snippet/1437/

It's a drawingmanager solution, where I can draw a circle, square, or polygon.  Not multiple layers, just one.

THe polygon placement is working perfectly (although I'm trying to figure out deleting a polygon vertice), but my problem truly is the console.

after placing a polygon, circle, or rectangle, I started receiving hovering errors on the map:

Uncaught TypeError: Cannot read property 'Sa' of null
    at UV.<anonymous> (onion.js:59)
    at Object._.A.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&libraries=drawing&callback=initMap:102)
    at UV.handleEvent (onion.js:63)
    at jy._.k.de (map.js:44)
    at Object._.A.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&libraries=drawing&callback=initMap:102)
    at hq.<anonymous> (common.js:132)
    at Object._.A.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&libraries=drawing&callback=initMap:102)
    at nq (common.js:87)
    at hq.<anonymous> (common.js:192)
    at hq.<anonymous> (common.js:192)

This error occurs when I hover over the map, and when I move the mouse, it continues to show.  I don't know how to figure this out.  any wisdom would be greatly appreciated.

Thanks.

UPDATE #1:

I tested against multiple browsers (Opera, Firefox, IE, and Chrome), I am getting the same response plus the following error:

Uncaught TypeError: JSON.parse is not a function
    at lW (onion.js:29)
    at OV.<anonymous> (onion.js:59)
    at Object._.z.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&v=3&libraries=drawing&callback=initMap:102)
    at OV.handleEvent (onion.js:63)
    at hy._.k.be (map.js:44)
    at Object._.z.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&v=3&libraries=drawing&callback=initMap:102)
    at aq.<anonymous> (common.js:135)
    at Object._.z.trigger (js?key=AIzaSyALxYexJJN5slLNWWGijb16z2Dys66ASIA&v=3&libraries=drawing&callback=initMap:102)
    at gq (common.js:90)
    at aq.<anonymous> (common.js:200)

Now, I'm not calling JSON.parse specifically, but it sounds like I'm doing it incidentally.  Where?  and how do I fix it?  Thanks!

Body:
You have made a very nice mistake in this function:

function setJSON(Shape) {
  console.log(Shape.type);
  if (Shape.type === "circle") {
    return '{"type":"' + Shape.type + '", "lat":"' + Shape.getCenter().lat() + '", "lng":"' + Shape.getCenter().lng() + '", "radius":"' + Shape.getRadius() + '"  }';
  }
  if (Shape.type === "rectangle") {
    return '{"type":"' + Shape.type + ', "start":"' + Shape.getBounds().getNorthEast() + '", "end":"' + Shape.getBounds().getSouthWest() + '"}';
  }
  if (Shape.type === "polygon") {
    //eturn '{"type":"'+ Shape.type +'"}' + Shape.getPaths();
    vertice = Shape.getPath();
    console.log("vertice count:  " + vertice.getLength());

/* HERE */
           JSON = '{"type":"' + Shape.type + '", "coordinates": "';
/* ^^^  */

    vertice.forEach(function(xy, i) {
      JSON = JSON + xy.lat() + ' ' + xy.lng() + ', ';
    });

    JSON = JSON.slice(0, -2) + '"}';
    return JSON;
  }

  return 0
}

You're overriding the global JSON object, so JSON do not have its methods anymore.

Fix it by declaring variable whithin the function scope:

var JSON = '{"type":"' + Shape.type + '", "coordinates": "';

https://www.jsnippet.net/snippet/1440/

Even better rename it to myJSON or whatever.

And better avoid global names like JSON, window, document etc. So you'll avoid a confusion.


问:
Can't echo using json_encode
I can't echo $arreglo on line 23, the screen is blank. I am trying json encode, but I don't know why is not working. I have checked the conexion and it is ok...</p>

```<code><?php

include ("conexion.php");

$query = "SELECT * FROM usuario WHERE estado = 1 ORDER BY idusuario desc;";
$resultado = mysqli_query($conexion, $query);

if (!$resultado)
{
    die("error");
}
else
{

    while($data = mysqli_fetch_assoc($resultado))
    {
        //echo $arreglo["data"][]=array_map("utf8_encode", $data);
     $arreglo["data"][] = $data;

    }

    echo json_encode($arreglo);

    mysqli_free_result($resultado);
    mysqli_close($conexion);
}

?>
</code>```

答:
You need to use header before echo. check the code.</p>

```<code>header('Content-type: application/json');
echo json_encode($arreglo);
</code>```

Title: Can't echo using json_encode

Body:
I can't echo $arreglo on line 23, the screen is blank. I am trying json encode, but I don't know why is not working. I have checked the conexion and it is ok...

<?php

include ("conexion.php");

$query = "SELECT * FROM usuario WHERE estado = 1 ORDER BY idusuario desc;";
$resultado = mysqli_query($conexion, $query);

if (!$resultado)
{
    die("error");
}
else
{

    while($data = mysqli_fetch_assoc($resultado))
    {
        //echo $arreglo["data"][]=array_map("utf8_encode", $data);
     $arreglo["data"][] = $data;

    }

    echo json_encode($arreglo);

    mysqli_free_result($resultado);
    mysqli_close($conexion);
}

?>

Body:
You need to use header before echo. check the code.

header('Content-type: application/json');
echo json_encode($arreglo);


问:
Ionic 2 check Internet connection
I have installed the Cordova network plugin, but cannot seem to check network connection.

This is my code

```<code>import { Network } from 'ionic-native';

declare var navigator: any;
declare var Connection: any;

this.platform.ready().then(() => {
   if(Network.connection === 'none') {
       let alert = this.alertCtrl.create({
       title: "Internet Connection",
       subTitle:"Please Check Your Network connection",
       buttons: [{
          text: 'Ok',
          handler: () => {
              this.platform.exitApp();
             }
          }]
        });
      alert.present();
     }
  });
}
</code>```

I get warning message

Native: deviceready did not fire within 2000ms. This can happen when
  plugins are in an inconsistent state. Try removing plugins from
  plugins/ and reinstalling them.

How could i go about resolving the issue?

答: Navigator.Online only returns a Boolean when the app is on the browser not the device or phone</p>

Title: Ionic 2 check Internet connection

Body:
I have installed the Cordova network plugin, but cannot seem to check network connection.

This is my code

import { Network } from 'ionic-native';

declare var navigator: any;
declare var Connection: any;

this.platform.ready().then(() => {
   if(Network.connection === 'none') {
       let alert = this.alertCtrl.create({
       title: "Internet Connection",
       subTitle:"Please Check Your Network connection",
       buttons: [{
          text: 'Ok',
          handler: () => {
              this.platform.exitApp();
             }
          }]
        });
      alert.present();
     }
  });
}

I get warning message

Native: deviceready did not fire within 2000ms. This can happen when
  plugins are in an inconsistent state. Try removing plugins from
  plugins/ and reinstalling them.

How could i go about resolving the issue?


问:
Search for Entity that has multiple tags in doctrine
I have a many to many relation between Document and Tag. So a Document can have several Tags's, and one Tag can be assigned to different Document's.

This is Tag

```<code>AppBundle\Entity\Tag:
    type: entity
    table: tags
    repositoryClass: AppBundle\Repository\TagRepository
    manyToMany:
        documents:
          targetEntity: Document
          mappedBy: tags
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        label:
            type: string
            length: 255
            unique: true
</code>```

And Document

```<code>AppBundle\Entity\Document:
type: entity
table: documents
repositoryClass: AppBundle\Repository\DocumentRepository

manyToMany:
    tags:
      targetEntity: Tag
      inversedBy: documents
      joinTable:
          name: documents_tags
id:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
fields:
    title:
        type: string
        length: 255
</code>```

Now I want to search for all Documents that has the tags animal and fiction. How can I achieve that with doctrine?

Something like

```<code>$repository = $this->getDoctrine()->getRepository('AppBundle:Document');
$query = $repository->createQueryBuilder('d');
$query  ->join('d.tags', 't')
                ->where($query->expr()->orX(
                            $query->expr()->eq('t.label', ':tag'),
                            $query->expr()->eq('t.label', ':tag2')
                        ))
                ->setParameter('tag', $tag)
                ->setParameter('tag2', $tag2)
</code>```

wont do the job, because it returns all Documents that have either tag1 or tag2. But andX won't work too, because there is no single tag that has both labels.

答:
You can achieve this with additional inner joins for each tag:

Example:

```<code>$em = $this->getDoctrine()->getManager();
$repository = $this->getDoctrine()->getRepository('AppBundle:Document');
$query = $repository->createQueryBuilder('d');
$query->innerJoin('d.tags', 't1', Join::WITH, 't1.label = :tag1');
$query->innerJoin('d.tags', 't2', Join::WITH, 't2.label = :tag2');

$dql = $query->getDql();
$result = $em->createQuery($dql)
    ->setParameter('tag1', 'LabelForTag1')
    ->setParameter('tag2', 'LabelForTag2')
    ->getResult();
</code>```

Maybe this little image helps understanding what this query does. The whole circle represent all your documents. If you are only using one single join, the query will return either the green+red or the blue+red part.
Using an additional inner join, you will only get the intersection of the joins seen individually (which is only the red part).

If you have even more tags to search for, you can simply add another join for that.

Body:
I have a many to many relation between Document and Tag. So a Document can have several Tags's, and one Tag can be assigned to different Document's.

This is Tag

AppBundle\Entity\Tag:
    type: entity
    table: tags
    repositoryClass: AppBundle\Repository\TagRepository
    manyToMany:
        documents:
          targetEntity: Document
          mappedBy: tags
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        label:
            type: string
            length: 255
            unique: true

And Document

AppBundle\Entity\Document:
type: entity
table: documents
repositoryClass: AppBundle\Repository\DocumentRepository

manyToMany:
    tags:
      targetEntity: Tag
      inversedBy: documents
      joinTable:
          name: documents_tags
id:
    id:
        type: integer
        id: true
        generator:
            strategy: AUTO
fields:
    title:
        type: string
        length: 255

Now I want to search for all Documents that has the tags animal and fiction. How can I achieve that with doctrine?

Something like

$repository = $this->getDoctrine()->getRepository('AppBundle:Document');
$query = $repository->createQueryBuilder('d');
$query  ->join('d.tags', 't')
                ->where($query->expr()->orX(
                            $query->expr()->eq('t.label', ':tag'),
                            $query->expr()->eq('t.label', ':tag2')
                        ))
                ->setParameter('tag', $tag)
                ->setParameter('tag2', $tag2)

wont do the job, because it returns all Documents that have either tag1 or tag2. But andX won't work too, because there is no single tag that has both labels.

Body:
You can achieve this with additional inner joins for each tag:

Example:

$em = $this->getDoctrine()->getManager();
$repository = $this->getDoctrine()->getRepository('AppBundle:Document');
$query = $repository->createQueryBuilder('d');
$query->innerJoin('d.tags', 't1', Join::WITH, 't1.label = :tag1');
$query->innerJoin('d.tags', 't2', Join::WITH, 't2.label = :tag2');

$dql = $query->getDql();
$result = $em->createQuery($dql)
    ->setParameter('tag1', 'LabelForTag1')
    ->setParameter('tag2', 'LabelForTag2')
    ->getResult();

Maybe this little image helps understanding what this query does. The whole circle represent all your documents. If you are only using one single join, the query will return either the green+red or the blue+red part.
Using an additional inner join, you will only get the intersection of the joins seen individually (which is only the red part).

If you have even more tags to search for, you can simply add another join for that.


问:
Contravariant parameters?
This is probably a stupid question but, I have a method I use to make the syntax of a page a little more easy to read

```<code>    public void Do(Delegate method, DispatcherPriority priority = DispatcherPriority.Normal)
    {
        this.Window.Dispatcher.BeginInvoke(method, DispatcherPriority.Background);
    }
</code>```

then I can write

```<code>        Do(new Action(() =>
        {
            //DoStuff()
        }));
</code>```

However, I'd like to move the Action up into the Do Method  so I can write more Simply:

```<code>        Do(() =>
        {
            //DoStuff()
        }));
</code>```

But I'm a bit sure how to write the contravariant parameter to do the Do Method?

答:
Lambdas are untyped, so this is not possible.

If you don't care about method-arguments,  which appears to be the case, why not change the method signature to :

```<code>public void Do(Action method,
               DispatcherPriority priority = DispatcherPriority.Normal)
</code>```

Then, the second sample will work fine since the compiler will be able to implicitly convert the lambda to an Action.

If you really want to accept an instance of any delegate-type that represents a method that takes no arguments, you'll have to stick to something like what you currently have.

Title: Contravariant parameters?

Body:
This is probably a stupid question but, I have a method I use to make the syntax of a page a little more easy to read

    public void Do(Delegate method, DispatcherPriority priority = DispatcherPriority.Normal)
    {
        this.Window.Dispatcher.BeginInvoke(method, DispatcherPriority.Background);
    }

then I can write

        Do(new Action(() =>
        {
            //DoStuff()
        }));

However, I'd like to move the Action up into the Do Method  so I can write more Simply:

        Do(() =>
        {
            //DoStuff()
        }));

But I'm a bit sure how to write the contravariant parameter to do the Do Method?

Body:
Lambdas are untyped, so this is not possible.

If you don't care about method-arguments,  which appears to be the case, why not change the method signature to :

public void Do(Action method,
               DispatcherPriority priority = DispatcherPriority.Normal)

Then, the second sample will work fine since the compiler will be able to implicitly convert the lambda to an Action.

If you really want to accept an instance of any delegate-type that represents a method that takes no arguments, you'll have to stick to something like what you currently have.


问:
Increasing speed of subquery sql statement (mysql)
Is it possible to increase the speed of this sql statement?

```<code>SELECT
    (SELECT
            time
        FROM
            log
        WHERE
            user_id = 'name'
                AND category = 'Login'
        ORDER BY time DESC
        LIMIT 1 , 1) AS login_time,
    (SELECT
            time
        FROM
            log
        WHERE
            user_id = 'name'
                AND category = 'Logout'
                AND app = 'RES'
        ORDER BY time DESC
        LIMIT 1) AS res_logout_timea
</code>```

Its currently taking 10-16 seconds to complete and slowing down my app, anything I can do to improve efficiency? I was thinking about left joining the same table on itself instead of using a subquery, but I wasn't able to get the syntax down. Any help would be appreciated. Thanks

答:
Even better is

```<code>INDEX(user_id, category, time)       -- for the 1st subquery
INDEX(user_id, category, app, time)  -- for the 2nd subquery
</code>```

The time column must be last; the order of the other columns does not matter.  You might, for example, have these two

```<code>INDEX(user_id, category, time)       -- for the 1st subquery
INDEX(app, user_id, category, time)  -- for the 2nd subquery
</code>```

thereby helping some other query that needs an index starting with app.

Body:
Is it possible to increase the speed of this sql statement?

SELECT
    (SELECT
            time
        FROM
            log
        WHERE
            user_id = 'name'
                AND category = 'Login'
        ORDER BY time DESC
        LIMIT 1 , 1) AS login_time,
    (SELECT
            time
        FROM
            log
        WHERE
            user_id = 'name'
                AND category = 'Logout'
                AND app = 'RES'
        ORDER BY time DESC
        LIMIT 1) AS res_logout_timea

Its currently taking 10-16 seconds to complete and slowing down my app, anything I can do to improve efficiency? I was thinking about left joining the same table on itself instead of using a subquery, but I wasn't able to get the syntax down. Any help would be appreciated. Thanks

Body:
Even better is

INDEX(user_id, category, time)       -- for the 1st subquery
INDEX(user_id, category, app, time)  -- for the 2nd subquery

The time column must be last; the order of the other columns does not matter.  You might, for example, have these two

INDEX(user_id, category, time)       -- for the 1st subquery
INDEX(app, user_id, category, time)  -- for the 2nd subquery

thereby helping some other query that needs an index starting with app.


问:
show percentage scale in ggMarginal plot
With this code:

```<code>ggMarginal(p1, margins = "x", size = 2, type = "histogram",
       col = "blue", fill = "orange")
</code>```

I can make this type of plot:

But I would like to show on the y axis of the histogram the values in percentage scale, could you help me?

答:
you should import package (scales), should look something like this

```<code>...
library('scales')
ggMarginal(p1, margins = "x", size = 2, type = "histogram",
       col = "blue", fill = "orange") + scale_y_continuous(labels=percent)
</code>```

Body:
With this code:

ggMarginal(p1, margins = "x", size = 2, type = "histogram",
       col = "blue", fill = "orange")

I can make this type of plot:

But I would like to show on the y axis of the histogram the values in percentage scale, could you help me?

Body:
you should import package (scales), should look something like this

...
library('scales')
ggMarginal(p1, margins = "x", size = 2, type = "histogram",
       col = "blue", fill = "orange") + scale_y_continuous(labels=percent)


问:
Turning CSV data into nested JSON using OpenRefine
So I am trying to parse some weather data from a csv format and convert it to a nested JSON format. I currently have a large csv file with columns for: A Station ID, Month, and then 30 Columns for the data (per day). I have a header at the top with basic titles. I am trying to convert that into a json format where the Station ID is the key name, and inside of it there the months 1-12 are another key name, and inside of those each of the 30 days are displayed. I tried several online and donwlaodable CSV to JSON, and spent time playing with OpenRefine, but could not figure out how to take the Station id as the header and then nest the months, and then days. Here is a sample of the CSV data for reference : Station Name,Month,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
AQW00061705,1,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,824C,825C,825C,825C,825C,825C,825C,825C,825C,825C,825C,826C,826C,826C.

There are 12 of these columns for every station id making this process especially difficult. If anyone has an experience with OpenRefine, or converting this type of structured data to JSON, it would be very appreciated.

答:
So writing an export template for this in OpenRefine is a bit of a pain, but can be done.

First in the OpenRefine project use the 'Edit Cells -> Blank Down' menu option on the Station Name column
Then go to Export and choose "Templating"
In the 'Prefix' section just put [
In the Row Template section put:

```<code>    {{if(row.record.fromRowIndex==row.index,if(row.record.fromRowIndex>0,",","")+"{\"Station Name\" :"+ jsonize(cells["Station Name"].value)+",","")}}
{{jsonize(cells["Month"].value)}}:{
{{forEach(row.columnNames[2,33],v,jsonize(v)+": "+jsonize(cells[v].value)+if(v!="31",",",""))}}
}{{if(cells["Month"].value!="12",",","")}}
{{if(row.index+1==row.record.toRowIndex,unescape("}","html"),"")}}
</code>```

Leave the Row Separator section blank
In the 'Suffix' section just put ]

This should give you valid JSON like:

```<code>    [
  {
    "Station Name": "AQW00061705",
    "1": {
      "1": "824C",
      "2": "824C",
      "3": "824C",
      "4": "824C",
      "5": "824C",
</code>```

etc.

The first '1' is the Month number, the subsequent "1": "824C" etc are the days and the readings

I've had to put a load of logic in here to get this to work - in theory a simpler version should have worked I think, but I saw some odd behaviour which led to invalid JSON - hence I've worked all the logic into the GREL within the template

Body:
So writing an export template for this in OpenRefine is a bit of a pain, but can be done.

First in the OpenRefine project use the 'Edit Cells -> Blank Down' menu option on the Station Name column
Then go to Export and choose "Templating"
In the 'Prefix' section just put [
In the Row Template section put:

    {{if(row.record.fromRowIndex==row.index,if(row.record.fromRowIndex>0,",","")+"{\"Station Name\" :"+ jsonize(cells["Station Name"].value)+",","")}}
{{jsonize(cells["Month"].value)}}:{
{{forEach(row.columnNames[2,33],v,jsonize(v)+": "+jsonize(cells[v].value)+if(v!="31",",",""))}}
}{{if(cells["Month"].value!="12",",","")}}
{{if(row.index+1==row.record.toRowIndex,unescape("&#x7d;","html"),"")}}

Leave the Row Separator section blank
In the 'Suffix' section just put ]

This should give you valid JSON like:

    [
  {
    "Station Name": "AQW00061705",
    "1": {
      "1": "824C",
      "2": "824C",
      "3": "824C",
      "4": "824C",
      "5": "824C",

etc.

The first '1' is the Month number, the subsequent "1": "824C" etc are the days and the readings

I've had to put a load of logic in here to get this to work - in theory a simpler version should have worked I think, but I saw some odd behaviour which led to invalid JSON - hence I've worked all the logic into the GREL within the template


问:
Dagger 2 static provider methods in kotlin
With the recent versions of dagger 2 one of the improvements made are the possibility of having static provide methods. Simply so:

```<code>@Provides
static A providesA() {
  return A();
}
</code>```

I was wondering how does one go about doing this in kotlin? I've tried

```<code>@Module
class AModule {
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }
}
</code>```

But I get the error message:

```<code>@Provides methods can only be present within a @Module or @ProducerModule
</code>```

I'm guessing there's something going on here with the companion object, however I'm quite new to Kotlin and I'm unsure of how one can do this. Is it even possible?

Thanks!

答:
I can't test it right now, but I think this should work:</p>

```<code>@Module
object AModule {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
}
</code>```

Body:
With the recent versions of dagger 2 one of the improvements made are the possibility of having static provide methods. Simply so:

@Provides
static A providesA() {
  return A();
}

I was wondering how does one go about doing this in kotlin? I've tried

@Module
class AModule {
  companion object {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
  }
}

But I get the error message:

@Provides methods can only be present within a @Module or @ProducerModule

I'm guessing there's something going on here with the companion object, however I'm quite new to Kotlin and I'm unsure of how one can do this. Is it even possible?

Thanks!

Body:
I can't test it right now, but I think this should work:

@Module
object AModule {
    @JvmStatic
    @Provides
    fun providesA(): A = A()
}


问:
'Variable is never used' warning in android studio
i have created a button(id- btnBank).
But there is waraning of variable 'btnBank'is never used.

code in activity_maps.xml

```<code><Button
        android:id="@+id/btnBank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bank" />
</code>```

code in MapsActivity.java

Button btnBank = (Button) findViewById(R.id.btnBank);

```<code>    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Bank = "bank";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Bank);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Bank", Toast.LENGTH_LONG).show();
        }
    });
</code>```

In first line of java code 'btnBank' appears grey

答: Because btnBank you never use it. Otherwise would not it show you the warning. In this code you do not use that variable. Only you use btnRestaurant.</p>

Body:
i have created a button(id- btnBank).
But there is waraning of variable 'btnBank'is never used.

code in activity_maps.xml

<Button
        android:id="@+id/btnBank"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bank" />

code in MapsActivity.java

Button btnBank = (Button) findViewById(R.id.btnBank);

    btnRestaurant.setOnClickListener(new View.OnClickListener() {
        String Bank = "bank";
        @Override
        public void onClick(View v) {
            Log.d("onClick", "Button is Clicked");
            mMap.clear();
            String url = getUrl(latitude, longitude, Bank);
            Object[] DataTransfer = new Object[2];
            DataTransfer[0] = mMap;
            DataTransfer[1] = url;
            Log.d("onClick", url);
            GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
            getNearbyPlacesData.execute(DataTransfer);
            Toast.makeText(MapsActivity.this,"Nearby Bank", Toast.LENGTH_LONG).show();
        }
    });

In first line of java code 'btnBank' appears grey


问:
Hibernate query filter on collection
I want to execute following query:

```<code>from Item i where i.categoryItems.catalogId = :catId
</code>```

That however yields in following exception: illegal attempt to dereference collection
So I googled, found this Hibernate forum post https://forum.hibernate.org/viewtopic.php?p=2349920 that recommended me to do the following:

```<code>from Item i, IN (i.categoryItems) WHERE i.catalogId = :catId
</code>```

This kind of works, but there's a problem with this:
It returns me an Object array with Item object and CategoryItem object. I'm only interested in the single Item object (List)

My mapping of 'Item':

```<code><hibernate-mapping package="be.xx.xx.xx.xx.domain" default-access="field">
  <class name="Item" table="ITEM">
    <id name="articleId" column="article_id" type="long">
        <generator class="assigned" />
    </id>
...
...
        <set name="categoryItems" table="CATEGORY_ITEM">
            <key column="item_id" />
            <one-to-many class="be.xx.xx.xx.xx.domain.CategoryItem" />
    </set>
</class>
</hibernate-mapping>
</code>```

Anybody got any ideas?

Thanks

答:
Try:

```<code>SELECT i FROM Item i inner join i.categoryItems cat WHERE cat.id = :catID
</code>```

Explanation:
The navigation you have tried: i.categoryItems.catalogId works only for 1:1 or n:1 relations, but not for 1:n. -- For 1:n you have to use the explicite join operation.

Title: Hibernate query filter on collection

Body:
I want to execute following query:

from Item i where i.categoryItems.catalogId = :catId

That however yields in following exception: illegal attempt to dereference collection
So I googled, found this Hibernate forum post https://forum.hibernate.org/viewtopic.php?p=2349920 that recommended me to do the following:

from Item i, IN (i.categoryItems) WHERE i.catalogId = :catId

This kind of works, but there's a problem with this:
It returns me an Object array with Item object and CategoryItem object. I'm only interested in the single Item object (List)

My mapping of 'Item':

<hibernate-mapping package="be.xx.xx.xx.xx.domain" default-access="field">
  <class name="Item" table="ITEM">
    <id name="articleId" column="article_id" type="long">
        <generator class="assigned" />
    </id>
...
...
        <set name="categoryItems" table="CATEGORY_ITEM">
            <key column="item_id" />
            <one-to-many class="be.xx.xx.xx.xx.domain.CategoryItem" />
    </set>
</class>
</hibernate-mapping>

Anybody got any ideas?

Thanks

Body:
Try:

SELECT i FROM Item i inner join i.categoryItems cat WHERE cat.id = :catID

Explanation:
The navigation you have tried: i.categoryItems.catalogId works only for 1:1 or n:1 relations, but not for 1:n. -- For 1:n you have to use the explicite join operation.


问:
Efficient creation of a matrix of offsets

Goal

I want to use a long vector of numbers, to create a matrix where each column is a successive offset (lag or lead) of the original vector. If n is the maximum offset, the matrix will have dimensions [length(vector), n * 2 + 1] (because we want offsets in both directions, and include the 0 offset, i.e. the original vector).

Example

To illustrate, consider the following vector:

```<code>test <- c(2, 8, 1, 10, 7, 5, 9, 3, 4, 6)

[1]  2  8  1 10  7  5  9  3  4  6
</code>```

Expected output

Now we create offsets of values, let's say for n == 3:

```<code>      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]   NA   NA   NA    2    8    1   10
 [2,]   NA   NA    2    8    1   10    7
 [3,]   NA    2    8    1   10    7    5
 [4,]    2    8    1   10    7    5    9
 [5,]    8    1   10    7    5    9    3
 [6,]    1   10    7    5    9    3    4
 [7,]   10    7    5    9    3    4    6
 [8,]    7    5    9    3    4    6   NA
 [9,]    5    9    3    4    6   NA   NA
[10,]    9    3    4    6   NA   NA   NA
</code>```

I am looking for an efficient solution. data.table or tidyverse solutions more than welcome.

Returning only the rows that have no NA's (i.e. rows 4 to 7) is also ok.

Current solution

```<code>lags  <- lapply(3:1, function(x) dplyr::lag(test, x))
leads <- lapply(1:3, function(x) dplyr::lead(test, x))
l <- c(lags, test, leads)
matrix(unlist(l), nrow = length(test))
</code>```

Body:
Goal

I want to use a long vector of numbers, to create a matrix where each column is a successive offset (lag or lead) of the original vector. If n is the maximum offset, the matrix will have dimensions [length(vector), n * 2 + 1] (because we want offsets in both directions, and include the 0 offset, i.e. the original vector).

Example

To illustrate, consider the following vector:

test <- c(2, 8, 1, 10, 7, 5, 9, 3, 4, 6)

[1]  2  8  1 10  7  5  9  3  4  6

Expected output

Now we create offsets of values, let's say for n == 3:

      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]   NA   NA   NA    2    8    1   10
 [2,]   NA   NA    2    8    1   10    7
 [3,]   NA    2    8    1   10    7    5
 [4,]    2    8    1   10    7    5    9
 [5,]    8    1   10    7    5    9    3
 [6,]    1   10    7    5    9    3    4
 [7,]   10    7    5    9    3    4    6
 [8,]    7    5    9    3    4    6   NA
 [9,]    5    9    3    4    6   NA   NA
[10,]    9    3    4    6   NA   NA   NA

I am looking for an efficient solution. data.table or tidyverse solutions more than welcome.

Returning only the rows that have no NA's (i.e. rows 4 to 7) is also ok.

Current solution

lags  <- lapply(3:1, function(x) dplyr::lag(test, x))
leads <- lapply(1:3, function(x) dplyr::lead(test, x))
l <- c(lags, test, leads)
matrix(unlist(l), nrow = length(test))

Body:
This can be solved by constructing the matrix from a long vector and returning only the wanted columns and rows:

test <- c(2, 8, 1, 10, 7, 5, 9, 3, 4, 6)
n_offs <- 3L
n_row <- length(test) + n_offs + 1L
matrix(rep(c(rep(NA, n_offs), test), n_row), nrow = n_row)[1:length(test), 1:(n_offs * 2L + 1L)]

      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
 [1,]   NA   NA   NA    2    8    1   10
 [2,]   NA   NA    2    8    1   10    7
 [3,]   NA    2    8    1   10    7    5
 [4,]    2    8    1   10    7    5    9
 [5,]    8    1   10    7    5    9    3
 [6,]    1   10    7    5    9    3    4
 [7,]   10    7    5    9    3    4    6
 [8,]    7    5    9    3    4    6   NA
 [9,]    5    9    3    4    6   NA   NA
[10,]    9    3    4    6   NA   NA   NA

A variant which just returns the same result as embed(test, 7)[, 7:1] is:

matrix(rep(test, length(test) + 1L), nrow = length(test) + 1L)[
  seq_len(length(test) - 2L * n_offs), seq_len(n_offs * 2L + 1L)]

     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    2    8    1   10    7    5    9
[2,]    8    1   10    7    5    9    3
[3,]    1   10    7    5    9    3    4
[4,]   10    7    5    9    3    4    6


问:
angular js sending empty data to php using post method
I am making a test application to test angular and php data transfer.
But angular is  sending data through post method but php is not accepting the data

```<code><!DOCTYPE html>
<html>
<head>
  <title>Test</title>
    <script

src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
    </script>
</head>
<body ng-app="myApp">
<div ng-controller="myctrl">
 <form ng-submit="insert()">
   <input type="text" ng-model="name" name="name" placeholder="name">
   <input type="age" ng-model="age" name="age" placeholder="age">
   <button type="submit">Submit</button>
 </form>
</div>
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.controller('myctrl',function($scope,$http){

    $scope.insert=function(){

        $http.post("test.php", {
            'name':$scope.name,
            'age':$scope.age
        }).then(function(response){
                console.log(response);
            },function(error){
                alert("Sorry! Data Couldn't be inserted!");
                console.error(error);

            });
        }
    });
 </script>
</body>
</html>
</code>```

This is the html code
The php code is

```<code><?php

    $data = json_decode(file_get_contents('php://input'));
    $place=$data->name;
    $image=$data->age;
    echo $place;
    echo $image;
    echo "string";
?>
</code>```

When i access these name and age its giving the error as

"

Notice:  Trying to get property of non-object in C:\xampp\htdocs\test\test.php on line 5

Notice:  Trying to get property of non-object in C:\xampp\htdocs\test\test.php on line 6

string"

but angular is sending the data
data:Object
age:"2"
name:"abcd"
cant identify where is the problem.

答:
One way to make proper post request to php is through $httpParamSerializerJQLike,

so you can make a post like this:

```<code>var data = {
        'name':$scope.name,
        'age':$scope.age
    };
var req = {
      method : "POST",
      url: "http://yourUrl",
      data: $httpParamSerializerJQLike(data),
      headers: {
        'Content-Type': "application/x-www-form-urlencoded"
      }
    };
 $http(req).then(function(resp){//success}).catch(function(error){//error});
</code>```

Body:
I am making a test application to test angular and php data transfer.
But angular is  sending data through post method but php is not accepting the data

<!DOCTYPE html>

  <title>Test</title>

 <form ng-submit="insert()">
   <input type="text" ng-model="name" name="name" placeholder="name">
   <input type="age" ng-model="age" name="age" placeholder="age">
   <button type="submit">Submit</button>
 </form>

This is the html code
The php code is

<?php

    $data = json_decode(file_get_contents('php://input'));
    $place=$data->name;
    $image=$data->age;
    echo $place;
    echo $image;
    echo "string";
?>

When i access these name and age its giving the error as

"

Notice:  Trying to get property of non-object in C:\xampp\htdocs\test\test.php on line 5

Notice:  Trying to get property of non-object in C:\xampp\htdocs\test\test.php on line 6

string"

but angular is sending the data
data:Object
age:"2"
name:"abcd"
cant identify where is the problem.

Body:
One way to make proper post request to php is through $httpParamSerializerJQLike,

so you can make a post like this:

var data = {
        'name':$scope.name,
        'age':$scope.age
    };
var req = {
      method : "POST",
      url: "http://yourUrl",
      data: $httpParamSerializerJQLike(data),
      headers: {
        'Content-Type': "application/x-www-form-urlencoded"
      }
    };
 $http(req).then(function(resp){//success}).catch(function(error){//error});


问:
How to insert values in a PHP array to a MySQL table?
I am creating a registration form, with fields for Name, Email and Phone Number. To check the validity of user input, I have a function validate_input() that returns an array $arr containing input entered by the user (if user input is valid). $arr is then passed to a separate function that inserts the values in arr into a MySQL table user containing fields for name, email and phone.

I initially tried the following:

```<code>$insert_query = "INSERT INTO user (name, email, phone)
                 VALUES ('$arr['name']',
                         '$arr['email']',
                         '$arr['phone']')";
$run_insert_query = mysqli_query($con, $insert_query);
</code>```

But this didn't work. Some reading revealed that this is the wrong way to insert array values into the database. So I then tried the following (based on the accepted answer here):

```<code>$escaped_values = array_map('mysql_real_escape_string', array_values($arr));
$arr_values  = implode(",", $escaped_values);

$insert_query = "INSERT INTO user (name, email, phone) VALUES ($arr_values)";
$run_query = mysqli_query($con, $insert_query);
</code>```

But this didn't work either. Any ideas on how to make this work?

答:
In your insert dml statement, strings and formatted dates must be quoted in single quotes. Since mysql will attempt to dynamically cast strings to integers or floats, you could try quoting everything - but even if it you get it working, this will bite you back when you least expect it. Your second block of code is also dependent on the data being presented in the order you expect. Typically this is unlikely to change, but it is bad programming.

You can't mix mysqli_ and mysql_ functions. Read the errors and warnings php is telling you about.

Assuming that your validate_input() function also invokes mysql[i]_real_escape_string() on the data to prevent sql injection (also bad programming practice - you should validate input and escape output) then you just need to fix the semantics of your code in the first query: associative array indices should not be quoted when they are already enclosed in "....":

```<code>$insert_query = "INSERT INTO user
 (name, email, phone)
 VALUES ('$arr[name]', '$arr[email]', '$arr[phone]')";
$run_insert_query = mysqli_query($con, $insert_query);
</code>```

Body:
I am creating a registration form, with fields for Name, Email and Phone Number. To check the validity of user input, I have a function validate_input() that returns an array $arr containing input entered by the user (if user input is valid). $arr is then passed to a separate function that inserts the values in arr into a MySQL table user containing fields for name, email and phone.

I initially tried the following:

$insert_query = "INSERT INTO user (name, email, phone)
                 VALUES ('$arr['name']',
                         '$arr['email']',
                         '$arr['phone']')";
$run_insert_query = mysqli_query($con, $insert_query);

But this didn't work. Some reading revealed that this is the wrong way to insert array values into the database. So I then tried the following (based on the accepted answer here):

$escaped_values = array_map('mysql_real_escape_string', array_values($arr));
$arr_values  = implode(",", $escaped_values);

$insert_query = "INSERT INTO user (name, email, phone) VALUES ($arr_values)";
$run_query = mysqli_query($con, $insert_query);

But this didn't work either. Any ideas on how to make this work?

Body:
In your insert dml statement, strings and formatted dates must be quoted in single quotes. Since mysql will attempt to dynamically cast strings to integers or floats, you could try quoting everything - but even if it you get it working, this will bite you back when you least expect it. Your second block of code is also dependent on the data being presented in the order you expect. Typically this is unlikely to change, but it is bad programming.

You can't mix mysqli_ and mysql_ functions. Read the errors and warnings php is telling you about.

Assuming that your validate_input() function also invokes mysql[i]_real_escape_string() on the data to prevent sql injection (also bad programming practice - you should validate input and escape output) then you just need to fix the semantics of your code in the first query: associative array indices should not be quoted when they are already enclosed in "....":

$insert_query = "INSERT INTO user
 (name, email, phone)
 VALUES ('$arr[name]', '$arr[email]', '$arr[phone]')";
$run_insert_query = mysqli_query($con, $insert_query);


问:
Decimal input wrong java
The answer is incorrect in Decimal form however if the (input) answer is the full number it works. The decimal format works however if the user inputs the answer as a rounded decimal the system will print incorrect. It only works if the answer is not rounded please help :) I am still learning to code so anything is useful.

```<code>public class Generator {

        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            /* Prints 10 random numbers
            Random num = new Random();

            int number;

            for(int counter=1; counter<=1;counter++){
                number = num.nextInt(10);
                System.out.println(number);
            }
            */

            Random num1 = new Random();
            Random num2 = new Random();
            Random num3 = new Random();;

            int number1;
            int number2;
            int number3;

            number1 = num1.nextInt(10) + 2;
            number2 = num2.nextInt(10) * 2;
            number3 = -num3.nextInt(10) * 2;

            System.out.println("Solve the quadratic: "+number1 + "x"+"\u00B2+" + number2 + "x" +  number3);

            double answer = -number2/2/number1+Math.pow(Math.pow(number2,2)-4*number1*number3,0.5)/2/number1;

            double answer2 = -number2/2/number1-Math.pow(Math.pow(number2,2)-4*number1*number3,0.5)/2/number1;

            DecimalFormat df = new DecimalFormat("#.####");
            df.setRoundingMode(RoundingMode.CEILING);
            for (Number n : Arrays.asList(answer, answer2)) {
                Double d = n.doubleValue();
                System.out.println(df.format(d));
            }
            //System.out.println(answer); <---- works if answer is not rounded.
            System.out.println("Enter answer:");
            double x = scan.nextDouble();

            if(x == answer){
            System.out.println("Correct");

        }else{
            System.out.println("Try again");

            System.out.println("Enter answer:");
            double x1 = scan.nextDouble();
            if(x1 == answer){
                System.out.println("Correct");

            }else{
                System.out.println("Try again");
        }

    }
        }
    }
</code>```

答:
You format the answer for printing it out, but this is the rounded value, therefore when you enter the rounded answer it will not equate to the answer value as it is the full, unrounded double value, so x == answer will always fail when rounding occurs.

Adding print statement of answer will show this to you, this is the output when you do so.

Solve the quadratic: 5x²+6x-14

      answer: 1.7776388834631178

      rounded1: 1.7777

      rounded2: -1.7776

      Enter answer:

      1.7777

      Try again

      Enter answer:

      1.7776388834631178

      Correct

You will need some way of comparing the input answer to the rounded answer, something like this would work

```<code>if(x == (double)Math.round(answer * 10000d) / 10000d)
</code>```

Here the number of zeros indicate the number of decimals you want to use.

Title: Decimal input wrong java

Body:
The answer is incorrect in Decimal form however if the (input) answer is the full number it works. The decimal format works however if the user inputs the answer as a rounded decimal the system will print incorrect. It only works if the answer is not rounded please help :) I am still learning to code so anything is useful.

public class Generator {

        public static void main(String[] args) {
            Scanner scan = new Scanner(System.in);
            /* Prints 10 random numbers
            Random num = new Random();

            int number;

            for(int counter=1; counter<=1;counter++){
                number = num.nextInt(10);
                System.out.println(number);
            }
            */

            Random num1 = new Random();
            Random num2 = new Random();
            Random num3 = new Random();;

            int number1;
            int number2;
            int number3;

            number1 = num1.nextInt(10) + 2;
            number2 = num2.nextInt(10) * 2;
            number3 = -num3.nextInt(10) * 2;

            System.out.println("Solve the quadratic: "+number1 + "x"+"\u00B2+" + number2 + "x" +  number3);

            double answer = -number2/2/number1+Math.pow(Math.pow(number2,2)-4*number1*number3,0.5)/2/number1;

            double answer2 = -number2/2/number1-Math.pow(Math.pow(number2,2)-4*number1*number3,0.5)/2/number1;

            DecimalFormat df = new DecimalFormat("#.####");
            df.setRoundingMode(RoundingMode.CEILING);
            for (Number n : Arrays.asList(answer, answer2)) {
                Double d = n.doubleValue();
                System.out.println(df.format(d));
            }
            //System.out.println(answer); <---- works if answer is not rounded.
            System.out.println("Enter answer:");
            double x = scan.nextDouble();

            if(x == answer){
            System.out.println("Correct");

        }else{
            System.out.println("Try again");

            System.out.println("Enter answer:");
            double x1 = scan.nextDouble();
            if(x1 == answer){
                System.out.println("Correct");

            }else{
                System.out.println("Try again");
        }

    }
        }
    }

Body:
You format the answer for printing it out, but this is the rounded value, therefore when you enter the rounded answer it will not equate to the answer value as it is the full, unrounded double value, so x == answer will always fail when rounding occurs.

Adding print statement of answer will show this to you, this is the output when you do so.

Solve the quadratic: 5x²+6x-14

      answer: 1.7776388834631178

      rounded1: 1.7777

      rounded2: -1.7776

      Enter answer:

      1.7777

      Try again

      Enter answer:

      1.7776388834631178

      Correct

You will need some way of comparing the input answer to the rounded answer, something like this would work

if(x == (double)Math.round(answer * 10000d) / 10000d)

Here the number of zeros indicate the number of decimals you want to use.


问:
is it possible to calculate next z-index in javascript
Is it possible to get the highest z-index property in some container if none of the elements in it have z-index set via styles? The only approach i've found googling returns "auto" for the z-index.</p>

答: There's a JQuery Module that can do this.</p>


问:
how can i cut one line on two on a cat /ect/passwd?
I'm trying to write a command that shows all odd lines of
/etc/passwd:

I've tried:

```<code>sh-3.2$ cat /etc/passwd | grep -vn \# | sed '0~2d'
</code>```

but it didn't work

```<code>sed: 1: "0~2d": invalid command code ~
</code>```

Is there a different  way to obtain the result?

答:
The step syntax is a GNU extension.
sed 'n;d' should be the portable version of your sed invocation.

Body:
I'm trying to write a command that shows all odd lines of
/etc/passwd:

I've tried:

sh-3.2$ cat /etc/passwd | grep -vn \# | sed '0~2d'

but it didn't work

sed: 1: "0~2d": invalid command code ~

Is there a different  way to obtain the result?


问:
Send data to a decent user with Kemal over websocket
How can i send data data to a decent user connected via websockets? I know,
Websocket connections yields the context, but how can i filter a decent socket connection for sending data to only 1 (or some) connected user(s) depending on context (env)?

```<code>SOCKETS = [] of HTTP::WebSocket
ws "/chat" do |socket,env|
  room = env.params.query["room"]
  SOCKETS << socket
  socket.on_message do |message|
    SOCKETS.each { |socket| socket.send message}
  end
  socket.on_close do
    SOCKETS.delete socket
  end
end
</code>```

Must socket contain the room or needs SOCKETS to be a Hash?

答:
You can store sockets as hash and give id to your clients and then you can send saved socket of your recent client.

I mean that

```<code>SOCKETS = {} of String => HTTP::WebSocket

socket.on_message do |message|
  j = JSON.parse(message)
  case j["type"]
  when "login"
    user_id = j["id"].to_s
    SOCKETS[user_id] = socket
  when "whisper"
    to = j["to"].to_s
    from = j["from"]
    user = SOCKETS[to].send("#{from} is whispering you!")
end
</code>```

something like that.

Body:
How can i send data data to a decent user connected via websockets? I know,
Websocket connections yields the context, but how can i filter a decent socket connection for sending data to only 1 (or some) connected user(s) depending on context (env)?

SOCKETS = [] of HTTP::WebSocket
ws "/chat" do |socket,env|
  room = env.params.query["room"]
  SOCKETS << socket
  socket.on_message do |message|
    SOCKETS.each { |socket| socket.send message}
  end
  socket.on_close do
    SOCKETS.delete socket
  end
end

Must socket contain the room or needs SOCKETS to be a Hash?

Body:
You can store sockets as hash and give id to your clients and then you can send saved socket of your recent client.

I mean that

SOCKETS = {} of String => HTTP::WebSocket

socket.on_message do |message|
  j = JSON.parse(message)
  case j["type"]
  when "login"
    user_id = j["id"].to_s
    SOCKETS[user_id] = socket
  when "whisper"
    to = j["to"].to_s
    from = j["from"]
    user = SOCKETS[to].send("#{from} is whispering you!")
end

something like that.


问:
Python - Num1 1 not defined
```<code>def to_numbers():
  num1 = str(raw_input('Enter a string number?\n'))

for value in num1:
  try:
    print '%s as an int is %d' % (str(value), int(value))
  except ValueError, ex:
    print '"%s" cannot be converted to an int: %s' % (value, ex)
</code>```

Was wondering if I can code this correctly. Received num1 not defined error.

答:
Python is very sensitive when it comes to indentation, so make sure you indent your code correctly to get expected results. You are getting num1 as not defined error as num1 scope is in method to_numbers() and for loop is not in to_numbers() scope, hence error.

Deleting line between num1 assignment and for loop and indenting for loop to be in sync (spaces) just as num1 will make num1 accessible in to_numbers().

As I am using Python 3.x, I have to update few syntax like adding brackets to print statements and using as keyword for naming exception instance but your logic remains same.

```<code>import platform

## Your method
def to_numbers():
  num1 = str(input('Enter a string number?\n'))
  for value in num1:
    try:
      print ('%s as an int is %d' % (str(value), int(value)))
    except ValueError as ex :
      print ('"%s" cannot be converted to an int: %s' % (value, ex))

## Print Python version for your reference
print("Python version : " + platform.python_version())
## Calling your method
to_numbers()
</code>```

Sample Run

```<code>Python version : 3.6.1
Enter a string number?
1234567890abcdefgh
1 as an int is 1
2 as an int is 2
3 as an int is 3
4 as an int is 4
5 as an int is 5
6 as an int is 6
7 as an int is 7
8 as an int is 8
9 as an int is 9
0 as an int is 0
"a" cannot be converted to an int: invalid literal for int() with base 10: 'a'
"b" cannot be converted to an int: invalid literal for int() with base 10: 'b'
"c" cannot be converted to an int: invalid literal for int() with base 10: 'c'
"d" cannot be converted to an int: invalid literal for int() with base 10: 'd'
"e" cannot be converted to an int: invalid literal for int() with base 10: 'e'
"f" cannot be converted to an int: invalid literal for int() with base 10: 'f'
"g" cannot be converted to an int: invalid literal for int() with base 10: 'g'
"h" cannot be converted to an int: invalid literal for int() with base 10: 'h'
</code>```

Title: Python - Num1 1 not defined

Body:
def to_numbers():
  num1 = str(raw_input('Enter a string number?\n'))

for value in num1:
  try:
    print '%s as an int is %d' % (str(value), int(value))
  except ValueError, ex:
    print '"%s" cannot be converted to an int: %s' % (value, ex)

Was wondering if I can code this correctly. Received num1 not defined error.

Body:
Python is very sensitive when it comes to indentation, so make sure you indent your code correctly to get expected results. You are getting num1 as not defined error as num1 scope is in method to_numbers() and for loop is not in to_numbers() scope, hence error.

Deleting line between num1 assignment and for loop and indenting for loop to be in sync (spaces) just as num1 will make num1 accessible in to_numbers().

As I am using Python 3.x, I have to update few syntax like adding brackets to print statements and using as keyword for naming exception instance but your logic remains same.

import platform

## Your method
def to_numbers():
  num1 = str(input('Enter a string number?\n'))
  for value in num1:
    try:
      print ('%s as an int is %d' % (str(value), int(value)))
    except ValueError as ex :
      print ('"%s" cannot be converted to an int: %s' % (value, ex))

## Print Python version for your reference
print("Python version : " + platform.python_version())
## Calling your method
to_numbers()

Sample Run

Python version : 3.6.1
Enter a string number?
1234567890abcdefgh
1 as an int is 1
2 as an int is 2
3 as an int is 3
4 as an int is 4
5 as an int is 5
6 as an int is 6
7 as an int is 7
8 as an int is 8
9 as an int is 9
0 as an int is 0
"a" cannot be converted to an int: invalid literal for int() with base 10: 'a'
"b" cannot be converted to an int: invalid literal for int() with base 10: 'b'
"c" cannot be converted to an int: invalid literal for int() with base 10: 'c'
"d" cannot be converted to an int: invalid literal for int() with base 10: 'd'
"e" cannot be converted to an int: invalid literal for int() with base 10: 'e'
"f" cannot be converted to an int: invalid literal for int() with base 10: 'f'
"g" cannot be converted to an int: invalid literal for int() with base 10: 'g'
"h" cannot be converted to an int: invalid literal for int() with base 10: 'h'


答:
You just forgot to set the quotes right.
Here's the correct syntax: </p>

```<code>$insert_query = "INSERT INTO user (name, email, phone)
                 VALUES ('".$arr['name']."',
                         '".$arr['email']."',
                         '".$arr['phone']."')";
</code>```

Title: How to insert values in a PHP array to a MySQL table?

Body:
You just forgot to set the quotes right.
Here's the correct syntax:

$insert_query = "INSERT INTO user (name, email, phone)
                 VALUES ('".$arr['name']."',
                         '".$arr['email']."',
                         '".$arr['phone']."')";


问:
Do localhost routes work in live environments?
I have a project on localhost at the following route:

http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php/signup

and I currently post data to the application from javascript like this:

```<code>// Centralised, referenced from each javascript file:
var baseUrl = 'http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php';

// The signup post URL is generated like this:
var postUrl: baseUrl + "/signup",
</code>```

This works for all files on localhost.

Questions:

When this project goes live, do these URLs still work?

Is there a cleaner way to write the baseUrl so that it doesn't need to change when the project goes live?

Apologies if this is an obvious one but I currently only work on localhost. Any suggestions welcome.
Symfony 3 application, XAMPP server, OSX.

EDIT:

Using $.ajax to make posts to server.

答:
When the project goes live the localhost URL absolutely will not work.

What you should do is have a build process that uses the localhost URL in development and inserts the production URL when the site is live.

Using Webpack, for example, you'd do something like this in development:

```<code>module.exports = {
  URL: '"http://127.0.0.1"'
}
</code>```

And this in production:

```<code>module.exports = merge(devEnv, {
  URL: '"http://example.com"'
})
</code>```

Then you'd then import that variable and probably assign it to something more concise and descriptive like so:

```<code>const baseUrl = process.env.URL
</code>```

Having done this you can now use the variable wherever to make requests by concatenating it, for example, with a subdirectory like so:

```<code>`${baseUrl}/projects/PROJECT_NAME/web/app_dev.php`
</code>```

Body:
I have a project on localhost at the following route:

http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php/signup

and I currently post data to the application from javascript like this:

// Centralised, referenced from each javascript file:
var baseUrl = 'http://127.0.0.1/projects/PROJECT_NAME/web/app_dev.php';

// The signup post URL is generated like this:
var postUrl: baseUrl + "/signup",

This works for all files on localhost.

Questions:

When this project goes live, do these URLs still work?

Is there a cleaner way to write the baseUrl so that it doesn't need to change when the project goes live?

Apologies if this is an obvious one but I currently only work on localhost. Any suggestions welcome.
Symfony 3 application, XAMPP server, OSX.

EDIT:

Using $.ajax to make posts to server.

Body:
When the project goes live the localhost URL absolutely will not work.

What you should do is have a build process that uses the localhost URL in development and inserts the production URL when the site is live.

Using Webpack, for example, you'd do something like this in development:

module.exports = {
  URL: '"http://127.0.0.1"'
}

And this in production:

module.exports = merge(devEnv, {
  URL: '"http://example.com"'
})

Then you'd then import that variable and probably assign it to something more concise and descriptive like so:

const baseUrl = process.env.URL

Having done this you can now use the variable wherever to make requests by concatenating it, for example, with a subdirectory like so:

`${baseUrl}/projects/PROJECT_NAME/web/app_dev.php`


问:
in a select statement - how to include a filter after a function b4 the from clause
I want to select the top sales person by 'location & Product' combination.
1st I Sort & Rank, then I sum for "Location & Product", then I want to drop all but the top sales person by "Location & Product" such that the query result contains only The Top Salesperson by "Location & Product" with the total sales for each "Location & Product" combination.

The one part I don't have is the "select Rank = 1" - adding a "where" clause after "From" does not work:

```<code>Select Location, Product, Sales, Salesperson
       row_number() OVER (PARTITION BY concat(Location,Product) ORDER BY Sales desc) AS Rank,
       Sum(Sales) OVER(PARTITION BY concat(Location,Product)) AS Salesbylocprod
From Table A
</code>```

答:
You can also use Common Table Expressions:</p>

```<code>;WITH CTE
     AS (SELECT *,
                ROW_NUMBER() OVER(PARTITION BY Location,Product ORDER BY Sales DESC) AS RowNum,
                SUM(Sales) OVER(PARTITION BY Location,Product) AS SalesByLocProd
         FROM TableA
        )
        SELECT Location,
             Product,
             Sales,
             SalesPerson,
             SalesByLocProd
        FROM CTE
        WHERE RowNum = 1;
</code>```

Body:
I want to select the top sales person by 'location & Product' combination.
1st I Sort & Rank, then I sum for "Location & Product", then I want to drop all but the top sales person by "Location & Product" such that the query result contains only The Top Salesperson by "Location & Product" with the total sales for each "Location & Product" combination.

The one part I don't have is the "select Rank = 1" - adding a "where" clause after "From" does not work:

Select Location, Product, Sales, Salesperson
       row_number() OVER (PARTITION BY concat(Location,Product) ORDER BY Sales desc) AS Rank,
       Sum(Sales) OVER(PARTITION BY concat(Location,Product)) AS Salesbylocprod
From Table A

Body:
You can also use Common Table Expressions:

;WITH CTE
     AS (SELECT *,
                ROW_NUMBER() OVER(PARTITION BY Location,Product ORDER BY Sales DESC) AS RowNum,
                SUM(Sales) OVER(PARTITION BY Location,Product) AS SalesByLocProd
         FROM TableA
        )
        SELECT Location,
             Product,
             Sales,
             SalesPerson,
             SalesByLocProd
        FROM CTE
        WHERE RowNum = 1;


问:
Dependency Injection in PHP 5.3
I am trying to tidy up an application, and have manually been doing Constructor Dependency Injection for a while.

This is a bit tedious, and I would like to start utilizing a Dependency Injection Container instead.

I am looking for an actively developed and maintained DI container. I have found Crafty as an alternative, which can wire together dependencies with XML, YAML, Arrays or programatically.

The DI container should not be tightly coupled with a full blown framework, we are looking for something simple and pluggable, with the least hassle possible.

Does anyone have a recommendation and why you chose the particular implementation? Thanks for reading.

答:
Since people seem to like my comment, I post it as an answer. I do not have experience of it, but i know of Symfony Dependency Injection library. It should be decoupled from the rest of the framework and it seems to be pretty flexible. Check it out at Symfony Components.

I also think Substrate looks pretty good. According to the author, it also has production experience, which is always good.

Title: Dependency Injection in PHP 5.3


问:
Mongoose how to find docs within two different dates?
This is my weather model:

```<code>// Declare schema
var weatherSchema = Schema({
    data: {
        type: Object
    },
    date: {
        type: String,
        required: true
    },
    created_at: {
        type: Date,
        default: Date.now,
        index: 1
    }
});
</code>```

in date field, I store dates such as 2017-7-1, 2017-7-2, 2017-7-3, etc

Now I have many docs in this weather table, from 2017-6-20 to 2017-7-3 for instance.

So I want to retrieve the docs from 2017-7-1 to 2017-7-2 only:

```<code>Weather
.find({})
.where('date').gt('2017-7-1').lt('2017-7-2')
.exec(function (err, docs) {
    console.log(docs);
    if (err) {
        res.set('Content-Type', 'application/json');
        return res.sendStatus(-1);
    }

    if (!docs) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Not weather data found.');
    }
    // return docs as json.
    return res.status(200).json(docs);
});
</code>```

But what I get is []. What have I done wrong?

Any ideas?

EDIT:

The official format above does not work, but it works with this format:

```<code>var options =  {
    "date": {
        "$gte": start,
        "$lt": end
    }
}

Weather
.find(options, function (err, docs) {
    console.log(docs);
    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (!docs) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Not weather data found.');
    }
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE');

    // return docs as json.
    return res.status(200).json(docs);
}).select("-created_at -_id -__v");
</code>```

Why?

答:
To compare a dates the date field should be a Date type. and then you can search like:

```<code>.where('date').gt(new Date('2017-7-1')).lt(new Date('2017-7-2'))
</code>```

Or If you want use date as a string, you can search like this:

```<code>.where('date').in(['2017-7-1', '2017-7-2'])
</code>```

This query will find entries with exact date string ('2017-7-1' or '2017-7-2')

Body:
This is my weather model:

// Declare schema
var weatherSchema = Schema({
    data: {
        type: Object
    },
    date: {
        type: String,
        required: true
    },
    created_at: {
        type: Date,
        default: Date.now,
        index: 1
    }
});

in date field, I store dates such as 2017-7-1, 2017-7-2, 2017-7-3, etc

Now I have many docs in this weather table, from 2017-6-20 to 2017-7-3 for instance.

So I want to retrieve the docs from 2017-7-1 to 2017-7-2 only:

Weather
.find({})
.where('date').gt('2017-7-1').lt('2017-7-2')
.exec(function (err, docs) {
    console.log(docs);
    if (err) {
        res.set('Content-Type', 'application/json');
        return res.sendStatus(-1);
    }

    if (!docs) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Not weather data found.');
    }
    // return docs as json.
    return res.status(200).json(docs);
});

But what I get is []. What have I done wrong?

Any ideas?

EDIT:

The official format above does not work, but it works with this format:

var options =  {
    "date": {
        "$gte": start,
        "$lt": end
    }
}

Weather
.find(options, function (err, docs) {
    console.log(docs);
    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (!docs) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Not weather data found.');
    }
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,DELETE');

    // return docs as json.
    return res.status(200).json(docs);
}).select("-created_at -_id -__v");

Why?

Body:
To compare a dates the date field should be a Date type. and then you can search like:

.where('date').gt(new Date('2017-7-1')).lt(new Date('2017-7-2'))

Or If you want use date as a string, you can search like this:

.where('date').in(['2017-7-1', '2017-7-2'])

This query will find entries with exact date string ('2017-7-1' or '2017-7-2')


问:
try to add two columns in pandas data frame, always get error
please see code and return

new to Python and really appreciate your help!

```<code>df['Height'] = df['Wall Top'] - df['Elevation']
</code>```

答:
If you read the error, seems like a data type issue

```<code>df['Height'] = df['Wall Top'].astype(float) - df['Elevation'].astype(float)
</code>```

or you can following existing post

Body:
please see code and return

new to Python and really appreciate your help!

df['Height'] = df['Wall Top'] - df['Elevation']

Body:
If you read the error, seems like a data type issue

df['Height'] = df['Wall Top'].astype(float) - df['Elevation'].astype(float)

or you can following existing post