问:
Different Display of CSS opacity in Safari Browser
I'm working on a hybrid App for mobile devices in the Ionic-Framework.
I try to make some HTML span look transparent to a certain degree for a defined area.
The HTML and CSS works fine on every android device, but is displayed horribly useless on every Apple Device. Meaning the shady Opacity and the related HTML elements suddenly are displayed at complete different places in the view everytime. The Opacity sometimes effects the whole page. When I delete the related HTML from the view, everything is fine which leads me to the suspicion safari just can't interpret my code the way I want it to.

I suspect a safari bug or some safari quirk to be responsible for the strange display.

Here how it is correct and looks like on android devices: https://ibb.co/diNxxw
And here how its crashed on every iOS device: https://ibb.co/eNfZcw   https://ibb.co/jiPGqG

This is my HTML

```<code><ion-item>
                <ion-label class="label-left-filler" [ngStyle]="{'width': avgRatings[speise.id]?.ratingAverage ? (((avgRatings[speise.id]?.ratingAverage | roundDecimal : avgRatings[speise.id]?.ratingAverage)-1) * (25+5) +13) +'px' : 0 +'px' }">
                </ion-label>
                <ion-label class="label-rating">
                  <span class="span-rating">
                    <span class="span-emojicon">
                      <mat-icon class="mat-icon-one">sentiment_very_dissatisfied</mat-icon>
                      <span class='mat-icon-spacer'></span>
                      <mat-icon class="mat-icon-two">sentiment_dissatisfied</mat-icon>
                      <span class='mat-icon-spacer'></span>
                      <mat-icon class="mat-icon-three">sentiment_neutral</mat-icon>
                      <span class='mat-icon-spacer'></span>
                      <mat-icon class="mat-icon-four">sentiment_satisfied</mat-icon>
                      <span class='mat-icosxn-spacer'></span>
                      <mat-icon class="mat-icon-five">sentiment_very_satisfied</mat-icon>
                    </span>
                  </span>
                </ion-label>
                <ion-label class="label-right-filler" [ngStyle]="{'margin-left': avgRatings[speise.id]?.ratingAverage ? (avgRatings[speise.id]?.ratingAverage | roundDecimal : avgRatings[speise.id]?.ratingAverage) * (25+5) -3 +'px' : 0 +'px' }">
                </ion-label>
              </ion-item>
</code>```

And this is my corresponding CSS

```<code>  .label-rating {
    position: fixed;
    padding-left: 15px;
    top: 0px;
    left: 0px;
    background: rgba(255, 255, 255, 0);
    z-index: 1;
  }
  .label-left-filler {
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    z-index: 2;
  }
  .label-right-filler {
    top: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    z-index: 2;
  }
  .mat-icon-one {
    background: radial-gradient(
      red $mat-icon-radial-gradient-inner,
      white $mat-icon-radial-gradient-outer
    );
  }
  span > .mat-icon {
    font-size: $mat-icon-font-size;
    width: $mat-icon-width;
    height: $mat-icon-height;
    color: rgb(0, 0, 0);
    -webkit-mask-size: cover;
  }
  h2 span.mat-icon-spacer {
    padding: 0 $mat-icon-spacer-padding;
    background: white;
  }
</code>```

答:
To be more cross-browser friendly, you can use the opacity element, and increase compatibility using browser-specific settings. </p>

```<code>opacity: 0.5; /* Standard compliant browsers */
   -moz-opacity: 0.5; /* Firefox and Mozilla browsers */
   -webkit-opacity: 0.5; /* WebKit browser e.g. Safari */
   filter: alpha(opacity=50); /* For IE8 and earlier */
</code>```

Body:
I'm working on a hybrid App for mobile devices in the Ionic-Framework.
I try to make some HTML span look transparent to a certain degree for a defined area.
The HTML and CSS works fine on every android device, but is displayed horribly useless on every Apple Device. Meaning the shady Opacity and the related HTML elements suddenly are displayed at complete different places in the view everytime. The Opacity sometimes effects the whole page. When I delete the related HTML from the view, everything is fine which leads me to the suspicion safari just can't interpret my code the way I want it to.

I suspect a safari bug or some safari quirk to be responsible for the strange display.

Here how it is correct and looks like on android devices: https://ibb.co/diNxxw
And here how its crashed on every iOS device: https://ibb.co/eNfZcw   https://ibb.co/jiPGqG

This is my HTML

<ion-item>
                <ion-label class="label-left-filler" [ngStyle]="{'width': avgRatings[speise.id]?.ratingAverage ? (((avgRatings[speise.id]?.ratingAverage | roundDecimal : avgRatings[speise.id]?.ratingAverage)-1) * (25+5) +13) +'px' : 0 +'px' }">
                </ion-label>
                <ion-label class="label-rating">

                      <mat-icon class="mat-icon-one">sentiment_very_dissatisfied</mat-icon>

                      <mat-icon class="mat-icon-two">sentiment_dissatisfied</mat-icon>

                      <mat-icon class="mat-icon-three">sentiment_neutral</mat-icon>

                      <mat-icon class="mat-icon-four">sentiment_satisfied</mat-icon>

                      <mat-icon class="mat-icon-five">sentiment_very_satisfied</mat-icon>

                </ion-label>
                <ion-label class="label-right-filler" [ngStyle]="{'margin-left': avgRatings[speise.id]?.ratingAverage ? (avgRatings[speise.id]?.ratingAverage | roundDecimal : avgRatings[speise.id]?.ratingAverage) * (25+5) -3 +'px' : 0 +'px' }">
                </ion-label>
              </ion-item>

And this is my corresponding CSS

  .label-rating {
    position: fixed;
    padding-left: 15px;
    top: 0px;
    left: 0px;
    background: rgba(255, 255, 255, 0);
    z-index: 1;
  }
  .label-left-filler {
    position: fixed;
    top: 0px;
    left: 0px;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    z-index: 2;
  }
  .label-right-filler {
    top: 0px;
    right: 0px;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    z-index: 2;
  }
  .mat-icon-one {
    background: radial-gradient(
      red $mat-icon-radial-gradient-inner,
      white $mat-icon-radial-gradient-outer
    );
  }
  span > .mat-icon {
    font-size: $mat-icon-font-size;
    width: $mat-icon-width;
    height: $mat-icon-height;
    color: rgb(0, 0, 0);
    -webkit-mask-size: cover;
  }
  h2 span.mat-icon-spacer {
    padding: 0 $mat-icon-spacer-padding;
    background: white;
  }

Body:
To be more cross-browser friendly, you can use the opacity element, and increase compatibility using browser-specific settings.

opacity: 0.5; /* Standard compliant browsers */
   -moz-opacity: 0.5; /* Firefox and Mozilla browsers */
   -webkit-opacity: 0.5; /* WebKit browser e.g. Safari */
   filter: alpha(opacity=50); /* For IE8 and earlier */


来源: stackexchange

问:
How to use rc.exe with MSBuild in a .NET project
In a MSBuild project file for a .NET app, I’ve been using rc.exe, and I called it using the Exec task, and I retrieved the path to rc.exe from WindowsSDK80Path.

This worked fine with Visual Studio 2015, however with VS2017 (without having VS2015 installed), WindowsSDK80Path points to a non-existing directory. Unfortunately, I did not find a way to retrieve the new installation path, which on my machine happens to be C:\Program Files (x86)\Windows Kits\10.

I don’t know how to use the RC task, and I don’t know if it’s the right thing to use, because the documentation says, “Tasks Specific to Visual C++”.

How can I use rc.exe so that it works with both VS2015 and VS2017 and, if possible, with the next version of Visual Studio as well?

(Note that GetFrameworkPath doesn’t retrieve a suitable path.)

答:
I came up with this: An Exec task calls a PowerShell script, that looks in the registry in HKLM\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows for the SDK with the largest version number, retrieves the installation path, and then calls from that path the first rc.exe it encounters that is beneath a x86 directory.

A little bit ugly, but it works.

ContentLicense: CC BY-SA 3.0


问:
How use Laravel Language Translation in controller as constant?
Is it possible to use Laravel Language Translator (Localization) in controller as constant? Below attempt, example that does not work:</p>

```<code>class SearchApproval extends Controller
{
    private $request;

    const stage_1 = Lang::get('message.failed');
</code>```

答: Use trans('message.failed') instead of Lang::get('message.failed') https://laravel.com/docs/5.5/helpers#method-trans

Body:
Is it possible to use Laravel Language Translator (Localization) in controller as constant? Below attempt, example that does not work:

class SearchApproval extends Controller
{
    private $request;

    const stage_1 = Lang::get('message.failed');


问:
How use liferay validator with js submit?
I try to use Liferay validator with javascript on Liferay 6.2.

Have a problem is my button must using submit form with a button onlick, but when submit this way Liferay form validator no trigger prevent submit. It just triggers when I using a button type submit.

Here mycode example:

```<code> <portlet:actionURL name="updateURL" var="submitURL"/>

<aui:form name="fm2" id="fm2" action="<%=submitURL %>" method="post">
    <aui:input name="userName" value='' label="User Name"></aui:input>
    <aui:input name="password" value='' label="Password"></aui:input>

    <aui:button type="button" name="logIn" id="logIn" value="Login" />
</aui:form>
<aui:script>
AUI().use('aui-base','liferay-form','aui-form-validator',function(A){

    A.one("#<portlet:namespace/>logIn").on("click",function(){
        submitForm(document.<portlet:namespace />fm2);
    });

    Liferay.Form.register(
        {
            id: '<portlet:namespace/>fm2',
            fieldRules: [
                            {
                                body: '',
                                custom: false,
                                errorMessage: '',
                                fieldName: '<portlet:namespace/>password',
                                validatorName: 'required'
                            },

                            {
                                body: '',
                                custom: false,
                                errorMessage: '',
                                fieldName: '<portlet:namespace/>userName',
                                validatorName: 'required'
                            }
                ]

        });
    });
</aui:script>
</code>```

What i can do ?

How to liferay can prevent event submit with tag, but does not with js?

Here is AUIFormValidator-portlet to demo.

https://drive.google.com/open?id=0B27gY2oYFX7QTTFFdXc3TnZ4d1k

答:
You can do one thing,

```<code><aui:form name="fm2" id="fm2" action="javascript:void(0)" method="post">
</code>```

It will prevent your submit event and fire the aui form validation.

Now in onClick function you can assign your submit url to form action like below.

```<code> $("#<portlet:namespace/>logIn").on("click",function(){
    var url = '${submitURL}';
    $('#<portlet:namespace />fm2').attr('action', url);
    $('#<portlet:namespace />fm2').trigger("submit");
 });
</code>```

Body:
I try to use Liferay validator with javascript on Liferay 6.2.

Have a problem is my button must using submit form with a button onlick, but when submit this way Liferay form validator no trigger prevent submit. It just triggers when I using a button type submit.

Here mycode example:

 <portlet:actionURL name="updateURL" var="submitURL"/>

<aui:form name="fm2" id="fm2" action="<%=submitURL %>" method="post">
    <aui:input name="userName" value='' label="User Name"></aui:input>
    <aui:input name="password" value='' label="Password"></aui:input>

    <aui:button type="button" name="logIn" id="logIn" value="Login" />
</aui:form>
<aui:script>
AUI().use('aui-base','liferay-form','aui-form-validator',function(A){

    A.one("#<portlet:namespace/>logIn").on("click",function(){
        submitForm(document.<portlet:namespace />fm2);
    });

    Liferay.Form.register(
        {
            id: '<portlet:namespace/>fm2',
            fieldRules: [
                            {
                                body: '',
                                custom: false,
                                errorMessage: '',
                                fieldName: '<portlet:namespace/>password',
                                validatorName: 'required'
                            },

                            {
                                body: '',
                                custom: false,
                                errorMessage: '',
                                fieldName: '<portlet:namespace/>userName',
                                validatorName: 'required'
                            }
                ]

        });
    });
</aui:script>

What i can do ?

How to liferay can prevent event submit with tag, but does not with js?

Here is AUIFormValidator-portlet to demo.

https://drive.google.com/open?id=0B27gY2oYFX7QTTFFdXc3TnZ4d1k

Body:
You can do one thing,

<aui:form name="fm2" id="fm2" action="javascript:void(0)" method="post">

It will prevent your submit event and fire the aui form validation.

Now in onClick function you can assign your submit url to form action like below.

 $("#<portlet:namespace/>logIn").on("click",function(){
    var url = '${submitURL}';
    $('#<portlet:namespace />fm2').attr('action', url);
    $('#<portlet:namespace />fm2').trigger("submit");
 });


问:
Correct dateFormat for String ending .629Z
I am getting this date string from a API "2017-11-25T20:41:00.629Z"

I am trying to convert it into Date type, but I  can't find the -> .629Z representation online

```<code>dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
</code>```

apparently this is not working and I get nil when I am converting the String into Date. I tried different things but .... !

Any idea ?

Thanks

答:
You can specify milliseconds using SSS for your date format with 3 digit milliseconds precision.

```<code>let dateString = "2017-11-25T20:41:00.629Z"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
df.locale = Locale(identifier: "en_US_POSIX")
df.date(from: dateString) // "Nov 25, 2017 at 8:41 PM"
</code>```

Body:
I am getting this date string from a API "2017-11-25T20:41:00.629Z"

I am trying to convert it into Date type, but I  can't find the -> .629Z representation online

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

apparently this is not working and I get nil when I am converting the String into Date. I tried different things but .... !

Any idea ?

Thanks

Body:
You can specify milliseconds using SSS for your date format with 3 digit milliseconds precision.

let dateString = "2017-11-25T20:41:00.629Z"
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
df.locale = Locale(identifier: "en_US_POSIX")
df.date(from: dateString) // "Nov 25, 2017 at 8:41 PM"


问:
error while loading the webview
I am using a webview in my fragment.

```<code>private void LoadWebView()
{
    privacy_Webview.getSettings().setJavaScriptEnabled(true);
    privacy_Webview.setWebViewClient(new WebViewClient());
    privacy_Webview.loadUrl("http://www.google.com");
}
</code>```

I am getting the error

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.webkit.WebSettings android.webkit.WebView.getSettings()' on a null object reference
</code>```

The error is occurred at the line :-
 privacy_Webview.getSettings().setJavaScriptEnabled(true);

On a button click from one fragment this fragment gets load in which it has the web view.

I cant figure out the issue.

答: It seems like your fragment_forgot_password doesn't contain wv_privacy, so rootView.findViewById(R.id.wv_privacy) returns null.

Title: error while loading the webview

Body:
I am using a webview in my fragment.

private void LoadWebView()
{
    privacy_Webview.getSettings().setJavaScriptEnabled(true);
    privacy_Webview.setWebViewClient(new WebViewClient());
    privacy_Webview.loadUrl("http://www.google.com");
}

I am getting the error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.webkit.WebSettings android.webkit.WebView.getSettings()' on a null object reference

The error is occurred at the line :-
 privacy_Webview.getSettings().setJavaScriptEnabled(true);

On a button click from one fragment this fragment gets load in which it has the web view.

I cant figure out the issue.


问:
Python indexing numpy array using a smaller boolean array
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

If obj.ndim == x.ndim, x[obj] returns a 1-dimensional array filled
  with the elements of x corresponding to the True values of obj. The
  search order will be row-major, C-style. If obj has True values at
  entries that are outside of the bounds of x, then an index error will
  be raised. If obj is smaller than x it is identical to filling it with
  False.

I read from the numpy reference that I can index a larger array using a smaller boolean array ,and the rest entries would be automatically filled with False.

Example :
  From an array, select all rows which sum up to less or equal two:

```<code>>>> x = np.array([[0, 1], [1, 1], [2, 2]])
>>> rowsum = x.sum(-1)
>>> x[rowsum <= 2, :]
array([[0, 1],[1, 1]])
</code>```

But if rowsum would have two dimensions as well:

```<code>>>> rowsum = x.sum(-1, keepdims=True)
>>> rowsum.shape
(3, 1)
>>> x[rowsum <= 2, :]    # fails
IndexError: too many indices
>>> x[rowsum <= 2]
array([0, 1])
</code>```

The last one giving only the first elements because of the extra
  dimension.

But the example simply doesn't work ,it says "IndexError: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1"

How to make it work ?I'm using python 3.6.3 and numpy 1.13.3.

答:
From Numpy 11, It's not compatible with the new default behaviour : (boolean-indexing-changes) :

Boolean indexing changes.

...

...

Boolean indexes must match the dimension of the axis that
they index.

...

Internals have been optimized, the docs not yet ....

Body:
https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

If obj.ndim == x.ndim, x[obj] returns a 1-dimensional array filled
  with the elements of x corresponding to the True values of obj. The
  search order will be row-major, C-style. If obj has True values at
  entries that are outside of the bounds of x, then an index error will
  be raised. If obj is smaller than x it is identical to filling it with
  False.

I read from the numpy reference that I can index a larger array using a smaller boolean array ,and the rest entries would be automatically filled with False.

Example :
  From an array, select all rows which sum up to less or equal two:

>>> x = np.array([[0, 1], [1, 1], [2, 2]])
>>> rowsum = x.sum(-1)
>>> x[rowsum <= 2, :]
array([[0, 1],[1, 1]])

But if rowsum would have two dimensions as well:

>>> rowsum = x.sum(-1, keepdims=True)
>>> rowsum.shape
(3, 1)
>>> x[rowsum <= 2, :]    # fails
IndexError: too many indices
>>> x[rowsum <= 2]
array([0, 1])

The last one giving only the first elements because of the extra
  dimension.

But the example simply doesn't work ,it says "IndexError: boolean index did not match indexed array along dimension 1; dimension is 2 but corresponding boolean dimension is 1"

How to make it work ?I'm using python 3.6.3 and numpy 1.13.3.


问:
Unpair bluetooth Android with dependency service
I need to unpair bluetooth after a installation has been made and i've tried this code:

```<code>string address;

    public void UnpairDroid()
    {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
        BluetoothDevice bluetoothDevice = bluetoothAdapter.GetRemoteDevice(address);
        var mi = bluetoothDevice.Class.GetMethod("removeBond", null);
        mi.Invoke(bluetoothDevice, null);
    }
</code>```

It throws an exception when it reaches that code because object (string address) is not set. Do I need to verify the address towards the bluetooth api?

Ive spend hours to find a solution but no ideas left. Please help! Thanks.

Is this a better approach?

```<code>BluetoothDevice device;
private void unpairDevice() {
try {
    Method m = device.getClass()
        .getMethod("removeBond", (Class[]) null);
    m.invoke(device, (Object[]) null);
} catch (Exception e) {
    Log.e(TAG, e.getMessage());
}}
</code>```

I have not gotten that code to work though..

答:
Local address can be got by bluetoothAdapter.Address , remote address can be got by</p>

```<code>    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
    List<BluetoothDevice> bondedDevices = new List<BluetoothDevice>(bluetoothAdapter.BondedDevices);
    if (bondedDevices.Count > 0)
    {
        foreach (BluetoothDevice device in bondedDevices)
        {
            System.Diagnostics.Debug.Write("Name="+device.Name+" Address="+device.Address);
            BluetoothDevice bluetoothDevice = bluetoothAdapter.GetRemoteDevice(device.Address);
            var mi = bluetoothDevice.Class.GetMethod("removeBond", null);
            mi.Invoke(bluetoothDevice, null);

        }
    }
}
</code>```

Body:
I need to unpair bluetooth after a installation has been made and i've tried this code:

string address;

    public void UnpairDroid()
    {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
        BluetoothDevice bluetoothDevice = bluetoothAdapter.GetRemoteDevice(address);
        var mi = bluetoothDevice.Class.GetMethod("removeBond", null);
        mi.Invoke(bluetoothDevice, null);
    }

It throws an exception when it reaches that code because object (string address) is not set. Do I need to verify the address towards the bluetooth api?

Ive spend hours to find a solution but no ideas left. Please help! Thanks.

Is this a better approach?

BluetoothDevice device;
private void unpairDevice() {
try {
    Method m = device.getClass()
        .getMethod("removeBond", (Class[]) null);
    m.invoke(device, (Object[]) null);
} catch (Exception e) {
    Log.e(TAG, e.getMessage());
}}

I have not gotten that code to work though..

Body:
Local address can be got by bluetoothAdapter.Address , remote address can be got by

    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
    List<BluetoothDevice> bondedDevices = new List<BluetoothDevice>(bluetoothAdapter.BondedDevices);
    if (bondedDevices.Count > 0)
    {
        foreach (BluetoothDevice device in bondedDevices)
        {
            System.Diagnostics.Debug.Write("Name="+device.Name+" Address="+device.Address);
            BluetoothDevice bluetoothDevice = bluetoothAdapter.GetRemoteDevice(device.Address);
            var mi = bluetoothDevice.Class.GetMethod("removeBond", null);
            mi.Invoke(bluetoothDevice, null);

        }
    }
}


答:
Just found it after aaaa loooot of time

"yyyy-MM-dd'T'HH:mm:ss'.'SSSz"

Thanks

Title: Correct dateFormat for String ending .629Z


问:
Passing strings between activities, intents not working
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

```<code>    String Name,Pass,tokenString;

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

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}
</code>```

here is the code for the home activity (the relevant bits) :

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }
</code>```

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

答:
You are not adding bundle (extras) when calling the activity
For example </p>

```<code>Intent intent = new Intent(this, Home.class);
intent.putExtra("Token", "XXX-YYY-ZZZ");  //Imp
startActivity(intent);
</code>```

Body:
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

    String Name,Pass,tokenString;

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

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}

here is the code for the home activity (the relevant bits) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

Body:
You are not adding bundle (extras) when calling the activity
For example

Intent intent = new Intent(this, Home.class);
intent.putExtra("Token", "XXX-YYY-ZZZ");  //Imp
startActivity(intent);


问:
Zebra Stripe using CSS
I am trying to achieve the below stripe pattern, but none of the nth-child combination is working out. Any suggestion / solution to achieve this.

答:
You can do it like this:

.parent {
  display: flex;
  flex-wrap: wrap;
}

.child {
  flex-basis: 50%;
  height: 25px;
  background: #7F7F7F;
}

.child:nth-child(4n+1),
.child:nth-child(4n+4) {
  background: #FF0080;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div></code>```

The point is to see after how many div elements (.child) the pattern repeats, this is the first number or 4n, then just set the first and fourth to be of the same color with the +1 and +4.

Title: Zebra Stripe using CSS

Body:
You can do it like this:

.parent {
  display: flex;
  flex-wrap: wrap;
}

.child {
  flex-basis: 50%;
  height: 25px;
  background: #7F7F7F;
}

.child:nth-child(4n+1),
.child:nth-child(4n+4) {
  background: #FF0080;
}

<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

The point is to see after how many div elements (.child) the pattern repeats, this is the first number or 4n, then just set the first and fourth to be of the same color with the +1 and +4.

ContentLicense: CC BY-SA 4.0


问:
Get raw JSON Data of REST request in RestSharp
I use RestSharp to access a Sever API.

```<code>RestClient client = new RestClient(serverUrl);

JObject parameters = new JObject
        {
           new JProperty("Param1", p1),
           new JProperty("Param2", p2)
        };

RestRequest request = new RestRequest("/Foo", Method.POST);
request.AddParameter("application/json; charset=UTF-8", parameters, ParameterType.RequestBody);
</code>```

Is there a way to get the raw JSON Data of the REST request in RestSharp?

答: At this moment the answer is no. All parts of the actual request, including URL with query parameters, body and headers are only constructed in the ConfigureHttp private method.

Body:
I use RestSharp to access a Sever API.

RestClient client = new RestClient(serverUrl);

JObject parameters = new JObject
        {
           new JProperty("Param1", p1),
           new JProperty("Param2", p2)
        };

RestRequest request = new RestRequest("/Foo", Method.POST);
request.AddParameter("application/json; charset=UTF-8", parameters, ParameterType.RequestBody);

Is there a way to get the raw JSON Data of the REST request in RestSharp?


问:
scikit learn averaged perceptron classifier
I am a new learner to machine learning and I want to do a 2-class classification with only a few attributes. I have learned by researching online that two-class averaged perceptron algorithm is good for two-class classification with a linear model.

However, I have been reading through the documentation of Scikit-learn, and I am a bit confused if Scikit-learn is providing a averaged perceptron algorithm.

I wonder if the sklearn.linear_model.Perceptron class can be implemented as the two-class averaged perceptron algorithm by setting up the parameters correctly.

I appreciate it very much for your kind help.

答:
I'm sure someone will correct me if I'm wrong but I do not believe Averaged Perceptron is implemented in sklearn.  If I recall correctly, Perceptron in sklearn is simply SGD with certain default parameters.

With that said, have you tried good old logistic regression?  While it may not be the sexiest algorithm around, it often does provide good results and can serve as a baseline to see if you need to explore more complicated methods.


问:
jqGrid filter or search by date not working client side
I have an ASP.NET MVC 3 page.  On it, I have a table which I turn into a jqGrid using JSON data from an ajax call.  The grid has the following setup:

```<code>myGrid = $('#myGrid');
myGrid.jqGrid({
    caption: 'My Grid',
    datatype: 'local',
    data: data.rows,
    height: 250,
    pager: '#myPager',
    viewrecords: true,
    colModel: [
        ...,
        {
            label: 'blah',
            name: 'blah',
            align: 'left',
            sortable: true,
            editable: false,
            width: 85,
            formatter: 'date',
            sorttype: 'date',
            datefmt: 'm/d/Y',
            formatoptions: { srcformat: 'm/d/Y', newformat: 'm/d/Y' }
        },
        ...
    ]
});

// turn on filter toolbar
myGrid.filterToolbar();
</code>```

data.rows is returned from the ajax call.  This works in all ways except one.  I can paginate client-side, sort client side, and search by every field except the one I show the colModel for.  This 'blah' field is a date field, and it displays the dates correctly, in mm/dd/yyyy format.  However, when I type in something like 11/17/2010 into the toolbar and press enter, the search returns 0 records.

So I dug deep into the jqGrid code, and here's what it generates before it searches:

```<code>{"groupOp":"AND","rules":[{"field":"blah","op":"bw","data":"11/17/2010"}]}
</code>```

Eventually, when it goes through every row and it evaluates the operation on the field, the eval(m) && p.push(this) line, m is this:

```<code>(String(this.blah).substr(0,10) == String("11/17/2010"))
</code>```

Basically, it looks to me like it's not recognizing that the field is a date.  It calls parse instead of parseDate.  Anybody have any ideas how to fix this?  I know searching server side is easy, I can just pass that string, parse it, and bam.  But I'd like to stay client side if I can.  I was able to duplicate this in some of the samples that Oleg and Tom put up, so it's either an issue or I'm missing something in the configuration...

答:
I find your question interesting so +1 from me to your question. Because you posted the line

```<code>(String(this.blah).substr(0,10) == String("11/17/2010"))
</code>```

used in eval during the local searching I suppose you spend much time to understand how the local searching are implemented. Because you see that the line above (see (String(this.blah).substr(0,10) ...) is not what should be done (the value of String(this.blah) will be "2010-11-17" instead of "11/17/2010"), you can overwrite the corresponding function of jqGrid (the function _getStr inside of $.jgrid.from) and fix the problem in the way.

Some time ago I spend much time to prepare the corresponding the demo, which demonstrates this technique. The demo was prepared as the answer in trirand forum. In the question one wanted to find strings like 'bénevise' in case of searching for 'benevise'. So one have to implement really custom local searching. I hope that the information will be enough for you to fix the problem which you describe.

UPDATED: It seems to me that I have found a much more simple workaround. You should just define searchoptions: {sopt: ['eq','ne']} for the 'blah' column having the data. Then "bw" (begin with) will not used for the column. The "equal to" and "not equal to" operations work correctly in the local searching.

UPDATED 2: Here is the working example where I use sopt option.

ContentLicense: CC BY-SA 2.5

Body:
I have an ASP.NET MVC 3 page.  On it, I have a table which I turn into a jqGrid using JSON data from an ajax call.  The grid has the following setup:

myGrid = $('#myGrid');
myGrid.jqGrid({
    caption: 'My Grid',
    datatype: 'local',
    data: data.rows,
    height: 250,
    pager: '#myPager',
    viewrecords: true,
    colModel: [
        ...,
        {
            label: 'blah',
            name: 'blah',
            align: 'left',
            sortable: true,
            editable: false,
            width: 85,
            formatter: 'date',
            sorttype: 'date',
            datefmt: 'm/d/Y',
            formatoptions: { srcformat: 'm/d/Y', newformat: 'm/d/Y' }
        },
        ...
    ]
});

// turn on filter toolbar
myGrid.filterToolbar();

data.rows is returned from the ajax call.  This works in all ways except one.  I can paginate client-side, sort client side, and search by every field except the one I show the colModel for.  This 'blah' field is a date field, and it displays the dates correctly, in mm/dd/yyyy format.  However, when I type in something like 11/17/2010 into the toolbar and press enter, the search returns 0 records.

So I dug deep into the jqGrid code, and here's what it generates before it searches:

{"groupOp":"AND","rules":[{"field":"blah","op":"bw","data":"11/17/2010"}]}

Eventually, when it goes through every row and it evaluates the operation on the field, the eval(m) && p.push(this) line, m is this:

(String(this.blah).substr(0,10) == String("11/17/2010"))

Basically, it looks to me like it's not recognizing that the field is a date.  It calls parse instead of parseDate.  Anybody have any ideas how to fix this?  I know searching server side is easy, I can just pass that string, parse it, and bam.  But I'd like to stay client side if I can.  I was able to duplicate this in some of the samples that Oleg and Tom put up, so it's either an issue or I'm missing something in the configuration...

Body:
I find your question interesting so +1 from me to your question. Because you posted the line

(String(this.blah).substr(0,10) == String("11/17/2010"))

used in eval during the local searching I suppose you spend much time to understand how the local searching are implemented. Because you see that the line above (see (String(this.blah).substr(0,10) ...) is not what should be done (the value of String(this.blah) will be "2010-11-17" instead of "11/17/2010"), you can overwrite the corresponding function of jqGrid (the function _getStr inside of $.jgrid.from) and fix the problem in the way.

Some time ago I spend much time to prepare the corresponding the demo, which demonstrates this technique. The demo was prepared as the answer in trirand forum. In the question one wanted to find strings like 'bénevise' in case of searching for 'benevise'. So one have to implement really custom local searching. I hope that the information will be enough for you to fix the problem which you describe.

UPDATED: It seems to me that I have found a much more simple workaround. You should just define searchoptions: {sopt: ['eq','ne']} for the 'blah' column having the data. Then "bw" (begin with) will not used for the column. The "equal to" and "not equal to" operations work correctly in the local searching.

UPDATED 2: Here is the working example where I use sopt option.


答:
After getting response from server , you are calling launchHomeActivity method only. But you setting data in "createIntent" method only. i think that is the issue. I have edited the launchHomeActivity method.</p>

```<code>    private void launchHomeActivity() {

     Intent intent = new Intent(this, Home.class);
    intent .putExtra("Token", getToken());
    startActivity(intent);
  }
</code>```

Title: Passing strings between activities, intents not working

Body:
After getting response from server , you are calling launchHomeActivity method only. But you setting data in "createIntent" method only. i think that is the issue. I have edited the launchHomeActivity method.

    private void launchHomeActivity() {

     Intent intent = new Intent(this, Home.class);
    intent .putExtra("Token", getToken());
    startActivity(intent);
  }


问:
No application found with flask sqlalchemy
I'm new to Flask and I'm trying to connect a local postgre database with python.

My code is below:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/flaskmovie'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

@app.route('/')
def index():
    return "Hello Flask"

if __name__ == "__main__":
    app.run()
</code>```

The error I'm getting is:

```<code>'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
</code>```

I've read the documentation and tried different options such as:

```<code>def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app
</code>```

and running the following code in the python shell:

```<code>app = create_app()
app.app_context().push()
</code>```

But i'm still getting the same error.

Any hints?

答:
Try the following:

```<code>with app.app_context():
    db.init_app(app)
</code>```

See here for more information.

Body:
I'm new to Flask and I'm trying to connect a local postgre database with python.

My code is below:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres@localhost/flaskmovie'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

@app.route('/')
def index():
    return "Hello Flask"

if __name__ == "__main__":
    app.run()

The error I'm getting is:

'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.

I've read the documentation and tried different options such as:

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app

and running the following code in the python shell:

app = create_app()
app.app_context().push()

But i'm still getting the same error.

Any hints?

Body:
Try the following:

with app.app_context():
    db.init_app(app)

See here for more information.


问:
Firebase notification not working on iOS 11.1
I am using swift 2.3 and Xcode 8

I tried to upgrade to Firebase v4 then came to know, v4 supports only swift 3. But my entire project is in Swift v2.3 and Its very difficult to change everything so I want to keep in Swift v2.3 only.

So I am using Firebase 3x series.

I tried Firebase iOS kit v3.10, v3.12 and v3.16

All works perfectly fine with lower iOS 10x and higher 11.1.1

but not receiveing notification on 11.1

Do I need to do anything from my end or is it firebase issue ?

To Upgrade to Firebase v4, need to upgrade Swift to v3 or v4

To upgrade to Swift v4, need to upgrade Xcode to v9

To upgrade to Xcode v9, need to upgrade Mac os to 10.12

So, What is the stable version of Firebase 3.x series compatible with

swift 2.3 and iOS 11.1

答:
Same problem last week.

I resolved this by adding "content_available" = true in my push messages.

Take a look at : https://firebase.google.com/docs/cloud-messaging/http-server-ref


问:
Use JS map/reduce to merge array of objects instead of forEach
I'm trying to learn better use of JS functions and I have a feeling what I'm after can be done using reduce or map or both, but I simply cannot find examples of this particular scenario:

I have an array of objects, eg:

```<code>const data =  [
    {
        "member": "111111",
        "offers": 0,
        "categories": 0,
        "total": 100,
        "favorites": 0
    },
    {
        "member": "111111",
        "offers": 2,
        "categories": 1,
        "total": 400,
        "favorites": 1
    },
    {
        "member": "222222",
        "offers": 1,
        "categories": 0,
        "total": 50,
        "favorites": 5
    }
]
</code>```

The goal is to reduce to an array that merges all the key values into ONE array for each member, ie:

```<code>    {
        "member": "111111",
        "offers": 2,
        "categories": 1,
        "total": 500,
        "favorites": 1
    },
    {
        "member": "222222",
        "offers": 1,
        "categories": 0,
        "total": 50,
        "favorites": 5
    },
</code>```

Therefore, there were two entries for member 111111, they have been merged and all the other values summed into a single array.

Honestly, everything I've tried is a mess, so apart from using the boring for loops or adding code here that is clearly rubbish, I hope you can point me in the right direction.

答:
Heres another example with just a reduce and indexOf

const data =  [
    {
        "member": "111111",
        "offers": 0,
        "categories": 0,
        "total": 100,
        "favorites": 0
    },
    {
        "member": "111111",
        "offers": 2,
        "categories": 1,
        "total": 400,
        "favorites": 1
    },
    {
        "member": "222222",
        "offers": 1,
        "categories": 0,
        "total": 50,
        "favorites": 5
    }
]

const merge = (target, props) => {
  for(p in props){
    if(p !== 'member') {
      target[p] += props[p]
    }
  }
  return target
}

const a = data.reduce((res, d) => {
  const idx = res.findIndex(r => r.member === d.member)
  if (idx >= 0) {
    const newRes = merge(res[idx], {...d})
    res.splice(res[idx], 1, newRes)
  } else {
    res.push(d)
  }
  return res
}, [])

console.log(a)```

Body:
I'm trying to learn better use of JS functions and I have a feeling what I'm after can be done using reduce or map or both, but I simply cannot find examples of this particular scenario:

I have an array of objects, eg:

const data =  [
    {
        "member": "111111",
        "offers": 0,
        "categories": 0,
        "total": 100,
        "favorites": 0
    },
    {
        "member": "111111",
        "offers": 2,
        "categories": 1,
        "total": 400,
        "favorites": 1
    },
    {
        "member": "222222",
        "offers": 1,
        "categories": 0,
        "total": 50,
        "favorites": 5
    }
]

The goal is to reduce to an array that merges all the key values into ONE array for each member, ie:

    {
        "member": "111111",
        "offers": 2,
        "categories": 1,
        "total": 500,
        "favorites": 1
    },
    {
        "member": "222222",
        "offers": 1,
        "categories": 0,
        "total": 50,
        "favorites": 5
    },

Therefore, there were two entries for member 111111, they have been merged and all the other values summed into a single array.

Honestly, everything I've tried is a mess, so apart from using the boring for loops or adding code here that is clearly rubbish, I hope you can point me in the right direction.


问:
what's the 'marks' file in repo folder generated by svn-all-fast-export for?
I am using the svn2git tool namely svn-all-fast-export written by the KDE guys to migrate some repos from SVN to Git. Sources are available at github

In the resulting Git bare folder, there is a file marks-<reponame>. It contains entries like:

```<code>:13 3072a401f97757160dc0943d287328feed97b838
:14 d5f658e7ca286ba4b05ddd28cad1dae486ff5a00
:15 b01559e660078de3c614cdd8a72398d8a6cd74b1
:16 2e4efc6ecbe8cc619f2df403d0ac2664041acbbe
(...)
:18446744073709551613 8f4c22ee321fbb452fede97933ce7078a4fda9ab
:18446744073709551614 339edf4fad5c4ca4a42feaae194c002fac220ead
</code>```

I don't expect a file like this to remains in that folder.

I have two questions:

Is it safe to delete it ?

What is it used for ?

答:
If you finished the migration, you can safely delete it.

It is used to run in multiple steps. The file contains information that svn2git needs to correctly proceed in such a case.

It cannot delete the file itself, because you might do the run, then there are 50 additional SVN commits and you continue from where you stopped, then the marks file is needed to not have to run from scratch again.

Body:
I am using the svn2git tool namely svn-all-fast-export written by the KDE guys to migrate some repos from SVN to Git. Sources are available at github

In the resulting Git bare folder, there is a file marks-<reponame>. It contains entries like:

:13 3072a401f97757160dc0943d287328feed97b838
:14 d5f658e7ca286ba4b05ddd28cad1dae486ff5a00
:15 b01559e660078de3c614cdd8a72398d8a6cd74b1
:16 2e4efc6ecbe8cc619f2df403d0ac2664041acbbe
(...)
:18446744073709551613 8f4c22ee321fbb452fede97933ce7078a4fda9ab
:18446744073709551614 339edf4fad5c4ca4a42feaae194c002fac220ead

I don't expect a file like this to remains in that folder.

I have two questions:

Is it safe to delete it ?

What is it used for ?


问:
How Facebook link preview happens?
When you type a URL into facebook, it automatically comes up with the "post a link" feature. With most websites, it automatically loads a selection of images it pulls from somewhere in the page to go alongside the link and description. does anyone have an idea of how to implement that same feature for our own site without any FB API etc.. just javascript or JQuery ?</p>

答:
Due to security restrictions, JavaScript cannot load any page from any server. Facebook actually asks the Facebook servers for information about that page, and the servers in turn query the page to extract the information. You, too, will need a server-side implementation of this.

Aside from that, it's fairly simple: use an HTTP client library for your language of choice to connect to the provided URL, then use an HTML parsing library to extract the title tag, identify a significant piece of text in the body tag, and extract the img tag sources that seem the most appropriate.

Once your server is able to extract information about a page, it's a fairly simple exercise to call it through AJAX.

Title: How Facebook link preview happens?


问:
"is unavailable" error for elements in viewController file
In my new quest to learn objective c, I have can't get past the error in my viewController that a button (which I have declared in the header file - IBOutlet) is unavailable.

in the header.h file:

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

@interface MessageContactViewController : TTTemplateViewController
{
    __weak IBOutlet UIButton *showBtn;
    __weak IBOutlet UIView *photoView;
}
@end
</code>```

code in .m file

```<code>import "header.h"
@implementation MessageContactViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_IOS_7) {
        [showBtn.titleLabel setFont:[UIFont fontWithName:FONT_GOTHAM_BOOK size:17]]; // this gives the error: "showBtn" is unavailable
    //some extra code for labels and button

}
</code>```

Please help me out in this and forgive my ignorance.

答:
not only IBOUTLET you also give connection in xib then check (OR)

UIbutton *imgBtn = (UIButton*)[self.view viewWithTag:sometag]; //give tag in xib

Body:
In my new quest to learn objective c, I have can't get past the error in my viewController that a button (which I have declared in the header file - IBOutlet) is unavailable.

in the header.h file:

#import <UIKit/UIKit.h>

@interface MessageContactViewController : TTTemplateViewController
{
    __weak IBOutlet UIButton *showBtn;
    __weak IBOutlet UIView *photoView;
}
@end

code in .m file

import "header.h"
@implementation MessageContactViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (IS_IOS_7) {
        [showBtn.titleLabel setFont:[UIFont fontWithName:FONT_GOTHAM_BOOK size:17]]; // this gives the error: "showBtn" is unavailable
    //some extra code for labels and button

}

Please help me out in this and forgive my ignorance.


问:
How do I loop a HTML name value with PHP
I have a PHP page pulls mobile phones from a database. Depending on how many phones are in the database, the PHP page will determine how many fields to create. I have a session in place to only allow those who are logged in, able to edit and access certain features.

I want the checkbox to update the database with a 1 (as active) and a 0 (as inactive) devices so I will be able to show only those which are active.

Edit: session_start(); is in every page within header.php connected to the top of each page. I have left that out in the code.

phones.php

```<code><?php
    if (isset($_SESSION['u_name'])) {
        echo ' <button type="submit" name="submit"
        form="activeForm">Save</button>';
    }
    for($x = 1; $x <= deviceCount("phones"); $x++) {
?>
    </section>
        <?php
            if (isset($_SESSION['u_name'])) {
        ?>
        <form id="activeForm" method="POST" action="save.php">
            <input type="checkbox" echo ' name="active'.$x.'"';?>>
        </form>
    <?php
        }
    }
    ?>
</code>```

Below is my PHP. I am wanting to check if each check box is selected. The issue I am having is that after the first checkbox is checked, the rest are always not selected.

save.php

```<code><?php

if (isset($_POST['submit'])) {
    include_once 'connect.inc.php';

    $query = "SELECT * FROM phones";
    if ($result=mysqli_query($conn, $query)) {
        // Return the number of rows in result set
        $rowcount=mysqli_num_rows($result);
    }

    for($x = 1; $x < $rowcount + 1; $x++) {
        $select = 'active'.$x;
        if (isset($_POST[$select])) {
            $sql = "UPDATE phones SET active='1' WHERE id=$x";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE phones SET active='0' WHERE id=$x";
            mysqli_query($conn, $sql);
        }
    }
}
</code>```

Let's say I have 4 devices. The first checkbox would be responsive, however, the next 3 would all say not selected.

答:
phones.php

```<code>  <?php
// you need first start session
 session_start();

        if (isset($_SESSION['u_name'])) {
            echo ' <button type="submit" name="submit"
            form="activeForm">Save</button>';
        }
        for($x = 1; $x <= deviceCount("phones"); $x++) {
    ?>
        </section>
            <?php
                if (isset($_SESSION['u_name'])) {
            ?>
            <form id="activeForm" method="POST" action="save.php">
                <input type="checkbox"  name="active<?= $x ?>" >
            </form>
        <?php
            }
        }
        ?>
</code>```

Body:
I have a PHP page pulls mobile phones from a database. Depending on how many phones are in the database, the PHP page will determine how many fields to create. I have a session in place to only allow those who are logged in, able to edit and access certain features.

I want the checkbox to update the database with a 1 (as active) and a 0 (as inactive) devices so I will be able to show only those which are active.

Edit: session_start(); is in every page within header.php connected to the top of each page. I have left that out in the code.

phones.php

<?php
    if (isset($_SESSION['u_name'])) {
        echo ' <button type="submit" name="submit"
        form="activeForm">Save</button>';
    }
    for($x = 1; $x <= deviceCount("phones"); $x++) {
?>

        <?php
            if (isset($_SESSION['u_name'])) {
        ?>
        <form id="activeForm" method="POST" action="save.php">
            <input type="checkbox" echo ' name="active'.$x.'"';?>>
        </form>
    <?php
        }
    }
    ?>

Below is my PHP. I am wanting to check if each check box is selected. The issue I am having is that after the first checkbox is checked, the rest are always not selected.

save.php

<?php

if (isset($_POST['submit'])) {
    include_once 'connect.inc.php';

    $query = "SELECT * FROM phones";
    if ($result=mysqli_query($conn, $query)) {
        // Return the number of rows in result set
        $rowcount=mysqli_num_rows($result);
    }

    for($x = 1; $x < $rowcount + 1; $x++) {
        $select = 'active'.$x;
        if (isset($_POST[$select])) {
            $sql = "UPDATE phones SET active='1' WHERE id=$x";
            mysqli_query($conn, $sql);
        } else {
            $sql = "UPDATE phones SET active='0' WHERE id=$x";
            mysqli_query($conn, $sql);
        }
    }
}

Let's say I have 4 devices. The first checkbox would be responsive, however, the next 3 would all say not selected.

Body:
phones.php

  <?php
// you need first start session
 session_start();

        if (isset($_SESSION['u_name'])) {
            echo ' <button type="submit" name="submit"
            form="activeForm">Save</button>';
        }
        for($x = 1; $x <= deviceCount("phones"); $x++) {
    ?>
        </section>
            <?php
                if (isset($_SESSION['u_name'])) {
            ?>
            <form id="activeForm" method="POST" action="save.php">
                <input type="checkbox"  name="active<?= $x ?>" >
            </form>
        <?php
            }
        }
        ?>


问:
ORA-00905: missing keyword after creating table
I am working on sql developer (11g) , I'm trying to create this table, but it doesn't work, it says ORA-00905: missing keyword

SQL Code

```<code>CREATE TABLE module(
    code_mod int NOT NULL,
    intitule varchar2(255) NOT NULL,
    charge_hor int NOT NULL,
    coef double NOT NULL,
    CONSTRAINT PK_module   PRIMARY KEY(code_mod)
);
</code>```

答:
double is not a type in Oracle.  Use double precision:

```<code>CREATE TABLE module (
    code_mod int NOT NULL,
    intitule varchar2(255) NOT NULL,
    charge_hor int NOT NULL,
    coef double precision NOT NULL,
    CONSTRAINT PK_module   PRIMARY KEY(code_mod)
);
</code>```

Here is a SQL Fiddle.

Body:
I am working on sql developer (11g) , I'm trying to create this table, but it doesn't work, it says ORA-00905: missing keyword

SQL Code

CREATE TABLE module(
    code_mod int NOT NULL,
    intitule varchar2(255) NOT NULL,
    charge_hor int NOT NULL,
    coef double NOT NULL,
    CONSTRAINT PK_module   PRIMARY KEY(code_mod)
);

Body:
double is not a type in Oracle.  Use double precision:

CREATE TABLE module (
    code_mod int NOT NULL,
    intitule varchar2(255) NOT NULL,
    charge_hor int NOT NULL,
    coef double precision NOT NULL,
    CONSTRAINT PK_module   PRIMARY KEY(code_mod)
);

Here is a SQL Fiddle.


问:
Printing out a number in assembly language?
```<code>mov al,10
add al,15
</code>```

How do I print the value of 'al'?

答:
```<code>PRINT_SUM PROC NEAR
 CMP AL, 0
 JNE PRINT_AX
 PUSH AX
 MOV AL, '0'
 MOV AH, 0EH
 INT 10H
 POP AX
 RET
    PRINT_AX:
 PUSHA
 MOV AH, 0
 CMP AX, 0
 JE PN_DONE
 MOV DL, 10
 DIV DL
 CALL PRINT_AX
 MOV AL, AH
 ADD AL, 30H
 MOV AH, 0EH
 INT 10H
    PN_DONE:
 POPA
 RET
PRINT_SUM ENDP
</code>```

Body:
mov al,10
add al,15

How do I print the value of 'al'?


问:
JSON contains incorrect UTF-8 \u00ce\u00b2 instead of Unicode \u03b2, how to fix in Python?
First note that symbol β (Greek beta) have hex representation in UTF-8: CE B2

I have legacy source code in Python 2.7 that uses json strings:

```<code>u'{"something":"text \\u00ce\\u00b2 text..."}'
</code>```

I then it calls json.loads(string) or json.loads(string, 'utf-8'), but the result is Unicode string with UTF-8 characters:

```<code>u'text \xce\xb2 text'
</code>```

What I want is normal Python Unicode (UTF-16?) string:

```<code>u'text β text'
</code>```

If I call:

```<code>text = text.decode('unicode_escape')
</code>```

before json.loads, then I got correct Unicode β symbol, but it also breaks json by also replacing all new lines - \n

The question is, how to convert only "\\u00ce\\00b2" part without affecting other json special characters?

(I am new to Python, and it is not my source code, so I have no idea how this is supposed to work. I suspect that the code only works with ASCII characters)

答:
Something like this, perhaps.  This is limited to 2-byte UTF-8 characters.

```<code>import re

j = u'{"something":"text \\u00ce\\u00b2 text..."}'

def decodeu (match):
    u = '%c%c' % (int(match.group(1), 16), int(match.group(2), 16))
    return repr(u.decode('utf-8'))[2:8]

j = re.sub(r'\\u00([cd][0-9a-f])\\u00([89ab][0-9a-f])',decodeu, j)

print(j)
</code>```

returns {"something":"text \u03b2 text..."} for your sample.  At this point, you can import it as regular JSON and get the final string you want.

```<code>result = json.loads(j)
</code>```

Body:
First note that symbol β (Greek beta) have hex representation in UTF-8: CE B2

I have legacy source code in Python 2.7 that uses json strings:

u'{"something":"text \\u00ce\\u00b2 text..."}'

I then it calls json.loads(string) or json.loads(string, 'utf-8'), but the result is Unicode string with UTF-8 characters:

u'text \xce\xb2 text'

What I want is normal Python Unicode (UTF-16?) string:

u'text β text'

If I call:

text = text.decode('unicode_escape')

before json.loads, then I got correct Unicode β symbol, but it also breaks json by also replacing all new lines - \n

The question is, how to convert only "\\u00ce\\00b2" part without affecting other json special characters?

(I am new to Python, and it is not my source code, so I have no idea how this is supposed to work. I suspect that the code only works with ASCII characters)

Body:
Something like this, perhaps.  This is limited to 2-byte UTF-8 characters.

import re

j = u'{"something":"text \\u00ce\\u00b2 text..."}'

def decodeu (match):
    u = '%c%c' % (int(match.group(1), 16), int(match.group(2), 16))
    return repr(u.decode('utf-8'))[2:8]

j = re.sub(r'\\u00([cd][0-9a-f])\\u00([89ab][0-9a-f])',decodeu, j)

print(j)

returns {"something":"text \u03b2 text..."} for your sample.  At this point, you can import it as regular JSON and get the final string you want.

result = json.loads(j)


答:
Try to do like this..

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
token = (TextView) findViewById(R.id.TV1) ;
title = (TextView) findViewById(R.id.welcome_Txt);

String extras = getIntent().getStringExtra("Token);
</code>```

But I will suggest you to better save that token in shared preferences and use if it all your activity.

For Example:

For Setting values in Preference:

```<code> SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
 MODE_PRIVATE).edit();
 editor.putString("Token", getToken);
 editor.apply();
</code>```

For Retrieve data from preference:

```<code> SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,
 MODE_PRIVATE);
 String restoredText = prefs.getString("text", null);
 if (restoredText != null) {
 String name = prefs.getString("Token", "No name defined");//"No name
 defined"
 is the default value.

 }
</code>```

Body:
I am currently working on a project with a friend, where we have a website hosting login details and such. when a user logs in it returns a token to the app, to use as verification for further api calls by the user. (ie. getting the profile). i need to pass this token across other activities (it is a string), and i tried to use intents, but every time i try it comes up with a nullPointerException , where the class i'm calling the intent from can't find the extra i'm sending. i've tried putting the code for creating the intent at the top of the onCreate method, however this returns 401 errors from the server as (i assume) the token has no value because it hasn't been sent by the server using the JSONObject request yet.
here is the code for the main activity (all links removed)(i also didnt include all the imports and variable declarations as i figured they're un-necessary)

    String Name,Pass,tokenString;

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

    button = (Button) findViewById(R.id.button);
    token = (TextView) findViewById(R.id.TV1);
    name = (EditText) findViewById(R.id.name);
    pass = (EditText) findViewById(R.id.pass);
    register = (Button) findViewById(R.id.button2);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          Name = name.getText().toString();
            Pass = pass.getText().toString();

            if(Name.equals("") || Pass.equals("")){
                Toast.makeText(MainActivity.this, "Fields cannot be left empty!", Toast.LENGTH_SHORT).show();
            }

            StringRequest stringRequest = new StringRequest(Request.Method.POST, Url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject =  new JSONObject(response);
                        setToken(jsonObject.getString("token"));

                        launchHomeActivity();

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if(error.networkResponse.statusCode==401) {
                        Toast.makeText(MainActivity.this, "Incorrect login details, please retry", Toast.LENGTH_SHORT).show();
                    }
                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("email", Name);
                    params.put("password", Pass);
                    return params;
                }
            };
            MySingleton.getInstance(MainActivity.this).addToRequestQueue(stringRequest);
            name.setText("");
            pass.setText("");

        }

    });
    register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            launchRegisterActivity();
        }
    });

}
private void launchRegisterActivity() {

    Intent intent = new Intent(this, RegisterActivity.class);
    startActivity(intent);
}
private void launchHomeActivity() {

    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

private void setToken(String token){
    tokenString = token;

}
public String getToken(){
    return tokenString;
}

public void createIntent(){
    Intent i = new Intent(this, Home.class);
    i.putExtra("Token", getToken());
    startActivity(i);
}
}

here is the code for the home activity (the relevant bits) :

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    token = (TextView) findViewById(R.id.TV1) ;
    title = (TextView) findViewById(R.id.welcome_Txt);

    Bundle extras = getIntent().getExtras();

   final String tokenString = extras.getString("Token");

            StringRequest stringRequest = new StringRequest(Request.Method.GET, ProfileUrl, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        // JSONArray jsonArray = new JSONArray(response);
                        JSONObject jsonObject =  new JSONObject(response);
                         title.setText("Welcome back " +  jsonObject.getString("token") + "!");

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                protected Map<String,String> getParams() throws AuthFailureError{
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("key", "****");
                    params.put("Token", tokenString);
                    return params;
                }
            };
            MySingleton.getInstance(Home.this).addToRequestQueue(stringRequest);

        }

Any help is greatly appreciated.

(p.s i'm very new to android studio, and learning as i go)

Body:
Try to do like this..

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
token = (TextView) findViewById(R.id.TV1) ;
title = (TextView) findViewById(R.id.welcome_Txt);

String extras = getIntent().getStringExtra("Token);

But I will suggest you to better save that token in shared preferences and use if it all your activity.

For Example:

For Setting values in Preference:

 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
 MODE_PRIVATE).edit();
 editor.putString("Token", getToken);
 editor.apply();

For Retrieve data from preference:

 SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,
 MODE_PRIVATE);
 String restoredText = prefs.getString("text", null);
 if (restoredText != null) {
 String name = prefs.getString("Token", "No name defined");//"No name
 defined"
 is the default value.

 }


问:
Check if dynamically created checkbox is checked or not?
I have a table with 16 rows and each row contains checkbox. I need to check if checkbox is checked or not. If check then do something otherwise do something else. I am trying but logic not working:

BtnGet is a button in each row. I am firing event on BtnGet:

```<code>$('.btnGet').each(function (i, obj) {
   if ($(obj)
      .closest("tr")
      .children("td:nth-child(3)")
      .find("input[type = checkbox]")
      .checked)
      {
          console.log("Working");
       }
}
</code>```

答:
checked is a property of the checkbox DOM element, not the jQuery object. You could use is(':checked') instead:

```<code>$('.btnGet').each(function(i, obj) {
  if ($(obj).closest("tr").find("td:nth-child(3) :checkbox").is(':checked')) {
    console.log("Working");
  }
}
</code>```

Body:
I have a table with 16 rows and each row contains checkbox. I need to check if checkbox is checked or not. If check then do something otherwise do something else. I am trying but logic not working:

BtnGet is a button in each row. I am firing event on BtnGet:

$('.btnGet').each(function (i, obj) {
   if ($(obj)
      .closest("tr")
      .children("td:nth-child(3)")
      .find("input[type = checkbox]")
      .checked)
      {
          console.log("Working");
       }
}

Body:
checked is a property of the checkbox DOM element, not the jQuery object. You could use is(':checked') instead:

$('.btnGet').each(function(i, obj) {
  if ($(obj).closest("tr").find("td:nth-child(3) :checkbox").is(':checked')) {
    console.log("Working");
  }
}


问:
How to pass variable in nested json of request body
I am trying to pass a variable to my request body which has a nested json but not able to do so.

```<code> Given path 'url'
 * request {abc:'ab',pqrs:'{"mno":"data","ijk":"data"}',dcb:'tata'} // Double quotes are required for 'pqrs' because thats the format of the service.
 When method post
 Then status 200
 * def test = response.lmn
 * print lmn
 * def browser = Java.type('file path')
 * def testing = browser.do(parameter) // 'do' function will call a java file which will return a String parameter
 * print testing

Given path 'url'
 * def nested = {uvw:"value",xyz:'#(testing)',ght:} //We tried storing nested variable in json format but that didn't work.
 * request { abc:'ab',pqr:'#(nested)',dcb:'tata' }
 When method post
 Then status 200
</code>```

After hitting above request getting error as "Invalid pqr object". Please suggest solution.

答:
It looks like you are making basic mistakes in forming JSON, that's all. For example, the ght field has nothing after it above. I'll just focus on the second part of your script. You can paste the below into a Scenario and see it work, by the way - this is a good tip: you can experiment like this quickly without making HTTP requests in a separate file.

```<code>* json testing = '{"helo":"world","test":"done"}'
* def nested = { uvw: 'value', xyz: '#(testing)', ght: null }
* def temp = { abc: 'ab', pqr: '#(nested)', dcb: 'tata' }
* print temp
</code>```

And the output is:

```<code>[print] {
  "abc": "ab",
  "pqr": {
    "uvw": "value",
    "xyz": {
      "helo": "world",
      "test": "done"
    },
    "ght": null
  },
  "dcb": "tata"
}
</code>```

So everything is working as expected.

Edit: showing how you can take a string and convert it back to JSON if needed. Please refer to the doc on type-conversion normally you don't need it, but looks like you do.

Body:
I am trying to pass a variable to my request body which has a nested json but not able to do so.

 Given path 'url'
 * request {abc:'ab',pqrs:'{"mno":"data","ijk":"data"}',dcb:'tata'} // Double quotes are required for 'pqrs' because thats the format of the service.
 When method post
 Then status 200
 * def test = response.lmn
 * print lmn
 * def browser = Java.type('file path')
 * def testing = browser.do(parameter) // 'do' function will call a java file which will return a String parameter
 * print testing

Given path 'url'
 * def nested = {uvw:"value",xyz:'#(testing)',ght:} //We tried storing nested variable in json format but that didn't work.
 * request { abc:'ab',pqr:'#(nested)',dcb:'tata' }
 When method post
 Then status 200

After hitting above request getting error as "Invalid pqr object". Please suggest solution.

Body:
It looks like you are making basic mistakes in forming JSON, that's all. For example, the ght field has nothing after it above. I'll just focus on the second part of your script. You can paste the below into a Scenario and see it work, by the way - this is a good tip: you can experiment like this quickly without making HTTP requests in a separate file.

* json testing = '{"helo":"world","test":"done"}'
* def nested = { uvw: 'value', xyz: '#(testing)', ght: null }
* def temp = { abc: 'ab', pqr: '#(nested)', dcb: 'tata' }
* print temp

And the output is:

[print] {
  "abc": "ab",
  "pqr": {
    "uvw": "value",
    "xyz": {
      "helo": "world",
      "test": "done"
    },
    "ght": null
  },
  "dcb": "tata"
}

So everything is working as expected.

Edit: showing how you can take a string and convert it back to JSON if needed. Please refer to the doc on type-conversion normally you don't need it, but looks like you do.


问:
How use Laravel Language Translation in controller as constant?
Is it possible to use Laravel Language Translator (Localization) in controller as constant? Below attempt, example that does not work:</p>

```<code>class SearchApproval extends Controller
{
    private $request;

    const stage_1 = Lang::get('message.failed');
</code>```

答:
trans it's a global function, so you can use it directly from your controller

```<code>trans('messages.failed');
</code>```

but this won't work as constant, so you can use it like this:

```<code>class SearchApproval extends Controller
{
    private $request;

    const stage_1 = 'message.failed';

    public function xxx(){
        $whatever = trans(self::stage_1);
    }
}
</code>```

UPDATED:

You can use this  __('Your Text') inside the controller.

Body:
Is it possible to use Laravel Language Translator (Localization) in controller as constant? Below attempt, example that does not work:

class SearchApproval extends Controller
{
    private $request;

    const stage_1 = Lang::get('message.failed');

Body:
trans it's a global function, so you can use it directly from your controller

trans('messages.failed');

but this won't work as constant, so you can use it like this:

class SearchApproval extends Controller
{
    private $request;

    const stage_1 = 'message.failed';

    public function xxx(){
        $whatever = trans(self::stage_1);
    }
}

UPDATED:

You can use this  __('Your Text') inside the controller.


问:
Problems filtering django datetime field by month and day
Can someone explain to me why the following filters are not working at the month and day level?  Filtering by year seems to work, but not the other two.

```<code>>>> clicks.count()
36
>>> date = clicks[0].created
>>> date.month
2
>>> date.year
2014
>>> date.day
1
>>> clicks.filter(created__month=2)
[]
>>> clicks.filter(created__month=02)
[]
>>> clicks.filter(created__month='02')
[]
>>> clicks.filter(created__month='2')
[]
>>> clicks.filter(created__month=date.month)
[]
>>> clicks.filter(created__day=date.day)
[]
</code>```

A quick update to demonstrate that I am getting the same behavior before creating and dealing with a queryset:

```<code>>>> clicks = PreviewClick.objects.filter(created__month = 2)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = 02)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '02')
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '2')
>>> clicks.count()
0
</code>```

Here's more food for thought:

```<code>>>> clicks = PreviewClick.objects.all()
>>> counter = 0
>>> for click in clicks:
...      if click.created.month == 2:
...           counter += 1
...
>>> counter
35
</code>```

答:
To update the answer here since I ran into the above issue but none of the solutions worked. Most new mysql installations come pre-installed with tz-info, so the mysql_tzinfo_to_sql command wont really help. And setting TZ_INFO to False isn't really a solution since many need time-zone aware datetime.

So, what worked for me was to create a tz aware datetime object and check against that. Lets say you wanna filter records for today you would do something like,

```<code>from datetime import datetime
import pytz

today = datetime.now().replace(tzinfo=pytz.UTC).date()   # tz aware datetime object
todays_records = myModel.objects.filter(created__year=today.year, created__month=today.month,created__day=today.day)
</code>```

Hope this helps.

Body:
Can someone explain to me why the following filters are not working at the month and day level?  Filtering by year seems to work, but not the other two.

>>> clicks.count()
36
>>> date = clicks[0].created
>>> date.month
2
>>> date.year
2014
>>> date.day
1
>>> clicks.filter(created__month=2)
[]
>>> clicks.filter(created__month=02)
[]
>>> clicks.filter(created__month='02')
[]
>>> clicks.filter(created__month='2')
[]
>>> clicks.filter(created__month=date.month)
[]
>>> clicks.filter(created__day=date.day)
[]

A quick update to demonstrate that I am getting the same behavior before creating and dealing with a queryset:

>>> clicks = PreviewClick.objects.filter(created__month = 2)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = 02)
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '02')
>>> clicks.count()
0
>>> clicks = PreviewClick.objects.filter(created__month = '2')
>>> clicks.count()
0

Here's more food for thought:

>>> clicks = PreviewClick.objects.all()
>>> counter = 0
>>> for click in clicks:
...      if click.created.month == 2:
...           counter += 1
...
>>> counter
35

Body:
To update the answer here since I ran into the above issue but none of the solutions worked. Most new mysql installations come pre-installed with tz-info, so the mysql_tzinfo_to_sql command wont really help. And setting TZ_INFO to False isn't really a solution since many need time-zone aware datetime.

So, what worked for me was to create a tz aware datetime object and check against that. Lets say you wanna filter records for today you would do something like,

from datetime import datetime
import pytz

today = datetime.now().replace(tzinfo=pytz.UTC).date()   # tz aware datetime object
todays_records = myModel.objects.filter(created__year=today.year, created__month=today.month,created__day=today.day)

Hope this helps.


问:
Migrating create-react-app from javascript to typescript
I started a react project using create-react-app few months ago and I'm interesting in migrating the project from Javascript to Typescript.

I saw that there is a way to create react app with typescript using the flag:

```<code>--scripts-version=react-scripts-ts
</code>```

But I didn't find any explanation how can I migrate an existing JS project to TS.
I need it to be done incrementally so I can work with both .js and .ts files so I can do the transformation over time.
Does anyone has any experience with this migration? What are the required steps that should be done to make this work?

答:
UPDATE: create-react-app version 2.1.0 support typescript so for those of you who are starting from scratch you can use it to create new application with typescript, and according to the documentation it should be done with the following command:

```<code>$ npx create-react-app my-app --template typescript
</code>```

For existing projects, after updating to version 2.1.0, add the following packages to your project's dependencies with the following command:

```<code>$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest
</code>```

and then you can simply rename .js to .ts files.

I found a solution to migrate create-react-app from javascript to typescript, this way doesn't require eject.

Create a temporary react project with typescript by running the command create-react-app --scripts-version=react-scripts-ts
(Note - requires create-react-app to be installed globally)

In your own project - under package.json file remove the react-scripts

Add react-scripts-ts to your project by running the command yarn add react-scripts-ts or if your are using npm then npm install react-scripts-ts. Or, add "react-scripts-ts": "2.8.0" to package.json.

From the project you created in step 1 copy the files: tsconfig.json, tsconfig.test.json tslint.json to your own project

Under your own project, in package.json, under scripts section, change react-scripts instances to react-scripts-ts (should be under start, build, test and eject

Install the typings for react by installing the following modules using yarn or npm: @types/node, @types/react and @types/react-dom. Put in devDependencies section if using package.json.

Change index.js file name to index.tsx

In your tsconfig.json file add the following configuration: "allowSyntheticDefaultImports": true - for more info

NOTE step 7 might require additional modification depends on what you have in your index.js file (if it depends on JS modules in the project).

Now you can run your project and it might work, for those of you who are getting error that contains You may need an appropriate loader to handle this file type regarding .js files, it happens because babel doesn't know how to load .js file from .tsx files. What we need to do is to change the project configuration. The way I found doing it without running eject is using react-app-rewired package. This package lets you configure external configuration which will be added/override the default project settings. What we'll do is using babel to load these type of files. Let's moved on:

Install the package react-app-rewired using yarn or npm

In your root folder (where package.json is located) create a new file with the name config-overrides.js

Put this code in config-overrides file:

```<code>var paths = require('react-scripts-ts/config/paths')

module.exports = function override(config) {
  config.module.rules.push({
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: require.resolve('babel-loader'),
    options: {
        babelrc: false,
        presets: [require.resolve('babel-preset-react-app')],
        cacheDirectory: true,
    },
  })

  return config
}
</code>```

Edit package.json so the start/start-js, build, test, and eject scripts use react-app-rewired as shown in the project readme. E.g. "test": "react-app-rewired test --scripts-version react-scripts-ts --env=jsdom".

Now you can start you the project and the problem should be solved. You might need additional modifications depending on your project (additional types and so).

Hope it helps

As suggested here in the comments, it's possible to define: "compilerOptions": { "allowJs": true} in your tsconfig.json file, so you can mix JS and TS without react-app-rewired. Thanks for mention this!

Body:
I started a react project using create-react-app few months ago and I'm interesting in migrating the project from Javascript to Typescript.

I saw that there is a way to create react app with typescript using the flag:

--scripts-version=react-scripts-ts

But I didn't find any explanation how can I migrate an existing JS project to TS.
I need it to be done incrementally so I can work with both .js and .ts files so I can do the transformation over time.
Does anyone has any experience with this migration? What are the required steps that should be done to make this work?

Body:
UPDATE: create-react-app version 2.1.0 support typescript so for those of you who are starting from scratch you can use it to create new application with typescript, and according to the documentation it should be done with the following command:

$ npx create-react-app my-app --template typescript

For existing projects, after updating to version 2.1.0, add the following packages to your project's dependencies with the following command:

$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest

and then you can simply rename .js to .ts files.

I found a solution to migrate create-react-app from javascript to typescript, this way doesn't require eject.

Create a temporary react project with typescript by running the command create-react-app --scripts-version=react-scripts-ts
(Note - requires create-react-app to be installed globally)

In your own project - under package.json file remove the react-scripts

Add react-scripts-ts to your project by running the command yarn add react-scripts-ts or if your are using npm then npm install react-scripts-ts. Or, add "react-scripts-ts": "2.8.0" to package.json.

From the project you created in step 1 copy the files: tsconfig.json, tsconfig.test.json tslint.json to your own project

Under your own project, in package.json, under scripts section, change react-scripts instances to react-scripts-ts (should be under start, build, test and eject

Install the typings for react by installing the following modules using yarn or npm: @types/node, @types/react and @types/react-dom. Put in devDependencies section if using package.json.

Change index.js file name to index.tsx

In your tsconfig.json file add the following configuration: "allowSyntheticDefaultImports": true - for more info

NOTE step 7 might require additional modification depends on what you have in your index.js file (if it depends on JS modules in the project).

Now you can run your project and it might work, for those of you who are getting error that contains You may need an appropriate loader to handle this file type regarding .js files, it happens because babel doesn't know how to load .js file from .tsx files. What we need to do is to change the project configuration. The way I found doing it without running eject is using react-app-rewired package. This package lets you configure external configuration which will be added/override the default project settings. What we'll do is using babel to load these type of files. Let's moved on:

Install the package react-app-rewired using yarn or npm

In your root folder (where package.json is located) create a new file with the name config-overrides.js

Put this code in config-overrides file:

var paths = require('react-scripts-ts/config/paths')

module.exports = function override(config) {
  config.module.rules.push({
    test: /\.(js|jsx)$/,
    include: paths.appSrc,
    loader: require.resolve('babel-loader'),
    options: {
        babelrc: false,
        presets: [require.resolve('babel-preset-react-app')],
        cacheDirectory: true,
    },
  })

  return config
}

Edit package.json so the start/start-js, build, test, and eject scripts use react-app-rewired as shown in the project readme. E.g. "test": "react-app-rewired test --scripts-version react-scripts-ts --env=jsdom".

Now you can start you the project and the problem should be solved. You might need additional modifications depending on your project (additional types and so).

Hope it helps

As suggested here in the comments, it's possible to define: "compilerOptions": { "allowJs": true} in your tsconfig.json file, so you can mix JS and TS without react-app-rewired. Thanks for mention this!