答:
You are passing invalid view argument to Snackbar. so you've to give RegisterActivity BaseLayout reference to it.
you should try declare id to activity_register.xml Linear / Relative or whatever you design.

```<code>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:background="#a7b6bdd6"
    android:id="@+id/ll1"  //here
     >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="@color/colorPrimary"
        android:minHeight="?attr/actionBarSize" />

        //your design

</LinearLayout>
</code>```

then initialise pass this layout to snackbar like below

```<code> private void registerProcess(String name,String email,String password){

     final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.ll1);// here change
      //Snackbar.make(linearLayout,"Hello", Snackbar.LENGTH_LONG).show();

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(linearLayout,resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
    });
}
</code>```

Title: java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view

Body:
You are passing invalid view argument to Snackbar. so you've to give RegisterActivity BaseLayout reference to it.
you should try declare id to activity_register.xml Linear / Relative or whatever you design.

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical"
              android:background="#a7b6bdd6"
    android:id="@+id/ll1"  //here
     >

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="@color/colorPrimary"
        android:minHeight="?attr/actionBarSize" />

        //your design

</LinearLayout>

then initialise pass this layout to snackbar like below

 private void registerProcess(String name,String email,String password){

     final LinearLayout linearLayout = (LinearLayout)findViewById(R.id.ll1);// here change
      //Snackbar.make(linearLayout,"Hello", Snackbar.LENGTH_LONG).show();

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(linearLayout,resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();

        }
    });
}


来源: stackexchange

问:
Semantic UI React Popup(s) Not Appearing
See title.

Code is literally

```<code><Popup
trigger={<li id="close"><a>Close</a></li>}
content="Click to close"
basic
/>
</code>```

And yeah when the item in question is hovered, or clicked, the popup doesn't appear. When I set open={true} it does, not attached to the component (as expected). Has anyone encountered this issue and could they advise possible solutions?

答:
I just rewrote your code and it works! However, in case you wanna control the popup with an open attribute, you should create a state for it and handle popup opening with an onMouseOver function.

For example:
you define a state named isPopupOpen and set it to false by default.

```<code>this.state={
isPopupOpen : false
}
</code>```

then you handle the situation with two methods:

```<code>handleMouseOver = () => this.setState({ isPopupOpen: true })

handleMouseOut = () => this.setState({ isPopupOpen: false })
</code>```

and finally write the popup this way:

```<code>                <Popup
                trigger={
                    <li
                    id='close'
                    onMouseOver={this.handleMouseOver}
                    onMouseOut={this.handleMouseOut}
                    >
                        <a>Close</a>
                    </li>
                }
                content={'click to close'}
                basic
                open={this.state.isPopupOpen}
            />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
See title.

Code is literally

<Popup
trigger={
Close
}
content="Click to close"
basic
/>

And yeah when the item in question is hovered, or clicked, the popup doesn't appear. When I set open={true} it does, not attached to the component (as expected). Has anyone encountered this issue and could they advise possible solutions?

Body:
I just rewrote your code and it works! However, in case you wanna control the popup with an open attribute, you should create a state for it and handle popup opening with an onMouseOver function.

For example:
you define a state named isPopupOpen and set it to false by default.

this.state={
isPopupOpen : false
}

then you handle the situation with two methods:

handleMouseOver = () => this.setState({ isPopupOpen: true })

handleMouseOut = () => this.setState({ isPopupOpen: false })

and finally write the popup this way:

                <Popup
                trigger={
                    <li
                    id='close'
                    onMouseOver={this.handleMouseOver}
                    onMouseOut={this.handleMouseOut}
                    >
                        <a>Close</a>
                    </li>
                }
                content={'click to close'}
                basic
                open={this.state.isPopupOpen}
            />


问:
Set vertical Index for dataframe
I want to bring the index 'Stkcd' into vertical index so that it will show a row of 1,2,3 .... for each row. I have try many transpose with different index but I seem that the index always shifting to the horizontal row, which is not what I want. I want my result to be like this.Stkcd on the vertical index on the left side

This is what I am getting I don't want the Stkcd to be on the horizontal line And the original data is this enter image description here

Title: Set vertical Index for dataframe

Body:
Use unstack:

Given:

print(df1)
                  value
Stkcd date
1     2015-12-02     11
      2015-12-03     12
      2015-12-04     12
      2015-12-05     11
      2015-12-06     10
      2015-12-07     12
      2015-12-08     10
      2015-12-09     10
      2015-12-10     11
      2015-12-11     14
      2015-12-12     14
      2015-12-13     12
      2015-12-14     14
2     2015-12-02     13
      2015-12-03     14
      2015-12-04     10
      2015-12-05     12
      2015-12-06     13
      2015-12-07     12
      2015-12-08     11
      2015-12-09     10
      2015-12-10     12
      2015-12-11     12
      2015-12-12     13
      2015-12-13     10
      2015-12-14     11
3     2015-12-02     10
      2015-12-03     11
      2015-12-04     13
      2015-12-05     11
      2015-12-06     12
      2015-12-07     10
      2015-12-08     12
      2015-12-09     11
      2015-12-10     14
      2015-12-11     13
      2015-12-12     12
      2015-12-13     11
      2015-12-14     12

df1.unstack()

Output:

           value                                                                               \
date  2015-12-02 2015-12-03 2015-12-04 2015-12-05 2015-12-06 2015-12-07 2015-12-08 2015-12-09
Stkcd
1             11         12         12         11         10         12         10         10
2             13         14         10         12         13         12         11         10
3             10         11         13         11         12         10         12         11

date  2015-12-10 2015-12-11 2015-12-12 2015-12-13 2015-12-14
Stkcd
1             11         14         14         12         14
2             12         12         13         10         11
3             14         13         12         11         12


问:
How to build instances after extracting a CSV file containing multiples values
I am trying to make multiples instance of the class Employee from a CSV file that contains employees and extracted from a static method. From now I just can get a list of those employees but what I want is Instantly assign those values to an instance variable.

Here is my code:

class Employees():

```<code>nums_of_employees = 0

def __init__(self, name, last, salary):

    self.name = name
    self.last = last
    self.salary = salary
    Employees.nums_of_employees +=1

def data(self):
    print(f'Name: {self.name} LastName: {self.last} Salary: {self.salary}')

@staticmethod
def extract_csv():
    new_emp = []
    with open('Employees.csv', 'r') as data_file:
        csv_data = csv.DictReader(data_file)
        next(csv_data)

        for line in csv_data:
            new_emp += line['Name'], line['Last'], line['Salary']

        return new_emp
</code>```

答:
Assuming Employee takes in 3 arguments (name, last and salary), you can replace

```<code>new_emp += (line['Name'], line['Last'], line['Salary'])
</code>```

with

```<code>new_emp.append(Employee(line['Name'], line['Last'], line['Salary']))
</code>```

to create a new Employee instance for every line you iterate through and append it to the new_emp list.

Body:
I am trying to make multiples instance of the class Employee from a CSV file that contains employees and extracted from a static method. From now I just can get a list of those employees but what I want is Instantly assign those values to an instance variable.

Here is my code:

class Employees():

nums_of_employees = 0

def __init__(self, name, last, salary):

    self.name = name
    self.last = last
    self.salary = salary
    Employees.nums_of_employees +=1

def data(self):
    print(f'Name: {self.name} LastName: {self.last} Salary: {self.salary}')

@staticmethod
def extract_csv():
    new_emp = []
    with open('Employees.csv', 'r') as data_file:
        csv_data = csv.DictReader(data_file)
        next(csv_data)

        for line in csv_data:
            new_emp += line['Name'], line['Last'], line['Salary']

        return new_emp

Body:
Assuming Employee takes in 3 arguments (name, last and salary), you can replace

new_emp += (line['Name'], line['Last'], line['Salary'])

with

new_emp.append(Employee(line['Name'], line['Last'], line['Salary']))

to create a new Employee instance for every line you iterate through and append it to the new_emp list.


问:
Simple way to restrict a function to only one instance
Every source just talks about classes. How do I ensure that only one instance of a function is running at a time in a multithreaded environment? The function will just be in a while(true) loop and has state conditions which the next set of data requires.

答: Functions are thread-agnostic by default. You can use a critical section in the function body to restrict the execution to a single process.</p>


问:
Why is Jersey Client response giving garbage data?
I cannot figure out why my code is giving me garbage data when I read the Http Response entity.  This is only happening when I issue a request to one specific URL with data that causes a 400 response.  My code attempts to read the response entity, but as you can see below it is garbage.

Here is a simplified test case:

```<code>import org.junit.Test;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;

public class Sandbox {
    @Test
    public void jaguarTestCase() {
        Client client = ClientBuilder.newClient();

        WebTarget target = client.target("http://www.jaguarusa.com/owners/vin-recall.html?view=vinRecallQuery&vin=xxxxxxxxxxxxxxxxx");
        Invocation.Builder builder = target.request();
        Response response = builder.get(Response.class);

        System.out.println("Response Code:");
        System.out.println("\t" + response.getStatus() + " - " + response.getStatusInfo().getReasonPhrase());

        System.out.println("\nResponse Headers:");
        for (Map.Entry<String, List<String>> entry : response.getStringHeaders().entrySet()) {
            System.out.print("\t" + entry.getKey() + ": ");
            for (String value : entry.getValue()) {
                System.out.println(value);
            }
        }

        String responseEntity = response.readEntity(String.class);
        System.out.println("\nResponse Entity: ");
        System.out.println(responseEntity);
    }
}
</code>```

And the output from that testcase:

```<code>Response Code:
    400 - Bad Request

Response Headers:
    X-Frame-Options: SAMEORIGIN
    Cache-Control: no-cache, no-store, must-revalidate
    Server: Apache-Coyote/1.1
    Connection: keep-alive
    Content-Encoding: gzip
    Vary: Accept-Encoding
    Content-Length: 135
    Date: Tue, 08 Nov 2016 00:03:23 GMT
    Content-Language: en-US
    Content-Type: application/json;charset=UTF-8

Response Entity:
�       \�1
�@E��:H
���B��C2����X�wנ��z�{%1�vw��:ga�����4$ ������k�Q�-i�����y��T��!f��� c�  ��iK-��?z�  ���dW��
</code>```

This is what the entity body is supposed to be (paste the URL in any browser and see for yourself):

```<code>{
    "errorMessage" : "Please check your details and try again.",
    "error" : 400,
    "errorTitle" : "Sorry, that is not a valid VIN.",
    "vin" : "XXXXXXXXXXXXXXXXX"
}
</code>```

I am using the JDK version 1.8.0_102.  I think the problem is happening when the response entity is parsed because the reported content-length of 135 is the correct value, confirmed by running this request in a Chrome browser debug window.

The Content-Type response header shows charset=UTF-8, which is what my JVM is running as.  What gives?  I'm completely stumped after working on this all afternoon.

答:
You can uncompress that response.

```<code>WebTarget target = ...
target.register(GZipEncoder.class);
</code>```

After this change, the readEntity thing you are doing should work fine.

This works in Jersey 2.26.

For earlier versions, the solutions are slightly different. Refer to https://stackoverflow.com/a/7574663/2695332

Body:
I cannot figure out why my code is giving me garbage data when I read the Http Response entity.  This is only happening when I issue a request to one specific URL with data that causes a 400 response.  My code attempts to read the response entity, but as you can see below it is garbage.

Here is a simplified test case:

import org.junit.Test;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Map;

public class Sandbox {
    @Test
    public void jaguarTestCase() {
        Client client = ClientBuilder.newClient();

        WebTarget target = client.target("http://www.jaguarusa.com/owners/vin-recall.html?view=vinRecallQuery&vin=xxxxxxxxxxxxxxxxx");
        Invocation.Builder builder = target.request();
        Response response = builder.get(Response.class);

        System.out.println("Response Code:");
        System.out.println("\t" + response.getStatus() + " - " + response.getStatusInfo().getReasonPhrase());

        System.out.println("\nResponse Headers:");
        for (Map.Entry<String, List<String>> entry : response.getStringHeaders().entrySet()) {
            System.out.print("\t" + entry.getKey() + ": ");
            for (String value : entry.getValue()) {
                System.out.println(value);
            }
        }

        String responseEntity = response.readEntity(String.class);
        System.out.println("\nResponse Entity: ");
        System.out.println(responseEntity);
    }
}

And the output from that testcase:

Response Code:
    400 - Bad Request

Response Headers:
    X-Frame-Options: SAMEORIGIN
    Cache-Control: no-cache, no-store, must-revalidate
    Server: Apache-Coyote/1.1
    Connection: keep-alive
    Content-Encoding: gzip
    Vary: Accept-Encoding
    Content-Length: 135
    Date: Tue, 08 Nov 2016 00:03:23 GMT
    Content-Language: en-US
    Content-Type: application/json;charset=UTF-8

Response Entity:
�       \�1
�@E��:H
���B��C2����X�wנ��z�{%1�vw��:ga�����4$ ������k�Q�-i�����y��T��!f��� c�  ��iK-��?z�  ���dW��

This is what the entity body is supposed to be (paste the URL in any browser and see for yourself):

{
    "errorMessage" : "Please check your details and try again.",
    "error" : 400,
    "errorTitle" : "Sorry, that is not a valid VIN.",
    "vin" : "XXXXXXXXXXXXXXXXX"
}

I am using the JDK version 1.8.0_102.  I think the problem is happening when the response entity is parsed because the reported content-length of 135 is the correct value, confirmed by running this request in a Chrome browser debug window.

The Content-Type response header shows charset=UTF-8, which is what my JVM is running as.  What gives?  I'm completely stumped after working on this all afternoon.

Body:
You can uncompress that response.

WebTarget target = ...
target.register(GZipEncoder.class);

After this change, the readEntity thing you are doing should work fine.

This works in Jersey 2.26.

For earlier versions, the solutions are slightly different. Refer to https://stackoverflow.com/a/7574663/2695332

ContentLicense: CC BY-SA 4.0


问:
How to use Hive sql's lag function with two columns?
I feel like I have a fairly simple SQL problem to solve, just don't know how to search for it correctly.

Say I have a table where values are updated based on time:

```<code>|timestamp|value|session|
|---------|-----|-------|
| ts1     | v1  |  s1   |
| ts2     | v2  |  s1   |
| ts3     | v3  |  s1   |
| ...     | ..  |  s2   |
</code>```

I want to get current value and previous value with associated timestamps.

So the result should be:

```<code>|timestamp_current|value_current|timestamp_prev|value_prev|
|-----------------|-------------|--------------|----------|
|      ts2        |      v2     |    ts1       |    v1    |
|      ts3        |      v3     |    ts2       |    v2    |
|      ...        |      ..     |    ...       |    ..    |
</code>```

I think the following query is correct if I was only looking to get the previous value, not the previous timestamp:

select timestamp, value, lag(value,1) over (partition by (session) order by timestamp)
from mytable

However, what is the correct way of adding TWO values from the previous row, do I add two lag clauses or is there a better way?

答:
You can derive your result by using lag() twice; once for prev_timestamp and once for prev_val as below.

```<code>select * from
(
select timestamp,
       value,
       lag(timestamp) over(partition by session order by timestamp) as prev_timestamp,
       lag(value) over(partition by session order by timestamp) as prev_value
from table1
) t
where prev_timestamp is not null
</code>```

where clause is used to exclude rows having prev_timestamp as NULL

Result:

```<code>+-----------+-------+----------------+------------+
| timestamp | value | prev_timestamp | prev_value |
+-----------+-------+----------------+------------+
| ts2       | v2    | ts1            | v1         |
| ts3       | v3    | ts2            | v2         |
+-----------+-------+----------------+------------+
</code>```

DEMO

Body:
I feel like I have a fairly simple SQL problem to solve, just don't know how to search for it correctly.

Say I have a table where values are updated based on time:

|timestamp|value|session|
|---------|-----|-------|
| ts1     | v1  |  s1   |
| ts2     | v2  |  s1   |
| ts3     | v3  |  s1   |
| ...     | ..  |  s2   |

I want to get current value and previous value with associated timestamps.

So the result should be:

|timestamp_current|value_current|timestamp_prev|value_prev|
|-----------------|-------------|--------------|----------|
|      ts2        |      v2     |    ts1       |    v1    |
|      ts3        |      v3     |    ts2       |    v2    |
|      ...        |      ..     |    ...       |    ..    |

I think the following query is correct if I was only looking to get the previous value, not the previous timestamp:

select timestamp, value, lag(value,1) over (partition by (session) order by timestamp)
from mytable

However, what is the correct way of adding TWO values from the previous row, do I add two lag clauses or is there a better way?

Body:
You can derive your result by using lag() twice; once for prev_timestamp and once for prev_val as below.

select * from
(
select timestamp,
       value,
       lag(timestamp) over(partition by session order by timestamp) as prev_timestamp,
       lag(value) over(partition by session order by timestamp) as prev_value
from table1
) t
where prev_timestamp is not null

where clause is used to exclude rows having prev_timestamp as NULL

Result:

+-----------+-------+----------------+------------+
| timestamp | value | prev_timestamp | prev_value |
+-----------+-------+----------------+------------+
| ts2       | v2    | ts1            | v1         |
| ts3       | v3    | ts2            | v2         |
+-----------+-------+----------------+------------+

DEMO


问:
how to set Linearlayout Center inside relative layout in android
```<code> <RelativeLayout
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:fillViewport="true"

            android:paddingLeft="80dp"
            android:paddingRight="80dp"
            android:paddingTop="40dp">

            <LinearLayout
                android:id="@+id/appLogogImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/circular_textview_drawable"
                android:gravity="center">

                <ImageView
                    android:layout_width="72dp"
                    android:layout_height="72dp"
                    android:layout_gravity="center"
                    android:background="@drawable/ic_share_illustration" />
            </LinearLayout>

            <TextView
                android:id="@+id/appTextview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appLogogImageView"
                android:fontFamily="sans-serif-medium"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:paddingTop="@dimen/baseline_grid_4x"
                android:text="Sharing is Caring"
                android:textColor="@color/colorDusk"
                android:textSize="20.1sp"
                android:textStyle="normal"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appTextview"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:lineSpacingExtra="6sp"
                android:text="Share ContSync with your friends to get them onboard"
                android:textColor="@color/colorBlueyGrey"
                android:textSize="14sp"
                android:textStyle="normal" />

        </RelativeLayout>
    </RelativeLayout>

// toolbar .xml

      <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"

                android:layout_height="?android:attr/actionBarSize">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?android:attr/actionBarSize"
                    app:elevation="@dimen/app_bar_default_elevation"
                    style="@style/TextAppearance.Widget.Event.Toolbar.Title"
                    tools:title="@string/label_select_your_country" />
            </android.support.design.widget.AppBarLayout>

https://pasteboard.co/
</code>```

This is my Xml and current Screen you can see the imageview which is inside Linearlayout is not set center . i  have puted gravity center in Linarlayout but its not   set center  i dont know what mistake i am doing even  on tool bar also i tried to set shadow below but its not coming can any one please suggest me what i am doing wrong.
[![enter image description here][1]][1]

this is my expected screen   in my current Screen and using current xml i am not able to set Imageview which is coming inside linear layout is not center and also toolbar below shadow is not coming please suggest me how to keep its center and how to put shadow below on tool bar as expected screen.

答:
Try this make your LinearLayout android:layout_centerInParent="true" like below code

```<code>    <LinearLayout
        android:id="@+id/appLogogImageView"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:background="@drawable/circular_textview_drawable"
        android:gravity="center">

        <ImageView
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:layout_gravity="center"
            android:background="@drawable/ic_share_illustration" />
    </LinearLayout>
</code>```

EDIT

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="#689F38"
        android:gravity="center">

        <include
            android:id="@+id/layout_toolbar"
            layout="@layout/toolbar_white_bg" />

    </RelativeLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:foregroundGravity="center_horizontal"
        android:text="SHARE"
        android:textColor="#ffff" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="80dp"
        android:paddingRight="80dp">

        <LinearLayout
            android:id="@+id/appLogogImageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginTop="-50dp"
            android:gravity="center"
            android:orientation="vertical">

            <ImageView
                android:layout_width="72dp"
                android:layout_height="72dp"
                android:layout_gravity="center"
                android:src="@mipmap/ic_launcher_round" />

            <TextView
                android:id="@+id/appTextview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appLogogImageView"
                android:fontFamily="sans-serif-medium"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:text="Sharing is Caring"
                android:textSize="20.1sp"
                android:textStyle="normal"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appTextview"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:lineSpacingExtra="6sp"
                android:text="Share ContSync with your friends to get them onboard"
                android:textSize="14sp"
                android:textStyle="normal" />

        </LinearLayout>

    </RelativeLayout>
</RelativeLayout>
</code>```

OUTPUT

Body:
 <RelativeLayout
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:fillViewport="true"

            android:paddingLeft="80dp"
            android:paddingRight="80dp"
            android:paddingTop="40dp">

            <LinearLayout
                android:id="@+id/appLogogImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/circular_textview_drawable"
                android:gravity="center">

                <ImageView
                    android:layout_width="72dp"
                    android:layout_height="72dp"
                    android:layout_gravity="center"
                    android:background="@drawable/ic_share_illustration" />
            </LinearLayout>

            <TextView
                android:id="@+id/appTextview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appLogogImageView"
                android:fontFamily="sans-serif-medium"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:paddingTop="@dimen/baseline_grid_4x"
                android:text="Sharing is Caring"
                android:textColor="@color/colorDusk"
                android:textSize="20.1sp"
                android:textStyle="normal"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appTextview"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:lineSpacingExtra="6sp"
                android:text="Share ContSync with your friends to get them onboard"
                android:textColor="@color/colorBlueyGrey"
                android:textSize="14sp"
                android:textStyle="normal" />

        </RelativeLayout>
    </RelativeLayout>

// toolbar .xml

      <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"

                android:layout_height="?android:attr/actionBarSize">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?android:attr/actionBarSize"
                    app:elevation="@dimen/app_bar_default_elevation"
                    style="@style/TextAppearance.Widget.Event.Toolbar.Title"
                    tools:title="@string/label_select_your_country" />
            </android.support.design.widget.AppBarLayout>

https://pasteboard.co/

This is my Xml and current Screen you can see the imageview which is inside Linearlayout is not set center . i  have puted gravity center in Linarlayout but its not   set center  i dont know what mistake i am doing even  on tool bar also i tried to set shadow below but its not coming can any one please suggest me what i am doing wrong.
[![enter image description here][1]][1]

this is my expected screen   in my current Screen and using current xml i am not able to set Imageview which is coming inside linear layout is not center and also toolbar below shadow is not coming please suggest me how to keep its center and how to put shadow below on tool bar as expected screen.

Body:
Try this make your LinearLayout android:layout_centerInParent="true" like below code

    <LinearLayout
        android:id="@+id/appLogogImageView"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:background="@drawable/circular_textview_drawable"
        android:gravity="center">

        <ImageView
            android:layout_width="72dp"
            android:layout_height="72dp"
            android:layout_gravity="center"
            android:background="@drawable/ic_share_illustration" />
    </LinearLayout>

EDIT

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="#689F38"
        android:gravity="center">

        <include
            android:id="@+id/layout_toolbar"
            layout="@layout/toolbar_white_bg" />

    </RelativeLayout>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:foregroundGravity="center_horizontal"
        android:text="SHARE"
        android:textColor="#ffff" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="80dp"
        android:paddingRight="80dp">

        <LinearLayout
            android:id="@+id/appLogogImageView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginTop="-50dp"
            android:gravity="center"
            android:orientation="vertical">

            <ImageView
                android:layout_width="72dp"
                android:layout_height="72dp"
                android:layout_gravity="center"
                android:src="@mipmap/ic_launcher_round" />

            <TextView
                android:id="@+id/appTextview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appLogogImageView"
                android:fontFamily="sans-serif-medium"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:text="Sharing is Caring"
                android:textSize="20.1sp"
                android:textStyle="normal"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/appTextview"
                android:fontFamily="sans-serif"
                android:gravity="center_horizontal"
                android:letterSpacing="-0.03"
                android:lineSpacingExtra="6sp"
                android:text="Share ContSync with your friends to get them onboard"
                android:textSize="14sp"
                android:textStyle="normal" />

        </LinearLayout>

    </RelativeLayout>
</RelativeLayout>

OUTPUT


问:
How to get real name from Google API via Node Client
My web app allows signing up / signing in with a Google account. I am using the following code to obtain user info from Google:

```<code>var scopes = ['profile', 'email'];
var url = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: scopes });

router.route('/authorize').post((req, res) => {
  code = req.body.code;
  oauth2Client.getToken(code, (err, tokens) => {
    if (err) return // error handler
    oauth2Client.verifyIdToken(tokens.id_token, clientId, (err, login) => {
      if (err) return // error handler
      console.log(login.getPayload()); // this gives me the JSON object below
    });
  });
});
</code>```

I've tried adding different scopes, but I always just get the same info, which doesn't include the user's real name:

```<code>{ azp: 'stuffblahblah',
  aud: 'stuffblahblah',
  sub: 'google-id-here',
  email: 'email@address.com',
  email_verified: true,
  at_hash: 'some-hash',
  iss: 'accounts.google.com',
  iat: 1234567890,
  exp: 1234567890 }
</code>```

答:
Despite some documentation suggesting it's possible to get info like real name in the id_token (see https://developers.google.com/identity/sign-in/android/backend-auth), I couldn't get it to return that info with the .getToken method. However, I was able to get it by requesting the info in a separate request via the access token:

```<code>let url = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=' + access_token;
request(url, (err, response, body) => {
  if (err) console.log('error');
  console.log(body);
});
</code>```

And the body looks like this:

```<code>{
  "sub": "4319874317893142",
  "name": "My Real name",
  "given_name": "My First Name",
  "family_name": "My Last Name",
  "profile": "https://plus.google.com/link_to_my_profile",
  "picture": "https://lh4.googleusercontent.com/link_to_my_pic.jpg",
  "email": "email@address.com",
  "email_verified": true,
  "gender": "male",
  "locale": "en"
}
</code>```

Still wishing there was a way to grab the real name in my initial request, rather than having to make a separate one, but this works well enough.

Body:
My web app allows signing up / signing in with a Google account. I am using the following code to obtain user info from Google:

var scopes = ['profile', 'email'];
var url = oauth2Client.generateAuthUrl({ access_type: 'offline', scope: scopes });

router.route('/authorize').post((req, res) => {
  code = req.body.code;
  oauth2Client.getToken(code, (err, tokens) => {
    if (err) return // error handler
    oauth2Client.verifyIdToken(tokens.id_token, clientId, (err, login) => {
      if (err) return // error handler
      console.log(login.getPayload()); // this gives me the JSON object below
    });
  });
});

I've tried adding different scopes, but I always just get the same info, which doesn't include the user's real name:

{ azp: 'stuffblahblah',
  aud: 'stuffblahblah',
  sub: 'google-id-here',
  email: 'email@address.com',
  email_verified: true,
  at_hash: 'some-hash',
  iss: 'accounts.google.com',
  iat: 1234567890,
  exp: 1234567890 }

Body:
Despite some documentation suggesting it's possible to get info like real name in the id_token (see https://developers.google.com/identity/sign-in/android/backend-auth), I couldn't get it to return that info with the .getToken method. However, I was able to get it by requesting the info in a separate request via the access token:

let url = 'https://www.googleapis.com/oauth2/v3/userinfo?access_token=' + access_token;
request(url, (err, response, body) => {
  if (err) console.log('error');
  console.log(body);
});

And the body looks like this:

{
  "sub": "4319874317893142",
  "name": "My Real name",
  "given_name": "My First Name",
  "family_name": "My Last Name",
  "profile": "https://plus.google.com/link_to_my_profile",
  "picture": "https://lh4.googleusercontent.com/link_to_my_pic.jpg",
  "email": "email@address.com",
  "email_verified": true,
  "gender": "male",
  "locale": "en"
}

Still wishing there was a way to grab the real name in my initial request, rather than having to make a separate one, but this works well enough.


问:
What is generateStubs configuration in Kotlin?
What is generateStubs for Kotlin? Here is my configuration in build.gradle.

I can not find it in public document here : http://kotlinlang.org/docs/reference/kapt.html

```<code>kapt {
  generateStubs = true
}
</code>```

If I'm using Java and Kotlin(1.2) in my project, it is still needed to add?

答:
EDIT:

If I'm using Java and Kotlin(1.2) in my project, it is still needed to
add

No, With the version 1.0.4 introduces a new experimental implementation of the annotation processing API. Now there is no need to configure this generateStubs in build.gradle.

Add the following to your build.gradle if you want to enable it:

```<code>apply plugin: 'kotlin-kapt'
</code>```

You will also have to remove the generateStubs config from build.gradle

But as your question about the Details on generateStubs I keep my old Post as it is.

Use :

Using kapt with: generatestubs = true, in order to use libraries like dagger 2 or dbflow,This will enable the compiler to generate stub classes required for interoperability between Java and Kotlin. Unless generateStubs = true is enabled, "bootstrap" (A custom annotation processor, which is passed to javac, loads the annotation data and calls other annotation processors.) Java code is required to reference generated sources.pulled that from

Note : Generated codes are always in Java not in Kotlin.

When to Include:

Generating stubs requires relatively much work, because all declarations must be resolved, and sometimes knowing return types requires analysis of expression (bodies of functions or property initializers after the = sign). So, using stubs in kapt slows your build down somewhat. That’s why stubs are off by default, and to enable them you need to write the following in your build.gradle file:

```<code>kapt {
  generateStubs = true
}
</code>```

How this works:

Stubs, compiler generated intermediate classes, allows "generated" sources to be referenced from Kotlin otherwise the compiler will not be able to reference the missing sources.

Generated source is created in "build/generated/source/kapt/main", as this is under "build", normally excluded from IntelliJ's project sources, this source root will be marked in the build script itself.

```<code>sourceSets {
  main.java.srcDirs += [file("$buildDir/generated/source/kapt/main")]
}
</code>```

Example :

Dagger2-example with Kotlin (1.1.50) annotation processor support Gradle build

Body:
What is generateStubs for Kotlin? Here is my configuration in build.gradle.

I can not find it in public document here : http://kotlinlang.org/docs/reference/kapt.html

kapt {
  generateStubs = true
}

If I'm using Java and Kotlin(1.2) in my project, it is still needed to add?

Body:
EDIT:

If I'm using Java and Kotlin(1.2) in my project, it is still needed to
add

No, With the version 1.0.4 introduces a new experimental implementation of the annotation processing API. Now there is no need to configure this generateStubs in build.gradle.

Add the following to your build.gradle if you want to enable it:

apply plugin: 'kotlin-kapt'

You will also have to remove the generateStubs config from build.gradle

But as your question about the Details on generateStubs I keep my old Post as it is.

Use :

Using kapt with: generatestubs = true, in order to use libraries like dagger 2 or dbflow,This will enable the compiler to generate stub classes required for interoperability between Java and Kotlin. Unless generateStubs = true is enabled, "bootstrap" (A custom annotation processor, which is passed to javac, loads the annotation data and calls other annotation processors.) Java code is required to reference generated sources.pulled that from

Note : Generated codes are always in Java not in Kotlin.

When to Include:

Generating stubs requires relatively much work, because all declarations must be resolved, and sometimes knowing return types requires analysis of expression (bodies of functions or property initializers after the = sign). So, using stubs in kapt slows your build down somewhat. That’s why stubs are off by default, and to enable them you need to write the following in your build.gradle file:

kapt {
  generateStubs = true
}

How this works:

Stubs, compiler generated intermediate classes, allows "generated" sources to be referenced from Kotlin otherwise the compiler will not be able to reference the missing sources.

Generated source is created in "build/generated/source/kapt/main", as this is under "build", normally excluded from IntelliJ's project sources, this source root will be marked in the build script itself.

sourceSets {
  main.java.srcDirs += [file("$buildDir/generated/source/kapt/main")]
}

Example :

Dagger2-example with Kotlin (1.1.50) annotation processor support Gradle build


问:
Desktop Windows Application automation using winium using c#
If multiple elements have got the same name and there is no unique id for elements?How do we proceed automation using winium ?

Is it possible to use clickable point coordinates for automation? If possible how to do it?

答: sometimes elements dont have unique ID available , but they have a unique automation ID which is helpful while automating the process


问:
visitnum for unscheduled visits
I am having the following data set: I am trying to assign the visit number for planned and unplanned visits according to the available date.If the date is different then I would like to increment the unplanned visit number (i.e:101.1,101.2). But if the date is same for unplanned visits then I would like to keep the constant visit number across the rows (i.e. 2 or more unplanned visits with same visit number i.e. 101.1,101.1).

```<code>    data test;
    infile cards dlm=" ";
    input subject visit event$11. date:date9.;
    format date date9.;
    cards;
    1 1  screening   10oct2017
    1 1  screening   10oct2017
    1 99 unscheduled 10oct2017
    1 99 unscheduled 11oct2017
    1 2  day-1       12oct2017
    1 2  day-1       12oct2017
    1 3  day1        16oct2017
    1 99 unscheduled 15oct2017
    ;
    run;
</code>```

I would like to assign the avisitn as follows:

```<code>    1 1  screening   10oct2017   101
    1 1  screening   10oct2017   101
    1 99 unscheduled 10oct2017   101.1
    1 99 unscheduled 11oct2017   101.2
    1 2  day-1       12oct2017   102
    1 2  day-1       12oct2017   102
    1 3  day1        16oct2017   103
    1 99 unscheduled 15oct2017   103.1
</code>```

I have tried to use the following code:

```<code>data test;
infile cards dlm=" ";
input subject visit event$11. date:date9.;
format date date9.;
cards;
1 1  screening   10oct2017
1 1  screening   10oct2017
1 99 unscheduled 10oct2017
1 99 unscheduled 11oct2017
1 2  day-1       12oct2017
1 2  day-1       12oct2017
1 3  day1        16oct2017
1 99 unscheduled 15oct2017
;
run;

proc sort data=test;
by subject date visit;
run;

data test1;
   set test;
   by subject date visit;

   fp = first.subject;
   lp = last.subject;
   fo = first.date;
   lo = last.date;
run;

data test2;
   set test1;
   by subject date visit;

   retain avisitn;

   prev_patient_num = lag(subject);
   prev_ordering_date = lag(date);

   if visit ne 99 then do;
       if first.subject then avisitn = 101;
       else if subject = prev_patient_num and date ne prev_ordering_date then avisitn + 1;
   end;

    if visit eq 99 then do;
        avisitn+0.1;
    end;

   keep subject date visit avisitn;
run;
</code>```

But, I am getting the following output

```<code>subject visit    date     avisitn
1        1     10OCT2017    101
1        1     10OCT2017    101
1       99     10OCT2017    101.1
1       99     11OCT2017    101.2
1       2      12OCT2017    102.2
1       2      12OCT2017    102.2
1      99      15OCT2017    102.3
1       3      16OCT2017    103.3
</code>```

Please help me to resolve this. Thanks in advance.

答:
In your try you sort by subject and date.  However, in the original sample, the last two lines are disordered in date.  The last two want values (103 and 103.1) are based on unsorted data.

For sorted data you can use FLOOR before advancing by 1 when the dates change.  Tracking for too many .1 increments is a good idea.

```<code>data want;
  set test;
  by subject date;

  retain avisitn;

  prev_date = lag(date);

  if first.subject then do;
    avisitn = 101;
    _99s = 0;
    if visit eq 99 then do; _99s + 1; avisitn + 0.1; end;
  end;
  else
  if visit eq 99 then do;
    _99s + 1;
    if _99s = 10 then do; put 'ERROR: Too many 99s' ; abort cancel; end;
    avisitn + 0.1;
  end;
  else
  if date ne prev_date then
    avisitn = floor(avisitn) + 1;

  drop prev_date;
run;
</code>```

If you need to process in the original order, say as in a transactional event logging order, there are solutions, however they might not be 'slick' and would require tracking states for 'weird' sequencing cases.

Title: visitnum for unscheduled visits

Body:
I am having the following data set: I am trying to assign the visit number for planned and unplanned visits according to the available date.If the date is different then I would like to increment the unplanned visit number (i.e:101.1,101.2). But if the date is same for unplanned visits then I would like to keep the constant visit number across the rows (i.e. 2 or more unplanned visits with same visit number i.e. 101.1,101.1).

    data test;
    infile cards dlm=" ";
    input subject visit event$11. date:date9.;
    format date date9.;
    cards;
    1 1  screening   10oct2017
    1 1  screening   10oct2017
    1 99 unscheduled 10oct2017
    1 99 unscheduled 11oct2017
    1 2  day-1       12oct2017
    1 2  day-1       12oct2017
    1 3  day1        16oct2017
    1 99 unscheduled 15oct2017
    ;
    run;

I would like to assign the avisitn as follows:

    1 1  screening   10oct2017   101
    1 1  screening   10oct2017   101
    1 99 unscheduled 10oct2017   101.1
    1 99 unscheduled 11oct2017   101.2
    1 2  day-1       12oct2017   102
    1 2  day-1       12oct2017   102
    1 3  day1        16oct2017   103
    1 99 unscheduled 15oct2017   103.1

I have tried to use the following code:

data test;
infile cards dlm=" ";
input subject visit event$11. date:date9.;
format date date9.;
cards;
1 1  screening   10oct2017
1 1  screening   10oct2017
1 99 unscheduled 10oct2017
1 99 unscheduled 11oct2017
1 2  day-1       12oct2017
1 2  day-1       12oct2017
1 3  day1        16oct2017
1 99 unscheduled 15oct2017
;
run;

proc sort data=test;
by subject date visit;
run;

data test1;
   set test;
   by subject date visit;

   fp = first.subject;
   lp = last.subject;
   fo = first.date;
   lo = last.date;
run;

data test2;
   set test1;
   by subject date visit;

   retain avisitn;

   prev_patient_num = lag(subject);
   prev_ordering_date = lag(date);

   if visit ne 99 then do;
       if first.subject then avisitn = 101;
       else if subject = prev_patient_num and date ne prev_ordering_date then avisitn + 1;
   end;

    if visit eq 99 then do;
        avisitn+0.1;
    end;

   keep subject date visit avisitn;
run;

But, I am getting the following output

subject visit    date     avisitn
1        1     10OCT2017    101
1        1     10OCT2017    101
1       99     10OCT2017    101.1
1       99     11OCT2017    101.2
1       2      12OCT2017    102.2
1       2      12OCT2017    102.2
1      99      15OCT2017    102.3
1       3      16OCT2017    103.3

Please help me to resolve this. Thanks in advance.

Body:
In your try you sort by subject and date.  However, in the original sample, the last two lines are disordered in date.  The last two want values (103 and 103.1) are based on unsorted data.

For sorted data you can use FLOOR before advancing by 1 when the dates change.  Tracking for too many .1 increments is a good idea.

data want;
  set test;
  by subject date;

  retain avisitn;

  prev_date = lag(date);

  if first.subject then do;
    avisitn = 101;
    _99s = 0;
    if visit eq 99 then do; _99s + 1; avisitn + 0.1; end;
  end;
  else
  if visit eq 99 then do;
    _99s + 1;
    if _99s = 10 then do; put 'ERROR: Too many 99s' ; abort cancel; end;
    avisitn + 0.1;
  end;
  else
  if date ne prev_date then
    avisitn = floor(avisitn) + 1;

  drop prev_date;
run;

If you need to process in the original order, say as in a transactional event logging order, there are solutions, however they might not be 'slick' and would require tracking states for 'weird' sequencing cases.


问:
compare date with datetime in FilterExpression
```<code><asp:TextBox ID="date_tb" runat="server" TextMode="Date"></asp:TextBox>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT * FROM [table_1] WHERE [type]='AAA'" FilterExpression="[ScheduledDateTime] = #{0}#">

<asp:ControlParameter Name="ScheduledDateTime" ControlID="date_tb" PropertyName="Text" type="DateTime"/>
</code>```

ScheduledDateTime column is of datetime type.

date_tb textbox only has date.

How do I compared the two of them?

Please note that CAST() does not work in FilterExpression

and CONVERT() in sql server is different from CONVERT() in FilterExpression.

I tried using FilterExpression="[ScheduledDateTime] <= #{0}# AND [ScheduledDateTime] >= #{0}#"" but it did not return any result.

答:
Please try
FilterExpression="[ScheduledDateTime] <= #{0}# AND [ScheduledDateTime] >= #{0}+1#""
The results are not returned because of time part in datetime

Body:
<asp:TextBox ID="date_tb" runat="server" TextMode="Date"></asp:TextBox>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>" SelectCommand="SELECT * FROM [table_1] WHERE [type]='AAA'" FilterExpression="[ScheduledDateTime] = #{0}#">

<asp:ControlParameter Name="ScheduledDateTime" ControlID="date_tb" PropertyName="Text" type="DateTime"/>

ScheduledDateTime column is of datetime type.

date_tb textbox only has date.

How do I compared the two of them?

Please note that CAST() does not work in FilterExpression

and CONVERT() in sql server is different from CONVERT() in FilterExpression.

I tried using FilterExpression="[ScheduledDateTime] <= #{0}# AND [ScheduledDateTime] >= #{0}#"" but it did not return any result.


问:
Vue.js client-side hydration works in development but fails in production
I decided to build my own Vue SSR template that I could use for my projects. It's partially based on this example. Everything was fine and worked as expected. And it still does on the dev-server) But when I'd built the app for production I suddenly discovered that it was totally dead. I got no errors, no warnings, no other signs that could point out the direction where I should search for the answers whatsoever... And it's just blowing my mind!

The app works perfectly on dev-server but in production, it appears to be totally dead as client-side hydration somehow fails.

I'm not sure what it is really... Or maybe I'm just stupid enough to miss something very simple here. I just don't know. I spent so much time trying to solve this... But found nothing, and I feel pretty helpless. So any help would be appreciated!

答:
Found it! It was so simple that it’s actually very funny.

That’s what will happen if you accidentally define a wrong entry point for your client bundle in webpack config.

So be aware!
Hopefully, it would save some time for someone)


问:
Python Convert string to dict
I have a string :

```<code>'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
</code>```

and would like to convert it to

```<code>{
  "tomatoes" : "5" ,
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}
</code>```

Any ideas ?

答:
The problem with your input string is that it's actually not a valid JSON because your keys are not declared as strings, otherwise you could just use the json module to load it and be done with it.

A simple and dirty way to get what you want is to first turn it into a valid JSON by adding quotation marks around everything that's not a whitespace or a syntax character:

```<code>source = '{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'

output = ""
quoting = False
for char in source:
    if char.isalnum():
        if not quoting:
            output += '"'
            quoting = True
    elif quoting:
        output += '"'
        quoting = False
    output += char

print(output)  #  {"tomatoes" : "5" , "livestock" :{"cow" : "5" , "sheep" :"2" }}
</code>```

This gives you a valid JSON so now you can easily parse it to a Python dict using the json module:

```<code>import json

parsed = json.loads(output)
# {'livestock': {'sheep': '2', 'cow': '5'}, 'tomatoes': '5'}
</code>```

Title: Python Convert string to dict

Body:
I have a string :

'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'

and would like to convert it to

{
  "tomatoes" : "5" ,
  "livestock" :"{"cow" : "5" , "sheep" :"2" }"
}

Any ideas ?

Body:
The problem with your input string is that it's actually not a valid JSON because your keys are not declared as strings, otherwise you could just use the json module to load it and be done with it.

A simple and dirty way to get what you want is to first turn it into a valid JSON by adding quotation marks around everything that's not a whitespace or a syntax character:

source = '{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'

output = ""
quoting = False
for char in source:
    if char.isalnum():
        if not quoting:
            output += '"'
            quoting = True
    elif quoting:
        output += '"'
        quoting = False
    output += char

print(output)  #  {"tomatoes" : "5" , "livestock" :{"cow" : "5" , "sheep" :"2" }}

This gives you a valid JSON so now you can easily parse it to a Python dict using the json module:

import json

parsed = json.loads(output)
# {'livestock': {'sheep': '2', 'cow': '5'}, 'tomatoes': '5'}


问:
How can you pass a function as a template parmater where the function return is same as the template parameter?
I am trying to figure out how I can make a template class that works like the following:

```<code>template<typename T, typename Fn>
class Point
{
public:
    T x;
    T y;

    void pt(const std::string& x_str, const std::string& y_str)
    {
          x = Fn(x_str);
          y = Fn(y_str);
    }
    .... more Point stuff ....
};

typedef Point<float, std::stof> FPoint;
typedef Point<int, std::stoi> IPoint;
.....
</code>```

and then when I read a string - say "100.25,200.25", I could split on "," (which I actually have figured out how to do, and then say, set that point:

```<code>FPoint a;
a.pt("100.25","200.25")
</code>```

so far I have tried defining directly as I have above, I have tried:

```<code>template<typename T, T (C*)(const std::string&)>
.....
</code>```

and

```<code>template<typename T, T Fn(const std::string&)>
......
</code>```

and then doing:
    typedef Point FloatPoint;

and I get various errors like  cannot convert from 'overloaded-function' to 'float (__cdecl *)(const std::string &)'or 'std::stof' is not a valid template type argument for parameter 'convert_func' depending on how I try to define the parameter.  Any hints - nothing I have googled has seemed to help.

Thanks!

答:
You cannot use

```<code>typedef Point<float, std::stof> FPoint;
</code>```

since std::stof is a pointer to a function, not a type.

You could try changing the template parameter to a non-type parameter, such as:

```<code>template<typename T, T(*Fn)(const std::string&)>
class Point { ... };
</code>```

but that won't work since std::stof has an optional parameter of type std::size_t*. The type of std::stof, that takes a std::string const& as the first parameter is float (*)(std::string const&, std::size_t*).

If you try to shoehorn Point to match that declaration,

```<code>template<typename T, T(*Fn)(const std::string&, std::size_t*)>
class Point { ... };
</code>```

you won't be able to use:

```<code>typedef Point<int, std::stoi> IPoint;
</code>```

since std::stoi has a third parameter, int base. The type of std::stoi is int (*)(std::string const&, std::size_t*, int).

I think your best option is to create two wrapper functions in your namespace and use them instead of using std::stof and std::stoi directly as template parameters.

The following demonstrative program works in my setup.

```<code>#include <cstdlib>
#include <string>
#include <functional>

template<typename T, T(*Fn)(const std::string&)>
class Point
{
public:
    T x;
    T y;

    void pt(const std::string& x_str, const std::string& y_str)
    {
       x = Fn(x_str);
       y = Fn(y_str);
    }
};

namespace MyApp
{
   float stof(std::string const& in)
   {
      return std::stof(in);
   }

   int stoi(std::string const& in)
   {
      return std::stoi(in);
   }
}

typedef Point<float, MyApp::stof> FPoint;
typedef Point<int, MyApp::stoi> IPoint;

int main()
{
   FPoint a;
   a.pt("100.25", "200.25");
   IPoint b;
   b.pt("100", "200");
}
</code>```

Body:
I am trying to figure out how I can make a template class that works like the following:

template<typename T, typename Fn>
class Point
{
public:
    T x;
    T y;

    void pt(const std::string& x_str, const std::string& y_str)
    {
          x = Fn(x_str);
          y = Fn(y_str);
    }
    .... more Point stuff ....
};

typedef Point<float, std::stof> FPoint;
typedef Point<int, std::stoi> IPoint;
.....

and then when I read a string - say "100.25,200.25", I could split on "," (which I actually have figured out how to do, and then say, set that point:

FPoint a;
a.pt("100.25","200.25")

so far I have tried defining directly as I have above, I have tried:

template<typename T, T (C*)(const std::string&)>
.....

and

template<typename T, T Fn(const std::string&)>
......

and then doing:
    typedef Point FloatPoint;

and I get various errors like  cannot convert from 'overloaded-function' to 'float (__cdecl *)(const std::string &)'or 'std::stof' is not a valid template type argument for parameter 'convert_func' depending on how I try to define the parameter.  Any hints - nothing I have googled has seemed to help.

Thanks!

Body:
You cannot use

typedef Point<float, std::stof> FPoint;

since std::stof is a pointer to a function, not a type.

You could try changing the template parameter to a non-type parameter, such as:

template<typename T, T(*Fn)(const std::string&)>
class Point { ... };

but that won't work since std::stof has an optional parameter of type std::size_t*. The type of std::stof, that takes a std::string const& as the first parameter is float (*)(std::string const&, std::size_t*).

If you try to shoehorn Point to match that declaration,

template<typename T, T(*Fn)(const std::string&, std::size_t*)>
class Point { ... };

you won't be able to use:

typedef Point<int, std::stoi> IPoint;

since std::stoi has a third parameter, int base. The type of std::stoi is int (*)(std::string const&, std::size_t*, int).

I think your best option is to create two wrapper functions in your namespace and use them instead of using std::stof and std::stoi directly as template parameters.

The following demonstrative program works in my setup.

#include <cstdlib>
#include <string>
#include <functional>

template<typename T, T(*Fn)(const std::string&)>
class Point
{
public:
    T x;
    T y;

    void pt(const std::string& x_str, const std::string& y_str)
    {
       x = Fn(x_str);
       y = Fn(y_str);
    }
};

namespace MyApp
{
   float stof(std::string const& in)
   {
      return std::stof(in);
   }

   int stoi(std::string const& in)
   {
      return std::stoi(in);
   }
}

typedef Point<float, MyApp::stof> FPoint;
typedef Point<int, MyApp::stoi> IPoint;

int main()
{
   FPoint a;
   a.pt("100.25", "200.25");
   IPoint b;
   b.pt("100", "200");
}


问:
Maven - exception during project building
When I'm trying to build project I get exception:

Downloading:
  http://repo.maven.apache.org/maven2/log4j/log4j/1.2.14/log4j-1.2.14.jar
  Nov 4, 2012 5:47:16 PM
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector
  tryExecute INFO: I/O exception (java.net.SocketException) caught when
  processing request: Connection reset Nov 4, 2012 5:47:16 PM
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector
  tryExecute INFO: Retrying request Nov 4, 2012 5:48:16 PM
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector
  tryExecute INFO: I/O exception (java.net.SocketException) caught when
  processing request: Connection reset Nov 4, 2012 5:48:16 PM
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector
  tryExecute INFO: Retrying request Nov 4, 2012 5:49:17 PM
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector
  tryExecute INFO: I/O exception (java.net.SocketException) caught when
  processing request: Connection reset Nov 4, 2012 5:49:17 PM
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector
  tryExecute INFO: Retrying request [DEBUG] Writing resolution tracking
  file
  /root/.m2/repository/log4j/log4j/1.2.14/log4j-1.2.14.jar.lastUpdated
  [INFO]
  ------------------------------------------------------------------------ [INFO] BUILD FAILURE [INFO]
  ------------------------------------------------------------------------ [INFO] Total time: 4:03.016s [INFO] Finished at: Sun Nov 04 17:50:17
  CET 2012 [INFO] Final Memory: 5M/15M [INFO]
  ------------------------------------------------------------------------ [ERROR] Failed to execute goal on project
  jboss-ejb3-examples-ch04-firstejb: Could not resolve dependencies for
  project
  org.jboss.ejb3.examples:jboss-ejb3-examples-ch04-firstejb:jar:1.0.0-cr-1:
  Could not transfer artifact log4j:log4j:jar:1.2.14 from/to central
  (http://repo.maven.apache.org/maven2): Connection reset -> [Help 1]
  org.apache.maven.lifecycle.LifecycleExecutionException: Failed to
  execute goal on project jboss-ejb3-examples-ch04-firstejb: Could not
  resolve dependencies for project
  org.jboss.ejb3.examples:jboss-ejb3-examples-ch04-firstejb:jar:1.0.0-cr-1:
  Could not transfer artifact log4j:log4j:jar:1.2.14 from/to central
  (http://repo.maven.apache.org/maven2): Connection reset   at
  org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:210)
    at
  org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.resolveProjectDependencies(LifecycleDependencyResolver.java:117)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.ensureDependenciesAreResolved(MojoExecutor.java:258)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:201)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at
  org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at
  org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at
  org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at
  org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at
  org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)   at
  org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)  at
  org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)  at
  org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)   at
  org.apache.maven.cli.MavenCli.main(MavenCli.java:141)     at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)   at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)     at
  org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at
  org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at
  org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at
  org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)
  Caused by: org.apache.maven.project.DependencyResolutionException:
  Could not resolve dependencies for project
  org.jboss.ejb3.examples:jboss-ejb3-examples-ch04-firstejb:jar:1.0.0-cr-1:
  Could not transfer artifact log4j:log4j:jar:1.2.14 from/to central
  (http://repo.maven.apache.org/maven2): Connection reset   at
  org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:189)
    at
  org.apache.maven.lifecycle.internal.LifecycleDependencyResolver.getDependencies(LifecycleDependencyResolver.java:185)
    ... 22 more Caused by:
  org.sonatype.aether.resolution.DependencyResolutionException: Could
  not transfer artifact log4j:log4j:jar:1.2.14 from/to central
  (http://repo.maven.apache.org/maven2): Connection reset   at
  org.sonatype.aether.impl.internal.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:375)
    at
  org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:183)
    ... 23 more Caused by:
  org.sonatype.aether.resolution.ArtifactResolutionException: Could not
  transfer artifact log4j:log4j:jar:1.2.14 from/to central
  (http://repo.maven.apache.org/maven2): Connection reset   at
  org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:538)
    at
  org.sonatype.aether.impl.internal.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:216)
    at
  org.sonatype.aether.impl.internal.DefaultRepositorySystem.resolveDependencies(DefaultRepositorySystem.java:358)
    ... 24 more Caused by:
  org.sonatype.aether.transfer.ArtifactTransferException: Could not
  transfer artifact log4j:log4j:jar:1.2.14 from/to central
  (http://repo.maven.apache.org/maven2): Connection reset   at
  org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(WagonRepositoryConnector.java:951)
    at
  org.sonatype.aether.connector.wagon.WagonRepositoryConnector$4.wrap(WagonRepositoryConnector.java:939)
    at
  org.sonatype.aether.connector.wagon.WagonRepositoryConnector$GetTask.run(WagonRepositoryConnector.java:669)
    at
  org.sonatype.aether.util.concurrency.RunnableErrorForwarder$1.run(RunnableErrorForwarder.java:60)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662) Caused by:
  org.apache.maven.wagon.TransferFailedException: Connection reset  at
  org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.fillInputData(AbstractHttpClientWagon.java:799)
    at
  org.apache.maven.wagon.StreamWagon.getInputStream(StreamWagon.java:116)
    at org.apache.maven.wagon.StreamWagon.getIfNewer(StreamWagon.java:88)
    at org.apache.maven.wagon.StreamWagon.get(StreamWagon.java:61)  at
  org.sonatype.aether.connector.wagon.WagonRepositoryConnector$GetTask.run(WagonRepositoryConnector.java:601)
    ... 4 more Caused by: java.net.SocketException: Connection reset    at
  java.net.SocketInputStream.read(SocketInputStream.java:168)   at
  org.apache.maven.wagon.providers.http.httpclient.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:149)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.io.SocketInputBuffer.fillBuffer(SocketInputBuffer.java:111)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:264)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:98)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:252)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:282)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:247)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:219)
    at
  org.apache.maven.wagon.providers.http.httpclient.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:298)
    at
  org.apache.maven.wagon.providers.http.httpclient.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:633)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:454)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at
  org.apache.maven.wagon.providers.http.httpclient.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at
  org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.execute(AbstractHttpClientWagon.java:674)
    at
  org.apache.maven.wagon.shared.http4.AbstractHttpClientWagon.fillInputData(AbstractHttpClientWagon.java:793)
    ... 8 more [ERROR]  [ERROR]  [ERROR] For more information about the
  errors and possible solutions, please read the following articles:
  [ERROR] [Help 1]
  http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

What is the problem? I think pom and other things are ok as it is example from book, so it should build.

答:
Adding a web proxy entry/declaration to Maven /.m2/settings.xml">settings.xml as described in their documentation resolved the ERROR messages if the current system is behind a web proxy.

Hope it helps!

Body:
Adding a web proxy entry/declaration to Maven settings.xml as described in their documentation resolved the ERROR messages if the current system is behind a web proxy.

Hope it helps!


问:
RecyclerView item background alternating color out of order
I want change my RecyclerView item background with alternating color.

Here is the method in Adapter.

```<code>public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<NewsModel> mNewsList;

class ViewHolder extends RecyclerView.ViewHolder {
    TextView newsNameText;
    TextView newsDataText;
    View listView;
    public ViewHolder(View newsView) {
        super(newsView);
        newsNameText = (TextView) newsView.findViewById(R.id.news_Name);
        newsDataText = (TextView) newsView.findViewById(R.id.news_Data);
        listView = newsView;
    }
}
public NewsAdapter(List<NewsModel> newsList) {
    mNewsList = newsList;
}
@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    return holder;
}
public void setData(List<NewsModel> viewData) {
    mNewsList.clear();
    mNewsList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    NewsModel news = mNewsList.get(position);
    holder.setIsRecyclable(true);
    if(position % 2 == 0){
        holder.listView.setBackgroundColor(0x80E0EEEE);
    }
    holder.newsNameText.setText(news.getName());
    holder.newsDataText.setText(news.getData());
}
@Override
public int getItemCount() {
    return mNewsList.size();
}
</code>```

}

The problem is when I touch the screen and swipe down to see more item, the item background color become out of order. It is not alternating.

Am I wrong in using this method?

Thanks!

答:
It is because RecyclerView recycles your old views to create new views. When you scroll down the old views are used to create the new ones,since the backgound colour of these old views was already set when onBindViewHolder was called, you have to specify the else condition in onBindViewHolder which will change the colour and maintain the alternating colour order. Change your onBindViewHolder code to this:

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    NewsModel news = mNewsList.get(position);
    holder.setIsRecyclable(true);
    if(position % 2 == 0){
        holder.listView.setBackgroundColor(0x80E0EEEE);
    }else{
        holder.listview.setBackgroundColor(#FFFFFF);
    }
    holder.newsNameText.setText(news.getName());
    holder.newsDataText.setText(news.getData());
}
</code>```

Body:
I want change my RecyclerView item background with alternating color.

Here is the method in Adapter.

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
private List<NewsModel> mNewsList;

class ViewHolder extends RecyclerView.ViewHolder {
    TextView newsNameText;
    TextView newsDataText;
    View listView;
    public ViewHolder(View newsView) {
        super(newsView);
        newsNameText = (TextView) newsView.findViewById(R.id.news_Name);
        newsDataText = (TextView) newsView.findViewById(R.id.news_Data);
        listView = newsView;
    }
}
public NewsAdapter(List<NewsModel> newsList) {
    mNewsList = newsList;
}
@Override
public  ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    return holder;
}
public void setData(List<NewsModel> viewData) {
    mNewsList.clear();
    mNewsList.addAll(viewData);
    notifyDataSetChanged();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    NewsModel news = mNewsList.get(position);
    holder.setIsRecyclable(true);
    if(position % 2 == 0){
        holder.listView.setBackgroundColor(0x80E0EEEE);
    }
    holder.newsNameText.setText(news.getName());
    holder.newsDataText.setText(news.getData());
}
@Override
public int getItemCount() {
    return mNewsList.size();
}

}

The problem is when I touch the screen and swipe down to see more item, the item background color become out of order. It is not alternating.

Am I wrong in using this method?

Thanks!

Body:
It is because RecyclerView recycles your old views to create new views. When you scroll down the old views are used to create the new ones,since the backgound colour of these old views was already set when onBindViewHolder was called, you have to specify the else condition in onBindViewHolder which will change the colour and maintain the alternating colour order. Change your onBindViewHolder code to this:

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    NewsModel news = mNewsList.get(position);
    holder.setIsRecyclable(true);
    if(position % 2 == 0){
        holder.listView.setBackgroundColor(0x80E0EEEE);
    }else{
        holder.listview.setBackgroundColor(#FFFFFF);
    }
    holder.newsNameText.setText(news.getName());
    holder.newsDataText.setText(news.getData());
}


问:
Not able to resolve error in pom.xml
```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>Sniip</groupId>
    <artifactId>Sniip</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <resources>
            <resource>
                <directory>src</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>
        <dependencies> //Throws an error right here
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>3.5.0</version>
            </dependency>
            <dependency>
                <groupId>io.appium</groupId>
                <artifactId>java-client</artifactId>
                <version>5.0.3</version>
            </dependency>
            <dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>6.11.0.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-server</artifactId>
                <version>3.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>42.0.0</version>
            </dependency>
        </dependencies>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

I am adding dependencies in pom.xml, but throws an error saying : Invalid content was found starting with the element "dependencies". Not sure if there is any restructuring required?
I want to get my automated tests running on CI pipeline and this is one step i need to accomplish but not able to proceed .
Can anyone help me?

Thanks.

答:
Vadim had commented the right thing asking you to remove dependencies outside your build.

In a regular maven POM this is how the structure exists

```<code>    <project>
        <modelVersion>X.x.x</modelVersion>
        <groupId>xxx.xxx.xxx</groupId>
        <artifactId>xxxx</artifactId>
        <packaging>war/jar...</packaging>
        <version>1.0.0-SNAPSHOT</version>
        <name>xxxx</name>
        <properties></properties>
        <parent></parent>
        <profiles></profiles>
        <dependencies>
            <dependency1></dependency1>
        </dependencies>
   </project>
</code>```

Get the POM in a proper structure. If you still get a dependency related error, then it can be because

You are inside an org network, and the org artifactory/nexus or any other repo manager does not have the dependecy.

The dependency has some typo or version conflict.

Resolve them and see if you can proceed.

Title: Not able to resolve error in pom.xml

Body:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>Sniip</groupId>
    <artifactId>Sniip</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <resources>
            <resource>
                <directory>src</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
        </resources>
        <dependencies> //Throws an error right here
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-java</artifactId>
                <version>3.5.0</version>
            </dependency>
            <dependency>
                <groupId>io.appium</groupId>
                <artifactId>java-client</artifactId>
                <version>5.0.3</version>
            </dependency>
            <dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>6.11.0.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-server</artifactId>
                <version>3.5.2</version>
            </dependency>
            <dependency>
                <groupId>org.postgresql</groupId>
                <artifactId>postgresql</artifactId>
                <version>42.0.0</version>
            </dependency>
        </dependencies>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

I am adding dependencies in pom.xml, but throws an error saying : Invalid content was found starting with the element "dependencies". Not sure if there is any restructuring required?
I want to get my automated tests running on CI pipeline and this is one step i need to accomplish but not able to proceed .
Can anyone help me?

Thanks.

Body:
Vadim had commented the right thing asking you to remove dependencies outside your build.

In a regular maven POM this is how the structure exists

    <project>
        <modelVersion>X.x.x</modelVersion>
        <groupId>xxx.xxx.xxx</groupId>
        <artifactId>xxxx</artifactId>
        <packaging>war/jar...</packaging>
        <version>1.0.0-SNAPSHOT</version>
        <name>xxxx</name>
        <properties></properties>
        <parent></parent>
        <profiles></profiles>
        <dependencies>
            <dependency1></dependency1>
        </dependencies>
   </project>

Get the POM in a proper structure. If you still get a dependency related error, then it can be because

You are inside an org network, and the org artifactory/nexus or any other repo manager does not have the dependecy.

The dependency has some typo or version conflict.

Resolve them and see if you can proceed.


问:
Combining Firebase Auth with Firebase Realtime Database or Google Cloud Datastore?
I'm planning a web application that requires user auth, plus the ability to display data for the users that is stored in a database. No interaction between the users is needed (yet), however the users should be able create objects and query their "own" objects. For example I list 10 book names (10 book objects), and User A should be able to pick a book and create a new object, call it userNoteObject that contains the name of a choosen book and a short note (that he/she writes).

With a basic pseudo code one book object would look like this:

```<code>bookObj = {"id": 1, "name": "book name"}
</code>```

And the user's note object would be something like this:

```<code>userNoteObject = {
             "id": 1,
             "book_name": "random book name",
             "owner_userid": "a1b2c3d",
             "note": "some random string"
                  }
</code>```

With MySQL I would create three tables, one for the users and one for the userNoteObject-s and another for the bookObj-s. Everytime an user saves a note, I would add it to the table that lists the saved notes. Then I can simply query the notes that belongs to X user based on the user's owner_userid. It's a quite simple functionality.

After reading about the possibilities I've made a decision to go with Firebase Auth (because in the future I might need Android and iOS compatibility) + Google Cloud Datastore or Firebase Realtime Database. However I'm a little bit scared about the Realtime Database of Firebase since I've never worked any DB like it. I also like to be able to modify records manually with something like PhpMyAdmin and I assume Cloud Datastore has a visual interface like that.

I'm familiar with JSON handling and creating JSON files, however the JSON based database is strange for me at the moment. Therefore I'm thinking about that maybe the other option would be a better choice. It's very important that I don't need realtime db features. I would load X number of entries into the table that holds the bookObj-s and sometimes update them. I assume when the user creates an userNoteObject it would be saved quickly with both and after deleting an userNoteObject I could refresh the page close to realtime with Datastore. But the table that holds the book objects must be able to store millions of entries easily.

So the important things:

One db table should be able to handle millions of records easily

Easy as possible querying

Visual interface for the DB (if it's possible)

I don't need realtime features like dynamic game score display/saving

Other info:

I would like to use Angular.js

I'm familiar with Python if it can help in something

So my question is that which database would be better for my needs? At the moment I say Datastore, but I'm totally new with these services so I'm not really against the Realtime Database, but Datastore looks more suitable since it has a visual interface. However I'm also not sure that how would work Datastore with Firebase. If there is a third option like combining both, Realtime Database for the objects save by the user and the static objects for Datastore for example, I would love to hear about it too. My overall goal is to be able to write and query the db easy and fast as it's possible and easily use it with Firebase auth.

UPDATE: I just discovered Firebase's Cloud Firestore, so if it can be more useful I could use it.

答: For the Firestore console/UI, see https://firebase.google.com/docs/firestore/using-console. Is that the kind of thing you're looking for?</p>

Body:
I'm planning a web application that requires user auth, plus the ability to display data for the users that is stored in a database. No interaction between the users is needed (yet), however the users should be able create objects and query their "own" objects. For example I list 10 book names (10 book objects), and User A should be able to pick a book and create a new object, call it userNoteObject that contains the name of a choosen book and a short note (that he/she writes).

With a basic pseudo code one book object would look like this:

bookObj = {"id": 1, "name": "book name"}

And the user's note object would be something like this:

userNoteObject = {
             "id": 1,
             "book_name": "random book name",
             "owner_userid": "a1b2c3d",
             "note": "some random string"
                  }

With MySQL I would create three tables, one for the users and one for the userNoteObject-s and another for the bookObj-s. Everytime an user saves a note, I would add it to the table that lists the saved notes. Then I can simply query the notes that belongs to X user based on the user's owner_userid. It's a quite simple functionality.

After reading about the possibilities I've made a decision to go with Firebase Auth (because in the future I might need Android and iOS compatibility) + Google Cloud Datastore or Firebase Realtime Database. However I'm a little bit scared about the Realtime Database of Firebase since I've never worked any DB like it. I also like to be able to modify records manually with something like PhpMyAdmin and I assume Cloud Datastore has a visual interface like that.

I'm familiar with JSON handling and creating JSON files, however the JSON based database is strange for me at the moment. Therefore I'm thinking about that maybe the other option would be a better choice. It's very important that I don't need realtime db features. I would load X number of entries into the table that holds the bookObj-s and sometimes update them. I assume when the user creates an userNoteObject it would be saved quickly with both and after deleting an userNoteObject I could refresh the page close to realtime with Datastore. But the table that holds the book objects must be able to store millions of entries easily.

So the important things:

One db table should be able to handle millions of records easily

Easy as possible querying

Visual interface for the DB (if it's possible)

I don't need realtime features like dynamic game score display/saving

Other info:

I would like to use Angular.js

I'm familiar with Python if it can help in something

So my question is that which database would be better for my needs? At the moment I say Datastore, but I'm totally new with these services so I'm not really against the Realtime Database, but Datastore looks more suitable since it has a visual interface. However I'm also not sure that how would work Datastore with Firebase. If there is a third option like combining both, Realtime Database for the objects save by the user and the static objects for Datastore for example, I would love to hear about it too. My overall goal is to be able to write and query the db easy and fast as it's possible and easily use it with Firebase auth.

UPDATE: I just discovered Firebase's Cloud Firestore, so if it can be more useful I could use it.


问:
Is there a way to make npm install (the command) to work behind proxy?
Read about a proxy variable in a .npmrc file but it does not work. Trying to avoid manually downloading all require packages and installing.

答:
After tying different answers finally, @Kayvar answers's first four lines help me to solve the issue:</p>

```<code>npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set https-proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set strict-ssl false
</code>```

Body:
After tying different answers finally, @Kayvar answers's first four lines help me to solve the issue:

npm config set registry http://registry.npmjs.org/
npm config set proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set https-proxy http://myusername:mypassword@proxy.us.somecompany:8080
npm config set strict-ssl false


问:
UIView with shadow and masked layer
So I have an UIView (called myView) with some mask applied to it.

```<code>let maskPath = UIBezierPath(roundedRect: myView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 12, height: 12))
let maskLayer = CAShapeLayer()
maskLayer.frame = myView.bounds
maskLayer.path = maskPath.cgPath
myView.layer.mask = maskLayer
</code>```

Which layout this way:

What I am failing to do is add some shadow to myView. Since the view's layer have a mask, I am not able to add differents layers to it with shadow.

Does anyone ever had this problem?

答:
set your image color to clear and to the following:</p>

```<code>let maskPath = UIBezierPath(roundedRect: redView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 12, height: 12))
        let maskLayer = CAShapeLayer()[![enter image description here][1]][1]
        maskLayer.fillColor = UIColor.red.cgColor // your color
        maskLayer.frame = redView.bounds
        maskLayer.path = maskPath.cgPath

        redView.layer.addSublayer(maskLayer)

        redView.layer.shadowOffset = CGSize(width: 10, height: 10)
        redView.layer.shadowColor = UIColor.green.cgColor
        redView.layer.shadowOpacity = 1
</code>```

Title: UIView with shadow and masked layer

Body:
So I have an UIView (called myView) with some mask applied to it.

let maskPath = UIBezierPath(roundedRect: myView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 12, height: 12))
let maskLayer = CAShapeLayer()
maskLayer.frame = myView.bounds
maskLayer.path = maskPath.cgPath
myView.layer.mask = maskLayer

Which layout this way:

What I am failing to do is add some shadow to myView. Since the view's layer have a mask, I am not able to add differents layers to it with shadow.

Does anyone ever had this problem?

Body:
set your image color to clear and to the following:

let maskPath = UIBezierPath(roundedRect: redView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 12, height: 12))
        let maskLayer = CAShapeLayer()[![enter image description here][1]][1]
        maskLayer.fillColor = UIColor.red.cgColor // your color
        maskLayer.frame = redView.bounds
        maskLayer.path = maskPath.cgPath

        redView.layer.addSublayer(maskLayer)

        redView.layer.shadowOffset = CGSize(width: 10, height: 10)
        redView.layer.shadowColor = UIColor.green.cgColor
        redView.layer.shadowOpacity = 1