来源: stackexchange

问:
RxJS not all Subscribers receive all events
I'm working on an exercise about RxJS.
And there's something very strange happening:

```<code>  typoStream.subscribe(x => console.log('wont get executed'));
  wordCompletedStream.subscribe(nextStream);
  typoStream.subscribe(x => console.log('will get executed'));
</code>```

When the application runs the first console.log won't get printed and the second one will.

Regardless of what the streams are and how they interact - this should never happen, right? Why is it important when I subscribe to an observable - shouldn't it emit the event to every subscriber anyways?

If you want to try it:
http://embed.plnkr.co/xb8Yimo5RcYGPtgClYgY/

Type the displayed word correctly and you can see the "error" in action. But it doesn't happen every time - only most of the time.

Here's the stream flow: https://photos.app.goo.gl/Z4cpKzekAIuKzMF93

答:
I had a play with the code you posted, and the key fix is to properly multicast the checkWord observable. You can do this with .publish().refCount() like you did for wordStream, or you can use the shortcut method that does the same thing, .share().

```<code>  const checkStream = wordStream.combineLatest(inputStream).share();
</code>```

The reason this works is that without it, multiple subscriptions to checkStream or any streams derived from it, such as typoStream and wordCompletedStream will each trigger a new subscription to the wordStream observable (which is correctly multicast, so no new request gets made) and the inputStream observable, which will register new event listeners on the input.

With the .share() operator, it doesn't matter how many subscriptions are made to checkStream or derived observables, only the first one will trigger a subscription to inputStream.

Note that after this fix, neither of the two subscribers to typoStream will fire for a correctly entered word. Which is what I would expect from an observable called typoStream. Both will fire when an incorrect character is entered.

Forked Plunkr here

Or see the snippet below:

(() => {

  // --- UI Stuff, NO NEED TO TOUCH THESE --- //
  const wordField = $('#TotDWord');
  const inputField = $('#TotDInput');
  // ----------------------------------------- //

  // A stream of the users string inputs
  const inputFieldStream = Rx.Observable.fromEvent(inputField, 'keyup')
    .map(x => x.target.value).distinctUntilChanged();

  // This stream is used to represent the users unput - we don't use the
  // inputFieldStream directly because we want to manually send values aswell
  const inputStream = new Rx.Subject();

  // Feed the stream from the field into our inputStream
  inputFieldStream.subscribe(inputStream);

  // A stream that allows us to manually trigger that we need a new word
  const nextStream = new Rx.Subject();

  // When we want the next word we need to reset the users input
  nextStream.subscribe(() => {
    inputField.val('');
    inputStream.onNext('');
  });

  // This stream calls a server for a new random word every time the nextStream emits an event. We startWith a value to trigger the first word
  const wordStream = nextStream.startWith('')
    .flatMapLatest(getRandomWord)
    // publish & refCount cache the result - otherwise every .map on wordStream would cause a new HTTP request
    .publish().refCount();

  // When there is a new word, we display it
  wordStream.subscribe(word => {
    wordField.empty();
    wordField.append(word);
  });

  // Checkstream combines the latest word with the latest userinput. It emits an array, like this ['the word', 'the user input'];
  const checkStream = wordStream.combineLatest(inputStream).share();

  // Emits an event if the user input is not correct
  const typoStream = checkStream.filter(tuple => {
    const word = tuple[0];
    const input = tuple[1];
    return !word.startsWith(input);
  });

  // When there is a typo we need a new word
  typoStream.subscribe(nextStream);

  // Emits an event when the user has entered the entire word correctly
  const wordCompletedStream = checkStream.filter(tuple => {
    const word = tuple[0];
    const input = tuple[1];
    return word == input;
  });

  /**
   * THIS WILL (MOST OF THE TIME) NOT FIRE WHEN YOU COMPLETE A WORD
   */
  typoStream.subscribe(x => console.log('wont get executed'));

  // Whenever the word is completed, request a new word
  wordCompletedStream.subscribe(nextStream);

  /**
   * THIS WILL FIRE WHEN YOU COMPLETE A WORD
   */
  typoStream.subscribe(x => console.log('will get executed'));

  // Calls a server for a random word
  // returns a promise
  function getRandomWord() {
    return $.ajax({
      // Change the URL to cause a 404 error
      url: 'https://setgetgo.com/randomword/get.php'
    }).promise();
  }

})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>

<div>
  <h1>Exercise: Typing of the Dead</h1>
  <div>
    Type the given word correctly and watch the console. Most of the time 1 of the 2 subscriptions on the typoStream will fire (when there should fire none).
  </div>
  <br />
  <div id="TotDWord"></div>
  <input type="text" name="" id="TotDInput" value="" /><span>Highscore: </span><span id="TotDHighscore"></span>
  <div id="TotDScore"></div>
</div>

<script>
  console.clear();
</script></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm working on an exercise about RxJS.
And there's something very strange happening:

  typoStream.subscribe(x => console.log('wont get executed'));
  wordCompletedStream.subscribe(nextStream);
  typoStream.subscribe(x => console.log('will get executed'));

When the application runs the first console.log won't get printed and the second one will.

Regardless of what the streams are and how they interact - this should never happen, right? Why is it important when I subscribe to an observable - shouldn't it emit the event to every subscriber anyways?

If you want to try it:
http://embed.plnkr.co/xb8Yimo5RcYGPtgClYgY/

Type the displayed word correctly and you can see the "error" in action. But it doesn't happen every time - only most of the time.

Here's the stream flow: https://photos.app.goo.gl/Z4cpKzekAIuKzMF93

Body:
I had a play with the code you posted, and the key fix is to properly multicast the checkWord observable. You can do this with .publish().refCount() like you did for wordStream, or you can use the shortcut method that does the same thing, .share().

  const checkStream = wordStream.combineLatest(inputStream).share();

The reason this works is that without it, multiple subscriptions to checkStream or any streams derived from it, such as typoStream and wordCompletedStream will each trigger a new subscription to the wordStream observable (which is correctly multicast, so no new request gets made) and the inputStream observable, which will register new event listeners on the input.

With the .share() operator, it doesn't matter how many subscriptions are made to checkStream or derived observables, only the first one will trigger a subscription to inputStream.

Note that after this fix, neither of the two subscribers to typoStream will fire for a correctly entered word. Which is what I would expect from an observable called typoStream. Both will fire when an incorrect character is entered.

Forked Plunkr here

Or see the snippet below:

(() => {

  // --- UI Stuff, NO NEED TO TOUCH THESE --- //
  const wordField = $('#TotDWord');
  const inputField = $('#TotDInput');
  // ----------------------------------------- //

  // A stream of the users string inputs
  const inputFieldStream = Rx.Observable.fromEvent(inputField, 'keyup')
    .map(x => x.target.value).distinctUntilChanged();

  // This stream is used to represent the users unput - we don't use the
  // inputFieldStream directly because we want to manually send values aswell
  const inputStream = new Rx.Subject();

  // Feed the stream from the field into our inputStream
  inputFieldStream.subscribe(inputStream);

  // A stream that allows us to manually trigger that we need a new word
  const nextStream = new Rx.Subject();

  // When we want the next word we need to reset the users input
  nextStream.subscribe(() => {
    inputField.val('');
    inputStream.onNext('');
  });

  // This stream calls a server for a new random word every time the nextStream emits an event. We startWith a value to trigger the first word
  const wordStream = nextStream.startWith('')
    .flatMapLatest(getRandomWord)
    // publish & refCount cache the result - otherwise every .map on wordStream would cause a new HTTP request
    .publish().refCount();

  // When there is a new word, we display it
  wordStream.subscribe(word => {
    wordField.empty();
    wordField.append(word);
  });

  // Checkstream combines the latest word with the latest userinput. It emits an array, like this ['the word', 'the user input'];
  const checkStream = wordStream.combineLatest(inputStream).share();

  // Emits an event if the user input is not correct
  const typoStream = checkStream.filter(tuple => {
    const word = tuple[0];
    const input = tuple[1];
    return !word.startsWith(input);
  });

  // When there is a typo we need a new word
  typoStream.subscribe(nextStream);

  // Emits an event when the user has entered the entire word correctly
  const wordCompletedStream = checkStream.filter(tuple => {
    const word = tuple[0];
    const input = tuple[1];
    return word == input;
  });

  /**
   * THIS WILL (MOST OF THE TIME) NOT FIRE WHEN YOU COMPLETE A WORD
   */
  typoStream.subscribe(x => console.log('wont get executed'));

  // Whenever the word is completed, request a new word
  wordCompletedStream.subscribe(nextStream);

  /**
   * THIS WILL FIRE WHEN YOU COMPLETE A WORD
   */
  typoStream.subscribe(x => console.log('will get executed'));

  // Calls a server for a random word
  // returns a promise
  function getRandomWord() {
    return $.ajax({
      // Change the URL to cause a 404 error
      url: 'https://setgetgo.com/randomword/get.php'
    }).promise();
  }

})();

<script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.0.6/rx.all.js"></script>

<div>
  <h1>Exercise: Typing of the Dead</h1>
  <div>
    Type the given word correctly and watch the console. Most of the time 1 of the 2 subscriptions on the typoStream will fire (when there should fire none).
  </div>
  <br />
  <div id="TotDWord"></div>
  <input type="text" name="" id="TotDInput" value="" /><span>Highscore: </span><span id="TotDHighscore"></span>
  <div id="TotDScore"></div>
</div>

<script>
  console.clear();
</script>


问:
Garble JavaScript code before sending to client-side
How can I garble JavaScript code before sending it to client-side? I don't want to expose functionalities. The code is already compressed using jsmin.

答:
Search google for: Javascript obfuscator

You might add your platform to the query, as well. There are plenty of tools already out there that you can incorporate into your project.

OwnerDisplayName: Rakesh

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
How to hide all elements except one using jquery?
I have HTML page:

```<code><head></head>
<body>
  <div>
    <div>
      <div id="myDiv">
      </div>
    </div>
  </div>
</body>
</code>```

How to hide all divs, and just have the myDiv inside the body using jquery?

Update

The page may contain some other html elements such as some tables, anchors, p, and i just want to see the myDiv element.

答:
If you're objective is just to see that content and not see anything else, you can always just do this.  You don't need jQuery:</p>

```<code>document.body.innerHTML=document.getElementById('myDiv').innerHTML;
</code>```

Body:
I have HTML page:

How to hide all divs, and just have the myDiv inside the body using jquery?

Update

The page may contain some other html elements such as some tables, anchors, p, and i just want to see the myDiv element.

Body:
If you're objective is just to see that content and not see anything else, you can always just do this.  You don't need jQuery:

document.body.innerHTML=document.getElementById('myDiv').innerHTML;


问:
Asp.net Repeater hide image controls if url img null into db and show video controls And vice versa
I have an article repeater and the content should be either image or video. If image url is null, hide image controls and show video controls. If video url is null hide video control and show image control.

Webform

```<code><form id="form1" runat="server">
    <asp:Repeater runat="server" ID="rptrInfo" OnItemCommand="Repeater1_ItemCommand">
        <ItemTemplate>
            <asp:Image runat="server" ImageUrl='<%#Eval("ImageUrl") %>' />
            <video controls height="200" width="385" id="v<%#Eval("Info_Id") %>">
                <source src="<%#Eval("VideoUrl") %>" type="video/mp4" />
            </video>
        </ItemTemplate>
    </asp:Repeater>
</form>
</code>```

What I do into C# page ??

答:
It can be achieved either using code behind method or using Repeater inline code method.

Using code behind method

```<code><form id="form1" runat="server">
<asp:Repeater runat="server" ID="rptrInfo" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="rptrInfo_ItemDataBound">
    <ItemTemplate>
        <asp:Image ID="imgImage" runat="server" ImageUrl='<%#Eval("ImageUrl") %>' />
        <asp:Panel id="pnlVideo" runat="server">
        <video controls height="200" width="385" id="v<%#Eval("Info_Id") %>">
            <source src="<%#Eval("VideoUrl") %>" type="video/mp4" />
        </video>
        </asp:Panel>
    </ItemTemplate>
</asp:Repeater>
</code>```

```<code>protected void rptrInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Image img = (Image)e.Item.FindControl("imgImage");
            Panel pnlVdo = (Panel)e.Item.FindControl("pnlVideo");

            if(DataBinder.Eval(e.Item.DataItem, "ImageURL") != null)
            {
               img.Visible = true;
               pnlVdo.Visible = false;
            }
            else
            {
               img.Visible = false;
               pnlVdo.Visible = true;
            }
        }

    }
</code>```

Using Repeater inline code method

```<code><form id="form1" runat="server">
<asp:Repeater runat="server" ID="rptrInfo" OnItemCommand="Repeater1_ItemCommand">
    <ItemTemplate>
        <asp:Image runat="server" Visible='<%#Eval("ImageUrl") != null %>' ImageUrl='<%#Eval("ImageUrl") %>' />
    <div id="dVideo" runat="server" Visible='<%#Eval("VideoUrl") != null %>'>
        <video controls height="200" width="385" id="<%#Eval("Info_Id") %>">
            <source src='<%#Eval("VideoUrl") %>' type="video/mp4" />
        </video>
    </div>
    </ItemTemplate>
</asp:Repeater>
</code>```

Body:
I have an article repeater and the content should be either image or video. If image url is null, hide image controls and show video controls. If video url is null hide video control and show image control.

Webform

<form id="form1" runat="server">
    <asp:Repeater runat="server" ID="rptrInfo" OnItemCommand="Repeater1_ItemCommand">
        <ItemTemplate>
            <asp:Image runat="server" ImageUrl='<%#Eval("ImageUrl") %>' />
            <video controls height="200" width="385" id="v<%#Eval("Info_Id") %>">
                <source src="<%#Eval("VideoUrl") %>" type="video/mp4" />
            </video>
        </ItemTemplate>
    </asp:Repeater>
</form>

What I do into C# page ??

Body:
It can be achieved either using code behind method or using Repeater inline code method.

Using code behind method

<form id="form1" runat="server">
<asp:Repeater runat="server" ID="rptrInfo" OnItemCommand="Repeater1_ItemCommand" OnItemDataBound="rptrInfo_ItemDataBound">
    <ItemTemplate>
        <asp:Image ID="imgImage" runat="server" ImageUrl='<%#Eval("ImageUrl") %>' />
        <asp:Panel id="pnlVideo" runat="server">
        <video controls height="200" width="385" id="v<%#Eval("Info_Id") %>">
            <source src="<%#Eval("VideoUrl") %>" type="video/mp4" />
        </video>
        </asp:Panel>
    </ItemTemplate>
</asp:Repeater>

protected void rptrInfo_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Image img = (Image)e.Item.FindControl("imgImage");
            Panel pnlVdo = (Panel)e.Item.FindControl("pnlVideo");

            if(DataBinder.Eval(e.Item.DataItem, "ImageURL") != null)
            {
               img.Visible = true;
               pnlVdo.Visible = false;
            }
            else
            {
               img.Visible = false;
               pnlVdo.Visible = true;
            }
        }

    }

Using Repeater inline code method

<form id="form1" runat="server">
<asp:Repeater runat="server" ID="rptrInfo" OnItemCommand="Repeater1_ItemCommand">
    <ItemTemplate>
        <asp:Image runat="server" Visible='<%#Eval("ImageUrl") != null %>' ImageUrl='<%#Eval("ImageUrl") %>' />
    <div id="dVideo" runat="server" Visible='<%#Eval("VideoUrl") != null %>'>
        <video controls height="200" width="385" id="<%#Eval("Info_Id") %>">
            <source src='<%#Eval("VideoUrl") %>' type="video/mp4" />
        </video>
    </div>
    </ItemTemplate>
</asp:Repeater>


问:
FirebaseDatabase save log on file
I noticed that FirebaseDatabase only method to manage debugging is

```<code>FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);
</code>```

Can i get or redirect it on a my file  (myfirebaselogs.txt) ? I need to send it by email when needed to understand possible errors.

答:
A way to get the log into a file is

```<code>        Process process = Runtime.getRuntime().exec("logcat -d");

        BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(process.getInputStream())));

        StringBuilder log = new StringBuilder();

        String line;
        while ((line = bufferedReader.readLine()) != null)
        {
            log.append(line);
            log.append(TextConstants.newLine);
        }

        fileLog = new File("myFileLog.txt);

        FileOutputStream out = new FileOutputStream(fileLog);
        OutputStreamWriter osw = new OutputStreamWriter(out);

        osw.write(log.toString());
        osw.flush();
        osw.close();
</code>```

It get all the log lines from the beginning of the execution.

Title: FirebaseDatabase save log on file

Body:
I noticed that FirebaseDatabase only method to manage debugging is

FirebaseDatabase.getInstance().setLogLevel(Logger.Level.DEBUG);

Can i get or redirect it on a my file  (myfirebaselogs.txt) ? I need to send it by email when needed to understand possible errors.

Body:
A way to get the log into a file is

        Process process = Runtime.getRuntime().exec("logcat -d");

        BufferedReader bufferedReader = new BufferedReader((new InputStreamReader(process.getInputStream())));

        StringBuilder log = new StringBuilder();

        String line;
        while ((line = bufferedReader.readLine()) != null)
        {
            log.append(line);
            log.append(TextConstants.newLine);
        }

        fileLog = new File("myFileLog.txt);

        FileOutputStream out = new FileOutputStream(fileLog);
        OutputStreamWriter osw = new OutputStreamWriter(out);

        osw.write(log.toString());
        osw.flush();
        osw.close();

It get all the log lines from the beginning of the execution.


问:
Three part related entities not specifically identified by a sentence
How do I train a Watson Knowledge Studio machine learning annotator to identify education info that is not a part of a proper sentence. For example, two bullet points. How do I form a type system that will identify entities without breaking them all apart? I've considered using relation annotations, but according to the official documentation relation types should only be annotated if the sentence specifically mentions the relation. Such as "Mary works for IBM" is an example of the employedBy relation type. (Mary employedBy IBM) However, their own videos show them annotating "Ford F-150" with a manufacturedBy relation even though the sentence doesn't specifically state the relation. For example, "The Ford F-150 struck a light pole." (F-150 manufacturedBy Ford)

This is the kind of text I'm working with:

B.A., City University of New York, 1995

M.A., New York University, 1997

Ph.D, Columbia University, 1999

I could annotate these with degree, school, and graduationYear entities, but I'll end up getting back "1995", "1997", "1999" "B.A.", "City University of New York", "Columbia University", "M.A.", "New York University", "Ph.D"; a jumble that I can't work with because I can't tell anymore what degree belongs with what school belongs with what graduation year.

答:
As for the expressions which include two bullet points, there is a possibility to improve accuracy to detect sentences as they can work with WKS, using Dictionary-based Tokenizer.
https://console.bluemix.net/docs/services/knowledge-studio/create-project.html#wks_tokenizer

I imported your example text to WKS and checked the result of tokenization, and then the expression was separated into 3 sentences.
In this case you can annotate relations among degree, school and graduation year.


问:
Building boost libraries for windows
I'm trying to build boost static libs for mingw compiler on windows 8.1, using commands:

```<code>bootstrap.bat gcc
b2 toolset=gcc link=static --prefix=boost_mingw_530_static install
</code>```

but getting as result .a files in boost_mingw_530_static/lib folder instead of .lib.
How to get .lib files?

答: seems that .lib is not needed when using mingw, .a worked as well

Title: Building boost libraries for windows

Body:
I'm trying to build boost static libs for mingw compiler on windows 8.1, using commands:

bootstrap.bat gcc
b2 toolset=gcc link=static --prefix=boost_mingw_530_static install

but getting as result .a files in boost_mingw_530_static/lib folder instead of .lib.
How to get .lib files?


问:
Uploading multiple files with Fetch and FormData APIs
I'm trying to use the native Fetch and FormData APIs to upload multiple files at once to the server but I can't for the life of me get it to work. Here's what I've got:

```<code>// acceptedFiles are File objects coming from `react-dropzone`.
function handleSubmit(acceptedFiles) {
  const data = new FormData();

  for (const file of acceptedFiles) {
    data.append('files', file, file.name);
  }

  return fetch('https://example.com/api/upload', {
    method: 'POST',
    body: data,
  });
}
</code>```

But what my Rails server receives is this:

```<code>Parameters: {"files"=>#
<ActionDispatch::Http::UploadedFile:0x00007feb347becc0 @tempfile=#
<Tempfile:/var/folders/kl/y1jrp7zs55sbx075jjjl3p280000gn/T/RackMultipart201
71112-6486-1ftkufy.mp4>, @original_filename="SampleVideo_1280x720_5mb.mp4",
 @content_type="video/mp4", @headers="Content-Disposition: form-data;
name=\"files\"; filename=\"SampleVideo_1280x720_5mb.mp4\"\r\nContent-Type:
 video/mp4\r\n">}
</code>```

In other words, it looks like files is actually just one file. But the docs for FormData say that append should append multiple files.

So what's going wrong?

答:
The solution was to change files to files[]:

```<code>// acceptedFiles are File objects coming from `react-dropzone`.
function handleSubmit(acceptedFiles) {
  const data = new FormData();

  for (const file of acceptedFiles) {
    data.append('files[]', file, file.name);
  }

  return fetch('https://example.com/api/upload', {
    method: 'POST',
    body: data,
  });
}
</code>```

Body:
I'm trying to use the native Fetch and FormData APIs to upload multiple files at once to the server but I can't for the life of me get it to work. Here's what I've got:

// acceptedFiles are File objects coming from `react-dropzone`.
function handleSubmit(acceptedFiles) {
  const data = new FormData();

  for (const file of acceptedFiles) {
    data.append('files', file, file.name);
  }

  return fetch('https://example.com/api/upload', {
    method: 'POST',
    body: data,
  });
}

But what my Rails server receives is this:

Parameters: {"files"=>#
<ActionDispatch::Http::UploadedFile:0x00007feb347becc0 @tempfile=#
<Tempfile:/var/folders/kl/y1jrp7zs55sbx075jjjl3p280000gn/T/RackMultipart201
71112-6486-1ftkufy.mp4>, @original_filename="SampleVideo_1280x720_5mb.mp4",
 @content_type="video/mp4", @headers="Content-Disposition: form-data;
name=\"files\"; filename=\"SampleVideo_1280x720_5mb.mp4\"\r\nContent-Type:
 video/mp4\r\n">}

In other words, it looks like files is actually just one file. But the docs for FormData say that append should append multiple files.

So what's going wrong?

Body:
The solution was to change files to files[]:

// acceptedFiles are File objects coming from `react-dropzone`.
function handleSubmit(acceptedFiles) {
  const data = new FormData();

  for (const file of acceptedFiles) {
    data.append('files[]', file, file.name);
  }

  return fetch('https://example.com/api/upload', {
    method: 'POST',
    body: data,
  });
}


问:
How to ignore JSON fields when marshalling not unmarshalling
Assume I have a password field in a User struct.

```<code>type User struct{
   UserName string `json:"username"`
   Password string `json:"-"`
}
</code>```

My clients register their users by posting username and password together. So if I decode JSON to above struct, it ignores password. It's expected. But I wondered is there any way to ignore fields when only marshalling. I checked go official documentation page but couldn't find anything.

https://golang.org/pkg/encoding/json/

I can add an extra field into the struct but I need to know first is it possible to do that with JSON lib.

答:
As with any custom marshaling/unmarshaling requirements in Go, your best bet is to look at implementing json.Marshaler/json.Unmarshaler interface on a custom type.

In this case, you can do it for the password field:

```<code>// Use an explicit password type.
type password string

type User struct{
    UserName string   `json:"username"`
    Password password `json:"password"`
}

// Marshaler ignores the field value completely.
func (password) MarshalJSON() ([]byte, error) {
    return []byte(`""`), nil
}
</code>```

Note that by not implementing json.Unmarshaler, type password retains the default behavior of its underlying type (string), which allows the struct to be unmarshalled with the Password value.

Working example: https://play.golang.org/p/HZQoCKm0vN

Body:
Assume I have a password field in a User struct.

type User struct{
   UserName string `json:"username"`
   Password string `json:"-"`
}

My clients register their users by posting username and password together. So if I decode JSON to above struct, it ignores password. It's expected. But I wondered is there any way to ignore fields when only marshalling. I checked go official documentation page but couldn't find anything.

https://golang.org/pkg/encoding/json/

I can add an extra field into the struct but I need to know first is it possible to do that with JSON lib.

Body:
As with any custom marshaling/unmarshaling requirements in Go, your best bet is to look at implementing json.Marshaler/json.Unmarshaler interface on a custom type.

In this case, you can do it for the password field:

// Use an explicit password type.
type password string

type User struct{
    UserName string   `json:"username"`
    Password password `json:"password"`
}

// Marshaler ignores the field value completely.
func (password) MarshalJSON() ([]byte, error) {
    return []byte(`""`), nil
}

Note that by not implementing json.Unmarshaler, type password retains the default behavior of its underlying type (string), which allows the struct to be unmarshalled with the Password value.

Working example: https://play.golang.org/p/HZQoCKm0vN


问:
Creating a Google map in iOS that doesn't fit the whole screen
I'm using the Google Maps SDK to generate a map in my UIViewController but it's generating a map on the whole screen. I only need it to create a map on half the screen. How do I accomplish that?    </p>

```<code>class MapViewController: UIViewController,CLLocationManagerDelegate{
    var locationManager = CLLocationManager()
    var mapView = GMSMapView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // User Location
        locationManager.delegate = self
        //locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
        view.backgroundColor = UIColor.gray

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation = locations.last
        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

        let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
                                              longitude: userLocation!.coordinate.longitude, zoom: 9.1)

        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        self.view = mapView

        locationManager.stopUpdatingLocation()
    }
}
</code>```

答:
Create another view on your ViewController that is exactly the size you want, then instead of:
 self.view = mapView
you can do self.(insert your new view name here) = mapView

Body:
I'm using the Google Maps SDK to generate a map in my UIViewController but it's generating a map on the whole screen. I only need it to create a map on half the screen. How do I accomplish that?

class MapViewController: UIViewController,CLLocationManagerDelegate{
    var locationManager = CLLocationManager()
    var mapView = GMSMapView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // User Location
        locationManager.delegate = self
        //locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
        view.backgroundColor = UIColor.gray

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation = locations.last
        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

        let camera = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude,
                                              longitude: userLocation!.coordinate.longitude, zoom: 9.1)

        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        self.view = mapView

        locationManager.stopUpdatingLocation()
    }
}


问:
Laravel Blade @section Not Displaying
I have this blade page called "home.blade.php"

home.blade.php

```<code><doctype html>

<html>
   <head>
      <title>{{$title}}</title>
   </head>
   <body>
      <!-- some other html here -->
      @section('content')
      @show
   </body>
</html>
</code>```

And I also have a file "content.blade.php"

content.blade.php

```<code>@extends('home')

@section('content')
   <p>Page content goes here</p>
@endsection
</code>```

When I load the page on my browser though, the content in @section('content') does not display. When I check the source, it is not being output -- the line

```<code><p>Page content goes here</p>
</code>```

is not in the source code.

I don't know if it's relevant, but here is the route for this page and controller code.

Route

```<code>Route::get('/', 'Controller@show')->name("home");
</code>```

Controller code

```<code>public function show()
{
    return view("home", ['title' => "My Home"]);
}
</code>```

What am I missing here?

答:
Why not try using @yield,

```<code>@yield('content')
</code>```

https://laravel.com/docs/5.0/templates

Hope this helps :)

Title: Laravel Blade @section Not Displaying

Body:
I have this blade page called "home.blade.php"

home.blade.php

<doctype html>

      <title>{{$title}}</title>

      @section('content')
      @show

And I also have a file "content.blade.php"

content.blade.php

@extends('home')

@section('content')

Page content goes here

@endsection

When I load the page on my browser though, the content in @section('content') does not display. When I check the source, it is not being output -- the line

Page content goes here

is not in the source code.

I don't know if it's relevant, but here is the route for this page and controller code.

Route

Route::get('/', 'Controller@show')->name("home");

Controller code

public function show()
{
    return view("home", ['title' => "My Home"]);
}

What am I missing here?

Body:
Why not try using @yield,

@yield('content')

https://laravel.com/docs/5.0/templates

Hope this helps :)


问:
Convert dates to pd.to_datetime where month could be either a number or month name
I have a datatime data, their format is like 29062017 and 01AUG2017.
As you can see, the month is in the middle of data.

I want to convert this data to datetime, when I use pd.to_datetime, but it doesn't work.

Do you know a good way to solve this problem?

答:
Since you have two type of datetime ...</p>

```<code>s.apply(lambda x : pd.to_datetime(x, format="%d%m%Y") if x.isdigit() else pd.to_datetime(x, format="%d%b%Y"))

Out[360]:
0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]
</code>```

Body:
Since you have two type of datetime ...

s.apply(lambda x : pd.to_datetime(x, format="%d%m%Y") if x.isdigit() else pd.to_datetime(x, format="%d%b%Y"))

Out[360]:
0   2017-06-29
1   2017-08-01
dtype: datetime64[ns]


问:
Font awesome icon
How can I get color icon of font awesome ?

Like I am using fa fa-facebook class to get a facebook icon. But it is not colorful. I need a font awesome colorful(facebook color) icon of facebook.

答:
You can change color by using css properties.</p>

```<code>#elementID {
   color: #fff;
   text-shadow: 1px 1px 1px #ccc;
   font-size: 1.5em;
}
</code>```

Title: Font awesome icon

Body:
You can change color by using css properties.

#elementID {
   color: #fff;
   text-shadow: 1px 1px 1px #ccc;
   font-size: 1.5em;
}


问:
PDO: Not running multiple queries
Code

DB Dump

index.php

The issue

Running index.php from the browser
gives you no output when it should
give you an array of 4 rows. ( the issue )

Executing the sql statement directly into the
database gives you 4 rows as output.( as expected )

Also, running a simpler query such as
SELECT * FROM company in index.php
gives you the correct output.( as expected )

So there's no issue with the pdo connection and no issue with the sql statements, and I still don't get the required output.

PHP Version: 5.3.1 | MySQL Version: 5.1.41

答:
Like the answer above already mentioned, it's a security thing. They've done that to make sure that you can't insert "evil" values into the query, e.g. 'OR 1=1; SELECT * FROM users'. I am aware that you're using prepared statements, so this could never happen anyway, but PDO_MySQL still doesn't allow for this, as far as I am aware. The (newer?) PDO_MYSQLND driver however does seem to allow this.

As far as I can tell, that driver is currently not ready for production. Guess you'll have to do it in two queries, or if they are always called in that specific sequence, you could hide that inside a stored procedure.

Title: PDO: Not running multiple queries


问:
How to Integrate Linkedin in Angular2
I have problem regarding LinkedIn Authentication in Angular2 my code is.

```<code>import {Component , OnInit , NgZone} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {ROUTER_DIRECTIVES , Router} from 'angular2/router';

declare var IN : any;

@Component({
  directives : [ROUTER_DIRECTIVES],
  selector : '.main',
  providers : [HTTP_PROVIDERS],
  templateUrl : './app/registration/employee.reg.html'
})

export class EmployeeRegistrationComponent implements OnInit{

 constructor(private zone : NgZone){
    this.zone.run(() => {
        $.proxy(this.OnLinkedInFrameworkLoad, this);
    });
}

ngOnInit(){
    var linkedIn = document.createElement("script");
    linkedIn.type = "text/javascript";
    linkedIn.src = "http://platform.linkedin.com/in.js";
    linkedIn.innerHTML = "\n"+
        "api_key: **********\n" +
        "authorize: true\n" +
        "onLoad:" + this.OnLinkedInFrameworkLoad ;
    document.head.appendChild(linkedIn);

    var script = document.createElement("script");
    script.type = "in/Login";
    document.body.appendChild(script);
}

OnLinkedInFrameworkLoad = () => {
    IN.Event.on(IN, "auth", this.OnLinkedInAuth);
}

OnLinkedInAuth = () => {
    IN.API.Profile("me").result(result => this.ShowProfileData);
}

ShowProfileData(profiles) {
    console.log(profiles);
    var member = profiles.values[0];
    var id=member.id;
    var firstName=member.firstName;
    var lastName=member.lastName;
    var photo=member.pictureUrl;
    var headline=member.headline;

    //use information captured above
   }

}
</code>```

Console Throwing Error : angular2-polyfills.js:1250 Uncaught Error: Could not execute 'function () {'. Please provide a valid function for callback.

Please Help me out what is wrong I'm doing...

答:
Your using javascript dom functions, so you need to change this:

```<code>"onLoad:" + this.OnLinkedInFrameworkLoad ;
</code>```

To this:

```<code>"onLoad: onLinkedInLoad";
</code>```

Now add this to the  of your index.html

```<code><script type="text/javascript">

// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
    IN.Event.on(IN, "auth", getProfileData);
}

// Handle the successful return from the API call
function onSuccess(data) {
    console.log(data);
}

// Handle an error response from the API call
function onError(error) {
    console.log(error);
}

// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
    IN.API.Raw("/people/~").result(onSuccess).error(onError);
}

</script>
</code>```

Title: How to Integrate Linkedin in Angular2

Body:
I have problem regarding LinkedIn Authentication in Angular2 my code is.

import {Component , OnInit , NgZone} from 'angular2/core';
import {HTTP_PROVIDERS} from 'angular2/http';
import {ROUTER_DIRECTIVES , Router} from 'angular2/router';

declare var IN : any;

@Component({
  directives : [ROUTER_DIRECTIVES],
  selector : '.main',
  providers : [HTTP_PROVIDERS],
  templateUrl : './app/registration/employee.reg.html'
})

export class EmployeeRegistrationComponent implements OnInit{

 constructor(private zone : NgZone){
    this.zone.run(() => {
        $.proxy(this.OnLinkedInFrameworkLoad, this);
    });
}

ngOnInit(){
    var linkedIn = document.createElement("script");
    linkedIn.type = "text/javascript";
    linkedIn.src = "http://platform.linkedin.com/in.js";
    linkedIn.innerHTML = "\n"+
        "api_key: **********\n" +
        "authorize: true\n" +
        "onLoad:" + this.OnLinkedInFrameworkLoad ;
    document.head.appendChild(linkedIn);

    var script = document.createElement("script");
    script.type = "in/Login";
    document.body.appendChild(script);
}

OnLinkedInFrameworkLoad = () => {
    IN.Event.on(IN, "auth", this.OnLinkedInAuth);
}

OnLinkedInAuth = () => {
    IN.API.Profile("me").result(result => this.ShowProfileData);
}

ShowProfileData(profiles) {
    console.log(profiles);
    var member = profiles.values[0];
    var id=member.id;
    var firstName=member.firstName;
    var lastName=member.lastName;
    var photo=member.pictureUrl;
    var headline=member.headline;

    //use information captured above
   }

}

Console Throwing Error : angular2-polyfills.js:1250 Uncaught Error: Could not execute 'function () {'. Please provide a valid function for callback.

Please Help me out what is wrong I'm doing...

Body:
Your using javascript dom functions, so you need to change this:

"onLoad:" + this.OnLinkedInFrameworkLoad ;

To this:

"onLoad: onLinkedInLoad";

Now add this to the <head> of your index.html

<script type="text/javascript">

// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
    IN.Event.on(IN, "auth", getProfileData);
}

// Handle the successful return from the API call
function onSuccess(data) {
    console.log(data);
}

// Handle an error response from the API call
function onError(error) {
    console.log(error);
}

// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
    IN.API.Raw("/people/~").result(onSuccess).error(onError);
}

</script>


答:
You can change the color of the font using custom CSS, for you case</p>

```<code>.fa-facebook-square:before {
    color: #488dd8;
}
</code>```

Title: Font awesome icon

Body:
How can I get color icon of font awesome ?

Like I am using fa fa-facebook class to get a facebook icon. But it is not colorful. I need a font awesome colorful(facebook color) icon of facebook.

Body:
You can change the color of the font using custom CSS, for you case

.fa-facebook-square:before {
    color: #488dd8;
}


问:
BigQuery API PY Client Library - Difference between Client.query() vs Client.query_rows()
I'm learning to use BigQuery APIs using Google BigQuery client library for Python v0.28 - https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html#queries

and unable to understand the difference between following two methods to query data

```<code>query(query, job_config=None, job_id=None, job_id_prefix=None, retry=<google.api_core.retry.Retry object>)
query_rows(query, job_config=None, job_id=None, job_id_prefix=None, timeout=None, retry=<google.api_core.retry.Retry object>)
</code>```

What's the difference between the two and in what situation you'll use one over the other? To me, both seem to be a way we can query a table.

Thanks a lot for providing insight into it!

Cheers!

答:
They are kind of the same indeed with one main difference: query_rows could be considered a synchronous implementation as it will wait for the job to complete and return for you an iterator with results.

Running it will block your python interpreter until the job is done.

query on the other hand is asynchronous, if you run it your interpreter will be free to execute other operations regardless whether the job is done or not (and it's up to you to wait for the job and get the results).

As you can see in the source code, query_rows calls self.query inside its method and then it calls result (which waits for the job to complete).

Body:
I'm learning to use BigQuery APIs using Google BigQuery client library for Python v0.28 - https://googlecloudplatform.github.io/google-cloud-python/latest/bigquery/usage.html#queries

and unable to understand the difference between following two methods to query data

query(query, job_config=None, job_id=None, job_id_prefix=None, retry=<google.api_core.retry.Retry object>)
query_rows(query, job_config=None, job_id=None, job_id_prefix=None, timeout=None, retry=<google.api_core.retry.Retry object>)

What's the difference between the two and in what situation you'll use one over the other? To me, both seem to be a way we can query a table.

Thanks a lot for providing insight into it!

Cheers!


问:
How to get in tsql total number of hours inside a time range
Thanks in advance.

My question is I have a start time(2017-10-09 20:28:05.997) and end time(2017-10-10 05:37:12.413) on my table

I would like to check how many hours using tsql will fall between (2017-10-09 22:00:00.00) and (2017-10-10 06:00:00.000) this are constant.

Thank you!

答:
You should do something like this:

```<code>Declare @start_time datetime;
Declare @start_range datetime;
Declare @end_range datetime;
Declare @end_time datetime;

If @start_range < @start_time
Begin
  Set @start_range =@start_time;
End

If @end_time  < @end_range
Begin
  Set @end_range =@end_time;
End

Select datediff(hour, @start_range, @end_range)
</code>```

In the range variables, you set the fixed range you are looking for

Body:
You should do something like this:

Declare @start_time datetime;
Declare @start_range datetime;
Declare @end_range datetime;
Declare @end_time datetime;

If @start_range < @start_time
Begin
  Set @start_range =@start_time;
End

If @end_time  < @end_range
Begin
  Set @end_range =@end_time;
End

Select datediff(hour, @start_range, @end_range)

In the range variables, you set the fixed range you are looking for


问:
Image Skeletonization using Medial Axis Transform
My requirement is something like this:

Lets take there is a Bitmap with a big letter 'A'.
The Bitmap is two colors (Either Black or White).

I need to skeletonize the big 'A'. (see: http://en.wikipedia.org/wiki/Topological_skeleton)
Using "Medial Axis Transforming" algorithm.

I tried my best in googling but i ended up being lost in finding a C#, C++ or at least pseudo code implementation of this algorithm.

I would like if someone could help me on this.

答: This page http://www.cs.sunysb.edu/~algorith/files/thinning.shtml has some sources you may wish to review.</p>


问:
Calculate object rotation angle from mouse movement in OpenGL drawing in Qt5
In the Qt 5.9 Qt OpenGL Hello GL2 Example, to implement the rotation of the objects, there is a degree normalization function when calculate the rotation from the movement of the mouse. I just don't get it 1) why it needs dx and dy time 8 to get the mouse movement distance? and 2) then 360 times 16 here to normalize the angle, why 16? And 3) when set up the rotation in render by dividing 16? Thanks.</p>

```<code>void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->x() - m_lastPos.x();
    int dy = event->y() - m_lastPos.y();

    if (event->buttons() & Qt::RightButton) {
        ....
        setZRotation(m_zRot + 8 * dx);
    }
    m_lastPos = event->pos();
}

static void qNormalizeAngle(int &angle) {
    while (angle < 0)
        angle += 360 * 16;
    while (angle > 360 * 16)
        angle -= 360 * 16;
}

void GLWidget::setZRotation(int angle)
{
    qNormalizeAngle(angle);
    if (angle != m_zRot) {
        m_zRot = angle;
        .....
        update();
    }
}

void GLWidget::paintGL() {
    ....
    m_world.rotate(m_zRot / 16.0f, 0, 0, 1);
    ....
}
</code>```

答:
Everything about the code in question smells like someone who simply had no real idea what they're doing.

The effect of what they've done is this. They scaled the input angle by 8, relative to the mouse delta. This causes the eventual angle to be 8x larger. But then they divide this angle by 16 before getting matrices with it. Therefore, the effect of what they've done is scale the input angle by 0.5.

The clamping to the range [0, 360 * 16] is just a part of that nonsense. They're really clamping to [0, 360], just in a really obtuse and insane way.

Overall, I'd say you should avoid Qt's example code like the plague.

Body:
In the Qt 5.9 Qt OpenGL Hello GL2 Example, to implement the rotation of the objects, there is a degree normalization function when calculate the rotation from the movement of the mouse. I just don't get it 1) why it needs dx and dy time 8 to get the mouse movement distance? and 2) then 360 times 16 here to normalize the angle, why 16? And 3) when set up the rotation in render by dividing 16? Thanks.

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    int dx = event->x() - m_lastPos.x();
    int dy = event->y() - m_lastPos.y();

    if (event->buttons() & Qt::RightButton) {
        ....
        setZRotation(m_zRot + 8 * dx);
    }
    m_lastPos = event->pos();
}

static void qNormalizeAngle(int &angle) {
    while (angle < 0)
        angle += 360 * 16;
    while (angle > 360 * 16)
        angle -= 360 * 16;
}

void GLWidget::setZRotation(int angle)
{
    qNormalizeAngle(angle);
    if (angle != m_zRot) {
        m_zRot = angle;
        .....
        update();
    }
}

void GLWidget::paintGL() {
    ....
    m_world.rotate(m_zRot / 16.0f, 0, 0, 1);
    ....
}


Title: Font awesome icon

Body:
use css to color the font, You can use style tag like this down example:-

< li class="fa fa-facebook" style="color: #0000ff" > </li>


问:
How to get more params when I use the rest framework?
How to get more params when I use the rest framework ?

This is my model:

```<code>class CloudServer(models.Model):
    buytime = models.ForeignKey(to=BuyTime)  # time duration
    expiration_time = models.DateTimeField()  # expire time
    availablearea = models.ForeignKey(to=AvailableArea)
    profile = models.TextField()  # profile
</code>```

This is my serializers:

```<code>class CloudServerCreateSerializer(ModelSerializer):
    class Meta:
        model = CloudServer
        fields = "__all__"
</code>```

This is my views:

```<code>class CloudServerCreateAPIView(CreateAPIView):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

    def post(self, request, *args, **kwargs):
        # there I want more params.
        #serializer.save()
        return Response(data="Create success", status=HTTP_200_OK, exception=None)
</code>```

The rest framework api web browser:

You see, there are only 4 params related to the model fields.

In there I want to get more params inputs here(such as 10 count),
and when I create I want to save 4 of the 10 params to the model serializer, and the remainder 6 params to use as other usefulness in CloudServerCreateAPIView's post method.

答:
You can take a look at  serializer fields :

You can put more serializer fields in your CloudServerCreateSerializer :

```<code>class CloudServerCreateSerializer(ModelSerializer):
    ...
    ext_one = serializers.CharField()
    ext_two = serializers.CharField()

    class Meta:
        model = CloudServer
        fields = "__all__"
</code>```

Body:
How to get more params when I use the rest framework ?

This is my model:

class CloudServer(models.Model):
    buytime = models.ForeignKey(to=BuyTime)  # time duration
    expiration_time = models.DateTimeField()  # expire time
    availablearea = models.ForeignKey(to=AvailableArea)
    profile = models.TextField()  # profile

This is my serializers:

class CloudServerCreateSerializer(ModelSerializer):
    class Meta:
        model = CloudServer
        fields = "__all__"

This is my views:

class CloudServerCreateAPIView(CreateAPIView):
    serializer_class = CloudServerCreateSerializer
    permission_classes = []
    queryset = CloudServer.objects.all()

    def post(self, request, *args, **kwargs):
        # there I want more params.
        #serializer.save()
        return Response(data="Create success", status=HTTP_200_OK, exception=None)

The rest framework api web browser:

You see, there are only 4 params related to the model fields.

In there I want to get more params inputs here(such as 10 count),
and when I create I want to save 4 of the 10 params to the model serializer, and the remainder 6 params to use as other usefulness in CloudServerCreateAPIView's post method.

Body:
You can take a look at  serializer fields :

You can put more serializer fields in your CloudServerCreateSerializer :

class CloudServerCreateSerializer(ModelSerializer):
    ...
    ext_one = serializers.CharField()
    ext_two = serializers.CharField()

    class Meta:
        model = CloudServer
        fields = "__all__"


问:
Iterator in a while loop executes one more time than expected
I am trying to create a code that runs until a person says 'BYE' three consecutive times.

With the following code:

```<code>ask = gets.chomp
count = 0
while (count != 3)
  if (ask == 'BYE')
    puts 'HUH?!  SPEAK UP, SONNY!'
    count = count + 1
    ask = gets.chomp
  elsif (ask != ask.upcase)
    puts 'HUH?!  SPEAK UP, SONNY!'
    count = 0
    ask = gets.chomp
  else
    puts 'NO, NOT SINCE ' + rand(1930..1950).to_s + '!'
    count = 0
    ask = gets.chomp
  end
end
puts 'Goodbye for now'
</code>```

I actually need to type 'BYE' four times. Can someone point to how to fix it?

答:
Putting gets only once at the beginning of the loop fixes it :

```<code>count = 0

while count != 3
    ask = gets.chomp

    if ask == 'BYE'
        puts 'HUH?!  SPEAK UP, SONNY!'
        count = count + 1
    elsif ask != ask.upcase
        puts 'HUH?!  SPEAK UP, SONNY!'
        count = 0
    else
        puts 'NO, NOT SINCE ' + rand(1930..1950).to_s + '!'
        count = 0
    end
end

puts 'Goodbye for now'
</code>```

Execution :

```<code>$ ruby -w topc.rb
a
HUH?!  SPEAK UP, SONNY!
A
NO, NOT SINCE 1931!
BYE
HUH?!  SPEAK UP, SONNY!
BYE
HUH?!  SPEAK UP, SONNY!
BYEE
NO, NOT SINCE 1939!
BYE
HUH?!  SPEAK UP, SONNY!
BYE
HUH?!  SPEAK UP, SONNY!
BYE
HUH?!  SPEAK UP, SONNY!
Goodbye for now
</code>```

Body:
I am trying to create a code that runs until a person says 'BYE' three consecutive times.

With the following code:

ask = gets.chomp
count = 0
while (count != 3)
  if (ask == 'BYE')
    puts 'HUH?!  SPEAK UP, SONNY!'
    count = count + 1
    ask = gets.chomp
  elsif (ask != ask.upcase)
    puts 'HUH?!  SPEAK UP, SONNY!'
    count = 0
    ask = gets.chomp
  else
    puts 'NO, NOT SINCE ' + rand(1930..1950).to_s + '!'
    count = 0
    ask = gets.chomp
  end
end
puts 'Goodbye for now'

I actually need to type 'BYE' four times. Can someone point to how to fix it?

Body:
Putting gets only once at the beginning of the loop fixes it :

count = 0

while count != 3
    ask = gets.chomp

    if ask == 'BYE'
        puts 'HUH?!  SPEAK UP, SONNY!'
        count = count + 1
    elsif ask != ask.upcase
        puts 'HUH?!  SPEAK UP, SONNY!'
        count = 0
    else
        puts 'NO, NOT SINCE ' + rand(1930..1950).to_s + '!'
        count = 0
    end
end

puts 'Goodbye for now'

Execution :

$ ruby -w topc.rb
a
HUH?!  SPEAK UP, SONNY!
A
NO, NOT SINCE 1931!
BYE
HUH?!  SPEAK UP, SONNY!
BYE
HUH?!  SPEAK UP, SONNY!
BYEE
NO, NOT SINCE 1939!
BYE
HUH?!  SPEAK UP, SONNY!
BYE
HUH?!  SPEAK UP, SONNY!
BYE
HUH?!  SPEAK UP, SONNY!
Goodbye for now


问:
Upload file without form
Upload file without form
Yes i used the search button but i just couldn't find the solution i need.
Is there any way to upload a file so that user wouldn't need to press any form buttons?

My first idea was to use CURL but then i remembered that CURL is server sided.

I know it's possible thru Java and/or Flash but is there any way to do that using PHP & OR Javascript?

Edit:
Thanks for clearing this for me but...
But what about PHP based FTP upload?*

答:
what do you mean without pressing any form buttons ?
well you could do a javascript document.getElementById('FORM_NAME').submit(); if you want some function in javascript to do the upload , where FORM_NAME is the id or your current html form .

but you CAN NOT make your webpage select the file to upload , you have to let the user select the file in an <input type="file"> element .

otherwise use a java applet

Title: Upload file without form


答:
You can style it with css, and if you want multiple color you can use gradient</p>

```<code><h1><i class="fa fa-facebook-official"></i></h1>

h1 {
    color: blue;
}
h1 {
    color: red; /* For browsers that do not support gradients */
    color: -webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
    color: -o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
    color: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
    color: linear-gradient(red, yellow); /* Standard syntax */
}
</code>```

Title: Font awesome icon

Body:
You can style it with css, and if you want multiple color you can use gradient

<h1><i class="fa fa-facebook-official"></i></h1>

h1 {
    color: blue;
}
h1 {
    color: red; /* For browsers that do not support gradients */
    color: -webkit-linear-gradient(red, yellow); /* For Safari 5.1 to 6.0 */
    color: -o-linear-gradient(red, yellow); /* For Opera 11.1 to 12.0 */
    color: -moz-linear-gradient(red, yellow); /* For Firefox 3.6 to 15 */
    color: linear-gradient(red, yellow); /* Standard syntax */
}


问:
Can I reuse the same variable name but for different BackgroundWorker threads?
Sample coding below:

```<code>private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  string var1 = "sample 1";
  //display in UI var1
  string var1 = "sample 1.1";
  //display in UI var1
}

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
  string var1 = "sample 2";
  //display in UI var1
  string var1 = "sample 2.1";
  //display in UI var1
}

private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
  string var1 = "sample 3";
  //display in UI var1
  string var1 = "sample 3.1";
  //display in UI var1
}
</code>```

Will it cause the threads to slow down because they are using the same variable? Or will it cause the wrong values to be shown at the UI since the value is always changing? My program will have a lot of threads so I worry about the potential unforeseen consequences.

答:
These are local variables, they exist independently of each other and the compiler and the runtime will never mix them up because they are... local to where they were declared. In fact, local variables are not a concern for threading, see Thread safety and local variables [*].

Once compiled, the name of local variables is lost (they will be - the equivalent of saying - local variable 1, local variable 2, etc...). That is, in Microsoft Intermediate Language, the name of local variables is irrelevant. See OpCodes.Ldloc Field.

Will it cause the threads to slow down because they are using the same variable?

No. These are unfounded worries. These local variables have nothing to do with each other.

Or will it cause the wrong values to be shown at the UI since the value is always changing?

This could happen regardless of variables names. What matters is what value you show in UI, and when and where you show it. What was the name of the variable holding it has no impact.

My program will have a lot of threads so I worry about the potential unforeseen consequences.

Worry not about local variables. Once we start talking about some form of shared memory across threads then you have a reason to worry. And no, local variables are not shared across threads, let me be clear here: they are local [**].

I want to suggest Joseph Albahari's series Threading in C#. Which despite being outdated [***] are well written, have clear examples, and get all the fundamentals across.

With that said, naming variables is important for readability and maintainability of the code. Anyway, I am not in the mood to preach. So, you do you. I will only say on the matter this: the next time you see a variable and you are not sure what it is or where else you might be using it, think about it.

[*]: The answer to the linked question mentions two ways a local variable could be exposed. Both amount to upgrade the local variable to a field of ana nonymous object behind the scenes (yield return copies the value to a hidden IEnumerator, on the other hand if make a closure on a local variable and share it, you are sharing the local variable - in a hidden anonymous class).

[**]: Even if you are using async/await and the method was resumed in a different thread, there is no chance two threads will share the local variable (it changed hands, but you usually have no reason to worry about that, unless you are using ThreadLocal or similar).

[***]: these days we will be using async/await, in fact, why are you using BackgroundWorker?

Body:
Sample coding below:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
  string var1 = "sample 1";
  //display in UI var1
  string var1 = "sample 1.1";
  //display in UI var1
}

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
  string var1 = "sample 2";
  //display in UI var1
  string var1 = "sample 2.1";
  //display in UI var1
}

private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
  string var1 = "sample 3";
  //display in UI var1
  string var1 = "sample 3.1";
  //display in UI var1
}

Will it cause the threads to slow down because they are using the same variable? Or will it cause the wrong values to be shown at the UI since the value is always changing? My program will have a lot of threads so I worry about the potential unforeseen consequences.


问:
Resource 'corpora/wordnet' not found on Heroku
I'm trying to get NLTK and wordnet working on Heroku. I've already done

```<code>heroku run python
nltk.download()
  wordnet
pip install -r requirements.txt
</code>```

But I get this error:

```<code>Resource 'corpora/wordnet' not found.  Please use the NLTK
  Downloader to obtain the resource:  >>> nltk.download()
  Searched in:
    - '/app/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
</code>```

Yet, I've looked at in /app/nltk_data and it's there, so I'm not sure what's going on.

答:
This one works:

For Mac OS users.

```<code>python -m nltk.downloader -d /usr/local/share/nltk_data wordnet
</code>```

Body:
I'm trying to get NLTK and wordnet working on Heroku. I've already done

heroku run python
nltk.download()
  wordnet
pip install -r requirements.txt

But I get this error:

Resource 'corpora/wordnet' not found.  Please use the NLTK
  Downloader to obtain the resource:  >>> nltk.download()
  Searched in:
    - '/app/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'

Yet, I've looked at in /app/nltk_data and it's there, so I'm not sure what's going on.

Body:
This one works:

For Mac OS users.

python -m nltk.downloader -d /usr/local/share/nltk_data wordnet


问:
Solution for previewing user changes and allowing rollback/commit over a period of time
I have asked a few questions today as I try to think through to the solution of a problem.

We have a complex data structure where all of the various entities are tightly interconnected, with almost all entities heavily reliant/dependant upon entities of other types.

The project is a website (MVC3, .NET 4), and all of the logic is implemented using LINQ-to-SQL (2008) in the business layer.

What we need to do is have a user "lock" the system while they make their changes (there are other reasons for this which I won't go into here that are not database related). While this user is making their changes we want to be able to show them the original state of entities which they are updating, as well as a "preview" of the changes they have made. When finished, they need to be able to rollback/commit.

We have considered these options:

Holding open a transaction for the length of time a user takes to make multiple changes stinks, so that's out.

Holding a copy of all the data in memory (or cached to disk) is an option but there is heck of a lot of it, so seems unreasonable.

Maintaining a set of secondary tables, or attempting to use session state to store changes, but this is  complex and difficult to maintain.

Using two databases, flipping between them by connection string, and using T-SQL to manage replication, putting them back in sync after commit/rollback. I.e. switching on/off, forcing snapshot, reversing direction etc.

We're a bit stumped for a solution that is relatively easy to maintain. Any suggestions?

答:
Our solution to a similar problem is to use a locking table that holds locks per entity type in our system. When the client application wants to edit an entity, we do a "GetWithLock" which gets the client the most up-to-date version of the entity's data as well as obtaining a lock (a GUID that is stored in the lock table along with the entity type and the entity ID). This prevents other users from editing the same entity. When you commit your changes with an update, you release the lock by deleting the lock record from the lock table. Since stored procedures are the api we use for interacting with the database, this allows a very straight forward way to lock/unlock access to specific entities.

On the client side, we implement IEditableObject on the UI model classes. Our model classes hold a reference to the instance of the service entity that was retrieved on the service call. This allows the UI to do a Begin/End/Cancel Edit and do the commit or rollback as necessary. By holding the instance of the original service entity, we are able to see the original and current data, which would allow the user to get that "preview" you're looking for.

While our solution does not implement LINQ, I don't believe there's anything unique in our approach that would prevent you from using LINQ as well.

HTH


问:
How to determine what type of layers do I need for my Deep learning model?
Suppose that I have want to make a model that does something. Now when I search about the topic in Google or YouTube, I find many related tutorials and it seems like some clever programmer had already implemented that model with Deep learning.

But how do they know that what type of layers, what type of activation functions, loss functions, optimizer, number of units etc. they need to solve that certain problem using deep learning.

Are there any techniques for knowing this, or its just a matter of understanding and experience? Also it would be very helpful if somebody could point me to some videos or articles answering my question.

答:
Thanks for the question.

The CS231n Stanford lectures on CNN is the best for beginners refer to the video lectures here and class notes are available here

After watching the lectures and completing the assignments, you will get a basic idea of what Deep Learning is and all the algorithms available etc.

But when it comes to solving real-world problems this won't be sufficient So take this course by Jeremy Howard where he teaches more on how to approach a problem using Kaggle platform.

Keep on solving more problems experimenting new models and algorithms using several platforms like hackerearth, Kaggle, topcoder etc.


问:
Error "Import Error: No module named numpy" on Windows
I have a very similar question to this question, but I am still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system.

I installed NumPy following this link - as suggested in the question. The installation went fine but when I execute

```<code>import numpy
</code>```

I got the following error:

Import error: No module named numpy

答:
Installing Numpy on Windows

Open Windows command prompt with administrator privileges (quick method: Press the Windows key. Type "cmd". Right-click on the
suggested "Command Prompt" and select "Run as Administrator)

Navigate to the Python installation directory's Scripts folder using the "cd" (change directory) command. e.g. "cd C:\Program Files (x86)\PythonXX\Scripts"

This might be: C:\Users\\AppData\Local\Programs\Python\PythonXX\Scripts or C:\Program Files (x86)\PythonXX\Scripts (where XX represents the Python version number), depending on where it was installed. It may be easier to find the folder using Windows explorer, and then paste or type the address from the Explorer address bar into the command prompt.

Enter the following command: "pip install numpy".

You should see something similar to the following text appear as the package is downloaded and installed.

```<code>Collecting numpy
  Downloading numpy-1.13.3-2-cp27-none-win32.whl (6.7MB)
  100% |################################| 6.7MB 112kB/s
Installing collected packages: numpy
Successfully installed numpy-1.13.3
</code>```

Body:
I have a very similar question to this question, but I am still one step behind. I have only one version of Python 3 installed on my Windows 7 (sorry) 64-bit system.

I installed NumPy following this link - as suggested in the question. The installation went fine but when I execute

import numpy

I got the following error:

Import error: No module named numpy

Body:
Installing Numpy on Windows

Open Windows command prompt with administrator privileges (quick method: Press the Windows key. Type "cmd". Right-click on the
suggested "Command Prompt" and select "Run as Administrator)

Navigate to the Python installation directory's Scripts folder using the "cd" (change directory) command. e.g. "cd C:\Program Files (x86)\PythonXX\Scripts"

This might be: C:\Users\\AppData\Local\Programs\Python\PythonXX\Scripts or C:\Program Files (x86)\PythonXX\Scripts (where XX represents the Python version number), depending on where it was installed. It may be easier to find the folder using Windows explorer, and then paste or type the address from the Explorer address bar into the command prompt.

Enter the following command: "pip install numpy".

You should see something similar to the following text appear as the package is downloaded and installed.

Collecting numpy
  Downloading numpy-1.13.3-2-cp27-none-win32.whl (6.7MB)
  100% |################################| 6.7MB 112kB/s
Installing collected packages: numpy
Successfully installed numpy-1.13.3


问:
Haskell - Takes a list of floats and returns a list of chars
I am wondering to create a Haskell function to take a list of floats and returns a list of chars that represent the letter grades based off the original scores.
I can complete this requirement without list:

```<code> convertRawsToLetters :: (RealFloat score) => score -> Char
 convertRawsToLetters score
    | score > 90 = 'A'
    | score <= 90 && score > 80 = 'B'
</code>```

How can I use condition in list?

答:
You can write a function that converts ONE float to a Char, as you've done here:

```<code>convertRawsToLetters :: (Num a, Ord a) => a -> Char
convertRawsToLetters s | s > 90    = 'A'
                       | s > 80    = 'B'
                       | s > 70    = 'C'
                       | otherwise = 'F'
</code>```

(note that I don't have to run both inequalities here since the guards are evaluated in order)

Then you map that over the list of floats. map has type:

```<code>map :: (a -> b) -> [a] -> [b]
</code>```

so its first argument is a function from a -> b (Float -> Char, in this case), its second argument is a list of as (Floats), and it returns a list of bs (Chars).

```<code>listOfChars :: [Char]
listOfChars = map convertRawsToLetters listOfFloats
</code>```

Body:
I am wondering to create a Haskell function to take a list of floats and returns a list of chars that represent the letter grades based off the original scores.
I can complete this requirement without list:

 convertRawsToLetters :: (RealFloat score) => score -> Char
 convertRawsToLetters score
    | score > 90 = 'A'
    | score <= 90 && score > 80 = 'B'

How can I use condition in list?

Body:
You can write a function that converts ONE float to a Char, as you've done here:

convertRawsToLetters :: (Num a, Ord a) => a -> Char
convertRawsToLetters s | s > 90    = 'A'
                       | s > 80    = 'B'
                       | s > 70    = 'C'
                       | otherwise = 'F'

(note that I don't have to run both inequalities here since the guards are evaluated in order)

Then you map that over the list of floats. map has type:

map :: (a -> b) -> [a] -> [b]

so its first argument is a function from a -> b (Float -> Char, in this case), its second argument is a list of as (Floats), and it returns a list of bs (Chars).

listOfChars :: [Char]
listOfChars = map convertRawsToLetters listOfFloats


问:
Zsh find permission denied - Application Saved State
Whenever I use the find command in zsh, if I have it run from the user level, it always outputs a specific permission denied message (in addition to any found paths) For example:

```<code>$ find "/Users/usr" -name "Python.gitignore"

/Users/usr/Dropbox/Programming/Git/gitignore/Python.gitignore
find: /Users/usr/Library/Saved Application State/com.bitrock.appinstaller.savedState: Permission denied
</code>```

But if it's run on any subdirectory of /Users/usr (except Users/usr/Library) it works as expected:

```<code>$ find "/Users/usr/Dropbox" -name "Python.gitignore"

/Users/vivekjha/Dropbox/Programming/Git/gitignore/Python.gitignore
</code>```

What is a "Saved Application State" and how can I prevent this error message from outputting when running find?

答:
If you want to hide all the permission error messages from the find command, you can directly redirect its stderr to /dev/null

```<code>find "/Users/usr" -name "Python.gitignore" 2> /dev/null;
</code>```

However you might hide other error messages that what you want, therefore you could filter it out in the following way:

```<code> find "/Users/usr" -name "Python.gitignore" 2>&1 | grep -v ": Permission denied$"
</code>```

Body:
Whenever I use the find command in zsh, if I have it run from the user level, it always outputs a specific permission denied message (in addition to any found paths) For example:

$ find "/Users/usr" -name "Python.gitignore"

/Users/usr/Dropbox/Programming/Git/gitignore/Python.gitignore
find: /Users/usr/Library/Saved Application State/com.bitrock.appinstaller.savedState: Permission denied

But if it's run on any subdirectory of /Users/usr (except Users/usr/Library) it works as expected:

$ find "/Users/usr/Dropbox" -name "Python.gitignore"

/Users/vivekjha/Dropbox/Programming/Git/gitignore/Python.gitignore

What is a "Saved Application State" and how can I prevent this error message from outputting when running find?

Body:
If you want to hide all the permission error messages from the find command, you can directly redirect its stderr to /dev/null

find "/Users/usr" -name "Python.gitignore" 2> /dev/null;

However you might hide other error messages that what you want, therefore you could filter it out in the following way:

 find "/Users/usr" -name "Python.gitignore" 2>&1 | grep -v ": Permission denied$"


问:
Text field containing multiple values, suggestions in a drop-down (like Gmail "To:" field)
I need functionality in my web application similar to Gmail's drop-down of suggestions when entering recipient addresses, or Stack Overflow's drop-down when entering tags for in question composition.

In Gmail, there is a text field for the "To:" address. Once you start typing, a drop-down appears with suggestions. If you enter a semi-colon or comma, you can enter another address. Again, once you start typing this address, a drop-down appears with suggestions.

The suggestions are the subset of your address book containing the text you've entered. (E.g. if you typed "jo" then "John" and "Foojoe" would appear as suggestions, but "XYZ" would not.) The matched part of the word is highlighted in bold.

If you press "enter" or use the up and down cursor keys, you can navigate around the drop-down suggestion list.

I could presumably program this myself, however I have the feeling there must be standard solutions out there I could incorporate. However, all I found were solutions where the value of the field led to the suggestions, and not the value of the current part of the field led to the suggestions (where each part was separated by a separator, for example "," or ";" in the case of Gmail, or space in the case of Stack Overflow tags).

I am using Wicket (Java server-side Web framework) so any Wicket-specific solution would be great, but otherwise I'm sure I can incorporate any plain Javascript library in the project.

答: There is a AutoComplete Component in the Wicketstuff project. There is an Blog on how to use it.</p>


问:
Processing: text won't print only on first activation of mousePressed()
Backstory: Making a whack-a-mole game in Processing. When you click on a mole it prints BOINK above its head and the mole disappears. Running into an issue where on the first click the text won't print. I've triple-checked the location and the fill for the text to no avail.

What confuses me is that if I put a print statement right before the text the print will appear in the console, but if I put any sort of shape before the text it also will not print.

To reiterate, this error is ONLY happening on the first click.

Further testing demonstrated that the same issue occurs with keyPressed, so here is a very short program that demonstrates the error.

```<code>void setup() {
}

void draw() {
    background(0);
}

void keyPressed() {
    textAlign(CENTER);
    textSize(16);
    fill(255, 255, 0);
    println("test");
    text("Test", width / 2, height / 2);
}
</code>```

答:
Keep in mind that the draw() function is called 60 times per second, and each frame you're calling the background() function which clears the screen and draws a black background.

Compare that to the keyPressed() function, which is only called when the user presses a key. In that, you're drawing some text to the screen.

The problem is, the draw() function will then immediately be called and will clear what you just drew.

Instead of using the keyPressed() function, you probably want to use the keyPressed variable in the draw() function, like this:

```<code>void draw(){
   background(255, 0, 0);

   if(keyPressed){
      background(0, 255, 0);
   }
}
</code>```

Shameless self-promotion: I wrote a tutorial on input in Processing available here.

Body:
Backstory: Making a whack-a-mole game in Processing. When you click on a mole it prints BOINK above its head and the mole disappears. Running into an issue where on the first click the text won't print. I've triple-checked the location and the fill for the text to no avail.

What confuses me is that if I put a print statement right before the text the print will appear in the console, but if I put any sort of shape before the text it also will not print.

To reiterate, this error is ONLY happening on the first click.

Further testing demonstrated that the same issue occurs with keyPressed, so here is a very short program that demonstrates the error.

void setup() {
}

void draw() {
    background(0);
}

void keyPressed() {
    textAlign(CENTER);
    textSize(16);
    fill(255, 255, 0);
    println("test");
    text("Test", width / 2, height / 2);
}

Body:
Keep in mind that the draw() function is called 60 times per second, and each frame you're calling the background() function which clears the screen and draws a black background.

Compare that to the keyPressed() function, which is only called when the user presses a key. In that, you're drawing some text to the screen.

The problem is, the draw() function will then immediately be called and will clear what you just drew.

Instead of using the keyPressed() function, you probably want to use the keyPressed variable in the draw() function, like this:

void draw(){
   background(255, 0, 0);

   if(keyPressed){
      background(0, 255, 0);
   }
}

Shameless self-promotion: I wrote a tutorial on input in Processing available here.


问:
Dispatch an action before rendering in react native redux?
I'm trying to log user in with firebase authentication and I ran into this problem that when I use onAuthStateChanged method in action creator to get is user logged in before or not. When users is logged in before so I just call login success and navigate them to main screen, if not I just dispatch another action and show login screen, but I still see login screen for like half a second if login success action dispatched, I'm new to react native and redux, can anyone help me solve this issue, thank you guys so much!!

here is my index.js

```<code>import { checkLogin } from './actions';

class LoginScreen extends Component {
  componentDidMount() {
    this.props.checkLogin();
  }

  componentWillReceiveProps(nextProp) {
    if (nextProp.loggedIn) {
      this.props.navigation.navigate('main');
    }
  }

  //... some code

  render() {
    if (this.props.isChecking) {
      return <Spinner />
    }
    return this.renderContent();
  }
}

const mapStateToProps = ({ auth }) => {
  const { email, password, error, loading, loggedIn, isChecking } = auth;
  return { email, password, error, loading, loggedIn, isChecking };
};

export default connect(mapStateToProps, {
  emailChanged, passwordChanged, emailLogin, checkLogin
})(LoginScreen);
</code>```

and here is my actions.js

```<code>import firebase from 'firebase';

export const checkLogin = () => {
  return(dispatch) => {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        dispatch({ type: EMAIL_LOGIN_SUCCESS, payload: user });
      } else {
        dispatch({ type: CHECK_LOGIN_FAILED });
      }
    })
  }
}

// some code
</code>```

and reducer.js

```<code>const INITIAL_STATE = {
  // ...
  isChecking: true,
}

export default (state = INITIAL_STATE, action) => {
  console.log(action);
  switch (action.type) {
    // ...
    case CHECK_LOGIN_FAILED:
      return { ...state, isChecking: false };
    case EMAIL_LOGIN_SUCCESS:
      return { ...state, user: action.payload, error: '', loading: false, email: '', password: '', loggedIn: true, isChecking: false };
    default:
      return state;
  }
}
</code>```

答: I think this happens because the previous state of isChecking is remembered by your reducer from the previous rendering of your component. I bet if you reset the content and settings of your simulator that you would not first see the login page. However, to fix this I would recommend dispatching an action before firebase.auth().onAuthStateChanged to tell your reducer that you are in an "isChecking" state.</p>

Body:
I'm trying to log user in with firebase authentication and I ran into this problem that when I use onAuthStateChanged method in action creator to get is user logged in before or not. When users is logged in before so I just call login success and navigate them to main screen, if not I just dispatch another action and show login screen, but I still see login screen for like half a second if login success action dispatched, I'm new to react native and redux, can anyone help me solve this issue, thank you guys so much!!

here is my index.js

import { checkLogin } from './actions';

class LoginScreen extends Component {
  componentDidMount() {
    this.props.checkLogin();
  }

  componentWillReceiveProps(nextProp) {
    if (nextProp.loggedIn) {
      this.props.navigation.navigate('main');
    }
  }

  //... some code

  render() {
    if (this.props.isChecking) {
      return <Spinner />
    }
    return this.renderContent();
  }
}

const mapStateToProps = ({ auth }) => {
  const { email, password, error, loading, loggedIn, isChecking } = auth;
  return { email, password, error, loading, loggedIn, isChecking };
};

export default connect(mapStateToProps, {
  emailChanged, passwordChanged, emailLogin, checkLogin
})(LoginScreen);

and here is my actions.js

import firebase from 'firebase';

export const checkLogin = () => {
  return(dispatch) => {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        dispatch({ type: EMAIL_LOGIN_SUCCESS, payload: user });
      } else {
        dispatch({ type: CHECK_LOGIN_FAILED });
      }
    })
  }
}

// some code

and reducer.js

const INITIAL_STATE = {
  // ...
  isChecking: true,
}

export default (state = INITIAL_STATE, action) => {
  console.log(action);
  switch (action.type) {
    // ...
    case CHECK_LOGIN_FAILED:
      return { ...state, isChecking: false };
    case EMAIL_LOGIN_SUCCESS:
      return { ...state, user: action.payload, error: '', loading: false, email: '', password: '', loggedIn: true, isChecking: false };
    default:
      return state;
  }
}


问:
How to solve a RubyMine "'ruby-debug-ide' isn't installed" error
I get the error:

```<code>Cannot start debugger. Gem 'ruby-debug-ide' isn't installed or its executable script 'rdebug-ide' doesn't exist.
</code>```

but all gems were successfuly installed:

```<code>gem 'ruby-debug-ide'
gem 'debase'
</code>```

I can run 'rdebug-ide' manually:

```<code>$ rdebug-ide
Using ruby-debug-base 0.2.1
Usage: rdebug-ide is supposed to be called from RDT, NetBeans, RubyMine, or
       the IntelliJ IDEA Ruby plugin.  The command line interface to
       ruby-debug is rdebug.
</code>```

But when I start debugging, RubyMine asks to install the ruby-debug-ide gem. Why?

And, after installation I get:

```<code>Cannot start debugger. Gem 'ruby-debug-ide' isn't installed or its executable script 'rdebug-ide' doesn't exist.
</code>```

I'm running Mac OS X 10.11.3.

答:
Check ruby SDK's version is right.You can first using rails installer to install everything .

Then using gem to install rdebug for ruby 2+.

Make sure Rubymine's Ruby version is same to which you have installed.With those all done,you will be able to debug ruby.

Body:
I get the error:

Cannot start debugger. Gem 'ruby-debug-ide' isn't installed or its executable script 'rdebug-ide' doesn't exist.

but all gems were successfuly installed:

gem 'ruby-debug-ide'
gem 'debase'

I can run 'rdebug-ide' manually:

$ rdebug-ide
Using ruby-debug-base 0.2.1
Usage: rdebug-ide is supposed to be called from RDT, NetBeans, RubyMine, or
       the IntelliJ IDEA Ruby plugin.  The command line interface to
       ruby-debug is rdebug.

But when I start debugging, RubyMine asks to install the ruby-debug-ide gem. Why?

And, after installation I get:

Cannot start debugger. Gem 'ruby-debug-ide' isn't installed or its executable script 'rdebug-ide' doesn't exist.

I'm running Mac OS X 10.11.3.


问:
The specified path, file name, or both are too long when deploying WebJob to Azure
I've recently upgraded a project to .NET Framework 4.6.1 and now am having issues when trying to deploy to Azure as a WebJob. I'm getting the following error:

C:\Program Files (x86)\Microsoft Visual
  Studio\2017\Community\MSBuild\Microsoft\VisualStudio\v15.0\Web\Microsoft.Web.Publishing.targets(2603,5):
  Error : Copying file
  C:\Users\XXXXXXXXXXX\Documents\Source\Workspaces\XXXXX Server
  Application\ServerApplication\XXXXXXXX.IntegrationService\bin\Release\Microsoft.Extensions.DependencyInjection.Abstractions.dll
  to
  obj\Release\Package\PackageTmp\app_data\jobs\continuous\XXXXXXXXIntegrationService\Microsoft.Extensions.DependencyInjection.Abstractions.dll
  failed. The specified path, file name, or both are too long. The fully
  qualified file name must be less than 260 characters, and the
  directory name must be less than 248 characters.

I'm confused by the error as the path and filename are only 189 characters combined:

C:\Users\XXXXXXXXXXX\Documents\Source\Workspaces\XXXXX Server Application\ServerApplication\XXXXXXXX.IntegrationService\bin\Release\Microsoft.Extensions.DependencyInjection.Abstractions.dll

If I remove the Microsoft.Extensions.DependencyInjection.Abstractions.dll from my project I can then deploy as normal. I've tried cleaning the solution and restarting VS.

答:
I'm confused by the error as the path and filename are only 189 characters combined

That because event if the error as the path and filename are only 189 characters combined in below path:

C:\Users\XXXXXXXXXXX...bin\Release\Microsoft.Extensions.DependencyInjection.Abstractions.dll

But when we publishing the project, VS/MSBuild will copy this file to the path:

obj\Release\Package\PackageTmp\app_data\jobs\continuous\XXXXXXXXIntegrationService\Microsoft.Extensions.DependencyInjection.Abstractions.dll

So the full path and filename should be:

C:\Users\XXXXXXXXXXX\Documents\Source\Workspaces\XXXXX Server
  Application\ServerApplication\XXXXXXXX.IntegrationServiceobj\Release\Package\PackageTmp\app_data\jobs\continuous\XXXXXXXXIntegrationService\Microsoft.Extensions.DependencyInjection.Abstractions.dll

Then the path and file name are about 260 characters combined, so VS/MSBuild could not access that path. To resolve this issue, you can try to move your solutions/projects to the the root directory, like:C:\Workspaces


问:
Css mask shaping & border
I wonder if it is possible for me to do this shape purely with CSS?

I did try it with image mask but the problem was the border so I went on and try with the background image solution but the problem was the background-size by different devices since there will be text contained inside the box.

I wonder if any has done similar shape or if there are any recommended techniques I need to know, I would be appreciated.

Thank you in advanced.

答:
Here's a working demo of a way you could accomplish this shape with just CSS and no images. I added a pseudo-element and absolute positioned it.

Keep in mind that if your body background is a different color, you'll need to change the color in the ::before to keep up the illusion.

Let me know if you have any questions.

#box {
  height: 100px;
  background: #f7f7f7;
  border: 2px solid #e4e4e4;
  border-radius: 10px;
  position: relative;
}

#box::before {
  background: white;
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  width: 35px;
  height: 30px;
  border-radius: 0 0 20px 0;
  border-right: 2px solid #e4e4e4;
  border-bottom: 2px solid #e4e4e4;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="box"></div></code>```

Title: Css mask shaping & border

Body:
Here's a working demo of a way you could accomplish this shape with just CSS and no images. I added a pseudo-element and absolute positioned it.

Keep in mind that if your body background is a different color, you'll need to change the color in the ::before to keep up the illusion.

Let me know if you have any questions.

#box {
  height: 100px;
  background: #f7f7f7;
  border: 2px solid #e4e4e4;
  border-radius: 10px;
  position: relative;
}

#box::before {
  background: white;
  content: '';
  position: absolute;
  top: -2px;
  left: -2px;
  width: 35px;
  height: 30px;
  border-radius: 0 0 20px 0;
  border-right: 2px solid #e4e4e4;
  border-bottom: 2px solid #e4e4e4;
}

<div id="box"></div>


问:
ngOnInit is not triggering after disabling zone.js in Angular 5
I recently upgraded my Angular app from 4.3 to 5.0 and trying to play around some of the new features in it. One of them is removing dependancy from zone.js.

main.ts:

```<code>platformBrowserDynamic().bootstrapModule(AppModule, {
  ngZone: 'noop',
});
</code>```

component:

```<code>import { ApplicationRef, Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs/Rx';

import { MenuService } from '../../services/menu.service';

@Component({
  selector: 'ba-menu',
  templateUrl: './baMenu.html',
  styleUrls: ['./baMenu.scss'],
})
export class BaMenu {
  menuItems: any[];
  protected _menuItemsSub: Subscription;
  protected _onRouteChange: Subscription;

  constructor(public _router: Router, public _service: MenuService, public app: ApplicationRef) {
    console.log('constructor triggered'); //This worked
    this.app.tick();
  }

  ngOnInit(): void {
    console.log('ngOnInit() triggered'); //This doesn't worked
    this._onRouteChange = this._router.events.subscribe((event) => {

      if (event instanceof NavigationEnd) {
        if (this.menuItems) {
          this.selectMenuAndNotify();
        } else {
          // on page load we have to wait as event is fired before menu elements are prepared
          setTimeout(() => this.selectMenuAndNotify());
        }
      }
    });

    this._menuItemsSub = this._service.menuItems.subscribe(this.updateMenu.bind(this));
  }

  public ngOnDestroy(): void {
    console.log('ngOnDestroy() triggered'); //This worked
    this._onRouteChange.unsubscribe();
    this._menuItemsSub.unsubscribe();
  }

}
</code>```

In my component the ngOnDestroy() event is getting fired but ngOnInit() is not getting fired. And since ngOnInit() is not working, _onRouteChange never gets initialized and I get error on line this._onRouteChange.unsubscribe(); inside ngOnDestroy.

Error:

zone.js:690 Unhandled Promise rejection: Cannot read property
  'unsubscribe' of undefined ; Zone:  ; Task: Promise.then ;
  Value: TypeError: Cannot read property 'unsubscribe' of undefined

答:
You haven't implemented OnInit in your component code.

```<code>//Change here
export class BaMenu implements OnInit {
  menuItems: any[];
  protected _menuItemsSub: Subscription;
  protected _onRouteChange: Subscription;

  ngOnInit() {
     //Some code
  }
  //Some code

}
</code>```

Body:
I recently upgraded my Angular app from 4.3 to 5.0 and trying to play around some of the new features in it. One of them is removing dependancy from zone.js.

main.ts:

platformBrowserDynamic().bootstrapModule(AppModule, {
  ngZone: 'noop',
});

component:

import { ApplicationRef, Component } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { Subscription } from 'rxjs/Rx';

import { MenuService } from '../../services/menu.service';

@Component({
  selector: 'ba-menu',
  templateUrl: './baMenu.html',
  styleUrls: ['./baMenu.scss'],
})
export class BaMenu {
  menuItems: any[];
  protected _menuItemsSub: Subscription;
  protected _onRouteChange: Subscription;

  constructor(public _router: Router, public _service: MenuService, public app: ApplicationRef) {
    console.log('constructor triggered'); //This worked
    this.app.tick();
  }

  ngOnInit(): void {
    console.log('ngOnInit() triggered'); //This doesn't worked
    this._onRouteChange = this._router.events.subscribe((event) => {

      if (event instanceof NavigationEnd) {
        if (this.menuItems) {
          this.selectMenuAndNotify();
        } else {
          // on page load we have to wait as event is fired before menu elements are prepared
          setTimeout(() => this.selectMenuAndNotify());
        }
      }
    });

    this._menuItemsSub = this._service.menuItems.subscribe(this.updateMenu.bind(this));
  }

  public ngOnDestroy(): void {
    console.log('ngOnDestroy() triggered'); //This worked
    this._onRouteChange.unsubscribe();
    this._menuItemsSub.unsubscribe();
  }

}

In my component the ngOnDestroy() event is getting fired but ngOnInit() is not getting fired. And since ngOnInit() is not working, _onRouteChange never gets initialized and I get error on line this._onRouteChange.unsubscribe(); inside ngOnDestroy.

Error:

zone.js:690 Unhandled Promise rejection: Cannot read property
  'unsubscribe' of undefined ; Zone:  ; Task: Promise.then ;
  Value: TypeError: Cannot read property 'unsubscribe' of undefined

Body:
You haven't implemented OnInit in your component code.

//Change here
export class BaMenu implements OnInit {
  menuItems: any[];
  protected _menuItemsSub: Subscription;
  protected _onRouteChange: Subscription;

  ngOnInit() {
     //Some code
  }
  //Some code

}


问:
<xsl:apply-templates> usage with <xsl:for-each> using XSLT1.0 transformations
I am new to XSLT and I am struggling with this one.
I have a xml like this:

```<code><rowset>
<row num="l">
<empno>7839</empno>
<ename>KING</ename>
<country>Australia</country>
</row>
<row num="2">
<empno>7788</empno>
<ename>REIJK/ename>
<country>Japan</country>
</row>
</rowset>
</code>```

I need to tranform using XSLT into the below format in HTML:

```<code><hl>Names</hl>
<ul>
<li>KING</li>
<li>REIJK/li>
</ul>
<hl>Countries</hl>
<ul>
<li>Australia</li>
<li>Japan</li>
</ul>
</code>```

I have the below code.I using for-each unable to get the tags.Please would be really appreciated.

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<h1>Names</h1>
<ul>
<li>
<xsl:for-each select="/row/ename">
<xsl:apply-templates select="rowset/row/ename"/>
</xsl:for-each>
</li>
</ul>
<h1>Countries</h1>
<ul>
<li>
<xsl:apply-templates select="rowset/row/country"/>
</li>
</ul>
</xsl:template>
<xsl:template match="/row/ename">
<xsl:value-of select="ename"/>
</xsl:template>
<xsl:template match="/row/country">
<xsl:for-each select="country">
<li>
<xsl:value-of select="country"/>
</li>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

The output for the code I got is below:

```<code><h1>Names</h1>
<ul>
<li/>
</ul>
<h1>Countries</h1>
<ul>
<li>AustraliaJapan</li>
</ul>
</code>```

答:
You're missing rowset from your XPaths where you need it and using it where you don't need it.

You can do this cleanly without for-each. If you want to repeat
 for each name or country, then
 would need to be inside the for-each or template.

When the following is applied to your sample input (with the missing < added)

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <h1>Names</h1>
    <ul>
      <xsl:apply-templates select="rowset/row/ename"/>
    </ul>
    <h1>Countries</h1>
    <ul>
      <xsl:apply-templates select="rowset/row/country"/>
    </ul>
  </xsl:template>

  <xsl:template match="ename | country">
    <li>
      <xsl:value-of select ="."/>
    </li>
  </xsl:template>
</xsl:stylesheet>
</code>```

The result is:

```<code><h1>Names</h1>
<ul>
  <li>KING</li>
  <li>REIJK</li>
</ul>
<h1>Countries</h1>
<ul>
  <li>Australia</li>
  <li>Japan</li>
</ul>
</code>```

Body:
I am new to XSLT and I am struggling with this one.
I have a xml like this:

<rowset>
<row num="l">
<empno>7839</empno>
<ename>KING</ename>
<country>Australia</country>
</row>
<row num="2">
<empno>7788</empno>
<ename>REIJK/ename>
<country>Japan</country>
</row>
</rowset>

I need to tranform using XSLT into the below format in HTML:

<hl>Names</hl>

KING

REIJK/li>

<hl>Countries</hl>

Australia

Japan

I have the below code.I using for-each unable to get the tags.Please would be really appreciated.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">

Names

<xsl:for-each select="/row/ename">
<xsl:apply-templates select="rowset/row/ename"/>
</xsl:for-each>

Countries

<xsl:apply-templates select="rowset/row/country"/>

</xsl:template>
<xsl:template match="/row/ename">
<xsl:value-of select="ename"/>
</xsl:template>
<xsl:template match="/row/country">
<xsl:for-each select="country">

<xsl:value-of select="country"/>

</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

The output for the code I got is below:

Names

Countries

AustraliaJapan

Body:
You're missing rowset from your XPaths where you need it and using it where you don't need it.

You can do this cleanly without for-each. If you want to repeat <li> for each name or country, then <li> would need to be inside the for-each or template.

When the following is applied to your sample input (with the missing < added)

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
  <xsl:output method="html"/>
  <xsl:template match="/">
    <h1>Names</h1>
    <ul>
      <xsl:apply-templates select="rowset/row/ename"/>
    </ul>
    <h1>Countries</h1>
    <ul>
      <xsl:apply-templates select="rowset/row/country"/>
    </ul>
  </xsl:template>

  <xsl:template match="ename | country">
    <li>
      <xsl:value-of select ="."/>
    </li>
  </xsl:template>
</xsl:stylesheet>

The result is:

<h1>Names</h1>
<ul>
  <li>KING</li>
  <li>REIJK</li>
</ul>
<h1>Countries</h1>
<ul>
  <li>Australia</li>
  <li>Japan</li>
</ul>