答:
Your problem is that you are using the second Array(100).fill(false) in every position of the first array. Thats why when you change one value in the "second" dimension it will change in every single position of the array. If you want to avoid this you hve to create a new Array for each position of the initial.

```<code>var x = Array(100).fill().map(x => Array(100).fill(false));
</code>```

Title: Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?

Body:
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Body:
Your problem is that you are using the second Array(100).fill(false) in every position of the first array. Thats why when you change one value in the "second" dimension it will change in every single position of the array. If you want to avoid this you hve to create a new Array for each position of the initial.

var x = Array(100).fill().map(x => Array(100).fill(false));


来源: stackexchange

问:
Configuring multiple metadata.xml with its own entityid in SAML
We have a requirement of having multiple metadata.xml and its entity to enable SSO as we have multiple country sites running from a same instance and same code base.

What we did so far

Customised the metadatageneratorfilter to set proper entity based on the request url (we have country code coming in the domain of url).

In Spring XML,

```<code>     ```
[bean id="metadata"  class="org.springframework.security.saml.metadata.CachingMetadataManager">
        [constructor-arg>
            [list>
            [bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                     [constructor-arg>
                [bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">

                    [constructor-arg>
                        [value type="java.io.File">${sso.metadata.location:classpath:security/metadata_se.xml}[/value>
                    [/constructor-arg>
                    [property name="parserPool" ref="parserPool"/>
                [/bean>
                [/constructor-arg>
                 [!-- added section starts -->
                    [constructor-arg>
                        [bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                [property name="signingKey" value="ssoIDPCertr"/>
                        [/bean>
                    [/constructor-arg>
                    [!-- added section ends-->
                 [/bean>
                 [bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                     [constructor-arg>
                [bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">

                    [constructor-arg>
                        [value type="java.io.File">${sso.metadata.location:classpath:security/metadata_es.xml}[/value>
                    [/constructor-arg>
                    [property name="parserPool" ref="parserPool"/>
                [/bean>
                [/constructor-arg>
                 [!-- added section starts -->
                    [constructor-arg>
                        [bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                [property name="signingKey" value="ssoIDPCertr"/>
                        [/bean>
                    [/constructor-arg>
                    [!-- added section ends-->
                 [/bean>
                 [bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                     [constructor-arg>
                [bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">

                    [constructor-arg>
                        [value type="java.io.File">${sso.metadata.location:classpath:security/metadata_de.xml}[/value>
                    [/constructor-arg>
                    [property name="parserPool" ref="parserPool"/>
                [/bean>
                [/constructor-arg>
                 [!-- added section starts -->
                    [constructor-arg>
                        [bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                [property name="signingKey" value="ssoIDPCertr"/>
                        [/bean>
                    [/constructor-arg>
                    [!-- added section ends-->
                 [/bean>
            [/list>
        [/constructor-arg>
    [/bean>

```

But this approach is not working as we dont have set providers against any unique values to identify the proper providers for countries.

our urls will be like
```
https://xy.brand.com

https://yy.brand.com
```
</code>```

Each site has separate metadata.xml.

we need to store metadata.xml with countryCode as identifiers and retrieve it based on request url before forming SAML request & response.

Any help will be much appreciated.

Thanks,
Siva

答: Is using a different entityID the only reason why you are separating your SP metadata xml files? If so, have you considered using entity alias ?</p>

ContentLicense: CC BY-SA 3.0

Body:
We have a requirement of having multiple metadata.xml and its entity to enable SSO as we have multiple country sites running from a same instance and same code base.

What we did so far

Customised the metadatageneratorfilter to set proper entity based on the request url (we have country code coming in the domain of url).

In Spring XML,

[bean id="metadata"  class="org.springframework.security.saml.metadata.CachingMetadataManager">
        [constructor-arg>
            [list>
            [bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                     [constructor-arg>
                [bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">

                    [constructor-arg>
                        [value type="java.io.File">${sso.metadata.location:classpath:security/metadata_se.xml}[/value>
                    [/constructor-arg>
                    [property name="parserPool" ref="parserPool"/>
                [/bean>
                [/constructor-arg>
                 [!-- added section starts -->
                    [constructor-arg>
                        [bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                [property name="signingKey" value="ssoIDPCertr"/>
                        [/bean>
                    [/constructor-arg>
                    [!-- added section ends-->
                 [/bean>
                 [bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                     [constructor-arg>
                [bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">

                    [constructor-arg>
                        [value type="java.io.File">${sso.metadata.location:classpath:security/metadata_es.xml}[/value>
                    [/constructor-arg>
                    [property name="parserPool" ref="parserPool"/>
                [/bean>
                [/constructor-arg>
                 [!-- added section starts -->
                    [constructor-arg>
                        [bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                [property name="signingKey" value="ssoIDPCertr"/>
                        [/bean>
                    [/constructor-arg>
                    [!-- added section ends-->
                 [/bean>
                 [bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                     [constructor-arg>
                [bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">

                    [constructor-arg>
                        [value type="java.io.File">${sso.metadata.location:classpath:security/metadata_de.xml}[/value>
                    [/constructor-arg>
                    [property name="parserPool" ref="parserPool"/>
                [/bean>
                [/constructor-arg>
                 [!-- added section starts -->
                    [constructor-arg>
                        [bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                                [property name="signingKey" value="ssoIDPCertr"/>
                        [/bean>
                    [/constructor-arg>
                    [!-- added section ends-->
                 [/bean>
            [/list>
        [/constructor-arg>
    [/bean>

But this approach is not working as we dont have set providers against any unique values to identify the proper providers for countries.

our urls will be like

https://xy.brand.com

https://yy.brand.com

Each site has separate metadata.xml.

we need to store metadata.xml with countryCode as identifiers and retrieve it based on request url before forming SAML request & response.

Any help will be much appreciated.

Thanks,
Siva


问:
How to write regex to match anything or nothing except certain character
I have a regex which is \$[A-a]+[0-9]+ to match the strings like:
$A1 + $A10 to filter "$A1" and "$A10".

But if there is ":" before or after I don't want anything to be matched. Say, if the string is $A1:$A10. I don't want either $A1 or $A10 can be filtered.

How should I write the regex. I tried to use [^:] , which will be like:
[^:]\$[A-a]+[0-9]+[^:]
It seems string "$A1:$A10" works. (Nothing matched)
But then string "$A1+$A10" doesn't work. (Neither $A1 nor $A10 is matched)

答:
You want zero-length lookahead and look behind patterns:

(?<!:)\$\a+\d+(?!:)

Demo


问:
After effects and Hyperlinks
I am trying to add a hyperlink in an After Effects composition so that when the animation plays that you can click on it to jump to a hyperlink. I have tried placing the hyperlink inside a marker in the composition but once rendered, nothing seems to be working.

Basically trying to recreate the link overlays that people add to their youtube clips. Any help?

答:
TL;DR: There is nothing mature to do this that works on all platforms except for HTML5 + JS.

In After Effects itself this is not possible. You could use Flash. But that means that your recipient needs to have a flash player on his machine.

In ancient times you could also create interactive Videos with QuickTime Pro 7 e.g. like in this tutorial but it never moved out of the QT and nobody cared. It is bound to the platform (macOS) and the player (QT).

In 2003  Matthew R. Peterson wrote a book about it Authoring Wired Media (QuickTime Developer Series) and it sounds like "the next big thing".

Title: After effects and Hyperlinks


问:
Simplest way to listen to another server?
I have server A (Windows, C#.NET), which  needs to send an alert/signal to server B (Linux, Java, Apache) everytime a certain process is done. I need to do this using a method call from .NET. What would be the easiest way to do this? I am thinking of setting up a web server on server B on some port which would listen to requests from server A. But how should I go about this? I am new to Java and have no experience with writing java web services, and I need to get this up quick, that is why I want to do this as easy as possible.</p>

答:
You might be interested in Thrift, which is designed for cross-language services. It only takes a few minutes to setup a simple server/client application in any of the supported languages. It supports Java and C#.

Thrift is used heavily by Facebook, so it is mature enough for production use.

ContentLicense: CC BY-SA 2.5


问:
How to Integrate Arc Lengths using python, numpy, and scipy?
On another thread, I saw someone manage to integrate the length of a arc using mathematica.They wrote:

```<code>In[1]:= ArcTan[3.05*Tan[5Pi/18]/2.23]
Out[1]= 1.02051
In[2]:= x=3.05 Cos[t];
In[3]:= y=2.23 Sin[t];
In[4]:= NIntegrate[Sqrt[D[x,t]^2+D[y,t]^2],{t,0,1.02051}]
Out[4]= 2.53143
</code>```

How exactly could this be transferred to python using the imports of numpy and scipy? In particular, I am stuck on line 4 in his code with the "NIntegrate" function. Thanks for the help!

Also, if I already have the arc length and the vertical axis length, how would I be able to reverse the program to spit out the original paremeters from the known values? Thanks!

答:
To my knowledge scipy cannot perform symbolic computations (such as symbolic differentiation). You may want to have a look at http://www.sympy.org for a symbolic computation package. Therefore, in the example below, I compute derivatives analytically (the Dx(t) and Dy(t) functions).

```<code>>>> from scipy.integrate import quad
>>> import numpy as np
>>> Dx = lambda t: -3.05 * np.sin(t)
>>> Dy = lambda t: 2.23 * np.cos(t)
>>> quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, 1.02051)
(2.531432761012828, 2.810454936566873e-14)
</code>```

EDIT: Second part of the question - inverting the problem

From the fact that you know the value of the integral (arc) you can now solve for one of the parameters that determine the arc (semi-axes, angle, etc.) Let's assume you want to solve for the angle. Then you can use one of the non-linear solvers in scipy, to revert the equation quad(theta) - arcval == 0. You can do it like this:

```<code>>>> from scipy.integrate import quad
>>> from scipy.optimize import broyden1
>>> import numpy as np
>>> a = 3.05
>>> b = 2.23
>>> Dx = lambda t: -a * np.sin(t)
>>> Dy = lambda t: b * np.cos(t)
>>> arc = lambda theta: quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, np.arctan((a / b) * np.tan(np.deg2rad(theta))))[0]
>>> invert = lambda arcval: float(broyden1(lambda x: arc(x) - arcval, np.rad2deg(arcval / np.sqrt((a**2 + b**2) / 2.0))))
</code>```

Then:

```<code>>>> arc(50)
2.531419526553662
>>> invert(arc(50))
50.000031008458365
</code>```

Body:
On another thread, I saw someone manage to integrate the length of a arc using mathematica.They wrote:

In[1]:= ArcTan[3.05*Tan[5Pi/18]/2.23]
Out[1]= 1.02051
In[2]:= x=3.05 Cos[t];
In[3]:= y=2.23 Sin[t];
In[4]:= NIntegrate[Sqrt[D[x,t]^2+D[y,t]^2],{t,0,1.02051}]
Out[4]= 2.53143

How exactly could this be transferred to python using the imports of numpy and scipy? In particular, I am stuck on line 4 in his code with the "NIntegrate" function. Thanks for the help!

Also, if I already have the arc length and the vertical axis length, how would I be able to reverse the program to spit out the original paremeters from the known values? Thanks!

Body:
To my knowledge scipy cannot perform symbolic computations (such as symbolic differentiation). You may want to have a look at http://www.sympy.org for a symbolic computation package. Therefore, in the example below, I compute derivatives analytically (the Dx(t) and Dy(t) functions).

>>> from scipy.integrate import quad
>>> import numpy as np
>>> Dx = lambda t: -3.05 * np.sin(t)
>>> Dy = lambda t: 2.23 * np.cos(t)
>>> quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, 1.02051)
(2.531432761012828, 2.810454936566873e-14)

EDIT: Second part of the question - inverting the problem

From the fact that you know the value of the integral (arc) you can now solve for one of the parameters that determine the arc (semi-axes, angle, etc.) Let's assume you want to solve for the angle. Then you can use one of the non-linear solvers in scipy, to revert the equation quad(theta) - arcval == 0. You can do it like this:

>>> from scipy.integrate import quad
>>> from scipy.optimize import broyden1
>>> import numpy as np
>>> a = 3.05
>>> b = 2.23
>>> Dx = lambda t: -a * np.sin(t)
>>> Dy = lambda t: b * np.cos(t)
>>> arc = lambda theta: quad(lambda t: np.sqrt(Dx(t)**2 + Dy(t)**2), 0, np.arctan((a / b) * np.tan(np.deg2rad(theta))))[0]
>>> invert = lambda arcval: float(broyden1(lambda x: arc(x) - arcval, np.rad2deg(arcval / np.sqrt((a**2 + b**2) / 2.0))))

Then:

>>> arc(50)
2.531419526553662
>>> invert(arc(50))
50.000031008458365


问:
Vue js 2 list rendering issue
I have faced an issue when doing a simple shopping cart app in vue js 2
Here is the code I have:

blank cart item array for when I press add to cart button then that particular product will be pushed in this array.

```<code>data () {
    return {
      cartItems: []
    }
}
</code>```

add to cart method:

```<code>methods: {
    addToCart (product) {
      product.quantity += 1
      this.cartItems.push(product)
    }
}
</code>```

Template view:

```<code><ul>
   <li v-for="item in items">
        ```
            {{item.name}} -- {{item.quantity}}
        ```
    </li>
</ul>
</code>```

in the browser, I got this:

note: right side 1 and 2 value is the quantity of that product
but I want something like this.

note: right side 1 and 2 value is the quantity of that product

If I use vue js 1 instead of vue js 2 then same code gives me browser view like 2nd screenshot I attached.

Please, anybody, help me to solve this.

答:
How du you create the new products? Do you reference the same object when calling addToCart or do you do some kind of deep copy or extend? If your adding the same reference multiple times they will all have the same quantity.

v-for="item in items" this should be ìf cartItems if you are not using pseudo code as example.

Title: Vue js 2 list rendering issue

Body:
I have faced an issue when doing a simple shopping cart app in vue js 2
Here is the code I have:

blank cart item array for when I press add to cart button then that particular product will be pushed in this array.

data () {
    return {
      cartItems: []
    }
}

add to cart method:

methods: {
    addToCart (product) {
      product.quantity += 1
      this.cartItems.push(product)
    }
}

Template view:

            {{item.name}} -- {{item.quantity}}

in the browser, I got this:

note: right side 1 and 2 value is the quantity of that product
but I want something like this.

note: right side 1 and 2 value is the quantity of that product

If I use vue js 1 instead of vue js 2 then same code gives me browser view like 2nd screenshot I attached.

Please, anybody, help me to solve this.


问:
Want to edit the HTML/PHP of a Wordpress Widget
Basically, in my theme there is called a top-widget which allows you to add a menu, which is made up of
 and
 tags. I really want to edit the HTML of this
 setup it has going, and add a few more things (like custom fields to them).

The farthest I was able to trace it was this line:

```<code><?php if ( is_front_page() ) : ?>
  <div class="container">
    <div class="row">
      <div class="col-md-4">
        <?php dynamic_sidebar( 'top_widget_left' ); ?>
      </div>
      <div class="col-md-4">
       <?php dynamic_sidebar( 'top_widget_middle' ); ?>
     </div>
     <div class="col-md-4">
      <?php dynamic_sidebar( 'top_widget_right' ); ?>
    </div>
  </div>
</div>
<?php endif; ?>
</code>```

More specifically the <?php dynamic_sidebar( 'top_widget_left' ); ?>. Any possible idea what file/location this is calling?

答:
Add this code in widget action hook of your theme function.php

```<code><?php
register_sidebar( array(
    'name' => 'Custom Widget',
    'id' => 'custom-widget',
    'description' => 'Appears in the Home area',
    'before_widget' => '<aside id="%1$s" class="widget %2$s">',
    'after_widget' => '</aside>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
    ) );
?>
</code>```

For calling in your theme any page widget use this code:

```<code><?php
    if(is_active_sidebar('custom-widget'))
    {
        dynamic_sidebar('custom-widget');
    }
?>
</code>```

Body:
Basically, in my theme there is called a top-widget which allows you to add a menu, which is made up of
 and
 tags. I really want to edit the HTML of this
 setup it has going, and add a few more things (like custom fields to them).

The farthest I was able to trace it was this line:

<?php if ( is_front_page() ) : ?>

        <?php dynamic_sidebar( 'top_widget_left' ); ?>

       <?php dynamic_sidebar( 'top_widget_middle' ); ?>

      <?php dynamic_sidebar( 'top_widget_right' ); ?>

<?php endif; ?>

More specifically the <?php dynamic_sidebar( 'top_widget_left' ); ?>. Any possible idea what file/location this is calling?

Body:
Add this code in widget action hook of your theme function.php

<?php
register_sidebar( array(
    'name' => 'Custom Widget',
    'id' => 'custom-widget',
    'description' => 'Appears in the Home area',
    'before_widget' => '<aside id="%1$s" class="widget %2$s">',
    'after_widget' => '</aside>',
    'before_title' => '<h3 class="widget-title">',
    'after_title' => '</h3>',
    ) );
?>

For calling in your theme any page widget use this code:

<?php
    if(is_active_sidebar('custom-widget'))
    {
        dynamic_sidebar('custom-widget');
    }
?>


问:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

```<code>>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true
</code>```

答:
what you are doing here is adding the same array object at each index of bigger array.

So when you do

```<code>Array(x).fill(Array(y).fill(false));
</code>```

What you are doing actually is :

```<code>Array(x).fill(Y); // i.e. X.fill(Y)
</code>```

Now whenever you change Y, you will get the same value at each index of X.

You should use loop to fill in data when data itself is an object(remember Array is object).

Body:
what you are doing here is adding the same array object at each index of bigger array.

So when you do

Array(x).fill(Array(y).fill(false));

What you are doing actually is :

Array(x).fill(Y); // i.e. X.fill(Y)

Now whenever you change Y, you will get the same value at each index of X.

You should use loop to fill in data when data itself is an object(remember Array is object).


问:
How to set margin top for header?
The --margin-top option is for the contents margin, but I would like to set the margin from the top of the page to the header. The project I'm working on allows users to create header and footer themselves, so the height of the header or footer is dynamic.

I don't know how to do it so can anyone help?

答:
Use -T -B -L and -R for margins.</p>

```<code>wkhtmltopdf -B 13 -L 13 -R 13 -T 53  /tmp/e0cb9c4597860b5abfbf2bafc1000d5a.html /tmp/e0cb9c4597860b5abfbf2bafc1000d5a.pdf
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to set margin top for header?

Body:
Use -T -B -L and -R for margins.

wkhtmltopdf -B 13 -L 13 -R 13 -T 53  /tmp/e0cb9c4597860b5abfbf2bafc1000d5a.html /tmp/e0cb9c4597860b5abfbf2bafc1000d5a.pdf


问:
Pandas select rows in DataFrameGroupBy bases on hierarchical index
I have the following dataframe (called df):

```<code>   user_id  product_id  probReorder
0        1         196          1.0
1        1       10258          0.9
2        1       10326          0.1
3        1       12427          1.0
4        1       13032          0.3
...
</code>```

For each user_id in df, I'd like to retain only the N rows with the largest values in the "probReorder" column. Also, I want N to depend on user_id.
In my current approach, I have a dict "lastReordNumber" whose key-value pairs are (user_id, int), and I select the rows as follows:

```<code>predictions = []
for usr,data in df.groupby(by="user_id"):
    data = data.nlargest(lastReordNumber[usr], "probReorder")
    predictions.append(data)
df = pd.concat(predictions)
</code>```

The problem is that this is really slow. The dataframe has around 13M rows and 200k unique user_id's. Is there a faster/better approach?

EDIT: The previous code produces unexpected output when there are duplicate values in the probReorder column for a given user_id. Example:

```<code>lastReordNumber = {1:2, 2:3}
df = pd.DataFrame({"user_id":[1,1,1,2,2,2,2],"probReorder":[0.9,0.6,0.9,0.1,1,0.5,0.4],\
    "product_id":[1,2,3,4,5,6,7]})
</code>```

I get the output:

```<code>   probReorder  product_id  user_id
0          0.9           1        1
1          0.9           3        1
2          0.9           1        1
3          0.9           3        1
4          1.0           5        2
5          0.5           6        2
6          0.4           7        2
</code>```

which for user_id=2 is what I expect, but for user_id=1 there are duplicate rows.
My expected output is:

```<code>   probReorder  product_id  user_id
0          0.9           1        1
1          0.9           3        1
2          1.0           5        2
3          0.5           6        2
4          0.4           7        2
</code>```

This can be obtained by using the simpler piece of code

```<code>predictions = []
for usr,data in df.groupby(by="user_id"):
    predictions.append(data.sort_values('probReorder', ascending=False).head(lastReordNumber[usr]))
predictions = pd.concat(predictions, ignore_index=True)
</code>```

in which each column is sorted completely and then truncated. This is also reasonably efficient.
I haven't understood yet how to interpret the result of the nlargest() method, though.

答:
You can use sort_values with groupby and head:

```<code>df1 = df.sort_values('probReorder', ascending=False)
        .groupby('user_id', group_keys=False)
        .apply(lambda x: x.head([x.name]))
print (df1)
   probReorder  product_id  user_id
0          0.9           1        1
2          0.9           3        1
4          1.0           5        2
5          0.5           6        2
6          0.4           7        2
</code>```

Another solution with nlargest:

```<code>df1 = df.groupby('user_id', group_keys=False)
        .apply(lambda x: x.nlargest(lastReordNumber[x.name], 'probReorder'))
print (df1)
   probReorder  product_id  user_id
0          0.9           1        1
2          0.9           3        1
4          1.0           5        2
5          0.5           6        2
6          0.4           7        2
</code>```

Body:
I have the following dataframe (called df):

   user_id  product_id  probReorder
0        1         196          1.0
1        1       10258          0.9
2        1       10326          0.1
3        1       12427          1.0
4        1       13032          0.3
...

For each user_id in df, I'd like to retain only the N rows with the largest values in the "probReorder" column. Also, I want N to depend on user_id.
In my current approach, I have a dict "lastReordNumber" whose key-value pairs are (user_id, int), and I select the rows as follows:

predictions = []
for usr,data in df.groupby(by="user_id"):
    data = data.nlargest(lastReordNumber[usr], "probReorder")
    predictions.append(data)
df = pd.concat(predictions)

The problem is that this is really slow. The dataframe has around 13M rows and 200k unique user_id's. Is there a faster/better approach?

EDIT: The previous code produces unexpected output when there are duplicate values in the probReorder column for a given user_id. Example:

lastReordNumber = {1:2, 2:3}
df = pd.DataFrame({"user_id":[1,1,1,2,2,2,2],"probReorder":[0.9,0.6,0.9,0.1,1,0.5,0.4],\
    "product_id":[1,2,3,4,5,6,7]})

I get the output:

   probReorder  product_id  user_id
0          0.9           1        1
1          0.9           3        1
2          0.9           1        1
3          0.9           3        1
4          1.0           5        2
5          0.5           6        2
6          0.4           7        2

which for user_id=2 is what I expect, but for user_id=1 there are duplicate rows.
My expected output is:

   probReorder  product_id  user_id
0          0.9           1        1
1          0.9           3        1
2          1.0           5        2
3          0.5           6        2
4          0.4           7        2

This can be obtained by using the simpler piece of code

predictions = []
for usr,data in df.groupby(by="user_id"):
    predictions.append(data.sort_values('probReorder', ascending=False).head(lastReordNumber[usr]))
predictions = pd.concat(predictions, ignore_index=True)

in which each column is sorted completely and then truncated. This is also reasonably efficient.
I haven't understood yet how to interpret the result of the nlargest() method, though.

Body:
You can use sort_values with groupby and head:

df1 = df.sort_values('probReorder', ascending=False)
        .groupby('user_id', group_keys=False)
        .apply(lambda x: x.head([x.name]))
print (df1)
   probReorder  product_id  user_id
0          0.9           1        1
2          0.9           3        1
4          1.0           5        2
5          0.5           6        2
6          0.4           7        2

Another solution with nlargest:

df1 = df.groupby('user_id', group_keys=False)
        .apply(lambda x: x.nlargest(lastReordNumber[x.name], 'probReorder'))
print (df1)
   probReorder  product_id  user_id
0          0.9           1        1
2          0.9           3        1
4          1.0           5        2
5          0.5           6        2
6          0.4           7        2


问:
How do I update a fields in table with strings randomly selected from a known list?
I have a table named "buildings" that contains a varchar(50) field named "use".  The table already has several thousand records, however the "use" values are all null.  I would like to update these this table with randomly chosen values from a list of strings (e.g., warehouse, office, market, retail, workshop). I would also like to leave some of these null to emulate real world usage.

How can I update a field in a table with strings randomly selected from a known list?

答:
This might work for you:</p>

```<code>BEGIN;
UPDATE Buildings SET Use = (ARRAY['warehouse', 'office', 'market', 'retail', 'workshop', NULL])[floor(random() * 6.0) + 1];
COMMIT;
</code>```

OwnerDisplayName: Ryan Taylor

Body:
This might work for you:

BEGIN;
UPDATE Buildings SET Use = (ARRAY['warehouse', 'office', 'market', 'retail', 'workshop', NULL])[floor(random() * 6.0) + 1];
COMMIT;

OwnerDisplayName: calebbrown


答:
Your entire array will be filled with references to the same (second dimension) array object.

To fill it with distinct objects, you'd have to do something like this:

const a = Array(100).fill(false).map(x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);```
</div>
</div>
</p>

<p>Note that the values in the initial array need to be explicitly set to something (in my example <code>false</code>, but could also be <code>undefined</code>), because the array created by the constructor is sparse and the <code>map()</code> function will only operate on properties that actually exist.</p>

<p>To work around that, you could use <code>Array.from()</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a = Array.from(Array(100), x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);</code>```

Body:
Your entire array will be filled with references to the same (second dimension) array object.

To fill it with distinct objects, you'd have to do something like this:

const a = Array(100).fill(false).map(x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);

Note that the values in the initial array need to be explicitly set to something (in my example false, but could also be undefined), because the array created by the constructor is sparse and the map() function will only operate on properties that actually exist.

To work around that, you could use Array.from():

const a = Array.from(Array(100), x => Array(100).fill(false));

a[0][0] = true;

console.log(a[0][0]);
console.log(a[0][1]);
console.log(a[1][1]);


问:
Link two tables with Order: MySQL and PHP
I have this table called user_friends:

```<code>accid  |  user1  |  user2
1       mark_12     john_24
2       john_24     jim_01
3       mark_12     jim_01
4       nico_7      mark_12
</code>```

And this table called users_students:

```<code>studentuniqueid  |  firstname  |  lastname  |  age
mark_12           Mark Anthony   Sierra       20
john_24           Johhny         Powers       21
jim_01            James          Sanders      21
nico_7            Nicolai        Renade       19
janice_53         Janice         Allaine      24
peter_41          Peter          Allan        21
</code>```

Now, here's what I wanted to do:

1.Select all entry/data in the user_friends table that has mark_12 (Mark's ID). Mark's ID could either be on user1 or user2 right? So I can just use SELECT * FROM user_friends WHERE user1 = 'mark_12' OR user2 = 'mark_12' and echo its accid, it will then display:

1, 3, 4 since mark_12 appears on those entries on the table.

2.Now I want to select and link the user_friends and users_student so that I could alphabetically arrange Mark's friends based on the user_friends table ORDERING them based on the lastname on the users_student table. I know this is possible, I just don't know how to do it yet.

I tried:

```<code>$user_id = $_SESSION['id'];
$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN IN (user_friends.user1,user_friends.user2)=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";
</code>```

And also:

```<code>$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN user_friends.user1,user_friends.user2=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";
</code>```

But somehow didn't work.
I want to achieve something like:

```<code>Mark's Friends:

Johnny Powers
Nicolai Renade
James Sanders
</code>```

答:
Do it like below:-

```<code>SELECT * FROM users_students LEFT JOIN user_friends ON user_friends.user2 = users_students.studentuniqueid WHERE (user_friends.user1 ="mark_12" OR user_friends.user2 ="mark_12" ) ORDER BY users_student.lastname ASC;
</code>```

Output:- http://sqlfiddle.com/#!9/cd4043/6/0

Now your full code need to look like this (what you asked in comment):-

```<code><?php
    //comment these two lines when your code satrted working fine
    error_reporting(E_ALL);
    ini_set('display_errors',1);

    //i have hard-code below two lines so comment them while using at your end
    $user_uniqueid = "mark_12";

    $con = mysqli_connect ('localhost','root','ourdesignz','stack');

    $mf_sql = "SELECT * FROM users_students LEFT JOIN user_friends ON user_friends.user2 = users_students.studentuniqueid WHERE (user_friends.user1 ='$user_uniqueid' OR user_friends.user2 ='$user_uniqueid' ) ORDER BY users_students.lastname ASC ";

    $mf_result = mysqli_query($con,$mf_sql) or die(mysqli_error($con));

    while($mf_row = mysqli_fetch_assoc($mf_result)){
        $friend_user1 = $mf_row['User1'];
        $friend_user2 = $mf_row['User2'];

        if($friend_user1!==$user_uniqueid){
          $ind_uniqueid =$friend_user1;
        }

        if($friend_user2!==$user_uniqueid){
          $ind_uniqueid =$friend_user2;
        }

        $us2_sql = "SELECT lastname FROM users_students WHERE studentuniqueid = '$ind_uniqueid' ORDER BY users_students.lastname ASC";
        $us2_result = mysqli_query($con,$us2_sql);
        $us2_row = mysqli_fetch_assoc($us2_result);

        $st_lastname = $us2_row['lastname'];

        echo $st_lastname."<br/>";
    }
?>
</code>```

Body:
I have this table called user_friends:

accid  |  user1  |  user2
1       mark_12     john_24
2       john_24     jim_01
3       mark_12     jim_01
4       nico_7      mark_12

And this table called users_students:

studentuniqueid  |  firstname  |  lastname  |  age
mark_12           Mark Anthony   Sierra       20
john_24           Johhny         Powers       21
jim_01            James          Sanders      21
nico_7            Nicolai        Renade       19
janice_53         Janice         Allaine      24
peter_41          Peter          Allan        21

Now, here's what I wanted to do:

1.Select all entry/data in the user_friends table that has mark_12 (Mark's ID). Mark's ID could either be on user1 or user2 right? So I can just use SELECT * FROM user_friends WHERE user1 = 'mark_12' OR user2 = 'mark_12' and echo its accid, it will then display:

1, 3, 4 since mark_12 appears on those entries on the table.

2.Now I want to select and link the user_friends and users_student so that I could alphabetically arrange Mark's friends based on the user_friends table ORDERING them based on the lastname on the users_student table. I know this is possible, I just don't know how to do it yet.

I tried:

$user_id = $_SESSION['id'];
$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN IN (user_friends.user1,user_friends.user2)=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";

And also:

$sql = "SELECT user_friends.accid,users_student.studentuniqueid FROM user_friends INNER JOIN user_friends.user1,user_friends.user2=users_student.studentuniqueid WHERE user1 = '$user_id' OR user2 = '$user_id' ORDER BY users_student.lastname ASC ";

But somehow didn't work.
I want to achieve something like:

Mark's Friends:

Johnny Powers
Nicolai Renade
James Sanders

Body:
Do it like below:-

SELECT * FROM users_students LEFT JOIN user_friends ON user_friends.user2 = users_students.studentuniqueid WHERE (user_friends.user1 ="mark_12" OR user_friends.user2 ="mark_12" ) ORDER BY users_student.lastname ASC;

Output:- http://sqlfiddle.com/#!9/cd4043/6/0

Now your full code need to look like this (what you asked in comment):-

<?php
    //comment these two lines when your code satrted working fine
    error_reporting(E_ALL);
    ini_set('display_errors',1);

    //i have hard-code below two lines so comment them while using at your end
    $user_uniqueid = "mark_12";

    $con = mysqli_connect ('localhost','root','ourdesignz','stack');

    $mf_sql = "SELECT * FROM users_students LEFT JOIN user_friends ON user_friends.user2 = users_students.studentuniqueid WHERE (user_friends.user1 ='$user_uniqueid' OR user_friends.user2 ='$user_uniqueid' ) ORDER BY users_students.lastname ASC ";

    $mf_result = mysqli_query($con,$mf_sql) or die(mysqli_error($con));

    while($mf_row = mysqli_fetch_assoc($mf_result)){
        $friend_user1 = $mf_row['User1'];
        $friend_user2 = $mf_row['User2'];

        if($friend_user1!==$user_uniqueid){
          $ind_uniqueid =$friend_user1;
        }

        if($friend_user2!==$user_uniqueid){
          $ind_uniqueid =$friend_user2;
        }

        $us2_sql = "SELECT lastname FROM users_students WHERE studentuniqueid = '$ind_uniqueid' ORDER BY users_students.lastname ASC";
        $us2_result = mysqli_query($con,$us2_sql);
        $us2_row = mysqli_fetch_assoc($us2_result);

        $st_lastname = $us2_row['lastname'];

        echo $st_lastname."<br/>";
    }
?>


问:
Main.js file in React -native not reflecting in my code
I am new in react-native applications.
When i am going to do changes in the Main.js file nothing is reflecting into it.but it works while changes in the index.android.bundle file.

what is the need of main.js file when all is reflecting into index.android.bundle file

I want to know the way to change the file in main.js so that i can be able to check the changes to the project.

Below are the file structure
android/app/src/main/assets/index.android.bundle

(Main.js file structure)
   project/main.js

Please help..

答:
We need to run below command after doind changes in the react js files
main.js . It will bundle them  to android state

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/

Then you need to run :->
command : react-native run-android

All changes will reflect into it directly on index.android.bundle files


问:
How to use class / id in li that is created by string query

$('.dropdown-container')
 .on('click', '.dropdown-button', function() {
     $('.dropdown-list').toggle();
 })
 .on('input', '.dropdown-search', function() {
     var target = $(this);
     var search = target.val().toLowerCase();

     if (!search) {
            $('li').show();
            return false;
        }

     $('li').each(function() {
         var text = $(this).text().toLowerCase();
            var match = text.indexOf(search) > -1;
            $(this).toggle(match);
        });
 })
 .on('change', '[type="checkbox"]', function() {
     var numChecked = $('[type="checkbox"]:checked').length;
     $('.quantity').text(numChecked || 'Any');
 });
// JSON of States for demo purposes
var usStates = [
    { name: 'ALABAMA', abbreviation: 'AL'},
    { name: 'ALASKA', abbreviation: 'AK'},
    { name: 'AMERICAN SAMOA', abbreviation: 'AS'}
];
//
 template
var stateTemplate = _.template(
    '
' +
     '<input name="<%= abbreviation %>" type="checkbox">' +
     '<label for="<%= abbreviation %>"><%= capName %>' +
    '
'
);
// Populate list with states
_.each(usStates, function(s) {
    s.capName = _.startCase(s.name.toLowerCase());
    $('ul').append(stateTemplate(s));
});```

I am trying to create a searchable multi-selector drop-down menu. But When I run this js file it changes all the li in the HTML. How Can I specify that js to only one div? So it won't mess with rest of the li or ul. As shown in the pic below.

答:
change your selector to:

```<code>$('.dropdown-container .dropdown-list ul').append(stateTemplate(s));
</code>```

and for the li's as well

```<code>$('.dropdown-container .dropdown-list ul li').each(function() {//....
</code>```

Body:
$('.dropdown-container')
 .on('click', '.dropdown-button', function() {
     $('.dropdown-list').toggle();
 })
 .on('input', '.dropdown-search', function() {
     var target = $(this);
     var search = target.val().toLowerCase();

     if (!search) {
            $('li').show();
            return false;
        }

     $('li').each(function() {
         var text = $(this).text().toLowerCase();
            var match = text.indexOf(search) > -1;
            $(this).toggle(match);
        });
 })
 .on('change', '[type="checkbox"]', function() {
     var numChecked = $('[type="checkbox"]:checked').length;
     $('.quantity').text(numChecked || 'Any');
 });
// JSON of States for demo purposes
var usStates = [
    { name: 'ALABAMA', abbreviation: 'AL'},
    { name: 'ALASKA', abbreviation: 'AK'},
    { name: 'AMERICAN SAMOA', abbreviation: 'AS'}
];
//
 template
var stateTemplate = _.template(
    '
' +
     '<input name="<%= abbreviation %>" type="checkbox">' +
     '<label for="<%= abbreviation %>"><%= capName %>' +
    '
'
);
// Populate list with states
_.each(usStates, function(s) {
    s.capName = _.startCase(s.name.toLowerCase());
    $('ul').append(stateTemplate(s));
});

I am trying to create a searchable multi-selector drop-down menu. But When I run this js file it changes all the li in the HTML. How Can I specify that js to only one div? So it won't mess with rest of the li or ul. As shown in the pic below.

Body:
change your selector to:

$('.dropdown-container .dropdown-list ul').append(stateTemplate(s));

and for the li's as well

$('.dropdown-container .dropdown-list ul li').each(function() {//....


答:
The problem is you push your product to array both times.
Check if product exists in cartItems array, if not - add, else - update product quantity</p>

Title: Vue js 2 list rendering issue


问:
Can this numpy.where() approach be adapted for two conditions instead of one?
I can get numpy.where() to work for one condition but not two conditions.

For one condition:

```<code>import numpy as np

a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5])
i, = np.where(a < 2)
print(i)
>> [ 0  5  8 10 11 12] ## indices where a[i] = 1
</code>```

For two conditions:

```<code># condition = (a > 1 and a < 3)
# i, = np.where(condition)
i, = np.where(a > 1 and a < 3)
print(i)
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code>```

I read up on a.any() and a.all() in this other SO post, but this doesn't work for my purpose since I want all indices that fit the condition rather than a single boolean value.

Is there a way to adapt this for two conditions?

答: Use np.where((a > 1) & (a < 3))

Body:
I can get numpy.where() to work for one condition but not two conditions.

For one condition:

import numpy as np

a = np.array([1, 2, 3, 4, 5, 1, 2, 3, 1, 2, 1, 1, 1, 2, 4, 5])
i, = np.where(a < 2)
print(i)
>> [ 0  5  8 10 11 12] ## indices where a[i] = 1

For two conditions:

# condition = (a > 1 and a < 3)
# i, = np.where(condition)
i, = np.where(a > 1 and a < 3)
print(i)
>> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I read up on a.any() and a.all() in this other SO post, but this doesn't work for my purpose since I want all indices that fit the condition rather than a single boolean value.

Is there a way to adapt this for two conditions?

Body: Use np.where((a > 1) & (a < 3))


问:
Check all $_POST Variable at once
instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like</p>

```<code>if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}
</code>```

答:
You can create an array of required fields and loop through that</p>

```<code>$required_fields = array("name", "address", "phone", "email");
foreach ($require_fields as $field) {
    if (!strlen($_POST[$field])) {
        echo "$field cannot be empty";
    }
}
</code>```

Title: Check all $_POST Variable at once

Body:
instead of checking all my post variables from a form one at a time is there any way to run one check to atleast verify that they are not empty something like

if(!isset(ALL $_POST)){
echo "one of your fields is not completed.";
}

Body:
You can create an array of required fields and loop through that

$required_fields = array("name", "address", "phone", "email");
foreach ($require_fields as $field) {
    if (!strlen($_POST[$field])) {
        echo "$field cannot be empty";
    }
}


问:
Android: Why does my android app displays an empty layout then crash when I am trying to retrieve information from a website?
I am trying to retrieve the source of a website but my app neither displays my gui nor does it print to the logs.

Here is my code.

```<code>import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try{

            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection)url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();           //start reading inputstream reader

            while(data!=-1){
                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        }
        catch (Exception e){

            e.printStackTrace();
            return null;
        }

    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DownloadTask task = new DownloadTask();
    String result = null;

    try {
        result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();

        Log.i("Contents of the url:", result);

    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    catch (ExecutionException e) {
        e.printStackTrace();
    }

}
</code>```

}

This is what displays in my log

```<code>07-06 21:08:01.020 2025-2025/? I/art: Late-enabling -Xcheck:jni
07-06 21:08:01.050 2025-2031/? I/art: Debugger is no longer active
07-06 21:08:01.082 2025-2025/? W/System: ClassLoader referenced unknown path: /data/app/com.example.jimmy.guesstherich-1/lib/arm
07-06 21:08:01.116 2025-2025/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-06 21:08:01.138 2025-2025/? D/PhoneWindowEx: [PWEx][generateLayout] setLGNavigationBarColor : colors=0xff000000
07-06 21:08:01.138 2025-2025/? I/PhoneWindow: [setLGNavigationBarColor] color=0x ff000000
07-06 21:08:01.233 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:01.234 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err: java.net.ConnectException: failed to connect to www.therichest.com/34.202.89.146 (port 443): connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.Socket.connect(Socket.java:888)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:188)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:99)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:151)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:187)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:238)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:134)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:384)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:371)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:408)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:247)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:29)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:15)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.Posix.connect(Native Method)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:   ... 26 more
07-06 21:08:32.299 2025-2025/com.example.jimmy.guesstherich D/AndroidRuntime: Shutting down VM
</code>```

It shows a blank screen for 30-45 seconds then it crashes and the logs print the following

```<code>07-06 21:08:32.300 2025-2025/com.example.jimmy.guesstherich E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.jimmy.guesstherich, PID: 2025
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jimmy.guesstherich/com.example.jimmy.guesstherich.MainActivity}: java.lang.NullPointerException: println needs a message
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
                                                                               Caused by: java.lang.NullPointerException: println needs a message
                                                                                at android.util.Log.println_native(Native Method)
                                                                                at android.util.Log.i(Log.java:160)
                                                                                at com.example.jimmy.guesstherich.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6279)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
</code>```

Any idea whats going on?

I'm a beginner so I apologize for any mistakes.

I am also following a video tutorial and have triple checked that everything is the same. His works completely fine. If it matters it's Rob Percival's "The Complete Android Development Course"

Thanks in advance, I appreciate it!

答:
You are facing this problem because you are putting wrong URL chek that url in your browser.

```<code>result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();
</code>```

Here is demo URL

```<code>result = task.execute("http://api.androidhive.info/contacts/").get();
</code>```

Body:
I am trying to retrieve the source of a website but my app neither displays my gui nor does it print to the logs.

Here is my code.

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class MainActivity extends AppCompatActivity {

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try{

            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection)url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();           //start reading inputstream reader

            while(data!=-1){
                char current = (char) data;

                result += current;

                data = reader.read();

            }
            return result;

        }
        catch (Exception e){

            e.printStackTrace();
            return null;
        }

    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DownloadTask task = new DownloadTask();
    String result = null;

    try {
        result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();

        Log.i("Contents of the url:", result);

    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    catch (ExecutionException e) {
        e.printStackTrace();
    }

}

}

This is what displays in my log

07-06 21:08:01.020 2025-2025/? I/art: Late-enabling -Xcheck:jni
07-06 21:08:01.050 2025-2031/? I/art: Debugger is no longer active
07-06 21:08:01.082 2025-2025/? W/System: ClassLoader referenced unknown path: /data/app/com.example.jimmy.guesstherich-1/lib/arm
07-06 21:08:01.116 2025-2025/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-06 21:08:01.138 2025-2025/? D/PhoneWindowEx: [PWEx][generateLayout] setLGNavigationBarColor : colors=0xff000000
07-06 21:08:01.138 2025-2025/? I/PhoneWindow: [setLGNavigationBarColor] color=0x ff000000
07-06 21:08:01.233 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:01.234 2025-2039/? D/libc: skt_base:0, kt_base:0, mptcp_enabled:0, socks_enabled:0, wifi_connected:1
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err: java.net.ConnectException: failed to connect to www.therichest.com/34.202.89.146 (port 443): connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:124)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.net.Socket.connect(Socket.java:888)
07-06 21:08:32.295 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:188)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:99)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:151)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:187)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:238)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:134)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:384)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:371)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:408)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:247)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:29)
07-06 21:08:32.296 2025-2039/com.example.jimmy.guesstherich W/System.err:     at com.example.jimmy.guesstherich.MainActivity$DownloadTask.doInBackground(MainActivity.java:15)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err: Caused by: android.system.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-06 21:08:32.297 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.Posix.connect(Native Method)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:111)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:     at libcore.io.IoBridge.connect(IoBridge.java:122)
07-06 21:08:32.298 2025-2039/com.example.jimmy.guesstherich W/System.err:   ... 26 more
07-06 21:08:32.299 2025-2025/com.example.jimmy.guesstherich D/AndroidRuntime: Shutting down VM

It shows a blank screen for 30-45 seconds then it crashes and the logs print the following

07-06 21:08:32.300 2025-2025/com.example.jimmy.guesstherich E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.jimmy.guesstherich, PID: 2025
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jimmy.guesstherich/com.example.jimmy.guesstherich.MainActivity}: java.lang.NullPointerException: println needs a message
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
                                                                               Caused by: java.lang.NullPointerException: println needs a message
                                                                                at android.util.Log.println_native(Native Method)
                                                                                at android.util.Log.i(Log.java:160)
                                                                                at com.example.jimmy.guesstherich.MainActivity.onCreate(MainActivity.java:67)
                                                                                at android.app.Activity.performCreate(Activity.java:6279)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:163)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5585)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Any idea whats going on?

I'm a beginner so I apologize for any mistakes.

I am also following a video tutorial and have triple checked that everything is the same. His works completely fine. If it matters it's Rob Percival's "The Complete Android Development Course"

Thanks in advance, I appreciate it!

Body:
You are facing this problem because you are putting wrong URL chek that url in your browser.

result = task.execute("https://www.therichest.com/top-lists/top-100-richest-celebrities").get();

Here is demo URL

result = task.execute("http://api.androidhive.info/contacts/").get();


问:
parse data from Dictionary in python
So i have this dictionary "runs":

```<code>[{
'id': 12,
'suite_id': 2,
'name': 'name',
'description': "desc.",
'nice_id': 3,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 1,
'blocked_count': 2,
'untested_count': 3,
'retest_count': 4,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'projekti_id': 1,
'plan_id': None,
'created_on': 12343214,
'created_by': 11,
'url': 'google.com'
}, {
'id': 16,
'suite_id': 2,
'name': 'namae)',
'description': "desc1",
'nice_id': 5,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 100,
'blocked_count': 1,
'untested_count': 3,
'retest_count': 2,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'prokti_id': 7,
'plan_id': None,
'created_on': 4321341644,
'created_by': 11,
'url': 'google.com/2' }
</code>```

there is "id" for about 50 times. that is just a part of it.
i need to find all "id":s (Not joku_ids, ncie_ids etc. Only "id") and make  a string/dict of them
and same for name, and description

i have tried:

```<code>j = json.load(run)
ids = (j["id"])

j = json.load(run)
names = (j["name"])

j = json.load(run)
descriptions = (j["description"])
</code>```

but it returns:

```<code>AttributeError: 'list' object has no attribute 'read'
</code>```

I also need to send a request with specific id and in this case the specific id is marked by o. so id[o]
the request code is below:

```<code>test = client.send_get('get_tests/1/ ')
</code>```

so i need to have the id[o] instead of the 1.
i have tried

```<code>test = client.send_get('get_tests/' + id[o] + '/ ')
</code>```

but it returns:

```<code>TypeError: 'int' object is not subscriptable
</code>```

答:
You are trying to pass a list to a json.load function. Please read the docs. Load() does not accep lists, it accepts

a .read()-supporting file-like object containing a JSON document

Title: parse data from Dictionary in python

Body:
So i have this dictionary "runs":

[{
'id': 12,
'suite_id': 2,
'name': 'name',
'description': "desc.",
'nice_id': 3,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 1,
'blocked_count': 2,
'untested_count': 3,
'retest_count': 4,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'projekti_id': 1,
'plan_id': None,
'created_on': 12343214,
'created_by': 11,
'url': 'google.com'
}, {
'id': 16,
'suite_id': 2,
'name': 'namae)',
'description': "desc1",
'nice_id': 5,
'joku_id': None,
'onko': False,
'eikai': False,
'tehty': None,
'config': None,
'config_ids': [],
'passed_count': 100,
'blocked_count': 1,
'untested_count': 3,
'retest_count': 2,
'failed_count': 5,
'custom_status1_count': 0,
'custom_status2_count': 0,
'custom_status3_count': 0,
'custom_status4_count': 0,
'custom_status5_count': 0,
'custom_status6_count': 0,
'custom_status7_count': 0,
'prokti_id': 7,
'plan_id': None,
'created_on': 4321341644,
'created_by': 11,
'url': 'google.com/2' }

there is "id" for about 50 times. that is just a part of it.
i need to find all "id":s (Not joku_ids, ncie_ids etc. Only "id") and make  a string/dict of them
and same for name, and description

i have tried:

j = json.load(run)
ids = (j["id"])

j = json.load(run)
names = (j["name"])

j = json.load(run)
descriptions = (j["description"])

but it returns:

AttributeError: 'list' object has no attribute 'read'

I also need to send a request with specific id and in this case the specific id is marked by o. so id[o]
the request code is below:

test = client.send_get('get_tests/1/ ')

so i need to have the id[o] instead of the 1.
i have tried

test = client.send_get('get_tests/' + id[o] + '/ ')

but it returns:

TypeError: 'int' object is not subscriptable


问:
Remove symbol when crawling data using scrapy
I want to get text by scrapy from a website. This is sample code:

```<code>def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div b::text").extract()
            print(dict(text=text))
</code>```

This is the result:

I want to remove the '.' symbol and every number symbol. So, I use regular expression. I change my code:

```<code>def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div b::text").re(r'[a-z]+')
            print(dict(text=text))
</code>```

But the result is:

I don't expect the result like that. I want to get like this:

{'text': ['abadi', 'mengabadi', 'mengabadikan', 'pengabadian', 'keabadian']}. How to do that?

答:
You can parse from text you scraped with re:

```<code>import re
text = ['aba.di','meng.a.ba.di','megn.a.ba.di.kan','1','2','peng.a.ba.di.an','ke.a.ba.di.an','1','2']
stack = [re.sub('[^a-zA-Z]+', '', e) for e in text]
text_new = [i for i in stack if i!=""]
print(text_new)
</code>```

text_new will be:

```<code>['abadi', 'mengabadi', 'megnabadikan', 'pengabadian', 'keabadian']
</code>```

Body:
I want to get text by scrapy from a website. This is sample code:

def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div b::text").extract()
            print(dict(text=text))

This is the result:

I want to remove the '.' symbol and every number symbol. So, I use regular expression. I change my code:

def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div b::text").re(r'[a-z]+')
            print(dict(text=text))

But the result is:

I don't expect the result like that. I want to get like this:

{'text': ['abadi', 'mengabadi', 'mengabadikan', 'pengabadian', 'keabadian']}. How to do that?

Body:
You can parse from text you scraped with re:

import re
text = ['aba.di','meng.a.ba.di','megn.a.ba.di.kan','1','2','peng.a.ba.di.an','ke.a.ba.di.an','1','2']
stack = [re.sub('[^a-zA-Z]+', '', e) for e in text]
text_new = [i for i in stack if i!=""]
print(text_new)

text_new will be:

['abadi', 'mengabadi', 'megnabadikan', 'pengabadian', 'keabadian']


问:
Box with multiple borders
I am trying to code and style a box which will contain a post. My problem is with multiple borders (i guess), trying to find the best way to code this, i prefer semantic HTML5 and CSS3, but if there is no other way, i can do "old style" with 3 divs (top, center, bottom) with css background: url..., can anyone give me some lights please?

If you please check the following url, you can check what i need to accomplish.

http://dl.dropbox.com/u/3696224/postBox.jpg

If you notice it has:

one border around all the box with a dark gray (#cccccc); (border)

a small space between that border and other light gray (#f7f7f7), almost white;

and only then the content with a white background;

Any suggestions? Very sorry for English grammar, thanks in advance.

Regards

PS - I almost forgot, i don't know is if needed or not, but the all around the box i have a box-shadow (i know how to do this part)

答:
```<code>.postcbox {
  border: 1px #ccc solid;
  background-color: #f7f7f7;
}

.postbox {
  background-color: white;
}

<div class="postcbox">
  <div class="postbox">

  </div>
</div>
</code>```

Title: Box with multiple borders


答:
May be this can help you.

```<code>id = []
for i in runs :
    id.append(i.get('id'))
</code>```

[12, 16]

Title: parse data from Dictionary in python

Body:
May be this can help you.

id = []
for i in runs :
    id.append(i.get('id'))

[12, 16]


问:
Javalin tutorial yielding "Unresolved reference: AtomicInteger"
Title says it. Following the Javalin tutorial as part of learning kotlin and getting the Unresolved Reference on mvn package.  I imagine I need to pull in a dependency, but the example doesn't show it and Google is failing me.  My pom.xml is large-ish, but my version info is as follows:

```<code><properties>
    <kotlin.version>1.1.3-2</kotlin.version>
</properties>
</code>```

and my current dependency list is:

```<code><dependencies>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jre8</artifactId>
        <version>${kotlin.version}</version>
    </dependency>
    <dependency>
        <groupId>io.javalin</groupId>
        <artifactId>javalin</artifactId>
        <version>0.3.3</version>
    </dependency>
</dependencies>
</code>```

Not really sure where to go from here.

答:
In the class UserDao you've forgotten to add the following import

```<code>import java.util.concurrent.atomic.AtomicInteger
</code>```

All the sources for the sample are available on github (https://github.com/tipsy/javalin-kotlin-example) so you can look that up as reference.

Body:
Title says it. Following the Javalin tutorial as part of learning kotlin and getting the Unresolved Reference on mvn package.  I imagine I need to pull in a dependency, but the example doesn't show it and Google is failing me.  My pom.xml is large-ish, but my version info is as follows:

<properties>
    <kotlin.version>1.1.3-2</kotlin.version>
</properties>

and my current dependency list is:

<dependencies>
    <dependency>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-stdlib-jre8</artifactId>
        <version>${kotlin.version}</version>
    </dependency>
    <dependency>
        <groupId>io.javalin</groupId>
        <artifactId>javalin</artifactId>
        <version>0.3.3</version>
    </dependency>
</dependencies>

Not really sure where to go from here.

Body:
In the class UserDao you've forgotten to add the following import

import java.util.concurrent.atomic.AtomicInteger

All the sources for the sample are available on github (https://github.com/tipsy/javalin-kotlin-example) so you can look that up as reference.


问:
Keep values selected after form submission
Consider:

```<code><form method="get" action="">
   <select name="name">
      <option value="a">a</option>
      <option value="b">b</option>
   </select>
   <select name="location">
      <option value="x">x</option>
      <option value="y">y</option>
   </select>
   <input type="submit" value="Submit" class="submit" />
</form>
</code>```

On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside WordPress (PHP).

答:
Try this solution for keep selected value in dropdown:</p>

```<code><form action="<?php echo get_page_link(); ?>" method="post">
    <select name="<?php echo $field_key['key']; ?>" onchange="javascript:
       submit()">
    <option value="">All Category</option>
    <?php
    foreach( $field['choices'] as $key => $value ){
       if($post_key==$key){ ?>
          <option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
   }else{?>
  <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
 <?php }
  }?>
 </select>
</form>
</code>```

Body:
Consider:

<form method="get" action="">
   <select name="name">
      <option value="a">a</option>
      <option value="b">b</option>
   </select>
   <select name="location">
      <option value="x">x</option>
      <option value="y">y</option>
   </select>
   <input type="submit" value="Submit" class="submit" />
</form>

On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside WordPress (PHP).

Body:
Try this solution for keep selected value in dropdown:

<form action="<?php echo get_page_link(); ?>" method="post">
    <select name="<?php echo $field_key['key']; ?>" onchange="javascript:
       submit()">
    <option value="">All Category</option>
    <?php
    foreach( $field['choices'] as $key => $value ){
       if($post_key==$key){ ?>
          <option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
   }else{?>
  <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
 <?php }
  }?>
 </select>
</form>