问:
How to change form action dynamically with Laravel + VueJS
I have a route setup like this:

```<code>Route::post('subjects/{subject}/{tag}', 'TagController@show');
</code>```

And I have the following form structure, where I am populating the options of a select element by looping through a $tags array:

```<code><form id="tagForm" method="POST"
action="/subjects/{{ $lesson->subject->slug }}/{{ 'selected option will go here' }}">
    {{ csrf_field() }}
   <div class="select">
      <select @change="onTagSelected">
        <option>Tags</option>
        @foreach ($tags as $tag)
                <option value="{{ $tag->id }}">{{ $tag->title }}</option>
        @endforeach
      </select>
    </div>
</form>
</code>```

How can I change the form action according to the currently selected tag from the option?

I am using Vue.js as js framework and I am listening for onchange event:

```<code>onTagSelected: function(event) {
        var tagForm = document.getElementById('tagForm');
// what should I do here to change the action?
        tagForm.submit();
}
</code>```

答:
The way that you've solved it, you're not really using VueJS, and flat javascript would make more sense. A more VueJS approach would be something like this: (presuming you're writing in a Blade View, this would need to be in a )

```<code>new Vue({
   data: function() {
      return {
         form: {
             baseAction: "/subjects/{{ $lesson->subject->slug }}/",
             chosenAction: '',
         }
      }
   },
   computed: {
       computedAction: function() {
           return this.form.baseAction + this.form.chosenAction;
       }
   }
});
</code>```

Now for your form:

```<code><form action="computedAction">
</code>```

And for your select:

```<code><select v-model="form.chosenAction">
</code>```

The onchange isn't necessary here as we're binding the value of the selected  to the chosenAction property of the form object. We then use the computedAction property (which is a computed value, of course) to dictate the action of our form.

EDIT - When using a transpiled vuejs approach with single file components:

If you want vuejs to be responsible for the life-cycle of the form, then you can use a single file component:

```<code><template>
    <form id="tagForm" method="POST" action="computedAction">
        <input type="hidden" name="_token" value="token"/>
        <div class="select">
            <select v-model="form.chosenAction">
                <option value="">Tags</option>
                <option v-for="tag in tags" value="tag.id"> {{tag.title}} </option>
            </select>
        </div>
     </form>
</template>

<script>
    export default {
        props: ['tags', 'slug', 'token']
        data: function() {
            return {
               form: {
                   chosenAction: ''
               }
            }
       },

       computed: {
           computedAction: function() {
               return `/subjects/${slug}/${this.form.chosenAction}`
           }
       }
    }
</script>
</code>```

Now in your app.js file you need to tell Vue about this new component so you can use it in your blade template. This needs to come after you use import Vue from 'vue' in your app.js file.

```<code>import MyCoolForm from './path/to/my/cool/form.js';

Vue.component('v-mycoolform', MyCoolForm);
</code>```

Now in your blade template, you can pass properties to this component:

```<code><v-mycoolform :slug="{{$lesson->subject->slug}}" :token="{{csrf_token()}}" :tags="{{json_encode($tags)}}"/>
</code>```

Body:
I have a route setup like this:

Route::post('subjects/{subject}/{tag}', 'TagController@show');

And I have the following form structure, where I am populating the options of a select element by looping through a $tags array:

<form id="tagForm" method="POST"
action="/subjects/{{ $lesson->subject->slug }}/{{ 'selected option will go here' }}">
    {{ csrf_field() }}

      <select @change="onTagSelected">
        <option>Tags</option>
        @foreach ($tags as $tag)
                <option value="{{ $tag->id }}">{{ $tag->title }}</option>
        @endforeach
      </select>

</form>

How can I change the form action according to the currently selected tag from the option?

I am using Vue.js as js framework and I am listening for onchange event:

onTagSelected: function(event) {
        var tagForm = document.getElementById('tagForm');
// what should I do here to change the action?
        tagForm.submit();
}

Body:
The way that you've solved it, you're not really using VueJS, and flat javascript would make more sense. A more VueJS approach would be something like this: (presuming you're writing in a Blade View, this would need to be in a )

new Vue({
   data: function() {
      return {
         form: {
             baseAction: "/subjects/{{ $lesson->subject->slug }}/",
             chosenAction: '',
         }
      }
   },
   computed: {
       computedAction: function() {
           return this.form.baseAction + this.form.chosenAction;
       }
   }
});

Now for your form:

<form action="computedAction">

And for your select:

<select v-model="form.chosenAction">

The onchange isn't necessary here as we're binding the value of the selected  to the chosenAction property of the form object. We then use the computedAction property (which is a computed value, of course) to dictate the action of our form.

EDIT - When using a transpiled vuejs approach with single file components:

If you want vuejs to be responsible for the life-cycle of the form, then you can use a single file component:

<template>
    <form id="tagForm" method="POST" action="computedAction">
        <input type="hidden" name="_token" value="token"/>
        <div class="select">
            <select v-model="form.chosenAction">
                <option value="">Tags</option>
                <option v-for="tag in tags" value="tag.id"> {{tag.title}} </option>
            </select>
        </div>
     </form>
</template>

<script>
    export default {
        props: ['tags', 'slug', 'token']
        data: function() {
            return {
               form: {
                   chosenAction: ''
               }
            }
       },

       computed: {
           computedAction: function() {
               return `/subjects/${slug}/${this.form.chosenAction}`
           }
       }
    }
</script>

Now in your app.js file you need to tell Vue about this new component so you can use it in your blade template. This needs to come after you use import Vue from 'vue' in your app.js file.

import MyCoolForm from './path/to/my/cool/form.js';

Vue.component('v-mycoolform', MyCoolForm);

Now in your blade template, you can pass properties to this component:

<v-mycoolform :slug="{{$lesson->subject->slug}}" :token="{{csrf_token()}}" :tags="{{json_encode($tags)}}"/>


来源: stackexchange

问:
scp: how to find out that copying was finished
I'm using scp command to copy file from one Linux host to another.
I run scp commend on host1 and copy file from host1 to host2. File is quite big and it takes for some time to copy it.
On host2 file appears immediately as soon as copying was started. I can do everything with this file even if copying is still in progress.

Is there any reliable way to find out if copying was finished or not on host2?

答:
If avoiding a second SSH handshake is important, you can use something like the following:

```<code>ssh host cat \> bigfile \&\& touch complete < bigfile
</code>```

Then wait for the "complete" file to get created on the remote end.

ContentLicense: CC BY-SA 3.0

Body:
If avoiding a second SSH handshake is important, you can use something like the following:

ssh host cat \> bigfile \&\& touch complete < bigfile

Then wait for the "complete" file to get created on the remote end.


问:
UA String failed,prompt Invalid Device type
We set it "TPV_linux", but we found UA String failed.

We checked the underscore "" and found that it was half-width "" rather than full-size "＿", so it should not fail.

We do not understand what caused this, can you help to check?

答:
Underscore and some other characters are replaced in function Sanitize() when the User Agent string is created in UserAgentStringFactory::CreateUserAgentString().

Please, check file cobalt/network/user_agent_string_factory.cc for more details, but comments in the source code suggest that these chars are reserved:

```<code>struct SanitizeReplacements {
  const char* replace_chars;
  const char* replace_with;
} kSanitizeReplacements[] = {
  { ",", u8"\uFF0C" },  // fullwidth comma
  { "_", u8"\u2E0F" },  // paragraphos
  { "/", u8"\u2215" },  // division slash
  { "(", u8"\uFF08" },  // fullwidth left paren
  { ")", u8"\uFF09" },  // fullwidth right paren
};
</code>```

Body:
Underscore and some other characters are replaced in function Sanitize() when the User Agent string is created in UserAgentStringFactory::CreateUserAgentString().

Please, check file cobalt/network/user_agent_string_factory.cc for more details, but comments in the source code suggest that these chars are reserved:

struct SanitizeReplacements {
  const char* replace_chars;
  const char* replace_with;
} kSanitizeReplacements[] = {
  { ",", u8"\uFF0C" },  // fullwidth comma
  { "_", u8"\u2E0F" },  // paragraphos
  { "/", u8"\u2215" },  // division slash
  { "(", u8"\uFF08" },  // fullwidth left paren
  { ")", u8"\uFF09" },  // fullwidth right paren
};


问:
not on a query in RoR
In Ruby on rails 3 I want to query on a has_many field of a model as follows:

@project.items.where(:status => 1)

The problem is I'm trying to get the exact opposite result than this. What i want is all items of @project where the status is not 1. Been looking for the answer to this for a while, anyone?

答:
There are many ways to accomplish what you are trying to do, however, some are better than others. If you will always be searching for a hardcoded number (i.e. 1 in this case), then the following solution will work:

```<code>@project.items.where('status != 1')
</code>```

However, if this value is not hard-coded, you are openly vulnerable to SQL injection as Rails will not (cannot) escape this kind of query. As a result, it is preferred among Rails developers to user the following syntax for most custom conditions (those that can't be constructed via Hash):

```<code>@project.items.where(['status != ?', 1])
</code>```

This syntax is slightly confusing, so let me go over it. Basically you are providing the where clause an Array of values. The first value in the array is a String representing the query you want executed. Anywhere you want a value in that string, you place a ?. This serves as a placeholder. Next, you add an element for every question mark in you query. For example, if I had the following:

```<code>where(['first_name = ? AND last_name = ?', params[:first_name], params[:last_name]]
</code>```

Rails will automatically match these up forming the query for you. In that process, it also escapes potentially unsafe characters, preventing injection.

In general, it is preferred to use the Array syntax, even for a hardcoded value. I've been told that pure string conditions in Rails 3.5 will raise a warning (unverified), so it doesn't hurt to get in the process of using the Array syntax now.

ContentLicense: CC BY-SA 2.5

Title: not on a query in RoR

Body:
There are many ways to accomplish what you are trying to do, however, some are better than others. If you will always be searching for a hardcoded number (i.e. 1 in this case), then the following solution will work:

@project.items.where('status != 1')

However, if this value is not hard-coded, you are openly vulnerable to SQL injection as Rails will not (cannot) escape this kind of query. As a result, it is preferred among Rails developers to user the following syntax for most custom conditions (those that can't be constructed via Hash):

@project.items.where(['status != ?', 1])

This syntax is slightly confusing, so let me go over it. Basically you are providing the where clause an Array of values. The first value in the array is a String representing the query you want executed. Anywhere you want a value in that string, you place a ?. This serves as a placeholder. Next, you add an element for every question mark in you query. For example, if I had the following:

where(['first_name = ? AND last_name = ?', params[:first_name], params[:last_name]]

Rails will automatically match these up forming the query for you. In that process, it also escapes potentially unsafe characters, preventing injection.

In general, it is preferred to use the Array syntax, even for a hardcoded value. I've been told that pure string conditions in Rails 3.5 will raise a warning (unverified), so it doesn't hurt to get in the process of using the Array syntax now.


问:
split file in bash after unescaped newline
Given common bash-tools, it is easy to split a big file (in my case a MySQL dump and thus a TSV-file) into smaller parts using the split command. Furthermore, this command supports splitting a file after n new lines (i.e. -l argument). But this command does not distinguished between escaped and unescaped newline characters and thus might break a single table row into two incomplete parts.

Example (TSV with 2 columns)

```<code>cool    2014-12-15 17:31:00
do not censor it ...^M\\n      2016-01-24 22:33:00
watch out ari, you've got compeition! hahah     2001-12-05 19:11:01
Oh God, the poor guy!  xD\\nCan't wait to watch this!      2011-07-11 22:01:20
wish i could do that.\\n       2001-02-07 00:24:11
Funny! I will use this reason when I drink something in other houses    2015-06-10 12:20:00
</code>```

As you can see, there are two columns (first contains the comment and the second the date), which are separated by an tab. I visualised just the escaped newlines, tabs and unescaped newlines are not printed. If you put these lines into a file and split it (e.g.,  split example.tsv -l 1) you will get 9 files, but there are only 6 comments (3 contain escaped newlines)! This is because escaped newlines are treated as regular newlines prefixed with a backslash. This is a huge problem for me, because splitting the file might lead to incomplete table rows in the output-files.

Is it somehow possible to ignore escaped newlines or does someone know another command which can do this?

答:
This will break the file every 20 lines (or whatever you set n to) but not on lines that end with a backslash:

```<code>awk -v n=20 'NR==1 || (c>n && !(last~/\\$/)){c=0; close(f); f="file" ++count ".out"} {c++; print>f; last=$0}' file
</code>```

How it works

-v n=20

This creates an awk variable n which we will use to decide when to split the file.

NR==1 || (c>n && !(last~/\\$/)){c=0; close(f); f="file" ++count ".out"}

Every time that we need to start a new file, we (a) set the line counter, c, to zero, (b) close the previous file, and (c) define a name for the next file.

We need to start a new file when (i) we are on the first input line, NR==1, or else when (ii) the line counter c exceeds the limit n and the last line did not end with \.

c++; print>f; last=$0

This increments the line counter, c, prints the current line to file f, and updates last to the value of the current line.

Example

Let's try this test file:

```<code>$ cat file
text1   2014-12-15 17:31:01
text2\
        2014-12-15 17:31:02
text3   2014-12-15 17:31:03
text4a\
text4b\
        2014-12-15 17:31:04
text5   2014-12-15 17:31:05
</code>```

Now, let's run our command.  To keep the example short, we set n=2:

```<code>$ awk -v n=2 'NR==1 || (c>n && !(last~/\\$/)){c=0; close(f); f="file" ++count ".out"} {c++; print>f; last=$0}' file
</code>```

After the command is run, new files appear in the directory:

```<code>$ ls
file  file1.out  file2.out  file3.out
</code>```

The new files contain the old contents split every 2 lines except not split on lines ending in \:

```<code>$ cat file1.out
text1   2014-12-15 17:31:01
text2\
        2014-12-15 17:31:02
$ cat file2.out
text3   2014-12-15 17:31:03
text4a\
text4b\
        2014-12-15 17:31:04
$ cat file3.out
text5   2014-12-15 17:31:05
</code>```

Body:
Given common bash-tools, it is easy to split a big file (in my case a MySQL dump and thus a TSV-file) into smaller parts using the split command. Furthermore, this command supports splitting a file after n new lines (i.e. -l argument). But this command does not distinguished between escaped and unescaped newline characters and thus might break a single table row into two incomplete parts.

Example (TSV with 2 columns)

cool    2014-12-15 17:31:00
do not censor it ...^M\\n      2016-01-24 22:33:00
watch out ari, you've got compeition! hahah     2001-12-05 19:11:01
Oh God, the poor guy!  xD\\nCan't wait to watch this!      2011-07-11 22:01:20
wish i could do that.\\n       2001-02-07 00:24:11
Funny! I will use this reason when I drink something in other houses    2015-06-10 12:20:00

As you can see, there are two columns (first contains the comment and the second the date), which are separated by an tab. I visualised just the escaped newlines, tabs and unescaped newlines are not printed. If you put these lines into a file and split it (e.g.,  split example.tsv -l 1) you will get 9 files, but there are only 6 comments (3 contain escaped newlines)! This is because escaped newlines are treated as regular newlines prefixed with a backslash. This is a huge problem for me, because splitting the file might lead to incomplete table rows in the output-files.

Is it somehow possible to ignore escaped newlines or does someone know another command which can do this?

Body:
This will break the file every 20 lines (or whatever you set n to) but not on lines that end with a backslash:

awk -v n=20 'NR==1 || (c>n && !(last~/\\$/)){c=0; close(f); f="file" ++count ".out"} {c++; print>f; last=$0}' file

How it works

-v n=20

This creates an awk variable n which we will use to decide when to split the file.

NR==1 || (c>n && !(last~/\\$/)){c=0; close(f); f="file" ++count ".out"}

Every time that we need to start a new file, we (a) set the line counter, c, to zero, (b) close the previous file, and (c) define a name for the next file.

We need to start a new file when (i) we are on the first input line, NR==1, or else when (ii) the line counter c exceeds the limit n and the last line did not end with \.

c++; print>f; last=$0

This increments the line counter, c, prints the current line to file f, and updates last to the value of the current line.

Example

Let's try this test file:

$ cat file
text1   2014-12-15 17:31:01
text2\
        2014-12-15 17:31:02
text3   2014-12-15 17:31:03
text4a\
text4b\
        2014-12-15 17:31:04
text5   2014-12-15 17:31:05

Now, let's run our command.  To keep the example short, we set n=2:

$ awk -v n=2 'NR==1 || (c>n && !(last~/\\$/)){c=0; close(f); f="file" ++count ".out"} {c++; print>f; last=$0}' file

After the command is run, new files appear in the directory:

$ ls
file  file1.out  file2.out  file3.out

The new files contain the old contents split every 2 lines except not split on lines ending in \:

$ cat file1.out
text1   2014-12-15 17:31:01
text2\
        2014-12-15 17:31:02
$ cat file2.out
text3   2014-12-15 17:31:03
text4a\
text4b\
        2014-12-15 17:31:04
$ cat file3.out
text5   2014-12-15 17:31:05


问:
Rename output PDF files as subdirectory name recursively Powershell
I'm pretty new to Powershell. Want to merge all PDF files subcategory (done). Next, I want to define a recursive name for my $outputfile that will consist of subdirectory name + 'Additional Text'. I am stuck in this point...

```<code>$pdftk = 'C:\Program Files (x86)\PDFtk Server\bin\pdftk.exe'
$inputfolder = "C:\Tests"
$outputfile = "combined.pdf"

dir $inputfolder -r -include *.pdf -exclude $outputfile | sort-object |
group DirectoryName |   % {& $PDFtk $_.group CAT OUTPUT "$($_.Name)\$outputfile" verbose}
</code>```

I'm trying to use something like this line below. I don't know how to refer to $outputfile. How can I define a dynamic output name?

```<code>gci C:\Tests\*.*  | % { rename-item –path $_.Fullname –Newname ( $_.basename + (get-date -format ' Additional Text') + $_.extension)}
</code>```

In directory C:\Tests there're folders xx, yy, zz. My code merges all files within each subdirectory and name it combined.pdf. Instead of combined.pdf I want to see a final file xx.pdf in C:\Tests\xx subdirectory, yy.pdf in \\yy and zz.pdf in \\zz :) Now I'm thinking how to use $($currentfolder.FullName)\$outputfile to achieve it.

答:
Instead of renaming, you could write the correct name during the initial creation of the file like this:</p>

```<code>    & $PDFtk $_.group CAT OUTPUT "$($_.Name)\$($_.Name | Split-Path -Leaf).pdf" verbose
</code>```

Body:
I'm pretty new to Powershell. Want to merge all PDF files subcategory (done). Next, I want to define a recursive name for my $outputfile that will consist of subdirectory name + 'Additional Text'. I am stuck in this point...

$pdftk = 'C:\Program Files (x86)\PDFtk Server\bin\pdftk.exe'
$inputfolder = "C:\Tests"
$outputfile = "combined.pdf"

dir $inputfolder -r -include *.pdf -exclude $outputfile | sort-object |
group DirectoryName |   % {& $PDFtk $_.group CAT OUTPUT "$($_.Name)\$outputfile" verbose}

I'm trying to use something like this line below. I don't know how to refer to $outputfile. How can I define a dynamic output name?

gci C:\Tests\*.*  | % { rename-item –path $_.Fullname –Newname ( $_.basename + (get-date -format ' Additional Text') + $_.extension)}

In directory C:\Tests there're folders xx, yy, zz. My code merges all files within each subdirectory and name it combined.pdf. Instead of combined.pdf I want to see a final file xx.pdf in C:\Tests\xx subdirectory, yy.pdf in \\yy and zz.pdf in \\zz :) Now I'm thinking how to use $($currentfolder.FullName)\$outputfile to achieve it.

Body:
Instead of renaming, you could write the correct name during the initial creation of the file like this:

    & $PDFtk $_.group CAT OUTPUT "$($_.Name)\$($_.Name | Split-Path -Leaf).pdf" verbose


问:
jQuery Click and following function is not called
The below code works in Chrome and Firefox but not in Edge.

On click a button, it should create a programmatic click on input file so the user can upload the attachment.

Once the user selects the attachment, the file change is detected and uploaded using Ajax call.

jQuery:

```<code>jQuery(document).ready(function(){
        jQuery(document).on("click",".upload-btn",function(){
            jQuery(document).find(".upload").click();
            watchCoveringLetterUpload();
        });
    });

    function watchCoveringLetterUpload() {
    var target = jQuery(document).find(".upload");
    var textType = /text.*/;
    target.change(function(e) {
        console.log(e)

})
}
</code>```

https://jsfiddle.net/sv3oougf/   ---- original code

https://jsfiddle.net/sv3oougf/1/ ---- tested with self invoking function

Please check the console.log, the function called is not executed in IE but executed in Chrome.

答:
use id's instead of using classes for referencing input types and it will work.

check this code tested on edge

  (function() {

      function watchCoveringLetterUpload() {
          console.log("function is called");
          var target = jQuery(document).find("#upload");
          var textType = /text.*/;
          target.change(function(e) {
              console.log(e)
              file = target[0].files[0];
              console.log("file", file);
          });
      }

      jQuery(document).ready(function() {
          jQuery(document).on("click", ".upload-btn", function() {
              jQuery(document).find("#upload").click();
              watchCoveringLetterUpload();
          });
      });

  })(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="file" style="display:none" id="upload">
<button class="upload-btn">Click</button></code>```

Body:
The below code works in Chrome and Firefox but not in Edge.

On click a button, it should create a programmatic click on input file so the user can upload the attachment.

Once the user selects the attachment, the file change is detected and uploaded using Ajax call.

jQuery:

jQuery(document).ready(function(){
        jQuery(document).on("click",".upload-btn",function(){
            jQuery(document).find(".upload").click();
            watchCoveringLetterUpload();
        });
    });

    function watchCoveringLetterUpload() {
    var target = jQuery(document).find(".upload");
    var textType = /text.*/;
    target.change(function(e) {
        console.log(e)

})
}

https://jsfiddle.net/sv3oougf/   ---- original code

https://jsfiddle.net/sv3oougf/1/ ---- tested with self invoking function

Please check the console.log, the function called is not executed in IE but executed in Chrome.

Body:
use id's instead of using classes for referencing input types and it will work.

check this code tested on edge

  (function() {

      function watchCoveringLetterUpload() {
          console.log("function is called");
          var target = jQuery(document).find("#upload");
          var textType = /text.*/;
          target.change(function(e) {
              console.log(e)
              file = target[0].files[0];
              console.log("file", file);
          });
      }

      jQuery(document).ready(function() {
          jQuery(document).on("click", ".upload-btn", function() {
              jQuery(document).find("#upload").click();
              watchCoveringLetterUpload();
          });
      });

  })(jQuery);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="file" style="display:none" id="upload">
<button class="upload-btn">Click</button>


问:
Toggle between two colors when key is pressed
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}
</code>```

答:
You want to press C key to change color to red and press it again to chage to green. This is really basic programming stuff.

You need to use a boolean variable then flip or inverse it each time you press the key. The flipping is accomplished by using the ! sign. If the boolean variable is true, use red color, else use the green color.  I do encourage you to read and understand logical operators and decision making in C#. You will need those in order to make an actual game yourself.

```<code>Renderer yourRenderer;
bool red = true;

// Use this for initialization
void Start()
{
    yourRenderer = gameObject.GetComponent<Renderer>();
    //Use red as default
    yourRenderer.material.color = Color.red;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.C))
    {
        //Flip the boolean variable to the opposite of what it is
        red = !red;

        //If true, use red color
        if (red)
        {
            yourRenderer.material.color = Color.red;
        }
        //If false, use green color
        else
        {
            yourRenderer.material.color = Color.green;
        }
    }
}
</code>```

Unrelated, use GetKeyDown instead of GetKey otherwise you will run into problems while changing color multiple times in a frame therefore not being able to see the color change.

Body:
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}

Body:
You want to press C key to change color to red and press it again to chage to green. This is really basic programming stuff.

You need to use a boolean variable then flip or inverse it each time you press the key. The flipping is accomplished by using the ! sign. If the boolean variable is true, use red color, else use the green color.  I do encourage you to read and understand logical operators and decision making in C#. You will need those in order to make an actual game yourself.

Renderer yourRenderer;
bool red = true;

// Use this for initialization
void Start()
{
    yourRenderer = gameObject.GetComponent<Renderer>();
    //Use red as default
    yourRenderer.material.color = Color.red;
}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.C))
    {
        //Flip the boolean variable to the opposite of what it is
        red = !red;

        //If true, use red color
        if (red)
        {
            yourRenderer.material.color = Color.red;
        }
        //If false, use green color
        else
        {
            yourRenderer.material.color = Color.green;
        }
    }
}

Unrelated, use GetKeyDown instead of GetKey otherwise you will run into problems while changing color multiple times in a frame therefore not being able to see the color change.


问:
PyCharm Professional how to get jinja comment color working?
I try to change the color of Jinja comment syntax as below snapshot though it doesn't get effect.

@1 The sample Jinja comment

@2, @3 the new color to set as green

After clicking OK/Apply, the color remain unchanged.

How can we get it work?

答: I also have question for the comment color, because it was too dim to read comfortably. Try this: e.g. Select: Line comment ---> Click: the color box on the right pannel


问:
results of jquery $.get assignment to variable not usable in event listener
Can anyone identify the problem with this code and/or help to fix it?

I'm trying to preload html files, assign their html to variables, then inject them into a div after the user clicks a button.

I have it working successfully where the html files are loaded into the div on click, but I want to preload the html so the user doesn't have to wait for the external resource of the html file to load or not load if there is internet failure/ external resource fetching issues.

In the code, the alert successfully shows the html so I know at least that part works.

```<code>//IIFE
(function() {

// ^other stuff omitted

// start navButton behavior

var hatContent;
function doSomethingWithData(data) {
  hatContent = data;
  alert(data);
}

$.get('helpAndTips.html', doSomethingWithData);

function replaceNotebookContentWithVariable(content){
    $("#usersNotebook").innerHTML = content;
  }

document.getElementById('helpAndTipsButton').addEventListener("click", function(){
  replaceNotebookContentWithVariable(hatContent);
 }, false);

// end navButton behavior ____________________X

// other stuff omitted

})(); // end IIFE
</code>```

答:
For some reason $('#usersNotebook').innerHTML = data; does not work, but document.getElementById('usersNotebook').innerHTML does work.

I never really managed to use helpAndTips like a variable and I think that is because fetching its data executes later in terms of event order than the code where I want to use the variable. However @Taplar your suggestion of using jquery's .then to fire a function after the data is fetched allowed me to add the "on cick" event listener with the acquired data inside of that "done" function which ensures the data is available due to it's place in the event chain. So the following code is working for me. Thanks!

```<code>`// start navButton behavior

function replaceNotebookContentWithVariable(content) {
  document.getElementById('usersNotebook').innerHTML = content;
}

var helpAndTips = $.get('helpAndTips.html');

helpAndTips.then(function(data){

  document.getElementById('helpAndTipsButton').addEventListener("click", function(){
    replaceNotebookContentWithVariable(data);
   }, false);

})
// end navButton behavior ____________________X`
</code>```

Body:
Can anyone identify the problem with this code and/or help to fix it?

I'm trying to preload html files, assign their html to variables, then inject them into a div after the user clicks a button.

I have it working successfully where the html files are loaded into the div on click, but I want to preload the html so the user doesn't have to wait for the external resource of the html file to load or not load if there is internet failure/ external resource fetching issues.

In the code, the alert successfully shows the html so I know at least that part works.

//IIFE
(function() {

// ^other stuff omitted

// start navButton behavior

var hatContent;
function doSomethingWithData(data) {
  hatContent = data;
  alert(data);
}

$.get('helpAndTips.html', doSomethingWithData);

function replaceNotebookContentWithVariable(content){
    $("#usersNotebook").innerHTML = content;
  }

document.getElementById('helpAndTipsButton').addEventListener("click", function(){
  replaceNotebookContentWithVariable(hatContent);
 }, false);

// end navButton behavior ____________________X

// other stuff omitted

})(); // end IIFE

Body:
For some reason $('#usersNotebook').innerHTML = data; does not work, but document.getElementById('usersNotebook').innerHTML does work.

I never really managed to use helpAndTips like a variable and I think that is because fetching its data executes later in terms of event order than the code where I want to use the variable. However @Taplar your suggestion of using jquery's .then to fire a function after the data is fetched allowed me to add the "on cick" event listener with the acquired data inside of that "done" function which ensures the data is available due to it's place in the event chain. So the following code is working for me. Thanks!

`// start navButton behavior

function replaceNotebookContentWithVariable(content) {
  document.getElementById('usersNotebook').innerHTML = content;
}

var helpAndTips = $.get('helpAndTips.html');

helpAndTips.then(function(data){

  document.getElementById('helpAndTipsButton').addEventListener("click", function(){
    replaceNotebookContentWithVariable(data);
   }, false);

})
// end navButton behavior ____________________X`


问:
Mapping some HashMap Key/Values to a POJO
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

```<code>    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));
</code>```

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

```<code>Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)
</code>```

To ignore the errors I tried :

```<code>mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
</code>```

But then nothing got mapped.

答:
If i have understood your question correctly -  you want to put the value of map into the member variable of the Pojo based on key.

Try below approach.

Main Class as follows

```<code>package org.anuj.collections.map;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ConverMapToPojo {

    public static void main(String[] args) {
        Map<String, String> map = getMap();
        Set<String> keySet = map.keySet();

        String fieldName = null;
        Pojo pojo = new Pojo();
        Field[] field = Pojo.class.getDeclaredFields();

        for (Field f : field) {
            fieldName = f.getName();
            if (keySet.contains(fieldName)) {
                pojo = setField(fieldName, map.get(fieldName), pojo);
            }
        }
        System.out.println("fName = " + pojo.getfName());
        System.out.println("lName = " + pojo.getlName());
    }

    private static Pojo setField(String fieldName, String value, Pojo pojo) {
        switch (fieldName) {
        case "fName":
            pojo.setfName(value);
            break;
        case "lName":
            pojo.setlName(value);
            break;
        }
        return pojo;
    }

    private static Map<String, String> getMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("fName", "stack");
        map.put("lName", "overflow");
        return map;
    }
}
</code>```

Pojo Class as follows -

```<code>public class Pojo {

    private String fName;
    private String lName;

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }
}
</code>```

The Result comes out to be

fName = stack
lName = overflow

Body:
I have a HashMap of about 300 Key/String Value pairs and a POJO with about 12 string attributes where the names match the key names.

I would like to know how to get the HashMap values into the POJO?

I made this start which uses relfection and a loop but wasn't sure how to dynamically construct  the setter method name, and apparently reflection is a bad idea anyway...but FWIW:

    public void writeToFile(Map<String, String> currentSale) throws IOException {

    SaleExport saleExport = new SaleExport();

    Field[] fields = saleExport.getClass().getDeclaredFields();

       for (Field field : fields ) {
        System.out.println(field.getName());
        saleExport.set +field(saleExport.get(field));

I have used map struct once before but it does not appear to support HashMaps.

UPDATE

This answer looks similar to what I want to do but gave a stack error on fields that didn't map:

Exception in thread "Thread-2" java.lang.IllegalArgumentException: Unrecognized field "Physical" (class com.SaleExport), not marked as ignorable (6 known properties: "date", "city", "surname", "streetName", "salesNo", "salesSurname"])
 at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.SalesExport["Physical"])
    at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:3738)
    at com.fasterxml.jackson.databind.ObjectMapper.convertValue(ObjectMapper.java:3656)
    at com.CSVExport.writeToFile(CSVExport.java:20)
    at com.JFrameTest.writefiletoDB(JFrameTest.java:135)
    at com.JFrameTest$FileWorkerThread.run(JFrameTest.java:947)

To ignore the errors I tried :

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

But then nothing got mapped.

Body:
If i have understood your question correctly -  you want to put the value of map into the member variable of the Pojo based on key.

Try below approach.

Main Class as follows

package org.anuj.collections.map;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ConverMapToPojo {

    public static void main(String[] args) {
        Map<String, String> map = getMap();
        Set<String> keySet = map.keySet();

        String fieldName = null;
        Pojo pojo = new Pojo();
        Field[] field = Pojo.class.getDeclaredFields();

        for (Field f : field) {
            fieldName = f.getName();
            if (keySet.contains(fieldName)) {
                pojo = setField(fieldName, map.get(fieldName), pojo);
            }
        }
        System.out.println("fName = " + pojo.getfName());
        System.out.println("lName = " + pojo.getlName());
    }

    private static Pojo setField(String fieldName, String value, Pojo pojo) {
        switch (fieldName) {
        case "fName":
            pojo.setfName(value);
            break;
        case "lName":
            pojo.setlName(value);
            break;
        }
        return pojo;
    }

    private static Map<String, String> getMap() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("fName", "stack");
        map.put("lName", "overflow");
        return map;
    }
}

Pojo Class as follows -

public class Pojo {

    private String fName;
    private String lName;

    public String getfName() {
        return fName;
    }

    public void setfName(String fName) {
        this.fName = fName;
    }

    public String getlName() {
        return lName;
    }

    public void setlName(String lName) {
        this.lName = lName;
    }
}

The Result comes out to be

fName = stack
lName = overflow


问:
Why am I getting "Permission denied" when activating a venv?
I just started a new python project and created a venv inside the project folder by running virtualenv venv in the terminal. However, when I run venv/bin/activate I get a permission denied error.

I have tried

```<code>sudo chown -R user:user project/venv
</code>```

but I get

```<code>chown: user: illegal group name
</code>```

I have set these venvs up a ton of times and never had the issue. Is there anything else I can try?

I am on a Mac.

答:
Basically, it's looking for permission to execute activate on the created folder path.

On the root give below permissions command on the desired path where activate is located

sudo chmod -R 755 ~/tensorflow/* # or whatever the target structure
```

This will extend all the permissions including Read/Write/Execute and group

then execute  ~/bin/activate

ContentLicense: CC BY-SA 4.0

Body:
I just started a new python project and created a venv inside the project folder by running virtualenv venv in the terminal. However, when I run venv/bin/activate I get a permission denied error.

I have tried

sudo chown -R user:user project/venv

but I get

chown: user: illegal group name

I have set these venvs up a ton of times and never had the issue. Is there anything else I can try?

I am on a Mac.

Body:
Basically, it's looking for permission to execute activate on the created folder path.

On the root give below permissions command on the desired path where activate is located

sudo chmod -R 755 ~/tensorflow/* # or whatever the target structure

This will extend all the permissions including Read/Write/Execute and group

then execute  ~/bin/activate


问:
Unable to print Elements in Generic stack in Java
i have this code of a generic implementation of stacks in java.
I have used array implementation with some fixed size 2000

```<code>public class Stack_using_Array<E> {
    int N;
    int i; //starting index
    private E arr[];
    @SuppressWarnings("unchecked")
    Stack_using_Array(int N){
        arr=(E[]) new Object[N];
        i=0;
    }

    @SuppressWarnings("unchecked")
    void push(E object ) throws FullStackException{
        if(i==N-1){
            throw new FullStackException("stack is full");
        }
        arr[i]=(E) new Object();
        arr[i]=object;
        i++;
    }
    @SuppressWarnings("unchecked")
    E pop() throws FullStackException{
        if(i==0){
            throw new FullStackException("stack is empty");
        }
        arr[i]=(E) new Object();
        E ob=arr[i];
        arr[i]=null;
        i--;
        return ob;
    }
    public String toString(){
        String s=""+arr[i];
        return s;
    }
    public static void main(String []args){
        Stack_using_Array<Integer> stack= new Stack_using_Array<Integer>();
        try{
            stack.push(67);
            stack.push(90);
            stack.push(78);
            System.out.println(stack.pop());
            System.out.println(stack.pop());
            System.out.println(stack.pop());
        } catch (FullStackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
</code>```

But when i try to print them, the outcome comes like

```<code>java.lang.Object@15db9742
java.lang.Object@6d06d69c
java.lang.Object@7852e922
</code>```

it is the address of the object maybe. I want to print the Integers.please help

答:
First problem is in pop() method, remove this line, there is no need to instantiate a new value here:

```<code>arr[i]=(E) new Object();
</code>```

and also change the other two lines to manage index and array position, it's not the same:

```<code>E ob = arr[i-1];
arr[i-1] = null;
</code>```

Second problem: remove the toString method, it's completly wrong and can cause unwanted exceptions.

Body:
i have this code of a generic implementation of stacks in java.
I have used array implementation with some fixed size 2000

public class Stack_using_Array<E> {
    int N;
    int i; //starting index
    private E arr[];
    @SuppressWarnings("unchecked")
    Stack_using_Array(int N){
        arr=(E[]) new Object[N];
        i=0;
    }

    @SuppressWarnings("unchecked")
    void push(E object ) throws FullStackException{
        if(i==N-1){
            throw new FullStackException("stack is full");
        }
        arr[i]=(E) new Object();
        arr[i]=object;
        i++;
    }
    @SuppressWarnings("unchecked")
    E pop() throws FullStackException{
        if(i==0){
            throw new FullStackException("stack is empty");
        }
        arr[i]=(E) new Object();
        E ob=arr[i];
        arr[i]=null;
        i--;
        return ob;
    }
    public String toString(){
        String s=""+arr[i];
        return s;
    }
    public static void main(String []args){
        Stack_using_Array<Integer> stack= new Stack_using_Array<Integer>();
        try{
            stack.push(67);
            stack.push(90);
            stack.push(78);
            System.out.println(stack.pop());
            System.out.println(stack.pop());
            System.out.println(stack.pop());
        } catch (FullStackException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

But when i try to print them, the outcome comes like

java.lang.Object@15db9742
java.lang.Object@6d06d69c
java.lang.Object@7852e922

it is the address of the object maybe. I want to print the Integers.please help

Body:
First problem is in pop() method, remove this line, there is no need to instantiate a new value here:

arr[i]=(E) new Object();

and also change the other two lines to manage index and array position, it's not the same:

E ob = arr[i-1];
arr[i-1] = null;

Second problem: remove the toString method, it's completly wrong and can cause unwanted exceptions.


问:
Finding time taken by the code
I am trying to find the time taken by memmove function in c using time.h library. However, When i execute the code, I get the value as zero. Any possible solution to find the time taken by the memmove function?</p>

```<code>void main(){
uint64_t start,end;
uint8_t a,b;
char source[5000];
char dest[5000];
uint64_t j=0;

for(j=0;j<5000;j++){
source[j]=j;
}

start=clock();
memmove(dest,source,5000);
end=clock();
printf("%f",((double)end-start));
}
</code>```

答:
If you want to know the time it takes on a beagle bone or another device with a GIPO you can toggle a GPIO before and after your routine. You will have to hook up an oscilloscope or something similar that can sample voltage quickly.

I don't know much about beagle bones but it seems the library libpruio allows fast gpio toggling.

Also, what is your exact goal here? Compare speed on different hardware? As someone suggests, you could increase the number of loops so it becomes more easily measurable with time.h.

Title: Finding time taken by the code

Body:
I am trying to find the time taken by memmove function in c using time.h library. However, When i execute the code, I get the value as zero. Any possible solution to find the time taken by the memmove function?

void main(){
uint64_t start,end;
uint8_t a,b;
char source[5000];
char dest[5000];
uint64_t j=0;

for(j=0;j<5000;j++){
source[j]=j;
}

start=clock();
memmove(dest,source,5000);
end=clock();
printf("%f",((double)end-start));
}


问:
Desktop Bulk Upload SharePoint Profile Images
I am looking for a tool that can bulk upload user profile images to the SharePoint My Site host. Nothing too flash, it just needs to take a directory of images named by the account name. And then set the profile field to be the uploaded image.

A key requirement is that it must be able to be run by people that do not have remote desktop access to the server. So i guess that means powershell scripts are out.

答:
I decided to build my own component because one doesn't seem to exist

http://spc3.codeplex.com/wikipage?title=ProfileImageUpload


问:
Android cursor problems "Make sure the Cursor is initialized correctly before accessing data from it."
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

I want to get the photo name from SQL database,then get the photo from drawable file and link the photo to a ImageView item which is inside a ListView what is the problem with following code, Please help me fix it, thank you

```<code>import android.app.ListActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class HotProduct extends ListActivity {

    private ProductSQLiteHelper sqlHelper;
    private SQLiteDatabase infodb;
    private String[] columnsToSelect;
    private String[] columnsToSelect2;
    private Cursor infoCursor;
    private SimpleCursorAdapter dbAdapter;
    private SimpleCursorAdapter dbAdapter2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hotproduct_middle_page);
        columnsToSelect = new String[] {
                ProductSQLiteHelper.PRODUCT_ID,
                ProductSQLiteHelper.PRODUCT_NAME,
                ProductSQLiteHelper.PRODUCT_BRAND,
                ProductSQLiteHelper.PRODUCT_PRICE

        };

        Resources res = getResources();
        Log.v("Res:",String.valueOf(res));

//        setTitle("Hot Product");

        sqlHelper = new ProductSQLiteHelper(this);

        infodb = sqlHelper.getReadableDatabase();

        Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        infoCursor.moveToFirst();
        if (!infoCursor.isAfterLast()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }

        String columnsToDisplay[] = {
                ProductSQLiteHelper.PRODUCT_NAME,
                ProductSQLiteHelper.PRODUCT_BRAND,
                ProductSQLiteHelper.PRODUCT_PRICE
//                ProductSQLiteHelper.PRODUCT_PHOTO
        };

        int mappingToView[] = {
                R.id.productName,
                R.id.productBrand,
                R.id.productPrice
//                R.id.productPhoto
        };

        String args[] = {"1"};
        infoCursor = infodb.query(ProductSQLiteHelper.TABLE_NAME,columnsToSelect," hot = ? ",args,null,null,null);

        String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex("photo"));
        Log.v("resource name",posterResourceName);
        dbAdapter = new SimpleCursorAdapter(this,R.layout.hotproduct_middle_page_row,infoCursor,columnsToDisplay,mappingToView,0);

        setListAdapter(dbAdapter);

        }

}
</code>```

I found that the problems appear in

```<code>      Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        infoCursor.moveToFirst();
        if (!infoCursor.isAfterLast()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }
</code>```

答:
Your issue is due to a getColumnIndex not finding the specified column and thus returning -1 (as it does when the column is not a column). The underlying cause is that you are creating a Cursor with a single column yet in your code you are trying to access 2 columns i.e.

infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT)))

infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO))

The Cursor will contain just 1 column, the photo column.

I would suggest changing the SELECT clause to "SELECT * FROM phone", this will then create a Cursor with ALL columns from the table.

However, there is an additional flaw with the code in that you are not checking the result of the moveToFirst.

If the Cursor is empty then moveToFirst will return false. As the Cursor will not be after the last any attempt to retrieve data from the Cursor will fail as there is no data.

I would suggest amending your code to :-

```<code>        Cursor infoCursor= infodb.rawQuery("SELECT * FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        while (infoCursor.moveToNext()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }
</code>```

You may have to write code to handle an empty cursor.

Body:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.

I want to get the photo name from SQL database,then get the photo from drawable file and link the photo to a ImageView item which is inside a ListView what is the problem with following code, Please help me fix it, thank you

import android.app.ListActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class HotProduct extends ListActivity {

    private ProductSQLiteHelper sqlHelper;
    private SQLiteDatabase infodb;
    private String[] columnsToSelect;
    private String[] columnsToSelect2;
    private Cursor infoCursor;
    private SimpleCursorAdapter dbAdapter;
    private SimpleCursorAdapter dbAdapter2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hotproduct_middle_page);
        columnsToSelect = new String[] {
                ProductSQLiteHelper.PRODUCT_ID,
                ProductSQLiteHelper.PRODUCT_NAME,
                ProductSQLiteHelper.PRODUCT_BRAND,
                ProductSQLiteHelper.PRODUCT_PRICE

        };

        Resources res = getResources();
        Log.v("Res:",String.valueOf(res));

//        setTitle("Hot Product");

        sqlHelper = new ProductSQLiteHelper(this);

        infodb = sqlHelper.getReadableDatabase();

        Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        infoCursor.moveToFirst();
        if (!infoCursor.isAfterLast()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }

        String columnsToDisplay[] = {
                ProductSQLiteHelper.PRODUCT_NAME,
                ProductSQLiteHelper.PRODUCT_BRAND,
                ProductSQLiteHelper.PRODUCT_PRICE
//                ProductSQLiteHelper.PRODUCT_PHOTO
        };

        int mappingToView[] = {
                R.id.productName,
                R.id.productBrand,
                R.id.productPrice
//                R.id.productPhoto
        };

        String args[] = {"1"};
        infoCursor = infodb.query(ProductSQLiteHelper.TABLE_NAME,columnsToSelect," hot = ? ",args,null,null,null);

        String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex("photo"));
        Log.v("resource name",posterResourceName);
        dbAdapter = new SimpleCursorAdapter(this,R.layout.hotproduct_middle_page_row,infoCursor,columnsToDisplay,mappingToView,0);

        setListAdapter(dbAdapter);

        }

}

I found that the problems appear in

      Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        infoCursor.moveToFirst();
        if (!infoCursor.isAfterLast()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }

Body:
Your issue is due to a getColumnIndex not finding the specified column and thus returning -1 (as it does when the column is not a column). The underlying cause is that you are creating a Cursor with a single column yet in your code you are trying to access 2 columns i.e.

infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT)))

infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO))

The Cursor will contain just 1 column, the photo column.

I would suggest changing the SELECT clause to "SELECT * FROM phone", this will then create a Cursor with ALL columns from the table.

However, there is an additional flaw with the code in that you are not checking the result of the moveToFirst.

If the Cursor is empty then moveToFirst will return false. As the Cursor will not be after the last any attempt to retrieve data from the Cursor will fail as there is no data.

I would suggest amending your code to :-

        Cursor infoCursor= infodb.rawQuery("SELECT * FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        while (infoCursor.moveToNext()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }

You may have to write code to handle an empty cursor.


问:
Reading Words from a File and Writing Them on The Same Line
I have a file that contains a word per a line. Each sentence is separated by an empty line. I want to read the file and write the whole words of a sentence on the same line. For example:

```<code>This
is
a
sample
input

Hello
World
!!
</code>```

The desired output is:

```<code>This is a sample input
Hello World !!
</code>```

I try this:

```<code>file = open('Words.txt', "r")
Writfile = open('Sent.txt','w')

for line in file:
    if line in ['\n']:
        Writfile.write('\n')
    else:
        Writfile.write(line + " ",)
</code>```

答:
You can try doing it this way:

```<code>with open("infile.txt", "r") as infile:
  string = infile.read().split("\n\n")

with open("outfile.txt", "w") as outfile:
  for s in string:
    outfile.write(s.replace("\n"," ") + "\n")
</code>```

Output written on file:

```<code>This  is  a sample input
Hello World !!
</code>```

Body:
I have a file that contains a word per a line. Each sentence is separated by an empty line. I want to read the file and write the whole words of a sentence on the same line. For example:

This
is
a
sample
input

Hello
World
!!

The desired output is:

This is a sample input
Hello World !!

I try this:

file = open('Words.txt', "r")
Writfile = open('Sent.txt','w')

for line in file:
    if line in ['\n']:
        Writfile.write('\n')
    else:
        Writfile.write(line + " ",)

Body:
You can try doing it this way:

with open("infile.txt", "r") as infile:
  string = infile.read().split("\n\n")

with open("outfile.txt", "w") as outfile:
  for s in string:
    outfile.write(s.replace("\n"," ") + "\n")

Output written on file:

This  is  a sample input
Hello World !!


问:
Music play only one time
I'm trying to play sound on Button's setOnClickListener. this is what i'm trying:

```<code>final MediaPlayer mpclikc = MediaPlayer.create(getApplicationContext(), R.raw.click);
        btn1.setOnClickListener(new OnClickListener() {
            public void onClick(View var1) {
                mpclikc.start();
            }
        });
</code>```

The problem is sound play only once!

Sound play only the first time I click on Button!! What should i do?

答:
Depends on how you want it to act when you press the button again. Do you want it to play from the the current position? Or do you want to reset it?

However I would just read through the API doc: https://developer.android.com/reference/android/media/MediaPlayer.html

mpclikc.reset();
mpclikc.play();

Title: Music play only one time

Body:
I'm trying to play sound on Button's setOnClickListener. this is what i'm trying:

final MediaPlayer mpclikc = MediaPlayer.create(getApplicationContext(), R.raw.click);
        btn1.setOnClickListener(new OnClickListener() {
            public void onClick(View var1) {
                mpclikc.start();
            }
        });

The problem is sound play only once!

Sound play only the first time I click on Button!! What should i do?


问:
PHP - How to re-encode a URI
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.

Here is the situation:

JavaScript passes encoded uri as query string parameter to php script.

PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:

```<code>http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great
</code>```

Is there a pre-built php function for this or should I just write my own?

PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.

Thanks,
Macy

答:
I don't know if will help you, but PHP have 3 useful functions:

```<code>$url = parse_url('put the url here');
parse_str( $url['query'], $query ); // generating an array by reference (yes, kinda weird)
echo $query; //in this line, you can encode or decode.
</code>```

or, if you want to mount a query, you can use http_build_query(); that accepts values from an array, like:

```<code>$url = 'http://my.example.com/dog walk?';
$array = Array (
 'is' => 'very_great',
);
$url_created = $url . http_build_query($array);
</code>```

Title: PHP - How to re-encode a URI

Body:
I think I have the need to take a uri which has been decoded in PHP, and re-encode it.

Here is the situation:

JavaScript passes encoded uri as query string parameter to php script.

PHP script embeds uri as a hidden input value in an html document, responds with the document to a user agent.

JavaScript reads embedded uri and sets location of current document based on value of hidden input.

On Step 2, I am finding that the Uri is fully decoded after reading it in via $_GET.  So when I embed the uri in the hidden input, it becomes un-encoded.  So I would like to run a PHP script which re-encodes the Uri properly ex:

http://my.example.com/dog walk?is=very great

==>

http://my.example.com/dog%20walk?is=very%20great

Is there a pre-built php function for this or should I just write my own?

PLEASE NOTE: urlencode and urldecode are not the answer to get the desired input/output I have in the example above.

Thanks,
Macy

Body:
I don't know if will help you, but PHP have 3 useful functions:

$url = parse_url('put the url here');
parse_str( $url['query'], $query ); // generating an array by reference (yes, kinda weird)
echo $query; //in this line, you can encode or decode.

or, if you want to mount a query, you can use http_build_query(); that accepts values from an array, like:

$url = 'http://my.example.com/dog walk?';
$array = Array (
 'is' => 'very_great',
);
$url_created = $url . http_build_query($array);


问:
Accessing Angular component variable via Leaflet marker.on('click', ...)
I'm using ngx-leaflet to render a map in an Angular app. I'm adding markers to a layer with an EventListener on click like so:

```<code>questions.forEach((question) => {
  this.layers.push(
    marker([question.lat, question.lng], {
      icon: icon({
        iconSize: [25, 41],
        iconAnchor: [13, 41],
        iconUrl: 'assets/marker-icon.png',
        shadowUrl: 'assets/marker-shadow.png'
      })
    }).on('click', this.onClick)
  );
});
</code>```

With onClick being:

```<code>onClick(e) {
  this.showQuestion = true;
  console.log('data: ', e);
}
</code>```

I want the click on a marker to set the showQuestion Boolean to true, but the context of this is not related to the Angular component, but to the Leaflet event.

How can I access the Angular component this instead of the Leaflet this?

答:
The simplest approach is to use bind to create a function with an explicit this context. See the following example:

```<code>questions.forEach((question) => {
  this.layers.push(
    marker([question.lat, question.lng], {
      icon: icon({
        iconSize: [25, 41],
        iconAnchor: [13, 41],
        iconUrl: 'assets/marker-icon.png',
        shadowUrl: 'assets/marker-shadow.png'
      })
    }).on('click', this.onClick.bind(this))
  );
});
</code>```

In this example, the onClick handler will be invoked with this set to whatever this is referring to when the call to bind is evaluated (I'm assuming from your example it will be the ngx component).

Body:
I'm using ngx-leaflet to render a map in an Angular app. I'm adding markers to a layer with an EventListener on click like so:

questions.forEach((question) => {
  this.layers.push(
    marker([question.lat, question.lng], {
      icon: icon({
        iconSize: [25, 41],
        iconAnchor: [13, 41],
        iconUrl: 'assets/marker-icon.png',
        shadowUrl: 'assets/marker-shadow.png'
      })
    }).on('click', this.onClick)
  );
});

With onClick being:

onClick(e) {
  this.showQuestion = true;
  console.log('data: ', e);
}

I want the click on a marker to set the showQuestion Boolean to true, but the context of this is not related to the Angular component, but to the Leaflet event.

How can I access the Angular component this instead of the Leaflet this?

Body:
The simplest approach is to use bind to create a function with an explicit this context. See the following example:

questions.forEach((question) => {
  this.layers.push(
    marker([question.lat, question.lng], {
      icon: icon({
        iconSize: [25, 41],
        iconAnchor: [13, 41],
        iconUrl: 'assets/marker-icon.png',
        shadowUrl: 'assets/marker-shadow.png'
      })
    }).on('click', this.onClick.bind(this))
  );
});

In this example, the onClick handler will be invoked with this set to whatever this is referring to when the call to bind is evaluated (I'm assuming from your example it will be the ngx component).


问:
How to convert a nested lists to dataframe in R?
I'm have a nested list I would like to convert to a dataframe.

```<code>iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

df <- data.frame(t(sapply(All,c))) # Convert list to dataframe
</code>```

But my problem is that df$iter1 returns a list instead of a dataframe, any idea ?

```<code>> class(df)
[1] "data.frame"

> df$item1
$iter1
[1] 1

$iter2
[1] 1
</code>```

I have the same problem when converting with do.call : df <- data.frame(do.call(rbind, All)) but I can't figure out what is wrong.

答:
```<code>temp = unique(unlist(lapply(All, names)))
mydf = setNames(object = data.frame(lapply(temp, function(nm)
    unlist(lapply(All, function(x) x[[nm]])))), nm = temp)

mydf
#      item1 item2
#iter1     1     a
#iter2     1     b
</code>```

OR

```<code>do.call(rbind, lapply(All, data.frame))
#      item1 item2
#iter1     1     a
#iter2     1     b
</code>```

OR

```<code>data.table::rbindlist(All, idcol = TRUE)
#     .id item1 item2
#1: iter1     1     a
#2: iter2     1     b
</code>```

Body:
I'm have a nested list I would like to convert to a dataframe.

iter1 <- list(item1 = 1, item2 = "a")
iter2 <- list(item1 = 1, item2 = "b")
All <- list(iter1 = iter1, iter2 = iter2)

df <- data.frame(t(sapply(All,c))) # Convert list to dataframe

But my problem is that df$iter1 returns a list instead of a dataframe, any idea ?

> class(df)
[1] "data.frame"

> df$item1
$iter1
[1] 1

$iter2
[1] 1

I have the same problem when converting with do.call : df <- data.frame(do.call(rbind, All)) but I can't figure out what is wrong.

Body:
temp = unique(unlist(lapply(All, names)))
mydf = setNames(object = data.frame(lapply(temp, function(nm)
    unlist(lapply(All, function(x) x[[nm]])))), nm = temp)

mydf
#      item1 item2
#iter1     1     a
#iter2     1     b

OR

do.call(rbind, lapply(All, data.frame))
#      item1 item2
#iter1     1     a
#iter2     1     b

OR

data.table::rbindlist(All, idcol = TRUE)
#     .id item1 item2
#1: iter1     1     a
#2: iter2     1     b


问:
Restrict API key access to only one API in Google Cloud Endpoints
I have deployed a Google Cloud Endpoints v2 API with the apiKeyRequired = AnnotationBoolean.TRUE to restrict access to clients who have a api key. I have created an api key in the Credentials page in Cloud platform and I am able to access the api with the key.

I now want to give this API key to a third party consumer, but since I have deployed multiple API's with Google Cloud Endpoints I want to give them access to only one of them.
How can I achieve that?

答: Check out this article. Basically, the customer should use their own API key, and you should grant access to the API via Cloud Console.</p>


问:
Remove white space between the string using javascript
I have string. I just want to remove all white spaces between all characters.Please reply
"PB 10 CV 2662" to "PB10CV2662"</p>

答:
```<code>value = value.replace(/(\r\n\s|\n|\r|\s)/gm, '');
</code>```


问:
Trouble migrating from Gracenote Mobile Client to GNSDK for Mobile
I'm working on migrating my Android app from the legacy Gracenote Mobile Client to the newer GNSDK for Mobile SDK, and I've hit a few snags:

In mobile client, I used GNOperations.recognizeMIDStreamFromRadio(GNSearchResultReady, GNConfig, samplePCMBuffer)
to initiate a fingerprint and lookup operation on a PCM buffer.  My application can only supply prerecorded audio to Gracenote (as opposed to simply pointing Gracenote at a streaming audio source), ideally as raw PCM though I could encode to standard compression formats if necessary.  What should I use from the GNSDK for Mobile API to effect the same fingerprint and lookup operation on supplied prerecorded audio data, which can hopefully still be raw PCM?

The class GnMusicId looks like it might be a handy generic fingerprint generator and query issuer class, so it might be the answer to #1 above.  However, I haven't found a way to determine when it finishes writing a fingerprint and, therefore, we are ready to issue a query.  How can I get a callback letting me know that GnMusicId has finished writing a fingerprint from the GnMusicId.fingerprintWrite(byte[] audioData, long audioDataSize) method, and that the fingerprint is ready to be used in a query via GnMusicId.findAlbums(fingerprintDataGet(), GnFingerprintType.kFingerprintTypeStream6)?

In Mobile Client I was able to cancel ongoing Gracenote operations using GNOperations.cancel(GNSearchResultReady) -- I've read that the new architecture requires that specific operations be canceled individually due to a more modular design, but I haven't found a standard cancellation API on the various operations the GNSDK for Mobile can perform -- how should I cancel fingerprint and song lookup operations in GNSDK for Mobile?

答:
Turns out you can recognize a given PCM array in GNSDK for Android with the following three GnMusicIdStream API calls:

GnMusicIdStream.audioProcessStart(sampleRateHz,pcmBitcount,channelCount) to prepare the recognition engine for the incoming PCM

GnMusicIdStream.audioProcess(pcmArray,pcmArray.length) to pass in the PCM array that you want to recognize

GnMusicIdStream.identifyAlbumAsync() to generate the fingerprint and then use it for a lookup operation.  This will cause callbacks to the IGnMusicIdStreamEvents object passed to your GnMusicIdStream instance, and musicIdStreamAlbumResult() will deliver any results.

As far as I can see, using this approach you don't need to wait on fingerprint generation etc. explicitly -- you just call those three methods in order and then GNSDK handles the rest and will eventually issue a callback.  The full id operation ends up looking like this:

```<code>try {

        mGnMusicIdStream = new GnMusicIdStream(mGnUser, GnMusicIdStreamPreset.kPresetRadio, new IGnMusicIdStreamEvents() {
            @Override
            public void musicIdStreamProcessingStatusEvent(GnMusicIdStreamProcessingStatus gnMusicIdStreamProcessingStatus, IGnCancellable iGnCancellable) {
                Log.d(TAG,"gracenote gnsdk -- musicIdStreamProcessingStatusEvent(); event is: "+gnMusicIdStreamProcessingStatus);
            }

            @Override
            public void musicIdStreamIdentifyingStatusEvent(GnMusicIdStreamIdentifyingStatus gnMusicIdStreamIdentifyingStatus, IGnCancellable iGnCancellable) {
                Log.d(TAG,"gracenote gnsdk -- musicIdStreamIdentifyingStatusEvent(); event is: "+gnMusicIdStreamIdentifyingStatus);
            }

            @Override
            public void musicIdStreamAlbumResult(GnResponseAlbums gnResponseAlbums, IGnCancellable iGnCancellable) {

                Log.d(TAG,"gracenote gnsdk -- musicIdStreamAlbumResult();  responsealbums matches: "+gnResponseAlbums.resultCount());

                if (gnResponseAlbums.resultCount() > 0) {
                    try {
                        final GnAlbum albumResponse = gnResponseAlbums.albums().at(0).next();

                        final GnTrack trackResponse = albumResponse.trackMatched();

                        if (trackResponse != null) {
                            mEvent.postOnGNSearchResult(new ISongRecognitionResponse() {
                                @Override
                                public
                                @NonNull
                                String extractTrackTitle() {
                                    // seems that track title comes reliably from GnTrack and much of the rest is locked
                                    // up in the GnAlbum?
                                    if (trackResponse.title() != null) {
                                        return trackResponse.title().display();
                                    } else {
                                        return "";
                                    }
                                }

                                @Override
                                public
                                @NonNull
                                String extractTrackArtist() {
                                    if (albumResponse.artist() != null) {
                                        if(BuildConfig.RULE_DEBUG_LEVEL>0)
                                            Log.d(TAG,"gnsdk -- album artist says "+albumResponse.artist().name().display());
                                        return albumResponse.artist().name().display();
                                    } else {
                                        return "";
                                    }
                                }

                                @Override
                                public long extractTrackPosition() {
                                    return trackResponse.currentPosition();
                                }

                                @Override
                                public long extractTrackDuration() {
                                    return trackResponse.duration();
                                }

                                @Override
                                public byte[] extractCoverArtImageData() {
                                    // seems that base64 string of the image is not always/commonly available
                                    // at least as we're trying to access it here.  The sample app downloads the image
                                    // asynchronously from the URL, which seems more reliable
                                    String img64 = albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).imageDataBase64(); //trackResponse.content(GnContentType.kContentTypeImageCover).asset(GnImageSize.kImageSize220).imageDataBase64();

                                    if(img64 != null && !img64.isEmpty()) {
                                        return Base64.decode(img64, Base64.DEFAULT);
                                    }else{
                                        return null;
                                    }
                                }

                                @NonNull
                                @Override
                                public String extractCoverArtImageURL() {
                                    // beware: asking for specific image sizes has been known to cause
                                    // no cover art to come back even if there might be cover art at another size.
                                    // The sample app uses the categorical size qualifier constant kImageSizeSmall
                                    String httpURL = albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).urlHttp();

                                    return httpURL;
                                }
                            });
                        }//end if track response data is non-null
                        else {
                            mEvent.postOnGNSearchResult(null);
                        }
                    }catch(GnException e){
                        Log.e(TAG, "we received a response clbk, but failed to process it", e);
                    }
                }//end if greater than 0 results
                else{
                    //no results, so pass a null result to indicate a miss
                    mEvent.postOnGNSearchResult(null);
                }
            }

            @Override
            public void musicIdStreamIdentifyCompletedWithError(GnError gnError) {
                Log.e(TAG,"gnsdk -- musicIdStreamIdentifyCompletedWithError(); we received a response clbk, but failed to process it");
                mEvent.postOnGNSearchFailure(gnError.errorDescription());
            }

            @Override
            public void statusEvent(GnStatus gnStatus, long l, long l1, long l2, IGnCancellable iGnCancellable) {
                Log.e(TAG,"gnsdk -- statusEvent(); status is: "+gnStatus);
            }
        });

        //configure the options on the gnmusicidstream instance
        mGnMusicIdStream.options().lookupData(GnLookupData.kLookupDataContent, true);
        mGnMusicIdStream.options().lookupData(GnLookupData.kLookupDataSonicData, true);
        mGnMusicIdStream.options().lookupMode(GnLookupMode.kLookupModeOnline);
        mGnMusicIdStream.options().preferResultCoverart(true);
        mGnMusicIdStream.options().resultSingle(true);

        //configure audio processing params on gnmusicidstream
        mGnMusicIdStream.audioProcessStart(sampleRateHz,pcmBitcount,channelCount);

        //pass the pcm array to the gnmusicidstream for processing
        mGnMusicIdStream.audioProcess(pcmArray,pcmArray.length);

        //initiate the lookup operation based on the processed pcm
        mGnMusicIdStream.identifyAlbumAsync();

    }catch(GnException e){
        Log.e(TAG,"gnsdk -- failed recognition operation",e);
    }
</code>```

The return data is kind of confusing, with multiple potential ways to extract metadata about the track which may be null or empty when queried certain ways and not when queried in other ways.  Interesting points I've found about the GnResponseAlbums response object so far (I'm not sure about the nullability contract of the return values mentioned below, so watch out for nullpointerexceptions):

gnResponseAlbums.resultCount() will be 0 if nothing explicitly went wrong but there were no matches found.

the matched GnTrack can be retrieved with albumResponse.trackMatched()

the track title can be retrieved as a String with albumResponse.trackMatched().title().display()

the track artist can be retrieved with albumResponse.artist().name().display()

the current track position in time can be extracted with albumResponse.trackMatched().currentPosition(), which seems to be pretty accurate in determining the time the song will end as {endTime = currentTime + duration - currentPosition}

the duration of the track can be extracted with albumResponse.trackMatched().duration()

the cover art URL can be extracted with albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).urlHttp().

I haven't had any luck getting the image bundled as a base64 string via albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).imageDataBase64(), but the GNSDK provided a simple GnAssetFetch class which can be used to pull down cover art data as follows

```<code>GnAssetFetch assetData = new GnAssetFetch(mGnUser,coverArtUrl);
byte[] data = assetData.data();
</code>```

As for cancelling an operation in progress, the GnMusicIdStream instance's identifyCancel() method can be used.  If the cancellation is going to occur in the IGnMusicIdStreamEvents callback methods, the provided IGnCancellable canceller should be used instead.

Body:
Turns out you can recognize a given PCM array in GNSDK for Android with the following three GnMusicIdStream API calls:

GnMusicIdStream.audioProcessStart(sampleRateHz,pcmBitcount,channelCount) to prepare the recognition engine for the incoming PCM

GnMusicIdStream.audioProcess(pcmArray,pcmArray.length) to pass in the PCM array that you want to recognize

GnMusicIdStream.identifyAlbumAsync() to generate the fingerprint and then use it for a lookup operation.  This will cause callbacks to the IGnMusicIdStreamEvents object passed to your GnMusicIdStream instance, and musicIdStreamAlbumResult() will deliver any results.

As far as I can see, using this approach you don't need to wait on fingerprint generation etc. explicitly -- you just call those three methods in order and then GNSDK handles the rest and will eventually issue a callback.  The full id operation ends up looking like this:

try {

        mGnMusicIdStream = new GnMusicIdStream(mGnUser, GnMusicIdStreamPreset.kPresetRadio, new IGnMusicIdStreamEvents() {
            @Override
            public void musicIdStreamProcessingStatusEvent(GnMusicIdStreamProcessingStatus gnMusicIdStreamProcessingStatus, IGnCancellable iGnCancellable) {
                Log.d(TAG,"gracenote gnsdk -- musicIdStreamProcessingStatusEvent(); event is: "+gnMusicIdStreamProcessingStatus);
            }

            @Override
            public void musicIdStreamIdentifyingStatusEvent(GnMusicIdStreamIdentifyingStatus gnMusicIdStreamIdentifyingStatus, IGnCancellable iGnCancellable) {
                Log.d(TAG,"gracenote gnsdk -- musicIdStreamIdentifyingStatusEvent(); event is: "+gnMusicIdStreamIdentifyingStatus);
            }

            @Override
            public void musicIdStreamAlbumResult(GnResponseAlbums gnResponseAlbums, IGnCancellable iGnCancellable) {

                Log.d(TAG,"gracenote gnsdk -- musicIdStreamAlbumResult();  responsealbums matches: "+gnResponseAlbums.resultCount());

                if (gnResponseAlbums.resultCount() > 0) {
                    try {
                        final GnAlbum albumResponse = gnResponseAlbums.albums().at(0).next();

                        final GnTrack trackResponse = albumResponse.trackMatched();

                        if (trackResponse != null) {
                            mEvent.postOnGNSearchResult(new ISongRecognitionResponse() {
                                @Override
                                public
                                @NonNull
                                String extractTrackTitle() {
                                    // seems that track title comes reliably from GnTrack and much of the rest is locked
                                    // up in the GnAlbum?
                                    if (trackResponse.title() != null) {
                                        return trackResponse.title().display();
                                    } else {
                                        return "";
                                    }
                                }

                                @Override
                                public
                                @NonNull
                                String extractTrackArtist() {
                                    if (albumResponse.artist() != null) {
                                        if(BuildConfig.RULE_DEBUG_LEVEL>0)
                                            Log.d(TAG,"gnsdk -- album artist says "+albumResponse.artist().name().display());
                                        return albumResponse.artist().name().display();
                                    } else {
                                        return "";
                                    }
                                }

                                @Override
                                public long extractTrackPosition() {
                                    return trackResponse.currentPosition();
                                }

                                @Override
                                public long extractTrackDuration() {
                                    return trackResponse.duration();
                                }

                                @Override
                                public byte[] extractCoverArtImageData() {
                                    // seems that base64 string of the image is not always/commonly available
                                    // at least as we're trying to access it here.  The sample app downloads the image
                                    // asynchronously from the URL, which seems more reliable
                                    String img64 = albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).imageDataBase64(); //trackResponse.content(GnContentType.kContentTypeImageCover).asset(GnImageSize.kImageSize220).imageDataBase64();

                                    if(img64 != null && !img64.isEmpty()) {
                                        return Base64.decode(img64, Base64.DEFAULT);
                                    }else{
                                        return null;
                                    }
                                }

                                @NonNull
                                @Override
                                public String extractCoverArtImageURL() {
                                    // beware: asking for specific image sizes has been known to cause
                                    // no cover art to come back even if there might be cover art at another size.
                                    // The sample app uses the categorical size qualifier constant kImageSizeSmall
                                    String httpURL = albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).urlHttp();

                                    return httpURL;
                                }
                            });
                        }//end if track response data is non-null
                        else {
                            mEvent.postOnGNSearchResult(null);
                        }
                    }catch(GnException e){
                        Log.e(TAG, "we received a response clbk, but failed to process it", e);
                    }
                }//end if greater than 0 results
                else{
                    //no results, so pass a null result to indicate a miss
                    mEvent.postOnGNSearchResult(null);
                }
            }

            @Override
            public void musicIdStreamIdentifyCompletedWithError(GnError gnError) {
                Log.e(TAG,"gnsdk -- musicIdStreamIdentifyCompletedWithError(); we received a response clbk, but failed to process it");
                mEvent.postOnGNSearchFailure(gnError.errorDescription());
            }

            @Override
            public void statusEvent(GnStatus gnStatus, long l, long l1, long l2, IGnCancellable iGnCancellable) {
                Log.e(TAG,"gnsdk -- statusEvent(); status is: "+gnStatus);
            }
        });

        //configure the options on the gnmusicidstream instance
        mGnMusicIdStream.options().lookupData(GnLookupData.kLookupDataContent, true);
        mGnMusicIdStream.options().lookupData(GnLookupData.kLookupDataSonicData, true);
        mGnMusicIdStream.options().lookupMode(GnLookupMode.kLookupModeOnline);
        mGnMusicIdStream.options().preferResultCoverart(true);
        mGnMusicIdStream.options().resultSingle(true);

        //configure audio processing params on gnmusicidstream
        mGnMusicIdStream.audioProcessStart(sampleRateHz,pcmBitcount,channelCount);

        //pass the pcm array to the gnmusicidstream for processing
        mGnMusicIdStream.audioProcess(pcmArray,pcmArray.length);

        //initiate the lookup operation based on the processed pcm
        mGnMusicIdStream.identifyAlbumAsync();

    }catch(GnException e){
        Log.e(TAG,"gnsdk -- failed recognition operation",e);
    }

The return data is kind of confusing, with multiple potential ways to extract metadata about the track which may be null or empty when queried certain ways and not when queried in other ways.  Interesting points I've found about the GnResponseAlbums response object so far (I'm not sure about the nullability contract of the return values mentioned below, so watch out for nullpointerexceptions):

gnResponseAlbums.resultCount() will be 0 if nothing explicitly went wrong but there were no matches found.

the matched GnTrack can be retrieved with albumResponse.trackMatched()

the track title can be retrieved as a String with albumResponse.trackMatched().title().display()

the track artist can be retrieved with albumResponse.artist().name().display()

the current track position in time can be extracted with albumResponse.trackMatched().currentPosition(), which seems to be pretty accurate in determining the time the song will end as {endTime = currentTime + duration - currentPosition}

the duration of the track can be extracted with albumResponse.trackMatched().duration()

the cover art URL can be extracted with albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).urlHttp().

I haven't had any luck getting the image bundled as a base64 string via albumResponse.coverArt().asset(GnImageSize.kImageSizeSmall).imageDataBase64(), but the GNSDK provided a simple GnAssetFetch class which can be used to pull down cover art data as follows

GnAssetFetch assetData = new GnAssetFetch(mGnUser,coverArtUrl);
byte[] data = assetData.data();

As for cancelling an operation in progress, the GnMusicIdStream instance's identifyCancel() method can be used.  If the cancellation is going to occur in the IGnMusicIdStreamEvents callback methods, the provided IGnCancellable canceller should be used instead.


问:
MySQL query recovery
I created a database for my class and inserted all of my data into the tables but I did not save the queries I used to create them. Is there any way that I can get back the queries I originally used to input all of the data so that I can save them to a separate query tab?</p>

答:
For the tables issue the SHOW CREATE TABLE
; command.
For the data you can use a tool like phpMyAdmin or HeidiSQL (Windows) to create an export of the table contents.

Title: MySQL query recovery

Body:
For the tables issue the SHOW CREATE TABLE <table name>; command.
For the data you can use a tool like phpMyAdmin or HeidiSQL (Windows) to create an export of the table contents.