问:
Problem with webflow(s) in Grails
I've just come across a rather odd problem whilst testing my applications webflows.

I have two seperate webflows that are accessed once a user logs in depending on whether the user is male or female, they begin a process which sends them on a webflow.  One for males, a different one for females.

So to test my app, I login as a male user and enter the flow, thats all fine.. then either by logging out and logging in as a female (or logging in as a female user in a different browser) I then attempt to go through the female process but Bang I get an exception:

```<code>Error 500: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Servlet: grails
URI: /ACUREG/grails/applicant/ma.dispatch
Exception Message: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Caused by: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Class: ApplicantController
</code>```

Now this is strange, as the reverse is also true, If I started first going through as a female, then attempt to try the Male process, the same issue occurs but this time the exception will point to the first event in the male webflow code...

Does anyone know why this may be happening? I did think its perhaps something to do with two webflows in the same controller but after seperating them into their own controllers and still seeing the same issue thats clearly not the case.

Thanks,

答: The problem was down to webflow events having the same name across multiple webflows.  When I renamed the events so they were all different, no more problems.</p>

Title: Problem with webflow(s) in Grails

Body:
I've just come across a rather odd problem whilst testing my applications webflows.

I have two seperate webflows that are accessed once a user logs in depending on whether the user is male or female, they begin a process which sends them on a webflow.  One for males, a different one for females.

So to test my app, I login as a male user and enter the flow, thats all fine.. then either by logging out and logging in as a female (or logging in as a female user in a different browser) I then attempt to go through the female process but Bang I get an exception:

Error 500: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Servlet: grails
URI: /ACUREG/grails/applicant/ma.dispatch
Exception Message: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Caused by: java.util.Collections$UnmodifiableMap cannot be cast to groovy.lang.Closure
Class: ApplicantController

Now this is strange, as the reverse is also true, If I started first going through as a female, then attempt to try the Male process, the same issue occurs but this time the exception will point to the first event in the male webflow code...

Does anyone know why this may be happening? I did think its perhaps something to do with two webflows in the same controller but after seperating them into their own controllers and still seeing the same issue thats clearly not the case.

Thanks,


来源: stackexchange

问:
I wanted to extract the all the orderNumber values from given xml response in Jmeter
I wanted to extract the all the orderNumber values from given XML response in JMeter

Regular Expression I am using : orderNumber=(".*?")

Xml:

```<code>     <?xml version="1.0" encoding="UTF-8"?>
    <ReportExecuted ReportId="4130" >
           <DisplayName>Partner Asset - Landing Page (No Glis Orders) Descending</DisplayName>
           <ExecutedBy>admin</ExecutedBy>
           <ExecutionTime>Thu Nov 16 07:32:29 UTC 2017</ExecutionTime>
           <PageNumber>1</PageNumber>
           <PageSize>10</PageSize>
           <DisplayRecords>1 to 10</DisplayRecords>
           <TotalRecords>1000</TotalRecords>
           <ReportContent>
                          <![CDATA[
    <partnerAssetLandingPage orderNumber="AutoSoapEONID11486" orderDate="2017-07-20T00:00:00"/><partnerAssetLandingPage orderNumber="AutoOrder101" orderDate="2016-11-04T00:00:00"/>

                          ]]>
              </ReportContent>
           </ReportExecuted>
</code>```

Response after running Jmeter:
I am only getting the 1st order Number value but I want all the order No values

答:
Your regular expression is ok, you should update Match No. to -1 (or negative number) and then get all the values by reference name for example for orderNumber - use orderNumber_1, orderNumber_2,...

If the match number is set to a negative number, then all the possible matches in the sampler data are processed. The variables are set as follows:

refName_matchNr - the number of matches found; could be 0

  refName_n, where n = 1, 2, 3 etc. - the strings as generated by the template

  refName_n_gm, where m=0, 1, 2 - the groups for match n

  refName - always set to the default value

  refName_gn - not set

  Note that the refName variable is always set to the default value in this case, and the associated group variables are not set.

You can work with ForEach Controller

It is especially suited for running with the regular expression post-processor.
This can "create" the necessary input variables out of the result data of a previous request. By omitting the "_" separator, the ForEach Controller can be used to loop through the groups by using the input variable refName_g, and can also loop through all the groups in all the matches by using an input variable of the form refName_${C}_g, where C is a counter variable.

ContentLicense: CC BY-SA 3.0

Body:
I wanted to extract the all the orderNumber values from given XML response in JMeter

Regular Expression I am using : orderNumber=(".*?")

Xml:

     <?xml version="1.0" encoding="UTF-8"?>
    <ReportExecuted ReportId="4130" >
           <DisplayName>Partner Asset - Landing Page (No Glis Orders) Descending</DisplayName>
           <ExecutedBy>admin</ExecutedBy>
           <ExecutionTime>Thu Nov 16 07:32:29 UTC 2017</ExecutionTime>
           <PageNumber>1</PageNumber>
           <PageSize>10</PageSize>
           <DisplayRecords>1 to 10</DisplayRecords>
           <TotalRecords>1000</TotalRecords>
           <ReportContent>
                          <![CDATA[
    <partnerAssetLandingPage orderNumber="AutoSoapEONID11486" orderDate="2017-07-20T00:00:00"/><partnerAssetLandingPage orderNumber="AutoOrder101" orderDate="2016-11-04T00:00:00"/>

                          ]]>
              </ReportContent>
           </ReportExecuted>

Response after running Jmeter:
I am only getting the 1st order Number value but I want all the order No values


问:
Can Angular 4 pass an object along the route?
I have a parent component and a child component. I was trying to navigate to child component using route.navigate based on button click. Is it possible to pass an object with route.navigate to the child component?

答:
In my case I navigate from a material table to a form and pass a raw id (it is possible to pass all the raw object)

Here's my code :

```<code><mat-cell id="idVtitle" *cdkCellDef="let row">
  <button id="idValidationScreenButton" mat-button [routerLink]="['/validation', row.documentid]">{{row.title}}
  </button>
</mat-cell>
</code>```

And in my ValidationComponent refering to the rout validation I have something like this:

```<code>  constructor(private _route: ActivatedRoute,
              private _router: Router,) {
  }
</code>```

And then calling this this._route.params.map((params: any) => params.id) to get the param (in my case I use the param to call the backend)

```<code>private fetchDocument() {
    this._route.params
      .map((params: any) => params.id)
      .flatMap((id: string) => this._sharedService.fetchOneDocument(id))
      .subscribe((doc: any) => this.docToValidate = doc);
  }
</code>```

I hope this could help.

Body:
In my case I navigate from a material table to a form and pass a raw id (it is possible to pass all the raw object)

Here's my code :

<mat-cell id="idVtitle" *cdkCellDef="let row">
  <button id="idValidationScreenButton" mat-button [routerLink]="['/validation', row.documentid]">{{row.title}}
  </button>
</mat-cell>

And in my ValidationComponent refering to the rout validation I have something like this:

  constructor(private _route: ActivatedRoute,
              private _router: Router,) {
  }

And then calling this this._route.params.map((params: any) => params.id) to get the param (in my case I use the param to call the backend)

private fetchDocument() {
    this._route.params
      .map((params: any) => params.id)
      .flatMap((id: string) => this._sharedService.fetchOneDocument(id))
      .subscribe((doc: any) => this.docToValidate = doc);
  }

I hope this could help.


问:
babel-polyfill vs babel-plugins
I am a bit lost in the Babel options / config. I want to use recent js features and compile (with webpack) to browser code.

What is the difference between babel-polyfill and babel plugins with babel-preset-env?

Are they intended to work together?

答:
Answer from this article:

The distinction between a babel transform plugin versus
  babel-polyfill / babel-runtime is whether or not you can
  reimplement the feature today, in ES5. For example, Array.from can
  be rewritten in ES5 but there is nothing I can write in ES5 to add
  arrow function syntax to JavaScript. Therefore, there is a transform
  for arrow functions but none for Array.from. It will have to be
  provided by a separate polyfill like babel-polyfill, or
  babel-runtime.

As a side note, here is my current understanding of the babel eco-system.

Babel is a javascript compiler: it parses, transforms and outputs transformed code.

babel-core

This is the parse and output parts.

It does not do any transformation.

It can be used from the command line or from a bundler (webpack, rollup and co.)

babel-polyfill / babel-runtime

Acts on the transform part by prepending es5 javascript to your code to emulate es2015+ functions (like Object.assign).

Relies on Regenerator (to polyfill generators)  and core-js (to polyfill all the rest).

Difference between babel-polyfill and babel-runtime: the former defines global methods (and pollutes the global scope) whereas the latter transforms your code to make the same functionnality available as explained in this answer.

babel plugins

Transform the code you wrote.

babel syntax / transform plugins: parse and transform es2015+ syntax (like arrow functions) to convert it to es5.

babel-plugins-stage-x (from stage-0 to stage-4): transform future javascript syntax which is not in the JS specs yet, starting at stage-0 (just an idea) down to stage-4 (will land in the babel-plugins soon).

babel-preset-env

babel-preset-env determines the Babel plugins and polyfills needed for a specific environment.

With no configuration, it will load all the plugins (including es2015, es2016 and es2017) required to transpile es2015+ to es5.

With a target option, it loads only the plugins required to run on a specific target.

With the builtIn option, it uses only the babel-polyfill which are not built-in the target.

Does not work with babel-transform-runtime yet (as of nov. 2017). (see this issue)

Title: babel-polyfill vs babel-plugins


问:
returning a boolean in one line for a ball that has crashed into another ball
I've just started learning java this quarter and on a sample quiz, this is a question. I have no idea where to begin save for the fact that it has to return a boolean type.

Fill in the blank so that this function returns true if the circle at x1, y1, with radius r1, has collided with the circle at x2, y2, with radius r2.

```<code>boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
    return ___________________________________________________________;
}
</code>```

Appreciate the comments and kind help. Like I said above, if you had read it, I've just started learning java this quarter and on a sample quiz, this is a question I had no idea where to begin. If anyone is willing to direct me to another learning resource that is better suited for a complete beginner, that would be great.

答:
```<code>boolean collided(int x1, int y1, int r1, int x2, int y2, int r2)
{
  return !(Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2))>(r1+r2));
}
</code>```

Body:
I've just started learning java this quarter and on a sample quiz, this is a question. I have no idea where to begin save for the fact that it has to return a boolean type.

Fill in the blank so that this function returns true if the circle at x1, y1, with radius r1, has collided with the circle at x2, y2, with radius r2.

boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
    return ___________________________________________________________;
}

Appreciate the comments and kind help. Like I said above, if you had read it, I've just started learning java this quarter and on a sample quiz, this is a question I had no idea where to begin. If anyone is willing to direct me to another learning resource that is better suited for a complete beginner, that would be great.


问:
Writing a Multi-threaded C# application
I need to write an application in c# that keeps track of multiple tasks, each being implemented as a class instance running on its own thread. A user interface will be used to display the status of each task instance depending on which task I select from tree view which will display the list of tasks.

An idea I have is to create some other class, called PropertyClass which will have an instance of the TaskClass and some properties relating to this TaskClass instance. Then whenever the TaskClass instance changes its state the related property in the PropertyClass instance will get updated and then the UI will be updated with these property values from the PropertyClass when the task is selected from the Tree View list.

There will probably be hundreds of these tasks running which will be communicating with a service on a remote machine.

How else can I go about coding this solution in an efficient way?

答:
I have a few suggestions.

First, you need a way to make sure you don't end up with threads blocking your app from closing.  One sure fire way to do this is to make sure all your threads are background threads.  That can be a little problematic if you have to make sure a thread's work is done before it is joined or aborted.

Second, you could look at using the ThreadPool class which should make creating and using threads more efficient.  The thread pool is there to help you manage your threads.

Third, you will need a method of synchronizing your data access from the GUI to data in the other threads.  In WPF you use the Dispatcher and in WinForms you'll use Invoke.

Forth, the BackgroundWorker class can help with all of these if it'll fit in the model of your application.

Fifth, events and delegates can be BeginInvoked which essentially puts them on another thread.  It's kind of implicit multi-threading and can be useful.

Sixth, and I've not yet had the chance to use this, .Net 4 has the Parallel Task Library that may be of use to you.

Seventh, safe shared data access and synchronization can be accomplished using lock and/or Monitor.

Hope this helps.

-Nate

ContentLicense: CC BY-SA 2.5

Title: Writing a Multi-threaded C# application


问:
Excel - Returning Data From A List Into Separate Columns Based On Fixed Criteria
What I wish to do is return all values that match a criteria from a list, this criteria will be static .... as a simple example

I have a list of all employee names in column A

I wish to have a list of employees that contain the name 'John' in column B (this would include first, last or part of eg Johnson)

I wish to have a list of all employees that DO NOT contain the name 'John' in column C

The name will always be 'John' so I would prefer to hard code it into the formula rather than have it be entered in a cell for lookup if possible.

As a side note I cannot use the advance filter as the real example is across multiple sheets.

答:
Are you looking for something like this......

Enter following formula to B2 cell as Array formula.

```<code>=IFERROR(INDEX($A$2:$A$20,SMALL(IF(ISNUMBER(SEARCH("John",$A$2:$A$20)),ROW($A$2:$A$20)),ROWS($A$2:$A2))-1),"")
</code>```

Press CTRL+SHIFT+ENTER to evaluate the formula as it is an array formula.

Body:
Are you looking for something like this......

Enter following formula to B2 cell as Array formula.

=IFERROR(INDEX($A$2:$A$20,SMALL(IF(ISNUMBER(SEARCH("John",$A$2:$A$20)),ROW($A$2:$A$20)),ROWS($A$2:$A2))-1),"")

Press CTRL+SHIFT+ENTER to evaluate the formula as it is an array formula.


问:
elasticsearch autosuggest fetch only text data
I am new to elasticsearch.Now I am using elasticsearch5.6.

POST localhost:9200/hotels/_suggest

req-body: {
  "hotels" : {
    "text" : "m",
    "completion" : {
      "field" : "name_suggest"
    }
  }
}

response

```<code>{
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hotels": [
        {
            "text": "m",
            "offset": 0,
            "length": 1,
            "options": [
                {
                    "text": "Marriot Munich City",
                    "_index": "hotels",
                    "_type": "hotel",
                    "_id": "3",
                    "_score": 1,
                    "_source": {
                        "name": "Courtyard by Marriot Munich City",
                        "city": "Munich",
                        "name_suggest": {
                            "input": [
                                "Courtyard by Marriot Munich City",
                                "Marriot Munich City"
                            ]
                        }
                    }
                },
                {
                    "text": "Monaco Munich",
                    "_index": "hotels",
                    "_type": "hotel",
                    "_id": "1",
                    "_score": 1,
                    "_source": {
                        "name": "Hotel Monaco",
                        "city": "Munich",
                        "name_suggest": {
                            "input": [
                                "Monaco Munich",
                                "Hotel Monaco"
                            ]
                        }
                    }
                }
            ]
        }
    ]
}
</code>```

Is there any way , where I can exclude _source in response?

Thanks in advance.

答:
I found the solution i.e.

POST localhost:9200/hotels/_search

{   "_source" : false,   "suggest" : {
      "hotels" : {
        "text" : "m",
        "completion" : {
          "field" : "name_suggest",
          "size" : 10
        }
      }   } }

Body:
I am new to elasticsearch.Now I am using elasticsearch5.6.

POST localhost:9200/hotels/_suggest

req-body: {
  "hotels" : {
    "text" : "m",
    "completion" : {
      "field" : "name_suggest"
    }
  }
}

response

{
    "_shards": {
        "total": 5,
        "successful": 5,
        "skipped": 0,
        "failed": 0
    },
    "hotels": [
        {
            "text": "m",
            "offset": 0,
            "length": 1,
            "options": [
                {
                    "text": "Marriot Munich City",
                    "_index": "hotels",
                    "_type": "hotel",
                    "_id": "3",
                    "_score": 1,
                    "_source": {
                        "name": "Courtyard by Marriot Munich City",
                        "city": "Munich",
                        "name_suggest": {
                            "input": [
                                "Courtyard by Marriot Munich City",
                                "Marriot Munich City"
                            ]
                        }
                    }
                },
                {
                    "text": "Monaco Munich",
                    "_index": "hotels",
                    "_type": "hotel",
                    "_id": "1",
                    "_score": 1,
                    "_source": {
                        "name": "Hotel Monaco",
                        "city": "Munich",
                        "name_suggest": {
                            "input": [
                                "Monaco Munich",
                                "Hotel Monaco"
                            ]
                        }
                    }
                }
            ]
        }
    ]
}

Is there any way , where I can exclude _source in response?

Thanks in advance.


问:
How to display a stack panel after some delay on button hover in WPF?
I have one button, on hovering mouse on that button for two seconds, i want open the stack panel.

xaml code:

```<code><StackPanel x:Name="spPinDetailsPopup" Height="200" Width="240" Visibility="Hidden">
     <!--it contains label control which have text to display-->
</StackPanel>
<Button x:Name="btnDisplayPopUp" MouseEnter="DisplayPopUpOnMouseEnter"/>
</code>```

CS code :

```<code>void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    spPinDetailsPopup.Visibility = Visibility.Visible;
}
</code>```

I have used the stack panel as a pop up which displays the control information.

Current Result : Stack panel is displayed immediately.

Expected Result :
Stack panel should only be open when we put mouse cursor on button for more than 2 seconds.
Is there any solution ?

答:
Solution :

I created one DispatcherTimer object at global level to controlling the time interval to open the popup.

```<code>private static DispatcherTimer _popUpOpeningTimer = new DispatcherTimer();

void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    // if we do not have DispatcherTimer set then only initialize it
    if (_popUpOpeningTimer == null)
    {
          _popUpOpeningTimer = new DispatcherTimer();
    }
    else // this means that dispatcher timer is already initialized, so do nothing
    {
         // do nothing
    }
    // stop the timer if it is already set so that we can start new timer
    _popUpOpeningTimer.Stop();

    _popUpOpeningTimer.Interval = new TimeSpan(0, 0, 1);

    _popUpOpeningTimer.Tick += new EventHandler((senderObject, eventArguments) => DisplayPopUp(senderObject, eventArguments, btnDisplayPopUp));

    // start the timer for opening the details popup
    _popUpOpeningTimer.Start();
}

private void DisplayPopUp(object sender, EventArgs e, Button button)
{
    if(button.IsMouseOver)
    {
         spPinDetailsPopup.Visibility = Visibility.Visible;
    }
    else
    {
         // do nothing
    }
}
</code>```

Body:
I have one button, on hovering mouse on that button for two seconds, i want open the stack panel.

xaml code:

<StackPanel x:Name="spPinDetailsPopup" Height="200" Width="240" Visibility="Hidden">

</StackPanel>
<Button x:Name="btnDisplayPopUp" MouseEnter="DisplayPopUpOnMouseEnter"/>

CS code :

void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    spPinDetailsPopup.Visibility = Visibility.Visible;
}

I have used the stack panel as a pop up which displays the control information.

Current Result : Stack panel is displayed immediately.

Expected Result :
Stack panel should only be open when we put mouse cursor on button for more than 2 seconds.
Is there any solution ?

Body:
Solution :

I created one DispatcherTimer object at global level to controlling the time interval to open the popup.

private static DispatcherTimer _popUpOpeningTimer = new DispatcherTimer();

void DisplayPopUpOnMouseEnter(object sender, MouseEventArgs e)
{
    // if we do not have DispatcherTimer set then only initialize it
    if (_popUpOpeningTimer == null)
    {
          _popUpOpeningTimer = new DispatcherTimer();
    }
    else // this means that dispatcher timer is already initialized, so do nothing
    {
         // do nothing
    }
    // stop the timer if it is already set so that we can start new timer
    _popUpOpeningTimer.Stop();

    _popUpOpeningTimer.Interval = new TimeSpan(0, 0, 1);

    _popUpOpeningTimer.Tick += new EventHandler((senderObject, eventArguments) => DisplayPopUp(senderObject, eventArguments, btnDisplayPopUp));

    // start the timer for opening the details popup
    _popUpOpeningTimer.Start();
}

private void DisplayPopUp(object sender, EventArgs e, Button button)
{
    if(button.IsMouseOver)
    {
         spPinDetailsPopup.Visibility = Visibility.Visible;
    }
    else
    {
         // do nothing
    }
}


问:
Add PHP generated errors in error log
I have this code here to create error log:

```<code>  error_log(date("[Y-m-d H:i:s]:")." You messed up!", 3, "../my-errors.log");
</code>```

Here, we can see the custom error 'You messed up!' that I have set to print in the error log. I don't want to use the custom error here. Instead of this I want to set the Errors/Warnings/Notices that are generated by PHP itself.

Is this possible and how can we do that?

Thankyou

答:
if I understood it well, you're looking for error_get_last():

array error_get_last ( void )

error_get_last — Get the last occurred error. /  Gets information about the last error that occurred.

Take a look:

```<code>$last_error = error_get_last();
$formated_last_error = sprintf('%s in %s on line %d'.PHP_EOL,
   $last_error['message'], $last_error['file'], $last_error['line']);

error_log(date(DATE_ATOM) . $formated_last_error().PHP_EOL, 3, '/tmp/logs.log');
</code>```

However, you should take a look at set_error_handler() function which is a general approach.

Title: Add PHP generated errors in error log

Body:
I have this code here to create error log:

  error_log(date("[Y-m-d H:i:s]:")." You messed up!", 3, "../my-errors.log");

Here, we can see the custom error 'You messed up!' that I have set to print in the error log. I don't want to use the custom error here. Instead of this I want to set the Errors/Warnings/Notices that are generated by PHP itself.

Is this possible and how can we do that?

Thankyou

Body:
if I understood it well, you're looking for error_get_last():

array error_get_last ( void )

error_get_last — Get the last occurred error. /  Gets information about the last error that occurred.

Take a look:

$last_error = error_get_last();
$formated_last_error = sprintf('%s in %s on line %d'.PHP_EOL,
   $last_error['message'], $last_error['file'], $last_error['line']);

error_log(date(DATE_ATOM) . $formated_last_error().PHP_EOL, 3, '/tmp/logs.log');

However, you should take a look at set_error_handler() function which is a general approach.


问:
Error looping Bitmap class to convert base64 strings into images
I wrote a web service in Java -- what I am trying to do is to read JSON data in Android. The problem is, I receive an error only when looping the Bitmap class. I have the enclosed JSON request code:

```<code>RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, URL,null,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){

                            JSONObject jsonData = response.getJSONObject(i);

                            String name = jsonData.getString("name");
                            String manufacture = jsonData.getString("manufacture");
                            Double price = Double.valueOf(jsonData.getString("price"));
                            String imageString = jsonData.getString("image");

                            // Display the formatted json data in text view
                            productDetails.append("Name: " + name +"\nManufacture: " + manufacture + "\nPrice: " + price.toString() );
                            productDetails.append("\n\n");

                            // decode base64 string to image
                            decodeImageString( imageString, prodImageButton);

                        }
                    }catch (JSONException e){
                        Toast.makeText( getApplication(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    // Do something when error occurred
                    //Toast.makeText( getApplication(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

    // Add JsonArrayRequest to the RequestQueue
    requestQueue.add(jsonArrayRequest);
}

private void decodeImageString(String imageString, ImageButton imageView){

    byte[] decodeString = Base64.decode (imageString, Base64.DEFAULT);
    Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);
}
</code>```

The error thrown:

```<code> E/AndroidRuntime: FATAL EXCEPTION: main
              Process: lagecy.live.desh.com.shoppincarttest, PID: 5224
              java.lang.IllegalArgumentException: bad base-64
                  at android.util.Base64.decode(Base64.java:161)
                  at android.util.Base64.decode(Base64.java:136)
                  at android.util.Base64.decode(Base64.java:118)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.decodeImageString(MainActivity.java:106)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.access$000(MainActivity.java:31)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:84)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:61)
                  at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

Sample JSON data:

```<code>[{
    "id": 1,
    "name": "Albany",
    "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
    "price": 15.49,
    "category": "Food",
    "type": "Breads",
    "image": "data:image/jpeg;base64,...[long text string]"
}]
</code>```

答:
The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:

```<code>final String encodedString = "data:image/jpg;base64, ....";
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",")  + 1);
</code>```

Now the pureBase64Encoded object is ready to be decoded:

```<code> final byte[] decodeString= Base64.decode(pureBase64Encoded, Base64.DEFAULT);
Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote a web service in Java -- what I am trying to do is to read JSON data in Android. The problem is, I receive an error only when looping the Bitmap class. I have the enclosed JSON request code:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest( Request.Method.GET, URL,null,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    try{
                        // Loop through the array elements
                        for(int i=0;i<response.length();i++){

                            JSONObject jsonData = response.getJSONObject(i);

                            String name = jsonData.getString("name");
                            String manufacture = jsonData.getString("manufacture");
                            Double price = Double.valueOf(jsonData.getString("price"));
                            String imageString = jsonData.getString("image");

                            // Display the formatted json data in text view
                            productDetails.append("Name: " + name +"\nManufacture: " + manufacture + "\nPrice: " + price.toString() );
                            productDetails.append("\n\n");

                            // decode base64 string to image
                            decodeImageString( imageString, prodImageButton);

                        }
                    }catch (JSONException e){
                        Toast.makeText( getApplication(), e.getMessage().toString(), Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error){
                    // Do something when error occurred
                    //Toast.makeText( getApplication(), error.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });

    // Add JsonArrayRequest to the RequestQueue
    requestQueue.add(jsonArrayRequest);
}

private void decodeImageString(String imageString, ImageButton imageView){

    byte[] decodeString = Base64.decode (imageString, Base64.DEFAULT);
    Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);
}

The error thrown:

 E/AndroidRuntime: FATAL EXCEPTION: main
              Process: lagecy.live.desh.com.shoppincarttest, PID: 5224
              java.lang.IllegalArgumentException: bad base-64
                  at android.util.Base64.decode(Base64.java:161)
                  at android.util.Base64.decode(Base64.java:136)
                  at android.util.Base64.decode(Base64.java:118)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.decodeImageString(MainActivity.java:106)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity.access$000(MainActivity.java:31)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:84)
                  at lagecy.live.desh.com.shoppincarttest.MainActivity$1.onResponse(MainActivity.java:61)
                  at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
                  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6119)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Sample JSON data:

[{
    "id": 1,
    "name": "Albany",
    "manufacture": "Albany Superior Low Gi Sliced Brown Seed Bread 700g",
    "price": 15.49,
    "category": "Food",
    "type": "Breads",
    "image": "data:image/jpeg;base64,...[long text string]"
}]

Body:
The Base64.decode won't be able to decode it, So it has to be removed from your encoded String:

final String encodedString = "data:image/jpg;base64, ....";
final String pureBase64Encoded = encodedString.substring(encodedString.indexOf(",")  + 1);

Now the pureBase64Encoded object is ready to be decoded:

 final byte[] decodeString= Base64.decode(pureBase64Encoded, Base64.DEFAULT);
Bitmap decoded = BitmapFactory.decodeByteArray (decodeString, 0, decodeString.length);
    imageView.setImageBitmap(decoded);


问:
Emoji cStringUsingEncoding with NSASCIIStringEncoding not working
I have an array with data :

```<code>MY_ARRAY: (
  "email="My_Email_ID"",
  "message=\Ud83d\Ude0a",
  "key="MY_KEY"
  "id="MY_ID""
)
</code>```

In the message field I have added emoji and it is showing it's hex value.

But when I try converting it to string :

```<code>string = [MY_ARRAY componentsJoinedByString: @"&"];
</code>```

the output in terminal shows:

```<code>email="My_Email_ID"&message=&key="MY_KEY"&id="MY_ID"
</code>```

why is it converting back to emoji?

The problem which I am facing is at this line:

```<code>const char *charData = [string cStringUsingEncoding:NSASCIIStringEncoding];
</code>```

as I am getting null here.

答:
Changing below line:

```<code>const char *charData = [string cStringUsingEncoding:NSASCIIStringEncoding];
</code>```

to

```<code>const char *charData = [string cStringUsingEncoding:NSUTF8StringEncoding];
</code>```

solved my issue.

Thanks to this forum.

If at all possible, stay away from anything other than UTF8.
  NSASCIIStringEncoding will break (return NULL) whenever there is a non-ASCII character in the string. There is no reason to take the risk. Only use cStringUsingEncoding: if you actually for whatever strange reason need a string in that particular encoding. Since NSLog expects UTF8 strings, any encoding that isn't a subset of UTF8 will produce strange results.

Body:
I have an array with data :

MY_ARRAY: (
  "email="My_Email_ID"",
  "message=\Ud83d\Ude0a",
  "key="MY_KEY"
  "id="MY_ID""
)

In the message field I have added emoji and it is showing it's hex value.

But when I try converting it to string :

string = [MY_ARRAY componentsJoinedByString: @"&"];

the output in terminal shows:

email="My_Email_ID"&message=&key="MY_KEY"&id="MY_ID"

why is it converting back to emoji?

The problem which I am facing is at this line:

const char *charData = [string cStringUsingEncoding:NSASCIIStringEncoding];

as I am getting null here.

Body:
Changing below line:

const char *charData = [string cStringUsingEncoding:NSASCIIStringEncoding];

to

const char *charData = [string cStringUsingEncoding:NSUTF8StringEncoding];

solved my issue.

Thanks to this forum.

If at all possible, stay away from anything other than UTF8.
  NSASCIIStringEncoding will break (return NULL) whenever there is a non-ASCII character in the string. There is no reason to take the risk. Only use cStringUsingEncoding: if you actually for whatever strange reason need a string in that particular encoding. Since NSLog expects UTF8 strings, any encoding that isn't a subset of UTF8 will produce strange results.


问:
Element UI - Change text of loading
I'm using element-ui and the Loading service.

I would like to be able to dynamically change the text when loading

Expected result

The text should be directly changed to yyyy

Actual result

The text is load and stays load

Question

How can I dynamically change the loading text after 1sec

https://jsfiddle.net/zxjbxg7x/

```<code>var Main = {
data() {
  return {
    text: 'load'
  }
},
methods: {
  openFullScreen2() {
    const loading = this.$loading({
      lock: true,
      text: this.text,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    this.text = 'yyy';
    setTimeout(() => {
      loading.close();
    }, 5000);
  }
}
</code>```

}

答:
Try this:</p>

```<code>var Main = {
    data() {
      return {
        text: 'load'
      }
    },
    computed : {
      loading () {
        return this.$loading({
          lock: true,
          text: this.text,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
    },
    methods: {
      openFullScreen2() {
        this.loading.text = 'yyy';
        setTimeout(() => {
          this.loading.close();
        }, 5000);
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
</code>```

Title: Element UI - Change text of loading

Body:
I'm using element-ui and the Loading service.

I would like to be able to dynamically change the text when loading

Expected result

The text should be directly changed to yyyy

Actual result

The text is load and stays load

Question

How can I dynamically change the loading text after 1sec

https://jsfiddle.net/zxjbxg7x/

var Main = {
data() {
  return {
    text: 'load'
  }
},
methods: {
  openFullScreen2() {
    const loading = this.$loading({
      lock: true,
      text: this.text,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    this.text = 'yyy';
    setTimeout(() => {
      loading.close();
    }, 5000);
  }
}

}

Body:
Try this:

var Main = {
    data() {
      return {
        text: 'load'
      }
    },
    computed : {
      loading () {
        return this.$loading({
          lock: true,
          text: this.text,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
      }
    },
    methods: {
      openFullScreen2() {
        this.loading.text = 'yyy';
        setTimeout(() => {
          this.loading.close();
        }, 5000);
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')


问:
JavaScript - How to make sure array manipulations are persistent inside a function?
I am trying to write a JavaScript function (ES5) that will take in an array, filter it, and set the original array to the new one.

Here is my plunk: https://plnkr.co/edit/OWeOjJ3SLVGYRaweyy3Z

Here is the basic pseudocode of what I am trying to do:

```<code>var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '2017116' };
deleteEntry(data, result);
console.log(result); //should  have one entry

function deleteEntry(data, result) {
  result = result.filter(function(item) {
    return item.date !== data.date;
  });
}
</code>```

I believe the issue is to do with array references. I am not sure how to accomplish the task.

答:
You could use Array#splice where you delete all elements and add the new elements of filtering.

function deleteEntry(data, result) {
    Array.prototype.splice.apply(result, [0, result.length].concat(result.filter(function(item) {
        return item.date !== data.date;
    })));
}

var result = [{ date: '20171116' }, { date: '20171115' }],
    data = { date: '20171116' };

deleteEntry(data, result);
console.log(result);```
</div>
</div>
</p>

<p>ES6</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function deleteEntry(data, result) {
    var temp = result.filter(item => item.date !== data.date);
    result.length = 0;
    result.push(...temp);
}

var result = [{ date: '20171116' }, { date: '20171115' }],
    data = { date: '20171116' };

deleteEntry(data, result);
console.log(result);</code>```

Body:
I am trying to write a JavaScript function (ES5) that will take in an array, filter it, and set the original array to the new one.

Here is my plunk: https://plnkr.co/edit/OWeOjJ3SLVGYRaweyy3Z

Here is the basic pseudocode of what I am trying to do:

var result = [{ 'date': '20171116' }, { 'date': '20171115' }];
var data = { 'date': '2017116' };
deleteEntry(data, result);
console.log(result); //should  have one entry

function deleteEntry(data, result) {
  result = result.filter(function(item) {
    return item.date !== data.date;
  });
}

I believe the issue is to do with array references. I am not sure how to accomplish the task.

Body:
You could use Array#splice where you delete all elements and add the new elements of filtering.

function deleteEntry(data, result) {
    Array.prototype.splice.apply(result, [0, result.length].concat(result.filter(function(item) {
        return item.date !== data.date;
    })));
}

var result = [{ date: '20171116' }, { date: '20171115' }],
    data = { date: '20171116' };

deleteEntry(data, result);
console.log(result);

ES6

function deleteEntry(data, result) {
    var temp = result.filter(item => item.date !== data.date);
    result.length = 0;
    result.push(...temp);
}

var result = [{ date: '20171116' }, { date: '20171115' }],
    data = { date: '20171116' };

deleteEntry(data, result);
console.log(result);


问:
how to draw a horizontal and vertical line under specific gridcolumn in wpf
I'm trying to draw a vertical line under a specific column.so anyone tell me how to draw a line horizontally and vertically

```<code><Window x:Class="WPFDataGrid.GroupBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="GroupBox" Height="300" Width="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="186"/>
        <RowDefinition Height="72"/>
        <RowDefinition Height="3*" />
    </Grid.RowDefinitions>
    <GroupBox Header="Select Option" Height="150" HorizontalAlignment="Left"  Name="gb1" VerticalAlignment="Top" Width="250" BorderBrush="Black" BorderThickness="1" Margin="11" Padding="11">
        <StackPanel>
            <CheckBox Content="Add Cream" Margin="3.5"/>
            <CheckBox Content="Add Suger" Margin="3.5"/>
            <CheckBox Content="Add Flavering" Margin="3.5"/>
            <CheckBox Content="Add Biscuit" Margin="3.5"/>
        </StackPanel>
    </GroupBox>
    <Separator Grid.Row="1" HorizontalAlignment="Center" BorderThickness="1" BorderBrush="Black" />
</Grid>
</code>```

答:
```<code><Grid>
            <Grid.Resources>
                <Style x:Key="lineStyle" TargetType="Line">
                    <Setter Property="Stroke" Value="Gray" />
                    <Setter Property="Stretch" Value="Fill" />
                    <Setter Property="Grid.ZIndex" Value="100" />
                </Style>

                <Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">
                    <Setter Property="X2" Value="1" />
                    <Setter Property="X1" Value="0" />
                    <Setter Property="VerticalAlignment" Value="Bottom" />
                    <Setter Property="Grid.ColumnSpan"
                            Value="{Binding
                            Path=ColumnDefinitions.Count,
                            RelativeSource={RelativeSource AncestorType=Grid}}" />
                    <Setter Property="Stroke" Value="Black"/>
                    <Setter Property="StrokeThickness" Value="1"/>
                </Style>

                <Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">
                    <Setter Property="Y2" Value="1" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="Grid.RowSpan"
                            Value="{Binding
                            Path=RowDefinitions.Count,
                            RelativeSource={RelativeSource AncestorType=Grid}}" />
                    <Setter Property="Stroke" Value="Black"/>
                    <Setter Property="StrokeThickness" Value="1"/>
                </Style>
            </Grid.Resources>

            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <Line Style="{StaticResource horizontalLineStyle}" />
            <Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}" />
            <Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}" />

            <Line Grid.Column="0" Style="{StaticResource verticalLineStyle}" />
            <Line Grid.Column="1" Style="{StaticResource verticalLineStyle}" />
            <Line Grid.Column="2" Style="{StaticResource verticalLineStyle}" />
            <Line Grid.Column="3" Style="{StaticResource verticalLineStyle}" />
            <Line Grid.Column="4" Style="{StaticResource verticalLineStyle}" />

            <Label Content="" Grid.Row="0" Grid.Column="0" HorizontalContentAlignment="Center" FontWeight="Bold" Foreground="White"/>
            <Label Content="Dword" Grid.Row="0" Grid.Column="1" HorizontalContentAlignment="Center" FontWeight="Bold" Foreground="White"/>
            <Label Content="Words" Grid.Row="0" Grid.Column="2" HorizontalContentAlignment="Center" FontWeight="Bold" Foreground="White"/>
            <Label Content="Bytes" Grid.Row="0" Grid.Column="3" HorizontalContentAlignment="Center" FontWeight="Bold" Foreground="White"/>
            <Label Content="Bits" Grid.Row="0" Grid.Column="4" HorizontalContentAlignment="Center" FontWeight="Bold" Foreground="White"/>
</Grid>
</code>```

Body:
I'm trying to draw a vertical line under a specific column.so anyone tell me how to draw a line horizontally and vertically

<Window x:Class="WPFDataGrid.GroupBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="GroupBox" Height="300" Width="300">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="186"/>
        <RowDefinition Height="72"/>
        <RowDefinition Height="3*" />
    </Grid.RowDefinitions>
    <GroupBox Header="Select Option" Height="150" HorizontalAlignment="Left"  Name="gb1" VerticalAlignment="Top" Width="250" BorderBrush="Black" BorderThickness="1" Margin="11" Padding="11">
        <StackPanel>
            <CheckBox Content="Add Cream" Margin="3.5"/>
            <CheckBox Content="Add Suger" Margin="3.5"/>
            <CheckBox Content="Add Flavering" Margin="3.5"/>
            <CheckBox Content="Add Biscuit" Margin="3.5"/>
        </StackPanel>
    </GroupBox>
    <Separator Grid.Row="1" HorizontalAlignment="Center" BorderThickness="1" BorderBrush="Black" />
</Grid>


问:
How to assign column names to a table
I am working with the following data in Rstudio. I am trying to assign column names to the data. I have employed the following commands:

```<code>nlsdata -> read.table("C:/Users/perdue/Desktop/Adv.MicroEconometrics/HA 3/data/nls.dat",
                       header = FALSE, dec = ".")
</code>```

This command returns as a first row column names 'v1 v2 v3... v52'. When I follow with

```<code>colnames(nlsdata)
</code>```

I get a list of names: v1, v2, ..., v52. Then

```<code>col.names(nlsdata) <- c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66","age76",
                        "daded","nodaded","momed","nomomed","weight","momdad14","sinmom14",
                        "step14","reg661","reg662","reg663","reg664","reg665","reg666","reg667",
                        "reg668","reg669","south66","work76","work78","lwage76","lwage78",
                        "famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r",
                        "smsa66r","wage76","wage78","wage80","noint78","enroll76","enroll78",
                        "enroll80","kww","iq","marsta76","marsta78","marsta80","libcrd14")

where newname[i] is the ith column name of dataframe nlsdata`
</code>```

```<code>Error: unexpected symbol in ""south66","work76","work78","lwage76","lwage78","famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76","wage78","wage80", "noint78","enroll76","enroll78","enroll80","
</code>```

The error messages seem to suggest a syntax error. I have loooked – more than once – and can't find/recognize one.

答:
The error you were getting seems to be about these two quotes:

```<code>""south66"
</code>```

readr::read_table() does a good job of reading the file:

```<code>library(readr)
url <- "https://raw.githubusercontent.com/108michael/ms_thesis/ca258bc684c3a6f8ade13769590439ad1e8387d7/nls.dat"
col_names = c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66",
  "age76","daded","nodaded","momed","nomomed","weight","momdad14","sinmom14",
  "step14","reg661", "reg662","reg663","reg664","reg665","reg666","reg667",
  "reg668","reg669","south66","work76","work78","lwage76","lwage78","famed",
  "black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76",
  "wage78","wage80","noint78","enroll76","enroll78","enroll80",
  "kww","iq","marsta76","marsta78","marsta80","libcrd14")
read_table( url, col_names = col_names, na = "." )
#> Parsed with column specification:
#> cols(
#>   .default = col_integer(),
#>   daded = col_double(),
#>   momed = col_double(),
#>   lwage76 = col_double(),
#>   lwage78 = col_double()
#> )
#> See spec(...) for full column specifications.
#> # A tibble: 3,613 x 51
#>    inputid nearc2 nearc4 nearc4a nearc4b  ed76  ed66 age76 daded nodaded
#>      <int>  <int>  <int>   <int>   <int> <int> <int> <int> <dbl>   <int>
#>  1       2      0      0       0       0     7     5    29  9.94       1
#>  2       3      0      0       0       0    12    11    27  8.00       0
#>  3       4      0      0       0       0    12    12    34 14.00       0
#>  4       5      1      1       1       0    11    11    27 11.00       0
#>  5       6      1      1       1       0    12    12    34  8.00       0
#>  6       7      1      1       1       0    12    11    26  9.00       0
#>  7       8      1      1       1       0    18    16    33 14.00       0
#>  8       9      1      1       1       0    14    13    29 14.00       0
#>  9      10      1      1       1       0    12    12    28 12.00       0
#> 10      11      1      1       1       0    12    12    29 12.00       0
#> # ... with 3,603 more rows, and 41 more variables: momed <dbl>,
#> #   nomomed <int>, weight <int>, momdad14 <int>, sinmom14 <int>,
#> #   step14 <int>, reg661 <int>, reg662 <int>, reg663 <int>, reg664 <int>,
#> #   reg665 <int>, reg666 <int>, reg667 <int>, reg668 <int>, reg669 <int>,
#> #   south66 <int>, work76 <int>, work78 <int>, lwage76 <dbl>,
#> #   lwage78 <dbl>, famed <int>, black <int>, smsa76r <int>, smsa78r <int>,
#> #   reg76r <int>, reg78r <int>, reg80r <int>, smsa66r <int>, wage76 <int>,
#> #   wage78 <int>, wage80 <int>, noint78 <int>, enroll76 <int>,
#> #   enroll78 <int>, enroll80 <int>, kww <int>, iq <int>, marsta76 <int>,
#> #   marsta78 <int>, marsta80 <int>, libcrd14 <int>
</code>```

Title: How to assign column names to a table

Body:
I am working with the following data in Rstudio. I am trying to assign column names to the data. I have employed the following commands:

nlsdata -> read.table("C:/Users/perdue/Desktop/Adv.MicroEconometrics/HA 3/data/nls.dat",
                       header = FALSE, dec = ".")

This command returns as a first row column names 'v1 v2 v3... v52'. When I follow with

colnames(nlsdata)

I get a list of names: v1, v2, ..., v52. Then

col.names(nlsdata) <- c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66","age76",
                        "daded","nodaded","momed","nomomed","weight","momdad14","sinmom14",
                        "step14","reg661","reg662","reg663","reg664","reg665","reg666","reg667",
                        "reg668","reg669","south66","work76","work78","lwage76","lwage78",
                        "famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r",
                        "smsa66r","wage76","wage78","wage80","noint78","enroll76","enroll78",
                        "enroll80","kww","iq","marsta76","marsta78","marsta80","libcrd14")

where newname[i] is the ith column name of dataframe nlsdata`

Error: unexpected symbol in ""south66","work76","work78","lwage76","lwage78","famed","black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76","wage78","wage80", "noint78","enroll76","enroll78","enroll80","

The error messages seem to suggest a syntax error. I have loooked – more than once – and can't find/recognize one.

Body:
The error you were getting seems to be about these two quotes:

""south66"

readr::read_table() does a good job of reading the file:

library(readr)
url <- "https://raw.githubusercontent.com/108michael/ms_thesis/ca258bc684c3a6f8ade13769590439ad1e8387d7/nls.dat"
col_names = c("inputid","nearc2","nearc4","nearc4a","nearc4b","ed76","ed66",
  "age76","daded","nodaded","momed","nomomed","weight","momdad14","sinmom14",
  "step14","reg661", "reg662","reg663","reg664","reg665","reg666","reg667",
  "reg668","reg669","south66","work76","work78","lwage76","lwage78","famed",
  "black","smsa76r","smsa78r","reg76r","reg78r","reg80r","smsa66r","wage76",
  "wage78","wage80","noint78","enroll76","enroll78","enroll80",
  "kww","iq","marsta76","marsta78","marsta80","libcrd14")
read_table( url, col_names = col_names, na = "." )
#> Parsed with column specification:
#> cols(
#>   .default = col_integer(),
#>   daded = col_double(),
#>   momed = col_double(),
#>   lwage76 = col_double(),
#>   lwage78 = col_double()
#> )
#> See spec(...) for full column specifications.
#> # A tibble: 3,613 x 51
#>    inputid nearc2 nearc4 nearc4a nearc4b  ed76  ed66 age76 daded nodaded
#>      <int>  <int>  <int>   <int>   <int> <int> <int> <int> <dbl>   <int>
#>  1       2      0      0       0       0     7     5    29  9.94       1
#>  2       3      0      0       0       0    12    11    27  8.00       0
#>  3       4      0      0       0       0    12    12    34 14.00       0
#>  4       5      1      1       1       0    11    11    27 11.00       0
#>  5       6      1      1       1       0    12    12    34  8.00       0
#>  6       7      1      1       1       0    12    11    26  9.00       0
#>  7       8      1      1       1       0    18    16    33 14.00       0
#>  8       9      1      1       1       0    14    13    29 14.00       0
#>  9      10      1      1       1       0    12    12    28 12.00       0
#> 10      11      1      1       1       0    12    12    29 12.00       0
#> # ... with 3,603 more rows, and 41 more variables: momed <dbl>,
#> #   nomomed <int>, weight <int>, momdad14 <int>, sinmom14 <int>,
#> #   step14 <int>, reg661 <int>, reg662 <int>, reg663 <int>, reg664 <int>,
#> #   reg665 <int>, reg666 <int>, reg667 <int>, reg668 <int>, reg669 <int>,
#> #   south66 <int>, work76 <int>, work78 <int>, lwage76 <dbl>,
#> #   lwage78 <dbl>, famed <int>, black <int>, smsa76r <int>, smsa78r <int>,
#> #   reg76r <int>, reg78r <int>, reg80r <int>, smsa66r <int>, wage76 <int>,
#> #   wage78 <int>, wage80 <int>, noint78 <int>, enroll76 <int>,
#> #   enroll78 <int>, enroll80 <int>, kww <int>, iq <int>, marsta76 <int>,
#> #   marsta78 <int>, marsta80 <int>, libcrd14 <int>


问:
Looping through JSON object in Swift
I got this JSON object which I sent from my server to my Swift application.

```<code>{
  "625289": {
    "id": 1,
    "subject": "Hello World"
  },
  "625277": {
    "id": 2,
    "subject":"Bye World!"
  }
}
</code>```

So i tried to get the subject for each result ("625289" and "625277") by doing as below in my Swift class:

```<code>struct Resultat : Decodable   {
  let subject: String
}

var result = [Resultat]()
let urlll = URL(string:"http://localhost:8888/api/pouet.php")

URLSession.shared.dataTask(with: urlll!) { (data, response, error) in
  do {
    print("coucoulol")
    //print(response)

    self.result = try JSONDecoder().decode([Resultat].self, from: data!)

    print(self.result)

    for eachTicket in self.result {
      print(eachTicket.subject)
    }
  } catch {
    print("error"+error.localizedDescription)
  }
}.resume()
</code>```

However, when I tried to execute the code, it says "The data couldn’t be read because it isn’t in the correct format." From what I understand, the loop for in the code is suffice to get the values in the arrays or maybe I'm wrong. Any help is appreciated, thanks.

答:
The root object is a dictionary. You can decode the object to [String:Resultat]. The dictionary contains also dictionaries. An array is not involved.

```<code>struct Resultat : Decodable {
    let subject: String
    let id : Int
}
</code>```

```<code>...
let result = try JSONDecoder().decode([String:Resultat].self, from: data!)
for (key, value) in result {
    print(key, value.subject)
}
</code>```

Title: Looping through JSON object in Swift

Body:
I got this JSON object which I sent from my server to my Swift application.

{
  "625289": {
    "id": 1,
    "subject": "Hello World"
  },
  "625277": {
    "id": 2,
    "subject":"Bye World!"
  }
}

So i tried to get the subject for each result ("625289" and "625277") by doing as below in my Swift class:

struct Resultat : Decodable   {
  let subject: String
}

var result = [Resultat]()
let urlll = URL(string:"http://localhost:8888/api/pouet.php")

URLSession.shared.dataTask(with: urlll!) { (data, response, error) in
  do {
    print("coucoulol")
    //print(response)

    self.result = try JSONDecoder().decode([Resultat].self, from: data!)

    print(self.result)

    for eachTicket in self.result {
      print(eachTicket.subject)
    }
  } catch {
    print("error"+error.localizedDescription)
  }
}.resume()

However, when I tried to execute the code, it says "The data couldn’t be read because it isn’t in the correct format." From what I understand, the loop for in the code is suffice to get the values in the arrays or maybe I'm wrong. Any help is appreciated, thanks.

Body:
The root object is a dictionary. You can decode the object to [String:Resultat]. The dictionary contains also dictionaries. An array is not involved.

struct Resultat : Decodable {
    let subject: String
    let id : Int
}

...
let result = try JSONDecoder().decode([String:Resultat].self, from: data!)
for (key, value) in result {
    print(key, value.subject)
}


问:
Check if my app has a new version on AppStore
I would like to manually check if there are new updates for my app while the user is in it, and prompt him to download the new version. Can I do this by checking the version of my app in the app store - programatically?</p>

答:
Swift 3.1

```<code>func needsUpdate() -> Bool {
    let infoDictionary = Bundle.main.infoDictionary
    let appID = infoDictionary!["CFBundleIdentifier"] as! String
    let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(appID)")
    guard let data = try? Data(contentsOf: url) else {
      print("There is an error!")
      return false;
    }
    let lookup = (try? JSONSerialization.jsonObject(with: data! , options: [])) as? [String: Any]
    if let resultCount = lookup!["resultCount"] as? Int, resultCount == 1 {
        if let results = lookup!["results"] as? [[String:Any]] {
            if let appStoreVersion = results[0]["version"] as? String{
                let currentVersion = infoDictionary!["CFBundleShortVersionString"] as? String
                if !(appStoreVersion == currentVersion) {
                    print("Need to update [\(appStoreVersion) != \(currentVersion)]")
                    return true
                }
            }
        }
    }
    return false
}
</code>```

Body:
Swift 3.1

func needsUpdate() -> Bool {
    let infoDictionary = Bundle.main.infoDictionary
    let appID = infoDictionary!["CFBundleIdentifier"] as! String
    let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(appID)")
    guard let data = try? Data(contentsOf: url) else {
      print("There is an error!")
      return false;
    }
    let lookup = (try? JSONSerialization.jsonObject(with: data! , options: [])) as? [String: Any]
    if let resultCount = lookup!["resultCount"] as? Int, resultCount == 1 {
        if let results = lookup!["results"] as? [[String:Any]] {
            if let appStoreVersion = results[0]["version"] as? String{
                let currentVersion = infoDictionary!["CFBundleShortVersionString"] as? String
                if !(appStoreVersion == currentVersion) {
                    print("Need to update [\(appStoreVersion) != \(currentVersion)]")
                    return true
                }
            }
        }
    }
    return false
}


问:
Windows Installer: can two different installer share the same componet
I have two installers - one for 64-bit Windows and another for 32-bit Windows. The 32-bit installer installs 32-bit executable and DLls, while the 64-bit installer installs 64-bit exes and dlls as well as the 32-bit ones. The 32-bit components are shared by both installers.

Does Windows Installer explicitly allow this scenario? Thanks.

答: Yes, this is supported. Just make sure that the 32-bit components have the same names and GUIDs in both installers. This way a reference count is used for them.</p>


问:
Get elements by id array and order by this array
I want te get, for example, products by id array but I want these products on same order that id array.

For example, I want products with id 6, 3, 8:

```<code>ids = [6, 3, 8]
Product.where(id: ids)
</code>```

It gives me products but the first is product with id = 3, second with id = 6...

And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...

How could I do that in Products query?

答:
Indexing should work:

```<code>Product.where(id: ids).index_by(&:id).values_at(*ids)
</code>```

Or just (checked in MySQL, but sanitize ids before if ids are coming from external source):

```<code>Product.where(id: ids).order("field(id, #{ids.join(', ')})")
</code>```

Body:
I want te get, for example, products by id array but I want these products on same order that id array.

For example, I want products with id 6, 3, 8:

ids = [6, 3, 8]
Product.where(id: ids)

It gives me products but the first is product with id = 3, second with id = 6...

And I want these products in same order that ids array. I want the first product with id = 6, the second with id = 3...

How could I do that in Products query?

Body:
Indexing should work:

Product.where(id: ids).index_by(&:id).values_at(*ids)

Or just (checked in MySQL, but sanitize ids before if ids are coming from external source):

Product.where(id: ids).order("field(id, #{ids.join(', ')})")


问:
MVVM Light DispatcherHelper & Unit Testing w/MSTest
I considered putting this as an additional question in this thread:

Unit testing with MVVM Light & DispatcherHelper

but as I delved into it, I think it's a little different.

I have one project containing view models/views, a separate project containing models, and a third separate unit test project (MSTest) containing tests for the models.  I'm using MVVM Light's DispatcherHelper to help me do work in a background task, but to get errors from that task back to the UI.

The view model/view project has the App.xaml.cs file, which contains the OnStartup event handler, in which I've put the DispatcherHelper.Initialize() call.  One of the VMs invokes a call to one of the model's long-running methods on another thread using delegate.BeginInvoke():

```<code>     FileProcessDelegate processor = GenerateAddressingFile;
     processor.BeginInvoke(FileGenerationComplete, null);
</code>```

In this long-running method, it calls a utility method to send errors back to the UI.  These are in the form of mvvm-light messages that are sent using the DispatcherHelper.CheckBeginInvokeOnUI()

```<code>    internal static void ReportErrorToUi(IFileError error)
    {
        DispatcherHelper.CheckBeginInvokeOnUI(
            () => Messenger.Default.Send(new GenericMessage<IFileError>(error), MessageTokens.ReportFileError));
    }
</code>```

This all seems to work fine in the app.

In one of the unit test classes for the model, I attempt to check that the long-running method correctly sends messages when errors occur.  In that test class, I have a call to DispatcherHelper.Initialize() in the MSTest class initialization method.

```<code>    #region Additional test attributes
    //
    //You can use the following additional attributes as you write your tests:
    //
    //Use ClassInitialize to run code before running the first test in the class
    [ClassInitialize]
    public static void MyClassInitialize(TestContext testContext)
    {
        DispatcherHelper.Initialize();
    }
</code>```

The test registers for the message that should be sent, then calls the model's method directly, without invoking it on a separate thread.  As I understand it, because the call to send the message is wrapped by DispatcherHelper.CheckBeginInvokeOnUI() in the model, it  should do the right thing regardless of whether it is occurring on a background thread or on the UI thread.

In the first test of this class that checks the method, everything works fine.  The test receives the error messages being sent back and passes with flying colors.

When subsequent tests in the same class run, the messages are never received by the test.  When I've stepped through it on these subsequent tests, I notice that when I get to the  DispatcherHelper.CheckBeginInvokeOnUI() method, the DispatcherHelper.UIDispatcher.Thread instance says it's dead.

Any thoughts?

答:
Testing async code is tricky. Typically, if it works once, and then not anymore, it sounds like you are not synchronizing your threads correctly. In your test method (main thread), are you waiting for the background thread to execute?

Jonas Follesoe wrote a few good articles about async unit testing in Silverlight, for example http://jonas.follesoe.no/2007/09/18/unit-testing-event-based-asynchronous-code/. This is typically how I unit test my async code too.

Hope this helps,
Laurent

Body:
I considered putting this as an additional question in this thread:

Unit testing with MVVM Light & DispatcherHelper

but as I delved into it, I think it's a little different.

I have one project containing view models/views, a separate project containing models, and a third separate unit test project (MSTest) containing tests for the models.  I'm using MVVM Light's DispatcherHelper to help me do work in a background task, but to get errors from that task back to the UI.

The view model/view project has the App.xaml.cs file, which contains the OnStartup event handler, in which I've put the DispatcherHelper.Initialize() call.  One of the VMs invokes a call to one of the model's long-running methods on another thread using delegate.BeginInvoke():

     FileProcessDelegate processor = GenerateAddressingFile;
     processor.BeginInvoke(FileGenerationComplete, null);

In this long-running method, it calls a utility method to send errors back to the UI.  These are in the form of mvvm-light messages that are sent using the DispatcherHelper.CheckBeginInvokeOnUI()

    internal static void ReportErrorToUi(IFileError error)
    {
        DispatcherHelper.CheckBeginInvokeOnUI(
            () => Messenger.Default.Send(new GenericMessage<IFileError>(error), MessageTokens.ReportFileError));
    }

This all seems to work fine in the app.

In one of the unit test classes for the model, I attempt to check that the long-running method correctly sends messages when errors occur.  In that test class, I have a call to DispatcherHelper.Initialize() in the MSTest class initialization method.

    #region Additional test attributes
    //
    //You can use the following additional attributes as you write your tests:
    //
    //Use ClassInitialize to run code before running the first test in the class
    [ClassInitialize]
    public static void MyClassInitialize(TestContext testContext)
    {
        DispatcherHelper.Initialize();
    }

The test registers for the message that should be sent, then calls the model's method directly, without invoking it on a separate thread.  As I understand it, because the call to send the message is wrapped by DispatcherHelper.CheckBeginInvokeOnUI() in the model, it  should do the right thing regardless of whether it is occurring on a background thread or on the UI thread.

In the first test of this class that checks the method, everything works fine.  The test receives the error messages being sent back and passes with flying colors.

When subsequent tests in the same class run, the messages are never received by the test.  When I've stepped through it on these subsequent tests, I notice that when I get to the  DispatcherHelper.CheckBeginInvokeOnUI() method, the DispatcherHelper.UIDispatcher.Thread instance says it's dead.

Any thoughts?


问:
Send +1 Day on JQuery DatePicker
I want to emit the day after the selected day.

```<code>$('#toDate').datepicker({
        inline: true,
        altField: '#x',
        dateFormat: "dd-mm-yy", //day
        altFormat: "yy-mm-dd", //year
        monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
        dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
        firstDay: 1,
        numberOfMonths: 1,
        onSelect: function(dateText, inst) {
          socket.emit('sockettoDate', $('#x').val());
        }
      });
</code>```

If '2017-11-16' selected, I want to emit '2017-11-17'. Is there any way to do that?

答:
There are two inputBoxes; But at any time only one would be visible;

I have added a different label so that u can differentiate after date changes;

Tweak it to meet your needs.

$('#toDate').datepicker({
        inline: true,
        altField: '#x',
        dateFormat: "dd-mm-yy", //day
        altFormat: "yy-mm-dd", //year
        monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
        dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
        firstDay: 1,
        numberOfMonths: 1,
        onSelect: function(dateText, inst) {
            showHideDate(dateText);
        }
      });

 function showHideDate(dateText) {
   document.getElementById("defaultDate").style.display = "none";
   document.getElementById("hiddenDate").style.display = "block";
   let splittedDate = dateText.split("-");
   let nextDay = parseInt(splittedDate[0])+1
   let newDate =  nextDay + '-' + splittedDate[1] + '-' + splittedDate[2];

   document.getElementById("newDate").value = newDate;
 }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#hiddenDate {
  display:none;
}</code>```

Date: <input type="text" id="toDate">

New Date: <input type="text" id="newDate">
```

Title: Send +1 Day on JQuery DatePicker

Body:
I want to emit the day after the selected day.

$('#toDate').datepicker({
        inline: true,
        altField: '#x',
        dateFormat: "dd-mm-yy", //day
        altFormat: "yy-mm-dd", //year
        monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
        dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
        firstDay: 1,
        numberOfMonths: 1,
        onSelect: function(dateText, inst) {
          socket.emit('sockettoDate', $('#x').val());
        }
      });

If '2017-11-16' selected, I want to emit '2017-11-17'. Is there any way to do that?

Body:
There are two inputBoxes; But at any time only one would be visible;

I have added a different label so that u can differentiate after date changes;

Tweak it to meet your needs.

$('#toDate').datepicker({
        inline: true,
        altField: '#x',
        dateFormat: "dd-mm-yy", //day
        altFormat: "yy-mm-dd", //year
        monthNames: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"],
        dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
        firstDay: 1,
        numberOfMonths: 1,
        onSelect: function(dateText, inst) {
            showHideDate(dateText);
        }
      });

 function showHideDate(dateText) {
   document.getElementById("defaultDate").style.display = "none";
   document.getElementById("hiddenDate").style.display = "block";
   let splittedDate = dateText.split("-");
   let nextDay = parseInt(splittedDate[0])+1
   let newDate =  nextDay + '-' + splittedDate[1] + '-' + splittedDate[2];

   document.getElementById("newDate").value = newDate;
 }

#hiddenDate {
  display:none;
}

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p id="defaultDate">Date: <input type="text" id="toDate"></p>
<p id="hiddenDate">New Date: <input type="text" id="newDate"></p>


问:
Thrust vector slice/view
I have a matrix (row oriented) inside a thrust::device_vector<T>. Is there any way to get a slice/view of that vector (that would also be of type thrust::device_vector<T>)? I'm not interested in copy constructors as those create new vectors and use memory.

So basically assuming we have a vector thrust::device_vector<int> vec = {1,2,3,4,5,6} I'd like to do thrust::device_vector<int> vec_view = vec.slice(2,4) that would be a view pointing to {3,4}.

Need to run certain computations on it in batches and the method I'm using takes only thrust:device_vector<T> (no iterators etc.).

答:
There is no way to do this that I am aware of.

Thrust doesn't expose a device_vector constructor which accepts an existing device_pointer. Were that the case, you could potentially implement you own device_pointer which supported strided access or slicing, etc. But I don't know of a way to achieve what you envisage without recourse to fancy iterators, and apparently those are not viable for your use case.

Title: Thrust vector slice/view


问:
react redirect to another page not working
I want to redirect to home page after successful login.I searched throughly but didn't find the solution to this. Thanks in advance</p>

```<code>//imported react-router
import { Redirect } from 'react-router';

//main route file
<Router>
  <div>
    <Route exact path = "/" component={ App } />
    <Route path = "/home" component={ Homepage } />
  </div>
</Router>

//redirect after ajax success
$.ajax({
    type: 'POST',
    url: '/login_participant',
    data: data,
    dataType:'json',
    success:function(data) {
         console.log(data);

         //redirecting home after login successfully
         <Redirect to ="/home" />
    },
    error:function(err) {
         console.log(err);
    }
})
</code>```

答:
<Redirect /> is a simple component, that takes some props and do something with that. It has contract with other components provided by react-router, so it has to know what is the context.

If you want to redirect after successful login, you either have to use react-router-redux (push action) or to keep state flag isUserLoggedIn or sth like that to provide data to your components. Both solution requires using redux/flux or other state container.

If you don't want to use redux/flux, maybe just replace window location? (pathname).

It's all from my side, maybe others have better solution.

Body:
I want to redirect to home page after successful login.I searched throughly but didn't find the solution to this. Thanks in advance

//imported react-router
import { Redirect } from 'react-router';

//main route file
<Router>

    <Route exact path = "/" component={ App } />
    <Route path = "/home" component={ Homepage } />

</Router>

//redirect after ajax success
$.ajax({
    type: 'POST',
    url: '/login_participant',
    data: data,
    dataType:'json',
    success:function(data) {
         console.log(data);

         //redirecting home after login successfully
         <Redirect to ="/home" />
    },
    error:function(err) {
         console.log(err);
    }
})


问:
Import tensorflow in jupyter notebook fails
When updating tensorflow to version 1.4, cudnn to version 6 and setting up SSL encryption and a password on my jupyter notebook server I constantly got the following error in notebooks:

```<code>ImportError: libcudnn.so.6: cannot open shared object file: No such file or directory
</code>```

Importing tensorflow inside python3 -i worked fine.

答:
I realised that the necessary environment variable LD_LIBRARY_PATH is set when testing it with echo $LD_LIBRARY_PATH on the host but print(os.getenv('LD_LIBRARY_PATH')) in notebooks results in a KeyError.

Setting the variable in .bashrc and .profile didn't change anything.

The solution was to run jupyter notebook with a modified environment with env LD_LIBRARY_PATH=$LD_LIBRARY_PATH jupyter notebook.

Body:
When updating tensorflow to version 1.4, cudnn to version 6 and setting up SSL encryption and a password on my jupyter notebook server I constantly got the following error in notebooks:

ImportError: libcudnn.so.6: cannot open shared object file: No such file or directory

Importing tensorflow inside python3 -i worked fine.


问:
Positionning button from bottom screen
I am doing some XML for an android app.

I have images, text, and button in my view.

I used a Linear layout, but I think it's not what I need.

I would like to set my last button to 80 dp from the bottom screen. Regardless the smartphone and the size of the screen.
I want my button to be at 80 dp from the bottom of all device.

I have no idea how to do it if someone can help me it could be cool!

I tried with a LinearLayout but i think i can't do it.

Now I'm trying with a constraintLayout but I'm not sure it will work.

Thanks

答:
Use Relative layout as parent layout not Linear Layout after that use this code
ADD Views inside this Relative Layout whatever you want to add like Textview etc.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button at bottom"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="80dp"/>

    </RelativeLayout>
</code>```

Title: Positionning button from bottom screen

Body:
Use Relative layout as parent layout not Linear Layout after that use this code
ADD Views inside this Relative Layout whatever you want to add like Textview etc.

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Button at bottom"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="80dp"/>

    </RelativeLayout>


问:
Access list of all apps currently using hardware features
is there a possibility to access the number or even the name of apps and processes using some hardware elements such as camera or mic in Android? </p>

答:
The way to go about this would be to first find apps with features and then find the corresponding pid. If you are not root I don't think it is possible to get system services. Also getting pid is difficult.
Have a look at this github link.It works only below Android N.

Apps need to have permission declared to use hardware in their manifest.
For example, android.permission.RECORD_AUDIO to record audio or android.permission.CAMERA to use camera.

For more information on Permissions have a look at this official google doc.

```<code>String[] permissions = context.getPackageManager().getPackageInfo("Enter Your PackageName Here", PackageManager.GET_PERMISSIONS)
.requestedPermissions

for (String permission : permissions) {
    if(permission.equals("hardware permission like camera or record audio")){
        //Do Stuff here
       //Use the methods given in the gihtub link above to get PID
      //Below code is take from the github link given above
        List<AndroidAppProcess> processes =AndroidProcesses.getRunningAppProcesses();

        for (AndroidAppProcess process : processes) {
          // Get some information about the process
          String processName = process.name;

          Stat stat = process.stat();
          int pid = stat.getPid();
          int parentProcessId = stat.ppid();
          long startTime = stat.stime();
          int policy = stat.policy();
          char state = stat.state();

          Statm statm = process.statm();
          long totalSizeOfProcess = statm.getSize();
          long residentSetSize = statm.getResidentSetSize();

          PackageInfo packageInfo = process.getPackageInfo(context, 0);
          String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
        }
    }
}
</code>```

Manually if you want to check run adb shell and via top check if the corresponding uid is running.

Body:
The way to go about this would be to first find apps with features and then find the corresponding pid. If you are not root I don't think it is possible to get system services. Also getting pid is difficult.
Have a look at this github link.It works only below Android N.

Apps need to have permission declared to use hardware in their manifest.
For example, android.permission.RECORD_AUDIO to record audio or android.permission.CAMERA to use camera.

For more information on Permissions have a look at this official google doc.

String[] permissions = context.getPackageManager().getPackageInfo("Enter Your PackageName Here", PackageManager.GET_PERMISSIONS)
.requestedPermissions

for (String permission : permissions) {
    if(permission.equals("hardware permission like camera or record audio")){
        //Do Stuff here
       //Use the methods given in the gihtub link above to get PID
      //Below code is take from the github link given above
        List<AndroidAppProcess> processes =AndroidProcesses.getRunningAppProcesses();

        for (AndroidAppProcess process : processes) {
          // Get some information about the process
          String processName = process.name;

          Stat stat = process.stat();
          int pid = stat.getPid();
          int parentProcessId = stat.ppid();
          long startTime = stat.stime();
          int policy = stat.policy();
          char state = stat.state();

          Statm statm = process.statm();
          long totalSizeOfProcess = statm.getSize();
          long residentSetSize = statm.getResidentSetSize();

          PackageInfo packageInfo = process.getPackageInfo(context, 0);
          String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
        }
    }
}

Manually if you want to check run adb shell and via top check if the corresponding uid is running.


问:
How can I join two tables but only return rows that don't match specific column which include NULL as well?
I have two tables which look like this:

```<code>T1:  ID  |  oldID

T2:  ID  |  newID
</code>```

I basically need to join these tables when their IDs match. However, I only want to return the results like: ID  |  oldID  |  newID where oldID do not equal to newID.

Example data:

T1: 1  |  100
     2  |  NULL
     3  |  200
     4  |  500

T2: 1  |  NULL
     2  |  300
     3  |  200
     4  |  400

My expected result:

T3: 1 | 100  | NULL
     2 | NULL | 300
     4 | 500  | 400

Can anyone point me on the right track?

答:
```<code>select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID
AND COALESCE(t1.oldID,0) <> COALESCE(t2.NewId,0)
</code>```

Explanation

```<code>select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID #IDs are equal in two tables
AND t1.oldID <> t2.NewId

Result is:
# ID, oldID, NewId
'4', '500', '400'
</code>```

If you check like this, you will not get the result as you expected, the reason is NULL value not handled properly.
But If you use COALESE means it will check as below:

COALESCE(value1,value2,value3,...)

The above syntax is equivalent to the following IF-THEN-ELSE statement

```<code>IF value1 is not NULL THEN
 result = value1;
ELSIF value2 is not NULL THEN
 result = value2;
ELSIF value3 is not NULL THEN
 result = value3;
ELSE
 result = NULL;
END IF;
</code>```

Example:
SELECT COALESCE(NULL, 2, 3);  Returns 2

So In our Query,COALESCE(t1.oldID,0) will return 0 if the t1.oldID is null..

```<code>select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID
AND COALESCE(t1.oldID,0) <> COALESCE(t2.NewId,0)
</code>```

Body:
I have two tables which look like this:

T1:  ID  |  oldID

T2:  ID  |  newID

I basically need to join these tables when their IDs match. However, I only want to return the results like: ID  |  oldID  |  newID where oldID do not equal to newID.

Example data:

T1: 1  |  100
     2  |  NULL
     3  |  200
     4  |  500

T2: 1  |  NULL
     2  |  300
     3  |  200
     4  |  400

My expected result:

T3: 1 | 100  | NULL
     2 | NULL | 300
     4 | 500  | 400

Can anyone point me on the right track?

Body:
select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID
AND COALESCE(t1.oldID,0) <> COALESCE(t2.NewId,0)

Explanation

select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID #IDs are equal in two tables
AND t1.oldID <> t2.NewId

Result is:
# ID, oldID, NewId
'4', '500', '400'

If you check like this, you will not get the result as you expected, the reason is NULL value not handled properly.
But If you use COALESE means it will check as below:

COALESCE(value1,value2,value3,...)

The above syntax is equivalent to the following IF-THEN-ELSE statement

IF value1 is not NULL THEN
 result = value1;
ELSIF value2 is not NULL THEN
 result = value2;
ELSIF value3 is not NULL THEN
 result = value3;
ELSE
 result = NULL;
END IF;

Example:
SELECT COALESCE(NULL, 2, 3);  Returns 2

So In our Query,COALESCE(t1.oldID,0) will return 0 if the t1.oldID is null..

select t1.ID,t1.oldID,t2.NewId
FROM T1 t1, T2 t2
WHERE t1.ID=t2.ID
AND COALESCE(t1.oldID,0) <> COALESCE(t2.NewId,0)


问:
Check for value definedness in C++
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

```<code>class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}
</code>```

Is it possible in C++?

Thanks

答:
Initialize bar to some value which can never occur when you call the something() function in the constructor.

For example:

```<code>Foo(): bar(-1)
{
}
</code>```

Then check for the value -1 in the get_bar function.

(hmmm Laserallan also posted that answer 1 minute before :-( ;-) )

OwnerDisplayName: Tunnuz

Title: Check for value definedness in C++

Body:
I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

Body:
Initialize bar to some value which can never occur when you call the something() function in the constructor.

For example:

Foo(): bar(-1)
{
}

Then check for the value -1 in the get_bar function.

(hmmm Laserallan also posted that answer 1 minute before :-( ;-) )

OwnerDisplayName: RoccoD


问:
What is the type of the object which is assigned to null
In following code, what is the type of s

```<code>scala> val s:String = null
s: String = null

//cannot check if instance is of type Null
scala> s.isInstanceOf[Null]
<console>:13: error: type Null cannot be used in a type pattern or isInstanceOf test
       s.isInstanceOf[Null]
                     ^

//s is no longer a String or Any or AnyRef
scala> s.isInstanceOf[String]
res2: Boolean = false

scala> s.isInstanceOf[AnyRef]
res4: Boolean = false

scala> s.isInstanceOf[Any]
res5: Boolean = false

scala> s.isInstanceOf[Object]
res11: Boolean = false
</code>```

答:
Well, the null is just null and it will not be as object,where the object is father of all classes then if null is an object then this code should return true

val s:String=null;println(s.isInstanceOf[Object])

but actually it returns false so the null is just null and it will not have any type :D see the snapshot

Body:
In following code, what is the type of s

scala> val s:String = null
s: String = null

//cannot check if instance is of type Null
scala> s.isInstanceOf[Null]
<console>:13: error: type Null cannot be used in a type pattern or isInstanceOf test
       s.isInstanceOf[Null]
                     ^

//s is no longer a String or Any or AnyRef
scala> s.isInstanceOf[String]
res2: Boolean = false

scala> s.isInstanceOf[AnyRef]
res4: Boolean = false

scala> s.isInstanceOf[Any]
res5: Boolean = false

scala> s.isInstanceOf[Object]
res11: Boolean = false


问:
I want access span for hide & show purpose with class name & id name which will start with?
I want to access a span with a specific class and id (the id will start with specific pattern)

```<code><span id='asd111' class="demo"></span>
<span id='asd122' class="demo"></span>
<span id='asd133' class="demo"></span>
<span id='asd144' class="demo"></span>
</code>```

Now I want to hide/show above spans using single jQuery statement. How can do this? All span id start with common asd1 pattern.

Please give me idea as soon as possible.

*i have just given example in this code.. those spans are coming dynamically in my code in different nested divs, so i want hide those with those id pattern & class name???

答:
with jQuery:</p>

```<code>var asds = $('*[id^="asd"]');

for( var i = 0; i < dates.length; i++) {
  $("asds:eq(" + i  + ")").hide();
}
</code>```

Body:
I want to access a span with a specific class and id (the id will start with specific pattern)

Now I want to hide/show above spans using single jQuery statement. How can do this? All span id start with common asd1 pattern.

Please give me idea as soon as possible.

*i have just given example in this code.. those spans are coming dynamically in my code in different nested divs, so i want hide those with those id pattern & class name???

Body:
with jQuery:

var asds = $('*[id^="asd"]');

for( var i = 0; i < dates.length; i++) {
  $("asds:eq(" + i  + ")").hide();
}


问:
Checking total lines read by QTextStream without using a dedicated counter
I'm currently working on code for parsing a file with an unknown number of lines. The format is roughly like this:

```<code>ShapeId: 1
ShapeType: Line
ShapeDimensions: 20, 90, 100, 20
PenColor: blue
PenWidth: 2
PenStyle: DashDotLine
PenCapStyle: FlatCap
PenJoinStyle: MiterJoin

// and so on and so forth; formats vary slightly depending on the entry
</code>```

Being a text file, obviously we'll want to check for errors. Currently, I am doing this by throwing an exceptions with (fairly) informative messages.

However, my exception messages cannot be too specific, because many of my functions which help parse the file are too generic to have specific messages. Given the sheer diversity of the lines, it's impractical to have custom-written messages for each kind of line.

As I mentioned in the title, I am using QTextStream. I am using readLine to read the each line, and then doing stuff with that line. I am also using skipWhiteSpace to skip the gaps between the blocks of data.

I was hoping QTextStream would come with this functionality, but it doesn't. The closest thing I could find is pos. This is better than nothing, but it's not nearly as useful as a line number.

I could add an integer counter to count up as I step through each line. However, this is impractical in the context of my program, where I have many helper functions that will read lines. Also, skipWhiteSpace can skip multiple lines, so I couldn't use this if I were manually counting.

Unfortunately, I haven't been able to find a good solution. The closest would be something like this, but that's assuming we're already stepping through the file, one line at a time, within a simple loop. Again, that's too impractical in this situation.

So...I guess my question is: is there an elegant way of checking the line number which a QTextStream is pointing to without relying on any previous code? Am I missing something obvious?

(I would rather avoid using on libraries other than Qt and the basic C++ libraries for this.)

答:
You could wrap the QTextStream in something that counted lines.

```<code>class StreamWithLineCount
{
    QTextStream stream;
    int lineCount;
public:
    QString readLine(qint64 maxlen = 0)
    {
        ++lineCount;
        return stream.readLine(maxLen);
    }

    void skipWhitespace()
    {
         qint64 pos = stream.pos();
         while (!stream.atEnd() && readLine().simplified().isEmpty())
         {
             pos = stream.pos();
         }
         seek(pos);
    }
}
</code>```

Body:
I'm currently working on code for parsing a file with an unknown number of lines. The format is roughly like this:

ShapeId: 1
ShapeType: Line
ShapeDimensions: 20, 90, 100, 20
PenColor: blue
PenWidth: 2
PenStyle: DashDotLine
PenCapStyle: FlatCap
PenJoinStyle: MiterJoin

// and so on and so forth; formats vary slightly depending on the entry

Being a text file, obviously we'll want to check for errors. Currently, I am doing this by throwing an exceptions with (fairly) informative messages.

However, my exception messages cannot be too specific, because many of my functions which help parse the file are too generic to have specific messages. Given the sheer diversity of the lines, it's impractical to have custom-written messages for each kind of line.

As I mentioned in the title, I am using QTextStream. I am using readLine to read the each line, and then doing stuff with that line. I am also using skipWhiteSpace to skip the gaps between the blocks of data.

I was hoping QTextStream would come with this functionality, but it doesn't. The closest thing I could find is pos. This is better than nothing, but it's not nearly as useful as a line number.

I could add an integer counter to count up as I step through each line. However, this is impractical in the context of my program, where I have many helper functions that will read lines. Also, skipWhiteSpace can skip multiple lines, so I couldn't use this if I were manually counting.

Unfortunately, I haven't been able to find a good solution. The closest would be something like this, but that's assuming we're already stepping through the file, one line at a time, within a simple loop. Again, that's too impractical in this situation.

So...I guess my question is: is there an elegant way of checking the line number which a QTextStream is pointing to without relying on any previous code? Am I missing something obvious?

(I would rather avoid using on libraries other than Qt and the basic C++ libraries for this.)

Body:
You could wrap the QTextStream in something that counted lines.

class StreamWithLineCount
{
    QTextStream stream;
    int lineCount;
public:
    QString readLine(qint64 maxlen = 0)
    {
        ++lineCount;
        return stream.readLine(maxLen);
    }

    void skipWhitespace()
    {
         qint64 pos = stream.pos();
         while (!stream.atEnd() && readLine().simplified().isEmpty())
         {
             pos = stream.pos();
         }
         seek(pos);
    }
}