问:
Angular Modal issue
I am trying to implement a modal from
https://plnkr.co/edit/VSOzZ8AJz61az9TANGsp?p=preview

However, I am trying to put the modal into a component instead of  directive as shown in the plunker above. I rant into one error ($.confirm)

```<code>import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    closeResult: string;

    name: string;
    constructor(public modal: Modal) {
        this.name = 'Angular version'
    }

    @Output('confirm-click') click: any = new EventEmitter();

    @HostListener('click', ['$event']) clicked(e) {
        $.confirm({
            buttons: {
                confirm: () => this.click.emit(),
                cancel: () => { }
            }
        });
    }

}
</code>```

error:  Cannot find name '$'.

************************************UPDATE**************************************

I just ended up using bootstrap Modal , which works and easy to implement
modal.html

```<code><div>

    <span class="fa fa-trash-o"  data-toggle="modal" data-target="#myModal">

    </span>
    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title">Confirm</h4>
                </div>
                <div class="modal-body">
                    <p>Delete this record?</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

                </div>
            </div>
            <div>

            </div>
        </div>
    </div>
</div>
</code>```

Modal.ts

```<code>     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}
</code>```

答: Try modal.confirm() instead of $.confirm.

Title: Angular Modal issue

Body:
I am trying to implement a modal from
https://plnkr.co/edit/VSOzZ8AJz61az9TANGsp?p=preview

However, I am trying to put the modal into a component instead of  directive as shown in the plunker above. I rant into one error ($.confirm)

import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    closeResult: string;

    name: string;
    constructor(public modal: Modal) {
        this.name = 'Angular version'
    }

    @Output('confirm-click') click: any = new EventEmitter();

    @HostListener('click', ['$event']) clicked(e) {
        $.confirm({
            buttons: {
                confirm: () => this.click.emit(),
                cancel: () => { }
            }
        });
    }

}

error:  Cannot find name '$'.

************************************UPDATE**************************************

I just ended up using bootstrap Modal , which works and easy to implement
modal.html

                    <button type="button" class="close" data-dismiss="modal">×</button>

Confirm

Delete this record?

                    <button type="button" class="btn btn-primary" data-dismiss="modal" (click)="onOk()">OK</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

Modal.ts

     import { Component, Output, HostListener, EventEmitter, Directive, ElementRef, NgModule,Input } from '@angular/core';

import { Overlay } from 'ngx-modialog';
import { Modal } from 'ngx-modialog/plugins/bootstrap';

declare const jQuery: {
    confirm: Function
};

@Component({
    selector: 'modal',
    moduleId: module.id,
    templateUrl: 'modal.component.html'

})
export class ModalComponent {
    @Output() open: EventEmitter<any> = new EventEmitter();

    onOk() {
        console.log("OK");
        this.open.emit('yes');
    }
    onDelete() {

        console.log("Cancel");
    }

}


来源: stackexchange

问:
How to simply install apk in device in Android Studio
My question is when i click on run button it runs gradle command to check change files and build class and then dex to create apk.

If i know there is no change in my files still gradle runs to check.

As i have many libraries attached to my app module to reduce run time. if anyone knows to install apk in device from android studio without running gradle.

Note : I want to install on device which is connected to my system not to emulator,etc.

Note : I want to install from android studio not by using any other software.

答:
I use this method to install the generated APK to the device using bash script since I'm working on Linux(didn't try this on windows or os x).

When you run the app in the android studio the run tab will print out the commands which android studio uses to install the app on the device.

I just copy these commands into a file and save it as run.sh

run.sh

```<code>#!/bin/sh

adb push /home/gautam/sample/app/build/outputs/apk/debug/app-debug.apk /data/local/tmp/com.example.sample.sample
adb shell pm install -t -r "/data/local/tmp/com.example.sample.sample"
adb shell am start -n "com.example.sample.sample/com.example.sample.sample.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
</code>```

save the file in you project directory(although you can keep it any where).also add it to you gitignore if you need. Then open you terminal in android studio and run the script file to install the APK.

```<code>chmod a+x run.sh
./run.sh
</code>```

This will install the apk to the connected device. If more then one device are connected the script will throw error in which case you will have to provide the device id refer this.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I use this method to install the generated APK to the device using bash script since I'm working on Linux(didn't try this on windows or os x).

When you run the app in the android studio the run tab will print out the commands which android studio uses to install the app on the device.

I just copy these commands into a file and save it as run.sh

run.sh

#!/bin/sh

adb push /home/gautam/sample/app/build/outputs/apk/debug/app-debug.apk /data/local/tmp/com.example.sample.sample
adb shell pm install -t -r "/data/local/tmp/com.example.sample.sample"
adb shell am start -n "com.example.sample.sample/com.example.sample.sample.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER

save the file in you project directory(although you can keep it any where).also add it to you gitignore if you need. Then open you terminal in android studio and run the script file to install the APK.

chmod a+x run.sh
./run.sh

This will install the apk to the connected device. If more then one device are connected the script will throw error in which case you will have to provide the device id refer this.

Hope this helps.


问:
Need help about binary files
I'm having trouble creating a code that creates a bin file with multiple lines, each one containing 6 values per line. for example:
I'm doing a little project where each line will be a 'password', so my system will load this file and read all passwords from it, when it gets updated and etc.
I havent implemented the way to read the file yet because i'm struggling to manipulate the file.
This project will be running on linux with GPIO features from Raspberry pi
so i'm using  Visual Studio for creating the main code.

My current code is:

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char keys[4] = { '1', '2', '3', '4' }; // NOT USING
char temp_key[6];

int incl_key() {
    int i;
    FILE *fp;
    char code = "0";
    int control = 0;
    int var_internal = 0;

    fp = fopen("keys.bin", "wb");
    if (fp == NULL) {
        printf("\n Error opening file. \n");
    }

    printf("write your sequence <6 digits>:\n");

    do{
        scanf("%s", &temp_key);
        fputs(temp_key, fp);
        fputs("\n", fp);
        control++;
    } while (control < 5);
    fclose(fp);
}

int keys_db() {
    return 0;
}

int main() {
    incl_key();

    system("PAUSE");
}
</code>```

Thanks in advance.

答:
Array is too small for user input as a string.

```<code>char temp_key[6];
printf("write your sequence <6 digits>:\n");
scanf("%s", &temp_key);   // poor code
</code>```

A string is a contiguous sequence of characters terminated by and including the first null character.

When one types 1, 2, 3, 4, 5, 6, Enter, that puts '1', '2', '3', '4', '5', '6', '\n' into stdin.  scanf("%s", temp_key); looks for leading white-space, sees none and then reads the 6 non-white-space chracters and saves those in temp_key[0], temp_key[1],  .... temp_key[5].  Reading the '\n' (a white-space), the "%s" directs to stop scanning for more, puts the '\n' back into stdin for later input and then attempts to append a null character into temp_key[6] to make it a string.  But temp_key[] is too small for that and so anything may happens - it is undefined behavior.  Remaining code is irrelevant.

scanf("%s", &temp_key); is improper code for 3 reasons.

&temp_key passes the address of an array when the address of the first element of the array is needed to match "%s".  Both of those addresses have equivalent values, yet different types.  This itself is undefined behavior.  Yet the vast majority of the time, it "works" like the correct scanf("%s", temp_key);  (no &)

scanf("%s", temp_key); offers no limitation on how much data is read and as outlined above, entering 6 or more digits results in a buffer overrun and undefined behavior.

The return value is not checked, so code does not know if things are successful.  stdin could have been closed (no more input) or other concerns.

Instead use fgets() to read a line of user input and covert that input into a string.

```<code>#define KEY_N 6
//            key    \n   \0  extra - why be stingy?
char temp_key[KEY_N + 1 + 1 + 10];

//scanf("%s", &temp_key);
if (fgets(temp_key, sizeof temp_key, stdin)) {
  // user input successfully read!

  temp_key[strcspn(temp_key), "\n"] = '\0'; // lop off potential trailing \n
  if (strlen(temp_key) != KEY_N) Handle_Invalid_Input();
  else GoodToGo();
}
</code>```

Code may have other issues too.

E.g.: The fp in binary vs text mode along with "running on linux ... so i'm using Visual Studio" has concerns about the expectations of reading "keys.bin" which appears like a text file. For now, what OP is doing concerning that looks OK as long as it is treated a a binary file.

Title: Need help about binary files

Body:
I'm having trouble creating a code that creates a bin file with multiple lines, each one containing 6 values per line. for example:
I'm doing a little project where each line will be a 'password', so my system will load this file and read all passwords from it, when it gets updated and etc.
I havent implemented the way to read the file yet because i'm struggling to manipulate the file.
This project will be running on linux with GPIO features from Raspberry pi
so i'm using  Visual Studio for creating the main code.

My current code is:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char keys[4] = { '1', '2', '3', '4' }; // NOT USING
char temp_key[6];

int incl_key() {
    int i;
    FILE *fp;
    char code = "0";
    int control = 0;
    int var_internal = 0;

    fp = fopen("keys.bin", "wb");
    if (fp == NULL) {
        printf("\n Error opening file. \n");
    }

    printf("write your sequence <6 digits>:\n");

    do{
        scanf("%s", &temp_key);
        fputs(temp_key, fp);
        fputs("\n", fp);
        control++;
    } while (control < 5);
    fclose(fp);
}

int keys_db() {
    return 0;
}

int main() {
    incl_key();

    system("PAUSE");
}

Thanks in advance.

Body:
Array is too small for user input as a string.

char temp_key[6];
printf("write your sequence <6 digits>:\n");
scanf("%s", &temp_key);   // poor code

A string is a contiguous sequence of characters terminated by and including the first null character.

When one types 1, 2, 3, 4, 5, 6, Enter, that puts '1', '2', '3', '4', '5', '6', '\n' into stdin.  scanf("%s", temp_key); looks for leading white-space, sees none and then reads the 6 non-white-space chracters and saves those in temp_key[0], temp_key[1],  .... temp_key[5].  Reading the '\n' (a white-space), the "%s" directs to stop scanning for more, puts the '\n' back into stdin for later input and then attempts to append a null character into temp_key[6] to make it a string.  But temp_key[] is too small for that and so anything may happens - it is undefined behavior.  Remaining code is irrelevant.

scanf("%s", &temp_key); is improper code for 3 reasons.

&temp_key passes the address of an array when the address of the first element of the array is needed to match "%s".  Both of those addresses have equivalent values, yet different types.  This itself is undefined behavior.  Yet the vast majority of the time, it "works" like the correct scanf("%s", temp_key);  (no &)

scanf("%s", temp_key); offers no limitation on how much data is read and as outlined above, entering 6 or more digits results in a buffer overrun and undefined behavior.

The return value is not checked, so code does not know if things are successful.  stdin could have been closed (no more input) or other concerns.

Instead use fgets() to read a line of user input and covert that input into a string.

#define KEY_N 6
//            key    \n   \0  extra - why be stingy?
char temp_key[KEY_N + 1 + 1 + 10];

//scanf("%s", &temp_key);
if (fgets(temp_key, sizeof temp_key, stdin)) {
  // user input successfully read!

  temp_key[strcspn(temp_key), "\n"] = '\0'; // lop off potential trailing \n
  if (strlen(temp_key) != KEY_N) Handle_Invalid_Input();
  else GoodToGo();
}

Code may have other issues too.

E.g.: The fp in binary vs text mode along with "running on linux ... so i'm using Visual Studio" has concerns about the expectations of reading "keys.bin" which appears like a text file. For now, what OP is doing concerning that looks OK as long as it is treated a a binary file.


问:
Cant append  inside  tag
i want to append this new element

```<code><a data-toggle="tab"> <span class = "hyperspan"> </span> </a>
</code>```

but,  does not appear on the console after the append. it makes me not able to select element through button, must click text (element ).

Try Fill in the input form and submit in My JSFiddle and click the second button.

Button will not work if  is text not clicked.

Code Snippet Demonstration:

$('.submitButton').click(function () {
  var add = '
' +
      '
' +
        '
' +
          '

' +
          '
' +
            '
' +
              '
' +
                '
' +
                '
' +
              '
' +

              '' +

            '
' +
          '
' +
        '
' +
      '
' +
    '
';

    if( document.getElementById("addNew").value === '' ){
            alert("WRITE SOMETHING");
        } else {
          $('.nav').append(add)
      var inputan = document.getElementById("addNew").value;
            $('li:last').find('a').text(inputan);
            document.getElementById("newFoldr").value = "";
            }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._sideFolder {
  background-color: transparent;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active,
li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

<input type="text" id="addNew" placeholder="Write something">
<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">

            Main Folder

            Second Folder

```

答:
The problem is you're overwriting the contents of the a element when you do:

```<code>$('li:last').find('a').text(inputan);
</code>```

You could instead, put the text before the span element, like this:

```<code>$('li:last').find('span').before(inputan);
</code>```

$('.submitButton').click(function () {
  var add = '
' +
      '
' +
        '
' +
          '

' +
          '
' +
            '
' +
              '
' +
                '
' +
                '
' +
              '
' +

              '' +

            '
' +
          '
' +
        '
' +
      '
' +
    '
';

    if( document.getElementById("addNew").value === '' ){
            alert("WRITE SOMETHING");
        } else {
          $('.nav').append(add)
      var inputan = document.getElementById("addNew").value;
            $('li:last').find('span').before(inputan);
            document.getElementById("newFoldr").value = "";
            }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>._sideFolder {
  background-color: transparent;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active,
li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}</code>```

<input type="text" id="addNew" placeholder="Write something">
<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">

            Main Folder

            Second Folder

```

Here you have it on JSFiddle: https://jsfiddle.net/qb8b4hcj/35/

Title: Cant append <span> inside <a> tag

Body:
i want to append this new element

but,  does not appear on the console after the append. it makes me not able to select element through button, must click text (element ).

Try Fill in the input form and submit in My JSFiddle and click the second button.

Button will not work if  is text not clicked.

Code Snippet Demonstration:

$('.submitButton').click(function () {
  var add = '
' +
      '
' +
        '
' +
          '

' +
          '
' +
            '
' +
              '
' +
                '
' +
                '
' +
              '
' +

              '' +

            '
' +
          '
' +
        '
' +
      '
' +
    '
';

    if( document.getElementById("addNew").value === '' ){
            alert("WRITE SOMETHING");
        } else {
          $('.nav').append(add)
      var inputan = document.getElementById("addNew").value;
            $('li:last').find('a').text(inputan);
            document.getElementById("newFoldr").value = "";
            }
});

._sideFolder {
  background-color: transparent;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active,
li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>

<input type="text" id="addNew" placeholder="Write something">
<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">

            Main Folder

            Second Folder

Body:
The problem is you're overwriting the contents of the a element when you do:

$('li:last').find('a').text(inputan);

You could instead, put the text before the span element, like this:

$('li:last').find('span').before(inputan);

$('.submitButton').click(function () {
  var add = '<li>' +
      '<div class="zf-folder">' +
        '<div id="tabFolder3" class="_tabFolder _itemPosition" style="height: 40px;border-bottom:1px groove; user-select: none;">' +
          '<div class="_sideFolder"></div>' +
          '<div class="_iconText" style="width: 215px">' +
            '<div class="ellipsis">' +
              '<div class="_iconFolder">' +
                '<div class="_icon-col">' +
                '</div>' +
              '</div>' +

              '<a data-toggle="tab"><span class="hyperspan"></span></a>' +

            '</div>' +
          '</div>' +
        '</div>' +
      '</div>' +
    '</li>';

    if( document.getElementById("addNew").value === '' ){
            alert("WRITE SOMETHING");
        } else {
          $('.nav').append(add)
      var inputan = document.getElementById("addNew").value;
            $('li:last').find('span').before(inputan);
            document.getElementById("newFoldr").value = "";
            }
});

._sideFolder {
  background-color: transparent;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder:active ._sideFolder,
li.active .zf-folder ._sideFolder {
  background-color: blue;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0px;
  width: 5px
}

.zf-folder a {
  color: white;
  text-decoration: none;
}

._tabFolder {
  background: red;
  cursor: pointer;
  position: relative;
}

._tabFolder:hover {
  background-color: grey
}

._tabFolder:active,
li.active ._tabFolder {
  background-color: rgba(29, 33, 41, 1)
}

._itemPosition {
  align-items: center;
  display: flex
}

._iconText:hover ._1i5y,
.uiPopover.selected ._1i5y {
  display: block
}

._iconText {
  align-items: center;
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-left: 13px;
}

._iconFolder,
._1i5x,
._1i5w {
  display: inline-block;
  margin-right: 5px;
  vertical-align: middle
}

._5bme ._iconFolder {
  background-image: url(/rsrc.php/v3/yE/r/miCSJRxMvJi.png);
  background-repeat: no-repeat;
  background-size: auto;
  background-position: -412px -21px
}

.hyperspan {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}

<input type="text" id="addNew" placeholder="Write something">
<input type="button" class="submitButton" id="submitButton" value="Create" style="width:142px;margin-left: 5px;">

<ul class="nav">

  <li class="active">
    <div class="zf-folder">
      <div id="tabFolder" class="_tabFolder _itemPosition" style="height: 40px;border-bottom:1px groove; user-select: none;">
        <div class="_sideFolder"></div>
        <div class="_iconText" style="width: 215px">
          <div class="ellipsis">
            <div class="_iconFolder">
              <div class="_icon-col">
              </div>
            </div>

            <a href="#mainFolder" aria-controls="mainFolder" data-toggle="tab">Main Folder<span class="hyperspan"></span></a>

          </div>
        </div>
      </div>
    </div>
  </li>

  <li>
    <div class="zf-folder">
      <div id="tabFolder2" class="_tabFolder _itemPosition" style="height: 40px;border-bottom:1px groove; user-select: none;">
        <div class="_sideFolder"></div>
        <div class="_iconText" style="width: 215px">
          <div class="ellipsis">
            <div class="_iconFolder">
              <div class="_icon-col">
              </div>
            </div>
            <a href="#secondFolder" aria-controls="secondFolder" data-toggle="tab">Second Folder<span class="hyperspan"></span></a>
          </div>
        </div>
      </div>
    </div>
  </li>

</ul>

Here you have it on JSFiddle: https://jsfiddle.net/qb8b4hcj/35/


问:
How to use rc.exe with MSBuild in a .NET project
In a MSBuild project file for a .NET app, I’ve been using rc.exe, and I called it using the Exec task, and I retrieved the path to rc.exe from WindowsSDK80Path.

This worked fine with Visual Studio 2015, however with VS2017 (without having VS2015 installed), WindowsSDK80Path points to a non-existing directory. Unfortunately, I did not find a way to retrieve the new installation path, which on my machine happens to be C:\Program Files (x86)\Windows Kits\10.

I don’t know how to use the RC task, and I don’t know if it’s the right thing to use, because the documentation says, “Tasks Specific to Visual C++”.

How can I use rc.exe so that it works with both VS2015 and VS2017 and, if possible, with the next version of Visual Studio as well?

(Note that GetFrameworkPath doesn’t retrieve a suitable path.)

答:
The RC Task is defined in Microsoft.CppCommon.targets which is in C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\v140 on my machine.  You should be able to either just import that targets file in your project or find the  and copy it (with some modifications) to your project.

Edit...

should be a safe way to import that task and allow you to not use a physical path.


问:
SQL Server Code Reuse Via Stored Procedures - Good or Bad Practice?
I'm currently considering design options for a reporting application based on an existing dataset.

There are several clear opportunities for code reuse given that many of the reports need to use the same base data set (Edited).

The tempation is to create some base stored procedure that I can reuse throughout this system, however, the contract I was on 6 months ago or so showed me what the down side of this practice - multiple layers of - large stored procedure calls returning subsets of data in, making it very very difficult to workout what was going on, debug and test.

I'm these days of the opinion that code reuse does not necessarily enhance maintainability in database design.

I'm looking for some insight on this from a more experienced SQL Server dev than myself?

Thanks in advance.

答:
The primary purpose of code reuse, IMO, is to break monolithic programs up into more easily understood and more easily maintained pieces. The division of labor must not be idiosyncratic -- one man's personal quirky idea of order. The art of constructing a library of helper functions is in very large part a social art -- you must define an intelligible API that is consistent in its approach. You don't want the coders who follow after you to be cursing you in absentia. You want them to be thanking you for the clarity and utility of your design.

@Neil Barnwell: I see no problem with building business-rules into the database.  Triggers and stored procs can perform this role just as well if not better than a middle tier or client code.  Of course, you must have programmers who have mastered the programming language in the database, T-SQL or PL/SQL or whatever it happens to be.

ContentLicense: CC BY-SA 2.5


问:
Multiplying String in a list, Haskell
I am trying to multiply strings in a list. For instance, when I have a list like ["hello","World"] and I want to 'multiply' it by 2, I want to end up with ["hello","hello","World","World"].

Here's what I came up with:

```<code>rep :: Int -> [String] -> [String]
rep n [] = []
rep n [x:xs] = replicate n [x] ++ rep n [xs]
</code>```

But it gives me exception:

(298,1)-(299,44): Non-exhaustive patterns in function rep

I am totally new to this language and I do not have any ideas how to sort this out. Can you help?

答:
Your fist problem is that the pattern for non-empty lists is wrong, it should be (x:xs), not [x:xs].

Furthermore, replicate expects a single element and turns it into a list of length n, so it should be replicate n x, not replicate n [x].

In a similar vain xs is already a list.

If you fix all of this you'll end up with the following, which actually works as intended:

```<code>rep :: Int -> [String] -> [String]
rep n [] = []
rep n (x:xs) = replicate n x ++ rep n xs
</code>```

That said there are many different ways one could write this, for example with concatMap:

```<code>rep n = concatMap (replicate n)
</code>```

or

```<code>rep = concatMap . replicate
</code>```

Title: Multiplying String in a list, Haskell

Body:
I am trying to multiply strings in a list. For instance, when I have a list like ["hello","World"] and I want to 'multiply' it by 2, I want to end up with ["hello","hello","World","World"].

Here's what I came up with:

rep :: Int -> [String] -> [String]
rep n [] = []
rep n [x:xs] = replicate n [x] ++ rep n [xs]

But it gives me exception:

(298,1)-(299,44): Non-exhaustive patterns in function rep

I am totally new to this language and I do not have any ideas how to sort this out. Can you help?

Body:
Your fist problem is that the pattern for non-empty lists is wrong, it should be (x:xs), not [x:xs].

Furthermore, replicate expects a single element and turns it into a list of length n, so it should be replicate n x, not replicate n [x].

In a similar vain xs is already a list.

If you fix all of this you'll end up with the following, which actually works as intended:

rep :: Int -> [String] -> [String]
rep n [] = []
rep n (x:xs) = replicate n x ++ rep n xs

That said there are many different ways one could write this, for example with concatMap:

rep n = concatMap (replicate n)

or

rep = concatMap . replicate


问:
git clean not removing sub-directories (not recursive)
I am facing problems with git clean.
Consider the following scenario:

```<code>git status -su
?? file_1
?? xyz/file_2

git clean -f
Not removing xyz/file_2
Removing file_1
</code>```

I don't want to remove the xyz folder, but I want to remove the file_2 inside it.

Why is git clean is not working recursively?

答:
try this:

```<code>git clean -xdf
</code>```

let me know if that worked.

ContentLicense: CC BY-SA 4.0

Body:
I am facing problems with git clean.
Consider the following scenario:

git status -su
?? file_1
?? xyz/file_2

git clean -f
Not removing xyz/file_2
Removing file_1

I don't want to remove the xyz folder, but I want to remove the file_2 inside it.

Why is git clean is not working recursively?

Body:
try this:

git clean -xdf

let me know if that worked.


问:
How to style a checkbox using CSS
I am trying to style a checkbox using the following:

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />```

But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?

答:
It seems you can change the colour of the checkbox in grayscale by using CSS only.

The following converts the checkboxes from black to gray (which was about what I wanted):

```<code>input[type="checkbox"] {
    opacity: .5;
}
</code>```

Title: How to style a checkbox using CSS

Body:
I am trying to style a checkbox using the following:

<input type="checkbox" style="border:2px dotted #00f;display:block;background:#ff0000;" />

But the style is not applied. The checkbox still displays its default style. How do I give it the specified style?

Body:
It seems you can change the colour of the checkbox in grayscale by using CSS only.

The following converts the checkboxes from black to gray (which was about what I wanted):

input[type="checkbox"] {
    opacity: .5;
}


问:
If statement not executing during ActionPerformed event
Trying to write a Swing GUI. When clicking a button, I want to test if the other button has already been clicked. If it has, then execute the statements in the "if" statements. But it looks like the "if" statements never execute?</p>

```<code>private void radSingleBurgerActionPerformed(java.awt.event.ActionEvent evt) {
    if(radDoubleBurger.isSelected()){
        newItemPrice = Double.parseDouble(lblItemPrice.getText());
        newItemPrice -= doublePrice;
        lblTest.setText(String.valueOf(newItemPrice));//test to see if working
    }
    lblItemPrice.setText(String.valueOf(newItemPrice += singlePrice));
}

private void radDoubleBurgerActionPerformed(java.awt.event.ActionEvent evt) {
     if(radSingleBurger.isSelected()){
        newItemPrice = Double.parseDouble(lblItemPrice.getText());
        newItemPrice -= singlePrice;
        lblTest.setText(String.valueOf(newItemPrice));//test to see if working
    }
    lblItemPrice.setText(String.valueOf(newItemPrice += doublePrice));
}
</code>```

答:
Clicking a JButton does not make it (permanently) selected. Clicking is only a temporary action.

Maybe you want to use a JToggleButton. This allows you to click a button to make it selected and then click it again to make it unselected.

Read the section from the Swing tutorial on How to Use Buttons for more information.

Or if you just want to know if the user has clicked on a regular JButton, then you will need to maintain a Boolean variable yourself that you update in the ActionListener of the button.

Body:
Trying to write a Swing GUI. When clicking a button, I want to test if the other button has already been clicked. If it has, then execute the statements in the "if" statements. But it looks like the "if" statements never execute?

private void radSingleBurgerActionPerformed(java.awt.event.ActionEvent evt) {
    if(radDoubleBurger.isSelected()){
        newItemPrice = Double.parseDouble(lblItemPrice.getText());
        newItemPrice -= doublePrice;
        lblTest.setText(String.valueOf(newItemPrice));//test to see if working
    }
    lblItemPrice.setText(String.valueOf(newItemPrice += singlePrice));
}

private void radDoubleBurgerActionPerformed(java.awt.event.ActionEvent evt) {
     if(radSingleBurger.isSelected()){
        newItemPrice = Double.parseDouble(lblItemPrice.getText());
        newItemPrice -= singlePrice;
        lblTest.setText(String.valueOf(newItemPrice));//test to see if working
    }
    lblItemPrice.setText(String.valueOf(newItemPrice += doublePrice));
}


问:
Is it legal to call delete on a null pointer of an incomplete type?
And if so, why does the following code give me the warning

note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined

?

```<code>struct C;

int main()
{
    C *c = nullptr;

    delete c;

    return 0;
}
</code>```

I understand why it might be undefined behavior in the general case if C has non-trivial/virtual destructors, but doesn't the standard guarantee/define that delete on nullptr is always a noop no matter the situation?

To reiterate: I'm asking specifically about the case where the pointer to incomplete type is nullptr!

答:
The standard says ([expr.delete]/5):

If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined.

So if T has a non-trivial destructor or has an operator delete overload, you get UB. Nothing is said about the UB being based on the value of the pointer (ie: whether it's a null pointer or not).

On what "object being deleted" mean?

One could consider that "object being deleted" means that this clause only applies to delete calls on actual objects. And therefore, if you pass a null pointer, it does not apply.

First, the rest of the standard discussion about the behavior of delete explicitly calls out that its behavior does not apply to null pointers. [expr.delete]/6&7 both start with "If the value of the operand of the delete-expression is not a null pointer value". Paragraph 5 explicitly does not contain these words. Therefore, we must assume it does apply to null pointers.

Second, what would the meaning of "object being deleted" be if it were passed a null pointer? After all, there is no "object" there.

Well, consider what it means to interpret this text if "object being deleted" talks specifically about the object at the end of that pointer. Well, what happens if you're deleting an array of incomplete classes with non-trivial destructors?

By that logic, this clause does not apply, whether the pointer is null or not. Why? Because the "object being deleted" is of an array type, not a class type. And therefore, this clause cannot apply. Which means that a compiler must be able to invoke delete[] on an array of incomplete classes.

But that's impossible to implement; it would require the compiler to be able to track down code that doesn't exist yet.

So either the "object being deleted" is intended to refer to std::remove_pointer_t<std::decay_t<decltype(expr)>>, or the standard requires behavior that is impossible to implement. The standard wording could probably be cleaned up a bit, replacing "If the object being deleted has incomplete class type at the point of deletion" with "If T is a pointer to U or an array of U, and U has incomplete class type at the point of deletion, ..."

Body:
And if so, why does the following code give me the warning

note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined

?

struct C;

int main()
{
    C *c = nullptr;

    delete c;

    return 0;
}

I understand why it might be undefined behavior in the general case if C has non-trivial/virtual destructors, but doesn't the standard guarantee/define that delete on nullptr is always a noop no matter the situation?

To reiterate: I'm asking specifically about the case where the pointer to incomplete type is nullptr!


问:
add more than one dot indicator below date in android prolific material calendar view
I have implemented calendarview using android prolific material calendarview external library in my android application. Now I have to add multiple dot indicators below some dates to indicate number of events in each date. I tried but only got single dot below date. Please help

Here are my calendar fragment and decorator classes:

```<code>public class CalendarFragment extends Fragment {
    private View v;
    private List<Schedule> schedules = new ArrayList<Schedule>( );
    private MaterialCalendarView calendarView;

    public CalendarFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        try {
        v = inflater.inflate(R.layout.fragment_calendar, container, false);
        initViews();
        schedules = ScheduleDAO.getInstance().getScheduleListWithId();
            highlightDates(schedules);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return v;
    }

    private void highlightDates(List<Schedule>scheduleList) throws ParseException {
        for (int position = 0;position<scheduleList.size();position++)
        {
            Schedule schedule = scheduleList.get(position);
            if (schedule.getSessionStatus().equals("Incomplete")){
                int color = R.color.colorPrimaryDark;
                CurrentDayDecorator decorator = new CurrentDayDecorator(new Date(schedule.getScheduledDate()),color);
                calendarView.addDecorator(decorator);

            }else {
                int color = R.color.lightgray;
                CurrentDayDecorator decorator = new CurrentDayDecorator(new Date(schedule.getScheduledDate()),color);
                calendarView.addDecorator(decorator);
            }
        }
    }

    private void initViews() {
        calendarView = v.findViewById(R.id.calendarView);
    }
}

Decorator class
public class CurrentDayDecorator implements DayViewDecorator {
    private final int color;
    private final CalendarDay day;

    public CurrentDayDecorator(Date date,int color) {
        this.color = color;
        this.day = CalendarDay.from(date);
    }
    @Override
    public boolean shouldDecorate(CalendarDay day) {
        if (this.day.equals(day)){
            return true;
        }
        return false;
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.addSpan(new DotSpan(3,color));
    }
}
</code>```

答:
I had a similar issue and found this post very helpful.

What you want to do is not supported through the MaterialViewCalendar API so you need to add some extra helper classes. Note that one decorator maps to one dot. So if you want two dots under a given date, then that date must be bound to two decorators etc.

One way to solve the issue is to do the following:

Change the decorate-method in your CurrentDayDecorator class to the following:

```<code>@Override
    public void decorate(DayViewFacade view) {
        LineBackgroundSpan span = new CustomSpan(color, xOffsets[spanType]);
        view.addSpan(span);
    }
</code>```

As you can see we will need to add a new class (CustomSpan) and two fields (xOffsets and spanType) to your CurrentDayDecorator class. LineBackgroundSpan is an interface contained in the package.

```<code>private static class CustomSpan extends DotSpan{
    private int color;
    private int xOffset;
    private float radius = 3;
    CustomSpan(int color, int xOffset){
        this.color = color;
        this.xOffset = xOffset;
    }

        /*Note! The following code is more or less copy-pasted from the DotSpan class. I have commented the changes below.*/
    @Override
    public void drawBackground(Canvas canvas, Paint paint, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int oldColor = paint.getColor();
        if (color != 0) {
            paint.setColor(color);
        }
        int x = ((left + right) / 2); /*This is the x-coordinate right
    below the date. If we add to x, we will draw the
    circle to the right of the date and vice versa if we subtract from x.*/
        canvas.drawCircle(x + xOffset, bottom + radius, radius, paint);
        paint.setColor(oldColor);
    }
}
</code>```

So all that is left is to feed an offset to our CustomSpan. In my own Decorator-method I have an array of offsets to pick from. Which one I pick depends on which dot I am creating. In my application I can put at most 4 dots below a date. I need to tell my CurrentDayDecorator which one of the 4 dots it is "representing", before I draw it.

This is how my class looks like (for you, just change "EventDecorator" to "CurrentDayDecorator")

```<code> private static class EventDecorator implements DayViewDecorator {

    private static final float DEFAULT_DOT_RADIUS = 4;
    //Note that negative values indicate a relative offset to the LEFT
    private static final int[] xOffsets = new int[]{0,-10,10,-20};
    private int color;
    private HashSet<CalendarDay> dates;
    private float dotRadius;
    private int spanType;

    private EventDecorator(int color, float dotRadius, int spanType) {
        this.color = color;
        this.dotRadius = dotRadius;
        this.dates = new HashSet<>();
        this.spanType = spanType;
    }
    /*Note! I added this method so that I can add dates after object creation!*/
    public boolean addDate(CalendarDay day){
        return dates.add(day);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return dates.contains(day);
    }

    @Override
    public void decorate(DayViewFacade view) {
        LineBackgroundSpan span = new CustomSpan(color, xOffsets[spanType],DEFAULT_DOT_RADIUS);
        view.addSpan(span);
    }
}
</code>```

Now the tricky part becomes knowing when to create a DayViewDecorator with the correct corresponding spanType. If a day should have two dots, its going to need two DayViewDecorators (with different values for spanType). What I did was that I kept track of all days with "events" and associated each "eventful day" with a counter. In other words, a HashMap mapping a CalendarDay to an Integer. Then you go through each entry in the Map and add the given day to X amounts of decorators, where X is the total count of events. In code it would look something like this:

```<code>EventDecorator[] decoratorArray = new EventDecorator[4]; //Max 4 dots
for(int i = 0; i<decoratorArray.length; i++)
        decoratorArray[i] = new EventDecorator(myColor,myRadius,i);

/*dayInstanceMap contains all the mappings.*/
for(Map.Entry<CalendarDay,Integer> entry : dayInstanceMap.entrySet()){
      CalendarDay currDay = entry.getKey();
      Integer currDayCount = entry.getValue(); //If you have max amount of dots, check here if currDay is too large.
      for(int i = 0; i<currDayCount; i++)
          decoratorArray[i].addDate(currDay);
}
</code>```

After that, just add the decorators to the MaterialCalendarView and you should be good to go.

Body:
I have implemented calendarview using android prolific material calendarview external library in my android application. Now I have to add multiple dot indicators below some dates to indicate number of events in each date. I tried but only got single dot below date. Please help

Here are my calendar fragment and decorator classes:

public class CalendarFragment extends Fragment {
    private View v;
    private List<Schedule> schedules = new ArrayList<Schedule>( );
    private MaterialCalendarView calendarView;

    public CalendarFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        try {
        v = inflater.inflate(R.layout.fragment_calendar, container, false);
        initViews();
        schedules = ScheduleDAO.getInstance().getScheduleListWithId();
            highlightDates(schedules);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return v;
    }

    private void highlightDates(List<Schedule>scheduleList) throws ParseException {
        for (int position = 0;position<scheduleList.size();position++)
        {
            Schedule schedule = scheduleList.get(position);
            if (schedule.getSessionStatus().equals("Incomplete")){
                int color = R.color.colorPrimaryDark;
                CurrentDayDecorator decorator = new CurrentDayDecorator(new Date(schedule.getScheduledDate()),color);
                calendarView.addDecorator(decorator);

            }else {
                int color = R.color.lightgray;
                CurrentDayDecorator decorator = new CurrentDayDecorator(new Date(schedule.getScheduledDate()),color);
                calendarView.addDecorator(decorator);
            }
        }
    }

    private void initViews() {
        calendarView = v.findViewById(R.id.calendarView);
    }
}

Decorator class
public class CurrentDayDecorator implements DayViewDecorator {
    private final int color;
    private final CalendarDay day;

    public CurrentDayDecorator(Date date,int color) {
        this.color = color;
        this.day = CalendarDay.from(date);
    }
    @Override
    public boolean shouldDecorate(CalendarDay day) {
        if (this.day.equals(day)){
            return true;
        }
        return false;
    }

    @Override
    public void decorate(DayViewFacade view) {
        view.addSpan(new DotSpan(3,color));
    }
}

Body:
I had a similar issue and found this post very helpful.

What you want to do is not supported through the MaterialViewCalendar API so you need to add some extra helper classes. Note that one decorator maps to one dot. So if you want two dots under a given date, then that date must be bound to two decorators etc.

One way to solve the issue is to do the following:

Change the decorate-method in your CurrentDayDecorator class to the following:

@Override
    public void decorate(DayViewFacade view) {
        LineBackgroundSpan span = new CustomSpan(color, xOffsets[spanType]);
        view.addSpan(span);
    }

As you can see we will need to add a new class (CustomSpan) and two fields (xOffsets and spanType) to your CurrentDayDecorator class. LineBackgroundSpan is an interface contained in the package.

private static class CustomSpan extends DotSpan{
    private int color;
    private int xOffset;
    private float radius = 3;
    CustomSpan(int color, int xOffset){
        this.color = color;
        this.xOffset = xOffset;
    }

        /*Note! The following code is more or less copy-pasted from the DotSpan class. I have commented the changes below.*/
    @Override
    public void drawBackground(Canvas canvas, Paint paint, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int oldColor = paint.getColor();
        if (color != 0) {
            paint.setColor(color);
        }
        int x = ((left + right) / 2); /*This is the x-coordinate right
    below the date. If we add to x, we will draw the
    circle to the right of the date and vice versa if we subtract from x.*/
        canvas.drawCircle(x + xOffset, bottom + radius, radius, paint);
        paint.setColor(oldColor);
    }
}

So all that is left is to feed an offset to our CustomSpan. In my own Decorator-method I have an array of offsets to pick from. Which one I pick depends on which dot I am creating. In my application I can put at most 4 dots below a date. I need to tell my CurrentDayDecorator which one of the 4 dots it is "representing", before I draw it.

This is how my class looks like (for you, just change "EventDecorator" to "CurrentDayDecorator")

 private static class EventDecorator implements DayViewDecorator {

    private static final float DEFAULT_DOT_RADIUS = 4;
    //Note that negative values indicate a relative offset to the LEFT
    private static final int[] xOffsets = new int[]{0,-10,10,-20};
    private int color;
    private HashSet<CalendarDay> dates;
    private float dotRadius;
    private int spanType;

    private EventDecorator(int color, float dotRadius, int spanType) {
        this.color = color;
        this.dotRadius = dotRadius;
        this.dates = new HashSet<>();
        this.spanType = spanType;
    }
    /*Note! I added this method so that I can add dates after object creation!*/
    public boolean addDate(CalendarDay day){
        return dates.add(day);
    }

    @Override
    public boolean shouldDecorate(CalendarDay day) {
        return dates.contains(day);
    }

    @Override
    public void decorate(DayViewFacade view) {
        LineBackgroundSpan span = new CustomSpan(color, xOffsets[spanType],DEFAULT_DOT_RADIUS);
        view.addSpan(span);
    }
}

Now the tricky part becomes knowing when to create a DayViewDecorator with the correct corresponding spanType. If a day should have two dots, its going to need two DayViewDecorators (with different values for spanType). What I did was that I kept track of all days with "events" and associated each "eventful day" with a counter. In other words, a HashMap mapping a CalendarDay to an Integer. Then you go through each entry in the Map and add the given day to X amounts of decorators, where X is the total count of events. In code it would look something like this:

EventDecorator[] decoratorArray = new EventDecorator[4]; //Max 4 dots
for(int i = 0; i<decoratorArray.length; i++)
        decoratorArray[i] = new EventDecorator(myColor,myRadius,i);

/*dayInstanceMap contains all the mappings.*/
for(Map.Entry<CalendarDay,Integer> entry : dayInstanceMap.entrySet()){
      CalendarDay currDay = entry.getKey();
      Integer currDayCount = entry.getValue(); //If you have max amount of dots, check here if currDay is too large.
      for(int i = 0; i<currDayCount; i++)
          decoratorArray[i].addDate(currDay);
}

After that, just add the decorators to the MaterialCalendarView and you should be good to go.


问:
Octlet, quad word or what?
I am translating some documentation on libraw1394 to Russian. The documentation on libraw1394 says:

The basic data structures defined in
  the standard and used in this document
  are the quadlet (32 bit quantity) and
  the octlet (64 bit quantity)...

There is no such unit like "octlet" in Russian. I used to use "quad word" (russian "chetvertnoye slovo") for 64 bit quantity. Would it be correct to substitute "octlet" by "quad word"?

What are the alternative terms for "octlet"?

答:
What is wrong with specifying the number of bits? When I need this type of precision, I usually just refer to the number of bits used, i.e. 32-bit integer or 64-bit integer. For shorter, more pronounceable, names just tack on the bit specifier after the type, such as int32/int64 (which is something I often say but rarely write).

I am not sure of the idiomatic way to express this in Russian though, that will be up to you to decide :-)

Title: Octlet, quad word or what?


问:
Elasticsearch - Post Data using Java 1.4
We are using Java 1.4 and we would like to push data to the ELK stack.

I checked their site and googled and its mostly turning up artifacts/articles

that need more than 1.5.Are they any options since we cant change the current

java version installed.

Regards

答:
Java SE 6 was released in 2006 and if I remember correctly the minimum version for Elasticsearch (first public release in 2010) even in the early days has been that.

The oldest docs available on the Elastic website are for 0.90 and that is ancient. Even if you could run an older version, there are no docs for it, so you really don't want to go there.

While upgrading existing applications can be a challenge, it's still not possible to run new services on newer versions? Anyway, you need to get to Java 6 at the very least or rather 8 for current versions.


问:
Renaming models in database with existing data when using RavenDb
Is there any 'easy' way to rename models in RavenDb when the database already has existing data? I have various models which were originally created in another language, and now I would like to rename them to English as the codebase is becoming quite unmaintainable.  If I just rename them, then the data won't be loaded because the properties don't match anymore.

I would like the system to automatically do it on first load. Is there any best way how to approach this?  My solution would be:

Check if a document exists to determine if the upgrade has been done or not

If upgrade has not been done, execute patch scripts to update fields

Update document to know that the upgrade has been done

答:
I'd recommend you create new documents from the old documents.

This can be done pretty easily using patching via docStore.UpdateByIndex.

Suppose I had an old type name, Foo, and wanted to rename it to the new type name, Bar. And I wanted all the IDs to change from Foos/123 to Bars/123.

It would look something like this:

```<code>var patchScript = @"
   // Copy all the properties from the old document
   var newDoc = {};
   for (var prop in this) {
       if (prop !== '@metadata') {
          newDoc[prop] = this[prop];
       }
   }

   // Create the metadata.
   var meta = {};
   meta['Raven-Entity-Name'] = newCollection;
   meta['Raven-Clr-Type'] = newType;

   // Store the new document.
   var newId = __document_id.replace(oldCollection, newCollection);
   PutDocument(newId, newDoc, meta);
";

var oldCollection = "Foos";
var newCollection = "Bars";
var newType = "KarlCassar.Bar, KarlCassar"; // Where KarlCassar is your assembly name.
var query = new IndexQuery { Query = $"Tag:{oldCollection}" };
var options = new BulkOperationOptions { AllowStale = false };
var patch = new ScriptedPatchRequest
{
   Script = patchScript,
   Values = new Dictionary<string, object>
   {
       { nameof(oldCollection), oldCollection },
       { nameof(newCollection), newCollection },
       { nameof(newType), newType }
   }
};

var patchOperation = docStore.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName", query, patch, options);
patchOperation.WaitForCompletion();
</code>```

Run that code once at startup, and then your app will be able to work with the new name entities. Your old entities are still around - those can be safely deleted via the Studio.

Body:
I'd recommend you create new documents from the old documents.

This can be done pretty easily using patching via docStore.UpdateByIndex.

Suppose I had an old type name, Foo, and wanted to rename it to the new type name, Bar. And I wanted all the IDs to change from Foos/123 to Bars/123.

It would look something like this:

var patchScript = @"
   // Copy all the properties from the old document
   var newDoc = {};
   for (var prop in this) {
       if (prop !== '@metadata') {
          newDoc[prop] = this[prop];
       }
   }

   // Create the metadata.
   var meta = {};
   meta['Raven-Entity-Name'] = newCollection;
   meta['Raven-Clr-Type'] = newType;

   // Store the new document.
   var newId = __document_id.replace(oldCollection, newCollection);
   PutDocument(newId, newDoc, meta);
";

var oldCollection = "Foos";
var newCollection = "Bars";
var newType = "KarlCassar.Bar, KarlCassar"; // Where KarlCassar is your assembly name.
var query = new IndexQuery { Query = $"Tag:{oldCollection}" };
var options = new BulkOperationOptions { AllowStale = false };
var patch = new ScriptedPatchRequest
{
   Script = patchScript,
   Values = new Dictionary<string, object>
   {
       { nameof(oldCollection), oldCollection },
       { nameof(newCollection), newCollection },
       { nameof(newType), newType }
   }
};

var patchOperation = docStore.DatabaseCommands.UpdateByIndex("Raven/DocumentsByEntityName", query, patch, options);
patchOperation.WaitForCompletion();

Run that code once at startup, and then your app will be able to work with the new name entities. Your old entities are still around - those can be safely deleted via the Studio.


问:
How do I get the border the move up and down when "Up" and "Down" button is clicked?
I would just like the border to move up and down when I click the up or down button.

$(document).ready(function() {
  $("#up").click(function() {
    $("#up").prev().css("border", "2px solid blue");
  });
});

$(document).ready(function() {
  $("#down").click(function() {
    $("p").next().css("border", "2px solid blue");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four">paragraph 4</p>

<button id="up">Up</button>
<button id="down">Down</button></code>```

How can I achieve this using jQuery?

答:
This is how I would do it (comments in code):

var ps = $('p'),      // cache the paragraphs
    currentIndex = 3; // starting at paragraph 4

$("#up").click(function() {
  currentIndex -= 1;             // decrement index
  if (currentIndex < 0) {
    currentIndex = ps.length - 1;  // set back to bottom item
  }

  ps.removeClass('border');
  ps.eq(currentIndex).addClass('border')
});

$("#down").click(function() {
  currentIndex += 1;              // increment index
  if (currentIndex == ps.length) {
    currentIndex = 0;             // set back to top item
  }

  ps.removeClass('border');
  ps.eq(currentIndex).addClass('border')
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.border {
    border:2px solid blue;
}</code>```

paragraph 1

paragraph 2

paragraph 3

paragraph 4

<button id="up">Up</button>
<button id="down">Down</button>```

Body:
I would just like the border to move up and down when I click the up or down button.

$(document).ready(function() {
  $("#up").click(function() {
    $("#up").prev().css("border", "2px solid blue");
  });
});

$(document).ready(function() {
  $("#down").click(function() {
    $("p").next().css("border", "2px solid blue");
  });
});

paragraph 1

paragraph 2

paragraph 3

paragraph 4

<button id="up">Up</button>
<button id="down">Down</button>

How can I achieve this using jQuery?

Body:
This is how I would do it (comments in code):

var ps = $('p'),      // cache the paragraphs
    currentIndex = 3; // starting at paragraph 4

$("#up").click(function() {
  currentIndex -= 1;             // decrement index
  if (currentIndex < 0) {
    currentIndex = ps.length - 1;  // set back to bottom item
  }

  ps.removeClass('border');
  ps.eq(currentIndex).addClass('border')
});

$("#down").click(function() {
  currentIndex += 1;              // increment index
  if (currentIndex == ps.length) {
    currentIndex = 0;             // set back to top item
  }

  ps.removeClass('border');
  ps.eq(currentIndex).addClass('border')
});

.border {
    border:2px solid blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four" class="border">paragraph 4</p>

<button id="up">Up</button>
<button id="down">Down</button>


问:
Using string as array indices in NumPy
I'm handling large numerical arrays in python through a GUI.
I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand.

Simple example of what I'd like to do:

```<code>arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

a = "2:4" # example string from GUI Textbox
b = "[3, 4, 5]" # example string from GUI Textbox

print arr[a] # not valid code -> what should be written here to make it work?
print arr[b] # not valid code -> what should be written here to make it work?
</code>```

should output:

```<code>[20, 30]
[30, 40, 50]
</code>```

I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?

答:
Maybe since you are only expecting a very limited character set it is acceptable using eval this once:

```<code>if not all(c in "1234567890-[],: " for c in b): # maybe also limit the length of b?
    # tell user you couldn't parse and exit this branch
slice_ = eval(f'np.s_[{b}]')
# slice_ can now be applied to your array: arr[slice_]
</code>```

Title: Using string as array indices in NumPy

Body:
I'm handling large numerical arrays in python through a GUI.
I'd like to expose the slicing capabilities to a textbox in a GUI, so I can easily choose part of the array that should be used for the calculation at hand.

Simple example of what I'd like to do:

arr = array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

a = "2:4" # example string from GUI Textbox
b = "[3, 4, 5]" # example string from GUI Textbox

print arr[a] # not valid code -> what should be written here to make it work?
print arr[b] # not valid code -> what should be written here to make it work?

should output:

[20, 30]
[30, 40, 50]

I found out about the slice function, but I'd need to parse my string manually and create a slice. Is there a simpler way?

Body:
Maybe since you are only expecting a very limited character set it is acceptable using eval this once:

if not all(c in "1234567890-[],: " for c in b): # maybe also limit the length of b?
    # tell user you couldn't parse and exit this branch
slice_ = eval(f'np.s_[{b}]')
# slice_ can now be applied to your array: arr[slice_]


问:
How to git ignore folder based on content
Is it possible to ignore a full folder based on some criteria about it's content. For example I want to ignore everything in all folders that contain at least one html file. How can this be done? (If at all)</p>

答:
There is no such functionality in Git, and it doesn't make much sense to have it, anyway.

If you have some files in a directory you can easily inspect them to find out if there is any .html file amongst them. If there are many directories (with subdirectories) a simple command line can find the .html files and produce the needed rules to put in .gitignore.

If a .html file is created later in a directory that was not previously ignored, adding the directory path to .gitignore is not enough, you also have to remove the existing tracked files from the repo.

A simple command to get all .html files and produce the rules to put in .gitignore:

```<code>find . -name '*.html' -exec dirname \{\} \; | sort -u
</code>```

It finds all the .html files from the current directory and its subdirectories and executes dirname for each of them. The output of find is then piped to sort that sorts them and removes the duplicates (-u).

(I didn't test its output with Git, it might need small tweaking but this is the idea.)

Body:
There is no such functionality in Git, and it doesn't make much sense to have it, anyway.

If you have some files in a directory you can easily inspect them to find out if there is any .html file amongst them. If there are many directories (with subdirectories) a simple command line can find the .html files and produce the needed rules to put in .gitignore.

If a .html file is created later in a directory that was not previously ignored, adding the directory path to .gitignore is not enough, you also have to remove the existing tracked files from the repo.

A simple command to get all .html files and produce the rules to put in .gitignore:

find . -name '*.html' -exec dirname \{\} \; | sort -u

It finds all the .html files from the current directory and its subdirectories and executes dirname for each of them. The output of find is then piped to sort that sorts them and removes the duplicates (-u).

(I didn't test its output with Git, it might need small tweaking but this is the idea.)


问:
Compare two dates strictly in AngularJS
I am trying to compare two dates where the first is always greater than the second, it is important to note that the format obtained comes in yyyyMM/dd.

For example:

```<code>var date1 = yyyy/MM/dd;
var date2 = yyyy/MM/dd;
date1> date2
</code>```

the possible solutions like data1.getTime (), have not worked for me.

I am using AngularJS 1.5.11

I ask you please help me

答:
```<code>                    var first = "2017/11/16";
                    var second = "2017/11/14"
                    var valuate1 = (new Date(first)).getTime();
                    var valuate2 = (new Date(second)).getTime();

                    if(valuate1 > valuate2)
                    {
                     console.log(true);
                    }else{
                      console.log(false);
                    }
</code>```

Thank you very much @Aleksey Solovey for your clarification!

Title: Compare two dates strictly in AngularJS

Body:
I am trying to compare two dates where the first is always greater than the second, it is important to note that the format obtained comes in yyyyMM/dd.

For example:

var date1 = yyyy/MM/dd;
var date2 = yyyy/MM/dd;
date1> date2

the possible solutions like data1.getTime (), have not worked for me.

I am using AngularJS 1.5.11

I ask you please help me

Body:
                    var first = "2017/11/16";
                    var second = "2017/11/14"
                    var valuate1 = (new Date(first)).getTime();
                    var valuate2 = (new Date(second)).getTime();

                    if(valuate1 > valuate2)
                    {
                     console.log(true);
                    }else{
                      console.log(false);
                    }

Thank you very much @Aleksey Solovey for your clarification!


问:
How to send the SMS message to multiple users separately (Not at a time) using nodejs?
I want to send the SMS to multiple users using node.js code.what is the procedure to be followed? I had little bit experience to send the sms to single user. But I don't know how to send the sms to multiple users. I have enclosed the code to send SMS to the single user. But before 6 Months these code works fine. But now it doesn't work. Can anyone provide the solution for this two problem?

var accountSid = 'cnsjs'; // Your Account SID from www.twilio.com/console
var authToken = 'chdcbhh';   // Your Auth Token from www.twilio.com/console

var twilio = require('twilio');
var client = new twilio(accountSid, authToken);

client.messages.create({
    body: 'Hello hai I am vignesh Ravi . I sent the message from twilio account',
    to:   '+121331161616',  // Text this number
    from: '+18597401144' // From a valid Twilio number
}).then(function(message)
{
    console.log("Messages sent to 1213311161616");
});```

答:
if you want to send multiple messages at the same time you need to use Promise.all. I have updated your code with something that i think will work for you i created it using bluebird.js because i am familiar with it and it has kickass tools.

tri this:

```<code>var accountSid = 'cnsjs'; // Your Account SID from www.twilio.com/console
var authToken = 'chdcbhh';   // Your Auth Token from www.twilio.com/console
var Promise = require('bluebird');

var twilio = require('twilio');
var client = new twilio(accountSid, authToken);

var promises = [];

// add all the different send promises to this array like following

promises.push(
    client.messages.create({
        body: 'Hello hai I am vignesh Ravi . I sent the message from twilio account',
        to:   '+121331161616',  // Text this number
        from: '+18597401144' // From a valid Twilio number
    })
)

var result = {
    sent: [],
    failed: []
};

var finalPromise = Promise.all(promises.map(function (p) {
    return Promise.resolve(p).reflect(); // resolve will convert it to bluebird promise and reflect will make it always successful
})).each(function (inspection) {
    if (inspection.isFulfilled()) { //this means the send was successful
        result.sent.push(inspection.value());
    } else { //this means there was an error
        result.failed.push(inspection.reason());
    }
}).then(function () {
    return result;
})

finalPromise.then(function (res) {
    console.log(JSON.stringify(res))
})
</code>```

you might have to fix the code a bit before it starts to work as you intend it

Edit

i made small changes to code where i am calling the collective promise at the end. give it a try and let me know if it works

Body:
if you want to send multiple messages at the same time you need to use Promise.all. I have updated your code with something that i think will work for you i created it using bluebird.js because i am familiar with it and it has kickass tools.

tri this:

var accountSid = 'cnsjs'; // Your Account SID from www.twilio.com/console
var authToken = 'chdcbhh';   // Your Auth Token from www.twilio.com/console
var Promise = require('bluebird');

var twilio = require('twilio');
var client = new twilio(accountSid, authToken);

var promises = [];

// add all the different send promises to this array like following

promises.push(
    client.messages.create({
        body: 'Hello hai I am vignesh Ravi . I sent the message from twilio account',
        to:   '+121331161616',  // Text this number
        from: '+18597401144' // From a valid Twilio number
    })
)

var result = {
    sent: [],
    failed: []
};

var finalPromise = Promise.all(promises.map(function (p) {
    return Promise.resolve(p).reflect(); // resolve will convert it to bluebird promise and reflect will make it always successful
})).each(function (inspection) {
    if (inspection.isFulfilled()) { //this means the send was successful
        result.sent.push(inspection.value());
    } else { //this means there was an error
        result.failed.push(inspection.reason());
    }
}).then(function () {
    return result;
})

finalPromise.then(function (res) {
    console.log(JSON.stringify(res))
})

you might have to fix the code a bit before it starts to work as you intend it

Edit

i made small changes to code where i am calling the collective promise at the end. give it a try and let me know if it works


问:
Pyside2 how to open the dialog but not always on top
I create a main frame and a pushbutton ,

and let button clicked to open a dialog , but the dialog always on top ,

I try to used setWindowsFlag but not work.

```<code>from PySide2.QtWidgets import QApplication,QMainWindow,QTabWidget,QWidget
from PySide2.QtWidgets import QMessageBox,QFileDialog,QErrorMessage
from PySide2 import QtCore, QtGui, QtWidgets
class UI_Test20(object):
    def setupUi(self, Test202):
        Test202.setObjectName("Test202")
        Test202.resize(100,100)
        self.centralwidget = QtWidgets.QWidget(Test202)
        self.centralwidget.setObjectName("centralwidget")
        self.pb = QtWidgets.QPushButton(self.centralwidget)
        self.pb.setText('push button!')
        Test202.setCentralWidget(self.centralwidget)
        self.pb.clicked.connect(self.btnClicked)
        self.retranslateUi(Test202)
        QtCore.QMetaObject.connectSlotsByName(Test202)

    def retranslateUi(self, Test202):
        Test202.setWindowTitle(QtWidgets.QApplication.translate("Test202", "MainWindow", None, -1))

    def btnClicked(self):
        ui = Ui_Dialog1(self)
        ui.show()

class Test20(QMainWindow, UI_Test20) :

    def __init__(self, parent):
        super(Test20, self).__init__(parent)
        self.setupUi(self)
</code>```

and the dialog code

```<code>class Ui_Dialog1(QtWidgets.QDialog):

    def __init__(self, parent=None):
        super(Ui_Dialog1, self).__init__(parent)
        self.p = parent
        self.setupUi(self)

    def setupUi(self, Dialog1):
        Dialog1.setObjectName("Dialog1")
        Dialog1.resize(333, 173)
</code>```

main

```<code>if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = Test20(None)
    ui.show()
    sys.exit(app.exec_())
</code>```

答:
The problem is caused by the fact that the main window is the parent of the QDialog, so it must be removed, but if that is done, the garbage collector will delete it, so the QDialog member of the class must be made:

```<code>def btnClicked(self):
    self.ui = Ui_Dialog1()
    self.ui.show()
</code>```

Plus: the correct thing is not to modify the design so I move the connection and the slot associated with the clicked button pb and if we want it to close when the window closes we overwrite the closeEvent() method:

```<code>class Test20(QMainWindow, UI_Test20):
    def __init__(self, parent):
        super(Test20, self).__init__(parent)
        self.setupUi(self)
        self.pb.clicked.connect(self.btnClicked)

    def btnClicked(self):
        self.ui = Ui_Dialog1()
        self.ui.show()

    def closeEvent(self, *args, **kwargs):
        self.ui.close()
        QMainWindow.closeEvent(self, *args, **kwargs)
</code>```

Body:
I create a main frame and a pushbutton ,

and let button clicked to open a dialog , but the dialog always on top ,

I try to used setWindowsFlag but not work.

from PySide2.QtWidgets import QApplication,QMainWindow,QTabWidget,QWidget
from PySide2.QtWidgets import QMessageBox,QFileDialog,QErrorMessage
from PySide2 import QtCore, QtGui, QtWidgets
class UI_Test20(object):
    def setupUi(self, Test202):
        Test202.setObjectName("Test202")
        Test202.resize(100,100)
        self.centralwidget = QtWidgets.QWidget(Test202)
        self.centralwidget.setObjectName("centralwidget")
        self.pb = QtWidgets.QPushButton(self.centralwidget)
        self.pb.setText('push button!')
        Test202.setCentralWidget(self.centralwidget)
        self.pb.clicked.connect(self.btnClicked)
        self.retranslateUi(Test202)
        QtCore.QMetaObject.connectSlotsByName(Test202)

    def retranslateUi(self, Test202):
        Test202.setWindowTitle(QtWidgets.QApplication.translate("Test202", "MainWindow", None, -1))

    def btnClicked(self):
        ui = Ui_Dialog1(self)
        ui.show()

class Test20(QMainWindow, UI_Test20) :

    def __init__(self, parent):
        super(Test20, self).__init__(parent)
        self.setupUi(self)

and the dialog code

class Ui_Dialog1(QtWidgets.QDialog):

    def __init__(self, parent=None):
        super(Ui_Dialog1, self).__init__(parent)
        self.p = parent
        self.setupUi(self)

    def setupUi(self, Dialog1):
        Dialog1.setObjectName("Dialog1")
        Dialog1.resize(333, 173)

main

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = Test20(None)
    ui.show()
    sys.exit(app.exec_())

Body:
The problem is caused by the fact that the main window is the parent of the QDialog, so it must be removed, but if that is done, the garbage collector will delete it, so the QDialog member of the class must be made:

def btnClicked(self):
    self.ui = Ui_Dialog1()
    self.ui.show()

Plus: the correct thing is not to modify the design so I move the connection and the slot associated with the clicked button pb and if we want it to close when the window closes we overwrite the closeEvent() method:

class Test20(QMainWindow, UI_Test20):
    def __init__(self, parent):
        super(Test20, self).__init__(parent)
        self.setupUi(self)
        self.pb.clicked.connect(self.btnClicked)

    def btnClicked(self):
        self.ui = Ui_Dialog1()
        self.ui.show()

    def closeEvent(self, *args, **kwargs):
        self.ui.close()
        QMainWindow.closeEvent(self, *args, **kwargs)


问:
Laravel exception not catching
I'm trying to do a very basic exception try catch, but it doesn't catch.

```<code> $id =0;
 try {
        $question = $this->model->find($id);  // will not find anything since $id = 0
        $question->delete(); // throw an exception
        return true;
 } catch (\Exception $e) {
        dd ('hello');  // should end up here, but no?!?!?
 } catch (FatalThrowableError $f) {
        echo ("fatal"); // or here... but no.
 }
</code>```

but the catch doesn't "catch". I get an Fatal error in the browser saying that delete was called on a null object. But that's exactly what I was trying to do: do a delete on a null object (id = 0 is not in the DB), to test the exception.

I have tried

```<code>use Symfony\Component\Debug\Exception;
use Symfony\Component\Debug\Exception\FatalThrowableError;
</code>```

or simply

```<code>Exception;
FatalThrowableError;
</code>```

Also, having the \Exception $e  or Exception $e (with or without ) doesn't change anything.

Note that if I add a line like  $foo = 4/0    I get into the Exception section (dd (hello)).

in .env   APP_DEBUG=true, APP_LOG_LEVEL=debug

I'm on Laravel 5.5 using PHP 7.0.10 on windows 7.

答:
http://php.net/manual/en/language.errors.php7.php

As the Error hierarchy does not inherit from Exception, code that uses
  catch (Exception $e) { ... } blocks to handle uncaught exceptions in
  PHP 5 will find that these Errors are not caught by these blocks.
  Either a catch (Error $e) { ... } block or a set_exception_handler()
  handler is required.

You can, additionally, catch (\Throwable $e) {} to account for both Error and Exception types.

Title: Laravel exception not catching

Body:
I'm trying to do a very basic exception try catch, but it doesn't catch.

 $id =0;
 try {
        $question = $this->model->find($id);  // will not find anything since $id = 0
        $question->delete(); // throw an exception
        return true;
 } catch (\Exception $e) {
        dd ('hello');  // should end up here, but no?!?!?
 } catch (FatalThrowableError $f) {
        echo ("fatal"); // or here... but no.
 }

but the catch doesn't "catch". I get an Fatal error in the browser saying that delete was called on a null object. But that's exactly what I was trying to do: do a delete on a null object (id = 0 is not in the DB), to test the exception.

I have tried

use Symfony\Component\Debug\Exception;
use Symfony\Component\Debug\Exception\FatalThrowableError;

or simply

Exception;
FatalThrowableError;

Also, having the \Exception $e  or Exception $e (with or without ) doesn't change anything.

Note that if I add a line like  $foo = 4/0    I get into the Exception section (dd (hello)).

in .env   APP_DEBUG=true, APP_LOG_LEVEL=debug

I'm on Laravel 5.5 using PHP 7.0.10 on windows 7.


问:
Why does my XSL strip out all the tags?
I have this inbound XML (as a web service) :

```<code><?xml version="1.0" encoding="UTF-8"?><Envelope>
    <Body>
        <send_message>
            <user>
                <now>2017-11-17T13:38:11+00:00</now>
                <company>xyz.demo</company>
            </user>
            <messages>
                <message>
                    <app_host>app102.example.com</app_host>
                    <app_port>31632</app_port>
.....
</code>```

and I'm executing this XSL against it:

```<code><?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ms="urn:schemas-microsoft-com:xslt">

<xsl:template match="//Envelope/Body/send_message/user/now">
  <now>
    <xsl:variable name="srcDateTime" select="//Envelope/Body/send_message/user/now"/>
    <xsl:variable name="srcDate" select="substring-before($srcDateTime, 'T')" />
    <xsl:variable name="outDate" select="format-date(xs:date($srcDate),'[D01].[M01].[Y0001]')"/>
    <xsl:copy-of select="$outDate"/>
  </now>
</xsl:template>
</xsl:stylesheet>
</code>```

My intention is to reformat the date in the <now></now tags - which it does perfectly - but it also strips out all the other tags from the XML, when I need them in so I can extract data using XPath in further manipulation steps. This is what the result looks like:

```<code><?xml version="1.0" encoding="UTF-8"?>

                <now xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ms="urn:schemas-microsoft-com:xslt">17.11.2017</now>
                xyz.demo

                    app102.example.com
                    31632

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

You can see that all the other tags have been completely stripped away (just leaving white space behind), and I just don't understand why that's happening. What am I missing (other than the tags!)?

To further explain - these missing tags aren't null, they have data in them. As you can see, from the result I posted, the data is still there, but the enclosing tags are missing. I need the data back in the original enclosing tags.

答:
If you want your XML unmodified except for <now>, you just need to add an identity transform:

```<code><xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>
</code>```

Your other template will override it only on the nodes corresponding to the specified xpath //Envelope/Body/send_message/user/now.

(edit: As Martin Müller pointed out, you should consider to reduce that absolute path to the necessary relative path, depending on your usecase, e.g. simply now or, if you need to limit the scope of the expression, user/now.)

Title: Why does my XSL strip out all the tags?

Body:
I have this inbound XML (as a web service) :

<?xml version="1.0" encoding="UTF-8"?><Envelope>

        <send_message>
            <user>
                <now>2017-11-17T13:38:11+00:00</now>
                <company>xyz.demo</company>
            </user>
            <messages>
                <message>
                    <app_host>app102.example.com</app_host>
                    <app_port>31632</app_port>
.....

and I'm executing this XSL against it:

<?xml version='1.0'?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:ms="urn:schemas-microsoft-com:xslt">

<xsl:template match="//Envelope/Body/send_message/user/now">
  <now>
    <xsl:variable name="srcDateTime" select="//Envelope/Body/send_message/user/now"/>
    <xsl:variable name="srcDate" select="substring-before($srcDateTime, 'T')" />
    <xsl:variable name="outDate" select="format-date(xs:date($srcDate),'[D01].[M01].[Y0001]')"/>
    <xsl:copy-of select="$outDate"/>
  </now>
</xsl:template>
</xsl:stylesheet>

My intention is to reformat the date in the <now></now tags - which it does perfectly - but it also strips out all the other tags from the XML, when I need them in so I can extract data using XPath in further manipulation steps. This is what the result looks like:

<?xml version="1.0" encoding="UTF-8"?>

                <now xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ms="urn:schemas-microsoft-com:xslt">17.11.2017</now>
                xyz.demo

                    app102.example.com
                    31632

 .....

You can see that all the other tags have been completely stripped away (just leaving white space behind), and I just don't understand why that's happening. What am I missing (other than the tags!)?

To further explain - these missing tags aren't null, they have data in them. As you can see, from the result I posted, the data is still there, but the enclosing tags are missing. I need the data back in the original enclosing tags.

Body:
If you want your XML unmodified except for <now>, you just need to add an identity transform:

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

Your other template will override it only on the nodes corresponding to the specified xpath //Envelope/Body/send_message/user/now.

(edit: As Martin Müller pointed out, you should consider to reduce that absolute path to the necessary relative path, depending on your usecase, e.g. simply now or, if you need to limit the scope of the expression, user/now.)


问:
Why doesn't Future.get(...) kill the thread?
I have an application that is using future for asynchronous execution.

I set the parameter on get method, that the thread should get killed after 10 seconds, when it does not get the response:

```<code> Future<RecordMetadata> meta = producer.send(record, new ProducerCallBack());
      RecordMetadata data = meta.get(10, TimeUnit.SECONDS);
</code>```

But the thread get killed after 60 second:

```<code>java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
    at org.apache.kafka.clients.producer.KafkaProducer$FutureFailure.<init>(KafkaProducer.java:1124)
    at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:823)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:760)
    at io.khinkali.KafkaProducerClient.main(KafkaProducerClient.java:49)
Caused by: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
</code>```

What am I doing wrong?

答:
I set the parameter on get method, that the thread should get killed after 10 seconds, when it does not get the response:

If we are talking about Future.get(...) there is nothing about it that "kills" the thread at all.  To quote from the javadocs, the Future.get(...) method:

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

If the get(...) method times out then it will throw TimeoutException but your thread is free to continue to run.  If you want to stop the thread running then you'll need to catch TimeoutException and then call meta.cancel(true) but even that doesn't guarantee that the thread will be "killed".  That causes the thread to be interrupted which means that certain methods will throw InterruptedException or the thread needs to be checking for Thread.currentThread().isInterrupted().

java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.

Yeah this timeout has nothing to do with the Future.get(...) timeout.

Body:
I have an application that is using future for asynchronous execution.

I set the parameter on get method, that the thread should get killed after 10 seconds, when it does not get the response:

 Future<RecordMetadata> meta = producer.send(record, new ProducerCallBack());
      RecordMetadata data = meta.get(10, TimeUnit.SECONDS);

But the thread get killed after 60 second:

java.util.concurrent.ExecutionException: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.
    at org.apache.kafka.clients.producer.KafkaProducer$FutureFailure.<init>(KafkaProducer.java:1124)
    at org.apache.kafka.clients.producer.KafkaProducer.doSend(KafkaProducer.java:823)
    at org.apache.kafka.clients.producer.KafkaProducer.send(KafkaProducer.java:760)
    at io.khinkali.KafkaProducerClient.main(KafkaProducerClient.java:49)
Caused by: org.apache.kafka.common.errors.TimeoutException: Failed to update metadata after 60000 ms.

What am I doing wrong?


问:
Pytorch: Convert FloatTensor into DoubleTensor
I have 2 numpy arrays, which I convert into tensors to use the TensorDataset object.

```<code>import torch.utils.data as data_utils

X = np.zeros((100,30))
Y = np.zeros((100,30))

train = data_utils.TensorDataset(torch.from_numpy(X).double(), torch.from_numpy(Y))
train_loader = data_utils.DataLoader(train, batch_size=50, shuffle=True)
</code>```

when I do:

```<code>for batch_idx, (data, target) in enumerate(train_loader):
    data, target = Variable(data), Variable(target)
    optimizer.zero_grad()
    output = model(data)               # error occurs here
</code>```

I get the fallowing error:

TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.DoubleTensor, torch.FloatTensor), but expected one of:
   [...]

   * (float beta, float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
        didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, torch.FloatTensor)

   * (float beta, float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
        didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, torch.FloatTensor)

The last error comes from:

output.addmm_(0, 1, input, weight.t())

As you see in my code I tried converting the tensor by using .double() - but this did not work. Why is he casting one array into a FloatTensor object and the other into a DoubleTensor?
Any ideas?

答:
This is because in PyTorch, you can not do operations between Tensor of different types. Your data is DoubleTensor, but the model parameter are FloatTensor. So you get this error message. As @mexmex have said, convert data to FloatTensor to make it conform with the model parameter type.

Do not do the other way around! Trying to convert the model to double is greatly discouraged by PyTorch devs as GPUs are not good at double precision computation. Also, floating point is pretty enough for deep learning.

Body:
I have 2 numpy arrays, which I convert into tensors to use the TensorDataset object.

import torch.utils.data as data_utils

X = np.zeros((100,30))
Y = np.zeros((100,30))

train = data_utils.TensorDataset(torch.from_numpy(X).double(), torch.from_numpy(Y))
train_loader = data_utils.DataLoader(train, batch_size=50, shuffle=True)

when I do:

for batch_idx, (data, target) in enumerate(train_loader):
    data, target = Variable(data), Variable(target)
    optimizer.zero_grad()
    output = model(data)               # error occurs here

I get the fallowing error:

TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.DoubleTensor, torch.FloatTensor), but expected one of:
   [...]

   * (float beta, float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
        didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, torch.FloatTensor)

   * (float beta, float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
        didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, torch.FloatTensor)

The last error comes from:

output.addmm_(0, 1, input, weight.t())

As you see in my code I tried converting the tensor by using .double() - but this did not work. Why is he casting one array into a FloatTensor object and the other into a DoubleTensor?
Any ideas?


问:
local xml parsing in android

Possible Duplicate:

  Parsing local xml file in android

Hi every one, In this folowing link there is a xml parser

http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser/#idc-cover

instead of using
url can i use the xml file stored locally, means inside "res/xml/*.xml"
can any one provide me a code for dat...(am brand new to android, pls help me)

答:
try using assest folder like this

```<code>    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {

        stream = assetManager.open("sample.xml");

    } catch (IOException e) {

        // handle

    }
</code>```

and use this

```<code>xr.parse(stream);
</code>```

stream object instead of

```<code>xr.parse(new InputSource(sourceUrl.openStream()));
</code>```

One thing more: download this file and use above code  put this file in ur assest folder

Title: local xml parsing in android

Body:
try using assest folder like this

    AssetManager assetManager = getAssets();
    InputStream stream = null;

    try {

        stream = assetManager.open("sample.xml");

    } catch (IOException e) {

        // handle

    }

and use this

xr.parse(stream);

stream object instead of

xr.parse(new InputSource(sourceUrl.openStream()));

One thing more: download this file and use above code  put this file in ur assest folder