问:
How to use shared preference to checkbox - Android Studio
I created a login page that connects to a mysql database.
In the activity_user_login.xml I entered 2 editText for email and password and a login Botton, I added a checkbox for the saved data.
I would like to save email and password.

However, I can not add the sharedPreference.
Below the full code.. You can help me? Thank you

activity_user_login.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.UserLoginActivity"
    android:background="#FF5722"
    android:padding="20dp">

    <TextView
        android:text="User Login Form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/email"
        android:hint="Enter Your Email Here"
        android:gravity="center"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_below="@+id/email"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/password"
        android:hint="Enter Your Password Here"
        android:gravity="center"/>

    <Button
        android:text="Log In Here"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/Login" />

    <CheckBox
        android:id="@+id/saveLoginCheckBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextPassword"
        android:text="Save Login?"
        android:textColor="#FFF" />

</RelativeLayout>
</code>```

UserLoginActivity.java

```<code>package com.myapp.myappcode;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;

public class UserLoginActivity extends AppCompatActivity {

    EditText Email, Password;
    Button LogIn ;
    String PasswordHolder, EmailHolder;
    String finalResult ;
    String HttpURL = "http://mysite/User/UserLogin.php";
    Boolean CheckEditText ;
    ProgressDialog progressDialog;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    public static final String UserEmail = "";

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

        Email = (EditText)findViewById(R.id.email);
        Password = (EditText)findViewById(R.id.password);
        LogIn = (Button)findViewById(R.id.Login);

        LogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    UserLoginFunction(EmailHolder, PasswordHolder);

                }
                else {

                    Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });
    }
    public void CheckEditTextIsEmptyOrNot(){

        EmailHolder = Email.getText().toString();
        PasswordHolder = Password.getText().toString();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {
            CheckEditText = false;
        }
        else {

            CheckEditText = true ;
        }
    }

    public void UserLoginFunction(final String email, final String password){

        class UserLoginClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                if(httpResponseMsg.equalsIgnoreCase("Data Matched")){

                    finish();

                    Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class);

                    intent.putExtra(UserEmail,email);

                    startActivity(intent);

                }
                else{

                    Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
                }

            }

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

                hashMap.put("email",params[0]);

                hashMap.put("password",params[1]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        UserLoginClass userLoginClass = new UserLoginClass();

        userLoginClass.execute(email,password);
    }

}
</code>```

答:
```<code>  sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();

// get e mail and pass on button click and save it like this
            editor.putString(pass, ps);
            editor.putString(Email, e);
            editor.commit();
</code>```

and to get it back:

```<code>String n  = ed1.getText().toString();
            String pass  = ed2.getText().toString();
            String e  = ed3.getText().toString();
</code>```

here is the example link.

Body:
I created a login page that connects to a mysql database.
In the activity_user_login.xml I entered 2 editText for email and password and a login Botton, I added a checkbox for the saved data.
I would like to save email and password.

However, I can not add the sharedPreference.
Below the full code.. You can help me? Thank you

activity_user_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.UserLoginActivity"
    android:background="#FF5722"
    android:padding="20dp">

    <TextView
        android:text="User Login Form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/email"
        android:hint="Enter Your Email Here"
        android:gravity="center"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_below="@+id/email"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/password"
        android:hint="Enter Your Password Here"
        android:gravity="center"/>

    <Button
        android:text="Log In Here"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/Login" />

    <CheckBox
        android:id="@+id/saveLoginCheckBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextPassword"
        android:text="Save Login?"
        android:textColor="#FFF" />

</RelativeLayout>

UserLoginActivity.java

package com.myapp.myappcode;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;

public class UserLoginActivity extends AppCompatActivity {

    EditText Email, Password;
    Button LogIn ;
    String PasswordHolder, EmailHolder;
    String finalResult ;
    String HttpURL = "http://mysite/User/UserLogin.php";
    Boolean CheckEditText ;
    ProgressDialog progressDialog;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    public static final String UserEmail = "";

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

        Email = (EditText)findViewById(R.id.email);
        Password = (EditText)findViewById(R.id.password);
        LogIn = (Button)findViewById(R.id.Login);

        LogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    UserLoginFunction(EmailHolder, PasswordHolder);

                }
                else {

                    Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });
    }
    public void CheckEditTextIsEmptyOrNot(){

        EmailHolder = Email.getText().toString();
        PasswordHolder = Password.getText().toString();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {
            CheckEditText = false;
        }
        else {

            CheckEditText = true ;
        }
    }

    public void UserLoginFunction(final String email, final String password){

        class UserLoginClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                if(httpResponseMsg.equalsIgnoreCase("Data Matched")){

                    finish();

                    Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class);

                    intent.putExtra(UserEmail,email);

                    startActivity(intent);

                }
                else{

                    Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
                }

            }

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

                hashMap.put("email",params[0]);

                hashMap.put("password",params[1]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        UserLoginClass userLoginClass = new UserLoginClass();

        userLoginClass.execute(email,password);
    }

}

Body:
  sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();

// get e mail and pass on button click and save it like this
            editor.putString(pass, ps);
            editor.putString(Email, e);
            editor.commit();

and to get it back:

String n  = ed1.getText().toString();
            String pass  = ed2.getText().toString();
            String e  = ed3.getText().toString();

here is the example link.


来源: stackexchange

问:
How to query a write-heavy table in PostgreSQL?
I have a PostgreSQL table that records on average ~6 million records throughout the day. It take a very long time to query the table as the records are being recorded. Is there a way to create a streamer from that table where it would post new records? I want to be able to stream changes to my website as they are being recorded.

The reason it takes so long to query the table in postgres is because I have ~550 simultaneous threaded connections performing insert from different sources. Each thread does specific analysis on the data and stores information that is valuable. I scrape, quickly analyze and load the data using Perl, but building the querying from postgres table in Python.

During loading time, even if I query (read query) the table through SQL via pgAdmin:

```<code>select var1, var2, var3 from pg_table
where filter = 'xyz'
</code>```

or even

```<code>select * from pg_table limit 100
</code>```

the query is very slow, meaning the results take ~4 minutes to return. When table is not being loaded with data, it takes ~3 seconds.

BTW thank you for you all your suggestions. I just ran an explain analyze on my table as it's being loaded with data. Here is the query:

```<code>EXPLAIN ANALYZE select count(call_option_symbol) from optionsputnik;
</code>```

Here are the results:

```<code>QUERY PLAN
Aggregate  (cost=357092.30..357092.31 rows=1 width=51) (actual time=342775.893..342775.893 rows=1 loops=1)
  ->  Seq Scan on optionsputnik  (cost=0.00..342868.24 rows=5689624 width=51) (actual time=0.025..341802.509 rows=5686946 loops=1)
Planning time: 415.781 ms
Execution time: 342775.974 ms
</code>```

I will try and an index to the table, which I know will speed-up the query time but will not make interactive (process request from web, query table and return).

This is the query plan results when nothing is being written to the table:

```<code>QUERY PLAN
Aggregate  (cost=463634.94..463634.95 rows=1 width=0) (actual time=2326.104..2326.104 rows=1 loops=1)
  ->  Seq Scan on optionsputnik  (cost=0.00..445164.95 rows=7387995 width=0) (actual time=0.029..1773.378 rows=7383752 loops=1)
Planning time: 0.045 ms
Execution time: 2326.149 ms
</code>```

Below is my table structure:

```<code>column_name,data_type,character_maximum_length
load_time,character,30
call_option_symbol,character,50
call_bid,double precision,
call_ask,double precision,
call_bid_ask_size,character,50
call_last,character,50
call_delta,double precision,
call_volume,double precision,
call_open_interest,double precision,
put_bid,double precision,
put_ask,double precision,
put_bid_ask_size,character,50
put_last,character,50
put_delta,double precision,
put_volume,double precision,
put_open_interest,double precision,
</code>```

I was thinking of trying to split the table into n separate tables to reduce number of write connections at the same time. Is there anything else that I can try or test?

答:
Check if your I/O subsystem is under stress – that would explain the time it takes.

You can gain something if you avoid sequential scans by using indexes, but that will slow down insertion considerably.

There is no free lunch here.

You could try to add enough RAM so that the table is cached, that will speed up the queries considerably.

ContentLicense: CC BY-SA 3.0

Body:
I have a PostgreSQL table that records on average ~6 million records throughout the day. It take a very long time to query the table as the records are being recorded. Is there a way to create a streamer from that table where it would post new records? I want to be able to stream changes to my website as they are being recorded.

The reason it takes so long to query the table in postgres is because I have ~550 simultaneous threaded connections performing insert from different sources. Each thread does specific analysis on the data and stores information that is valuable. I scrape, quickly analyze and load the data using Perl, but building the querying from postgres table in Python.

During loading time, even if I query (read query) the table through SQL via pgAdmin:

select var1, var2, var3 from pg_table
where filter = 'xyz'

or even

select * from pg_table limit 100

the query is very slow, meaning the results take ~4 minutes to return. When table is not being loaded with data, it takes ~3 seconds.

BTW thank you for you all your suggestions. I just ran an explain analyze on my table as it's being loaded with data. Here is the query:

EXPLAIN ANALYZE select count(call_option_symbol) from optionsputnik;

Here are the results:

QUERY PLAN
Aggregate  (cost=357092.30..357092.31 rows=1 width=51) (actual time=342775.893..342775.893 rows=1 loops=1)
  ->  Seq Scan on optionsputnik  (cost=0.00..342868.24 rows=5689624 width=51) (actual time=0.025..341802.509 rows=5686946 loops=1)
Planning time: 415.781 ms
Execution time: 342775.974 ms

I will try and an index to the table, which I know will speed-up the query time but will not make interactive (process request from web, query table and return).

This is the query plan results when nothing is being written to the table:

QUERY PLAN
Aggregate  (cost=463634.94..463634.95 rows=1 width=0) (actual time=2326.104..2326.104 rows=1 loops=1)
  ->  Seq Scan on optionsputnik  (cost=0.00..445164.95 rows=7387995 width=0) (actual time=0.029..1773.378 rows=7383752 loops=1)
Planning time: 0.045 ms
Execution time: 2326.149 ms

Below is my table structure:

column_name,data_type,character_maximum_length
load_time,character,30
call_option_symbol,character,50
call_bid,double precision,
call_ask,double precision,
call_bid_ask_size,character,50
call_last,character,50
call_delta,double precision,
call_volume,double precision,
call_open_interest,double precision,
put_bid,double precision,
put_ask,double precision,
put_bid_ask_size,character,50
put_last,character,50
put_delta,double precision,
put_volume,double precision,
put_open_interest,double precision,

I was thinking of trying to split the table into n separate tables to reduce number of write connections at the same time. Is there anything else that I can try or test?


问:
ng-disabled within angular directive
I have an angular directive:

```<code>angular.module("app").directive("myButtons", function () {
    return {
        restrict: "E",
        scope: {
            bdisabled: '='
        },
        templateUrl: "buttons.html"
    }
});
</code>```

template:

```<code><input type="submit" value="Update" ng-disabled="{{bdisabled}}" />
</code>```

html:

```<code><my-buttons bdisabled="!form.$valid"></my-buttons>
</code>```

I'm trying to set the disabled state of the button in my template. The above code almost works.

The form loads and is valid, the html is rendered as follows:

```<code><input type="submit" ng-click="bdisabled()" value="Save" ng-disabled="false" disabled="disabled">
</code>```

When I make the form invalid ng-disabled changes to true but disabled="disabled" stays no matter what.

What am I doing wrong?

答:
since ng-disabled is angular directive no need to use the curly brackets

```<code><input type="submit" value="Update" ng-disabled="bdisabled" />
</code>```

Title: ng-disabled within angular directive

Body:
I have an angular directive:

angular.module("app").directive("myButtons", function () {
    return {
        restrict: "E",
        scope: {
            bdisabled: '='
        },
        templateUrl: "buttons.html"
    }
});

template:

<input type="submit" value="Update" ng-disabled="{{bdisabled}}" />

html:

<my-buttons bdisabled="!form.$valid"></my-buttons>

I'm trying to set the disabled state of the button in my template. The above code almost works.

The form loads and is valid, the html is rendered as follows:

<input type="submit" ng-click="bdisabled()" value="Save" ng-disabled="false" disabled="disabled">

When I make the form invalid ng-disabled changes to true but disabled="disabled" stays no matter what.

What am I doing wrong?

Body:
since ng-disabled is angular directive no need to use the curly brackets

<input type="submit" value="Update" ng-disabled="bdisabled" />


问:
Angular 2 - Store value from method GET
I have a question. I'm new o Angular 2 and I tried to store a simple value in a variable. I call a get method that returns a number (backend in c#). How can I store this value on a global variable?

```<code>getTarea(a,b,c,d,e){
        return this._http.get('http://localhost:50790/ApiProductoTipo/TareaPT?delegacionId='+a+'&municipioId='+b+'&ejercicioId='+c+'&ninternoId='+d+'&tipo='+e)
             .map(res=> {alert('Tarea:'+res);})
            .catch(this.handleError);
    }
</code>```

This code print

Tarea:Response with status: 200 OK for URL: http://localhost:50790/ApiProductoTipo/TareaPT?delegacionId=11&municipioId=1&ejercicioId=2017&ninternoId=-1&tipo=T

But i need the number value that returns this method. Any ideas?

Back

```<code>[HttpGet]
public int GetTareaPT(int delegacionId, int municipioId, int ejercicioId, int ninternoId, string tipo)
{
    int numtarea = this.productoTipoService.GetTareaPT(delegacionId, municipioId, ejercicioId, ninternoId, tipo);

    if (numtarea != 0)
    {
        return numtarea;
    }
    else
    {
        return 0;
    }
}
</code>```

答:
Solved thanks to AJT_82 by doing </p>

```<code>.map(res=> {alert('Tarea:', res.json());})
</code>```

Title: Angular 2 - Store value from method GET

Body:
I have a question. I'm new o Angular 2 and I tried to store a simple value in a variable. I call a get method that returns a number (backend in c#). How can I store this value on a global variable?

getTarea(a,b,c,d,e){
        return this._http.get('http://localhost:50790/ApiProductoTipo/TareaPT?delegacionId='+a+'&municipioId='+b+'&ejercicioId='+c+'&ninternoId='+d+'&tipo='+e)
             .map(res=> {alert('Tarea:'+res);})
            .catch(this.handleError);
    }

This code print

Tarea:Response with status: 200 OK for URL: http://localhost:50790/ApiProductoTipo/TareaPT?delegacionId=11&municipioId=1&ejercicioId=2017&ninternoId=-1&tipo=T

But i need the number value that returns this method. Any ideas?

Back

[HttpGet]
public int GetTareaPT(int delegacionId, int municipioId, int ejercicioId, int ninternoId, string tipo)
{
    int numtarea = this.productoTipoService.GetTareaPT(delegacionId, municipioId, ejercicioId, ninternoId, tipo);

    if (numtarea != 0)
    {
        return numtarea;
    }
    else
    {
        return 0;
    }
}

Body:
Solved thanks to AJT_82 by doing

.map(res=> {alert('Tarea:', res.json());})


问:
margin is set to zero but it still showing
My html has 2 sections, margin is zero but it still showing

.box1 {
  width: 300px;
  height: 450px;
  background-color: green;
  border: 0px;
  display: inline-block;
  margin: 0;
  padding: 0px;
}

.box2 {
  width: 150px;
  height: 300px;
  background-color: purple;
  border: 0px;
  display: inline-block;
  margin: 0;
  padding: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="box2"></div>
  <div class="box1"></div>
</body></code>```

this is result

答:
It is not the margin. It is the  new lines  converted to "spaces" when displaying it.It is because of the display:inline-block of the div . You can either remove the space or remove that with comments   between the divs

.box1 { width: 300px;
height: 450px;
background-color: green;
border: 0px;
display: inline-block;
margin: 0;
padding: 0px; }

.box2 { width: 150px;
height: 300px;
background-color: purple;
border: 0px;
display: inline-block;
margin: 0;
padding: 0px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box2"></div><!--

   --><div class="box1"></div>

 </code>```

Body:
My html has 2 sections, margin is zero but it still showing

.box1 {
  width: 300px;
  height: 450px;
  background-color: green;
  border: 0px;
  display: inline-block;
  margin: 0;
  padding: 0px;
}

.box2 {
  width: 150px;
  height: 300px;
  background-color: purple;
  border: 0px;
  display: inline-block;
  margin: 0;
  padding: 0px;
}

this is result

Body:
It is not the margin. It is the  new lines  converted to "spaces" when displaying it.It is because of the display:inline-block of the div . You can either remove the space or remove that with comments  <!-- --> between the divs

.box1 { width: 300px;
height: 450px;
background-color: green;
border: 0px;
display: inline-block;
margin: 0;
padding: 0px; }

.box2 { width: 150px;
height: 300px;
background-color: purple;
border: 0px;
display: inline-block;
margin: 0;
padding: 0px;}

<div class="box2"></div><!--

   --><div class="box1"></div>


问:
Create dynamic Component React (Native)
i get from web sevice array of object [{"id:1","title": "News",....},"id":2, "title": "History", .....}], so i want to create tab and scroll using react-native-scrollable-tab-view https://github.com/skv-headless/react-native-scrollable-tab-view, for static it work nice , but i don't know how to make dynamic because admin can add more title any time so static not work for this purpose.

In my code i do like this

```<code> constructor(props){
        super(props);
        this.state = {
            ws: []
        };
    }
</code>```

Also

```<code>componentDidMount() {
        fetch('http://localhost:8000/api/getThemeByOrganisations', {
            }).then((response) => response.json())
                .then((res) => {
                    this.setState({
                        ws : ws
                     });
                })
                .catch((error) => {
                    console.error(error);
                });
    };
</code>```

I want to make component name like that i get from web service (title) example NewsComponent

In the end i want to do like this but dynamic

```<code>var App = React.createClass({
  render() {
    return (
      <ScrollableTabView renderTabBar={() => <CustomTabBar someProp={'here'} />}>
        <ReactPage tabLabel="React" />
        <FlowPage tabLabel="Flow" />
        <JestPage tabLabel="Jest" />
      </ScrollableTabView>
    );
  }
});
</code>```

So here i want to do like for in "ws" and create dynamic Page , So anyone can help me and thanks

答:
So for using react-native-scrollable-tab-view

First i create new component ResultItem

```<code> var ResultItem = React.createClass({
  render: function() {
    return (
        <Text tabLabel>
            {this.props.result.nom}
        </Text>
    );
  }
});
</code>```

Second in render Main Component

```<code><ScrollableTabView
               renderTabBar={() => <ScrollableTabBar />}>
               {this.state.ws.map(function (result) {
                             return <ResultItem key={result.id} result={result} tabLabel={result.nom}/>;
                        })}
                    </ScrollableTabView>
</code>```

It work nice for dynamic render

Title: Create dynamic Component React (Native)

Body:
i get from web sevice array of object [{"id:1","title": "News",....},"id":2, "title": "History", .....}], so i want to create tab and scroll using react-native-scrollable-tab-view https://github.com/skv-headless/react-native-scrollable-tab-view, for static it work nice , but i don't know how to make dynamic because admin can add more title any time so static not work for this purpose.

In my code i do like this

 constructor(props){
        super(props);
        this.state = {
            ws: []
        };
    }

Also

componentDidMount() {
        fetch('http://localhost:8000/api/getThemeByOrganisations', {
            }).then((response) => response.json())
                .then((res) => {
                    this.setState({
                        ws : ws
                     });
                })
                .catch((error) => {
                    console.error(error);
                });
    };

I want to make component name like that i get from web service (title) example NewsComponent

In the end i want to do like this but dynamic

var App = React.createClass({
  render() {
    return (
      <ScrollableTabView renderTabBar={() => <CustomTabBar someProp={'here'} />}>
        <ReactPage tabLabel="React" />
        <FlowPage tabLabel="Flow" />
        <JestPage tabLabel="Jest" />
      </ScrollableTabView>
    );
  }
});

So here i want to do like for in "ws" and create dynamic Page , So anyone can help me and thanks

Body:
So for using react-native-scrollable-tab-view

First i create new component ResultItem

 var ResultItem = React.createClass({
  render: function() {
    return (
        <Text tabLabel>
            {this.props.result.nom}
        </Text>
    );
  }
});

Second in render Main Component

<ScrollableTabView
               renderTabBar={() => <ScrollableTabBar />}>
               {this.state.ws.map(function (result) {
                             return <ResultItem key={result.id} result={result} tabLabel={result.nom}/>;
                        })}
                    </ScrollableTabView>

It work nice for dynamic render


问:
How to fetch values from sqlite database and stored into array using objective c?
```<code>- (IBAction)submit:(id)sender {
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO employeedetails('employee_name','employee_mailid','employee_username','employee_password')VALUES('%@','%@','%@','%@')",self.textname.text,self.textmailid.text,self.textusername.text,self.textpassword.text];
    NSLog(@"%@The inserted values are",sql);
    char *err;
    if (sqlite3_exec(db,[sql UTF8String], NULL, NULL, &err)!=SQLITE_OK) {

        sqlite3_close(db);
        NSAssert(0,@"sdsadadsderererwrcould not update the tabel");
    }
    else{
        NSLog(@"nbbbbbbbbbbbbtable updated");
    }

}

-(void)selectfn
{
    const char *sqlStatement = "SELECT * FROM employeedetails";  // Your Tablename

    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        [name removeAllObjects];

        while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        {
            [name addObject:[NSString stringWithFormat:@"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
            NSLog(@"The array value is %@",name);
        }
    }
    sqlite3_finalize(compiledStatement);

sqlite3_close(db);
}
</code>```

Already I have insert values into table...Now I want to fetch values from the table and want to store one nsarray and display into tableview....help me plz

答:
You can create Model class something like this

Header file

```<code>#import "Model.h"

@implementation Model

@synthesize _firstValue ,_secondValue ;

@end
</code>```

Implementation file

```<code>#import <Foundation/Foundation.h>

@interface Model: NSObject
{
    NSString *_firstValue ;
    NSString *_secondValue ;
}

@property (nonatomic,retain) NSString *_firstValue ;
@property (nonatomic,retain) NSString *_secondValue ;

@end
</code>```

Now fetching data using below lines...

```<code>  //Cretae a array to store values
    NSMutableArray *retArr = [[NSMutableArray alloc]init];
        if ([self dbOpen]) // check db is open
        {
            const char *sqlStatement = [YOUR_QUERY UTF8String];
            sqlite3_stmt *statement;
            if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
            {
                while( sqlite3_step(statement) == SQLITE_ROW )
                {

    // used model to fill the set of data
                    Model *obj = [[Model alloc] init];
                    obj._firstValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
                    obj._secondValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
                    [retArr addObject:obj];
                    obj = nil;
                }
            }
            else {  NSLog( QRY_EXEC_ERROR, sqlite3_errmsg(database) );  } // excute if any error

            sqlite3_finalize(statement); // finalizing
            sqlite3_close(database); // clossing the DB
        }

Finally use retArr which holds your DB values.....
</code>```

Body:
- (IBAction)submit:(id)sender {
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO employeedetails('employee_name','employee_mailid','employee_username','employee_password')VALUES('%@','%@','%@','%@')",self.textname.text,self.textmailid.text,self.textusername.text,self.textpassword.text];
    NSLog(@"%@The inserted values are",sql);
    char *err;
    if (sqlite3_exec(db,[sql UTF8String], NULL, NULL, &err)!=SQLITE_OK) {

        sqlite3_close(db);
        NSAssert(0,@"sdsadadsderererwrcould not update the tabel");
    }
    else{
        NSLog(@"nbbbbbbbbbbbbtable updated");
    }

}

-(void)selectfn
{
    const char *sqlStatement = "SELECT * FROM employeedetails";  // Your Tablename

    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(db, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)
    {
        [name removeAllObjects];

        while(sqlite3_step(compiledStatement) == SQLITE_ROW)
        {
            [name addObject:[NSString stringWithFormat:@"%s",(char *) sqlite3_column_text(compiledStatement, 0)]];
            NSLog(@"The array value is %@",name);
        }
    }
    sqlite3_finalize(compiledStatement);

sqlite3_close(db);
}

Already I have insert values into table...Now I want to fetch values from the table and want to store one nsarray and display into tableview....help me plz

Body:
You can create Model class something like this

Header file

#import "Model.h"

@implementation Model

@synthesize _firstValue ,_secondValue ;

@end

Implementation file

#import <Foundation/Foundation.h>

@interface Model: NSObject
{
    NSString *_firstValue ;
    NSString *_secondValue ;
}

@property (nonatomic,retain) NSString *_firstValue ;
@property (nonatomic,retain) NSString *_secondValue ;

@end

Now fetching data using below lines...

  //Cretae a array to store values
    NSMutableArray *retArr = [[NSMutableArray alloc]init];
        if ([self dbOpen]) // check db is open
        {
            const char *sqlStatement = [YOUR_QUERY UTF8String];
            sqlite3_stmt *statement;
            if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
            {
                while( sqlite3_step(statement) == SQLITE_ROW )
                {

    // used model to fill the set of data
                    Model *obj = [[Model alloc] init];
                    obj._firstValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
                    obj._secondValue = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 1)];
                    [retArr addObject:obj];
                    obj = nil;
                }
            }
            else {  NSLog( QRY_EXEC_ERROR, sqlite3_errmsg(database) );  } // excute if any error

            sqlite3_finalize(statement); // finalizing
            sqlite3_close(database); // clossing the DB
        }

Finally use retArr which holds your DB values.....


问:
Largest value stored in 20 bits
I am assembly language student and yesterday my teacher asked me , what largest value can be stored in 20 bits for Signed Representation ?

I was confused. Kindly help me out

答:
With signed numbers the highest bit is treated as the sign bit. (0=positive 1=negative)

That leaves 19 bits for the actual number when you only have 20 bits of storage.

```<code>0000_0000_0000_0000_0000b    Smallest positive number:      0

0111_1111_1111_1111_1111b    Largest positive number:  524287

1111_1111_1111_1111_1111b    Smallest negative number:     -1

1000_0000_0000_0000_0000b    Largest negative number: -524288
</code>```

Title: Largest value stored in 20 bits

Body:
With signed numbers the highest bit is treated as the sign bit. (0=positive 1=negative)

That leaves 19 bits for the actual number when you only have 20 bits of storage.

0000_0000_0000_0000_0000b    Smallest positive number:      0

0111_1111_1111_1111_1111b    Largest positive number:  524287

1111_1111_1111_1111_1111b    Smallest negative number:     -1

1000_0000_0000_0000_0000b    Largest negative number: -524288


问:
Auth::viaRemember() doesnot work (means always return false even after successful login) in laravel 5.4
I make use of php artisan make:auth in laravel 5.4, as we know laravel default login only supports email so, I put login() in AuthController like below (login working)-

```<code>public function login(Request $request)
{
    $remember = ($request->input('remember')=='1')?true:false;
    // this will remember the user as given in laravel documentation.
    if (Auth::attempt(['user_name' => $request->user_name, 'password' => $request->password],$remember)) {
        return redirect()->intended('admin');
    }

    elseif (Auth::attempt(['email'=> $request->user_name, 'password' => $request->password],$remember)) {

            return redirect()->intended('admin');
    }

    else {
        return redirect('/login')->with(['error'=>'Invalid user name and password'])
                                 ->withInput();

    }
}
</code>```

Now, whenever session expired simply typing url should redirect to admin/dashboard, But couldnot do so... By default it redirects to login page.

I put Auth::viaRemember() in constructor of AuthContoller class before checking for middleware like below-

```<code>public function __construct()
{
    // login with  remember me before checking whether its logged in or not
    Auth::viaRemember();
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
</code>```

What i follow in stack overflow -

Via Remember me always return false -this link is similar to mine

viaRemember not work - laravel

Laravel 5 viaRemember() always false

Laravel: Implement Auth::viaRemember() across the website

答:
```<code>protected function attemptLogin(Request $request)
{
     // dd($request->has('remember'));
    $remember =$request->has('remember');
    return $this->guard()->attempt(
        $this->credentials($request), $remember
    );
}
</code>```

use this in AuthenticateUsers.php it worked for me

Body:
I make use of php artisan make:auth in laravel 5.4, as we know laravel default login only supports email so, I put login() in AuthController like below (login working)-

public function login(Request $request)
{
    $remember = ($request->input('remember')=='1')?true:false;
    // this will remember the user as given in laravel documentation.
    if (Auth::attempt(['user_name' => $request->user_name, 'password' => $request->password],$remember)) {
        return redirect()->intended('admin');
    }

    elseif (Auth::attempt(['email'=> $request->user_name, 'password' => $request->password],$remember)) {

            return redirect()->intended('admin');
    }

    else {
        return redirect('/login')->with(['error'=>'Invalid user name and password'])
                                 ->withInput();

    }
}

Now, whenever session expired simply typing url should redirect to admin/dashboard, But couldnot do so... By default it redirects to login page.

I put Auth::viaRemember() in constructor of AuthContoller class before checking for middleware like below-

public function __construct()
{
    // login with  remember me before checking whether its logged in or not
    Auth::viaRemember();
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}

What i follow in stack overflow -

Via Remember me always return false -this link is similar to mine

viaRemember not work - laravel

Laravel 5 viaRemember() always false

Laravel: Implement Auth::viaRemember() across the website

Body:
protected function attemptLogin(Request $request)
{
     // dd($request->has('remember'));
    $remember =$request->has('remember');
    return $this->guard()->attempt(
        $this->credentials($request), $remember
    );
}

use this in AuthenticateUsers.php it worked for me


问:
Is it possible to make an AIR app have a "nag"?
Is it possible to make a desktop AIR application that includes the ability to "nag" users every so often to perform an action (similar to Windows status bar notifications or "jumping icons" on the Mac dock)? </p>

答:
Look into the NativeApplication.nativeApplication.icon.bounce() method.  I think this might be what you're looking to try to achieve.

Here's an entire tutorial about doing stuff with the user's dock/system tray on Adobe's DevNet.
http://www.adobe.com/devnet/air/flash/quickstart/articles/stopwatch_dock_system_tray.html

ContentLicense: CC BY-SA 2.5


问:
Spring boot , native query, crudRepository
I have the following query

```<code>@Modifying
@Query(value = "update car_wash  set lon_lat=ST_GeomFromText('POINT( :lon :lat )') where id=:id ; ",nativeQuery = true)
void upateLonLat(@Param("lon")String lon,@Param("lat")String lat,@Param("id")Integer id);
</code>```

When I try to use this query i have the following exception

```<code>  java.lang.IllegalArgumentException: Parameter with that name [lon] did not exist
at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:487) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:638) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:163) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:139) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:101) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:161) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:152) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:238) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at com.sun.proxy.$Proxy118.upateLonLat(Unknown Source) ~[na:na]
</code>```

I tried to change type of lon ant lat to double, and change :lon :lat to ?1 ?2 inside the query

答:
Try with :</p>

```<code>set lon_lat=ST_GeomFromText('POINT(' || :lon || ' ' || :lat || ')')
</code>```

Body:
I have the following query

@Modifying
@Query(value = "update car_wash  set lon_lat=ST_GeomFromText('POINT( :lon :lat )') where id=:id ; ",nativeQuery = true)
void upateLonLat(@Param("lon")String lon,@Param("lat")String lat,@Param("id")Integer id);

When I try to use this query i have the following exception

  java.lang.IllegalArgumentException: Parameter with that name [lon] did not exist
at org.hibernate.jpa.spi.BaseQueryImpl.findParameterRegistration(BaseQueryImpl.java:487) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.spi.BaseQueryImpl.setParameter(BaseQueryImpl.java:638) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:163) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.jpa.spi.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:32) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:139) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.StringQueryParameterBinder.bind(StringQueryParameterBinder.java:61) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.ParameterBinder.bind(ParameterBinder.java:101) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.SpelExpressionStringQueryParameterBinder.bind(SpelExpressionStringQueryParameterBinder.java:69) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:161) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.ParameterBinder.bindAndPrepare(ParameterBinder.java:152) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractStringBasedJpaQuery.doCreateQuery(AbstractStringBasedJpaQuery.java:81) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.createQuery(AbstractJpaQuery.java:190) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ModifyingExecution.doExecute(JpaQueryExecution.java:238) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:85) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) ~[spring-data-jpa-1.11.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57) ~[spring-data-commons-1.13.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at com.sun.proxy.$Proxy118.upateLonLat(Unknown Source) ~[na:na]

I tried to change type of lon ant lat to double, and change :lon :lat to ?1 ?2 inside the query

Body:
Try with :

set lon_lat=ST_GeomFromText('POINT(' || :lon || ' ' || :lat || ')')


问:
Conditional Formatting multiple rules
I need cells to turn yellow greater than 20 days and red greater than 30 days from implementation date.I can get it to do one or the other but not both. </p>

答:
Why not use the "between" condition for the 20 and "greater than" for 30

this worked for me as expected

Title: Conditional Formatting multiple rules


答:
Change ng-disabled="{{bdisabled}}" to ng-disabled="bdisabled",

No need of interpolation operators, as its already in angular scope.

Title: ng-disabled within angular directive


问:
Want to add condition on my username field
I want to add the condition on the user name field.
If the user did not enter his name, a toast message should be displayed on the screen "Please enter your name"

Where should I put the if statement in my java code ?

Can anybody help me with this ?

This is my java code below:

```<code>package com.infinitystone.mani.justjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This app displays an order form to order coffee.
 */
public class MainActivity extends AppCompatActivity {
    int quantity = 0;

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

    /**
     * This method is called when the + button is clicked.
     */

    public void increment(View view) {
        if (quantity >= 10){
            Toast.makeText(getApplicationContext(), "Only 10 cups per order",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        quantity = quantity + 1;
        displayQuantity(quantity);
    }

    /**
     * This method is called when the - button is clicked.
     */

    public void decrement(View view) {
        if (quantity<=0){
            Toast.makeText(this, "Dude! are you drunk ?",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        quantity = quantity - 1;
        displayQuantity(quantity);
    }

    /**
     * This method is called when the order button is clicked.
     */

    public void submitOrder(View view) {
        if (quantity == 0){
            Toast.makeText(this, "How many bottles you had ?",
                    Toast.LENGTH_SHORT).show();
            return;
        }
            EditText userName = (EditText) findViewById(R.id.name_edit_text);
            String name = userName.getText().toString();
            CheckBox whippedCream = (CheckBox) findViewById(R.id.checkbox_cream);
            boolean hasWhippedCream = whippedCream.isChecked();
            CheckBox chocolate = (CheckBox) findViewById(R.id.checkbox_chocolate);
            boolean hasChocolate = chocolate.isChecked();
            int finalPrice = calculatePrice(hasWhippedCream, hasChocolate);
            String priceMessage = createOrderSummary(finalPrice, hasWhippedCream, hasChocolate, name);
            displayMessage(priceMessage);
    }

    /**
     * Calculates the price of the order.
     *
     * @param addWhippedCream tells if the user wants to add whipped cream
     * @param addChocolate tells if the user wants to add chocolate
     * @return total price of the order
     */
    private int calculatePrice(boolean addWhippedCream, boolean addChocolate) {
        int basePrice = 5;
        if (addWhippedCream){
            basePrice = basePrice + 1;
        }

        if (addChocolate){
            basePrice = basePrice +2;
        }
        return quantity * basePrice;
    }

    /**
     * Creates the summary of the order
     *
     * @param price
     * @param addWhippedCream
     * @param addChocolate
     * @param addUserName
     * @return
     */
    private String createOrderSummary(int price,
                                      boolean addWhippedCream,
                                      boolean addChocolate,
                                      String addUserName) {
        String orderSummary = "Name: " + addUserName;
        orderSummary += "\nQuantity: " + quantity + " cups";
        orderSummary += "\nWhipped cream added: " + addWhippedCream;
        orderSummary += "\nChocolate added: " + addChocolate;
        orderSummary += "\nTotal = $" + price;
        orderSummary += "\nThank You!";
        return orderSummary;
    }

    /**
     * This method displays the given quantity value on the screen.
     */
    private void displayQuantity(int number) {
        TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
        quantityTextView.setText("" + number);
    }

    /**
     * This method displays the given text on the screen.
     */
    private void displayMessage(String message) {
        TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
        orderSummaryTextView.setText(message);
    }
}
</code>```

And here's my XML code for the layout

```<code><ScrollView 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:id="@+id/name_edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:hint="Name"
            android:inputType="textCapWords" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="toppings"
            android:textAllCaps="true" />

        <CheckBox
            android:id="@+id/checkbox_cream"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="18dp"
            android:text="Whipped Cream"
            android:textSize="16sp" />

        <CheckBox
            android:id="@+id/checkbox_chocolate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="18dp"
            android:text="Chocolate"
            android:textSize="16sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="168dp"
            android:layout_marginTop="8dp"
            android:background="@android:color/darker_gray">

        </View>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="Quantity"
            android:textAllCaps="true" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:orientation="horizontal">

            <Button
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:onClick="decrement"
                android:text="-" />

            <TextView
                android:id="@+id/quantity_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:text="0"
                android:textColor="@android:color/black"
                android:textSize="16sp" />

            <Button
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:onClick="increment"
                android:text="+" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="168dp"
            android:layout_marginTop="8dp"
            android:background="@android:color/darker_gray">

        </View>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="order summary"
            android:textAllCaps="true" />

        <TextView
            android:id="@+id/order_summary_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="$0"
            android:textColor="@android:color/black"
            android:textSize="16sp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:onClick="submitOrder"
            android:text="Order" />

    </LinearLayout>
</ScrollView>
</code>```

答:
You're already validating the "quantity == 0" in submitOrder() , there add another one condition

```<code>if (username.getText().equals("")) {
  Toast
    .makeText(
      mContext,
      "Stay tuned with us we'll bring more exitting features for you!",
      Toast.LENGTH_SHORT
    )
    .show();
}
</code>```

Or
If any other condition you want check...

Body:
I want to add the condition on the user name field.
If the user did not enter his name, a toast message should be displayed on the screen "Please enter your name"

Where should I put the if statement in my java code ?

Can anybody help me with this ?

This is my java code below:

package com.infinitystone.mani.justjava;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This app displays an order form to order coffee.
 */
public class MainActivity extends AppCompatActivity {
    int quantity = 0;

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

    /**
     * This method is called when the + button is clicked.
     */

    public void increment(View view) {
        if (quantity >= 10){
            Toast.makeText(getApplicationContext(), "Only 10 cups per order",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        quantity = quantity + 1;
        displayQuantity(quantity);
    }

    /**
     * This method is called when the - button is clicked.
     */

    public void decrement(View view) {
        if (quantity<=0){
            Toast.makeText(this, "Dude! are you drunk ?",
                    Toast.LENGTH_SHORT).show();
            return;
        }
        quantity = quantity - 1;
        displayQuantity(quantity);
    }

    /**
     * This method is called when the order button is clicked.
     */

    public void submitOrder(View view) {
        if (quantity == 0){
            Toast.makeText(this, "How many bottles you had ?",
                    Toast.LENGTH_SHORT).show();
            return;
        }
            EditText userName = (EditText) findViewById(R.id.name_edit_text);
            String name = userName.getText().toString();
            CheckBox whippedCream = (CheckBox) findViewById(R.id.checkbox_cream);
            boolean hasWhippedCream = whippedCream.isChecked();
            CheckBox chocolate = (CheckBox) findViewById(R.id.checkbox_chocolate);
            boolean hasChocolate = chocolate.isChecked();
            int finalPrice = calculatePrice(hasWhippedCream, hasChocolate);
            String priceMessage = createOrderSummary(finalPrice, hasWhippedCream, hasChocolate, name);
            displayMessage(priceMessage);
    }

    /**
     * Calculates the price of the order.
     *
     * @param addWhippedCream tells if the user wants to add whipped cream
     * @param addChocolate tells if the user wants to add chocolate
     * @return total price of the order
     */
    private int calculatePrice(boolean addWhippedCream, boolean addChocolate) {
        int basePrice = 5;
        if (addWhippedCream){
            basePrice = basePrice + 1;
        }

        if (addChocolate){
            basePrice = basePrice +2;
        }
        return quantity * basePrice;
    }

    /**
     * Creates the summary of the order
     *
     * @param price
     * @param addWhippedCream
     * @param addChocolate
     * @param addUserName
     * @return
     */
    private String createOrderSummary(int price,
                                      boolean addWhippedCream,
                                      boolean addChocolate,
                                      String addUserName) {
        String orderSummary = "Name: " + addUserName;
        orderSummary += "\nQuantity: " + quantity + " cups";
        orderSummary += "\nWhipped cream added: " + addWhippedCream;
        orderSummary += "\nChocolate added: " + addChocolate;
        orderSummary += "\nTotal = $" + price;
        orderSummary += "\nThank You!";
        return orderSummary;
    }

    /**
     * This method displays the given quantity value on the screen.
     */
    private void displayQuantity(int number) {
        TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
        quantityTextView.setText("" + number);
    }

    /**
     * This method displays the given text on the screen.
     */
    private void displayMessage(String message) {
        TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
        orderSummaryTextView.setText(message);
    }
}

And here's my XML code for the layout

<ScrollView 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <EditText
            android:id="@+id/name_edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="16dp"
            android:layout_marginTop="16dp"
            android:hint="Name"
            android:inputType="textCapWords" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="toppings"
            android:textAllCaps="true" />

        <CheckBox
            android:id="@+id/checkbox_cream"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="18dp"
            android:text="Whipped Cream"
            android:textSize="16sp" />

        <CheckBox
            android:id="@+id/checkbox_chocolate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="18dp"
            android:text="Chocolate"
            android:textSize="16sp" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="168dp"
            android:layout_marginTop="8dp"
            android:background="@android:color/darker_gray">

        </View>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="Quantity"
            android:textAllCaps="true" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:orientation="horizontal">

            <Button
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:onClick="decrement"
                android:text="-" />

            <TextView
                android:id="@+id/quantity_text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="8dp"
                android:text="0"
                android:textColor="@android:color/black"
                android:textSize="16sp" />

            <Button
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:onClick="increment"
                android:text="+" />

        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="168dp"
            android:layout_marginTop="8dp"
            android:background="@android:color/darker_gray">

        </View>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="order summary"
            android:textAllCaps="true" />

        <TextView
            android:id="@+id/order_summary_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="$0"
            android:textColor="@android:color/black"
            android:textSize="16sp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:onClick="submitOrder"
            android:text="Order" />

    </LinearLayout>
</ScrollView>

Body:
You're already validating the "quantity == 0" in submitOrder() , there add another one condition

if (username.getText().equals("")) {
  Toast
    .makeText(
      mContext,
      "Stay tuned with us we'll bring more exitting features for you!",
      Toast.LENGTH_SHORT
    )
    .show();
}

Or
If any other condition you want check...


问:
Jmeter JSON PATH postprocessor
I have my JSON response code as

```<code><script type="text/javascript" id="RequestScript">
var contextpath = 'https://example.com/';
var JSONObject = null;
var XMLString ='';
var pswitchprofiles = new Object();

pswitchprofiles.WLDATAObject =
{
:   switchprofile:
:   {
:   :   totalRows:5,
:   :   moreRows:false,
:   :   rows:
:   :   [
:   :   :   {
:   :   :   :   id:'1f04b8c7788f47eaba507cd1f01bafd6',
:   :   :   :   ex:'N',
:   :   :   :   name:'Mahindra'
:   :   :   },
:   :   :   {
:   :   :   :   id:'a316419bf71f402cbc3a7af746d80626',
:   :   :   :   ex:'N',
:   :   :   :   name:'Toyota'
:   :   :   },
:   :   :   {
:   :   :   :   id:'1b8f642c00c6469cad1f73829d1b88df',
:   :   :   :   ex:'N',
:   :   :   :   name:'Renault'
:   :   :   },
:   :   :   {
:   :   :   :   id:'df989db921f84dfcac2fb1d4e72c18a3',
:   :   :   :   ex:'N',
:   :   :   :   name:'Huyndai'
:   :   :   },
:   :   :   {
:   :   :   :   id:'43B014C9BF0C1516E0530100007F2995',
:   :   :   :   ex:'N',
:   :   :   :   name:'Skoda'
:   :   :   }
:   :   ]
:   }
}
;
</script>
</code>```

I am trying to get the id for the corresponding name.
In JSON PATH postprocessor, if i give          $.switchprofile.rows[?(@.name == 'Renault')].id               in JSON path expressions, I am not able to get the correct id.

Please help me in getting it. Also, i am not sure if that response is actually JSON.
I am using jmeter 3.0

答:
Your response is not JSON one therefore you won't be able to use JSON Path PostProcessor, you will need to switch to Regular Expression Extractor instead.

The relevant regular expression would look like:

```<code>id:'(\w+)',\s.*,\s.*name:'Renault'
</code>```

Demo:

References:

JMeter: Regular Expressions

Using RegEx (Regular Expression Extractor) With JMeter

Perl 5 Regex Cheat sheet

Title: Jmeter JSON PATH postprocessor

Body:
I have my JSON response code as

I am trying to get the id for the corresponding name.
In JSON PATH postprocessor, if i give          $.switchprofile.rows[?(@.name == 'Renault')].id               in JSON path expressions, I am not able to get the correct id.

Please help me in getting it. Also, i am not sure if that response is actually JSON.
I am using jmeter 3.0

Body:
Your response is not JSON one therefore you won't be able to use JSON Path PostProcessor, you will need to switch to Regular Expression Extractor instead.

The relevant regular expression would look like:

id:'(\w+)',\s.*,\s.*name:'Renault'

Demo:

References:

JMeter: Regular Expressions

Using RegEx (Regular Expression Extractor) With JMeter

Perl 5 Regex Cheat sheet


问:
RoR nested :include to include sub-resources in to_xml/to_json
I have a weird data model situation to start with, so maybe my whole approach is wrong. Here's what I'm doing:

I have a class called Bird and a simple class called Color. Conceptually, each bird has two to_many associations to Color, one for male colors and one for female colors. The way I've handled this is to use a join model called BirdColoration that belongs to a bird and a color and has an additional boolean field to tell if the coloration is for male or female. So each bird actually has a to_many relationship to BirdColoration as well as a to_many to Color :through BirdColoration. If this sounds reasonable, then continue reading. Otherwise, stop and tell me why it's wrong!

I need to be able to dump the birds table as json. Previously, when each bird only had one to_many association to colors, I could just use :include to include each bird's colors in the json dump. Now, I'm including the BirdColorations in the dump, but I still need to get at the color models themselves. I could separately include each bird's colors and colorations and then match them up while parsing, but I would much rather just include each coloration's color directly. Something like

```<code>      format.json  { render :json => @birds.to_json(:include => [{:bird_colorations => :color}, :seasons, :habitats, :image_holders]) }
</code>```

The above doesn't work, however. I think that this should be possible. Can anyone point me in the right direction for how to handle this?

For now, I'll just include each bird's color and colorations separately and match them up in parsing. At least I know that will work.

Thanks!

答:
If you have a complex JSON structure, it's better to override serializable_hash or as_json in your model than to try to do it all through render :json.

So something like

```<code>def serializable_hash(options = nil)
  options ||= {}
  bird = {:name => name, ...}
  bird[:seasons] = seasons.serilizable_hash
  bird[:colors] = ... # whatever complex logic you want to get to the colors
  bird
end
</code>```

Both functions just need to return a hash.

Body:
I have a weird data model situation to start with, so maybe my whole approach is wrong. Here's what I'm doing:

I have a class called Bird and a simple class called Color. Conceptually, each bird has two to_many associations to Color, one for male colors and one for female colors. The way I've handled this is to use a join model called BirdColoration that belongs to a bird and a color and has an additional boolean field to tell if the coloration is for male or female. So each bird actually has a to_many relationship to BirdColoration as well as a to_many to Color :through BirdColoration. If this sounds reasonable, then continue reading. Otherwise, stop and tell me why it's wrong!

I need to be able to dump the birds table as json. Previously, when each bird only had one to_many association to colors, I could just use :include to include each bird's colors in the json dump. Now, I'm including the BirdColorations in the dump, but I still need to get at the color models themselves. I could separately include each bird's colors and colorations and then match them up while parsing, but I would much rather just include each coloration's color directly. Something like

      format.json  { render :json => @birds.to_json(:include => [{:bird_colorations => :color}, :seasons, :habitats, :image_holders]) }

The above doesn't work, however. I think that this should be possible. Can anyone point me in the right direction for how to handle this?

For now, I'll just include each bird's color and colorations separately and match them up in parsing. At least I know that will work.

Thanks!

Body:
If you have a complex JSON structure, it's better to override serializable_hash or as_json in your model than to try to do it all through render :json.

So something like

def serializable_hash(options = nil)
  options ||= {}
  bird = {:name => name, ...}
  bird[:seasons] = seasons.serilizable_hash
  bird[:colors] = ... # whatever complex logic you want to get to the colors
  bird
end

Both functions just need to return a hash.


问:
How to draw jigsaw?
I want to draw jigsaw shape using CAShapeLayer. I know how to draw square but I dont know how to draw that half circle (curves).

答:
I've coded this example using swift and playground.

```<code>import UIKit

let width : CGFloat = 400
let height : CGFloat = 400
let margin : CGFloat = 50

let topLeftCorner = CGPoint(x: 0 + margin, y: 0 + margin)
let topMidle = CGPoint(x: width/2.0, y: 0 + margin)
let topRightCorner = CGPoint(x: width - margin, y: 0 + margin)
let rightMidle = CGPoint(x: width - margin, y: height/2.0)
let bottomRightCorner = CGPoint(x: width - margin, y: height - margin)
let bottomMidle = CGPoint(x: width/2.0, y: height - margin)
let bottomLeftCorner = CGPoint(x: 0 + margin, y: height - margin)
let leftMidle = CGPoint(x: 0 + margin, y: height/2.0)

let jigsawPiece = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
let path = UIBezierPath()

// Starting point
path.move(to: topLeftCorner)

// Draw top circle
path.addArc(withCenter: topMidle, radius: margin, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)

// Draw line to corner
path.addLine(to: topRightCorner)

// Draw right circle
path.addArc(withCenter: rightMidle, radius: margin, startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(3*M_PI/2.0), clockwise: false)

// Draw line to corner
path.addLine(to: bottomRightCorner)

// Draw bottom cut
path.addArc(withCenter: bottomMidle, radius: margin, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)

// Draw line
path.addLine(to: bottomLeftCorner)

// Draw left cut
path.addArc(withCenter: leftMidle, radius: margin, startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(3*M_PI/2.0), clockwise: false)

// Draw line
path.addLine(to: topLeftCorner)
path.close()

let layer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = UIColor.red.cgColor

jigsawPiece.layer .addSublayer(layer)

jigsawPiece
</code>```

This is the output. You can convert it to objective c if necessary.

Title: How to draw jigsaw?

Body:
I've coded this example using swift and playground.

import UIKit

let width : CGFloat = 400
let height : CGFloat = 400
let margin : CGFloat = 50

let topLeftCorner = CGPoint(x: 0 + margin, y: 0 + margin)
let topMidle = CGPoint(x: width/2.0, y: 0 + margin)
let topRightCorner = CGPoint(x: width - margin, y: 0 + margin)
let rightMidle = CGPoint(x: width - margin, y: height/2.0)
let bottomRightCorner = CGPoint(x: width - margin, y: height - margin)
let bottomMidle = CGPoint(x: width/2.0, y: height - margin)
let bottomLeftCorner = CGPoint(x: 0 + margin, y: height - margin)
let leftMidle = CGPoint(x: 0 + margin, y: height/2.0)

let jigsawPiece = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
let path = UIBezierPath()

// Starting point
path.move(to: topLeftCorner)

// Draw top circle
path.addArc(withCenter: topMidle, radius: margin, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)

// Draw line to corner
path.addLine(to: topRightCorner)

// Draw right circle
path.addArc(withCenter: rightMidle, radius: margin, startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(3*M_PI/2.0), clockwise: false)

// Draw line to corner
path.addLine(to: bottomRightCorner)

// Draw bottom cut
path.addArc(withCenter: bottomMidle, radius: margin, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)

// Draw line
path.addLine(to: bottomLeftCorner)

// Draw left cut
path.addArc(withCenter: leftMidle, radius: margin, startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(3*M_PI/2.0), clockwise: false)

// Draw line
path.addLine(to: topLeftCorner)
path.close()

let layer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = UIColor.red.cgColor

jigsawPiece.layer .addSublayer(layer)

jigsawPiece

This is the output. You can convert it to objective c if necessary.


问:
Add animated checkbox to Bootstrap form-check
I'm really bad with CSS animations but I found this great animated checkmark on SO that I'd love to use in my code. But I don't know how to include it in.

This is my html code for checkmark, I'm using Bootstrap 4:

```<code><div class="form-check">
  <label class="custom-control custom-checkbox mb-0">
    <input type="checkbox" class="custom-control-input">
    <span class="custom-control-indicator"></span>
    <span class="custom-control-description">checkmark</span>
  </label>
</div>
</code>```

And here is the animated checkmark Fiddle.

Can someone please let me know how I can include this in my HTML code?

Thank you in advance.

答:
Try as follows.

JS Fiddle

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 2;
  stroke-miterlimit: 10;
  stroke: #7ac142;
  fill: none;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}

.checkmark {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: block;
  stroke-width: 2;
  stroke: #fff;
  stroke-miterlimit: 10;
  margin: 12px;
  box-shadow: inset 0px 0px 0px #7ac142;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
}

.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}

@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}

@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #7ac142;
  }
}

input[type=checkbox] {
  display: none;
}

input[type=checkbox]+svg {
  display: none;
}

input[type=checkbox]:checked+svg {
  display: block;
}

.check-box {
  position: relative;
}

.check-box label {
  display: flex;
  height: 80px;
  align-items: center;
  justify-content: left;
  padding-left: 88px;
}

.check-box label svg {
  position: absolute;
  top: 0;
  left: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  <div class="check-box">
    <label>
      <input type="checkbox" name="item_1" value="item 1" />
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
        <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
        <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      <span>Item 1</span>
    </label>
  </div>

  <div class="check-box">
    <label>
      <input type="checkbox" name="item_2" value="item 2" />
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
        <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
        <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      <span>Item 2</span>
    </label>
  </div>

</form></code>```

Body:
I'm really bad with CSS animations but I found this great animated checkmark on SO that I'd love to use in my code. But I don't know how to include it in.

This is my html code for checkmark, I'm using Bootstrap 4:

    <input type="checkbox" class="custom-control-input">

    checkmark

And here is the animated checkmark Fiddle.

Can someone please let me know how I can include this in my HTML code?

Thank you in advance.

Body:
Try as follows.

JS Fiddle

.checkmark__circle {
  stroke-dasharray: 166;
  stroke-dashoffset: 166;
  stroke-width: 2;
  stroke-miterlimit: 10;
  stroke: #7ac142;
  fill: none;
  animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
}

.checkmark {
  width: 56px;
  height: 56px;
  border-radius: 50%;
  display: block;
  stroke-width: 2;
  stroke: #fff;
  stroke-miterlimit: 10;
  margin: 12px;
  box-shadow: inset 0px 0px 0px #7ac142;
  animation: fill .4s ease-in-out .4s forwards, scale .3s ease-in-out .9s both;
}

.checkmark__check {
  transform-origin: 50% 50%;
  stroke-dasharray: 48;
  stroke-dashoffset: 48;
  animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
}

@keyframes stroke {
  100% {
    stroke-dashoffset: 0;
  }
}

@keyframes scale {
  0%,
  100% {
    transform: none;
  }
  50% {
    transform: scale3d(1.1, 1.1, 1);
  }
}

@keyframes fill {
  100% {
    box-shadow: inset 0px 0px 0px 30px #7ac142;
  }
}

input[type=checkbox] {
  display: none;
}

input[type=checkbox]+svg {
  display: none;
}

input[type=checkbox]:checked+svg {
  display: block;
}

.check-box {
  position: relative;
}

.check-box label {
  display: flex;
  height: 80px;
  align-items: center;
  justify-content: left;
  padding-left: 88px;
}

.check-box label svg {
  position: absolute;
  top: 0;
  left: 0;
}

<form>
  <div class="check-box">
    <label>
      <input type="checkbox" name="item_1" value="item 1" />
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
        <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
        <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      <span>Item 1</span>
    </label>
  </div>

  <div class="check-box">
    <label>
      <input type="checkbox" name="item_2" value="item 2" />
      <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
        <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
        <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
      </svg>
      <span>Item 2</span>
    </label>
  </div>

</form>