问:
Error encrypting webm video with webm crypt
I'm trying to use the example here for Clearkey encryption for videos. As per the steps mentioned here I was able to download and build the encryption tool wemb_crypt but When I try to encrypt the file with

```<code>webm_crypt -i input.webm -o input-enc_bear1_0123456789012345.webm -video true -audio true -video_options content_id=0123456789012345,base_file=bear1.key -audio_options content_id=0123456789012345,base_file=bear1.key
</code>```

I get this error

File: input.webm is not WebM file.Could not open WebM files.

Tried many different webm files with no luck.

Is there another way to encrypt clear key media with other tools? Any clue about the error above?

答:
You can use ffmpeg and openssl to create an AES encrypted HLS stream - the ffmpeg documentation (http://ffmpeg.org/ffmpeg-all.html#Options-34) includes this example script:

#!/bin/sh
BASE_URL=${1:-'.'}
openssl rand 16 > file.key
echo $BASE_URL/file.key > file.keyinfo
echo file.key >> file.keyinfo
echo $(openssl rand -hex 16) >> file.keyinfo
ffmpeg -f lavfi -re -i testsrc -c:v h264 -hls_flags delete_segments \
  -hls_key_info_file file.keyinfo out.m3u8
```

You can also use mp4Box (https://gpac.wp.imt.fr/mp4box/encryption/common-encryption/) to create basic clear DASH encryptions:

MP4Box -crypt drm_file.xml movie.mp4 -out movie_encrypted.mp4

The drm info is included in the drm_file.xml and is explained at the link above.

Body:
I'm trying to use the example here for Clearkey encryption for videos. As per the steps mentioned here I was able to download and build the encryption tool wemb_crypt but When I try to encrypt the file with

webm_crypt -i input.webm -o input-enc_bear1_0123456789012345.webm -video true -audio true -video_options content_id=0123456789012345,base_file=bear1.key -audio_options content_id=0123456789012345,base_file=bear1.key

I get this error

File: input.webm is not WebM file.Could not open WebM files.

Tried many different webm files with no luck.

Is there another way to encrypt clear key media with other tools? Any clue about the error above?

Body:
You can use ffmpeg and openssl to create an AES encrypted HLS stream - the ffmpeg documentation (http://ffmpeg.org/ffmpeg-all.html#Options-34) includes this example script:

#!/bin/sh
BASE_URL=${1:-'.'}
openssl rand 16 > file.key
echo $BASE_URL/file.key > file.keyinfo
echo file.key >> file.keyinfo
echo $(openssl rand -hex 16) >> file.keyinfo
ffmpeg -f lavfi -re -i testsrc -c:v h264 -hls_flags delete_segments \
  -hls_key_info_file file.keyinfo out.m3u8

You can also use mp4Box (https://gpac.wp.imt.fr/mp4box/encryption/common-encryption/) to create basic clear DASH encryptions:

MP4Box -crypt drm_file.xml movie.mp4 -out movie_encrypted.mp4

The drm info is included in the drm_file.xml and is explained at the link above.


来源: stackexchange

问:
How to start a thread to keep GUI refreshed?
I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed, I cannot even move the window.

So the question is how to start the thread, so it won't interfere with GUI, i.e. so the GUI would always be up to date (while processing I change the data, and GUI displays some pieces of it)?

That is how I start thread currectly:

```<code>        var thread = new Thread(doLearn);
        thread.IsBackground = true;
        thread.Start();
</code>```

Edit 1

Jon:

I don't use any locks at all

No Join calling

The UI thread is left alone -- it simply sits there

The processing is a big loop with math operations, not even allocating memory, on UI side I have controls with binding (WPF) to data, like the number of current iteration of the main loop. It should be refreshed each time the main loop "ticks". The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

Edit 2 -- Almost there!

Ok, so Jon hit the nail at the head (who is surprises? ;-D) -- thank you! The problem comes from changing the Counter. When I used instead the Counter, local counter the GUI was refreshed -- I mean I could move windows, but... I couldn't see display of the Counter.

What I have here -- a WPF GUI, with such data-binding

```<code><TextBlock Text="{Binding Path=Counter"/>
</code>```

and I have Counter property of course which on each change sends event PropertyChanged. One of the listeners is for sure GUI.

So, Jon answer is valid "the answer", but from good design POV not exactly, because if GUI part has to pull up the info about Counter and update the display every (let's say) 3 seconds, why would anyone use data binding? For me such approach invalidates data binding idea.

I could, theoretically, pass to the processing thread the GUI dispatcher, and do all the sending in GUI thread, and it could work (I didn't try it) but it would mean tight coupling of non-GUI part and GUI part.

So far, I have no idea how to do it "right" way. The best guess so far is to create TimerDispatcher but not at GUI side but inside the processing library, and update Counter value immediately but do all the sending from time to time (I didn't try it yet though).

Small remark: I have more properties binded actually, like IsRunning, which is changed at the beginning and at the end of processing. And those changes DO affect the display correctly -- but the Counter change triggers around 3000 notifications in 3-4 seconds. So it looks like jamming problem. I did another test -- I killed the data binding partially, so notifications were sent, but GUI was not "receiving" them -- but was listening to them. In such case the GUI was also frozen.

So, I am still listening to all advices -- thank you advance for sharing.

Edit 3

The saga continues here:

How to do the processing and keep GUI refreshed using databinding?

答:
It should be fine as it is. Things which may be freezing your UI:

Are you locking within the UI thread, and locking on the same lock in your other thread?

Are you calling Join on the thread from your UI thread?

Are you doing some other heavy work in the UI thread?

If you could come up with a short but complete program which shows the problem, I'm sure we could help to fix it... but it certainly should be okay.

EDIT: Okay, now you've added this:

The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

So you're updating the property from the non-UI thread? I would expect that to cause problems, because it will trigger UI changes from the wrong thread.

I suggest you take an approach such as:

Periodically update the counter via Dispatcher.BeginInvoke

Have the "UI counter" and the "worker counter" - and copy the value from the "worker counter" to the "UI counter" in the UI thread via a DispatcherTimer, essentially polling it.

ContentLicense: CC BY-SA 2.5

Body:
I have window with button which triggers lengthy processing. I put processing in a separate thread, but -- to my surprise -- it makes GUI frozen anyway. No control is refreshed, I cannot even move the window.

So the question is how to start the thread, so it won't interfere with GUI, i.e. so the GUI would always be up to date (while processing I change the data, and GUI displays some pieces of it)?

That is how I start thread currectly:

        var thread = new Thread(doLearn);
        thread.IsBackground = true;
        thread.Start();

Edit 1

Jon:

I don't use any locks at all

No Join calling

The UI thread is left alone -- it simply sits there

The processing is a big loop with math operations, not even allocating memory, on UI side I have controls with binding (WPF) to data, like the number of current iteration of the main loop. It should be refreshed each time the main loop "ticks". The counter of the loop is a property which triggers OnPropertyChanged with each change (classic WPF binding).

Edit 2 -- Almost there!

Ok, so Jon hit the nail at the head (who is surprises? ;-D) -- thank you! The problem comes from changing the Counter. When I used instead the Counter, local counter the GUI was refreshed -- I mean I could move windows, but... I couldn't see display of the Counter.

What I have here -- a WPF GUI, with such data-binding

<TextBlock Text="{Binding Path=Counter"/>

and I have Counter property of course which on each change sends event PropertyChanged. One of the listeners is for sure GUI.

So, Jon answer is valid "the answer", but from good design POV not exactly, because if GUI part has to pull up the info about Counter and update the display every (let's say) 3 seconds, why would anyone use data binding? For me such approach invalidates data binding idea.

I could, theoretically, pass to the processing thread the GUI dispatcher, and do all the sending in GUI thread, and it could work (I didn't try it) but it would mean tight coupling of non-GUI part and GUI part.

So far, I have no idea how to do it "right" way. The best guess so far is to create TimerDispatcher but not at GUI side but inside the processing library, and update Counter value immediately but do all the sending from time to time (I didn't try it yet though).

Small remark: I have more properties binded actually, like IsRunning, which is changed at the beginning and at the end of processing. And those changes DO affect the display correctly -- but the Counter change triggers around 3000 notifications in 3-4 seconds. So it looks like jamming problem. I did another test -- I killed the data binding partially, so notifications were sent, but GUI was not "receiving" them -- but was listening to them. In such case the GUI was also frozen.

So, I am still listening to all advices -- thank you advance for sharing.

Edit 3

The saga continues here:

How to do the processing and keep GUI refreshed using databinding?


问:
Run a query from access via excel VBA - Runtime error 1004 - SQL Syntax Error
Trying to edit some old code left by a previous employee and move to over to an updated system, but by simply copying the code that was wrote originally I get the Runtime Error '1004' - SQL Syntax Error. A copy of the code is below if anyone would like to point me in the right direction??

The part in bold seems to be where it errors...

```<code>Sub MIMacro()
'
'
    Sheets("MI_Report").Select
    Cells.Select
    Selection.ClearContents

    Dim StartDate As String

    Sheets("Date").Select

    StartDate = Range("D2").Value & "-" & Range("C2").Value & "-" & Range("B2").Value & " 00:00:00"

    Dim EndDate As String

    EndDate = Range("D3").Value & "-" & Range("C3").Value & "-" & Range("B3").Value & " 00:00:00"

    Sheets("MI_Report").Select

    Dim MySql As String
    MySql = "SELECT * FROM `W:\MI Reports\Imprint Reports.mdb`.XGSNOR_MI Katie L XGSNOR_MI Katie L WHERE (XGSNOR_MI Katie L.DelDate>={ts '" & StartDate & "'} And XGSNOR_MI Katie L.DelDate<={ts '" & EndDate & "'}) ORDER BY XGSNOR_MI Katie L.JobNo"

    With ActiveSheet.QueryTables.Add(Connection:=Array(Array( _
        "ODBC;DSN=MS Access Database;DBQ=W:\MI Reports\Imprint Reports.mdb;DefaultDir=W:\MI Reports;DriverId=25;FIL=MS Access;MaxBufferS" _
        ), Array("ize=2048;PageTimeout=5;")), Destination:=Range("A1"))
        .CommandText = Array(MySql)
        .Name = "Query from MS Access Database"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = True
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlOverwriteCells
        .SavePassword = True
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        **.Refresh BackgroundQuery:=False**
    End With

    Columns("E:E").Select
    Selection.NumberFormat = "General"
    Columns("C:C").Select
    Selection.NumberFormat = "m/d/yyyy"

    Range("A1").Select
    Selection.End(xlDown).Select
    lr1 = Selection.Row

    Range("G1").Select
    ActiveCell.FormulaR1C1 = "Cost"
    Range("H1").Select
    ActiveCell.FormulaR1C1 = "Total Pick Cost"
    Range("G2").Select

    Dim cost As Double
    Dim extra As Double
    Dim total As Double

    cost = 7#
    extra = 0.9
    total = 0#
    temp = "neworder"

    Dim e As Integer
    For e = 2 To lr1

        If temp = "neworder" Then
            temp = Range("A" & e).Value
            Range("G" & e).Select
            ActiveCell.FormulaR1C1 = cost
            total = total + cost
        Else
            temp = Range("A" & e).Value
            Range("G" & e).Select
            ActiveCell.FormulaR1C1 = extra
            total = total + extra
        End If

        temp2 = Range("A" & e + 1).Value

        If temp <> temp2 Then
            temp = "neworder"
            Range("H" & e).Select
            ActiveCell.FormulaR1C1 = total
            total = 0
        End If

    Next e

    Columns("G:H").Select
    Selection.NumberFormat = "$#,##0.00"

    Range("A1").Select

End Sub
</code>```

答:
I'm not that familiar with ODBC sequences that are used in that query, so no guarantees this will work:

Replace the MySql = line with

MySql = "SELECT * FROM [XGSNOR_MI Katie L] WHERE ([XGSNOR_MI Katie L].DelDate>={ts '" & StartDate & "'} And [XGSNOR_MI Katie L].DelDate<={ts '" & EndDate & "'}) ORDER BY [XGSNOR_MI Katie L].JobNo"

Also: the following lines should be corrected:

```<code>With ActiveSheet.QueryTables.Add(Connection:= _
        "ODBC;DSN=MS Access Database;DBQ=W:\MI Reports\Imprint Reports.mdb;DefaultDir=W:\MI Reports;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;", _
         Destination:=Range("A1"))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Trying to edit some old code left by a previous employee and move to over to an updated system, but by simply copying the code that was wrote originally I get the Runtime Error '1004' - SQL Syntax Error. A copy of the code is below if anyone would like to point me in the right direction??

The part in bold seems to be where it errors...

Sub MIMacro()
'
'
    Sheets("MI_Report").Select
    Cells.Select
    Selection.ClearContents

    Dim StartDate As String

    Sheets("Date").Select

    StartDate = Range("D2").Value & "-" & Range("C2").Value & "-" & Range("B2").Value & " 00:00:00"

    Dim EndDate As String

    EndDate = Range("D3").Value & "-" & Range("C3").Value & "-" & Range("B3").Value & " 00:00:00"

    Sheets("MI_Report").Select

    Dim MySql As String
    MySql = "SELECT * FROM `W:\MI Reports\Imprint Reports.mdb`.XGSNOR_MI Katie L XGSNOR_MI Katie L WHERE (XGSNOR_MI Katie L.DelDate>={ts '" & StartDate & "'} And XGSNOR_MI Katie L.DelDate<={ts '" & EndDate & "'}) ORDER BY XGSNOR_MI Katie L.JobNo"

    With ActiveSheet.QueryTables.Add(Connection:=Array(Array( _
        "ODBC;DSN=MS Access Database;DBQ=W:\MI Reports\Imprint Reports.mdb;DefaultDir=W:\MI Reports;DriverId=25;FIL=MS Access;MaxBufferS" _
        ), Array("ize=2048;PageTimeout=5;")), Destination:=Range("A1"))
        .CommandText = Array(MySql)
        .Name = "Query from MS Access Database"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = True
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlOverwriteCells
        .SavePassword = True
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        **.Refresh BackgroundQuery:=False**
    End With

    Columns("E:E").Select
    Selection.NumberFormat = "General"
    Columns("C:C").Select
    Selection.NumberFormat = "m/d/yyyy"

    Range("A1").Select
    Selection.End(xlDown).Select
    lr1 = Selection.Row

    Range("G1").Select
    ActiveCell.FormulaR1C1 = "Cost"
    Range("H1").Select
    ActiveCell.FormulaR1C1 = "Total Pick Cost"
    Range("G2").Select

    Dim cost As Double
    Dim extra As Double
    Dim total As Double

    cost = 7#
    extra = 0.9
    total = 0#
    temp = "neworder"

    Dim e As Integer
    For e = 2 To lr1

        If temp = "neworder" Then
            temp = Range("A" & e).Value
            Range("G" & e).Select
            ActiveCell.FormulaR1C1 = cost
            total = total + cost
        Else
            temp = Range("A" & e).Value
            Range("G" & e).Select
            ActiveCell.FormulaR1C1 = extra
            total = total + extra
        End If

        temp2 = Range("A" & e + 1).Value

        If temp <> temp2 Then
            temp = "neworder"
            Range("H" & e).Select
            ActiveCell.FormulaR1C1 = total
            total = 0
        End If

    Next e

    Columns("G:H").Select
    Selection.NumberFormat = "$#,##0.00"

    Range("A1").Select

End Sub

Body:
I'm not that familiar with ODBC sequences that are used in that query, so no guarantees this will work:

Replace the MySql = line with

MySql = "SELECT * FROM [XGSNOR_MI Katie L] WHERE ([XGSNOR_MI Katie L].DelDate>={ts '" & StartDate & "'} And [XGSNOR_MI Katie L].DelDate<={ts '" & EndDate & "'}) ORDER BY [XGSNOR_MI Katie L].JobNo"

Also: the following lines should be corrected:

With ActiveSheet.QueryTables.Add(Connection:= _
        "ODBC;DSN=MS Access Database;DBQ=W:\MI Reports\Imprint Reports.mdb;DefaultDir=W:\MI Reports;DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;", _
         Destination:=Range("A1"))


问:
How do i exit the program when i type a specific word, in my case "end"?
I'm having a problem. I'm currently doing a school project for a ChatBot. This is a game section for the chatbot. It's a word scramble game. I can enter the wrong answer and the program would prompt me to retype the answer. But, if I type the correct answer, the program just stops there, the program didn't stop.

What I would like to do is to repeat the code, like keeping playing the game, until I type the word "end", but I don't know how to implement it. Also, most of the words kept repeating. For example, the word [animal] would usually be scrambled into [anialm].

So I would like to get some help on improving the code too. Thank you very much!! I am still a Year 1 who just started learning to program.

```<code>public static void main(String[] args) {
        Scanner userinput = new Scanner(System.in);
        String guess = "";
        String scramble = "";
        String[] questions = {"animal", "duck", "dinosaur", "butterfly", "dog", "horse", "cow", "cat", "elephant", "crocodile", "alligator"};
        char charArr[] = null;
        String wordToGuess = questions[new Random().nextInt(questions.length)];// questions[0]

        for (int a = 0; a < wordToGuess.length(); a++) {
            charArr = wordToGuess.toCharArray();  //0a 1n 2i 3m 4a 5l 6s
            //generating a random number from the length of word to guess. Example: Animal, generated no = "1"
            int rdm = new Random().nextInt(charArr.length);
            //shuffling the words
            char temp = charArr[a];     //charArr[0] is the letter "A" which is moved to temp
            charArr[a] = charArr[rdm];  //A is then moved to charArr[rdm] which is index 1, so the word is currently "AAimals'
            charArr[rdm] = temp;        //charArr[1] contains n which is then moved to temmp, which is 0, becoming nAimal
        }
        scramble = new String(charArr);
        System.out.println("Your word is: " + scramble);

        do {
            while (!guess.equals(wordToGuess)) {
                System.out.print(">>> ");
                guess = userinput.nextLine();
                if (!guess.equals(wordToGuess)) {
                    System.out.print(">>> ");
                    System.out.println("Please try again!");
                } else {
                    System.out.println(">>> Great Job getting the answer!");
                }
            }
        }while (!guess.equalsIgnoreCase("end"));
    }
}
</code>```

答:
Use break; statement to end loop.

```<code>if(guess.equalsIgnoreCase("end")){
     break;
  }
</code>```

Body:
I'm having a problem. I'm currently doing a school project for a ChatBot. This is a game section for the chatbot. It's a word scramble game. I can enter the wrong answer and the program would prompt me to retype the answer. But, if I type the correct answer, the program just stops there, the program didn't stop.

What I would like to do is to repeat the code, like keeping playing the game, until I type the word "end", but I don't know how to implement it. Also, most of the words kept repeating. For example, the word [animal] would usually be scrambled into [anialm].

So I would like to get some help on improving the code too. Thank you very much!! I am still a Year 1 who just started learning to program.

public static void main(String[] args) {
        Scanner userinput = new Scanner(System.in);
        String guess = "";
        String scramble = "";
        String[] questions = {"animal", "duck", "dinosaur", "butterfly", "dog", "horse", "cow", "cat", "elephant", "crocodile", "alligator"};
        char charArr[] = null;
        String wordToGuess = questions[new Random().nextInt(questions.length)];// questions[0]

        for (int a = 0; a < wordToGuess.length(); a++) {
            charArr = wordToGuess.toCharArray();  //0a 1n 2i 3m 4a 5l 6s
            //generating a random number from the length of word to guess. Example: Animal, generated no = "1"
            int rdm = new Random().nextInt(charArr.length);
            //shuffling the words
            char temp = charArr[a];     //charArr[0] is the letter "A" which is moved to temp
            charArr[a] = charArr[rdm];  //A is then moved to charArr[rdm] which is index 1, so the word is currently "AAimals'
            charArr[rdm] = temp;        //charArr[1] contains n which is then moved to temmp, which is 0, becoming nAimal
        }
        scramble = new String(charArr);
        System.out.println("Your word is: " + scramble);

        do {
            while (!guess.equals(wordToGuess)) {
                System.out.print(">>> ");
                guess = userinput.nextLine();
                if (!guess.equals(wordToGuess)) {
                    System.out.print(">>> ");
                    System.out.println("Please try again!");
                } else {
                    System.out.println(">>> Great Job getting the answer!");
                }
            }
        }while (!guess.equalsIgnoreCase("end"));
    }
}

Body:
Use break; statement to end loop.

if(guess.equalsIgnoreCase("end")){
     break;
  }


问:
How to debug a "String index out of range" error in a Java program?
```<code>["Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]
</code>```

And here is my code. Why did I get this error?

```<code>import java.util.Scanner;

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) {
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i);
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);

    }

}
</code>```

答:
String.length() returns the length of the string, but with zero based indexes, you cannot use this as a character index.
Try something like this:

```<code>for ( i = Wort.length()-1; i >= 0; i-- )
{
    WortRev = WortRev +  Wort.charAt(i);
}
</code>```

Body:
["Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
    at java.lang.String.charAt(Unknown Source)
    at Haupt.main(Haupt.java:21)"]

And here is my code. Why did I get this error?

import java.util.Scanner;

public class Haupt {

    public static void main(String[] args) {
        String Wort="";
        String WortCpy="";
        String WortRev="";
        int i=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Geben Sie ein Wort ein : "); //Ausgabe
        Wort = scan.nextLine(); //Eingabe
        scan.close();
        for(i=0;i < Wort.length();i++) {
            WortCpy= WortCpy +  Wort.charAt(i); //Speichert jeden Buchstaben einzeln in Wortcpy ab
        }
        for(i=Wort.length();i>=0;i--) {
            WortRev = WortRev +  Wort.charAt(i);
        }

        System.out.println("Wort : " + Wort);
        System.out.println("Wort Kopiert : " + WortCpy);
        System.out.println("Wort umgedreht : " + WortRev);

    }

}

Body:
String.length() returns the length of the string, but with zero based indexes, you cannot use this as a character index.
Try something like this:

for ( i = Wort.length()-1; i >= 0; i-- )
{
    WortRev = WortRev +  Wort.charAt(i);
}


问:
SASS create attribute dynamically by other attribute value
I want to create an attribute depending on the value of an other attribute.

The data-active-nav will be set dynamically, so for an example we have:

HTML:

```<code><div data-active-nav="user">
    <div data-nav="user"></div>
    <div data-nav="admin"></div>
</div>
</code>```

Now I want to style the inner div's depending on the attribute, but I don't want to write a style for each.

I want something like this:

```<code>[data-nav=#{attr(data-active-nav)}] {
    color: black;
}
</code>```

But the output of this will be

```<code>[data-nav='attr(data-active-nav)']
</code>```

Is there a way to do this, without writing

```<code>[data-active-nav=user] {
    [data-nav=user] {
        color: black;
    }
}

[data-active-nav=admin] {
    [data-nav=admin] {
        color: black;
    }
}
</code>```

答:
Sass has no way of knowing anything about your dom.
Sass is a preprocessor, this mean that it generate pure CSS, it is not a dynamic language.

this mean that sass cannot figure out the value off a data-attribute. Only CSS can.

In CSS I think that you can only use, attr() for a property value, and even this is experimental, and will not be widely supported by the browsers. Today, it's only pretty safe to use it in content property for a pseudo-element.

so the short answer is no, you cannot.

In the other hand, I don't see why you are trying to style éléments using data attributes since there goal is to store data, and not determine style…
Also, they are slower selectors than classes. but I guess it's not the subject.

I would recommend :

```<code><nav class="nav is-user-active">
    <div class="nav__item nav__item--user">user</div>
    <div class="nav__item nav__item--other">other</div>
</nav>
</code>```

sass (in BEM fashion):

```<code>.nav__item {
   color: blue;

   .is-user-active &--user,
   .is-other-active &--other {
       color: black;
   }
}
</code>```

this will compile into :

```<code>.nav__item {
   color: blue;
}

.is-user-active .nav__item--user,
.is-other-active .nav__item--other {
    color: black;
}
</code>```

but if you really want to use data-attr, you can folow the same pattern:

```<code>   [data-nav-active="user"] [nav-item="user"],
   [data-nav-active="other"] [nav-item="other"] {
       color: black;
   }
</code>```

Body:
I want to create an attribute depending on the value of an other attribute.

The data-active-nav will be set dynamically, so for an example we have:

HTML:

Now I want to style the inner div's depending on the attribute, but I don't want to write a style for each.

I want something like this:

[data-nav=#{attr(data-active-nav)}] {
    color: black;
}

But the output of this will be

[data-nav='attr(data-active-nav)']

Is there a way to do this, without writing

[data-active-nav=user] {
    [data-nav=user] {
        color: black;
    }
}

[data-active-nav=admin] {
    [data-nav=admin] {
        color: black;
    }
}

Body:
Sass has no way of knowing anything about your dom.
Sass is a preprocessor, this mean that it generate pure CSS, it is not a dynamic language.

this mean that sass cannot figure out the value off a data-attribute. Only CSS can.

In CSS I think that you can only use, attr() for a property value, and even this is experimental, and will not be widely supported by the browsers. Today, it's only pretty safe to use it in content property for a pseudo-element.

so the short answer is no, you cannot.

In the other hand, I don't see why you are trying to style éléments using data attributes since there goal is to store data, and not determine style…
Also, they are slower selectors than classes. but I guess it's not the subject.

I would recommend :

<nav class="nav is-user-active">
    <div class="nav__item nav__item--user">user</div>
    <div class="nav__item nav__item--other">other</div>
</nav>

sass (in BEM fashion):

.nav__item {
   color: blue;

   .is-user-active &--user,
   .is-other-active &--other {
       color: black;
   }
}

this will compile into :

.nav__item {
   color: blue;
}

.is-user-active .nav__item--user,
.is-other-active .nav__item--other {
    color: black;
}

but if you really want to use data-attr, you can folow the same pattern:

   [data-nav-active="user"] [nav-item="user"],
   [data-nav-active="other"] [nav-item="other"] {
       color: black;
   }


问:
jqgrid - refresh a grid after an ajax file upload
How would I refresh a jqgrid based grid from outside of the grid itself? Within the code for a grid exists the option to call reloadGrid. However, I want to reload the grid after doing an ajax file upload, outside of the jqgrid code. How could I call reloadGrid in that context?

I realize I can completely reload the entire page with something like: location.reload(); but that reloads the whole lot and puts me back to the first page of results for a grid and kind of defeats the purpose of using ajax to upload a file in the first place.

Some code:

reloadGrid is called from within jqgrid as follows:

$("#thegrid").trigger("reloadGrid");

but it does nothing when called from within my ajaxupload:

```<code>        onComplete: function(file, response) {
            if (response == 'success') {
                        //location.reload();
                        $("#thegrid").trigger("reloadGrid");
                    }else if (response == 'error') {
                        alert("Doh!");
                    }
</code>```

If I uncomment location.reload(), the page reloads but with the trigger uncommented (as in the above example) nothing happens at all. So how do I reload this grid?

答:
Make a function of the code to load the jqgrid.
And unload the Jqgrid first, and call the previous function:

```<code>$("#thegrid").GridUnload();
Loadthegrid();
</code>```

I hope this helps.

Body:
How would I refresh a jqgrid based grid from outside of the grid itself? Within the code for a grid exists the option to call reloadGrid. However, I want to reload the grid after doing an ajax file upload, outside of the jqgrid code. How could I call reloadGrid in that context?

I realize I can completely reload the entire page with something like: location.reload(); but that reloads the whole lot and puts me back to the first page of results for a grid and kind of defeats the purpose of using ajax to upload a file in the first place.

Some code:

reloadGrid is called from within jqgrid as follows:

$("#thegrid").trigger("reloadGrid");

but it does nothing when called from within my ajaxupload:

        onComplete: function(file, response) {
            if (response == 'success') {
                        //location.reload();
                        $("#thegrid").trigger("reloadGrid");
                    }else if (response == 'error') {
                        alert("Doh!");
                    }

If I uncomment location.reload(), the page reloads but with the trigger uncommented (as in the above example) nothing happens at all. So how do I reload this grid?

Body:
Make a function of the code to load the jqgrid.
And unload the Jqgrid first, and call the previous function:

$("#thegrid").GridUnload();
Loadthegrid();

I hope this helps.


问:
Best way to check if column returns a null value (from database to .net application)
I have a table with a DateTime column
the column can have NULL values

Now I connect to the database using an ODBC connection and get the value into a DataTable in .net / c#.

I am able to check it for NULL by going

```<code>if(String.IsNullOrEmpty(table.rows[0][0].ToString())
{
     //Whatever I want to do
}
</code>```

Is String.IsNullOrEmpty the correct way to check for null values.

答:
If we are using EF and reading the database element in while loop then,</p>

```<code>   using( var idr = connection, SP.......)
   {
       while(idr.read())
       {
          if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
          //do something
       }
   }
</code>```

Body:
I have a table with a DateTime column
the column can have NULL values

Now I connect to the database using an ODBC connection and get the value into a DataTable in .net / c#.

I am able to check it for NULL by going

if(String.IsNullOrEmpty(table.rows[0][0].ToString())
{
     //Whatever I want to do
}

Is String.IsNullOrEmpty the correct way to check for null values.

Body:
If we are using EF and reading the database element in while loop then,

   using( var idr = connection, SP.......)
   {
       while(idr.read())
       {
          if(String.IsNullOrEmpty(idr["ColumnNameFromDB"].ToString())
          //do something
       }
   }

ContentLicense: CC BY-SA 4.0


问:
Use angularjs expression bindings with downgraded angular
Say i have a checkbox directive i'm rewriting to angular from angularjs

checkbox.directive.js (angularjs)

```<code>template: `<some html> ...`,
scope: { checked: '=', onChecked: '&' }
</code>```

checkbox.component.ts (angular)

```<code>@Component({
  selector: 'checkbox',
  templateUrl: '<some html> ...',
  ...
})
export class CheckboxComponent implements OnInit {
  @Input() checked: boolean;
  @Output() checkedChange = new EventEmitter<boolean>();
  @Output() onCheckedChange = new EventEmitter<boolean>();
  ...
</code>```

How can i bind to the expression binding (&) from not yet upgraded components?

not-yet-upgraded.directive.js (angularjs)

```<code>template: '<checkbox (onChecked)="foo()"> ...',
controller: function($scope) {
   $scope.foo = function() { console.log("change happened"); }
}
</code>```

答:
As it turns out, I had two mistakes

Outputs of events doesn't need the Change-suffix unless it's a two-way binding

The angularjs consumer uses kebab-casing

so:

1.
angular component @Output() onChecked<s>Change</s> = new EventEmitter();

2.
angularjs dom <checkbox (on-checked)="foo()"> ...

Body:
Say i have a checkbox directive i'm rewriting to angular from angularjs

checkbox.directive.js (angularjs)

template: `<some html> ...`,
scope: { checked: '=', onChecked: '&' }

checkbox.component.ts (angular)

@Component({
  selector: 'checkbox',
  templateUrl: '<some html> ...',
  ...
})
export class CheckboxComponent implements OnInit {
  @Input() checked: boolean;
  @Output() checkedChange = new EventEmitter<boolean>();
  @Output() onCheckedChange = new EventEmitter<boolean>();
  ...

How can i bind to the expression binding (&) from not yet upgraded components?

not-yet-upgraded.directive.js (angularjs)

template: '<checkbox (onChecked)="foo()"> ...',
controller: function($scope) {
   $scope.foo = function() { console.log("change happened"); }
}


问:
Format Chart.JS Data Element To Be Currency
I found that you can format the x or y axis of Chart.JS to currency by a quick JavaScript callback function

```<code>callback: function(value, index, values) {
    if (parseInt(value) >= 1000) {
        return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    } else {
        return '$' + value;
    }
}
}
</code>```

but this does not seem to be the case for the data:  In my instance this is a JavaScript 1D Array that holds numeric values, and I want to add a dollar sign, and comma where applicable.  How can this be added with Charts.jS

EDIT

This is how I am populating my JSON array - and I want to format the data in the data: values

```<code>var barChartData = {
    labels: labelsarr,
    datasets: [{
        label: 'Amount',
        backgroundColor: 'rgba(200, 200, 200, 0.75)',
        borderColor: 'rgb(255, 99, 132)',
        borderWidth: 1,
        data: values
    }]

};
</code>```

And the JSON array is in this format ["AAAA",100,10000,2310,24420,30,50000,400000,70000,700,823200,923200,1111]

I want to format starting at index[1] to show $ and currency.  How can this be achieved?

2nd Edit Time

I try to add title and format both data points and left axis as currency with below syntax, but this no longer displays anything on my page.

```<code>var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labelsarr,
        datasets: [{
            label: 'Test',
            data: values,
            backgroundColor: 'rgba(0, 119, 204, 0.8)',
        }]
    },
    options: {
        responsive: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    callback: function(value, index, values) {
                        if (parseInt(value) >= 1000) {
                            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                        } else {
                            return '$' + value;
                        }
                    }
                }
            }]
        },
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: '<?php echo $name ?> Test'
        }
        tooltips: {
            callbacks: {
                label: function(t, d) {
                    var xLabel = d.datasets[t.datasetIndex].label;
                    var yLabel = t.yLabel >= 1000 ?
                        '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") :
                        '$' + t.yLabel;
                    return xLabel + ': ' + yLabel;
                }
            }
        }
    }
});
</code>```

答:
This can be achieved using the following tool-tips label callback function ...

```<code>tooltips: {
   callbacks: {
      label: function(t, d) {
         var xLabel = d.datasets[t.datasetIndex].label;
         var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
         return xLabel + ': ' + yLabel;
      }
   }
}
</code>```

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var labelsarr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
var values = ["AAAA", 100, 10000, 2310, 24420, 30, 50000, 400000, 70000, 700, 823200, 923200, 1111];

var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: labelsarr,
      datasets: [{
         label: 'Amount',
         data: values,
         backgroundColor: 'rgba(0, 119, 204, 0.8)',
      }]
   },
   options: {
      tooltips: {
         callbacks: {
            label: function(t, d) {
               var xLabel = d.datasets[t.datasetIndex].label;
               var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
               return xLabel + ': ' + yLabel;
            }
         }
      },
      scales: {
         yAxes: [{
            ticks: {
               callback: function(value, index, values) {
                  if (parseInt(value) >= 1000) {
                     return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                  } else {
                     return '$' + value;
                  }
               }
            }
         }]
      }
   }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas></code>```

Body:
I found that you can format the x or y axis of Chart.JS to currency by a quick JavaScript callback function

callback: function(value, index, values) {
    if (parseInt(value) >= 1000) {
        return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    } else {
        return '$' + value;
    }
}
}

but this does not seem to be the case for the data:  In my instance this is a JavaScript 1D Array that holds numeric values, and I want to add a dollar sign, and comma where applicable.  How can this be added with Charts.jS

EDIT

This is how I am populating my JSON array - and I want to format the data in the data: values

var barChartData = {
    labels: labelsarr,
    datasets: [{
        label: 'Amount',
        backgroundColor: 'rgba(200, 200, 200, 0.75)',
        borderColor: 'rgb(255, 99, 132)',
        borderWidth: 1,
        data: values
    }]

};

And the JSON array is in this format ["AAAA",100,10000,2310,24420,30,50000,400000,70000,700,823200,923200,1111]

I want to format starting at index[1] to show $ and currency.  How can this be achieved?

2nd Edit Time

I try to add title and format both data points and left axis as currency with below syntax, but this no longer displays anything on my page.

var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: labelsarr,
        datasets: [{
            label: 'Test',
            data: values,
            backgroundColor: 'rgba(0, 119, 204, 0.8)',
        }]
    },
    options: {
        responsive: true,
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    callback: function(value, index, values) {
                        if (parseInt(value) >= 1000) {
                            return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                        } else {
                            return '$' + value;
                        }
                    }
                }
            }]
        },
        legend: {
            position: 'top',
        },
        title: {
            display: true,
            text: '<?php echo $name ?> Test'
        }
        tooltips: {
            callbacks: {
                label: function(t, d) {
                    var xLabel = d.datasets[t.datasetIndex].label;
                    var yLabel = t.yLabel >= 1000 ?
                        '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") :
                        '$' + t.yLabel;
                    return xLabel + ': ' + yLabel;
                }
            }
        }
    }
});

Body:
This can be achieved using the following tool-tips label callback function ...

tooltips: {
   callbacks: {
      label: function(t, d) {
         var xLabel = d.datasets[t.datasetIndex].label;
         var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
         return xLabel + ': ' + yLabel;
      }
   }
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

var labelsarr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'];
var values = ["AAAA", 100, 10000, 2310, 24420, 30, 50000, 400000, 70000, 700, 823200, 923200, 1111];

var ctx = document.getElementById('canvas').getContext('2d');
var chart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: labelsarr,
      datasets: [{
         label: 'Amount',
         data: values,
         backgroundColor: 'rgba(0, 119, 204, 0.8)',
      }]
   },
   options: {
      tooltips: {
         callbacks: {
            label: function(t, d) {
               var xLabel = d.datasets[t.datasetIndex].label;
               var yLabel = t.yLabel >= 1000 ? '$' + t.yLabel.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") : '$' + t.yLabel;
               return xLabel + ': ' + yLabel;
            }
         }
      },
      scales: {
         yAxes: [{
            ticks: {
               callback: function(value, index, values) {
                  if (parseInt(value) >= 1000) {
                     return '$' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                  } else {
                     return '$' + value;
                  }
               }
            }
         }]
      }
   }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="canvas"></canvas>


问:
How to convert DateTime of type DateTimeKind.Unspecified to DateTime.Kind.Utc in C# (.NET)
I've inherited C# code that has an awful lot of DateTimes where the Kind property is DateTimeKind.Unspecified.  These are fed into Datetime.ToUniversalTime() which gives back a UTC datetime (it adds 7 hours in my case). This is how ToUniversalTime() works; see MSDN.
 The problem is that these DateTimes are in fact already in UTC time.  They are pulled out of a SQL Server Compact 4.0 database.  They were stored there in UTC.  My main question is:

How do I modify the Kind property of a DateTime so that it's UTC and not Unspecified?  I don't want to change the time or date.  So for example, a date of April 1st 2013, 9:05 am with its Kind property of "Unspecified" should become a datetime of April 1st 2013, 9:05 UTC.

If I could be indulged with a follow up question(s), it would be:

Are values necessarily returned from Sql Server Compact as "Unspecified"?  Inside Sql Server Compact, they are being stored as type (datetime, not null).   Looking at the code, it appears they are just put in the database, but there are no provisions to mark them as UTC or anything.  Is there a better way to handle things?  Is there a slick way to ensure the DateTimes come out of SQL Compact as UTC?

Please let me know if I can provide more details.  I'm new to this code base and still getting my brain around it, so I'm having trouble describing the problem perfectly.

Dave

答:
You could combine the two above answers for a cleaner solution...</p>

```<code>public static DateTime SetKind(this DateTime DT, DateTimeKind DTKind)
{
    return DateTime.SpecifyKind(DT, DTKind);
}
</code>```

Body:
You could combine the two above answers for a cleaner solution...

public static DateTime SetKind(this DateTime DT, DateTimeKind DTKind)
{
    return DateTime.SpecifyKind(DT, DTKind);
}


问:
Resize image in PHP
I want to write some PHP code that automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I'm a relative PHP novice).

So far, I've got images uploading successfully, filetypes being recognized and names cleaned up, but I'd like to add the resize functionality into the code. For example, I've got a test image that is 2.3MB, and 1331x1331 in dimension, and I'd like the code to size it down, which I'm guessing will dramatically compress the file size of the image, too.

So far, I've got the following:

```<code>if ($_FILES) {
    //Put file properties into variables
    $file_name = $_FILES['profile-image']['name'];
    $file_size = $_FILES['profile-image']['size'];
    $file_tmp_name = $_FILES['profile-image']['tmp_name'];

    //Determine filetype
    switch ($_FILES['profile-image']['type']) {
        case 'image/jpeg': $ext = "jpg"; break;
        case 'image/png': $ext = "png"; break;
        default: $ext = ''; break;
    }

    if ($ext) {
        //Check filesize
        if ($file_size < 500000) {
            //Process file - clean up filename and move to safe location
            $n = "$file_name";
            $n = ereg_replace("[^A-Za-z0-9.]", "", $n);
            $n = strtolower($n);
            $n = "avatars/$n";
            move_uploaded_file($file_tmp_name, $n);
        } else {
            $bad_message = "Please ensure your chosen file is less than 5MB.";
        }
    } else {
        $bad_message = "Please ensure your image is of filetype .jpg or.png.";
    }
}

$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);
</code>```

答:
You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.

```<code>composer require tinify/tinify
</code>```

After that, your code is as follows.

```<code>require_once("vendor/autoload.php");

\Tinify\setKey("YOUR_API_KEY");

$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
    "method" => "fit",
    "width" => 150,
    "height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image
</code>```

I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng

Title: Resize image in PHP

Body:
I want to write some PHP code that automatically resizes any image uploaded via a form to 147x147px, but I have no idea how to go about it (I'm a relative PHP novice).

So far, I've got images uploading successfully, filetypes being recognized and names cleaned up, but I'd like to add the resize functionality into the code. For example, I've got a test image that is 2.3MB, and 1331x1331 in dimension, and I'd like the code to size it down, which I'm guessing will dramatically compress the file size of the image, too.

So far, I've got the following:

if ($_FILES) {
    //Put file properties into variables
    $file_name = $_FILES['profile-image']['name'];
    $file_size = $_FILES['profile-image']['size'];
    $file_tmp_name = $_FILES['profile-image']['tmp_name'];

    //Determine filetype
    switch ($_FILES['profile-image']['type']) {
        case 'image/jpeg': $ext = "jpg"; break;
        case 'image/png': $ext = "png"; break;
        default: $ext = ''; break;
    }

    if ($ext) {
        //Check filesize
        if ($file_size < 500000) {
            //Process file - clean up filename and move to safe location
            $n = "$file_name";
            $n = ereg_replace("[^A-Za-z0-9.]", "", $n);
            $n = strtolower($n);
            $n = "avatars/$n";
            move_uploaded_file($file_tmp_name, $n);
        } else {
            $bad_message = "Please ensure your chosen file is less than 5MB.";
        }
    } else {
        $bad_message = "Please ensure your image is of filetype .jpg or.png.";
    }
}

$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "
" . $query);

Body:
You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.

composer require tinify/tinify

After that, your code is as follows.

require_once("vendor/autoload.php");

\Tinify\setKey("YOUR_API_KEY");

$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
    "method" => "fit",
    "width" => 150,
    "height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image

I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng


问:
Case insensitive sorting with Mongoid
Right now I got:

```<code>@directories = collection.directories.all.asc(:name)
</code>```

But it's case-sensitive, how do I do case-insensitive sorting?

答:
Currently you cannot create case insensitive indexes in MongoDB see ...

http://jira.mongodb.org/browse/SERVER-90

So, it seems that means you cannot do case insensitive "sorting" either.

You can upvote the feature for future inclusion in MongoDB via the link above if you find it useful.

Eliot Horowitz from 10Gen (the supporters of MongoDB) suggest this in the meantime:

For short term - I would just add a
  2nd field that you call .toLower() on
  before inserting.  Then you can sort
  on that.

Title: Case insensitive sorting with Mongoid

Body:
Right now I got:

@directories = collection.directories.all.asc(:name)

But it's case-sensitive, how do I do case-insensitive sorting?


问:
get all fields in object that have given word and transform all values of these fields
I have an object. like this, for example

{
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    }
    amount: 100
}```

I need to get all fields those contain word "Date" (or "date") and convert them all into string date format.

Who can help please.

答:
This recursive function should convert all the dates to ISO strings:

```<code>obj = convertDatesToString(obj);

function convertDatesToString(obj) {
    Object.keys(obj).forEach((key) => {
        if(key.toLowerCase().match(/date/)){
            obj[key] = new Date(obj[key]).toISOString();
        } else if (obj[key] instanceof Object) {
            obj[key] = convertDatesToString(obj[key]);
        }
    });

    return obj;
}
</code>```

obj = {
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    },
    amount: 100
};

obj = convertDatesToString(obj);
console.log(obj);

function convertDatesToString(obj) {
    Object.keys(obj).forEach((key) => {
        if(key.toLowerCase().match(/date/)){
            obj[key] = new Date(obj[key]).toISOString();
        } else if (obj[key] instanceof Object) {
            obj[key] = convertDatesToString(obj[key]);
        }
    });

    return obj;
}```

Body:
I have an object. like this, for example

{
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    }
    amount: 100
}

I need to get all fields those contain word "Date" (or "date") and convert them all into string date format.

Who can help please.

Body:
This recursive function should convert all the dates to ISO strings:

obj = convertDatesToString(obj);

function convertDatesToString(obj) {
    Object.keys(obj).forEach((key) => {
        if(key.toLowerCase().match(/date/)){
            obj[key] = new Date(obj[key]).toISOString();
        } else if (obj[key] instanceof Object) {
            obj[key] = convertDatesToString(obj[key]);
        }
    });

    return obj;
}

obj = {
    startDate: 2141242141,
    adress: '',
    endDate: 2141242141,
    billings: {
        startBillingDate: 2142421421421,
        endBillingDate: 2142421421421
    },
    amount: 100
};

obj = convertDatesToString(obj);
console.log(obj);

function convertDatesToString(obj) {
    Object.keys(obj).forEach((key) => {
        if(key.toLowerCase().match(/date/)){
            obj[key] = new Date(obj[key]).toISOString();
        } else if (obj[key] instanceof Object) {
            obj[key] = convertDatesToString(obj[key]);
        }
    });

    return obj;
}


问:
PHPExcel very slow - ways to improve?
I am generating reports in .xlsx using PHPExcel. It was okay in the initial testing stages with small data sets (tens of rows, 3 sheets), but now when using it on a real production data with over 500 rows in each sheet, it becomes incredibly slow. 48 seconds to generate a file, and when running a report that combines more information, the whole thing fails with Fatal error: Maximum execution time of 30 seconds exceeded in PHPExcel/Worksheet.php on line 1041. Sometimes it's in another PHPExcel file, so I doubt the exact location is that relevant.

Ideally, I would want to speed it up somehow, if possible. If not, then at least increase the execution limit for this script.

The only suggestions I have seen so far was to style in ranges instead of individual cells. Unfortunately, I already do my styling in ranges and it is rather minimal too. Any other suggestions?

答:
In my case I increased performance by changing cache storage method to in memory gzip cache_in_memory_gzip

```<code>$cm = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
\PHPExcel_Settings::setCacheStorageMethod($cm);
</code>```

Title: PHPExcel very slow - ways to improve?

Body:
In my case I increased performance by changing cache storage method to in memory gzip cache_in_memory_gzip

$cm = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
\PHPExcel_Settings::setCacheStorageMethod($cm);


问:
Adding a script to a game object dynamically and assigning values to its properties
I want to add a script/component to a game object and populate values in that script. The values for input come from the parent object as 'LineManagerProperty'. In the example below I want to add the 'LineManager' class to the 'Line' game object and assign the properties in 'LineManager'. If you look at the 'Line' class I add 'LineManagerProperty' so that it can appear in the unity inspector as values to pass into 'LineManager'. Is there a better way to do this?

```<code>public class Line : MonoBehaviour
{
    //This is added here so that values can appear in inspector
    //These values will be passed into 'LineManager' when its created and added to 'Line' game object
    public LineManagerProperty LineManagerProperty;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Add the 'LineManager' script and assign its properties
            gameObject.AddComponent<LineManager>().LineManagerProperty = new LineManagerProperty()
            {
                CollisionTag = LineManagerProperty.CollisionTag,
                MaxTimeDuration = LineManagerProperty.MaxTimeDuration,
                NumberOfHits = LineManagerProperty.NumberOfHits,
                Health = LineManagerProperty.Health
            };
        }
    }
}

public class LineManager : MonoBehaviour
{
    public LineManagerProperty LineManagerProperty;

    //...
}

[Serializable]
public class LineManagerProperty
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;
}
</code>```

答:
Any public variables that you give a script in Unity will appear in the inspector and can be set from anywhere. In your case, move the variables from the LineManagerProperty into the LineManager script:

```<code>public class LineManager : MonoBehaviour
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;

    //...
}
</code>```

Then to set your variables, just use the GameObject.

```<code>_line.CollisionTag = "";
_line.MaxTimeDuration = 0;
//.....
</code>```

Hopefully this helps!

Body:
I want to add a script/component to a game object and populate values in that script. The values for input come from the parent object as 'LineManagerProperty'. In the example below I want to add the 'LineManager' class to the 'Line' game object and assign the properties in 'LineManager'. If you look at the 'Line' class I add 'LineManagerProperty' so that it can appear in the unity inspector as values to pass into 'LineManager'. Is there a better way to do this?

public class Line : MonoBehaviour
{
    //This is added here so that values can appear in inspector
    //These values will be passed into 'LineManager' when its created and added to 'Line' game object
    public LineManagerProperty LineManagerProperty;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Add the 'LineManager' script and assign its properties
            gameObject.AddComponent<LineManager>().LineManagerProperty = new LineManagerProperty()
            {
                CollisionTag = LineManagerProperty.CollisionTag,
                MaxTimeDuration = LineManagerProperty.MaxTimeDuration,
                NumberOfHits = LineManagerProperty.NumberOfHits,
                Health = LineManagerProperty.Health
            };
        }
    }
}

public class LineManager : MonoBehaviour
{
    public LineManagerProperty LineManagerProperty;

    //...
}

[Serializable]
public class LineManagerProperty
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;
}

Body:
Any public variables that you give a script in Unity will appear in the inspector and can be set from anywhere. In your case, move the variables from the LineManagerProperty into the LineManager script:

public class LineManager : MonoBehaviour
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;

    //...
}

Then to set your variables, just use the GameObject.

_line.CollisionTag = "";
_line.MaxTimeDuration = 0;
//.....

Hopefully this helps!


问:
Webdriver firefox-bin uses excessive amount of CPU
I am running a single test (FirefoxDriveR)which visits all links on a given domain.

OS: Ubuntu 9.10
Memory: 4GB
HD: 500GB
10 mbp/s line

Observing the following via command TOP

```<code>11001 hudson    20   0  508m 108m  28m S   64  2.8   2:31.58 firefox-bin
10937 hudson    20   0 1277m  73m 9772 S    6  1.8   0:21.93 java
10929 hudson    20   0 43820  10m 3440 S    3  0.3   0:06.25 Xvnc
</code>```

64% CPU Consumption via firefox-bin. Anyway I can reduce this ?

答:
On a 3Ghz machine, I see firefox using in the range from 25-40% CPU when running at full blast through a site. Remember that firefox is effectively an execution environment for code. So page efficiency corrolates to CPU usage on the host.

Standard tricks for optimizing javascript, css and page rendering apply here, this is not about webdriver as such, although you can expect a baseline for reasonably efficient pages around 30%

Body:
I am running a single test (FirefoxDriveR)which visits all links on a given domain.

OS: Ubuntu 9.10
Memory: 4GB
HD: 500GB
10 mbp/s line

Observing the following via command TOP

11001 hudson    20   0  508m 108m  28m S   64  2.8   2:31.58 firefox-bin
10937 hudson    20   0 1277m  73m 9772 S    6  1.8   0:21.93 java
10929 hudson    20   0 43820  10m 3440 S    3  0.3   0:06.25 Xvnc

64% CPU Consumption via firefox-bin. Anyway I can reduce this ?


问:
Multiple instances of SQL Server for connection vs connectionless?
Consider that I have two databases. If I want one of them to be connected to a TCP/IP protocol and one of them I don't want connected, do I need to open up two separate instances of SQL Server or would it be possible with the only one instance. How would I manage to separate the permissions in the latter case?</p>

答: The network configuration is at the instance level.  So if you really need network isolation (ie regular SQL Server security is not good enough), you need a second instance.</p>


问:
Where has simd matrix_linear_combination been gone in iOS11?
```<code> let m = matrix_linear_combination(alpha, v1, 1-alpha, v0)
</code>```

matrix_linear_combination now generates "Use of unresolved identifier 'matrix_linear_combination'" error.

Any existing replacement?

PS : Should I clarify I already import simd and that there was no issue in iOS10/Swift 3).

答:
Short answer:  The iOS 11/macOS 10.13 SDK renames many simd types and functions,
the prefix matrix_ is replaced by simd_.

Longer answer:

Xcode 8 uses the iOS 10.3 (resp. macOS 10.12) SDK, and that defines
the simd matrix types as

```<code>typedef struct { vector_float2 columns[2]; } matrix_float2x2;
</code>```

and the functions

```<code>static matrix_float2x2 __SIMD_ATTRIBUTES__ matrix_linear_combination(float __a, matrix_float2x2 __x, float __b, matrix_float2x2 __y);
</code>```

These are imported into Swift 3 as

```<code>public struct matrix_float2x2 { ... }
// ...
</code>```

and

```<code>public func matrix_linear_combination(_ __a: Float, _ __x: matrix_float2x2, _ __b: Float, _ __y: matrix_float2x2) -> matrix_float2x2
// ...
</code>```

Xcode 9 uses the iOS 11 (resp. macOS 10.13) SDK and that defines the
types as

```<code>typedef struct { simd_float2 columns[2]; } simd_float2x2;
// ...
</code>```

and the functions

```<code>static simd_float2x2 SIMD_CFUNC simd_linear_combination(float __a, simd_float2x2 __x, float __b, simd_float2x2 __y);
// ...
</code>```

These are imported into Swift 4 as

```<code>public struct simd_float2x2 { ... }
// ...
</code>```

and

```<code>public func simd_linear_combination(_ __a: Float, _ __x: simd_float2x2, _ __b: Float, _ __y: simd_float2x2) -> simd_float2x2
// ...
</code>```

Body:
 let m = matrix_linear_combination(alpha, v1, 1-alpha, v0)

matrix_linear_combination now generates "Use of unresolved identifier 'matrix_linear_combination'" error.

Any existing replacement?

PS : Should I clarify I already import simd and that there was no issue in iOS10/Swift 3).

Body:
Short answer:  The iOS 11/macOS 10.13 SDK renames many simd types and functions,
the prefix matrix_ is replaced by simd_.

Longer answer:

Xcode 8 uses the iOS 10.3 (resp. macOS 10.12) SDK, and that defines
the simd matrix types as

typedef struct { vector_float2 columns[2]; } matrix_float2x2;

and the functions

static matrix_float2x2 __SIMD_ATTRIBUTES__ matrix_linear_combination(float __a, matrix_float2x2 __x, float __b, matrix_float2x2 __y);

These are imported into Swift 3 as

public struct matrix_float2x2 { ... }
// ...

and

public func matrix_linear_combination(_ __a: Float, _ __x: matrix_float2x2, _ __b: Float, _ __y: matrix_float2x2) -> matrix_float2x2
// ...

Xcode 9 uses the iOS 11 (resp. macOS 10.13) SDK and that defines the
types as

typedef struct { simd_float2 columns[2]; } simd_float2x2;
// ...

and the functions

static simd_float2x2 SIMD_CFUNC simd_linear_combination(float __a, simd_float2x2 __x, float __b, simd_float2x2 __y);
// ...

These are imported into Swift 4 as

public struct simd_float2x2 { ... }
// ...

and

public func simd_linear_combination(_ __a: Float, _ __x: simd_float2x2, _ __b: Float, _ __y: simd_float2x2) -> simd_float2x2
// ...


问:
how to resolve "cannot read property appendChild of null" in the following code?
```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> speech synthesizer</title>
  </head>
  <body>
    <div class="voiceinator">
      <h1> My Speech Synthesizer </h1>

      <select id="voices" name="voice">
        <option value="">Select a voice</option>
      </select>

    <label for="rate">Rate:</label>
    <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

    <label for="pitch">Pitch:</label>
    <input type="range" name="pitch" min="0" max="2" step="0.1">

    <textarea name="text"> Hello there! </textarea>
    <button type="button" id="stop"> Stop! </button>
    <button type="button" id="speak"> Speak </button>
    </div>
 <script type="text/javascript">

  const msg = new SpeechSynthesisUtterance();
  let voices = [];
  var voicesDropdown = document.querySelector('[name="voices"]');
  const options = document.querySelector('[name="range"], [name="text"]'); // this selects the rate control bar, pitch bar and text area
  const speakButton = document.querySelector('#speak');
  const stopButton = document.querySelector('#stop');
  msg.text = document.querySelector('[name="text"]').value;

  function populateVoices()
  {
    voices = this.getVoices();

    for( var i=0 ; i<voices.length ; i++ ){
      var opt = voices[i];
      var el = document.createElement("option");
      el.textContent = opt;
      el.value = opt;
      voicesDropdown.appendChild(el);
    }

  }
  //when speechSynthesis loads , voiceschanged event occurs and populateVoices function is fired
  speechSynthesis.addEventListener('voiceschanged', populateVoices);
 </script>
  </body>
</html>
</code>```

THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

SPEECH SYNTHESIZER.html:45 Uncaught TypeError: Cannot read property 'appendChild' of null
      at SpeechSynthesis.populateVoices (SPEECH SYNTHESIZER.html:45)

Also please tell me how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang

答:
The name on the <select> is voice not voices. But simpler and more efficient to get that element by ID

Change:

```<code>var voicesDropdown = document.querySelector('[name="voices"]');
</code>```

To

```<code>var voicesDropdown = document.querySelector('#voices');
</code>```

Body:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title> speech synthesizer</title>

 My Speech Synthesizer

      <select id="voices" name="voice">
        <option value="">Select a voice</option>
      </select>

    Rate:
    <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

    Pitch:
    <input type="range" name="pitch" min="0" max="2" step="0.1">

    <textarea name="text"> Hello there! </textarea>
    <button type="button" id="stop"> Stop! </button>
    <button type="button" id="speak"> Speak </button>

THIS IS THE ERROR I AM GETTING --- HOW TO RESOLVE IT?

SPEECH SYNTHESIZER.html:45 Uncaught TypeError: Cannot read property 'appendChild' of null
      at SpeechSynthesis.populateVoices (SPEECH SYNTHESIZER.html:45)

Also please tell me how do I append two values to el.textContent? For eg. I want it to display voices[i].name and voices[i].lang

Body:
The name on the <select> is voice not voices. But simpler and more efficient to get that element by ID

Change:

var voicesDropdown = document.querySelector('[name="voices"]');

To

var voicesDropdown = document.querySelector('#voices');


问:
Why does CDT rebuild my C-project on Ant build in unrelated project?
I have an Eclipse workspace where a CDT project lives together with other unrelated projects. However, when I run "build as Ant build" in one of those projects, CDT insists on rebuilding its projects too.

Anyone have any ideas where to look to disconnect this "hidden" dependency? (And no, it's not in the "Linked Resources" or the "Project References"...)

答: Try to uncheck the Build Automatically checkbox, under Project menu.


问:
Confirmation alert when reloading or closing the window but not when submitting a form
I have created a form and using the window "onbeforeunload" feature, I've decided to add a confirmation box so that every time the user tries closing the window or reloading the page he gets an alert message.

The problem is that the message is something along the lines of "changes may not be saved" and that same confirmation error pops up when i'm submitting the form!

Is there a way i can get these confirmation pop ups everytime other than when submitting the form?

I've seen some stack exchange questions wherein the OP has asked for an alert when reloading but not closing tab or vice versa. Even in those questions the answer seems to be along the lines of "..It isn't possible..". Have a look at this question, for instance.

So, I have a feeling it might not be possible here too, but is there any other way? For example, i could make the submit button as a normal button and then add some features manually?

I have knowledge of JavaScript/HTML/CSS and nothing more. Perhaps I could learn another language which would make it plausible? Or maybe there is an intrinsic feature I still don't know about?

It would be preferable if I could somehow achieve it without using another language but I'm fine if that is the only option.

答:
You can add a onclick="dontShowAnythingAndSubmit()" to your submit button.
Then move the submit button outside the form.

Define your function to override the onbeforeunload.

```<code>function dontShowAnythingAndSubmit() {
    window.onbeforeunload = null;
    document.getElementById("yourForm").submit();
}
</code>```

Or did I not completely understand your question?

Body:
You can add a onclick="dontShowAnythingAndSubmit()" to your submit button.
Then move the submit button outside the form.

Define your function to override the onbeforeunload.

function dontShowAnythingAndSubmit() {
    window.onbeforeunload = null;
    document.getElementById("yourForm").submit();
}

Or did I not completely understand your question?


问:
Getting another element through a method thats related to the current operation
Sorry for the bad title, simple couldn't figure out how to explain my problem.

Let's say i have 4 of these fields, and not just one. I want to increment or decrement each input field. Each input field has a "+" and "-" that does incremental and decremental tasks.

I have setup a method that register the v-on click even to a method. But how do i get what input field it was incremented on, cause 'this' would return the buttons of +/-

normally i would just use jquery with .parent().find('.input-number'); but i feel like this is dirty, and excessive for such a small thing. most be a better approach?

This is my markup

```<code>      <div class="form-group">
        <span class="input-number-decrement" v-on:click="decrement()">–</span>
        <input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
        <span class="input-number-increment" v-on:click="increment()">+</span>
      </div>
</code>```

and looks like this
example of the field

any help would great, since i'm stuck at this part :)

答:
I am assuming above code is a vue component.

```<code><div class="form-group">
 <span class="input-number-decrement" v-on:click="decrement()">–</span>
 <inputn v-model="value" class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
 <span class="input-number-increment" v-on:click="increment()">+</span>
</div>
</code>```

In the script define a variable to hold the value.Then manipulate values using defined methods

```<code><script>
export default{
 data: {
    value
  },
  methods: {
    decrement: function (event) {
    },
    increment: function (event) {
    }
  }
}
</script>
</code>```

Body:
Sorry for the bad title, simple couldn't figure out how to explain my problem.

Let's say i have 4 of these fields, and not just one. I want to increment or decrement each input field. Each input field has a "+" and "-" that does incremental and decremental tasks.

I have setup a method that register the v-on click even to a method. But how do i get what input field it was incremented on, cause 'this' would return the buttons of +/-

normally i would just use jquery with .parent().find('.input-number'); but i feel like this is dirty, and excessive for such a small thing. most be a better approach?

This is my markup

        –
        <input class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
        +

and looks like this
example of the field

any help would great, since i'm stuck at this part :)

Body:
I am assuming above code is a vue component.

<div class="form-group">
 <span class="input-number-decrement" v-on:click="decrement()">–</span>
 <inputn v-model="value" class="input-number form-control" name="pack1" id="pack1" type="text" value="0" min="0">
 <span class="input-number-increment" v-on:click="increment()">+</span>
</div>

In the script define a variable to hold the value.Then manipulate values using defined methods

<script>
export default{
 data: {
    value
  },
  methods: {
    decrement: function (event) {
    },
    increment: function (event) {
    }
  }
}
</script>


问:
Can I select a previous sibling in CSS?
I want to select #btnsrchicon parent's child #txtSearch. I tried in the below format, but not works

HTML

```<code><div id="topSearch">

<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>
<button id="btnsrchicon" class="submit" onClick="search_another();"></button>

</div>
</code>```

and CSS

```<code><style>
 #txtSearch{display:none;}
#btnsrchicon:hover < #topSearch+#txtSearch
{
 display: block;
 border:2px solid red;
}
</style>
</code>```

答:
There is no parent selector in CSS. But you can select a following sibling. A possible solution might be to change the order of the button and the input and use the + selector, like that:

#btnsrchicon:hover + #txtSearch {
  display: block;
}

#txtSearch {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="btnsrchicon" class="submit" onClick="search_another();">Bouton</button>
<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/></code>```

Then, if the order is really important, you can use some css to visually revert the order

Title: Can I select a previous sibling in CSS?

Body:
I want to select #btnsrchicon parent's child #txtSearch. I tried in the below format, but not works

HTML

<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>
<button id="btnsrchicon" class="submit" onClick="search_another();"></button>

and CSS

Body:
There is no parent selector in CSS. But you can select a following sibling. A possible solution might be to change the order of the button and the input and use the + selector, like that:

#btnsrchicon:hover + #txtSearch {
  display: block;
}

#txtSearch {
  display: none;
}

<button id="btnsrchicon" class="submit" onClick="search_another();">Bouton</button>
<input id="txtSearch" name="search" type="text" value="" id="txtSearch" onClick="ClearTextBox()" onkeypress="searchenter(event);"/>

Then, if the order is really important, you can use some css to visually revert the order


问:
Cannot load such file -- bcrypt_ext
I'm currently experiencing the failure of bcrypt's encryptor while using Devise for Rails 5.0.1. I never had this issue before with the earlier Rails 4.2. I can't register new users through Devise. I will post information with regards to my gemfile and server log.

Gemfile.rb

```<code>gem 'bcrypt', platforms: :ruby

# Devise
gem 'devise'
gem 'devise_security_extension'

gem 'redis'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'
</code>```

Server log

```<code>Started POST "/register" for 127.0.0.1 at 2017-01-12 13:50:05 -0500
Processing by Users::RegistrationsController#create as HTML
  Parameters: {"utf8"=>"âœ“", "authenticity_token"=>"bH6n7iWLhPMECDzTVkMyTc9FXtvkGrq5+K4wFs1g8Bxbjq9ShaLJP5gn72SFQlHc01j2ao5JKcv57ClWAzwsmw==", "user"=>{"email"=>"craigcarl@codex.com", "username"=>"codex", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Completed 500 Internal Server Error in 258ms (ActiveRecord: 0.0ms)

LoadError - cannot load such file -- bcrypt_ext:
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `block in require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:259:in `load_dependency'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  bcrypt-3.1.11-x86 (mingw32) lib/bcrypt.rb:16:in `rescue in <top (required)>'
  bcrypt-3.1.11-x86 (mingw32) lib/bcrypt.rb:12:in `<top (required)>'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `block in require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:259:in `load_dependency'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  devise (4.2.0) lib/devise/encryptor.rb:1:in `<top (required)>'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `block in require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:259:in `load_dependency'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  devise (4.2.0) lib/devise/models/database_authenticatable.rb:147:in `password_digest'
  devise (4.2.0) lib/devise/models/database_authenticatable.rb:40:in `password='
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:46:in `public_send'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:39:in `each'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
  activerecord (5.0.1) lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
  activerecord (5.0.1) lib/active_record/core.rb:319:in `initialize'
  activerecord (5.0.1) lib/active_record/inheritance.rb:65:in `new'
  activerecord (5.0.1) lib/active_record/inheritance.rb:65:in `new'
  devise (4.2.0) lib/devise/models/registerable.rb:20:in `new_with_session'
  devise (4.2.0) app/controllers/devise/registrations_controller.rb:100:in `build_resource'
  devise (4.2.0) app/controllers/devise/registrations_controller.rb:15:in `create'
  actionpack (5.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
  actionpack (5.0.1) lib/abstract_controller/base.rb:188:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
  actionpack (5.0.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (5.0.1) lib/active_support/callbacks.rb:126:in `call'
  activesupport (5.0.1) lib/active_support/callbacks.rb:506:in `block (2 levels) in compile'
  activesupport (5.0.1) lib/active_support/callbacks.rb:455:in `call'
  activesupport (5.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__'
  activesupport (5.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks'
  activesupport (5.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
  actionpack (5.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
  activesupport (5.0.1) lib/active_support/notifications.rb:164:in `block in instrument'
  activesupport (5.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  activesupport (5.0.1) lib/active_support/notifications.rb:164:in `instrument'
  actionpack (5.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action'
  activerecord (5.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (5.0.1) lib/abstract_controller/base.rb:126:in `process'
  actionview (5.0.1) lib/action_view/rendering.rb:30:in `process'
  actionpack (5.0.1) lib/action_controller/metal.rb:190:in `dispatch'
  actionpack (5.0.1) lib/action_controller/metal.rb:262:in `dispatch'
  actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch'
  actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve'
  actionpack (5.0.1) lib/action_dispatch/routing/mapper.rb:16:in `block in <class:Constraints>'
  actionpack (5.0.1) lib/action_dispatch/routing/mapper.rb:46:in `serve'
  actionpack (5.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'
  actionpack (5.0.1) lib/action_dispatch/journey/router.rb:26:in `each'
  actionpack (5.0.1) lib/action_dispatch/journey/router.rb:26:in `serve'
  actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call'
  rack (2.0.1) lib/rack/deflater.rb:35:in `call'
  warden (1.2.6) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.6) lib/warden/manager.rb:34:in `catch'
  warden (1.2.6) lib/warden/manager.rb:34:in `call'
  rack (2.0.1) lib/rack/etag.rb:25:in `call'
  rack (2.0.1) lib/rack/conditional_get.rb:38:in `call'
  rack (2.0.1) lib/rack/head.rb:12:in `call'
  rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context'
  rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'
  activerecord (5.0.1) lib/active_record/migration.rb:553:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
  activesupport (5.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
  activesupport (5.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
  activesupport (5.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
  actionpack (5.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
  web-console (3.4.0) lib/web_console/middleware.rb:135:in `call_app'
  web-console (3.4.0) lib/web_console/middleware.rb:28:in `block in call'
  web-console (3.4.0) lib/web_console/middleware.rb:18:in `catch'
  web-console (3.4.0) lib/web_console/middleware.rb:18:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
  railties (5.0.1) lib/rails/rack/logger.rb:36:in `call_app'
  railties (5.0.1) lib/rails/rack/logger.rb:24:in `block in call'
  activesupport (5.0.1) lib/active_support/tagged_logging.rb:69:in `block in tagged'
  activesupport (5.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (5.0.1) lib/active_support/tagged_logging.rb:69:in `tagged'
  railties (5.0.1) lib/rails/rack/logger.rb:24:in `call'
  sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'
  rack (2.0.1) lib/rack/method_override.rb:22:in `call'
  rack (2.0.1) lib/rack/runtime.rb:22:in `call'
  activesupport (5.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'
  rack (2.0.1) lib/rack/sendfile.rb:111:in `call'
  railties (5.0.1) lib/rails/engine.rb:522:in `call'
  puma (3.6.2) lib/puma/configuration.rb:225:in `call'
  puma (3.6.2) lib/puma/server.rb:578:in `handle_request'
  puma (3.6.2) lib/puma/server.rb:415:in `process_client'
  puma (3.6.2) lib/puma/server.rb:275:in `block in run'
  puma (3.6.2) lib/puma/thread_pool.rb:116:in `block in spawn_thread'

Started POST "/__better_errors/4e4442c3f810d7b9/variables" for 127.0.0.1 at 2017-01-12 13:50:06 -0500
</code>```

答:
I also encountered the same problem, then I found some references and it's about version only.

When I changed bcrypt back to

```<code>bcrypt 3.1.0-x86-mingw32
</code>```

from

```<code>bcrypt 3.1.11-x86-mingw32(the latest now)
</code>```

Then make sure again in gemfile

```<code>gem 'bcrypt-ruby', '3.1.0', :require => 'bcrypt'
</code>```

then it works fine.

Title: Cannot load such file -- bcrypt_ext

Body:
I'm currently experiencing the failure of bcrypt's encryptor while using Devise for Rails 5.0.1. I never had this issue before with the earlier Rails 4.2. I can't register new users through Devise. I will post information with regards to my gemfile and server log.

Gemfile.rb

gem 'bcrypt', platforms: :ruby

# Devise
gem 'devise'
gem 'devise_security_extension'

gem 'redis'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.0.1'

Server log

Started POST "/register" for 127.0.0.1 at 2017-01-12 13:50:05 -0500
Processing by Users::RegistrationsController#create as HTML
  Parameters: {"utf8"=>"âœ“", "authenticity_token"=>"bH6n7iWLhPMECDzTVkMyTc9FXtvkGrq5+K4wFs1g8Bxbjq9ShaLJP5gn72SFQlHc01j2ao5JKcv57ClWAzwsmw==", "user"=>{"email"=>"craigcarl@codex.com", "username"=>"codex", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
Completed 500 Internal Server Error in 258ms (ActiveRecord: 0.0ms)

LoadError - cannot load such file -- bcrypt_ext:
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `block in require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:259:in `load_dependency'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  bcrypt-3.1.11-x86 (mingw32) lib/bcrypt.rb:16:in `rescue in <top (required)>'
  bcrypt-3.1.11-x86 (mingw32) lib/bcrypt.rb:12:in `<top (required)>'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `block in require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:259:in `load_dependency'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  devise (4.2.0) lib/devise/encryptor.rb:1:in `<top (required)>'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `block in require'
  activesupport (5.0.1) lib/active_support/dependencies.rb:259:in `load_dependency'
  activesupport (5.0.1) lib/active_support/dependencies.rb:293:in `require'
  devise (4.2.0) lib/devise/models/database_authenticatable.rb:147:in `password_digest'
  devise (4.2.0) lib/devise/models/database_authenticatable.rb:40:in `password='
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:46:in `public_send'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:39:in `each'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
  activerecord (5.0.1) lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
  activemodel (5.0.1) lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
  activerecord (5.0.1) lib/active_record/core.rb:319:in `initialize'
  activerecord (5.0.1) lib/active_record/inheritance.rb:65:in `new'
  activerecord (5.0.1) lib/active_record/inheritance.rb:65:in `new'
  devise (4.2.0) lib/devise/models/registerable.rb:20:in `new_with_session'
  devise (4.2.0) app/controllers/devise/registrations_controller.rb:100:in `build_resource'
  devise (4.2.0) app/controllers/devise/registrations_controller.rb:15:in `create'
  actionpack (5.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
  actionpack (5.0.1) lib/abstract_controller/base.rb:188:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/rendering.rb:30:in `process_action'
  actionpack (5.0.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (5.0.1) lib/active_support/callbacks.rb:126:in `call'
  activesupport (5.0.1) lib/active_support/callbacks.rb:506:in `block (2 levels) in compile'
  activesupport (5.0.1) lib/active_support/callbacks.rb:455:in `call'
  activesupport (5.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__'
  activesupport (5.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks'
  activesupport (5.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
  actionpack (5.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action'
  activesupport (5.0.1) lib/active_support/notifications.rb:164:in `block in instrument'
  activesupport (5.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  activesupport (5.0.1) lib/active_support/notifications.rb:164:in `instrument'
  actionpack (5.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (5.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action'
  activerecord (5.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (5.0.1) lib/abstract_controller/base.rb:126:in `process'
  actionview (5.0.1) lib/action_view/rendering.rb:30:in `process'
  actionpack (5.0.1) lib/action_controller/metal.rb:190:in `dispatch'
  actionpack (5.0.1) lib/action_controller/metal.rb:262:in `dispatch'
  actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch'
  actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve'
  actionpack (5.0.1) lib/action_dispatch/routing/mapper.rb:16:in `block in <class:Constraints>'
  actionpack (5.0.1) lib/action_dispatch/routing/mapper.rb:46:in `serve'
  actionpack (5.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'
  actionpack (5.0.1) lib/action_dispatch/journey/router.rb:26:in `each'
  actionpack (5.0.1) lib/action_dispatch/journey/router.rb:26:in `serve'
  actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call'
  rack (2.0.1) lib/rack/deflater.rb:35:in `call'
  warden (1.2.6) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.6) lib/warden/manager.rb:34:in `catch'
  warden (1.2.6) lib/warden/manager.rb:34:in `call'
  rack (2.0.1) lib/rack/etag.rb:25:in `call'
  rack (2.0.1) lib/rack/conditional_get.rb:38:in `call'
  rack (2.0.1) lib/rack/head.rb:12:in `call'
  rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context'
  rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'
  activerecord (5.0.1) lib/active_record/migration.rb:553:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
  activesupport (5.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
  activesupport (5.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
  activesupport (5.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
  actionpack (5.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
  web-console (3.4.0) lib/web_console/middleware.rb:135:in `call_app'
  web-console (3.4.0) lib/web_console/middleware.rb:28:in `block in call'
  web-console (3.4.0) lib/web_console/middleware.rb:18:in `catch'
  web-console (3.4.0) lib/web_console/middleware.rb:18:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
  railties (5.0.1) lib/rails/rack/logger.rb:36:in `call_app'
  railties (5.0.1) lib/rails/rack/logger.rb:24:in `block in call'
  activesupport (5.0.1) lib/active_support/tagged_logging.rb:69:in `block in tagged'
  activesupport (5.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (5.0.1) lib/active_support/tagged_logging.rb:69:in `tagged'
  railties (5.0.1) lib/rails/rack/logger.rb:24:in `call'
  sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'
  rack (2.0.1) lib/rack/method_override.rb:22:in `call'
  rack (2.0.1) lib/rack/runtime.rb:22:in `call'
  activesupport (5.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
  actionpack (5.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'
  rack (2.0.1) lib/rack/sendfile.rb:111:in `call'
  railties (5.0.1) lib/rails/engine.rb:522:in `call'
  puma (3.6.2) lib/puma/configuration.rb:225:in `call'
  puma (3.6.2) lib/puma/server.rb:578:in `handle_request'
  puma (3.6.2) lib/puma/server.rb:415:in `process_client'
  puma (3.6.2) lib/puma/server.rb:275:in `block in run'
  puma (3.6.2) lib/puma/thread_pool.rb:116:in `block in spawn_thread'

Started POST "/__better_errors/4e4442c3f810d7b9/variables" for 127.0.0.1 at 2017-01-12 13:50:06 -0500

Body:
I also encountered the same problem, then I found some references and it's about version only.

When I changed bcrypt back to

bcrypt 3.1.0-x86-mingw32

from

bcrypt 3.1.11-x86-mingw32(the latest now)

Then make sure again in gemfile

gem 'bcrypt-ruby', '3.1.0', :require => 'bcrypt'

then it works fine.


问:
Update same client collection with different subscription
I have a problem with subscriptions which should have fill same collection on the client with the different set of records.
For example:
I have a Books collection and two different publications:

Meteor.publish(‘books’, () => Books.find({ status: { $ne: 3 } });

publish  “booksForReservation” which is returning an array of books (books are filtered based on the reservation and some other data)

Problem occurs on the client, when I coming from one route to another. All Books collection are in the main component, and when I need those booksForReservation collection on the client is not updating with only that specific set of books.

I have subscribed on the client like:

```<code>Meteor.subscribe(‘booksForReservation’, reservationsIds);
let books = Books.find({}).fetch();
</code>```

but I’m still getting all books collection displayed. when I have filtered Books collection on the client side with the same query used on the server, collection is updated. But then filtering it on the server doesn’t have any point.

How can I update same collection with different subscription?

答: You have to filter collection on the client side with a query from the server. You subscribe to two publications, so on the client you will have data from both of them. The point of filtering collection on the server side is security. By doing it you won't publish any unwanted data to the client. You can read more about it here https://guide.meteor.com/data-loading.html#specific-queries</p>

Body:
I have a problem with subscriptions which should have fill same collection on the client with the different set of records.
For example:
I have a Books collection and two different publications:

Meteor.publish(‘books’, () => Books.find({ status: { $ne: 3 } });

publish  “booksForReservation” which is returning an array of books (books are filtered based on the reservation and some other data)

Problem occurs on the client, when I coming from one route to another. All Books collection are in the main component, and when I need those booksForReservation collection on the client is not updating with only that specific set of books.

I have subscribed on the client like:

Meteor.subscribe(‘booksForReservation’, reservationsIds);
let books = Books.find({}).fetch();

but I’m still getting all books collection displayed. when I have filtered Books collection on the client side with the same query used on the server, collection is updated. But then filtering it on the server doesn’t have any point.

How can I update same collection with different subscription?