问:
PocketSphinx for an Android dictation app
I'm trying to implement a "dictation" feature using the PocketSphinx on Android in conjunction with one of Keith Vertanen's language models.  I've modified the sample to look like this:

```<code>private void setupRecognizer(File assetsDir) throws IOException {
 recognizer = defaultSetup()
     .setAcousticModel(new File(assetsDir, "en-us-ptm"))
     .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
     .setRawLogDir(assetsDir)
     .setKeywordThreshold(1e-45f)
     .setBoolean("-allphone_ci", true)
      .getRecognizer();
  recognizer.addListener(this);
  File ngramModel = new File(assetsDir, "lm_csr_5k_nvp_2gram.arpa");
  recognizer.addNgramSearch(NGRAM_SEARCH, ngramModel);
</code>```

where lm_csr_5k_nvp_2gram.arpa is from the 5K NVP 2-gram dowload on Keith Vertanen's site.

I'm getting this error:

```<code>1 18:04:29.861 2837-2863/? I/SpeechRecognizer: Load N-gram model /storage/emulated/0/Android/data/edu.cmu.sphinx.pocketsphinx/files/sync/lm_csr_5k_nvp_2gram.arpa
01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(399): Trying to read LM in trie binary format
01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(410): Header doesn't match
01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(177): Trying to read LM in arpa format
01-31 18:04:29.862 2837-2863/? E/cmusphinx: ERROR: "ngram_model_trie.c", line 103: Bad ngram count
01-31 18:04:29.862 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(489): Trying to read LM in DMP format
01-31 18:04:29.862 2837-2863/? E/cmusphinx: ERROR: "ngram_model_trie.c", line 500: Wrong magic header size number a5c6461: /storage/emulated/0/Android/data/edu.cmu.sphinx.pocketsphinx/files/sync/lm_csr_5k_nvp_2gram.arpa is not a dump file
01-31 18:04:29.864 2837-2863/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                 Process: edu.cmu.sphinx.pocketsphinx, PID: 2837
                                                 java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                     at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                     at java.lang.Thread.run(Thread.java:818)
                                                  Caused by: java.lang.RuntimeException: Decoder_setLmFile returned -1
                                                     at edu.cmu.pocketsphinx.PocketSphinxJNI.Decoder_setLmFile(Native Method)
                                                     at edu.cmu.pocketsphinx.Decoder.setLmFile(Decoder.java:172)
                                                     at edu.cmu.pocketsphinx.SpeechRecognizer.addNgramSearch(SpeechRecognizer.java:247)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity.setupRecognizer(PocketSphinxActivity.java:161)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity.access$000(PocketSphinxActivity.java:50)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity$1.doInBackground(PocketSphinxActivity.java:72)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity$1.doInBackground(PocketSphinxActivity.java:66)
                                                     at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                     at java.lang.Thread.run(Thread.java:818)
</code>```

The lines

```<code>01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(177): Trying to read LM in arpa format
01-31 18:04:29.862 2837-2863/? E/cmusphinx: ERROR: "ngram_model_trie.c", line 103: Bad ngram count
</code>```

make me think that the lm_csr_5k_nvp_2gram.arpa file isn't correctly formatted or something.  The file looks like this:

```<code>\data\
ngram 1=5000
ngram 2=4331397
ngram 3=0

\1-grams:
-2.11154    </s>    0
-99 <s> -3.13167
-0.3954594  <unk>   -0.4365645
-2.271447   a   -2.953606
-3.384721   a.  -1.85196
-5.788997   a.'s    -0.8137056
-4.139672   abandoned   -0.9728376
-3.904189   ability -1.838658
-4.360272   able    -2.161723
...
</code>```

which at least looks like the example file here.

My only other thought was that perhaps the extension is wrong, since this says

Language model can be stored and loaded in three different format - text ARPA format, binary format BIN and binary DMP format. ARPA format takes more space but it is possible to edit it. ARPA files have .lm extension. Binary format takes significantly less space and faster to load. Binary files have .lm.bin extension. It is also possible to convert between formats. DMP format is obsolete and not recommended.

which makes it sound like the file should be named lm_csr_5k_nvp_2gram.lm instead of lm_csr_5k_nvp_2gram.arpa.  I did try renaming the file, however, without any change in the exception.

What is the correct way to do this?

答:
Convert your arpa file to language model(lm) using below command on sphinx.

```<code>sphinx_lm_convert -i lm_csr_5k_nvp_2gram.arpa -o lm_csr_5k_nvp_2gram.lm.dmp
</code>```

Use generated language model in your android program.

```<code>recognizer.addNgramSearch(DIGITS_SEARCH,new File(assetsDir, "lm_csr_5k_nvp_2gram.lm.dmp"))
</code>```

Body:
I'm trying to implement a "dictation" feature using the PocketSphinx on Android in conjunction with one of Keith Vertanen's language models.  I've modified the sample to look like this:

private void setupRecognizer(File assetsDir) throws IOException {
 recognizer = defaultSetup()
     .setAcousticModel(new File(assetsDir, "en-us-ptm"))
     .setDictionary(new File(assetsDir, "cmudict-en-us.dict"))
     .setRawLogDir(assetsDir)
     .setKeywordThreshold(1e-45f)
     .setBoolean("-allphone_ci", true)
      .getRecognizer();
  recognizer.addListener(this);
  File ngramModel = new File(assetsDir, "lm_csr_5k_nvp_2gram.arpa");
  recognizer.addNgramSearch(NGRAM_SEARCH, ngramModel);

where lm_csr_5k_nvp_2gram.arpa is from the 5K NVP 2-gram dowload on Keith Vertanen's site.

I'm getting this error:

1 18:04:29.861 2837-2863/? I/SpeechRecognizer: Load N-gram model /storage/emulated/0/Android/data/edu.cmu.sphinx.pocketsphinx/files/sync/lm_csr_5k_nvp_2gram.arpa
01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(399): Trying to read LM in trie binary format
01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(410): Header doesn't match
01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(177): Trying to read LM in arpa format
01-31 18:04:29.862 2837-2863/? E/cmusphinx: ERROR: "ngram_model_trie.c", line 103: Bad ngram count
01-31 18:04:29.862 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(489): Trying to read LM in DMP format
01-31 18:04:29.862 2837-2863/? E/cmusphinx: ERROR: "ngram_model_trie.c", line 500: Wrong magic header size number a5c6461: /storage/emulated/0/Android/data/edu.cmu.sphinx.pocketsphinx/files/sync/lm_csr_5k_nvp_2gram.arpa is not a dump file
01-31 18:04:29.864 2837-2863/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                 Process: edu.cmu.sphinx.pocketsphinx, PID: 2837
                                                 java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                     at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                     at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                     at java.lang.Thread.run(Thread.java:818)
                                                  Caused by: java.lang.RuntimeException: Decoder_setLmFile returned -1
                                                     at edu.cmu.pocketsphinx.PocketSphinxJNI.Decoder_setLmFile(Native Method)
                                                     at edu.cmu.pocketsphinx.Decoder.setLmFile(Decoder.java:172)
                                                     at edu.cmu.pocketsphinx.SpeechRecognizer.addNgramSearch(SpeechRecognizer.java:247)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity.setupRecognizer(PocketSphinxActivity.java:161)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity.access$000(PocketSphinxActivity.java:50)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity$1.doInBackground(PocketSphinxActivity.java:72)
                                                     at edu.cmu.pocketsphinx.demo.PocketSphinxActivity$1.doInBackground(PocketSphinxActivity.java:66)
                                                     at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                     at java.lang.Thread.run(Thread.java:818)

The lines

01-31 18:04:29.861 2837-2863/? I/cmusphinx: INFO: ngram_model_trie.c(177): Trying to read LM in arpa format
01-31 18:04:29.862 2837-2863/? E/cmusphinx: ERROR: "ngram_model_trie.c", line 103: Bad ngram count

make me think that the lm_csr_5k_nvp_2gram.arpa file isn't correctly formatted or something.  The file looks like this:

\data\
ngram 1=5000
ngram 2=4331397
ngram 3=0

\1-grams:
-2.11154    </s>    0
-99 <s> -3.13167
-0.3954594  <unk>   -0.4365645
-2.271447   a   -2.953606
-3.384721   a.  -1.85196
-5.788997   a.'s    -0.8137056
-4.139672   abandoned   -0.9728376
-3.904189   ability -1.838658
-4.360272   able    -2.161723
...

which at least looks like the example file here.

My only other thought was that perhaps the extension is wrong, since this says

Language model can be stored and loaded in three different format - text ARPA format, binary format BIN and binary DMP format. ARPA format takes more space but it is possible to edit it. ARPA files have .lm extension. Binary format takes significantly less space and faster to load. Binary files have .lm.bin extension. It is also possible to convert between formats. DMP format is obsolete and not recommended.

which makes it sound like the file should be named lm_csr_5k_nvp_2gram.lm instead of lm_csr_5k_nvp_2gram.arpa.  I did try renaming the file, however, without any change in the exception.

What is the correct way to do this?

Body:
Convert your arpa file to language model(lm) using below command on sphinx.

sphinx_lm_convert -i lm_csr_5k_nvp_2gram.arpa -o lm_csr_5k_nvp_2gram.lm.dmp

Use generated language model in your android program.

recognizer.addNgramSearch(DIGITS_SEARCH,new File(assetsDir, "lm_csr_5k_nvp_2gram.lm.dmp"))


来源: stackexchange

问:
Need to associate unique integer value with classes
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

```<code>type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;
</code>```

Testing this, I found out that I need to be super careful which class I declare. If I use this:

```<code>  var Fruit: TFruit;

  Fruit := TOrange.Create;
</code>```

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

答:
Looking on other angle: why ID is not an read-only object property (instead of a class const)?

So:

```<code> type
   TFruit = class
   protected
     FId: Integer;
   published
     property ID:Integer read FId;
   end;

   TApple = class(TFruit)
     constructor Create;
   end;

   TOrange = class(TFruit)
     constructor Create;
   end;

<...>
constructor TApple.Create;
begin
  FId := 1;
end;

constructor TOrange.Create;
begin
  FId := 2;
end;
</code>```

So, your example code will work now. (The descendants can see FId because it's a protected field).
EDIT: changes the visibility from public to published. But the same can be achieved using the $RTTI directive to allow RTTI to public members.

ContentLicense: CC BY-SA 2.5

Body:
Alright, so I have a base class which we'll call TFruit. From this there are various descendants like TApple, TOrange and so on. I need to save the properties of the descendant classes to a file.

In order to be able to create the right class when loading the data, each class needs to have an ID that I write to the file before writing the actual data. Currently, I've come up with the following way of doing it:

type
  TFruit = class
    const ID = 0;
  end;

  TApple = class(TFruit)
    const ID = 1;
  end;

  TOrange = class(TFruit)
    const ID = 2;
  end;

Testing this, I found out that I need to be super careful which class I declare. If I use this:

  var Fruit: TFruit;

  Fruit := TOrange.Create;

...then Fruit.ID will return zero. However, declaring Fruit as a TOrange will yield the expected result Fruit.ID = 2 (anyone know why?)

So basically, am I doing this right or is there a better way to do it? Having to create a class function and return a value from there seems very ugly by comparison (extra function declaration, implementation and code).

Body:
Looking on other angle: why ID is not an read-only object property (instead of a class const)?

So:

 type
   TFruit = class
   protected
     FId: Integer;
   published
     property ID:Integer read FId;
   end;

   TApple = class(TFruit)
     constructor Create;
   end;

   TOrange = class(TFruit)
     constructor Create;
   end;

<...>
constructor TApple.Create;
begin
  FId := 1;
end;

constructor TOrange.Create;
begin
  FId := 2;
end;

So, your example code will work now. (The descendants can see FId because it's a protected field).
EDIT: changes the visibility from public to published. But the same can be achieved using the $RTTI directive to allow RTTI to public members.


问:
Javascript: How can I use the filter() to filter out specific objects with a certain value?
I have an object with accounts, example:

```<code>    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }
</code>```

Let's say I want to filter out only the objects with the states of "FL" and "OH", how could I use the filter() to do that? Thanks.

答:
Try this</p>

```<code>function filterArray (item) {
    if (item.state === "OH" || item.state === "FL"){
        return item;
    }
}

var resultArray = yourArray.filter(filterArray);
console.log(resultArray);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an object with accounts, example:

    {
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }

Let's say I want to filter out only the objects with the states of "FL" and "OH", how could I use the filter() to do that? Thanks.

Body:
Try this

function filterArray (item) {
    if (item.state === "OH" || item.state === "FL"){
        return item;
    }
}

var resultArray = yourArray.filter(filterArray);
console.log(resultArray);


问:
How to truncate text with ellipsis (...) in flex?
In my flex app, I have a <mx:Text> control with a fixed height and width enough to show two lines. Now if the text is too long to be shown in two lines, I would like to have it truncated with showing ellipsis (...). The default truncation with ellipsis seems to be present with label, but label cannot show text in two lines.

How do I mimic this behavior in <mx:Text> control in flex? Thanks in advance!!!

答:
The best solution I've found is via the spark Label and the maxDisplayedLines property, like so:

```<code>        <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:s="library://ns.adobe.com/flex/spark" >
            <s:Label text="{data.Name}" maxDisplayedLines="3" verticalAlign="middle" />
        </mx:Canvas>
</code>```

Worked perfectly for me.
In general I've found the spark Label to be better than the mx Label, but YMMV.

Body:
The best solution I've found is via the spark Label and the maxDisplayedLines property, like so:

        <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:s="library://ns.adobe.com/flex/spark" >
            <s:Label text="{data.Name}" maxDisplayedLines="3" verticalAlign="middle" />
        </mx:Canvas>

Worked perfectly for me.
In general I've found the spark Label to be better than the mx Label, but YMMV.


问:
Read list of artists, Add top songs to playlist using Spotipy
I am wanting to write a python program that reads a list of artists and creates a playlist with the top three songs from each artist.  Is there a way to do this directly from the artist's name or would I have to create a list of artist IDs? If that is the case - I might as well make the playlist manually.

Thanks for your help!

答:
How very timely. I literally just wrote a program that does almost exactly this today.

https://github.com/streadgold/FestivalPlaylistMaker

It reads in a list of artists (one per line) from lineup.txt and converts them to IDs and returns their top 5 tracks. Just change the limit from 5 to 3 and it sounds like it is exactly what you are asking for. Or at least a decent starting point.


问:
How to remove 'Program Name' from Images?
I've tried the solutions from here: removing 'Program Name' in metadata for images but, nothing worked. Is there a way to remove all the 'Photoshop' information from the image and retain the other metadata in it, created by photoshop (eg: name, contact info, copyright info etc.)

EDIT: The 'Program Name' from the properties menu when someone right clicks on an image in windows.

答: I tried all these exiftool software that never worked for me. Assuming you are on Windows (or Windows 10), the solution to the problem was very simple. You can select which property you want to remove. If this worked for you, kindly mark it as the right answer.


问:
Add to Python Syntax Highlighting in Notepad++
I wanted to add syntax highlighting for Python built-ins in Notepad++. I modified langs.xml in AppData/Notepad++ by adding this line to the python tag:

```<code><Keywords name="instre2">len max min sum map str int reduce</Keywords>
</code>```

I also added this line to the python tag in stylers.xml in the same location:

```<code><WordsStyle name="BUILTINS" styleID="13" fgColor="8080FF" bgColor="FFFFFF" fontName="" fontStyle="0" fontSize="" keywordClass="instre2" />
</code>```

When I go to Settings->Style Configurator->Python->BUILTINS, I see my list of built-in functions as well as the colour I assigned to them. However, when editing a Python file, the built-in functions are not highlighted. Why is this?

I found something similar here, but I could not find the file LexPython.cxx. How do I resolve this? Is it possible to resolve?

答:
You are almost there ...
Just set the styleID to 14 for the keyword list you added, only 14 works.
Now you can set the color through the style configurator. See the effect here
built-in function highlighting
The built-in function int() and range() are rendered with custom color.

A little bit explanation:

It's pointed out here that " ... Syntilla lexers use predefined numbers for coloring things (these are the "styleID"s) ..." and they're defined for each language. You can check it in the notepad++ source file SciLexer.h.

There's actually a group WORD2 with id 14 defined for python (SCE_P_WORD2), but it's not used in the default stylers.xml.

Body:
I wanted to add syntax highlighting for Python built-ins in Notepad++. I modified langs.xml in AppData/Notepad++ by adding this line to the python tag:

<Keywords name="instre2">len max min sum map str int reduce</Keywords>

I also added this line to the python tag in stylers.xml in the same location:

<WordsStyle name="BUILTINS" styleID="13" fgColor="8080FF" bgColor="FFFFFF" fontName="" fontStyle="0" fontSize="" keywordClass="instre2" />

When I go to Settings->Style Configurator->Python->BUILTINS, I see my list of built-in functions as well as the colour I assigned to them. However, when editing a Python file, the built-in functions are not highlighted. Why is this?

I found something similar here, but I could not find the file LexPython.cxx. How do I resolve this? Is it possible to resolve?


问:
Array size in Java
What would be the memory size/space occupied in bits/bytes by array as follows.</p>

```<code>final String[] objects_user1={"1","10","100","1000","10000"};
</code>```

答: Impossible to say, since its an implementation detail of the JRE you're using.</p>

Title: Array size in Java

Body:
What would be the memory size/space occupied in bits/bytes by array as follows.

final String[] objects_user1={"1","10","100","1000","10000"};


问:
Clang Tooling Preprocess Source Files
I am using the Clang::Tooling library to parse some header files.  I can't seem to parse properly due to clang not pre-processing header files and other pre-processor stuff.  How can I tell Clang::Tooling to pre-process files before parsing. Cheers.  This is my current code for invoking my tool.</p>

```<code>/*static*/ SAST SAST::Parse( CFile& HeaderFile, const TArray<CString>& CommandLineArgs )
{
    //Our Custom Formated Ast Data Struct
    SAST AST;

    //Parse Command-Line Args.
    clang::tooling::CommandLineArguments CommandArgs;
    for (auto& Item : CommandLineArgs)
        CommandArgs.push_back(Item.GetRaw());

    //Traverse And Collect AST
    auto SourceText = HeaderFile.GetText();
    auto SourceFileName = HeaderFile.GetFullName();
    clang::tooling::runToolOnCodeWithArgs(new CollectASTAction(&AST), SourceText.GetRawConst(), CommandArgs);

    return AST;
}
</code>```

答: Apparently it actually is trying to pre-process the file.  I couldn't see any errors reported due to no console window open.  However, when I inspected the llvm::raw_fd_ostream class's write() method with a break-point, I could see that errors were being written such as "FileXXX.h could not be found".  So it simply couldn't find the #include files.  That's why pre-processing wasn't performed/completed.  Thanks everyone.  This solves my day long journey.

Title: Clang Tooling Preprocess Source Files

Body:
I am using the Clang::Tooling library to parse some header files.  I can't seem to parse properly due to clang not pre-processing header files and other pre-processor stuff.  How can I tell Clang::Tooling to pre-process files before parsing. Cheers.  This is my current code for invoking my tool.

/*static*/ SAST SAST::Parse( CFile& HeaderFile, const TArray<CString>& CommandLineArgs )
{
    //Our Custom Formated Ast Data Struct
    SAST AST;

    //Parse Command-Line Args.
    clang::tooling::CommandLineArguments CommandArgs;
    for (auto& Item : CommandLineArgs)
        CommandArgs.push_back(Item.GetRaw());

    //Traverse And Collect AST
    auto SourceText = HeaderFile.GetText();
    auto SourceFileName = HeaderFile.GetFullName();
    clang::tooling::runToolOnCodeWithArgs(new CollectASTAction(&AST), SourceText.GetRawConst(), CommandArgs);

    return AST;
}


问:
Problems found loading Plugins in Android Studio
After updating Gradle as suggested in this answer the following error appears while using Android Studio 0.2.0

How to get over this one?

答: Go to File->Settings-> Plugins then uncheck then check all the red highlighted plugin then restart the android studio if require </p>


问:
Why we cannot delete function in javascript using delete operator?
```<code>var sum = function(a, b) {return a + b;};

var add = sum;

delete sum;
</code>```

After Executing Delete it return False in console. Ideally it should return True.
Why sum function is not deleted?

Note above code is executed in google chrome browser console.

答:
delete cannot delete with direct member .

The delete operator removes a property from an object.

Since you giving sum and not telling from which object you want to remove it.

What you looking for is

```<code>delete window.sum
</code>```

Now it removes the sum from window object :)

demo

Body:
var sum = function(a, b) {return a + b;};

var add = sum;

delete sum;

After Executing Delete it return False in console. Ideally it should return True.
Why sum function is not deleted?

Note above code is executed in google chrome browser console.

Body:
delete cannot delete with direct member .

The delete operator removes a property from an object.

Since you giving sum and not telling from which object you want to remove it.

What you looking for is

delete window.sum

Now it removes the sum from window object :)

demo


答:
From MDN:

The delete operator removes a given property from an object.

If the property which you are trying to delete does not exist, delete will not have any effect and will return true.

If a property with the same name exists on the object's prototype chain, then, after deletion, the object will use the property from the prototype chain (in other words, delete only has an effect on own properties).

Any property declared with var cannot be deleted from the global scope or from a function's scope.

As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).

Functions which are part of an object (apart from the global scope) can be deleted with delete.

Hence sum which is a function attached to the global scope, cannot be deleted with delete.

Title: Why we cannot delete function in javascript using delete operator?


问:
How to generate coorectlly lmdb files from own dataset using caffe ?
I'm trying to to generate lmdbs to train my CNN using Caffe.

I've used as data set Stanford Dogs Dataset.After downloading the data set , I prepared the training data set et test data set.I have saved the configuration into the files train.txt and val.txt.

Then , I tried to generate the lmdb files by those two following commands on my console :

```<code>GLOG_logtostderr=1 /home/bme/caffe/build/tools/convert_imageset \
    --resize_height=200 --resize_width=200 --shuffle  \
    /home/bme/caffe/data/dogs/data/ \
    /home/bme/caffe/data/dogs/dogs_data/train.txt \
    /home/bme/caffe/examples/dogs/dogs_train_lmdb

GLOG_logtostderr=1 /home/bme/caffe/build/tools/convert_imageset \
    --resize_height=200 --resize_width=200 --shuffle  \
    /home/bme/caffe/data/dogs/data/ \
    /home/bme/caffe/data/dogs/dogs_data/val.txt \
    /home/bme/caffe/examples/dogs/dogs_val_lmdb
</code>```

But , it produced those errors for the first commands :

```<code>I0331 18:13:39.625823  8810 convert_imageset.cpp:86] Shuffling data
I0331 18:13:39.627516  8810 convert_imageset.cpp:89] A total of 17493 images.
I0331 18:13:39.627708  8810 db_lmdb.cpp:35] Opened lmdb /home/bme/caffe/examples/dogs/dogs_train_lmdb
E0331 18:13:39.627734  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/108_n02111889-Samoyed17.jpg 108
E0331 18:13:39.627743  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke145.jpg 12
E0331 18:13:39.627753  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/17_n02113712-miniature_poodle107.jpg 17
E0331 18:13:39.627760  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke63.jpg 12
E0331 18:13:39.627768  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/97_n02105056-groenendael102.jpg 97
E0331 18:13:39.627774  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/74_n02096585-Boston_bull38.jpg 74
E0331 18:13:39.627781  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/4_n02113799-standard_poodle145.jpg 4
E0331 18:13:39.627789  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/22_n02097047-miniature_schnauzer27.jpg 22
E0331 18:13:39.627797  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/80_n02107312-miniature_pinscher167.jpg 80
E0331 18:13:39.627805  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/95_n02091134-whippet42.jpg 95
</code>```

The errors for the second command are:

```<code>I0331 18:13:39.625823  8810 convert_imageset.cpp:86] Shuffling data
I0331 18:13:39.627516  8810 convert_imageset.cpp:89] A total of 17493 images.
I0331 18:13:39.627708  8810 db_lmdb.cpp:35] Opened lmdb /home/bme/caffe/examples/dogs/dogs_train_lmdb
E0331 18:13:39.627734  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/108_n02111889-Samoyed17.jpg 108
E0331 18:13:39.627743  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke145.jpg 12
E0331 18:13:39.627753  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/17_n02113712-miniature_poodle107.jpg 17
E0331 18:13:39.627760  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke63.jpg 12
E0331 18:13:39.627768  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/97_n02105056-groenendael102.jpg 97
E0331 18:13:39.627774  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/74_n02096585-Boston_bull38.jpg 74
E0331 18:13:39.627781  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/4_n02113799-standard_poodle145.jpg 4
E0331 18:13:39.627789  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/22_n02097047-miniature_schnauzer27.jpg 22
E0331 18:13:39.627797  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/80_n02107312-miniature_pinscher167.jpg 80
E0331 18:13:39.627805  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/95_n02091134-whippet42.jpg 95
E0331 18:13:39.627812  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/56_n02101556-clumber86.jpg 56
E0331 18:13:39.627820  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/26_n02085782-Japanese_spaniel36.jpg 26
</code>```

I tried to solve the issue by changing the permissions of the files train.txt and val.txt . But the same errors remained .So , any suggestions to fix this issue.

Thanks

答:
The outputs you posted are both for the training set generation (they are the same). It seems like out of 17,493 images you have 12 corrupted files that caffe cannot find/open.<br>
Check that these files exists, and that they are not corrupted. </p>

Body:
I'm trying to to generate lmdbs to train my CNN using Caffe.

I've used as data set Stanford Dogs Dataset.After downloading the data set , I prepared the training data set et test data set.I have saved the configuration into the files train.txt and val.txt.

Then , I tried to generate the lmdb files by those two following commands on my console :

GLOG_logtostderr=1 /home/bme/caffe/build/tools/convert_imageset \
    --resize_height=200 --resize_width=200 --shuffle  \
    /home/bme/caffe/data/dogs/data/ \
    /home/bme/caffe/data/dogs/dogs_data/train.txt \
    /home/bme/caffe/examples/dogs/dogs_train_lmdb

GLOG_logtostderr=1 /home/bme/caffe/build/tools/convert_imageset \
    --resize_height=200 --resize_width=200 --shuffle  \
    /home/bme/caffe/data/dogs/data/ \
    /home/bme/caffe/data/dogs/dogs_data/val.txt \
    /home/bme/caffe/examples/dogs/dogs_val_lmdb

But , it produced those errors for the first commands :

I0331 18:13:39.625823  8810 convert_imageset.cpp:86] Shuffling data
I0331 18:13:39.627516  8810 convert_imageset.cpp:89] A total of 17493 images.
I0331 18:13:39.627708  8810 db_lmdb.cpp:35] Opened lmdb /home/bme/caffe/examples/dogs/dogs_train_lmdb
E0331 18:13:39.627734  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/108_n02111889-Samoyed17.jpg 108
E0331 18:13:39.627743  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke145.jpg 12
E0331 18:13:39.627753  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/17_n02113712-miniature_poodle107.jpg 17
E0331 18:13:39.627760  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke63.jpg 12
E0331 18:13:39.627768  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/97_n02105056-groenendael102.jpg 97
E0331 18:13:39.627774  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/74_n02096585-Boston_bull38.jpg 74
E0331 18:13:39.627781  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/4_n02113799-standard_poodle145.jpg 4
E0331 18:13:39.627789  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/22_n02097047-miniature_schnauzer27.jpg 22
E0331 18:13:39.627797  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/80_n02107312-miniature_pinscher167.jpg 80
E0331 18:13:39.627805  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/95_n02091134-whippet42.jpg 95

The errors for the second command are:

I0331 18:13:39.625823  8810 convert_imageset.cpp:86] Shuffling data
I0331 18:13:39.627516  8810 convert_imageset.cpp:89] A total of 17493 images.
I0331 18:13:39.627708  8810 db_lmdb.cpp:35] Opened lmdb /home/bme/caffe/examples/dogs/dogs_train_lmdb
E0331 18:13:39.627734  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/108_n02111889-Samoyed17.jpg 108
E0331 18:13:39.627743  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke145.jpg 12
E0331 18:13:39.627753  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/17_n02113712-miniature_poodle107.jpg 17
E0331 18:13:39.627760  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/12_n02104365-schipperke63.jpg 12
E0331 18:13:39.627768  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/97_n02105056-groenendael102.jpg 97
E0331 18:13:39.627774  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/74_n02096585-Boston_bull38.jpg 74
E0331 18:13:39.627781  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/4_n02113799-standard_poodle145.jpg 4
E0331 18:13:39.627789  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/22_n02097047-miniature_schnauzer27.jpg 22
E0331 18:13:39.627797  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/80_n02107312-miniature_pinscher167.jpg 80
E0331 18:13:39.627805  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/95_n02091134-whippet42.jpg 95
E0331 18:13:39.627812  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/56_n02101556-clumber86.jpg 56
E0331 18:13:39.627820  8810 io.cpp:80] Could not open or find file /home/bme/caffe/data/dogs/data/26_n02085782-Japanese_spaniel36.jpg 26

I tried to solve the issue by changing the permissions of the files train.txt and val.txt . But the same errors remained .So , any suggestions to fix this issue.

Thanks

Body:
The outputs you posted are both for the training set generation (they are the same). It seems like out of 17,493 images you have 12 corrupted files that caffe cannot find/open.

Check that these files exists, and that they are not corrupted.


答:
Try this:

var array = [{
      "amount": "822370.71",
      "state": "ME"
    },
    {
      "amount": "968817.53",
      "state": "FL"
    },
    {
      "amount": "587603.26",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "OH"
    },
    {
      "amount": "657617.83",
      "state": "FL"
    }];

    var filterArray = array.filter(function(item){
      return item.state === 'FL' || item.state === 'OH';
    });

    console.log(filterArray);```

Title: Javascript: How can I use the filter() to filter out specific objects with a certain value?


问:
Change ng-click function attribute. In Angular.js
I have a function defined in a directive called old(), currently the button executes this function when clicking. I want when the directive is loaded, the old() function was changed to the new() function. The new function, would receive by parameter (this.form) ("form" is the name of my form).
I've tried this, but it

```<code>attrs.$set('ngClick', 'new(this.form)');
</code>```

but the new() function is not executed. How can I do it?.
I need to do this inside a directive, maybe it can be achieved in a controller, but I need to do it in a directive, and I put this example doubt to apply it in my real project. Thank you very much.

http://jsfiddle.net/mg8g138x/

```<code>    app.directive('validation', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel',

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;
              }

              scope.old= function(){
                alert("old")
              }
             //attrs.$set('ngClick', 'new(this.form)');
              scope.new= function(form){
                alert("new");
                console.log(form)
              }

           }

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

答:
the reason while your new function doesn't work is because by the time the code in your link function run, AngularJS had already finished compiled the template, and link all found directives (ng-click) with the directive scope.

Once you change your ng-click value to a new function, you will need to re-compile the directive in order to make that change effective.

You can have a look at angularjs $compile service to see how it can be used: https://docs.angularjs.org/api/ng/service/$compile.

However, I don't believe it's the best approach to your problem, as Javascript has some functional programming feature, which allow you to pass a function as a parameter, you can merge the old function and new function into a single function, and control which function to be called via a parameters, here is the example:

```<code>link: function (scope, element, attrs, ngModel) {
    if (!ngModel){
      return;
   }

   scope.old = function(){
       alert("old");
   }

   scope.new = function(form){
       alert("new");
      console.log(form)
   }

   scope.current = scope.old; // variable to control with function being called
   scope.form = ''; // variable to contain the parameter for the function called via ng-click

   scope.binding_to_button = function(function_to_call, parameter) {
       function_to_call(parameter);
   }
                 // Do this action may be within a function after an action
                 // or an event $emit/$broadcast rather than directly in code.
   scope.current = scope.new;
   scope.form = form; //
               }
</code>```

And then, instead of binding scope.new or scope.old directly to your ng-click, binding scope.binding_to_button.

```<code>ng-click="binding_to_button(current, form)"
</code>```

This function will take the $scope.current as it first parameter, and the $scope.form as its second, so you can dynamically control which function to be called and what parameters passed to them via the click event.

Body:
I have a function defined in a directive called old(), currently the button executes this function when clicking. I want when the directive is loaded, the old() function was changed to the new() function. The new function, would receive by parameter (this.form) ("form" is the name of my form).
I've tried this, but it

attrs.$set('ngClick', 'new(this.form)');

but the new() function is not executed. How can I do it?.
I need to do this inside a directive, maybe it can be achieved in a controller, but I need to do it in a directive, and I put this example doubt to apply it in my real project. Thank you very much.

http://jsfiddle.net/mg8g138x/

    app.directive('validation', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel',

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;
              }

              scope.old= function(){
                alert("old")
              }
             //attrs.$set('ngClick', 'new(this.form)');
              scope.new= function(form){
                alert("new");
                console.log(form)
              }

           }

        };
    });

Body:
the reason while your new function doesn't work is because by the time the code in your link function run, AngularJS had already finished compiled the template, and link all found directives (ng-click) with the directive scope.

Once you change your ng-click value to a new function, you will need to re-compile the directive in order to make that change effective.

You can have a look at angularjs $compile service to see how it can be used: https://docs.angularjs.org/api/ng/service/$compile.

However, I don't believe it's the best approach to your problem, as Javascript has some functional programming feature, which allow you to pass a function as a parameter, you can merge the old function and new function into a single function, and control which function to be called via a parameters, here is the example:

link: function (scope, element, attrs, ngModel) {
    if (!ngModel){
      return;
   }

   scope.old = function(){
       alert("old");
   }

   scope.new = function(form){
       alert("new");
      console.log(form)
   }

   scope.current = scope.old; // variable to control with function being called
   scope.form = ''; // variable to contain the parameter for the function called via ng-click

   scope.binding_to_button = function(function_to_call, parameter) {
       function_to_call(parameter);
   }
                 // Do this action may be within a function after an action
                 // or an event $emit/$broadcast rather than directly in code.
   scope.current = scope.new;
   scope.form = form; //
               }

And then, instead of binding scope.new or scope.old directly to your ng-click, binding scope.binding_to_button.

ng-click="binding_to_button(current, form)"

This function will take the $scope.current as it first parameter, and the $scope.form as its second, so you can dynamically control which function to be called and what parameters passed to them via the click event.


答:
Refer MDN

The delete operator removes a property from an object.

Any property declared with var cannot be deleted from the global scope or from a function's scope.

As such, delete cannot delete any functions in the global scope (whether this is part from a function definition or a function expression).

Functions which are part of an object (apart from the global scope) can be deleted with delete.


问:
Redis - monitoring memory usage
I am currently testing insertion of keys in a database Redis (on local).
I have more than 5 millions keys and I have just 4GB RAM so at one moment I reach capacity of RAM and swap fill in (and my PC goes down)...

My problematic : How can I make monitoring memory usage on the machine which has the Redis database, and in this way alert no more insert some keys in the Redis database ?

Thanks.

答:
Memory is a critical resource for Redis performance. Used memory defines total number of bytes allocated by Redis using its allocator (either standard libc, jemalloc, or an alternative allocator such as tcmalloc).

You can collect all memory utilization metrics data for a Redis instance by running “info memory”.

```
127.0.0.1:6379> info memory
Memory
used_memory:1007280
used_memory_human:983.67K
used_memory_rss:2002944
used_memory_rss_human:1.91M
used_memory_peak:1008128
used_memory_peak_human:984.50K
```

Sometimes, when Redis is configured with no max memory limit, memory usage will eventually reach system memory, and the server will start throwing “Out of Memory” errors. At other times, Redis is configured with a max memory limit but noeviction policy. This would cause the server not to evict any keys, thus preventing any writes until memory is freed. The solution to such problems would be configuring Redis with max memory and some eviction policy. In this case, the server starts evicting keys using eviction policy as memory usage reaches the max.

Memory RSS (Resident Set Size) is the number of bytes that the operating system has allocated to Redis. If the ratio of ‘memory_rss’ to ‘memory_used’ is greater than ~1.5, then it signifies memory fragmentation. The fragmented memory can be recovered by restarting the server.

Title: Redis - monitoring memory usage

Body:
Memory is a critical resource for Redis performance. Used memory defines total number of bytes allocated by Redis using its allocator (either standard libc, jemalloc, or an alternative allocator such as tcmalloc).

You can collect all memory utilization metrics data for a Redis instance by running “info memory”.

127.0.0.1:6379> info memory
Memory
used_memory:1007280
used_memory_human:983.67K
used_memory_rss:2002944
used_memory_rss_human:1.91M
used_memory_peak:1008128
used_memory_peak_human:984.50K

Sometimes, when Redis is configured with no max memory limit, memory usage will eventually reach system memory, and the server will start throwing “Out of Memory” errors. At other times, Redis is configured with a max memory limit but noeviction policy. This would cause the server not to evict any keys, thus preventing any writes until memory is freed. The solution to such problems would be configuring Redis with max memory and some eviction policy. In this case, the server starts evicting keys using eviction policy as memory usage reaches the max.

Memory RSS (Resident Set Size) is the number of bytes that the operating system has allocated to Redis. If the ratio of ‘memory_rss’ to ‘memory_used’ is greater than ~1.5, then it signifies memory fragmentation. The fragmented memory can be recovered by restarting the server.

ContentLicense: CC BY-SA 4.0


问:
Printing Out Repeated Numbers
so I'm working on a program that takes two strings. For instance [2,3,4] and [1,4,5] and outprints 1,1,4,4,4,5,5,5,5. I don't really have a working code. So, I'm just looking for tips, not a complete code.</p>

答: if you really want to take in strings, I would take two strings and convert each of them into array as you have written e.g.[2,3,4] and [1,4,5] then concatonate them. Then arrange them in order using simple data structure algorithm. So for example, go through each item in the array and move it to the 0 position if it is the smallest number. Then go to the next position and also try to move the lowest number in the array except the first position to the second position, etc.</p>

Title: Printing Out Repeated Numbers


问:
removing 'Program Name' in metadata for images
In Windows file properties, it's called 'Program Name' under Origin.
In Adobe Bridge, it's called 'Application' under File Properties.

I believe it adds the name of the program used to create the file. It cannot be edited/removed in Bridge or Windows.

I really don't understand how it gets added because certain images taken from a camera and edited in Lightroom does not add the attribute, and other times it does. One file was edited in Photoshop and tagged Photoshop, but when imported into Lightroom and exported, the attribute said Windows Photo Viewer instead.

Bottom line, I want the attribute deleted. Can't seem to find a reference to that attribute or how to remove it online.

答:
Referring my answer here.
I tried all these exiftool software that never worked for me. Assuming you are on Windows (or Windows 10), the solution to the problem was very simple. You can select which property you want to remove. If this worked for you, kindly mark it as the right answer.


问:
i try to read integer values form txt file using eclipes but its give me some error java.lang.NumberFormatException
my code is based on gui, i try run on gui but i didnt make it.
public class SecondFrame extends JFrame {

```<code>private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SecondFrame frame = new SecondFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public SecondFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 612, 469);
    contentPane = new JPanel();
    contentPane.setBackground(Color.BLUE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblNewLabel = new JLabel("Success !");
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 38));
    lblNewLabel.setBounds(201, 120, 233, 74);
    contentPane.add(lblNewLabel);

    JButton btnGenerateGraph = new JButton("GENERATE GRAPH");
    btnGenerateGraph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                FileReader reader = new FileReader("rn.txt");
                BufferedReader bufferedReader = new BufferedReader(reader);

                String line;
                **here i try to convert line that i has read to integer**
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(Integer.parseInt(line));
                }
                reader.close();

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

        }
    });
    btnGenerateGraph.setFont(new Font("Tahoma", Font.BOLD, 21));
    btnGenerateGraph.setBounds(168, 221, 245, 59);
    contentPane.add(btnGenerateGraph);
}
</code>```

}

this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"

my rn.txt file:

29
44
15
17

答: Nothing wrong with the code. i'm using eclipse to create txt file. but it does not provide me with the extension of .txt. so i do it manually. copy paste to the folder and its work.</p>

Body:
my code is based on gui, i try run on gui but i didnt make it.
public class SecondFrame extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                SecondFrame frame = new SecondFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public SecondFrame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 612, 469);
    contentPane = new JPanel();
    contentPane.setBackground(Color.BLUE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblNewLabel = new JLabel("Success !");
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 38));
    lblNewLabel.setBounds(201, 120, 233, 74);
    contentPane.add(lblNewLabel);

    JButton btnGenerateGraph = new JButton("GENERATE GRAPH");
    btnGenerateGraph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                FileReader reader = new FileReader("rn.txt");
                BufferedReader bufferedReader = new BufferedReader(reader);

                String line;
                **here i try to convert line that i has read to integer**
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(Integer.parseInt(line));
                }
                reader.close();

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

        }
    });
    btnGenerateGraph.setFont(new Font("Tahoma", Font.BOLD, 21));
    btnGenerateGraph.setBounds(168, 221, 245, 59);
    contentPane.add(btnGenerateGraph);
}

}

this is the error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "/"

my rn.txt file:

29
44
15
17


问:
MySql Connector/J 5.1.41 not connecting
I'm using MySQL Connector/J 5.1.41 to connect to a DB, here's the code I'm using to connect:

```<code>package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class ConexionMYSQL {
    public String db="floreria";
    public String url= "jdbc:mysql:/localhost"+db;
    public String user= "root";//aqui va el usuario del phpmyadmin
    public String pwd="";

public Connection conectar(){
    Connection link = null;
    try {
        Class.forName("org.gjt.mm.mysql.Driver");
        link = DriverManager.getConnection(this.url, this.user, this.pwd);
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "ERROR: "+e);
    }
    return link;
  }
}
</code>```

I'm a newbie in Java and mysql connections, when I execute the code, It shows me the following exception:

ERROR:java.lang.ClassNotFoundException:org.gjt.mm.mysql.Driver

I've already checked that the jar file is in the classpath, I've reinstalled and replaced the jar file for MySql connector too, but stays the same. As I said, I'm new in this world, I barely know about JavaFX and mysql connections, so thats all info I think I can provide, here's an image from my classpath, maybe there's the problem:

答:
First of all you need to change url like this

```<code>public String url= "jdbc:mysql://localhost/"+db;
</code>```

put a file with MySQL driver to your classpath in NetBeans, so the IDE know the driver class you want to load.

The other thing is a strange driver name org.gjt.mm.mysql.Driver, usually it is com.mysql.jdbc.Driver. Please try using the com.mysql.jdbc.Driver driver name and put a mysql-connector jar into your classpath. You can find the driver in MySQL JDBC Connector JAR, which you can download here:

http://dev.mysql.com/downloads/connector/j/

Right click on Libraries > Click on Add Library.

Scroll down to find MySQL JDBC driver.

Press Shift + F11. (Clean and Build)

Run

Title: MySql Connector/J 5.1.41 not connecting

Body:
I'm using MySQL Connector/J 5.1.41 to connect to a DB, here's the code I'm using to connect:

package DB;

import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

public class ConexionMYSQL {
    public String db="floreria";
    public String url= "jdbc:mysql:/localhost"+db;
    public String user= "root";//aqui va el usuario del phpmyadmin
    public String pwd="";

public Connection conectar(){
    Connection link = null;
    try {
        Class.forName("org.gjt.mm.mysql.Driver");
        link = DriverManager.getConnection(this.url, this.user, this.pwd);
    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, "ERROR: "+e);
    }
    return link;
  }
}

I'm a newbie in Java and mysql connections, when I execute the code, It shows me the following exception:

ERROR:java.lang.ClassNotFoundException:org.gjt.mm.mysql.Driver

I've already checked that the jar file is in the classpath, I've reinstalled and replaced the jar file for MySql connector too, but stays the same. As I said, I'm new in this world, I barely know about JavaFX and mysql connections, so thats all info I think I can provide, here's an image from my classpath, maybe there's the problem:

Body:
First of all you need to change url like this

public String url= "jdbc:mysql://localhost/"+db;

put a file with MySQL driver to your classpath in NetBeans, so the IDE know the driver class you want to load.

The other thing is a strange driver name org.gjt.mm.mysql.Driver, usually it is com.mysql.jdbc.Driver. Please try using the com.mysql.jdbc.Driver driver name and put a mysql-connector jar into your classpath. You can find the driver in MySQL JDBC Connector JAR, which you can download here:

http://dev.mysql.com/downloads/connector/j/

Right click on Libraries > Click on Add Library.

Scroll down to find MySQL JDBC driver.

Press Shift + F11. (Clean and Build)

Run


问:
Declare a function in Swift that returns a closure with a generic T.Type
we are trying to make a function in Swift , that returns a closure. The return type is as follows:

```<code>func completionBlock() -> (Response<T, NSError>) -> ()
</code>```

where Response itself is a struct with 2 generics. The second will be always NSError, but the first depends on a switch.

Declaration of Response:

```<code>public struct Response<Value, Error: ErrorType> { ...
</code>```

What we want to achieve is a function that will return a closure with a type that depends on a value of variable.
Depending on this value, and with a switch, it specifies one type or another, the only requirement for the generic parameter is that it must conform to a specific protocol, but we can't find a solution.

What we got so far is:

```<code>class BaseClass {
    var endpoint: Int
    ...

    func completionBlock() -> (Response<T, NSError>) -> () {

        switch endpoint
        {
        case 1:
            return getHandleResponseClosure(Car.self)
        case 2:
            return getHandleResponseClosure(Truck.self)
        }
    }

    func getHandleResponseClosure<T: Mappable>(_: T.Type) -> (Response<T, NSError>) -> () {

        let closure = { (_: Response<T, NSError>) -> () in
            // ...
        }
        return closure
    }

}
</code>```

But this don't compile: "Use of undeclared Type T" at func completionBlock(), the type at this point is generic, it only requires to conform to protocol Mappable, but we don't know how to specify this.

Thanks!!, Greetings

答:
While there are other problems with your code, the fundamental one is that generic types in method signatures must be declared directly after the name of the method. Take a look at completionBlock below. This code compiles and works.

```<code>struct Response<T, E: Error> {

}

struct Car {}
struct Truck {}

class BaseClass {

    func completionBlock<T>() -> ((Response<T, NSError>) -> ()) {
        return { response in /* What goes here? */ }
    }

}

let c = BaseClass()
let r: (Response<Car, NSError>) -> () = c.completionBlock()
</code>```

On a side note, I would replace struct Response<T, E: Error> with…

```<code>enum Response<T> {
case success(T)
case error(Error)
}
</code>```

Body:
we are trying to make a function in Swift , that returns a closure. The return type is as follows:

func completionBlock() -> (Response<T, NSError>) -> ()

where Response itself is a struct with 2 generics. The second will be always NSError, but the first depends on a switch.

Declaration of Response:

public struct Response<Value, Error: ErrorType> { ...

What we want to achieve is a function that will return a closure with a type that depends on a value of variable.
Depending on this value, and with a switch, it specifies one type or another, the only requirement for the generic parameter is that it must conform to a specific protocol, but we can't find a solution.

What we got so far is:

class BaseClass {
    var endpoint: Int
    ...

    func completionBlock() -> (Response<T, NSError>) -> () {

        switch endpoint
        {
        case 1:
            return getHandleResponseClosure(Car.self)
        case 2:
            return getHandleResponseClosure(Truck.self)
        }
    }

    func getHandleResponseClosure<T: Mappable>(_: T.Type) -> (Response<T, NSError>) -> () {

        let closure = { (_: Response<T, NSError>) -> () in
            // ...
        }
        return closure
    }

}

But this don't compile: "Use of undeclared Type T" at func completionBlock(), the type at this point is generic, it only requires to conform to protocol Mappable, but we don't know how to specify this.

Thanks!!, Greetings

Body:
While there are other problems with your code, the fundamental one is that generic types in method signatures must be declared directly after the name of the method. Take a look at completionBlock below. This code compiles and works.

struct Response<T, E: Error> {

}

struct Car {}
struct Truck {}

class BaseClass {

    func completionBlock<T>() -> ((Response<T, NSError>) -> ()) {
        return { response in /* What goes here? */ }
    }

}

let c = BaseClass()
let r: (Response<Car, NSError>) -> () = c.completionBlock()

On a side note, I would replace struct Response<T, E: Error> with…

enum Response<T> {
case success(T)
case error(Error)
}


问:
Custom Authorization Header
I know there is enough content for this question on the Stack Overflow but my subject is not the same as the others. ( Kinda the same but not equal )

I want to hear the community thoughts of what I doing and to see if I can improve somewhere or not.

I'm currently using BASIC Authorization for my login EndPoint as it doesn't require complexity and its over https so its fine the way it is.

Example:

GET - /api/login

Authorization : Basic BASE64String(username:password)

Some of my EndPoints require Tokens to be granted access to the resource. These Tokens I'm sending trough Headers and Https-Secured.

The thing is I'm not using a conventional method of doing these Authorizations. Some examples below:

Example 1:

GET - /api/hardware/{PUBLIC_TOKEN}/getMe

Authorization-Hardware : PRIVATE_TOKEN

This EndPoint doesn't require the Authorization-Hardware Header, but if included more things are done by the API. ( Not relevant here )

Example 2:

GET - /api/login/{id}

Authorization-Person : USER_TOKEN

This EndPoint otherwise is necessary including the Authorization-Person Header with the User Token to access the resource. ( Note that how the Token is generated is irrelevant here )

To access the API EndPoints an HTTPS request is necessary.

I gave arbitrary names to the Custom Headers and EndPoints above just to give a picture of what my Authorization Schema is, the names doesn't match the original ones. So don't bother the names just foccus on the schema.

My question is: Not following the convetional way is such a bad thing ? Creating Custom Authorization Headers is bad somehow ( if it is why ? ).

I find this way simpler to give Authorization and a secure way of passing tokens, all these Tokens can be re-generated in the platform again.

Lots of devices and a Mobile Application is already using this Schema, but its all under Development Environment and its not in Production yet. My fear is that this non-conventional way of doing this can affect users of the API in the future. Hope the community thoughts can help me to improve this.

EDIT: 26/03/2017

I would like to know if it would be better and why implementing in the way that is described in the protocol, as its harder to fetch from the Headers when multiple Authorizations is required than when you have a Custom Header and wants to retrieve its value.

Following the Protocol you should use Authorization Header like this:

```<code>Authorization: <type> <value>
</code>```

Example:

GET - /api/login/{id}

Authorization : User USER_TOKEN

But I just can't see what I gain following this, because when fetching its value would come a String   or in the example case it would return User Token.

Using an Custom Header its way easier validating the Token. Multiple Authorizations can give a headache too following the protocol way.

答:
TL;DR Some header names such as Authorization have special rules about caching as well as proxy & client handling; your custom header names would not get the special behavior unless you modified every single proxy & client.

The point of using the common Authorization: <type> <value> header as defined in RFC7234 is mostly to ensure that clients & HTTP proxies that natively implement handling of those headers behave CORRECTLY.

Section 4.2 of RFC7234 says:

A proxy forwarding a request MUST NOT modify any Authorization fields
in that request.  See Section 3.2 of [RFC7234] for details of and
requirements pertaining to handling of the Authorization field by
HTTP caches.

The Proxy may modify, omit, log or cache your other Authorization-* headers.

RFC7234, section 3.2 says that requests/responses Authorization header MUST not be cached (except in specific circumstances).

RFC7235, section 5.1.2, point 7 furthermore has this say to about NEW authentication schemes that use headers other than Authorization:

Therefore, new authentication schemes that choose not to carry credentials in the Authorization header field (e.g., using a newly       defined header field) will need to explicitly disallow caching, by       mandating the use of either Cache-Control request directives       (e.g., "no-store", Section 5.2.1.5 of [RFC7234]) or response       directives (e.g., "private").

So what should you do...? If you controller both ends of the system entirely, it's not unreasonable to define a new type value that might have multiple parameters to cover any combination of one or more token types, just avoiding the , character:

```<code>Authorization: MyAuth User=USER_TOKEN/Hardware=HWTOKEN/Person=PERSONTOKEN/Basic=...
</code>```

The alternative depends on server & client implementations more, and would be using a , as the alternate version list form of multiple headers:

```<code>Authorization: User USER_TOKEN, Hardware=HWTOKEN, Person=PERSONTOKEN, Basic=...
</code>```

Which depending on the server & client, may be treated the same as:

```<code>Authorization: User USER_TOKEN
Authorization: Hardware HWTOKEN
Authorization: Person PERSONTOKEN
Authorization: Basic ...
</code>```

The problem here is "MAY" (lots of added emphasis) be treated the same. There's discussions suggestion that various versions of Apache & NGINX don't treat this consistently, and that the older HTTP RFCs are very unclear about the intended behavior.

Title: Custom Authorization Header

Body:
I know there is enough content for this question on the Stack Overflow but my subject is not the same as the others. ( Kinda the same but not equal )

I want to hear the community thoughts of what I doing and to see if I can improve somewhere or not.

I'm currently using BASIC Authorization for my login EndPoint as it doesn't require complexity and its over https so its fine the way it is.

Example:

GET - /api/login

Authorization : Basic BASE64String(username:password)

Some of my EndPoints require Tokens to be granted access to the resource. These Tokens I'm sending trough Headers and Https-Secured.

The thing is I'm not using a conventional method of doing these Authorizations. Some examples below:

Example 1:

GET - /api/hardware/{PUBLIC_TOKEN}/getMe

Authorization-Hardware : PRIVATE_TOKEN

This EndPoint doesn't require the Authorization-Hardware Header, but if included more things are done by the API. ( Not relevant here )

Example 2:

GET - /api/login/{id}

Authorization-Person : USER_TOKEN

This EndPoint otherwise is necessary including the Authorization-Person Header with the User Token to access the resource. ( Note that how the Token is generated is irrelevant here )

To access the API EndPoints an HTTPS request is necessary.

I gave arbitrary names to the Custom Headers and EndPoints above just to give a picture of what my Authorization Schema is, the names doesn't match the original ones. So don't bother the names just foccus on the schema.

My question is: Not following the convetional way is such a bad thing ? Creating Custom Authorization Headers is bad somehow ( if it is why ? ).

I find this way simpler to give Authorization and a secure way of passing tokens, all these Tokens can be re-generated in the platform again.

Lots of devices and a Mobile Application is already using this Schema, but its all under Development Environment and its not in Production yet. My fear is that this non-conventional way of doing this can affect users of the API in the future. Hope the community thoughts can help me to improve this.

EDIT: 26/03/2017

I would like to know if it would be better and why implementing in the way that is described in the protocol, as its harder to fetch from the Headers when multiple Authorizations is required than when you have a Custom Header and wants to retrieve its value.

Following the Protocol you should use Authorization Header like this:

Authorization: <type> <value>

Example:

GET - /api/login/{id}

Authorization : User USER_TOKEN

But I just can't see what I gain following this, because when fetching its value would come a String   or in the example case it would return User Token.

Using an Custom Header its way easier validating the Token. Multiple Authorizations can give a headache too following the protocol way.

Body:
TL;DR Some header names such as Authorization have special rules about caching as well as proxy & client handling; your custom header names would not get the special behavior unless you modified every single proxy & client.

The point of using the common Authorization: <type> <value> header as defined in RFC7234 is mostly to ensure that clients & HTTP proxies that natively implement handling of those headers behave CORRECTLY.

Section 4.2 of RFC7234 says:

A proxy forwarding a request MUST NOT modify any Authorization fields
in that request.  See Section 3.2 of [RFC7234] for details of and
requirements pertaining to handling of the Authorization field by
HTTP caches.

The Proxy may modify, omit, log or cache your other Authorization-* headers.

RFC7234, section 3.2 says that requests/responses Authorization header MUST not be cached (except in specific circumstances).

RFC7235, section 5.1.2, point 7 furthermore has this say to about NEW authentication schemes that use headers other than Authorization:

Therefore, new authentication schemes that choose not to carry credentials in the Authorization header field (e.g., using a newly       defined header field) will need to explicitly disallow caching, by       mandating the use of either Cache-Control request directives       (e.g., "no-store", Section 5.2.1.5 of [RFC7234]) or response       directives (e.g., "private").

So what should you do...? If you controller both ends of the system entirely, it's not unreasonable to define a new type value that might have multiple parameters to cover any combination of one or more token types, just avoiding the , character:

Authorization: MyAuth User=USER_TOKEN/Hardware=HWTOKEN/Person=PERSONTOKEN/Basic=...

The alternative depends on server & client implementations more, and would be using a , as the alternate version list form of multiple headers:

Authorization: User USER_TOKEN, Hardware=HWTOKEN, Person=PERSONTOKEN, Basic=...

Which depending on the server & client, may be treated the same as:

Authorization: User USER_TOKEN
Authorization: Hardware HWTOKEN
Authorization: Person PERSONTOKEN
Authorization: Basic ...

The problem here is "MAY" (lots of added emphasis) be treated the same. There's discussions suggestion that various versions of Apache & NGINX don't treat this consistently, and that the older HTTP RFCs are very unclear about the intended behavior.


问:
Java Class and Interface Name Collision
```<code>interface A {
  void print();
}

class A implements A {
  public void print() {
    System.out.println("Hello");
  }
  public static void main(String args[]) {
    A a=new A();
    a.print();
  }
}
</code>```

When i am using this code then it is saying "duplicate class:A". Why so? Can I not have same class and interface name

答:
You can't have a class and an interface with the same name because the Java language doesn't allow it.

First of all, it's ambiguous.  If you declare a variable like this:

```<code>A a;
</code>```

What is the type of that variable?  Is it the class, or the interface?

Second, compiled Java code is stored in .class files named after the class or interface defined in the file.  An interface named A and a class named A would both compile to a file named A.class.  You can't have two files with the same name in the same folder.

The error message says "duplicate class" because Java internally treats an interface as a special kind of class.

Title: Java Class and Interface Name Collision

Body:
interface A {
  void print();
}

class A implements A {
  public void print() {
    System.out.println("Hello");
  }
  public static void main(String args[]) {
    A a=new A();
    a.print();
  }
}

When i am using this code then it is saying "duplicate class:A". Why so? Can I not have same class and interface name

Body:
You can't have a class and an interface with the same name because the Java language doesn't allow it.

First of all, it's ambiguous.  If you declare a variable like this:

A a;

What is the type of that variable?  Is it the class, or the interface?

Second, compiled Java code is stored in .class files named after the class or interface defined in the file.  An interface named A and a class named A would both compile to a file named A.class.  You can't have two files with the same name in the same folder.

The error message says "duplicate class" because Java internally treats an interface as a special kind of class.


问:
Loading custom JavaScript files in the Wordpress widgets admin panel
I'm writing a new Wordpress plugin that includes a widget. The widget configuration options require jQuery code to fetch them from a 3rd party server via JSONP, and attach events so that if one dropdown changes, say category, it dynamically changes the content of another dropdown, say subcategory.

To achieve this effect, I need to load some custom JavaScript files in the widget admin panel (the options that show after the user has dragged and dropped the widget to the relevant sidebar in the admin panel).

What is the correct way of doing so? I've tried the following code in my plugin class, but it doesn't seem to load the files:

```<code>class MyPlugin {

    function __construct() {
        add_action('admin_init', array(&$this, 'admin_init'));
        add_action('admin_head', array(&$this, 'admin_load_scripts'));
    }

    function admin_init() {
        wp_register_script('jsonp', 'js/jquery.jsonp-2.1.2.min.js', array('jquery'));
        wp_register_script('my_utils', 'js/my-utils.js', array('jquery', 'jsonp'));
    }

    function admin_load_scripts() {
        wp_enqueue_script('jsonp');
        wp_enqueue_script('my_utils');
    }

}
</code>```

Thanks in advance!

答:
It's probably because the hook admin_head is too late to queue - try using load-widgets.php instead (this will also mean your scripts don't appear on every admin page!).

And as a side note, you don't need to register, then enqueue - you can do both in one call;

```<code>wp_enqueue_script('jsonp', 'js/jquery.jsonp-2.1.2.min.js', array('jquery'));
wp_enqueue_script('my_utils', 'js/my-utils.js', array('jquery', 'jsonp'));
</code>```

Body:
I'm writing a new Wordpress plugin that includes a widget. The widget configuration options require jQuery code to fetch them from a 3rd party server via JSONP, and attach events so that if one dropdown changes, say category, it dynamically changes the content of another dropdown, say subcategory.

To achieve this effect, I need to load some custom JavaScript files in the widget admin panel (the options that show after the user has dragged and dropped the widget to the relevant sidebar in the admin panel).

What is the correct way of doing so? I've tried the following code in my plugin class, but it doesn't seem to load the files:

class MyPlugin {

    function __construct() {
        add_action('admin_init', array(&$this, 'admin_init'));
        add_action('admin_head', array(&$this, 'admin_load_scripts'));
    }

    function admin_init() {
        wp_register_script('jsonp', 'js/jquery.jsonp-2.1.2.min.js', array('jquery'));
        wp_register_script('my_utils', 'js/my-utils.js', array('jquery', 'jsonp'));
    }

    function admin_load_scripts() {
        wp_enqueue_script('jsonp');
        wp_enqueue_script('my_utils');
    }

}

Thanks in advance!

Body:
It's probably because the hook admin_head is too late to queue - try using load-widgets.php instead (this will also mean your scripts don't appear on every admin page!).

And as a side note, you don't need to register, then enqueue - you can do both in one call;

wp_enqueue_script('jsonp', 'js/jquery.jsonp-2.1.2.min.js', array('jquery'));
wp_enqueue_script('my_utils', 'js/my-utils.js', array('jquery', 'jsonp'));


问:
Toggle visibility property of div
I have an HTML 5 video in a div. I then have a custom play button - that works fine.

And I have the video's visibility set to hidden on load and visible when the play button is clicked, how do I return it to hidden when the play button is clicked again?

function showVid() {
  document.getElementById('video-over').style.visibility = 'visible';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#video-over {
  visibility: hidden;
  background-color: rgba(0, 0, 0, .7)
}</code>```

  <video class="home-banner" id="video" controls="">
    <source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />
    <source src="http://video-js.zencoder.com/oceans-clip.webm" type='video/webm' />
    <source src="http://video-js.zencoder.com/oceans-clip.ogv" type='video/ogg' />
    </video>

<button type="button" id="play-pause" onclick="showVid();">

      </button>```

I'm basically just trying to toggle it between the two states of visible and hidden except I can't use toggle because that show's and hides the div. I need it there, just hidden, so it maintains the correct height.

答:
There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

```<code>function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}
</code>```

Title: Toggle visibility property of div

Body:
I have an HTML 5 video in a div. I then have a custom play button - that works fine.

And I have the video's visibility set to hidden on load and visible when the play button is clicked, how do I return it to hidden when the play button is clicked again?

function showVid() {
  document.getElementById('video-over').style.visibility = 'visible';
}

#video-over {
  visibility: hidden;
  background-color: rgba(0, 0, 0, .7)
}

  <video class="home-banner" id="video" controls="">
    <source src="http://video-js.zencoder.com/oceans-clip.mp4" type='video/mp4' />
    <source src="http://video-js.zencoder.com/oceans-clip.webm" type='video/webm' />
    <source src="http://video-js.zencoder.com/oceans-clip.ogv" type='video/ogg' />
    </video>

<button type="button" id="play-pause" onclick="showVid();">

      </button>

I'm basically just trying to toggle it between the two states of visible and hidden except I can't use toggle because that show's and hides the div. I need it there, just hidden, so it maintains the correct height.

Body:
There is another way of doing this with just JavaScript. All you have to do is toggle the visibility based on the current state of the DIV's visibility in CSS.

Example:

function toggleVideo() {
     var e = document.getElementById('video-over');

     if(e.style.visibility == 'visible') {
          e.style.visibility = 'hidden';
     } else if(e.style.visibility == 'hidden') {
          e.style.visibility = 'visible';
     }
}


问:
Error: Action may not be undefined in async action testing in Redux app with nock and mock-store
bit stumped with this one. Following the Redux docs to setup tests for my async actions (docs here), I am getting the error:

Actions may not be an undefined. (at dispatch (node_modules/redux-mock-store/lib/index.js:35:19))

Testing this action:

```<code>export const FETCH_TRANSACTIONS = 'FETCH_TRANSACTIONS'

function fetchTransactionsSuccess (transactions) {
  return {
    type: FETCH_TRANSACTIONS,
    payload: transactions
  }
}

export const fetchTransactions = () => dispatch => axios.get('/api/transactions')
  .then(transactions => dispatch(fetchTransactionsSuccess(transactions)))
  .catch(err => dispatch(handleErr(err)))
</code>```

And this is the test itself. Any help would be amazing. Been staring at this so long my eyes hurt.

```<code>import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../client/actions/actionCreators'
import nock from 'nock'
import expect from 'expect'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('dispatches FETCH_TRANSACTIONS when data is returned', () => {
    nock('http://localhost:3000/')
      .get('/api/transactions')
      .reply(200, [
        {
          "_id": "588900efdf9d3e0905a2d604",
          "amount": 4.50,
          "name": "Cashew Nuts",
          "__v": 0,
          "date": "2017-01-25T00:00:00.000Z",
          "user": "58c2a33cc6cd5a5d15a8fc0c"
        },
        {
          "_id": "58890108df9d3e0905a2d605",
          "amount": 6.25,
          "name": "Monmouth Coffee",
          "__v": 0,
          "date": "2017-01-25T00:00:00.000Z",
          "user": "58c2a33cc6cd5a5d15a8fc0c"
        }
      ])

    const expectedActions = [
      {
        type: actions.FETCH_TRANSACTIONS,
        payload: [
          {
            "_id": "588900efdf9d3e0905a2d604",
            "amount": 4.50,
            "name": "Cashew Nuts",
            "__v": 0,
            "date": "2017-01-25T00:00:00.000Z",
            "user": "58c2a33cc6cd5a5d15a8fc0c"
          },
          {
            "_id": "58890108df9d3e0905a2d605",
            "amount": 6.25,
            "name": "Monmouth Coffee",
            "__v": 0,
            "date": "2017-01-25T00:00:00.000Z",
            "user": "58c2a33cc6cd5a5d15a8fc0c"
          }
        ]
      }
    ]

    const store = mockStore({ transactions: [] })
    console.log(actions)
    return store.dispatch(actions.fetchTransactions())
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})
</code>```

UPDATE
The handleErr function returns setCurrentUser  which is another action (which the original action called with dispatch:

```<code>export function handleErr (err) {
  if (err.status === 401 || err.status === 404) {
    localStorage.removeItem('mm-jwtToken')
    setAuthToken(false)
    return setCurrentUser({})
  }
}
</code>```

答: There is known issue with mocking axios request with nock. So I believe that promise chain in your fetchTransactions action creator falls to the catch clause. Please check your handleErr function, is it returning valid Action? I bet it returns undefined and that is why you have this error message.

Body:
bit stumped with this one. Following the Redux docs to setup tests for my async actions (docs here), I am getting the error:

Actions may not be an undefined. (at dispatch (node_modules/redux-mock-store/lib/index.js:35:19))

Testing this action:

export const FETCH_TRANSACTIONS = 'FETCH_TRANSACTIONS'

function fetchTransactionsSuccess (transactions) {
  return {
    type: FETCH_TRANSACTIONS,
    payload: transactions
  }
}

export const fetchTransactions = () => dispatch => axios.get('/api/transactions')
  .then(transactions => dispatch(fetchTransactionsSuccess(transactions)))
  .catch(err => dispatch(handleErr(err)))

And this is the test itself. Any help would be amazing. Been staring at this so long my eyes hurt.

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../client/actions/actionCreators'
import nock from 'nock'
import expect from 'expect'

const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('dispatches FETCH_TRANSACTIONS when data is returned', () => {
    nock('http://localhost:3000/')
      .get('/api/transactions')
      .reply(200, [
        {
          "_id": "588900efdf9d3e0905a2d604",
          "amount": 4.50,
          "name": "Cashew Nuts",
          "__v": 0,
          "date": "2017-01-25T00:00:00.000Z",
          "user": "58c2a33cc6cd5a5d15a8fc0c"
        },
        {
          "_id": "58890108df9d3e0905a2d605",
          "amount": 6.25,
          "name": "Monmouth Coffee",
          "__v": 0,
          "date": "2017-01-25T00:00:00.000Z",
          "user": "58c2a33cc6cd5a5d15a8fc0c"
        }
      ])

    const expectedActions = [
      {
        type: actions.FETCH_TRANSACTIONS,
        payload: [
          {
            "_id": "588900efdf9d3e0905a2d604",
            "amount": 4.50,
            "name": "Cashew Nuts",
            "__v": 0,
            "date": "2017-01-25T00:00:00.000Z",
            "user": "58c2a33cc6cd5a5d15a8fc0c"
          },
          {
            "_id": "58890108df9d3e0905a2d605",
            "amount": 6.25,
            "name": "Monmouth Coffee",
            "__v": 0,
            "date": "2017-01-25T00:00:00.000Z",
            "user": "58c2a33cc6cd5a5d15a8fc0c"
          }
        ]
      }
    ]

    const store = mockStore({ transactions: [] })
    console.log(actions)
    return store.dispatch(actions.fetchTransactions())
      .then(() => {
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})

UPDATE
The handleErr function returns setCurrentUser  which is another action (which the original action called with dispatch:

export function handleErr (err) {
  if (err.status === 401 || err.status === 404) {
    localStorage.removeItem('mm-jwtToken')
    setAuthToken(false)
    return setCurrentUser({})
  }
}


问:
How to add New line to a div contenteditable in javascript?
Basically I'm using a div with contenteditable as a text box. Now when I input a newline (By pressing enter) it doesn't counts it and escaps it.

Jsfiddle: https://jsfiddle.net/pgsp7q57/3/

You can input:

```<code>Hello
How are you
</code>```

And see the result by yourself which is(hellohow are you) But I need to get the result as:

```<code>Hello
How are you
</code>```

All replies are much appreciated.

答:
Try this code.</p>

```<code>var hello = "hello<br>how\nare\nyou";
document.getElementById("hey").innerHTML = hello;
</code>```

Body:
Basically I'm using a div with contenteditable as a text box. Now when I input a newline (By pressing enter) it doesn't counts it and escaps it.

Jsfiddle: https://jsfiddle.net/pgsp7q57/3/

You can input:

Hello
How are you

And see the result by yourself which is(hellohow are you) But I need to get the result as:

Hello
How are you

All replies are much appreciated.

Body:
Try this code.

var hello = "hello<br>how\nare\nyou";
document.getElementById("hey").innerHTML = hello;


问:
Is there an XML XQuery interface to existing XML files?
My company is in education industry and we use XML to store course content. We also store some course related information (mostly metainfo) in relational database. Right now we are in the process of switching from our proprietary XML Schema to DocBook 5. Along with the switch we want to move course related information from database to XML files. The reason for this is to have all course data in one place and to put it under Subversion. However, we would like to keep flexibility of the relational database and be able to easily extract specific information about a course from an XML document. XQuery seems to be up to the task so I was researching databases that supports it but so far could not find what I needed. What I basically want, is to have my XML files in a certain directory structure and then on top of this I would like to have a system that would index my files and let me select anything out of any file using XQuery. This way I can have "my cake and eat it too": I will have XQuery interface and still keep my files in plain text and versioned. Is there anything out there at least remotely resembling to what I want?

If you think that what I an asking for is nonsense please make an alternative suggestion.

On the related note: What XML Databases (preferably native and open source) do you have experience with and what would you recommend?

答: MarkLogic has released v4.2 with XSLT, which is very handy for XML transformation. The good part is in this version you can mix XQuery and XSLT code to get best of both worlds.</p>


问:
Hit enter to continue or skip function
I'm currently trying to write a program, and I've hit a bit of a bump. I was able to find how to do "hit enter to continue" easy, but now the function (void) that I have it in I also want to be able to skip right about where the first hit enter to continue pops up. Basically, I want to give the user the opportunity to either hit enter to continue with the rest of the function, or hit a button to skip the rest of the function. Here's an idea of what my code looks like currently:

```<code>void intro()
{
    int skip; // Not sure if I need this, was going to experiment

    cout << "Stuff being said " << endl;
    cout << "More stuff being said " << endl;
    cout << "Press 'enter' to continue...";
    cin.ignore(); // This is where I want the input to continue or skip.
</code>```

So basically, I want to keep the hit enter to continue while also giving the user the opportunity to skip the function. Is this possible, or do I have to do something else entirely?

答:
Here is a possible solution to your problem:  use _getch().  It is a function inside of conio.h that pauses and waits for the user to press a key, then returns an int representing that character.  Here is an example of how you could use it in your code:

```<code>#include <conio.h> // put this somewhere up at the top of the file
void intro()
{
    cout << "Stuff being said " << endl;
    cout << "More stuff being said " << endl;
    cout << "Press 'enter' to continue or 'backspace' to skip...";
    int result = _getch(); // returns number equivalent of a character
    if (result == 8) // 8 is the number equivalent of backspace
        return;
    ...
    code
    ...
}
</code>```

(technically any key besides backspace would continue)

You can use this table as a basic reference to which characters belong to which numbers.

Title: Hit enter to continue or skip function

Body:
I'm currently trying to write a program, and I've hit a bit of a bump. I was able to find how to do "hit enter to continue" easy, but now the function (void) that I have it in I also want to be able to skip right about where the first hit enter to continue pops up. Basically, I want to give the user the opportunity to either hit enter to continue with the rest of the function, or hit a button to skip the rest of the function. Here's an idea of what my code looks like currently:

void intro()
{
    int skip; // Not sure if I need this, was going to experiment

    cout << "Stuff being said " << endl;
    cout << "More stuff being said " << endl;
    cout << "Press 'enter' to continue...";
    cin.ignore(); // This is where I want the input to continue or skip.

So basically, I want to keep the hit enter to continue while also giving the user the opportunity to skip the function. Is this possible, or do I have to do something else entirely?

Body:
Here is a possible solution to your problem:  use _getch().  It is a function inside of conio.h that pauses and waits for the user to press a key, then returns an int representing that character.  Here is an example of how you could use it in your code:

#include <conio.h> // put this somewhere up at the top of the file
void intro()
{
    cout << "Stuff being said " << endl;
    cout << "More stuff being said " << endl;
    cout << "Press 'enter' to continue or 'backspace' to skip...";
    int result = _getch(); // returns number equivalent of a character
    if (result == 8) // 8 is the number equivalent of backspace
        return;
    ...
    code
    ...
}

(technically any key besides backspace would continue)

You can use this table as a basic reference to which characters belong to which numbers.