问:
Is there any easier way to get the key name value in the following json using newtonsoft
Let's say we have JSON as below:

```<code>{
  "Group1": ["Value1", "Value5"],
  "Group2": ["Value4", "Value11", "Value12", "Value9"],
  "Group3": ["Value2"]
}
</code>```

Given the value in the list say "Value1", I need to get the corresponding key name "Group1".

Is there any easier way to do this ?

What I tried:

```<code>var json = "{\r\n  \"Group1\": [\"Value1\", \"Value5\"],\r\n  \"Group2\": [\"Value4\", \"Value11\", \"Value12\", \"Value9\"],\r\n  \"Group3\": [\"Value2\"]\r\n}";

var jObject = JObject.Parse(json);

var group1 = jObject["Group1"].ToObject<List<string>>();
var group2 = jObject["Group2"].ToObject<List<string>>();
var group3 = jObject["Group3"].ToObject<List<string>>();

var value = group1.Contains("Value1") ? "Group1" : "Invalid";
</code>```

答:
Similar to Daniel Tran's fine answer, if you wanted to keep using JObject you could do this:

```<code>var jObject = JObject.Parse(json);

var key = jObject.Properties()
                 .Where(p => p.Value.Children().Contains("Value1"))
                 .Select(p => p.Name)
                 .FirstOrDefault();
</code>```

Fiddle: https://dotnetfiddle.net/14mgtV

Body:
Let's say we have JSON as below:

{
  "Group1": ["Value1", "Value5"],
  "Group2": ["Value4", "Value11", "Value12", "Value9"],
  "Group3": ["Value2"]
}

Given the value in the list say "Value1", I need to get the corresponding key name "Group1".

Is there any easier way to do this ?

What I tried:

var json = "{\r\n  \"Group1\": [\"Value1\", \"Value5\"],\r\n  \"Group2\": [\"Value4\", \"Value11\", \"Value12\", \"Value9\"],\r\n  \"Group3\": [\"Value2\"]\r\n}";

var jObject = JObject.Parse(json);

var group1 = jObject["Group1"].ToObject<List<string>>();
var group2 = jObject["Group2"].ToObject<List<string>>();
var group3 = jObject["Group3"].ToObject<List<string>>();

var value = group1.Contains("Value1") ? "Group1" : "Invalid";

Body:
Similar to Daniel Tran's fine answer, if you wanted to keep using JObject you could do this:

var jObject = JObject.Parse(json);

var key = jObject.Properties()
                 .Where(p => p.Value.Children().Contains("Value1"))
                 .Select(p => p.Name)
                 .FirstOrDefault();

Fiddle: https://dotnetfiddle.net/14mgtV


来源: stackexchange

问:
react-native-fb sdk com.android.support dependency error
```<code> > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified
</code>```

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip

答:
The key is in the error message shown in your case:

Searched in the following locations:
  file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/

I have had the same. Then I went to the location:

file:<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/

And found that there is no directory named 27.0.1 because in my case the latest buildTool was not downloaded. In my case I have had 27.0.0-alpha1.

So in both of my app build.gradle and in

node_modules/react-native-fbsdk/android/build.gradle

I replaced 27.0.1 with 27.0.0-alpha1 and build was successful.

ContentLicense: CC BY-SA 3.0

Body:
 > A problem occurred configuring project ':react-native-fbsdk'.
  > Could not resolve all dependencies for configuration ':react-native-fbsdk:_debugPublishCopy'.
     > Could not find com.android.support:appcompat-v7:27.0.1.
       Searched in the following locations:
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.pom
           file:/<location_to_sdk>/sdk/extras/android/m2repository/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
           file:/<location_to_app>/android/sdk-manager/com/android/support/appcompat-v7/27.0.1/appcompat-v7-27.0.1.jar
       Required by:
           newPtMobile:react-native-fbsdk:unspecified

This issue started happening this morning when running react-native run-android without making any changes to the code or adding new packages, it was working fine untill now!

"react-native":"0.50.3", "react-native-fbsdk":"0.6.3"

I can see that I am missing android support libraries in my sdk/extras/android/m2repository/com/android/support subfolders, all the subfolders have the 26.0.0-alpha1 folder as the last one.
I already tried removing support repository and installing again through android studio and downloading the latest android_m2repository manually but the folders are still missing.

What I am having trouble understanding is why google's maven repository (https://dl.google.com/dl/android/maven2/index.html) states that under for example m2repository/com/android/support/appcompat-v7 I should have a folder named 27.0.2 (along with some previous versions which are also missing) but even in the latest android_m2repository which they offer it is also missing!

https://dl.google.com/android/repository/android_m2repository_r48.zip


问:
Animated matplotlib imshow
Let me first clarify that I'm not trying to generate random walk lines like in this and many other questions. I'm trying to make a random walk heat map that changes color as points are revisted, like this.

I've been able to create still-lifes like this: but I want to see the process.

I can get the figure to show up, and if I print the array at each step I can see that the walk is working. But the figure itself doesn't animate. My code:

```<code>import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation as anim
import numpy as np
import sys
import random

length = int(sys.argv[1])

fig = plt.figure()
ax = plt.axes(xlim=(0, length-1), ylim=(0, length-1))
arr = np.zeros((length, length), dtype = int)

cmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
                                                    ['black','green','white'],
                                                    256)
bounds=[0,0,10,10]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

im=plt.imshow(arr, interpolation='nearest',
              cmap = cmap,
              origin='lower')

x = int(np.random.random_sample() * length)
y = int(np.random.random_sample() * length)

def walk():
    global x, y
        rand = np.random.random_sample()
        if rand < 0.25 :
            if x == length - 1:
                x = 0
            else: x = x + 1
        elif rand < 0.5 :
            if x == 0:
                x = length - 1
            else: x = x - 1
        elif rand < 0.75 :
            if y == length - 1:
                y = 0
            else: y = y + 1
        else:
            if y == 0:
                y = length - 1
            else: y = y - 1
    return

def stand(arr):
    global x,y
    arr[x][y] = arr[x][y] + 1
    return arr

def animate(i):
    arr=im.get_array()
    walk()
    #print(a)
    arr = stand(arr)
    im.set_array(arr)
    return [im]

anim = anim.FuncAnimation(fig, animate, frames=200, interval=20, blit=True)
plt.show()
</code>```

Running Python 3.6, as you can see by the print.

There are so many videos with these animated grids and I can't find any answers! Somebody must know how to do it. Thanks!

答:
I added animated=True and vmin=0, vmax=255, in the imshow() function below. I also changed the stand() line to arr[x][y] = arr[x][y] + 10.

```<code>#!/usr/bin/env python3
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation as anim
import numpy as np
import sys
import random

length = int(sys.argv[1])

fig = plt.figure()
ax = plt.axes(xlim=(0, length-1), ylim=(0, length-1))
arr = np.zeros((length, length), dtype = int)

cmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
                                                    ['black','green','white'],
                                                    256)
bounds=[0,0,10,10]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

im=plt.imshow(arr, interpolation='nearest',
        cmap = cmap, vmin=0, vmax=255,
              origin='lower', animated=True) # small changes here

x = int(np.random.random_sample() * length)
y = int(np.random.random_sample() * length)

def walk():
    global x, y
    rand = np.random.random_sample()
    if rand < 0.25 :
        if x == length - 1:
            x = 0
        else: x = x + 1
    elif rand < 0.5 :
        if x == 0:
            x = length - 1
        else: x = x - 1
    elif rand < 0.75 :
        if y == length - 1:
            y = 0
        else: y = y + 1
    else:
        if y == 0:
            y = length - 1
        else: y = y - 1
    return

def stand(arr):
    global x,y
    arr[x][y] = arr[x][y] + 1000
    return arr

def animate(i):
    global x,y
    arr=im.get_array()
    walk()
    #print(a)
    arr = stand(arr)
    im.set_array(arr)
    return [im]

anim = anim.FuncAnimation(fig, animate, frames=200, interval=20, blit=True)
plt.show()
</code>```

And I ran it with length = 50 and I get an animation. See it here. So you may have to play around with your color choices a bit.

Title: Animated matplotlib imshow

Body:
Let me first clarify that I'm not trying to generate random walk lines like in this and many other questions. I'm trying to make a random walk heat map that changes color as points are revisted, like this.

I've been able to create still-lifes like this: but I want to see the process.

I can get the figure to show up, and if I print the array at each step I can see that the walk is working. But the figure itself doesn't animate. My code:

import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation as anim
import numpy as np
import sys
import random

length = int(sys.argv[1])

fig = plt.figure()
ax = plt.axes(xlim=(0, length-1), ylim=(0, length-1))
arr = np.zeros((length, length), dtype = int)

cmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
                                                    ['black','green','white'],
                                                    256)
bounds=[0,0,10,10]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

im=plt.imshow(arr, interpolation='nearest',
              cmap = cmap,
              origin='lower')

x = int(np.random.random_sample() * length)
y = int(np.random.random_sample() * length)

def walk():
    global x, y
        rand = np.random.random_sample()
        if rand < 0.25 :
            if x == length - 1:
                x = 0
            else: x = x + 1
        elif rand < 0.5 :
            if x == 0:
                x = length - 1
            else: x = x - 1
        elif rand < 0.75 :
            if y == length - 1:
                y = 0
            else: y = y + 1
        else:
            if y == 0:
                y = length - 1
            else: y = y - 1
    return

def stand(arr):
    global x,y
    arr[x][y] = arr[x][y] + 1
    return arr

def animate(i):
    arr=im.get_array()
    walk()
    #print(a)
    arr = stand(arr)
    im.set_array(arr)
    return [im]

anim = anim.FuncAnimation(fig, animate, frames=200, interval=20, blit=True)
plt.show()

Running Python 3.6, as you can see by the print.

There are so many videos with these animated grids and I can't find any answers! Somebody must know how to do it. Thanks!

Body:
I added animated=True and vmin=0, vmax=255, in the imshow() function below. I also changed the stand() line to arr[x][y] = arr[x][y] + 10.

#!/usr/bin/env python3
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation as anim
import numpy as np
import sys
import random

length = int(sys.argv[1])

fig = plt.figure()
ax = plt.axes(xlim=(0, length-1), ylim=(0, length-1))
arr = np.zeros((length, length), dtype = int)

cmap = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
                                                    ['black','green','white'],
                                                    256)
bounds=[0,0,10,10]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

im=plt.imshow(arr, interpolation='nearest',
        cmap = cmap, vmin=0, vmax=255,
              origin='lower', animated=True) # small changes here

x = int(np.random.random_sample() * length)
y = int(np.random.random_sample() * length)

def walk():
    global x, y
    rand = np.random.random_sample()
    if rand < 0.25 :
        if x == length - 1:
            x = 0
        else: x = x + 1
    elif rand < 0.5 :
        if x == 0:
            x = length - 1
        else: x = x - 1
    elif rand < 0.75 :
        if y == length - 1:
            y = 0
        else: y = y + 1
    else:
        if y == 0:
            y = length - 1
        else: y = y - 1
    return

def stand(arr):
    global x,y
    arr[x][y] = arr[x][y] + 1000
    return arr

def animate(i):
    global x,y
    arr=im.get_array()
    walk()
    #print(a)
    arr = stand(arr)
    im.set_array(arr)
    return [im]

anim = anim.FuncAnimation(fig, animate, frames=200, interval=20, blit=True)
plt.show()

And I ran it with length = 50 and I get an animation. See it here. So you may have to play around with your color choices a bit.


问:
JQuery to get input field value based on label

I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

```<code><label>Code</label>
<input type="text" value="1234"  id="custcode_1" />

<label>Copy Code</label>
<input type="text" value=""  id="custcode_2" />
</code>```

For normal scenario it will be just

```<code>$('#custcode_2').val($('#custcode_1').val());
</code>```

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

答:
You can use this code,</p>

```<code>//Find the input textbox with label Code
var $copy = $('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'Code';
}).next('input');

//Find the input textbox with label Copy Code
var $copycode = $('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'Copy Code';
}).next('input');

//Copy the value
$copycode.val($copy.val());

//Copy the value as character typed into the textbox
$('input').on('keyup',function(){
$copycode.val($copy.val());
});
</code>```

Body:
I need to copy the value of the first input box to the second input box.  The id and name of these input boxes are coming from tables.  What is fix will be the labels like 'Code' and 'Copy Code'

Code
<input type="text" value="1234"  id="custcode_1" />

Copy Code
<input type="text" value=""  id="custcode_2" />

For normal scenario it will be just

$('#custcode_2').val($('#custcode_1').val());

But the id or name are generated on the fly so this is not possible.  How to achieve this using labels of the input boxes.

Thanks for the help.

Body:
You can use this code,

//Find the input textbox with label Code
var $copy = $('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'Code';
}).next('input');

//Find the input textbox with label Copy Code
var $copycode = $('label').filter(function () {
    return this.firstChild.nodeValue.trim() === 'Copy Code';
}).next('input');

//Copy the value
$copycode.val($copy.val());

//Copy the value as character typed into the textbox
$('input').on('keyup',function(){
$copycode.val($copy.val());
});


问:
Javascript second prompt is not showing as expected
I'm trying to code a rock paper scissors game where when I hit the new game button in the middle of the screen it prompts the user for two name inputs. I've seen this in action before but I can't figure out where I'm going wrong. Hopefully this is enough code to figure it out, otherwise I can post more! Thanks in advance.</p>

```<code>$('#gameController').bind('click', function() {
    if (game.running === false) {
       if ($(this).text() == 'New Game') {
           for (i = 1; i < 3; i++) {
               do {
                  var player = prompt('Player ' + i + ', enter your name...');
            } while (!player);
            $('#player' + i + 'Name').text(player);
            game.addPlayer(player);
        }
    };
</code>```

答:
I tried executing only the for loop with do...while in jsfiddle. It works fine.

Which means your error has something to do with $('#player' + i + 'Name').text(player); or game.addPlayer(player);

Based on the comments, I suspect an infinite recursion at game.addPlayer(player);. Glad that you found your solution.

Body:
I'm trying to code a rock paper scissors game where when I hit the new game button in the middle of the screen it prompts the user for two name inputs. I've seen this in action before but I can't figure out where I'm going wrong. Hopefully this is enough code to figure it out, otherwise I can post more! Thanks in advance.

$('#gameController').bind('click', function() {
    if (game.running === false) {
       if ($(this).text() == 'New Game') {
           for (i = 1; i < 3; i++) {
               do {
                  var player = prompt('Player ' + i + ', enter your name...');
            } while (!player);
            $('#player' + i + 'Name').text(player);
            game.addPlayer(player);
        }
    };


问:
Start a Task without waiting
I am using asp.net mvc and I want to cache some data about user from database when he reaches the home page of the site.
So when user requests the Home page, I want to call an async method, which makes database calls and caches data.

Any examples of doing this would be great.

答:
I would say you call the caching method via this:

```<code>HostingEnvironment.QueueBackgroundWorkItem(x=> CacheData());
</code>```

In that way, you don't really keep the home page request waiting so the users get to see the home page immediately, while the caching happens in the background at the server.

PS: But yes you run a slight risk of app domain recycling screwing up your caching thread.

Title: Start a Task without waiting

Body:
I would say you call the caching method via this:

HostingEnvironment.QueueBackgroundWorkItem(x=> CacheData());

In that way, you don't really keep the home page request waiting so the users get to see the home page immediately, while the caching happens in the background at the server.

PS: But yes you run a slight risk of app domain recycling screwing up your caching thread.


问:
WP7 UserControl with conditional Converter?
I'm developing a UserControl to manipulate numeric data, but I'd like to be able to specify the numeric format string (or even the Converter itself) per instance of the UC.

I tried adding a property to my UC and binding that to the Converter, but ran into errors.

It seems that binding to the converter is not possible in the version of SL that runs on WP7. I read that custom controls in SL support more customization.

But, do I really need to go that deep just to support this requirement?

答:
If by binding to the converter, you mean binding to the converter parameter, you can't do this in SL4, or even WPF!

I think you are going to have to do a bit more work in code behind, possibly using a view model. You can localise the view model to just this user control (see the following article), so do not need to use MVVM throughout your entire application.

ContentLicense: CC BY-SA 2.5


问:
Pythonic way of sum of dot product of two list of lists
How can this be done elegantly (Pythonic way)

You have two matrices A and B represented each by a list of lists.

You would like to calculate the overall sum over the matrix of element-wise product of A and B.

sample code:

```<code>sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
    for j in range(ncols):
        sum += A[i][j]*B[i][j]

# interested finally in the value of sum
# return sum
</code>```

for example if

A=[[1,2,3],[3,4,5]]

and

B=[[3,2,2],[1,1,1]]

the result is :

1*3 + 2*2 + 3*2 + 3*1 + 4*1 + 5*1 = 25

答:
Here is a flat version of @MadPhysicist's generator expr.</p>

```<code>sum(a*b for ab in zip(A, B) for a, b in zip(*ab))
# 25
</code>```

Body:
How can this be done elegantly (Pythonic way)

You have two matrices A and B represented each by a list of lists.

You would like to calculate the overall sum over the matrix of element-wise product of A and B.

sample code:

sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
    for j in range(ncols):
        sum += A[i][j]*B[i][j]

# interested finally in the value of sum
# return sum

for example if

A=[[1,2,3],[3,4,5]]

and

B=[[3,2,2],[1,1,1]]

the result is :

1*3 + 2*2 + 3*2 + 3*1 + 4*1 + 5*1 = 25

Body:
Here is a flat version of @MadPhysicist's generator expr.

sum(a*b for ab in zip(A, B) for a, b in zip(*ab))
# 25


问:
Rails get record newest in many has_many
I have some model like this:

```<code>class LogActivity < ActiveRecord::Base
   has_many :call_logs
   has_many :send_email_logs
   has_many :send_sms_logs
   ...
end

class CallLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendEmailLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendSmsLog < ActiveRecord::Base
   belongs_to :log_activity
end
</code>```

Now, i want get one newest record in :call_logs, :send_email_logs, :send_sms_logs. How can i do that???

答:
You can try doing this -

```<code>newest_call_log       = LogActivity.call_logs.last
newest_sent_email_log = LogActivity.send_email_logs.last
newest_sent_sms_log   = LogActivity.send_sms_logs.last
</code>```

A single query alternative would be to do this -

```<code>newest_log = LogActivity.eager_load(:call_logs, :send_email_logs, :send_sms_logs).last
# The above will fire a query and fetch all the data you need, the below lines will segregate your data
newest_call_log       = newest_log.call_logs.last
newest_sent_email_log = newest_log.send_email_logs.last
newest_sent_sms_log   = newest_log.send_sms_logs.last
</code>```

Body:
I have some model like this:

class LogActivity < ActiveRecord::Base
   has_many :call_logs
   has_many :send_email_logs
   has_many :send_sms_logs
   ...
end

class CallLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendEmailLog < ActiveRecord::Base
   belongs_to :log_activity
end

class SendSmsLog < ActiveRecord::Base
   belongs_to :log_activity
end

Now, i want get one newest record in :call_logs, :send_email_logs, :send_sms_logs. How can i do that???

Body:
You can try doing this -

newest_call_log       = LogActivity.call_logs.last
newest_sent_email_log = LogActivity.send_email_logs.last
newest_sent_sms_log   = LogActivity.send_sms_logs.last

A single query alternative would be to do this -

newest_log = LogActivity.eager_load(:call_logs, :send_email_logs, :send_sms_logs).last
# The above will fire a query and fetch all the data you need, the below lines will segregate your data
newest_call_log       = newest_log.call_logs.last
newest_sent_email_log = newest_log.send_email_logs.last
newest_sent_sms_log   = newest_log.send_sms_logs.last


问:
how to see if value entered is a number and not chars?

I want to know if someone entered a number and if they did the program continues but if they didn't the program terminates.
</p>

```<code>int main(void) {
    int i;

    printf("Enter a number: ");
    scanf("%d",&i);
    /*If input is not a number than terminate*/

    /*Otherwise continue*/
    else {
        if (test_prime(i))
            printf("Prime.\n");
        else
            printf("Not prime.\n");
    }
    return 0;
}
</code>```

<p>
If the user enters "hello" than I want program to terminate.
</p>

答:
To expand on what yano described, you will need to set your scanf function to a integer variable, which will count the number of successful scans. Here, you are looking for one successful scan: if integer c is not 1, then return a message saying "invalid number", etc.</p>

```<code>int main(void) {
 int i;
 int c;
 printf("Enter a number: ");
 c = scanf("%d",&i);
 if(c != 1) {
     printf("Invalid number");
 }
 else {
     printf("%d",i);
     return 0;
 }
}
</code>```

Body:
I want to know if someone entered a number and if they did the program continues but if they didn't the program terminates.

int main(void) {
    int i;

    printf("Enter a number: ");
    scanf("%d",&i);
    /*If input is not a number than terminate*/

    /*Otherwise continue*/
    else {
        if (test_prime(i))
            printf("Prime.\n");
        else
            printf("Not prime.\n");
    }
    return 0;
}

If the user enters "hello" than I want program to terminate.

Body:
To expand on what yano described, you will need to set your scanf function to a integer variable, which will count the number of successful scans. Here, you are looking for one successful scan: if integer c is not 1, then return a message saying "invalid number", etc.

int main(void) {
 int i;
 int c;
 printf("Enter a number: ");
 c = scanf("%d",&i);
 if(c != 1) {
     printf("Invalid number");
 }
 else {
     printf("%d",i);
     return 0;
 }
}


问:
Checking user input against an array, act as a guess Javascript
I am a new aspiring dev and I am trying to figure out how to build a game of hangman using vanilla js only. I have put together a key event listner, and have got it to console log the inputs. I have also got it to print the letters pushed into a "letters guessed" array.

```<code>document.addEventListener("keypress", letterPressed);

function letterPressed(event) {
    var letter = String.fromCharCode(event.keyCode);
    guessedLetters.push(letter);
    document.getElementById("lettersGuessed").innerHTML = guessedLetters;
    console.log(guessedLetters)
}
</code>```

I also have an array of choices of words

```<code>var wordList = ["Ravens", "Cardinals", "Falcons", "Bills",
"Panthers", "Bears", "Bengals", "Browns", "Cowboys",
"Broncos", "Lions", "Packers", "Texans", "Colts",
"Jaguars", "Cheifs", "Chargers", "Rams",
"Dolphins", "Vikings", "Patriots", "Saints",
"Giants", "Jets", "Raiders", "Eagles", "Steelers",
"Forty Niners", "Seahawks", "Buccaneers", "Titans",
"Redskins"];
</code>```

and a for loop picking the random word from this array, converting it to "_" strings in the length of the word, and printing it to the html document in a div id of "spaces".

```<code>   var wordBlanks = [];
var guessedLetters = [];
var randomWord = wordList[Math.floor(Math.random() * wordList.length)];

for (var i = 0; i < randomWord.length; i++) {
    wordBlanks[i] = "_";
    console.log(wordBlanks,randomWord);
    document.getElementById("spaces").innerHTML = wordBlanks.join(" ");
};
</code>```

Where would I even want to go from here? I want to check input from the keystrokes (or the letters guessed array, im not sure which would be best) against the word thats chosen and have the "_" strings reveal the correct guesses when guessed correctly.

My question is more regarding pointing me in the right direction. So, I can properly teach myself. Any words of advice?

Thank you!

答:
You'll have to come to terms with the upper/lowercase issue first, but after that, something like this will work:

const randomWord = "BEARS";
const guessedLetters = ["S", "O", "E"];
const wordBlanks = randomWord.split('')
        .map(letter => guessedLetters.indexOf(letter) >= 0 ? letter : "_")
        .join(' ');

console.log(wordBlanks);```

Body:
I am a new aspiring dev and I am trying to figure out how to build a game of hangman using vanilla js only. I have put together a key event listner, and have got it to console log the inputs. I have also got it to print the letters pushed into a "letters guessed" array.

document.addEventListener("keypress", letterPressed);

function letterPressed(event) {
    var letter = String.fromCharCode(event.keyCode);
    guessedLetters.push(letter);
    document.getElementById("lettersGuessed").innerHTML = guessedLetters;
    console.log(guessedLetters)
}

I also have an array of choices of words

var wordList = ["Ravens", "Cardinals", "Falcons", "Bills",
"Panthers", "Bears", "Bengals", "Browns", "Cowboys",
"Broncos", "Lions", "Packers", "Texans", "Colts",
"Jaguars", "Cheifs", "Chargers", "Rams",
"Dolphins", "Vikings", "Patriots", "Saints",
"Giants", "Jets", "Raiders", "Eagles", "Steelers",
"Forty Niners", "Seahawks", "Buccaneers", "Titans",
"Redskins"];

and a for loop picking the random word from this array, converting it to "_" strings in the length of the word, and printing it to the html document in a div id of "spaces".

   var wordBlanks = [];
var guessedLetters = [];
var randomWord = wordList[Math.floor(Math.random() * wordList.length)];

for (var i = 0; i < randomWord.length; i++) {
    wordBlanks[i] = "_";
    console.log(wordBlanks,randomWord);
    document.getElementById("spaces").innerHTML = wordBlanks.join(" ");
};

Where would I even want to go from here? I want to check input from the keystrokes (or the letters guessed array, im not sure which would be best) against the word thats chosen and have the "_" strings reveal the correct guesses when guessed correctly.

My question is more regarding pointing me in the right direction. So, I can properly teach myself. Any words of advice?

Thank you!


问:
How do I write a single function in laravel that will be usable for different controllers or schedule commands and access different facades of models
I have this public function below but I will have to write a similar code in about 60 other places, I don't want to repeat myself rather, I want to be able to write a single function such that all I need change is 'Dailysaving::', and '00:00:00' each time I use the function. And please note that I will be creating several other schedule commands which this function should work for. How do I go about this please and where am I supposed to place the function I write And how do I access different models from the function. Thanks in advance for anyone that will help me out.
public function handle()
    {</p>

```<code>    $users= Dailysaving::where('debit_time', '00:00:00')->where('status', 'Active')->get();
    //die($users);
    foreach ($users as $user) {
        $email = $user->email;
        $amount = $user->amount_daily * 100;
        //Let's know where the payment is on the db
        $user_id = $user->user_id;
        $savings_id = $user->id;
        $auth_code= $user->authorization_code;
        //

        $metastring = '{"custom_fields":[{"user_id":'. $user_id. '}, {"action": "activatedaily"},{"savings_id": '.$savings_id.'},{"savingstype": "dailysavings"}]}';
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.paystack.co/transaction/charge_authorization",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                'amount'=>$amount,
                'email'=>$email,
                'authorization_code' =>$auth_code,
                'metadata' => $metastring,
            ]),
            CURLOPT_HTTPHEADER => [
                "authorization:Bearer sk_test_656456h454545",
                "content-type: application/json",
                "cache-control: no-cache"
            ],
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        if($err){

            $failedtranx = new Failedtransaction;

            $failedtranx->error = $err;
            $failedtranx->save();
        }
        if($response) {

            $tranx = json_decode($response);

            if (!$tranx->status) {

                // there was an error contacting the Paystack API
                //register in failed transaction table
                $failedtranx = new Failedtransaction;

                $failedtranx->error = $err;
                $failedtranx->save();
            }

            if ('success' == $tranx->data->status) {

                $auth_code = $tranx->data->authorization->authorization_code;
                $amount = ($tranx->data->amount) / 100;
                $last_transaction = $tranx->data->transaction_date;

                $payment_ref = $tranx->data->reference;

                $record = new Transactionrecord;

                $record->payment_ref = $payment_ref;
                $record->save();
                //saving complete
                //die('saved');

                $item = Dailysaving::find($savings_id);
                $total_deposit = $item->total_deposit + $amount;
                $item->total_deposit = $total_deposit;
                $item->last_transaction_date = date('Y-m-d H:i:s');
                $target = $item->day_target;
                if ($target == $total_deposit) {
                    $item->status = 'Completed';
                }

                $item->save();

            }

            echo 'done';
        }
        else{
            echo 'failed';
        }
    }

}
</code>```

答:
As I understand you are trying to make custom helper functions.

So you need create helpers.php with your functions and follow instructions in the below answer: https://stackoverflow.com/a/28290359/5407558

Body:
I have this public function below but I will have to write a similar code in about 60 other places, I don't want to repeat myself rather, I want to be able to write a single function such that all I need change is 'Dailysaving::', and '00:00:00' each time I use the function. And please note that I will be creating several other schedule commands which this function should work for. How do I go about this please and where am I supposed to place the function I write And how do I access different models from the function. Thanks in advance for anyone that will help me out.
public function handle()
    {

    $users= Dailysaving::where('debit_time', '00:00:00')->where('status', 'Active')->get();
    //die($users);
    foreach ($users as $user) {
        $email = $user->email;
        $amount = $user->amount_daily * 100;
        //Let's know where the payment is on the db
        $user_id = $user->user_id;
        $savings_id = $user->id;
        $auth_code= $user->authorization_code;
        //

        $metastring = '{"custom_fields":[{"user_id":'. $user_id. '}, {"action": "activatedaily"},{"savings_id": '.$savings_id.'},{"savingstype": "dailysavings"}]}';
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.paystack.co/transaction/charge_authorization",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode([
                'amount'=>$amount,
                'email'=>$email,
                'authorization_code' =>$auth_code,
                'metadata' => $metastring,
            ]),
            CURLOPT_HTTPHEADER => [
                "authorization:Bearer sk_test_656456h454545",
                "content-type: application/json",
                "cache-control: no-cache"
            ],
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        if($err){

            $failedtranx = new Failedtransaction;

            $failedtranx->error = $err;
            $failedtranx->save();
        }
        if($response) {

            $tranx = json_decode($response);

            if (!$tranx->status) {

                // there was an error contacting the Paystack API
                //register in failed transaction table
                $failedtranx = new Failedtransaction;

                $failedtranx->error = $err;
                $failedtranx->save();
            }

            if ('success' == $tranx->data->status) {

                $auth_code = $tranx->data->authorization->authorization_code;
                $amount = ($tranx->data->amount) / 100;
                $last_transaction = $tranx->data->transaction_date;

                $payment_ref = $tranx->data->reference;

                $record = new Transactionrecord;

                $record->payment_ref = $payment_ref;
                $record->save();
                //saving complete
                //die('saved');

                $item = Dailysaving::find($savings_id);
                $total_deposit = $item->total_deposit + $amount;
                $item->total_deposit = $total_deposit;
                $item->last_transaction_date = date('Y-m-d H:i:s');
                $target = $item->day_target;
                if ($target == $total_deposit) {
                    $item->status = 'Completed';
                }

                $item->save();

            }

            echo 'done';
        }
        else{
            echo 'failed';
        }
    }

}


问:
configuring PHP and CodeIgniter to use an Oracle database
Hi All

i'm trying to configure PHP and CodeIgniter to use an Oracle database instead of using mysql 5.3.3.

It will be great if anybody can give me step by step solution to do this
note that i installed oracle database 10g express edition,but when i try to import .sql i get an error that tell me that this file is not supported

Thank You

答:
You cannot import a MySQL database definition into an oracle database. While both speak SQL the table definitions are pretty different (especially regarding auto_increment/serial fields and varchar fields).

You might be able to create the empty tables in your oracle database if Codeigniter supports orable at all and then import your data (only the data) into that database.


问:
Build list of data validation attributes for a given element
When using any of the Input Extension Helper Methods, like @Html.TextboxFor, any Validation Attributes from your model are automatically generated by the Razor engine (via ClientValidationEnabled/UnobtrusiveJavaScriptEnabled).

For example, take the following case which works fine

Model:

[Required]
public string QuestionOne { get; set; }
```

<p><strong>View</strong>:</p>

<pre class="lang-cs prettyprint-override"><code>@Html.TextBoxFor(model => model.QuestionOne)
@Html.ValidationMessageFor(model => model.QuestionOne)
</code>```

Generated Markup:

<input type="text" id="QuestionOne" name="QuestionOne" value=""
       data-val="true" data-val-required="The QuestionOne field is required." >

```

<p>In this case the attributes <code>data-val="true"</code> & <code>data-val-required="The QuestionOne field is required."</code> are picked up by Unobtrusive validation and the form element is successfully validated.</p>

<hr>

<p><strong>However</strong>, for extensibility reasons, I want to be able to generate the <code><input></code> element myself instead of using <code>TextBoxFor</code>.  So my view would now look like this:</p>

<pre class="lang-html prettyprint-override"><code><input type="textbox"
       id="@Html.IdFor(m => m.QuestionTwo)"
       name="@Html.NameFor(m => m.QuestionTwo)"
       value="@Model.QuestionTwo"
       data-val="true" data-val-required="Selection is Required" />

@Html.ValidationMessageFor(model => model.QuestionTwo)
</code>```

In this case, I'm faking the validation attribute output by just re-writing data-val="true" (etc) by hand, but this would have to be expanded to cover every single case.

Here's a running Demo in .NET Fiddle

Q: Can I build /return a list of data-val-* attributes for a given element?

答:
You can use the GetUnobtrusiveValidationAttributes() method of HtmlHelper to get the validation attributes associated with a specific property.

For example in the view

```<code>@{ var attributes = Html.GetUnobtrusiveValidationAttributes("QuestionTwo"); }

<input
    type="textbox"
    @foreach(var attr in attributes)
    {
        @:@attr.Key="@attr.Value"
    }
    id="@Html.IdFor(m => m.QuestionTwo)"
    ....
/>
</code>```

Note the @:@attr.Key="@attr.Value" line will give a warning (Missing attribute name) but will run correctly

Alternatively, you could use javaScript/jQuery to add the attributes

```<code><script type="text/javascript">
    var attributes = @Html.Raw(Json.Encode(attributes));
    var input = $('#QuestionTwo');
    for(var i in attributes) {
        input.attr(i, attributes[i]);
    }
</script>
</code>```

I have forked the DotNetFiddle here to show the working code for both options.

While the above code shows how it can be done, you should not be doing that. The HtmlHelper methods execute a lot of code your ignoring to ensure correct 2-way model binding, for example, the value attribute is determined by first checking for a value in ModelState, then in the ViewDataDictionary, and only if the previous values do not exist, does it use the value of the property (the second part of TextBoxFor displaying initial value, not the value updated from code explains the behavior).

Except for the incorrect value attribute, the code you have shown for the <input> is the same as will be generated by simply using @Html.TextBoxFor(m => m.Question2). I assume your real case is different, but if you cannot make use of TextBoxFor() and using an overload that accepts htmlAttributes to generate the html you need, then the correct approach is to create your own HtmlHelper method (and making use of existing methods in the HtmlHelper class and System.Web.Mvc.Html namespace)

Body:
When using any of the Input Extension Helper Methods, like @Html.TextboxFor, any Validation Attributes from your model are automatically generated by the Razor engine (via ClientValidationEnabled/UnobtrusiveJavaScriptEnabled).

For example, take the following case which works fine

Model:

[Required]
public string QuestionOne { get; set; }

View:

@Html.TextBoxFor(model => model.QuestionOne)
@Html.ValidationMessageFor(model => model.QuestionOne)

Generated Markup:

<input type="text" id="QuestionOne" name="QuestionOne" value=""
       data-val="true" data-val-required="The QuestionOne field is required." >

In this case the attributes data-val="true" & data-val-required="The QuestionOne field is required." are picked up by Unobtrusive validation and the form element is successfully validated.

However, for extensibility reasons, I want to be able to generate the <input> element myself instead of using TextBoxFor.  So my view would now look like this:

<input type="textbox"
       id="@Html.IdFor(m => m.QuestionTwo)"
       name="@Html.NameFor(m => m.QuestionTwo)"
       value="@Model.QuestionTwo"
       data-val="true" data-val-required="Selection is Required" />

@Html.ValidationMessageFor(model => model.QuestionTwo)

In this case, I'm faking the validation attribute output by just re-writing data-val="true" (etc) by hand, but this would have to be expanded to cover every single case.

Here's a running Demo in .NET Fiddle

Q: Can I build /return a list of data-val-* attributes for a given element?

Body:
You can use the GetUnobtrusiveValidationAttributes() method of HtmlHelper to get the validation attributes associated with a specific property.

For example in the view

@{ var attributes = Html.GetUnobtrusiveValidationAttributes("QuestionTwo"); }

<input
    type="textbox"
    @foreach(var attr in attributes)
    {
        @:@attr.Key="@attr.Value"
    }
    id="@Html.IdFor(m => m.QuestionTwo)"
    ....
/>

Note the @:@attr.Key="@attr.Value" line will give a warning (Missing attribute name) but will run correctly

Alternatively, you could use javaScript/jQuery to add the attributes

<script type="text/javascript">
    var attributes = @Html.Raw(Json.Encode(attributes));
    var input = $('#QuestionTwo');
    for(var i in attributes) {
        input.attr(i, attributes[i]);
    }
</script>

I have forked the DotNetFiddle here to show the working code for both options.

While the above code shows how it can be done, you should not be doing that. The HtmlHelper methods execute a lot of code your ignoring to ensure correct 2-way model binding, for example, the value attribute is determined by first checking for a value in ModelState, then in the ViewDataDictionary, and only if the previous values do not exist, does it use the value of the property (the second part of TextBoxFor displaying initial value, not the value updated from code explains the behavior).

Except for the incorrect value attribute, the code you have shown for the <input> is the same as will be generated by simply using @Html.TextBoxFor(m => m.Question2). I assume your real case is different, but if you cannot make use of TextBoxFor() and using an overload that accepts htmlAttributes to generate the html you need, then the correct approach is to create your own HtmlHelper method (and making use of existing methods in the HtmlHelper class and System.Web.Mvc.Html namespace)


问:
Evaluate only the latest window for event time based sliding windows
I would like to process events in EvenTime using sliding windows. The sliding interval is 24 hours and increment is 30 minutes. The problem is that below code is producing 48 calculations for each event. In our case events are coming in order so we need only the latest window to be evaluated.

Thanks,

Dejan

```<code>public static void processEventsa(
        DataStream<Tuple2<String, MyEvent>> events) throws Exception {

    events.assignTimestampsAndWatermarks(new MyWatermark()).
            keyBy(0).
            timeWindow(Time.hours(windowSizeHour), Time.seconds(windowSlideSeconds)).
            apply(new WindowFunction<Tuple2<String, MyEvent>, Tuple2<String, MyEvent>, Tuple, TimeWindow>() {
                @Override
                public void apply(Tuple key, TimeWindow window, Iterable<Tuple2<String, MyEvent>> input,
                                          Collector<Tuple2<String, MyEvent>> out) throws Exception {

                    for (Tuple2<String, MyEvent> record : input) {

                    }
                }
            });
}

public class MyWatermark implements
        AssignerWithPunctuatedWatermarks<Tuple2<String, MyEvent>> {

    @Override
    public long extractTimestamp(Tuple2<String, MyEvent> event, long previousElementTimestamp) {
        return event.f1.eventTime;
    }

    @Override
    public Watermark checkAndGetNextWatermark(Tuple2<String, MyEvent> event, long previousElementTimestamp) {
        return new Watermark(event.f1.eventTime);
    }
}

final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
</code>```

答:
The problem was in watermark. AssignerWithPeriodicWatermarks should be used</p>

```<code>public class MyWatermark implements
        AssignerWithPeriodicWatermarks<Tuple2<String, MyEvent>> {

    private final long maxTimeLag = 5000;

    @Override
    public long extractTimestamp(Tuple2<String, MyEvent> event, long previousElementTimestamp) {
        try {
            return event.f1.eventTime;
        }
        catch(NullPointerException ex) {}

        return System.currentTimeMillis() - maxTimeLag;
    }

    @Override
    public Watermark getCurrentWatermark() {
        return new Watermark(System.currentTimeMillis() - maxTimeLag);
    }
}
</code>```

Body:
I would like to process events in EvenTime using sliding windows. The sliding interval is 24 hours and increment is 30 minutes. The problem is that below code is producing 48 calculations for each event. In our case events are coming in order so we need only the latest window to be evaluated.

Thanks,

Dejan

public static void processEventsa(
        DataStream<Tuple2<String, MyEvent>> events) throws Exception {

    events.assignTimestampsAndWatermarks(new MyWatermark()).
            keyBy(0).
            timeWindow(Time.hours(windowSizeHour), Time.seconds(windowSlideSeconds)).
            apply(new WindowFunction<Tuple2<String, MyEvent>, Tuple2<String, MyEvent>, Tuple, TimeWindow>() {
                @Override
                public void apply(Tuple key, TimeWindow window, Iterable<Tuple2<String, MyEvent>> input,
                                          Collector<Tuple2<String, MyEvent>> out) throws Exception {

                    for (Tuple2<String, MyEvent> record : input) {

                    }
                }
            });
}

public class MyWatermark implements
        AssignerWithPunctuatedWatermarks<Tuple2<String, MyEvent>> {

    @Override
    public long extractTimestamp(Tuple2<String, MyEvent> event, long previousElementTimestamp) {
        return event.f1.eventTime;
    }

    @Override
    public Watermark checkAndGetNextWatermark(Tuple2<String, MyEvent> event, long previousElementTimestamp) {
        return new Watermark(event.f1.eventTime);
    }
}

final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

Body:
The problem was in watermark. AssignerWithPeriodicWatermarks should be used

public class MyWatermark implements
        AssignerWithPeriodicWatermarks<Tuple2<String, MyEvent>> {

    private final long maxTimeLag = 5000;

    @Override
    public long extractTimestamp(Tuple2<String, MyEvent> event, long previousElementTimestamp) {
        try {
            return event.f1.eventTime;
        }
        catch(NullPointerException ex) {}

        return System.currentTimeMillis() - maxTimeLag;
    }

    @Override
    public Watermark getCurrentWatermark() {
        return new Watermark(System.currentTimeMillis() - maxTimeLag);
    }
}


问:
Django create queryset or list of unique items in multiple manytomany instances
I have a QuestionSet that is a manytomany of questions. Each QuestionSet has multiple questions associated with it.

I want to get a list of all unique questions that are in two (or more) QuestionSets

For example:

```<code>First QuestionSet = Questions(1,2,3)
Second QuestionSet = Questions(1,3,4)

Output:
List/Queryset/Something of Questions(1,2,3,4)
</code>```

models.py

```<code>class QuestionSet(models.Model):
    name = models.CharField(max_length=255)
    questions = models.ManyToManyField(Question)

class Question(models.Model):
    question_num = models.IntegerField(default=0,blank=False)
</code>```

答:
Maybe try this:

```<code>questions = Question.objects.annotate(question_set_count=Count('questionset')).filter(question_set_count__gte=2)
</code>```

You can find that more in the docs: Django aggregates

Body:
I have a QuestionSet that is a manytomany of questions. Each QuestionSet has multiple questions associated with it.

I want to get a list of all unique questions that are in two (or more) QuestionSets

For example:

First QuestionSet = Questions(1,2,3)
Second QuestionSet = Questions(1,3,4)

Output:
List/Queryset/Something of Questions(1,2,3,4)

models.py

class QuestionSet(models.Model):
    name = models.CharField(max_length=255)
    questions = models.ManyToManyField(Question)

class Question(models.Model):
    question_num = models.IntegerField(default=0,blank=False)

Body:
Maybe try this:

questions = Question.objects.annotate(question_set_count=Count('questionset')).filter(question_set_count__gte=2)

You can find that more in the docs: Django aggregates


问:
Failed to link resource after updating gradle and Android studio version
Before I updated to android studio 3 and gradle 3.0.1 I could build my project without a problem, but ever since I updated I keep getting this errors:

```<code>Error:failed linking references.
    Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:Execution failed for task ':app:processDebugResources'.
            > Failed to execute aapt
</code>```

I tried to disable AAPT2 but then I get an error ProcessException for aapt

```<code>Error:java.util.concurrent.ExecutionException:
com.android.ide.common.process.ProcessException: Error while executing
process /build-tools/26.0.2/aapt with arguments {package -f --no-crunch
-I /android-25/android.jar -M
</code>```

I tried to change compile to implementation and api but they all gave the same erros. Can someone please help me solve this...

Here is my gradle file:

```<code>buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }

    buildscript {
        repositories {

            repositories {
                maven { url 'https://maven.fabric.io/public' }
            }
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

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

    dependencies {
        api fileTree(include: ['*.jar'], dir: 'libs')
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        api files('libs/signalr-client-sdk.jar')
        api files('libs/signalr-client-sdk-android.jar')
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        api 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
        api 'net.danlew:android.joda:2.9.9'
        api 'com.hbb20:ccp:2.0.3'
        api 'com.squareup.picasso:picasso:2.5.2'
        api 'com.xw.repo:bubbleseekbar:3.6'
        api 'com.github.pavlospt:circleview:1.3'
        api 'com.facebook.android:facebook-android-sdk:[4,5)'
        api 'com.amitshekhar.android:android-networking:1.0.0'
        api 'de.hdodenhof:circleimageview:2.2.0'
        api 'com.android.support.constraint:constraint-layout:1.0.2'
        api 'com.github.stfalcon:chatkit:0.2.2'
        api 'com.google.android.gms:play-services-gcm:11.0.4'
        api 'com.snatik:storage:2.1.0'
        api 'com.github.tamir7.contacts:contacts:1.1.7'
        api 'com.google.android.gms:play-services-maps:11.0.4'
        testCompile 'junit:junit:4.12'
    }
    apply plugin: 'com.google.gms.google-services'
</code>```

答:
Try this

Go to your gradle.properties

write the below code and Sync your project

```<code>android.enableAapt2=false
</code>```

Body:
Before I updated to android studio 3 and gradle 3.0.1 I could build my project without a problem, but ever since I updated I keep getting this errors:

Error:failed linking references.
    Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
    Error:Execution failed for task ':app:processDebugResources'.
            > Failed to execute aapt

I tried to disable AAPT2 but then I get an error ProcessException for aapt

Error:java.util.concurrent.ExecutionException:
com.android.ide.common.process.ProcessException: Error while executing
process /build-tools/26.0.2/aapt with arguments {package -f --no-crunch
-I /android-25/android.jar -M

I tried to change compile to implementation and api but they all gave the same erros. Can someone please help me solve this...

Here is my gradle file:

buildscript {
        repositories {
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }

    buildscript {
        repositories {

            repositories {
                maven { url 'https://maven.fabric.io/public' }
            }
            maven { url 'https://maven.fabric.io/public' }
        }

        dependencies {
            classpath 'io.fabric.tools:gradle:1.+'
        }
    }
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }
    apply plugin: 'com.android.application'
    apply plugin: 'io.fabric'

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

    dependencies {
        api fileTree(include: ['*.jar'], dir: 'libs')
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        api files('libs/signalr-client-sdk.jar')
        api files('libs/signalr-client-sdk-android.jar')
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        compile('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
            transitive = true;
        }
        api 'org.zakariya.stickyheaders:stickyheaders:0.7.6'
        api 'net.danlew:android.joda:2.9.9'
        api 'com.hbb20:ccp:2.0.3'
        api 'com.squareup.picasso:picasso:2.5.2'
        api 'com.xw.repo:bubbleseekbar:3.6'
        api 'com.github.pavlospt:circleview:1.3'
        api 'com.facebook.android:facebook-android-sdk:[4,5)'
        api 'com.amitshekhar.android:android-networking:1.0.0'
        api 'de.hdodenhof:circleimageview:2.2.0'
        api 'com.android.support.constraint:constraint-layout:1.0.2'
        api 'com.github.stfalcon:chatkit:0.2.2'
        api 'com.google.android.gms:play-services-gcm:11.0.4'
        api 'com.snatik:storage:2.1.0'
        api 'com.github.tamir7.contacts:contacts:1.1.7'
        api 'com.google.android.gms:play-services-maps:11.0.4'
        testCompile 'junit:junit:4.12'
    }
    apply plugin: 'com.google.gms.google-services'

Body:
Try this

Go to your gradle.properties

write the below code and Sync your project

android.enableAapt2=false


答:
Instead of putting into the guessedLetters array, try to see if the presses letter can be found in the randomWord.

If so, find the position of the letter and let it replace the appropriate _ space in the wordBlank array.

Something like:

```<code>function letterPressed(event) {
    var letter = String.fromCharCode(event.keyCode);

    if (randomWord.indexOf(letter) >= 0)
       wordBlank[(randomWord.indexOf(letter)] = letter;

    console.log(wordBlank);
}
</code>```

Note that a letter may have multiple occurences in a word.

Title: Checking user input against an array, act as a guess Javascript

Body:
Instead of putting into the guessedLetters array, try to see if the presses letter can be found in the randomWord.

If so, find the position of the letter and let it replace the appropriate _ space in the wordBlank array.

Something like:

function letterPressed(event) {
    var letter = String.fromCharCode(event.keyCode);

    if (randomWord.indexOf(letter) >= 0)
       wordBlank[(randomWord.indexOf(letter)] = letter;

    console.log(wordBlank);
}

Note that a letter may have multiple occurences in a word.


问:
Create EXCEL and open it
I'm creating an excel file, and I must open it immediately.
Obviously, when I create it on localhost, I can get the file, but when I publish my web application on IIS this not works because I suppose It's creating on server side...

So I create the excel file and try to upload to the server and after that download it, but I can't create it, If I run this on localhost works, but when I publish don't work.

Any advice?

this is my code:

I use this libraries for Excel:

```<code>using Microsoft.Office.Core;
using Excelo = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;
using System.Reflection;
using System.Globalization;
</code>```

Then, I start my excel file:

```<code>private void sacConsulPend_GenRemito()
{   // DB
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();

    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {   //SP for data query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA",
                    Convert.ToInt32(lblSac_ConPenDet_idCons.Text.Replace(" ", "")));

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);

            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    Excelo.Application oXL;
    Excelo._Workbook oWB;
    Excelo._Worksheet oSheet;
    Excelo.Range oRng;

    try
    {

        //Start Excel
        oXL = new Excelo.Application();

        //new blank workbook.
        oWB = (Excelo._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
        oSheet = (Excelo._Worksheet)oWB.ActiveSheet;
        object misValue = System.Reflection.Missing.Value;

        //Text Format
        oSheet.get_Range("A1", "Z1000").Font.Name = "Courier New";
        oSheet.get_Range("A1", "Z1000").Font.Size = 7;
        oSheet.get_Range("A1", "Z1000").Font.Bold = true;
        oSheet.get_Range("A1", "Z1000").NumberFormat = "@";

        oSheet.get_Range("D1", "E1").Cells.Merge();
        oSheet.get_Range("A1", "F1").Font.Bold = true;
        oSheet.get_Range("A1", "F1").Font.Italic = true;
        oSheet.get_Range("A1", "F1").VerticalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").HorizontalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").Font.Size = 9;

        //Logo Lockers
        oSheet.Shapes.AddPicture(Server.MapPath("~/images/LockersLogo.jpg"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, 60, 20);

        /*
        Excel Content
        */

         //Save ExcelFile
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Files/Envios/"), lblSac_ConPenDet_idCons.Text.Replace(" ", "") + ".xlsx");
        oWB.SaveAs(filePath, Excelo.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
        Missing.Value, false, false, Excelo.XlSaveAsAccessMode.xlNoChange,
        Excelo.XlSaveConflictResolution.xlUserResolution, true,
        Missing.Value, Missing.Value, Missing.Value);

    }
    catch (Exception thex)
    {
        String errorMessage;
        errorMessage = "Error en la creacion del archivo Excel: ";
        errorMessage = String.Concat(errorMessage, thex.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, thex.Source);
    }

}
</code>```

答:
You could use the (official) OpenXML SDK that is intended for scenarios like yours. It doesn't allow you to actually calculate and run functions in the server environment but its good for creating and manipulating workbooks. Download
However, the OpenXML SDK is not everyone's favorite since it requires some learning and at times a lot of code to achieve some simple things.

Luckily there are many other libraries that allow creating XLS/X files without Office like the ExcelLibrary or its successor EEPlus, or NPOI (see johnleniel), and many commercial third-party components.

I could imagine that a dedicated reporting component like Crystal Reports (that also exports to XLS/X) could also be of great use for you.

Title: Create EXCEL and open it

Body:
I'm creating an excel file, and I must open it immediately.
Obviously, when I create it on localhost, I can get the file, but when I publish my web application on IIS this not works because I suppose It's creating on server side...

So I create the excel file and try to upload to the server and after that download it, but I can't create it, If I run this on localhost works, but when I publish don't work.

Any advice?

this is my code:

I use this libraries for Excel:

using Microsoft.Office.Core;
using Excelo = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop;
using System.Reflection;
using System.Globalization;

Then, I start my excel file:

private void sacConsulPend_GenRemito()
{   // DB
    string conn = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
    DataSet dsRemito = new DataSet();
    DataTable dtCons = new DataTable();

    using (SqlConnection sqlCon = new SqlConnection(conn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            try
            {   //SP for data query
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "SACBUS_CONSUL_SOLICITUDEXIST";
                cmd.Parameters.AddWithValue("@ID_CONSULTA",
                    Convert.ToInt32(lblSac_ConPenDet_idCons.Text.Replace(" ", "")));

                cmd.Connection = sqlCon;
                sqlCon.Open();

                SqlDataAdapter dapC = new SqlDataAdapter(cmd);
                dapC.Fill(dsRemito);

            }
            catch (Exception sqlex)
            {
                throw sqlex;
            }
        }
    }

    Excelo.Application oXL;
    Excelo._Workbook oWB;
    Excelo._Worksheet oSheet;
    Excelo.Range oRng;

    try
    {

        //Start Excel
        oXL = new Excelo.Application();

        //new blank workbook.
        oWB = (Excelo._Workbook)(oXL.Workbooks.Add(System.Reflection.Missing.Value));
        oSheet = (Excelo._Worksheet)oWB.ActiveSheet;
        object misValue = System.Reflection.Missing.Value;

        //Text Format
        oSheet.get_Range("A1", "Z1000").Font.Name = "Courier New";
        oSheet.get_Range("A1", "Z1000").Font.Size = 7;
        oSheet.get_Range("A1", "Z1000").Font.Bold = true;
        oSheet.get_Range("A1", "Z1000").NumberFormat = "@";

        oSheet.get_Range("D1", "E1").Cells.Merge();
        oSheet.get_Range("A1", "F1").Font.Bold = true;
        oSheet.get_Range("A1", "F1").Font.Italic = true;
        oSheet.get_Range("A1", "F1").VerticalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").HorizontalAlignment = Excelo.XlVAlign.xlVAlignCenter;
        oSheet.get_Range("A1", "F1").Font.Size = 9;

        //Logo Lockers
        oSheet.Shapes.AddPicture(Server.MapPath("~/images/LockersLogo.jpg"), MsoTriState.msoFalse, MsoTriState.msoCTrue, 0, 0, 60, 20);

        /*
        Excel Content
        */

         //Save ExcelFile
        var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Files/Envios/"), lblSac_ConPenDet_idCons.Text.Replace(" ", "") + ".xlsx");
        oWB.SaveAs(filePath, Excelo.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
        Missing.Value, false, false, Excelo.XlSaveAsAccessMode.xlNoChange,
        Excelo.XlSaveConflictResolution.xlUserResolution, true,
        Missing.Value, Missing.Value, Missing.Value);

    }
    catch (Exception thex)
    {
        String errorMessage;
        errorMessage = "Error en la creacion del archivo Excel: ";
        errorMessage = String.Concat(errorMessage, thex.Message);
        errorMessage = String.Concat(errorMessage, " Line: ");
        errorMessage = String.Concat(errorMessage, thex.Source);
    }

}


问:
R sum of random numbers?
I am trying to Write a R function that will generate n(that are passed to a function) random numbers and return the sum of the numbers and show that random set of numbers

I am new to R and assuming an array would be used here,but not sure.
Also, my attempt only allows for 10 numbers, but if i try to do it for any amount other than 10 it gives wrong sum.

I don't know what I am doing wrong, but this is what i have got so far.

```<code>random.sum <- function(n) {
x[1:n] <- ceiling(10*runif(n))
cat("x:", x[1:n], "\n")
return(sum(x))
}
x <- rep(100, 10)
show(random.sum(10))
</code>```

答:
How about something like this:

```<code>random.sum <- function(n) {
  # Store n random integers between 0 and 100 in vector called random_nums
  random_nums <- floor(runif(n, min=0, max=100))

  # Show the random numbers
  print(random_nums)

  # Return the sum of the random numbers
  return(sum(random_nums))
}

print(paste("Sum:", random.sum(5), sep=" "))
</code>```

Example Output

```<code>[1] 57  3 64 18 46
[1] "Sum: 188"
</code>```

Title: R sum of random numbers?

Body:
I am trying to Write a R function that will generate n(that are passed to a function) random numbers and return the sum of the numbers and show that random set of numbers

I am new to R and assuming an array would be used here,but not sure.
Also, my attempt only allows for 10 numbers, but if i try to do it for any amount other than 10 it gives wrong sum.

I don't know what I am doing wrong, but this is what i have got so far.

random.sum <- function(n) {
x[1:n] <- ceiling(10*runif(n))
cat("x:", x[1:n], "\n")
return(sum(x))
}
x <- rep(100, 10)
show(random.sum(10))

Body:
How about something like this:

random.sum <- function(n) {
  # Store n random integers between 0 and 100 in vector called random_nums
  random_nums <- floor(runif(n, min=0, max=100))

  # Show the random numbers
  print(random_nums)

  # Return the sum of the random numbers
  return(sum(random_nums))
}

print(paste("Sum:", random.sum(5), sep=" "))

Example Output

[1] 57  3 64 18 46
[1] "Sum: 188"


问:
UserProfile as a foreign key in xadmin didn's dispaly option selection
```<code>class UserProfile(AbstractUser):
nick_name=models.CharField(max_length=50,verbose_name='昵称')
birthday=models.DateTimeField(verbose_name='生日',null=True,blank=True)
gender=models.CharField(max_length=50,choices=(('male',u'男'),('female',u'女')),default=('male',u'男'))
address=models.CharField(max_length=100,default=u'')
mobile=models.CharField(max_length=11,null=True,blank=True)
image=models.ImageField(upload_to='image/%Y/%m',default=u'image/default.png',max_length=100)

class Meta:
    verbose_name=u'用户信息'
    verbose_name_plural=verbose_name

def __unicode__(self):
    return self.username

class UserCourse(models.Model):
user = models.ForeignKey(UserProfile, verbose_name=u'用户')
course = models.ForeignKey(Course, verbose_name=u'课程')
add_time=models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')

class Meta:
    verbose_name = u'用户课程'
    verbose_name_plural = verbose_name
</code>```

the filter filed is search ,why is it option list?

they are all foreign key, why the first line are search and second line are option?

答:
you can type the username in select box,then it will show U the options;

this is caused by xadmin/plugins/auth.py

```<code>class UserAdmin(object):
change_user_password_template = None
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active')
search_fields = ('username', 'first_name', 'last_name', 'email')
ordering = ('username',)
style_fields = {'user_permissions': 'm2m_transfer'}
model_icon = 'fa fa-user'
relfield_style = 'fk-ajax'  # comments here if u prefer select mode
</code>```

you can change the source code

Body:
class UserProfile(AbstractUser):
nick_name=models.CharField(max_length=50,verbose_name='昵称')
birthday=models.DateTimeField(verbose_name='生日',null=True,blank=True)
gender=models.CharField(max_length=50,choices=(('male',u'男'),('female',u'女')),default=('male',u'男'))
address=models.CharField(max_length=100,default=u'')
mobile=models.CharField(max_length=11,null=True,blank=True)
image=models.ImageField(upload_to='image/%Y/%m',default=u'image/default.png',max_length=100)

class Meta:
    verbose_name=u'用户信息'
    verbose_name_plural=verbose_name

def __unicode__(self):
    return self.username

class UserCourse(models.Model):
user = models.ForeignKey(UserProfile, verbose_name=u'用户')
course = models.ForeignKey(Course, verbose_name=u'课程')
add_time=models.DateTimeField(default=datetime.now, verbose_name=u'添加时间')

class Meta:
    verbose_name = u'用户课程'
    verbose_name_plural = verbose_name

the filter filed is search ,why is it option list?

they are all foreign key, why the first line are search and second line are option?

Body:
you can type the username in select box,then it will show U the options;

this is caused by xadmin/plugins/auth.py

class UserAdmin(object):
change_user_password_template = None
list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active')
search_fields = ('username', 'first_name', 'last_name', 'email')
ordering = ('username',)
style_fields = {'user_permissions': 'm2m_transfer'}
model_icon = 'fa fa-user'
relfield_style = 'fk-ajax'  # comments here if u prefer select mode

you can change the source code


问:
How to implement 3 stacks with one array?
Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.</p>

答:
Space (not time) efficient. You could:

1) Define two stacks beginning at the array endpoints  and growing in opposite directions.

2) Define the third stack as starting in the middle and growing in any direction you want.

3) Redefine the Push op, so that when the operation is going to overwrite other stack, you shift the whole middle stack in the opposite direction before Pushing.

You need to store the stack top for the first two stacks, and the beginning and end of the third stack in some structure.

Edit

Above you may see an example. The shifting is done with an equal space partitioning policy, although other strategies could be chosen depending upon your problem heuristics.

Edit

Following @ruslik's suggestion, the middle stack could be implemented using an alternating sequence for subsequent pushes. The resulting stack structure will be something like:

| Elem 6  | Elem 4 | Elem 2 | Elem 0 | Elem 1 | Elem 3 | Elem 5 |

In this case, you'll need to store the number n of elements on the middle stack and use the function:

```<code>f[n_] := 1/4 ( (-1)^n (-1 + 2 n) + 1) + BS3
</code>```

to know the next array element to use for this stack.

Although probably this will lead to less shifting, the implementation is not homogeneous for the three stacks, and inhomogeneity (you know) leads to special cases, more bugs and difficulties to maintain code.

Body:
Space (not time) efficient. You could:

1) Define two stacks beginning at the array endpoints  and growing in opposite directions.

2) Define the third stack as starting in the middle and growing in any direction you want.

3) Redefine the Push op, so that when the operation is going to overwrite other stack, you shift the whole middle stack in the opposite direction before Pushing.

You need to store the stack top for the first two stacks, and the beginning and end of the third stack in some structure.

Edit

Above you may see an example. The shifting is done with an equal space partitioning policy, although other strategies could be chosen depending upon your problem heuristics.

Edit

Following @ruslik's suggestion, the middle stack could be implemented using an alternating sequence for subsequent pushes. The resulting stack structure will be something like:

| Elem 6  | Elem 4 | Elem 2 | Elem 0 | Elem 1 | Elem 3 | Elem 5 |

In this case, you'll need to store the number n of elements on the middle stack and use the function:

f[n_] := 1/4 ( (-1)^n (-1 + 2 n) + 1) + BS3

to know the next array element to use for this stack.

Although probably this will lead to less shifting, the implementation is not homogeneous for the three stacks, and inhomogeneity (you know) leads to special cases, more bugs and difficulties to maintain code.


问:
Importing a python file that only contains an object
Let's say I want to have a list object like in my list_of_employees.py

```<code>list = [{'name': "John Doe", 'age': 22, 'employed': True}, {'name': "Mary Doe", 'age': 24, 'employed': False}]
</code>```

and that's all that's in that file.

How do I do it so that my list_of_employees file only really contains the list object, and how do I import it as an object to say, a employee_processing.py file?

答:
You import it like this in your module:

```<code>from list_of_employees import my_list
</code>```

in list_of_employees.py, you have my_list in the global scope:

```<code>my_list = [{'name': "John Doe", 'age': 22, 'employed': True}, {'name': "Mary Doe", 'age': 24, 'employed': False}]
import
</code>```

It is better not to shadow the builtin name list with variable names.

Body:
Let's say I want to have a list object like in my list_of_employees.py

list = [{'name': "John Doe", 'age': 22, 'employed': True}, {'name': "Mary Doe", 'age': 24, 'employed': False}]

and that's all that's in that file.

How do I do it so that my list_of_employees file only really contains the list object, and how do I import it as an object to say, a employee_processing.py file?

Body:
You import it like this in your module:

from list_of_employees import my_list

in list_of_employees.py, you have my_list in the global scope:

my_list = [{'name': "John Doe", 'age': 22, 'employed': True}, {'name': "Mary Doe", 'age': 24, 'employed': False}]
import

It is better not to shadow the builtin name list with variable names.


问:
Detect charge in android without battery
I have a device connected directly to the pins of the Tablet (for charge it), not the battery.
This makes the Tablet is charging, although in reality the battery is discharged or with little charge.

There is some method to detect that the Tablet is charging, even if the battery is not connected.
Obviously the ACTION_BATTERY_CHANGED does not work because the battery is not charging.

Any idea?

答:
Try this...

Better way to get change value you should use BroadcastReceiver

```<code>IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);

BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float battPct = level/(float)scale;
    }
};
</code>```

Body:
Try this...

Better way to get change value you should use BroadcastReceiver

IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);

BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent){
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float battPct = level/(float)scale;
    }
};


问:
How to Model PowerBI Data to show the exact Date
I have a PowerBI report that contains bar graphs that date and other information and a Bing Map that is linked with the bar graph. Now the bing map contains latitude and longitude and some other information like date, and it has the same date column that is used inside the bar graphs. Now I am using a drill through feature here which drill through the map when I select a bar graph and use any of the data visuals inside the map to drill through, now when I drill through this other page contains different information of the bar graph like date and other things.

The problem is when I use drill through on a certain visual inside a map I dont get the exact date that is shown inside the tool tip of the map and the bargraph, thats why because I have the same longitude and latitude that contains different dates and the drill through feature is just showing me the latest date of that longitude and latitude, how can I make this useful so that I get the exact date which I can see earlier on the tooltip of the map and the bar graph any suggestions will be helpful.

答:
Can you provide a sample of your dataset to better understand your problem. The flow you have mentioned is not clear.

Are you drilling from bar graph to Bing map which is on another page?


问:
Importing specific text from Word
I have a couple hundred Word docs that have some number measurements that I need in my code. Naturally, I don't want to copy and paste the measurements into python each time. What I have tried to do is:

```<code>r = []
with open('NGC1705_rotmod.dat') as fo:
    for rec in fo:
        r.append(rec[0:4])
</code>```

Which returns:

```<code>['# Di', '# Ra', '# kp', '0.22', '0.66', '1.11', '1.55', '2.00', '2.45', '2.89', '3.34', '3.78', '4.22', '4.66', '5.11', '5.56', '6.00']
</code>```

However, the first three elements (#Di, #Ra, #kp) are simply the headers for the data, they aren't part of the data that I need. Is there any way to cut off the first 3 rows?

答:
You can track the line no there and then pass if the line no is 0 because header are only in line 0 so something like :</p>

```<code>r = []
with open('NGC1705_rotmod.dat') as fo:

    for line_no,rec in enumerate(fo):
        if line_no==0:
            pass
        else:
            r.append(rec[0:4])
</code>```

Title: Importing specific text from Word

Body:
I have a couple hundred Word docs that have some number measurements that I need in my code. Naturally, I don't want to copy and paste the measurements into python each time. What I have tried to do is:

r = []
with open('NGC1705_rotmod.dat') as fo:
    for rec in fo:
        r.append(rec[0:4])

Which returns:

['# Di', '# Ra', '# kp', '0.22', '0.66', '1.11', '1.55', '2.00', '2.45', '2.89', '3.34', '3.78', '4.22', '4.66', '5.11', '5.56', '6.00']

However, the first three elements (#Di, #Ra, #kp) are simply the headers for the data, they aren't part of the data that I need. Is there any way to cut off the first 3 rows?

Body:
You can track the line no there and then pass if the line no is 0 because header are only in line 0 so something like :

r = []
with open('NGC1705_rotmod.dat') as fo:

    for line_no,rec in enumerate(fo):
        if line_no==0:
            pass
        else:
            r.append(rec[0:4])


问:
map rect component array as group of two elements
I have an array of text inputs like

```<code>var A = [<TextInput ... />, <TextInput ... />, ....]
</code>```

and I want to map these elements group by two elements inside a row.
ie, every two <TextInput /> wrapped inside a <Row> how can I implement this.
I want output like this

```<code><Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
....
....
</code>```

I tried this code inside the loop but it produce an error.

```<code>{index % 2 === 0 && <Row> }
      <TextInput {...props} />
{index % 2 === 1 ? </Row>}
</code>```

I think we cannot return Closing tag of </Row> only inside jsx

答:
```<code>const A = [<TextInput ... />, <TextInput ... />, ....];
A.map((_, idx) => {
  if (idx % 2 === 0) {                // only do this on 0 and even indexs
    let inputs = [A[idx]];            // we'll always have an item at idx
    const y = A[idx+1];               // but idx+1 may not exist (i.e., idx was the last item)
    if (y) {                          // if idx+1 doesn't exist, it'll be undefined, so let's avoid including it
      inputs.push(y);
    }
    return (
      <Row>                           // return the items (or item) wrapped in a row
        {...inputs}
      </Row>
    );
  }
}).filter(x => x !== undefined);      // map function has to return something, so the odd indexes will return undefined; lets filter them out now
</code>```

A simple fiddle illustrating the functionality via console logging.

Body:
I have an array of text inputs like

var A = [<TextInput ... />, <TextInput ... />, ....]

and I want to map these elements group by two elements inside a row.
ie, every two <TextInput /> wrapped inside a <Row> how can I implement this.
I want output like this

<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
<Row>
   <TextInput ... />
   <TextInput ... />
</Row>
....
....

I tried this code inside the loop but it produce an error.

{index % 2 === 0 && <Row> }
      <TextInput {...props} />
{index % 2 === 1 ? </Row>}

I think we cannot return Closing tag of </Row> only inside jsx

Body:
const A = [<TextInput ... />, <TextInput ... />, ....];
A.map((_, idx) => {
  if (idx % 2 === 0) {                // only do this on 0 and even indexs
    let inputs = [A[idx]];            // we'll always have an item at idx
    const y = A[idx+1];               // but idx+1 may not exist (i.e., idx was the last item)
    if (y) {                          // if idx+1 doesn't exist, it'll be undefined, so let's avoid including it
      inputs.push(y);
    }
    return (
      <Row>                           // return the items (or item) wrapped in a row
        {...inputs}
      </Row>
    );
  }
}).filter(x => x !== undefined);      // map function has to return something, so the odd indexes will return undefined; lets filter them out now

A simple fiddle illustrating the functionality via console logging.


问:
Swift missing types when build framework for simulator
I've a project that has (my own) framework within it.

When I build for device, everything is fine.

However when I build for simulator it seems that Alamofire is an issue. My main project requires Alamofire, and so does my framework.

In order to get Alamofire to work within my external framework I dragged the framework files into my framework - perhaps this is the issue?

答: The way to get around this was to use private pods to manage the dependencies.</p>


问:
Combine queries to multiple tables having the same columns in to one query
I have 6 tables. All of them can have millions and millions of lines of data. All of the tables have object_id, changer_id, date_created columns.

I need to make a query on all of the tables

```<code>SELECT object_id
FROM table#
WHERE changer_id=someId
AND date_created > dateA
AND dateCreated < dateB
</code>```

or its grails equivalent

```<code>table#.createQuery().list{
        projections{property('object_id')}
        eq('changer_id', someId)
        ge('dateCreated' dateA)
        le('dateCreated', dateB)
}
</code>```

Same query will be made on all of the 6 tables, and then the results are combined and all duplicates are removed.

Im not using between because dateB might not always exist so it would be ommited.

Is there a way to combine this query into single query over 6 tables or any other way to make it faster than 6 separate queryes?

答:
SQL inheritance:

assuming your tables are table1, table2, etc,

setup: do this once:

```<code>create table combined ( like table1 );

alter table table1 inherits combined;
alter table table2 inherits combined;
alter table table3 inherits combined;
alter table table4 inherits combined;
alter table table5 inherits combined;
alter table table6 inherits combined;
</code>```

the query, do this many times as needed:

```<code>SELECT object_id
FROM combined
WHERE changer_id=someId
AND date_created > dateA
AND dateCreated < dateB
</code>```

postgresql will internally generate the unions needed.

I'm assuming that all the tables have the same columns, if not  exclude any columns that are missing from some tables when you create the combined table. (you don't have to use like... , you can use the more common list-of-columns syntax)

Body:
I have 6 tables. All of them can have millions and millions of lines of data. All of the tables have object_id, changer_id, date_created columns.

I need to make a query on all of the tables

SELECT object_id
FROM table#
WHERE changer_id=someId
AND date_created > dateA
AND dateCreated < dateB

or its grails equivalent

table#.createQuery().list{
        projections{property('object_id')}
        eq('changer_id', someId)
        ge('dateCreated' dateA)
        le('dateCreated', dateB)
}

Same query will be made on all of the 6 tables, and then the results are combined and all duplicates are removed.

Im not using between because dateB might not always exist so it would be ommited.

Is there a way to combine this query into single query over 6 tables or any other way to make it faster than 6 separate queryes?

Body:
SQL inheritance:

assuming your tables are table1, table2, etc,

setup: do this once:

create table combined ( like table1 );

alter table table1 inherits combined;
alter table table2 inherits combined;
alter table table3 inherits combined;
alter table table4 inherits combined;
alter table table5 inherits combined;
alter table table6 inherits combined;

the query, do this many times as needed:

SELECT object_id
FROM combined
WHERE changer_id=someId
AND date_created > dateA
AND dateCreated < dateB

postgresql will internally generate the unions needed.

I'm assuming that all the tables have the same columns, if not  exclude any columns that are missing from some tables when you create the combined table. (you don't have to use like... , you can use the more common list-of-columns syntax)


问:
Recursively cycle every path of an array
I have the following(json) object:

```<code>$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);
</code>```

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

```<code>Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)
</code>```

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

```<code>foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}
</code>```

答:
Try this

i have created sample recursive program which u can tune

```<code>$obj = json_decode('{"Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}');

recursive($obj);

function recursive($obj){

    if(is_array($obj)){

        foreach ($obj as $k => $v) {
            echo $v." ";
        }

        return;
    }

    foreach ($obj as $key => $value) {
        echo $key. " =>";
        recursive($value);
    }

    echo "\n";

}
</code>```

Following is sample output

```<code>Group1 =>Blue =>Round =>Harold Arthur Tom
Green =>Round =>Harold Circle =>Todd Mike
Group2 =>Blue =>Round =>Peter
</code>```

Body:
I have the following(json) object:

$obj = json_decode('{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}', true);

I'm trying to figure out how to recursively travel through it so I can see all the different paths that is in the array.

It could be 4 separate echo's or a 4 line string. The > could be replaced with anything or nothing at all. If each line was echo'd separately or pushed to an array that would probably give the most flexibility.

Group1 - Blue - Round - (Harold, Arthur, Tom)
Group1 - Green - Round - (Harold)
Group1 - Green - Circle - (Todd, Mike)
Group2 - Blue - Round - (Peter)

I can't wrap my head around it so any help would be appreciated.

I'm thinking I can somehow cycle through each like:

foreach($obj as $index => $value)
{
   // and then somehow do this until you reach an array?
}

Body:
Try this

i have created sample recursive program which u can tune

$obj = json_decode('{"Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        },
        "Green": {
            "Round": [
                "Harold"
            ],
            "Circle": [
                "Todd",
                "Mike"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}');

recursive($obj);

function recursive($obj){

    if(is_array($obj)){

        foreach ($obj as $k => $v) {
            echo $v." ";
        }

        return;
    }

    foreach ($obj as $key => $value) {
        echo $key. " =>";
        recursive($value);
    }

    echo "\n";

}

Following is sample output

Group1 =>Blue =>Round =>Harold Arthur Tom
Green =>Round =>Harold Circle =>Todd Mike
Group2 =>Blue =>Round =>Peter