问:
Prefered style for multiple elements in JSON?
I am trying to represent a user's selection with a JSON object, and I am uncertain about the exact representation.

A user can select up to 4 unique elements from a list of items. The list of items will increase over time, while the choice of 4 elements is unlikely to ever change (but not impossible).

Is it better to store the selection as object with four properties or as array? Here is my rationale:

As Properties

```<code>"selection" : {
    "selection1" : "itemFoo",
    "selection2" : "itemBar",
    "selection3" : "itemBaz",
    "selection4" : null //<-- User does not need to select all 4 items
}
</code>```

Pros:

Does not allow more than 4 items selected by design

Cons:

Makes it more difficult to check for uniqueness than in an array

Makes extension more difficult than in an array

As Array

```<code>"selection" : [
    "itemFoo", "itemBar", "itemBaz"
]
</code>```

Pros:

Less overhead

More intuitive representation of multiple items

Cons:

Requires assertion to ensure that the array does not contain more than 4 elements

答:
Going with the first approach is an overkill.
It's going to be harder to build the list especially if you allow to select / unselect items.

The trade-of in asserting the number of items isn't that big, so I would go with the second approach.

Based on the programming language that you use, you can enforce the desired size.

Body:
I am trying to represent a user's selection with a JSON object, and I am uncertain about the exact representation.

A user can select up to 4 unique elements from a list of items. The list of items will increase over time, while the choice of 4 elements is unlikely to ever change (but not impossible).

Is it better to store the selection as object with four properties or as array? Here is my rationale:

As Properties

"selection" : {
    "selection1" : "itemFoo",
    "selection2" : "itemBar",
    "selection3" : "itemBaz",
    "selection4" : null //<-- User does not need to select all 4 items
}

Pros:

Does not allow more than 4 items selected by design

Cons:

Makes it more difficult to check for uniqueness than in an array

Makes extension more difficult than in an array

As Array

"selection" : [
    "itemFoo", "itemBar", "itemBaz"
]

Pros:

Less overhead

More intuitive representation of multiple items

Cons:

Requires assertion to ensure that the array does not contain more than 4 elements


来源: stackexchange

问:
Can't Set correct date and time to Calendar
I am getting date time as String in this format from the server:2017-11-15 16:27:02

I want to set Calendar with this time so I Do something like this:

```<code> String[] dateTime = response.body().getUser().getUserSessionExpire().split(" ");
 String[] date = dateTime[0].split("-");
 String[] time = dateTime[1].split(":");
 Log.i("TIMMEE", "Received TIME: " + response.body().getUser().getUserSessionExpire());

 int month = Integer.parseInt(date[1]);
 int day = Integer.parseInt(date[2]);
 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.YEAR, Integer.parseInt(date[0]));
 calendar.set(Calendar.MONTH, month);
 calendar.set(Calendar.DAY_OF_MONTH, day);
 calendar.set(Calendar.HOUR, Integer.parseInt(time[0]));
 calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
 calendar.set(Calendar.SECOND, Integer.parseInt(time[2]));
</code>```

For example, if I get

2017-11-15 16:27:02

Calendar will set for :

2017-12-15 16:27:02 Or 2017-11-16 16:27:02

Actually, Month or Day will change!
What is the problem?

Thankyou for your answers.

答:
You do not need to split the date . SimpleDateFormat is responsible for formating . So you can parse the date and get Date object from it . See code below and read the SimpleDateFormat(linked above).</p>

```<code>Calendar calendar=Calendar.getInstance();
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd H:m:s", Locale.getDefault());
    try {
       Date d = DATE_FORMAT.parse("2017-11-15 16:27:02");
        calendar.setTime(d);// Use this calender
    } catch (ParseException e) {
        e.printStackTrace();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting date time as String in this format from the server:2017-11-15 16:27:02

I want to set Calendar with this time so I Do something like this:

 String[] dateTime = response.body().getUser().getUserSessionExpire().split(" ");
 String[] date = dateTime[0].split("-");
 String[] time = dateTime[1].split(":");
 Log.i("TIMMEE", "Received TIME: " + response.body().getUser().getUserSessionExpire());

 int month = Integer.parseInt(date[1]);
 int day = Integer.parseInt(date[2]);
 Calendar calendar = Calendar.getInstance();
 calendar.set(Calendar.YEAR, Integer.parseInt(date[0]));
 calendar.set(Calendar.MONTH, month);
 calendar.set(Calendar.DAY_OF_MONTH, day);
 calendar.set(Calendar.HOUR, Integer.parseInt(time[0]));
 calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
 calendar.set(Calendar.SECOND, Integer.parseInt(time[2]));

For example, if I get

2017-11-15 16:27:02

Calendar will set for :

2017-12-15 16:27:02 Or 2017-11-16 16:27:02

Actually, Month or Day will change!
What is the problem?

Thankyou for your answers.

Body:
You do not need to split the date . SimpleDateFormat is responsible for formating . So you can parse the date and get Date object from it . See code below and read the SimpleDateFormat(linked above).

Calendar calendar=Calendar.getInstance();
    SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd H:m:s", Locale.getDefault());
    try {
       Date d = DATE_FORMAT.parse("2017-11-15 16:27:02");
        calendar.setTime(d);// Use this calender
    } catch (ParseException e) {
        e.printStackTrace();
    }


问:
How does the Codepen fixed menu work?
When using Codepen on a mobile device (with the pen in fullscreen mode), the menu stays fixed at the top of the page while the rest of the content scrolls behind it. On inspecting the element, there does not seem to be any position:fixed or position:absolute being set nor any inline styles being written by Javascript. I can't see any properties which would seem to be defining this behaviour.

So how have they made the menu sticky like this? And if you were able to find out: how did you find out? As a junior dev it's just as helpful to know the way a solution was found as it is to know the solution :)

答:
Could you show us at least a screenshot of what you are trying to reproduce and a sample of what you have tried so far ?

If you looked a little more in detail, you'd see that the view is inside an iframe, so the scrolling actually occurs inside the iframe, that's why the menu holds still on top. You could have noticed that the scrollbar is actually inside the iframe too.

See the image below:

Title: How does the Codepen fixed menu work?


问:
SSRS Dynamically change the cell background and font color
I need to change the Table Cell Background color to Yellow and Font color to Bold / Red for values which are less than 80.

Cell Expression is  =Fields!Mark.Value

How to change the Cell Background Color / Fill the Color to Yellow ?

答:
select textbox ->right click-> go to property

font->color->give your expression ex : =iif(Fields!status.Value="1","Green","Red")


问:
How to programmatically enable auto start and floating window permissions

How can I enable auto-start permission programmatically?

How to find which phone need to do auto-start code?

How to check if the auto start permission is enable or disable?

I am able to find only about Display popup permission with canDrawOverlay() permission`.

I want to enable auto-start for the device if it is not enabled.

I have found a solution for Xiaomi, honor and let.

```<code>if(Build.BRAND.equalsIgnoreCase("xiaomi") ){

                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                startActivity(intent);

            }else if(Build.BRAND.equalsIgnoreCase("Letv")){

                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
                startActivity(intent);

            }
            else if(Build.BRAND.equalsIgnoreCase("Honor")){

                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
                startActivity(intent);

            }
</code>```

答:
Please check the following solution to enable the floating window and autostart permission for OPPO and VIVO devices.

There's no way to find out whether the Auto-start option is enabled or not. You can manually check under Security permissions => Autostart => Enable Autostart.

On Oppo devices:

```<code>  private void initOPPO() {
    try {

        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.floatwindow.FloatWindowListActivity"));
        startActivity(i);
    } catch (Exception e) {
        e.printStackTrace();
        try {

            Intent intent = new Intent("action.coloros.safecenter.FloatWindowListActivity");
            intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.floatwindow.FloatWindowListActivity"));
            startActivity(intent);
        } catch (Exception ee) {

            ee.printStackTrace();
            try{

                Intent i = new Intent("com.coloros.safecenter");
                i.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.sysfloatwindow.FloatWindowListActivity"));
                startActivity(i);
            }catch (Exception e1){

                e1.printStackTrace();
            }
        }

    }
}
</code>```

Auto Start permission for VIVO

```<code> private static void autoLaunchVivo(Context context) {
    try {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.iqoo.secure",
                "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"));
        context.startActivity(intent);
    } catch (Exception e) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                    "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
            context.startActivity(intent);
        } catch (Exception ex) {
            try {
                Intent intent = new Intent();
                intent.setClassName("com.iqoo.secure",
                        "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager");
                context.startActivity(intent);
            } catch (Exception exx) {
                ex.printStackTrace();
            }
        }
    }
}
</code>```

Auto Start for OPPO

```<code> if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.coloros.safecenter",
                    "com.coloros.safecenter.permission.startup.StartupAppListActivity");
            startActivity(intent);
        } catch (Exception e) {
            try {
                Intent intent = new Intent();
                intent.setClassName("com.oppo.safe",
                        "com.oppo.safe.permission.startup.StartupAppListActivity");
                startActivity(intent);

            } catch (Exception ex) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.coloros.safecenter",
                            "com.coloros.safecenter.startupapp.StartupAppListActivity");
                    startActivity(intent);
                } catch (Exception exx) {

                }
            }
        }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I enable auto-start permission programmatically?

How to find which phone need to do auto-start code?

How to check if the auto start permission is enable or disable?

I am able to find only about Display popup permission with canDrawOverlay() permission`.

I want to enable auto-start for the device if it is not enabled.

I have found a solution for Xiaomi, honor and let.

if(Build.BRAND.equalsIgnoreCase("xiaomi") ){

                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                startActivity(intent);

            }else if(Build.BRAND.equalsIgnoreCase("Letv")){

                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"));
                startActivity(intent);

            }
            else if(Build.BRAND.equalsIgnoreCase("Honor")){

                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
                startActivity(intent);

            }

Body:
Please check the following solution to enable the floating window and autostart permission for OPPO and VIVO devices.

There's no way to find out whether the Auto-start option is enabled or not. You can manually check under Security permissions => Autostart => Enable Autostart.

On Oppo devices:

  private void initOPPO() {
    try {

        Intent i = new Intent(Intent.ACTION_MAIN);
        i.setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.floatwindow.FloatWindowListActivity"));
        startActivity(i);
    } catch (Exception e) {
        e.printStackTrace();
        try {

            Intent intent = new Intent("action.coloros.safecenter.FloatWindowListActivity");
            intent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.floatwindow.FloatWindowListActivity"));
            startActivity(intent);
        } catch (Exception ee) {

            ee.printStackTrace();
            try{

                Intent i = new Intent("com.coloros.safecenter");
                i.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.sysfloatwindow.FloatWindowListActivity"));
                startActivity(i);
            }catch (Exception e1){

                e1.printStackTrace();
            }
        }

    }
}

Auto Start permission for VIVO

 private static void autoLaunchVivo(Context context) {
    try {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.iqoo.secure",
                "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"));
        context.startActivity(intent);
    } catch (Exception e) {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                    "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
            context.startActivity(intent);
        } catch (Exception ex) {
            try {
                Intent intent = new Intent();
                intent.setClassName("com.iqoo.secure",
                        "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager");
                context.startActivity(intent);
            } catch (Exception exx) {
                ex.printStackTrace();
            }
        }
    }
}

Auto Start for OPPO

 if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
        try {
            Intent intent = new Intent();
            intent.setClassName("com.coloros.safecenter",
                    "com.coloros.safecenter.permission.startup.StartupAppListActivity");
            startActivity(intent);
        } catch (Exception e) {
            try {
                Intent intent = new Intent();
                intent.setClassName("com.oppo.safe",
                        "com.oppo.safe.permission.startup.StartupAppListActivity");
                startActivity(intent);

            } catch (Exception ex) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.coloros.safecenter",
                            "com.coloros.safecenter.startupapp.StartupAppListActivity");
                    startActivity(intent);
                } catch (Exception exx) {

                }
            }
        }
}


问:
How do I catch an rpy2.rinterface.RRuntimeError in Python?
Setup:

Python 3.5.3 |Continuum Analytics, Inc.| (default, Mar  6 2017, 12:15:08)

Mac OSX 10.13.1

Problem:

I have downloaded the following R script https://github.com/daleroberts/heston/blob/master/heston.r
and I repeatedly call one of the functions in there via Python using the package RPy2. Now, for some of my inputs that I feed into the R function, R returns the following error:

rpy2.rinterface.RRuntimeError: Error in integrate(PIntegrand, lower =
  0, upper = Inf, lambda, vbar, eta,  :    roundoff error was detected

How do I go about catching this RuntimeError in Python?

答:
The RRuntimeError is derived from Exception so you should be able to catch it as you would with any other exception.

```<code>try:
    # your code
except rpy2.rinterface.RRuntimeError:
    # handle exception
</code>```

In rpy2 v3.0 and above, RRuntimeError seems to have been moved elsewhere (see example code from documentation) so you may need to use this instead:

```<code>try:
    # your code
except rpy2.rinterface_lib.embedded.RRuntimeError:
    # handle exception
</code>```

More on this: https://docs.python.org/3/tutorial/errors.html#handling-exceptions

Body:
The RRuntimeError is derived from Exception so you should be able to catch it as you would with any other exception.

try:
    # your code
except rpy2.rinterface.RRuntimeError:
    # handle exception

In rpy2 v3.0 and above, RRuntimeError seems to have been moved elsewhere (see example code from documentation) so you may need to use this instead:

try:
    # your code
except rpy2.rinterface_lib.embedded.RRuntimeError:
    # handle exception

More on this: https://docs.python.org/3/tutorial/errors.html#handling-exceptions


问:
Select text in TypeScript
how can I select text in input field in TypeScript.

in Javascript this wpuld look like this:

```<code>document.getElementById('id').select();
</code>```

but TypeScript does not support select (error: [ts] Property 'select' does not exist on type 'HTMLElement'.)

Added a few think:
It may be a problem beacouse I use dx controls and they create a wraper. You can see here in html:

```<code><dx-text-box _ngcontent-c1="" id="test" ng-reflect-disabled="false" ng-reflect-value="0:00" class="dx-texteditor dx-widget dx-textbox">
<div class="dx-texteditor-container">
<input autocomplete="off" class="dx-texteditor-input" type="text" spellcheck="false" tabindex="0" role="textbox">
<div data-dx_placeholder="" class="dx-placeholder dx-state-invisible"></div><div class="dx-texteditor-buttons-container">
</div></div></dx-text-box>
</code>```

答:
You can cast the result of document.getElementById() to a more specific type, in this case HTMLInputElement:

```<code>(<HTMLInputElement>document.getElementById('id')).select();
// or (TSX-friendly)
(document.getElementById('id') as HTMLInputElement).select();
</code>```

This is allowed, since HTMLInputElement extends HTMLElement, adding the properties such as select that don't exist on all types of HTML element.

Title: Select text in TypeScript

Body:
how can I select text in input field in TypeScript.

in Javascript this wpuld look like this:

document.getElementById('id').select();

but TypeScript does not support select (error: [ts] Property 'select' does not exist on type 'HTMLElement'.)

Added a few think:
It may be a problem beacouse I use dx controls and they create a wraper. You can see here in html:

<dx-text-box _ngcontent-c1="" id="test" ng-reflect-disabled="false" ng-reflect-value="0:00" class="dx-texteditor dx-widget dx-textbox">

<input autocomplete="off" class="dx-texteditor-input" type="text" spellcheck="false" tabindex="0" role="textbox">

</dx-text-box>

Body:
You can cast the result of document.getElementById() to a more specific type, in this case HTMLInputElement:

(<HTMLInputElement>document.getElementById('id')).select();
// or (TSX-friendly)
(document.getElementById('id') as HTMLInputElement).select();

This is allowed, since HTMLInputElement extends HTMLElement, adding the properties such as select that don't exist on all types of HTML element.


问:
AVAudioPlayer audio breaking and volume increases on its own
I am calling this function playSound() in viewWillAppear, the audio starts playing and then suddenly volume increases with a minor break in playback.

here is my code

```<code>   func playSound() {
    let url = Bundle.main.url(forResource: "music", withExtension: "mp3")!

    do {
        try self.player = AVAudioPlayer(contentsOf: url)
        player?.prepareToPlay()
        player?.numberOfLoops = -1
        player?.play()
    } catch let error as NSError {
        KBLog.log(object: error.description)
    }}
</code>```

Edit 1 :
I am using this code for an iPad app, so ipad only have speaker, no earpiece, if this has something to do with the issue.

答: The problem was i was playing this audio and at the same time i was initialising my publisher view for starting the video call, thus an instance of AVPlayer was initialised to take audio input i.e. two instances of AVPlayer were getting initialised causing the break in playback. </p>

Body:
I am calling this function playSound() in viewWillAppear, the audio starts playing and then suddenly volume increases with a minor break in playback.

here is my code

   func playSound() {
    let url = Bundle.main.url(forResource: "music", withExtension: "mp3")!

    do {
        try self.player = AVAudioPlayer(contentsOf: url)
        player?.prepareToPlay()
        player?.numberOfLoops = -1
        player?.play()
    } catch let error as NSError {
        KBLog.log(object: error.description)
    }}

Edit 1 :
I am using this code for an iPad app, so ipad only have speaker, no earpiece, if this has something to do with the issue.


问:
How to convert a mathematical expression into a tree/ .xml in R
I have a list of mathematical expressions like the one below. My goal is to compare these expressions and cluster them based on the structure.

(((53.0 / -98.0) * -2.0) + (-25.0 + 80.0))

I'm planning to use the graphkernels package in R. graphkernels can compare two graphs and it generates a similarity matrix. But it uses the graph in xml format.

Are there any existing R packages which I can use to convert the expression into an .xml tree or normal tree which later I can convert to xml. I found the data.tree package in R but it doesn't seem to work for this case.  Any suggestion in terms of packages or a different approach please?

答:
Phylogenic trees in R

Maybe this would be somehow useful? Also Mathematica has got the function that you are looking for:
Mathematica Tree Form


问:
Display number always with 2 decimal places in <input>
I have a float value for the ng-model that I would like to always display with 2 decimal places in the <input>:

```<code><input ng-model="myNumb" step ="0.01" type="number">
</code>```

This works for most case when "myNumb" has decimal. But it will not force display of the 2  decimal places if "myNumb" has less than 2 decimal places (3.2), or an integer(30)

How can I force a display of 2 decimal place in the <input> field

答:
Another shorthand to (@maudulus's answer) to remove {maxFractionDigits} since it's optional.

You can use {{numberExample | number : '1.2'}}

Body:
I have a float value for the ng-model that I would like to always display with 2 decimal places in the <input>:

<input ng-model="myNumb" step ="0.01" type="number">

This works for most case when "myNumb" has decimal. But it will not force display of the 2  decimal places if "myNumb" has less than 2 decimal places (3.2), or an integer(30)

How can I force a display of 2 decimal place in the <input> field


答:
document.getElementById(string) returns an HTMLElement which does not define a select() method. HTMLInputElement DOES define a select() method and also extends HTMLElement, so if you cast as HTMLInputElement, it should work:

```<code> (document.getElementById('id') as HTMLInputElement).select();
</code>```

Title: Select text in TypeScript

Body:
document.getElementById(string) returns an HTMLElement which does not define a select() method. HTMLInputElement DOES define a select() method and also extends HTMLElement, so if you cast as HTMLInputElement, it should work:

 (document.getElementById('id') as HTMLInputElement).select();


问:
Reading character by character from stdin until EOF in C
I'm trying to read a string in C until EOF, but react to every character before the input of the next character.
For example:
A user inputs abcd, and right after every character input, I will do some calculations on each character.
I have tried to approach this in two different ways:

Option 1, using getchar():

```<code>int d;
char c;

while ((d = getchar()) != EOF) {
    c = (char)d;
    <<< DO SOME CALCULATIONS ON 'c'>>>
    }
</code>```

Option 2, using scanf:

```<code>char c;
while (scanf(" %c",&c) != EOF) {
    <<< DO SOME CALCULATIONS ON 'c'>>>
}
</code>```

However, both approaches seem to fail. It seems that the getchar() and scanf() gets all the characters until it encounters the 'EOF', and only then enters the while loop.

Would love some help on this,
Thanks!

答:
scanf manual says :

"The  value  EOF is returned if the end of input is reached before either the first successful conversion or a
       matching failure occurs.  EOF is also returned if a read error occurs, in which case the error indicator  for
       the stream (see ferror(3)) is set, and errno is set indicate the error."

.. better use a do..while approch with scanf in this case (and if you want store return of scanf to check for errors) :

```<code>char c;

do{
  scanf("%c",&c);
  /* DO SOME CALCULATIONS ON 'c' */
}while(c != EOF);
</code>```

same with getchar() in raw mode will react to each user keystroke

see this for using raw mode : https://stackoverflow.com/a/22517349/8907248

Body:
I'm trying to read a string in C until EOF, but react to every character before the input of the next character.
For example:
A user inputs abcd, and right after every character input, I will do some calculations on each character.
I have tried to approach this in two different ways:

Option 1, using getchar():

int d;
char c;

while ((d = getchar()) != EOF) {
    c = (char)d;
    <<< DO SOME CALCULATIONS ON 'c'>>>
    }

Option 2, using scanf:

char c;
while (scanf(" %c",&c) != EOF) {
    <<< DO SOME CALCULATIONS ON 'c'>>>
}

However, both approaches seem to fail. It seems that the getchar() and scanf() gets all the characters until it encounters the 'EOF', and only then enters the while loop.

Would love some help on this,
Thanks!

Body:
scanf manual says :

"The  value  EOF is returned if the end of input is reached before either the first successful conversion or a
       matching failure occurs.  EOF is also returned if a read error occurs, in which case the error indicator  for
       the stream (see ferror(3)) is set, and errno is set indicate the error."

.. better use a do..while approch with scanf in this case (and if you want store return of scanf to check for errors) :

char c;

do{
  scanf("%c",&c);
  /* DO SOME CALCULATIONS ON 'c' */
}while(c != EOF);

same with getchar() in raw mode will react to each user keystroke

see this for using raw mode : https://stackoverflow.com/a/22517349/8907248


问:
PHP Image Uploaded Name won't change
I have PHP function to upload file (image).

```<code>foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];

    move_uploaded_file($file_tmp,"assets/img/wallpapers/".time().$file_name);
}
</code>```

It's working and I can see the data image uploaded on my folder.

But now how can I set the image file name only time() without .$file_name

If I remove .$file_name, file uploaded is not correct without extension and only 1 file, even though I uploaded 3 files.

Example:

Image file name: 1510750186shubuh.jpg

What I want only

1510750186.jpg

答:
You can use pathinfo() for this, with PATHINFO_EXTENSION flag, Like:

```<code>foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    move_uploaded_file($file_tmp,"assets/img/wallpapers/".time().'.'.$ext);
}
</code>```

This will only add the extension and no the full file name.

Edit:

To upload multiple files at the same time try to use 1 of these:

```<code>$newFileName = time()."{$key}.{$ext}";
move_uploaded_file($file_tmp,"assets/img/wallpapers/".$newFileName);
</code>```

Or

```<code>$newFileName = str_replace('.','',microtime(true)).".{$ext}";
move_uploaded_file($file_tmp,"assets/img/wallpapers/".$newFileName);
</code>```

Title: PHP Image Uploaded Name won't change

Body:
I have PHP function to upload file (image).

foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];

    move_uploaded_file($file_tmp,"assets/img/wallpapers/".time().$file_name);
}

It's working and I can see the data image uploaded on my folder.

But now how can I set the image file name only time() without .$file_name

If I remove .$file_name, file uploaded is not correct without extension and only 1 file, even though I uploaded 3 files.

Example:

Image file name: 1510750186shubuh.jpg

What I want only

1510750186.jpg

Body:
You can use pathinfo() for this, with PATHINFO_EXTENSION flag, Like:

foreach($_FILES['wallpaperFile']['tmp_name'] as $key => $tmpName)
{
    $file_name = $_FILES['wallpaperFile']['name'][$key];
    $file_type = $_FILES['wallpaperFile']['type'][$key];
    $file_size = $_FILES['wallpaperFile']['size'][$key];
    $file_tmp  = $_FILES['wallpaperFile']['tmp_name'][$key];
    $ext = pathinfo($file_name, PATHINFO_EXTENSION);

    move_uploaded_file($file_tmp,"assets/img/wallpapers/".time().'.'.$ext);
}

This will only add the extension and no the full file name.

Edit:

To upload multiple files at the same time try to use 1 of these:

$newFileName = time()."{$key}.{$ext}";
move_uploaded_file($file_tmp,"assets/img/wallpapers/".$newFileName);

Or

$newFileName = str_replace('.','',microtime(true)).".{$ext}";
move_uploaded_file($file_tmp,"assets/img/wallpapers/".$newFileName);


问:
environment variables in heroku
```<code>const firebase = require('firebase');
const devConfig = {
 //config here
};
const prodConfig = {
//config here
};

export const firebaseInit = firebase.initializeApp(process.env.NODE_ENV == 'development' ? devConfig : prodConfig);
export const rootRef = firebase.database().ref();
</code>```

i have this firebase config file.

in my procfile i have: web: NODE_ENV=production node ./src/server/index.js

in my webpack i have:

```<code>plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify(process.env.NODE_ENV) || '"development"'
        }
    }),
</code>```

and in my package.json i have:

```<code>"start": "node src/server/index.js",
"start:production": "NODE_ENV=production ./node_modules/.bin/webpack && node src/server/index.js",
"start:dev": "NODE_ENV=development ./node_modules/.bin/webpack && node src/server/index.js",
</code>```

and in my heroku app settings i have gone and set NODE_ENV as the key with production as the value

i have deployed the master code after pushing my code up. yet when the app starts up it still logs up in my console as 'development mode'. what am i missing to start the app in production? i can do it locally just not on heroku

答:
Not sure if any of this fixes your issue, but hopefully it helps.

1) Could Heroku be picking up the "start" script before the Procfile which doesn't have "NODE_ENV=production" in it? I don't use a Procfile, I just rely on the start script, so not sure.

2) Does NODE_ENV=production definitely carry through after an && in start:production script call? It might be worth copying and pasting it to before the node script too, just to be sure.

3) JSON.stringify will resolve an empty string as true so best to put || "development" inside the JSON.stringify function, like this:

```<code>'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
</code>```

4) You have single and double quotes around '"development"' which would create the string with the double quotes which would be a different string to just the word development.

Title: environment variables in heroku

Body:
const firebase = require('firebase');
const devConfig = {
 //config here
};
const prodConfig = {
//config here
};

export const firebaseInit = firebase.initializeApp(process.env.NODE_ENV == 'development' ? devConfig : prodConfig);
export const rootRef = firebase.database().ref();

i have this firebase config file.

in my procfile i have: web: NODE_ENV=production node ./src/server/index.js

in my webpack i have:

plugins: [
    new webpack.DefinePlugin({
        'process.env': {
            'NODE_ENV': JSON.stringify(process.env.NODE_ENV) || '"development"'
        }
    }),

and in my package.json i have:

"start": "node src/server/index.js",
"start:production": "NODE_ENV=production ./node_modules/.bin/webpack && node src/server/index.js",
"start:dev": "NODE_ENV=development ./node_modules/.bin/webpack && node src/server/index.js",

and in my heroku app settings i have gone and set NODE_ENV as the key with production as the value

i have deployed the master code after pushing my code up. yet when the app starts up it still logs up in my console as 'development mode'. what am i missing to start the app in production? i can do it locally just not on heroku

Body:
Not sure if any of this fixes your issue, but hopefully it helps.

1) Could Heroku be picking up the "start" script before the Procfile which doesn't have "NODE_ENV=production" in it? I don't use a Procfile, I just rely on the start script, so not sure.

2) Does NODE_ENV=production definitely carry through after an && in start:production script call? It might be worth copying and pasting it to before the node script too, just to be sure.

3) JSON.stringify will resolve an empty string as true so best to put || "development" inside the JSON.stringify function, like this:

'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')

4) You have single and double quotes around '"development"' which would create the string with the double quotes which would be a different string to just the word development.


问:
Problems with asynchronous methods
I'm working with Flex 4 invoking webservices from JVM 1.6

I'm trying to make asynchronous calls to java to populate three comboboxes that will display country, states and cities, these three are related (master-slave relationship) but sometimes the calls are not met, or they are not completed, and I think this is because they are asynchronous, how can I be sure that I'm making the call to fill the next combobox when the master combobox (country) is filled?

protected function comboCountry_changeHandler(idCombo:String):void
            {

```<code>            selectedComboCountry= idCombo;
            var countryId:String;
            if(selectedComboCountry == comboCountry.id){
                countryId = String(comboCountry.selectedItem.countryId);
            }else if(selectedCombocountry == combocountrySuc.id){
                countryId = String(comboCountrySuc.selectedItem.countryId);
            }

            obtainStatesResult.token = wsfacturas.obtainStates(countryId);

        }
</code>```

protected function obtainStatesResult_resultHandler(event:ResultEvent):void
            {
                var StateListVo:ArrayCollection = obtainStatesResult.token.result as ArrayCollection;

```<code>            if(selectedComboCountry == "comboCountrySuc"){

                StateListsSuc.removeAll();
                CityListsSuc.removeAll();
                for (var d:int = 0; d < StateListVo.length; d++){
                    var estSuc:State = StateListVo[d];
                    StateListsSuc.addItem(estSuc);
                }

                comboStateSuc.dataProvider = StateListsSuc;
            }
            else if(selectedCombocountry == "combocountry"){
                StateListsEmp.removeAll();
                CityListsEmp.removeAll();
                for (var i:int = 0; i < StateListVo.length; i++){
                    var estEmp:State = StateListVo[i];
                    StateListsEmp.addItem(estEmp);
                }
                comboState.dataProvider = StateListsEmp;
            } else {

                for (var f:int = 0; f < StateListVo.length; f++){
                    var est:State = StateListVo[f];
                    StateListsSuc.addItem(est);
                    StateListsEmp.addItem(est);
                }
                comboState.dataProvider = StateListsEmp;
                comboStateSuc.dataProvider = StateListsSuc;

            }
        }
</code>```

答:
Wouldn't it mean that you probably need to load the country and wait for change event on the country combobox to update state and so on? If you do that, you dont have to worry about asynchronicity of your requests? Otherwise, you might be able to use DataProviders and they might provide Event:Complete..
I am not sure though, I definitely am not an expert.. :)</p>

ContentLicense: CC BY-SA 2.5

Title: Problems with asynchronous methods

Body:
I'm working with Flex 4 invoking webservices from JVM 1.6

I'm trying to make asynchronous calls to java to populate three comboboxes that will display country, states and cities, these three are related (master-slave relationship) but sometimes the calls are not met, or they are not completed, and I think this is because they are asynchronous, how can I be sure that I'm making the call to fill the next combobox when the master combobox (country) is filled?

protected function comboCountry_changeHandler(idCombo:String):void
            {

            selectedComboCountry= idCombo;
            var countryId:String;
            if(selectedComboCountry == comboCountry.id){
                countryId = String(comboCountry.selectedItem.countryId);
            }else if(selectedCombocountry == combocountrySuc.id){
                countryId = String(comboCountrySuc.selectedItem.countryId);
            }

            obtainStatesResult.token = wsfacturas.obtainStates(countryId);

        }

protected function obtainStatesResult_resultHandler(event:ResultEvent):void
            {
                var StateListVo:ArrayCollection = obtainStatesResult.token.result as ArrayCollection;

            if(selectedComboCountry == "comboCountrySuc"){

                StateListsSuc.removeAll();
                CityListsSuc.removeAll();
                for (var d:int = 0; d < StateListVo.length; d++){
                    var estSuc:State = StateListVo[d];
                    StateListsSuc.addItem(estSuc);
                }

                comboStateSuc.dataProvider = StateListsSuc;
            }
            else if(selectedCombocountry == "combocountry"){
                StateListsEmp.removeAll();
                CityListsEmp.removeAll();
                for (var i:int = 0; i < StateListVo.length; i++){
                    var estEmp:State = StateListVo[i];
                    StateListsEmp.addItem(estEmp);
                }
                comboState.dataProvider = StateListsEmp;
            } else {

                for (var f:int = 0; f < StateListVo.length; f++){
                    var est:State = StateListVo[f];
                    StateListsSuc.addItem(est);
                    StateListsEmp.addItem(est);
                }
                comboState.dataProvider = StateListsEmp;
                comboStateSuc.dataProvider = StateListsSuc;

            }
        }


问:
node.js: Error: Cannot find module
Why do I get this error?

Node v8.9.1

code

```<code>var childProcess = require('child_process'),
    phantomjs = require('/var/bin/node_modules/phantomjs-prebuilt');

console.error = function(){
    require('system').stderr.write(Array.prototype.join.call(arguments, ' ')+'\n');
    phantomjs.exit(1);
};

console.log('hey', phantomjs.path)
console.error('error')

childProcess.execFile(phantomjs.path, require('system').args, function(err, stdout, stderr){
    if(err){
        console.error(err);
    }

    if(stderr){
        console.error(stderr);
    }

    console.log(stdout);
});
</code>```

error

```<code># /var/bin/node_modules/phantomjs-prebuilt/bin/phantomjs phantom.js
Error: Cannot find module 'path'

  phantomjs://platform/bootstrap.js:299 in require
  phantomjs://platform/bootstrap.js:263 in require
  phantomjs://platform/phantomjs.js:10
hey undefined
TypeError: undefined is not a function (evaluating 'phantomjs.exit(1)')

  phantomjs://code/phantom.js:6 in error
error
</code>```

答:
system is not a Node built-in module, it's part of PhantomJS. It won't be available if you're just running your script with the standard node command. As shown in the documentation, you need to use the phantomjs command, like so:

```<code>phantomjs phantom.js
</code>```

Title: node.js: Error: Cannot find module

Body:
Why do I get this error?

Node v8.9.1

code

var childProcess = require('child_process'),
    phantomjs = require('/var/bin/node_modules/phantomjs-prebuilt');

console.error = function(){
    require('system').stderr.write(Array.prototype.join.call(arguments, ' ')+'\n');
    phantomjs.exit(1);
};

console.log('hey', phantomjs.path)
console.error('error')

childProcess.execFile(phantomjs.path, require('system').args, function(err, stdout, stderr){
    if(err){
        console.error(err);
    }

    if(stderr){
        console.error(stderr);
    }

    console.log(stdout);
});

error

# /var/bin/node_modules/phantomjs-prebuilt/bin/phantomjs phantom.js
Error: Cannot find module 'path'

  phantomjs://platform/bootstrap.js:299 in require
  phantomjs://platform/bootstrap.js:263 in require
  phantomjs://platform/phantomjs.js:10
hey undefined
TypeError: undefined is not a function (evaluating 'phantomjs.exit(1)')

  phantomjs://code/phantom.js:6 in error
error

Body:
system is not a Node built-in module, it's part of PhantomJS. It won't be available if you're just running your script with the standard node command. As shown in the documentation, you need to use the phantomjs command, like so:

phantomjs phantom.js


问:
Implications of using MPI with TensorFlow
I come from a sort of HPC background and I am just starting to learn about machine learning in general and TensorFlow in particular.  I was initially surprised to find out that distributed TensorFlow is designed to communicate with TCP/IP by default though it makes sense in hindsight given what Google is and the kind of hardware it uses most commonly.

I am interested in experimenting with TensorFlow in a parallel way with MPI on a cluster.  From my perspective, this should be advantageous because latency should be much lower due to MPI's use of Remote Direct Memory Access (RDMA) across machines without shared memory.

So my question is, why doesn't this approach seem to be more common given the increasing popularity of TensorFlow and machine learning ?  Isn't latency a bottleneck ?  Is there some typical problem that is solved, that makes this sort of solution impractical?  Are there likely to be any meaningful differences between calling TensorFlow functions in a parallel way vs implementing MPI calls inside of the TensorFlow library ?

Thanks

答: According to the doc in Tensorflow git repo，actually tf utilizes gRPC library by detault, which is based on HTTP2 protocol, rather than TCP/IP protocol, and this paper should give you some insight, hope this information is useful.</p>


问:
jquery radio button change event not working
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

```<code><div class="col-sm-6" id="addresses">
  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address<br>
  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address<br>
</div>
</code>```

js code:

```<code>$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});
</code>```

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

答:
try with this code

```<code>$("input[name='deco_request[address]']").change(function() {
  $("#new-address").toggle();
});
</code>```

$("input[name='deco_request[address]']").change(function() {
  $("#new-address").toggle();
});```
<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>
<div class="col-sm-6" id="addresses">
  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address<br>
  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address<br>
</div>

<div id="new-address">Address</div></code>```

Body:
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address

  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address

js code:

$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

Body:
try with this code

$("input[name='deco_request[address]']").change(function() {
  $("#new-address").toggle();
});

$("input[name='deco_request[address]']").change(function() {
  $("#new-address").toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-6" id="addresses">
  <input type="radio" name="deco_request[address]" value="value[&quot;id&quot;]"> Some address<br>
  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address<br>
</div>

<div id="new-address">Address</div>


问:
Angular2 formating text input into dd-MM-yyyy
I have a form in my angular project that I send via json to my JAVA rest API, I need the date string to be in the dd-MM-yyyy format. How can I do this? I know you can use the date pipe to format it as output, but I need to format the value of the formControl string so I can send it as json. Any ideas?

Tried setting it as type="date" but it doesn't change anything

```<code><ion-input formControlName="pacientedataexame" placeholder="Data do Exame:" type="date"></ion-input>
</code>```

答:
Have you tried this? Check This Reference </p>

```<code><ion-item>
  <ion-label>Date</ion-label>
  <ion-datetime displayFormat="MM/DD/YYYY" formControlName="pacientedataexame"></ion-datetime>
</ion-item>
</code>```

<hr>

```<code><ion-item>
  <ion-label>Time</ion-label>
  <ion-datetime displayFormat="h:mm A" pickerFormat="h mm A" formControlName="pacientedataexame"></ion-datetime>
</ion-item>
</code>```

Body:
I have a form in my angular project that I send via json to my JAVA rest API, I need the date string to be in the dd-MM-yyyy format. How can I do this? I know you can use the date pipe to format it as output, but I need to format the value of the formControl string so I can send it as json. Any ideas?

Tried setting it as type="date" but it doesn't change anything

<ion-input formControlName="pacientedataexame" placeholder="Data do Exame:" type="date"></ion-input>

Body:
Have you tried this? Check This Reference

<ion-item>
  <ion-label>Date</ion-label>
  <ion-datetime displayFormat="MM/DD/YYYY" formControlName="pacientedataexame"></ion-datetime>
</ion-item>

<ion-item>
  <ion-label>Time</ion-label>
  <ion-datetime displayFormat="h:mm A" pickerFormat="h mm A" formControlName="pacientedataexame"></ion-datetime>
</ion-item>


问:
Android how to reuse Socket?
how to reuse TCP Socket connection(possible setReuseAddress(true), but not work for me) for download multiple files from Server(Apache, HTTPD) in on connection without disconnect(and connect again).

My code below..

```<code>public class ClientThread implements Runnable {
        public void run() {
            try {

                Log.d("ClientActivity", "C: Connecting...");
                SocketAddress sockaddr = new InetSocketAddress(serverIpAddress, SERVERPORT);
                socket = new Socket();

                socket.setReuseAddress(true);
                socket.setKeepAlive(true);
                socket.setSoLinger(true, 3000);
                socket.connect(sockaddr);

                if (socket.isConnected()) {
                    DataInputStream input = new DataInputStream(socket.getInputStream());
                    PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

                    output.println("GET /way/images/profile/1231 HTTP/1.1");
                    output.println("Host: 192.168.1.2");
                    output.println("User-Agent: Java");
                    output.println("Accept: */*");
                    output.println("Connection: Keep-Alive");
                    output.println("");
                    output.flush();

                    String line;
                    File file = new File("/sdcard/aaa.png");
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream fileOut = new FileOutputStream(file);
                    System.out.println("Getting first file");
                    while ( (line = input.readLine()) != null ) {
                        System.out.println(line);
                        fileOut.write(line.getBytes());
                    }
                    System.out.println("First file finished");
                    fileOut.flush();
                    fileOut.close();

                    output.println("GET /way/images/profile/1231 HTTP/1.1");
                    output.println("Host: 192.168.1.2");
                    output.println("User-Agent: Java");
                    output.println("Accept: */*");
                    output.println("Connection: Keep-Alive");
                    output.println("");
                    output.flush();

                    file = new File("/sdcard/aaa1.png");
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileOut = new FileOutputStream(file);
                    System.out.println("Getting second file");
                    while ( (line = input.readLine()) != null ) {
                        System.out.println(line);
                        fileOut.write(line.getBytes());
                    }
                    System.out.println("Second file finished");

                    fileOut.flush();
                    fileOut.close();
                    input.close();
                    output.close();

                }
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }

            finally {
                try {
                    Log.d("ClientActivity", "Socket: Closed.");
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
</code>```

Thanks...

答:
setReuseAddress(true) prior to binding the socket allows the socket to be bound even though a previous connection is in a timeout state.

documentation of setReuseAddress

I don't see sense in directly using socket for HTTP communication. I use HttpURLConnection. Works without problems in most cases.

Title: Android how to reuse Socket?

Body:
how to reuse TCP Socket connection(possible setReuseAddress(true), but not work for me) for download multiple files from Server(Apache, HTTPD) in on connection without disconnect(and connect again).

My code below..

public class ClientThread implements Runnable {
        public void run() {
            try {

                Log.d("ClientActivity", "C: Connecting...");
                SocketAddress sockaddr = new InetSocketAddress(serverIpAddress, SERVERPORT);
                socket = new Socket();

                socket.setReuseAddress(true);
                socket.setKeepAlive(true);
                socket.setSoLinger(true, 3000);
                socket.connect(sockaddr);

                if (socket.isConnected()) {
                    DataInputStream input = new DataInputStream(socket.getInputStream());
                    PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

                    output.println("GET /way/images/profile/1231 HTTP/1.1");
                    output.println("Host: 192.168.1.2");
                    output.println("User-Agent: Java");
                    output.println("Accept: */*");
                    output.println("Connection: Keep-Alive");
                    output.println("");
                    output.flush();

                    String line;
                    File file = new File("/sdcard/aaa.png");
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream fileOut = new FileOutputStream(file);
                    System.out.println("Getting first file");
                    while ( (line = input.readLine()) != null ) {
                        System.out.println(line);
                        fileOut.write(line.getBytes());
                    }
                    System.out.println("First file finished");
                    fileOut.flush();
                    fileOut.close();

                    output.println("GET /way/images/profile/1231 HTTP/1.1");
                    output.println("Host: 192.168.1.2");
                    output.println("User-Agent: Java");
                    output.println("Accept: */*");
                    output.println("Connection: Keep-Alive");
                    output.println("");
                    output.flush();

                    file = new File("/sdcard/aaa1.png");
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    fileOut = new FileOutputStream(file);
                    System.out.println("Getting second file");
                    while ( (line = input.readLine()) != null ) {
                        System.out.println(line);
                        fileOut.write(line.getBytes());
                    }
                    System.out.println("Second file finished");

                    fileOut.flush();
                    fileOut.close();
                    input.close();
                    output.close();

                }
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }

            finally {
                try {
                    Log.d("ClientActivity", "Socket: Closed.");
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Thanks...


问:
Unit-testing Delphi data modules
If all the business logic is present in a datamodule (TSQLDataSets and TDataSetProviders)  how would you refactor the code to make the application more appropiate for unit testing?</p>

答: After the last question about this, I wrote a blog post about how to do it.</p>

OwnerDisplayName: Tihy

Title: Unit-testing Delphi data modules

OwnerDisplayName: Craig Stuntz


问:
Tensorflow AVX Support
Does anyone know if the Tensorflow compiled executables here include AVX support? I have been running that compiled version of Tensorflow on Google Compute Engine and it is slow. Dog slow. Cold molasses slow. LA traffic slow. This article says compiling with AVX support significantly improves performance on Google Compute Engine, but when I follow the compile process on that site it fails. Just wondering if AVX is already in the executables?</p>

答:
This is the simplest method. Only one step.

It's easy and has significant impact on speed. Can make training 3 times faster.

Refer
custom builds of tensorflow

Title: Tensorflow AVX Support


问:
Why is not using semicolon is encouraged in standard configuration of eslint?
My project extends 'standard' rules for javascript in .eslintrc.js file, and according to that Javascript code shouldn't have semicolon at the end of lines. I have never seen something like that. Is it useful to leave it like that? Or am I misunderstanding the whole thing?

"semi" rule from standard eslint rules:

```<code>"semi": ["error", "never"]
</code>```

Usage from eslint documentation:

```<code>/*eslint semi: ["error", "never"]*/

var name = "ESLint"

object.method = function() {
    // ...
}

var name = "ESLint"

;(function() {
    // ...
})()
</code>```

答:
As said in the standardjs docs, the point is not to tell it's better or not to use semicolons but simply to settle once and for all a rule

I disagree with rule X, can you change it?

No. The whole point of standard is to save you time by avoiding
  bikeshedding about code style. There are lots of debates online about
  tabs vs. spaces, etc. that will never be resolved. These debates just
  distract from getting stuff done. At the end of the day you have to
  'just pick something', and that's the whole philosophy of standard --
  its a bunch of sensible 'just pick something' opinions. Hopefully,
  users see the value in that over defending their own opinions.

If you really want to configure hundreds of ESLint rules individually,
  you can always use eslint directly with eslint-config-standard to
  layer your changes on top. standard-eject can help you migrate from
  standard to eslint and eslint-config-standard.

Pro tip: Just use standard and move on. There are actual real problems
  that you could spend your time solving! :P

Discussing about it is opinionated and will induce an endless debate which is not what we want.

Body:
My project extends 'standard' rules for javascript in .eslintrc.js file, and according to that Javascript code shouldn't have semicolon at the end of lines. I have never seen something like that. Is it useful to leave it like that? Or am I misunderstanding the whole thing?

"semi" rule from standard eslint rules:

"semi": ["error", "never"]

Usage from eslint documentation:

/*eslint semi: ["error", "never"]*/

var name = "ESLint"

object.method = function() {
    // ...
}

var name = "ESLint"

;(function() {
    // ...
})()


问:
Issue to resize element content properly
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.6/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
</head>
<body>
<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section>

<section class="container">
            <div class="card">
                <div class="front" style="background-image: url('image.jpg');">
                    <h5>Image 1 With more text</h5>
                </div>
                <div class="back">Abc</div>
            </div>
</section></code>```

答: Your css set heigth of the element to 44px and font-size to 1.25rem, change one of the properties or both, for example heigth to auto if you want to keep font-size, or change font-size to 100% if you want to keep the heigth of the element. There are several ways to do this.</p>

Body:
The text of second h5 element doesnt resize properly and get out over the background color, I also tested put the h5 inside a div and apply css to the div but it didnt work, what am I missing?

Here is the relevant code (I had to remove other elements and css properties):

.container {
    position: relative;
    display: inline-block;
    margin-top: 50px;
}
.card .front {
    color: white;
    text-align: center;
    font-weight: bold;
    position: absolute;
}
.card .front h5 {
    background-color: #5E92F2;
    padding: 10px 0 10px 0;
    margin-top: 98%;
    width: 198px;
    height: 44px;
}

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">

Image 1

Abc

Image 1 With more text

Abc


问:
Django queryset for multilevel Foreignkey reference
Following are my models:

```<code>class A(models.Model):
    owner = models.ForeignKey(User, null=False)
    a_name= models.CharField(max_length=200, null=False, unique=True)

class B(models.Model):
    owner = models.ForeignKey(User)
    b_name= models.CharField(max_length=100, null=False)

class C(models.Model):
    a= models.OneToOneField(
        A,
        on_delete=models.CASCADE,
        null=False,
        unique=True,
    )
    b= models.OneToOneField(
        B,
        on_delete=models.CASCADE,
        null=False,
        unique=True,
    )

class D(models.Model):
       c= models.OneToOneField(C,
        on_delete=models.CASCADE,
        null=False,
        unique=True,
    )
    d1 = models.IntegerField(null=False, default=1)
</code>```

I am trying to override the queryset in ListView generic class to get the list of all the objects in model 'D' where the 'owner' in model 'A' in current logged in user. I am unable to write the filter for the query.

```<code>D.objects.filter(self.c__a__owner==self.request.user)
</code>```

But I am getting error as:

```<code>'MyListView' object has no attribute 'c__a__owner'
</code>```

Please guide me how to achieve this.

Thanks.

答:
Your query shouldn't have self. Also, you use a keyword assignment instead of a comparison in the filter method. It should like:

```<code>D.objects.filter(c__a__owner=self.request.user)
</code>```

Body:
Following are my models:

class A(models.Model):
    owner = models.ForeignKey(User, null=False)
    a_name= models.CharField(max_length=200, null=False, unique=True)

class B(models.Model):
    owner = models.ForeignKey(User)
    b_name= models.CharField(max_length=100, null=False)

class C(models.Model):
    a= models.OneToOneField(
        A,
        on_delete=models.CASCADE,
        null=False,
        unique=True,
    )
    b= models.OneToOneField(
        B,
        on_delete=models.CASCADE,
        null=False,
        unique=True,
    )

class D(models.Model):
       c= models.OneToOneField(C,
        on_delete=models.CASCADE,
        null=False,
        unique=True,
    )
    d1 = models.IntegerField(null=False, default=1)

I am trying to override the queryset in ListView generic class to get the list of all the objects in model 'D' where the 'owner' in model 'A' in current logged in user. I am unable to write the filter for the query.

D.objects.filter(self.c__a__owner==self.request.user)

But I am getting error as:

'MyListView' object has no attribute 'c__a__owner'

Please guide me how to achieve this.

Thanks.

Body:
Your query shouldn't have self. Also, you use a keyword assignment instead of a comparison in the filter method. It should like:

D.objects.filter(c__a__owner=self.request.user)


问:
changing img src of another div with jquery?
I have a trouble changing the src of my image with jquery :

I have my div projectName with all the buttons which will be clicked on for changing the images.
Those images will be contained in another div called projectImg.

But when I click on my buttons, nothing is happening. Someone know if there is a way to make my jquery work??

EDIT : Found the error ! I only needed to put a type="button" into my html buttons. Thanks for the help though  !

$(document).ready(function(){
 $('.sliding').click(function(){
     var url_img = $(this).attr('id');
     $('#projImg img').attr('src',url_img)
   });
});```
<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>
<section id="galerie" class="galerie-section content-section">
      <div class="container">
        <div class="row">

          <div class="container-fluid projectName text-center col-sm-6" id="projName">
              <button id="img/img1.jpg" class="sliding" type="button">img1</button>
              <button id="img/img2.jpg" class="sliding" type="button">img2</button>
              <button id="img/img3.jpg" class="sliding" type="button">img3</button>
          </div>

          <div class="container-fluid projectImg col-sm-6" id="projImg">
            <img src="img/img1.jpg" class="img-fluid img-galerie">
          </div>
        </div>
      </div>
    </section></code>```

答:
Multiple errors.

1) Ready function won't accept your direct function should be wrapped by function(){}

2) Your div directly do not have an src attribute. You have to find the image inside that and set.

3) Your id to the target div is wrong. Corrected.

$(document).ready(function(){
 $('.sliding').click(function(){
  debugger;
     var url_img = $(this).attr('id');
     $('#projImg').find("img").attr('src',url_img)
   });
});```
<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>
<section id="galerie" class="galerie-section content-section">
      <div class="container">
        <div class="row">

          <div class="container-fluid projectName text-center col-sm-6" id="projName">
              <button id="img1" class="sliding">img1</button>
              <button id="img2" class="sliding">img2</button>
              <button id="img3" class="sliding">img3</button>
          </div>

          <div class="container-fluid projectImg col-sm-6" id="projImg">  test
            <img src="img/img1.jpg" class="img-fluid img-galerie">
          </div>

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

Body:
I have a trouble changing the src of my image with jquery :

I have my div projectName with all the buttons which will be clicked on for changing the images.
Those images will be contained in another div called projectImg.

But when I click on my buttons, nothing is happening. Someone know if there is a way to make my jquery work??

EDIT : Found the error ! I only needed to put a type="button" into my html buttons. Thanks for the help though  !

$(document).ready(function(){
 $('.sliding').click(function(){
     var url_img = $(this).attr('id');
     $('#projImg img').attr('src',url_img)
   });
});

              <button id="img/img1.jpg" class="sliding" type="button">img1</button>
              <button id="img/img2.jpg" class="sliding" type="button">img2</button>
              <button id="img/img3.jpg" class="sliding" type="button">img3</button>

Body:
Multiple errors.

1) Ready function won't accept your direct function should be wrapped by function(){}

2) Your div directly do not have an src attribute. You have to find the image inside that and set.

3) Your id to the target div is wrong. Corrected.

$(document).ready(function(){
 $('.sliding').click(function(){
  debugger;
     var url_img = $(this).attr('id');
     $('#projImg').find("img").attr('src',url_img)
   });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="galerie" class="galerie-section content-section">
      <div class="container">
        <div class="row">

          <div class="container-fluid projectName text-center col-sm-6" id="projName">
              <button id="img1" class="sliding">img1</button>
              <button id="img2" class="sliding">img2</button>
              <button id="img3" class="sliding">img3</button>
          </div>

          <div class="container-fluid projectImg col-sm-6" id="projImg">  test
            <img src="img/img1.jpg" class="img-fluid img-galerie">
          </div>

        </div>
      </div>
    </section>


问:
How to return multiple values from a function in Kotlin like we do in Swift?
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

```<code>func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}
</code>```

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

答:
According to the Kotlin documentation (https://kotlinlang.org/docs/reference/multi-declarations.html#example-returning-two-values-from-a-function) you can achieve it like that:</p>

```<code>data class TimeData(val hour: Int, val minute: Int, val second: Int)

fun getTime(): TimeData {
    // do your calculations

    return TimeData(hour, minute, second)
}

// Get the time.
val (hour, minute, second) = getTime()
</code>```

Body:
How to return 3 separate data values of the same type (Int) from a function in Kotlin?

I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?

In swift we do it like following,

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

can we achieve this in Kotlin?

P.S: I know I can use Array or Hashmap for this but I want to know if there exists something in Kotlin like it is in Swift.

Body:
According to the Kotlin documentation (https://kotlinlang.org/docs/reference/multi-declarations.html#example-returning-two-values-from-a-function) you can achieve it like that:

data class TimeData(val hour: Int, val minute: Int, val second: Int)

fun getTime(): TimeData {
    // do your calculations

    return TimeData(hour, minute, second)
}

// Get the time.
val (hour, minute, second) = getTime()


问:
import c++ dll to windows phone project
I'm new on windows phone developement and i have one problem that i don't know how to resolve....

the problem is....

i have a c++ project that i had complided with visual c++ 2010 and this create one dll with code compiled...

so i know that C# import dll libraries but when i add refrences it's make this error "Unable to retrieve assembly fullname ""Parameter name: AssemblyPath" and i dont kown what it means...

I searched on google and i found one method to import c++ dll manualy with DllImport and calling a external method... that causes one error because it's dont find the dll location... it's happens because wp7 don't suport C++???

thanks for help me

答: 3rd party WP7 apps may only comprise of managed code. C++ is also not a supported language, even in managed form, at this time.</p>

Title: import c++ dll to windows phone project


问:
CSS FlexBox Horizontal Mansory
I am trying to get my app to look like this:

https://stock.adobe.com/search?load_type=search&k=dogs&native_visual_search=&similar_content_id=

Here is my HTML:

```<code><div class = "container">
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/320/240"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/320/240/paris"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/320/500/cat"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/320/300/dog"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/520/240/girl"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/320/240/boy"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/320/240/piano"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/1020/400/rome"/>
  </div>
  <div class = "item">
    <img class = "image" src = "https://loremflickr.com/100/40/london"/>
  </div>
</div>
</code>```

Here is my CSS:

```<code>.container {
   display: flex;
   flex-wrap: wrap;
   flex-direction: row;
   align-content: flex-end;
}

.container .item {
    margin: 10px;
    flex: auto;
}

.container .image {
    display: block;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    height: 180px;
    object-fit: cover;
    min-width: 100%;
}
</code>```

Here is the jsfiddle: https://jsfiddle.net/qq137/7rsk5tfc/

A few issues I noticed with my implementation is when I use object-fit: cover, it cuts off part of the image and stretches the images to the edge of the div. I have tried using object-fit: contain which captures the whole image. However, it creates a lot of white space surrounding the image which I want to avoid. Anyone know how I would be able to make my list of images look like the one I shared in the link above? Any help is much appreciated

答:
The Adobe-Site solves this, by changing the overall size of the images by +-5% which gives the impression, that the images fit better. This is done using some JavaScript embedded into the Website.

As far as I know pure CSS doesn't allow you to automatically resize Containers (or images) in such a way ...

Based on:

https://www.w3schools.com/css/css3_object-fit.asp

https://www.w3.org/TR/css3-images/

https://www.w3schools.com/css/css3_flexbox.asp

Title: CSS FlexBox Horizontal Mansory

Body:
I am trying to get my app to look like this:

https://stock.adobe.com/search?load_type=search&k=dogs&native_visual_search=&similar_content_id=

Here is my HTML:

Here is my CSS:

.container {
   display: flex;
   flex-wrap: wrap;
   flex-direction: row;
   align-content: flex-end;
}

.container .item {
    margin: 10px;
    flex: auto;
}

.container .image {
    display: block;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
    height: 180px;
    object-fit: cover;
    min-width: 100%;
}

Here is the jsfiddle: https://jsfiddle.net/qq137/7rsk5tfc/

A few issues I noticed with my implementation is when I use object-fit: cover, it cuts off part of the image and stretches the images to the edge of the div. I have tried using object-fit: contain which captures the whole image. However, it creates a lot of white space surrounding the image which I want to avoid. Anyone know how I would be able to make my list of images look like the one I shared in the link above? Any help is much appreciated


问:
optimise code into linq expression
I have an observable collection I want to remove an element from.  I have tried using the linq .Where syntax but i am getting stuck with the casting.

```<code>public class Atc
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string ParentDescriptions { get; set; }
}
</code>```

i have defined the observable collection of medicines,

```<code>public ObservableCollection<Atc> MedicinesObservableCollection
</code>```

and i have a method to filter out the item from the collection that works:

```<code>private void RemoveMedicineListItem(string code)
{
    var filteredCollection = new ObservableCollection<Atc>();
    foreach (var item in MedicinesObservableCollection)
    {
        if (item.Code != code)
        {
            filteredCollection.Add(item);
        }
    }
    MedicinesObservableCollection = filteredCollection;
}
</code>```

I have tried:

```<code>(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);
</code>```

but this gets a runtime exception
System.InvalidCastException: 'Unable to cast object of type 'WhereEnumerableIterator1[Atc]' to type 'System.Collections.ObjectModel.ObservableCollection1[Atc]'.'

i get this is something to do with the linq enumerables but i am out of my depth.

答:
You can´t cast an instance of WhereIterator<Atc> (which your Where-clause actually returns) to ObservableCollection<Atc>). The returned instance only implements IEnumerable<Atc>, this is you can iterate it. However it doesn´t havy anything in common with any list, or in particular with an observable one.

However you can create a new one based on the returned value:

```<code>var result = new ObservableCollection(MedicinesObservableCollection.Where(x => x.Code != code));
</code>```

Title: optimise code into linq expression

Body:
I have an observable collection I want to remove an element from.  I have tried using the linq .Where syntax but i am getting stuck with the casting.

public class Atc
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string ParentDescriptions { get; set; }
}

i have defined the observable collection of medicines,

public ObservableCollection<Atc> MedicinesObservableCollection

and i have a method to filter out the item from the collection that works:

private void RemoveMedicineListItem(string code)
{
    var filteredCollection = new ObservableCollection<Atc>();
    foreach (var item in MedicinesObservableCollection)
    {
        if (item.Code != code)
        {
            filteredCollection.Add(item);
        }
    }
    MedicinesObservableCollection = filteredCollection;
}

I have tried:

(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);

but this gets a runtime exception
System.InvalidCastException: 'Unable to cast object of type 'WhereEnumerableIterator1[Atc]' to type 'System.Collections.ObjectModel.ObservableCollection1[Atc]'.'

i get this is something to do with the linq enumerables but i am out of my depth.

Body:
You can´t cast an instance of WhereIterator<Atc> (which your Where-clause actually returns) to ObservableCollection<Atc>). The returned instance only implements IEnumerable<Atc>, this is you can iterate it. However it doesn´t havy anything in common with any list, or in particular with an observable one.

However you can create a new one based on the returned value:

var result = new ObservableCollection(MedicinesObservableCollection.Where(x => x.Code != code));


问:
Appium, WebDriver
I am new to Appium. I try to execute my selenium script in mobile using Appium. But I got an error like below

org.openqa.selenium.WebDriverException: Returned value cannot be
  converted to WebElement: {ELEMENT=0.5768692365381867-1}

Code I am using is as below :-

```<code>AppiumDriver d;
    @BeforeClass
    public void setUp() throws Exception
    {
        //Set Capabilities
        DesiredCapabilities caps=new DesiredCapabilities();
        caps.setCapability("deviceName", "Celkon A35K Remote");
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "4.4.2");
        caps.setCapability("browserName", "Browser");

        d = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);
        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        d.manage().timeouts().pageLoadTimeout(120,TimeUnit.SECONDS);
    }
@Test
public void testFBLogin() throws Exception
{
    //Load web page
    d.get("https://www.facebook.com/");
    //Enter user name
    d.findElementByName("email").sendKeys("Appium");
    //Enter password
    d.findElementByName("pass").sendKeys("Appium");
    //Click on Login
    d.findElementByName("login").click();
    Thread.sleep(10000);
}
@AfterClass
public void tearDown()
{
    //Close browser
    d.quit();
}`script:
</code>```

答:
You should replace

```<code>AppiumDriver d;
</code>```

With this

```<code>AndroidDriver <MobileElement> d;
</code>```

Hopefully this will solve your issue.

Title: Appium, WebDriver

Body:
I am new to Appium. I try to execute my selenium script in mobile using Appium. But I got an error like below

org.openqa.selenium.WebDriverException: Returned value cannot be
  converted to WebElement: {ELEMENT=0.5768692365381867-1}

Code I am using is as below :-

AppiumDriver d;
    @BeforeClass
    public void setUp() throws Exception
    {
        //Set Capabilities
        DesiredCapabilities caps=new DesiredCapabilities();
        caps.setCapability("deviceName", "Celkon A35K Remote");
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "4.4.2");
        caps.setCapability("browserName", "Browser");

        d = new AndroidDriver(new URL("http://0.0.0.0:4723/wd/hub"), caps);
        d.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
        d.manage().timeouts().pageLoadTimeout(120,TimeUnit.SECONDS);
    }
@Test
public void testFBLogin() throws Exception
{
    //Load web page
    d.get("https://www.facebook.com/");
    //Enter user name
    d.findElementByName("email").sendKeys("Appium");
    //Enter password
    d.findElementByName("pass").sendKeys("Appium");
    //Click on Login
    d.findElementByName("login").click();
    Thread.sleep(10000);
}
@AfterClass
public void tearDown()
{
    //Close browser
    d.quit();
}`script:

Body:
You should replace

AppiumDriver d;

With this

AndroidDriver <MobileElement> d;

Hopefully this will solve your issue.


答:
you can return multiple values like shown below

```<code>data class Result(val result: Int, val status: Status)
fun function(...): Result {
    // computations

    return Result(result, status)
}

// Now, to use this function:
val (result, status) = function(...)
</code>```

see this documentation

for more example see this link

Title: How to return multiple values from a function in Kotlin like we do in Swift?

Body:
you can return multiple values like shown below

data class Result(val result: Int, val status: Status)
fun function(...): Result {
    // computations

    return Result(result, status)
}

// Now, to use this function:
val (result, status) = function(...)

see this documentation

for more example see this link


问:
Does C correctly handle sizeof(...) and sizeof ... in this case?
In the following code, are the functions test and test2 equivalent?

```<code>typedef int rofl;

void test(void) {
    rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}

void test2(void) {
    rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}
</code>```

In other words:

Does rofl in sizeof(rofl) correctly pick the rofl type because of the parentheses?

Does rofl in sizeof *rofl correctly pick the rofl variable because of a lack of parentheses?

Note: This is a silly-looking example, but it can actually happen in practice that you have a type name that's the same as a variable name. Hence the question.

答:
There is no "picking" or "choosing" involved. In both cases the rofl referred to in each sizeof invocation is the variable, not the type, due to scoping rules. The variable is declared at inner scope, and thus overrides the type name. The parenthesization of the argument to the sizeof operator is irrelevant.

Best of luck.

Body:
In the following code, are the functions test and test2 equivalent?

typedef int rofl;

void test(void) {
    rofl * rofl = malloc(sizeof(rofl)); // Is the final rofl here the TYPE?
}

void test2(void) {
    rofl * rofl = malloc(sizeof *rofl); // Is the final rofl here the VARIABLE?
}

In other words:

Does rofl in sizeof(rofl) correctly pick the rofl type because of the parentheses?

Does rofl in sizeof *rofl correctly pick the rofl variable because of a lack of parentheses?

Note: This is a silly-looking example, but it can actually happen in practice that you have a type name that's the same as a variable name. Hence the question.


答:
change this way

```<code>$("#addresses input").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});
</code>```

https://jsfiddle.net/6d0zydjj/1/

Title: jquery radio button change event not working

Body:
I want to display some form when the specific radio button is checked and to hide it when user selects other radio button

  <input type="radio" name="deco_request[address]" value="value["id"]"> Some address

  <input type="radio" name="deco_request[address]" value="other" id="other-address"> Other Address

js code:

$("#other-address").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});

from what I see the change event is not firing up, I also tried click event but didn't have any success with it too, also I noticed when I check the radio button no checked attributes is added but .is(':checked') returns true

Body:
change this way

$("#addresses input").on("change", function() {
  if ($("#other-address").is(':checked')) {
    return $("#new-address").show();
  } else {
    return $("#new-address").hide();
  }
});

https://jsfiddle.net/6d0zydjj/1/


问:
strophe connect openfire error
I input a jid and pwd on a html form, and use Strophe to connect to openfire, but when I press the login button, the xmpp server response is error 302.
I enabled the option on openfire, and restarted it.

```<code>var BOSH_SERVICE = 'http://ip:7070/http-bind';
    $('#btn-login').click(function() {
    if(!connected) {
        connection = new Strophe.Connection(BOSH_SERVICE);
        connection.connect($("#input-jid").val(), $("#input-pwd").val(), onConnect);
        jid = $("#input-jid").val();
    }
});
</code>```

It seems a little harder than to use smack in java because of the network problem?

答:
The problem is in the uri specified in BOSH_SERVICE.

Correct uri is:

http://ip:7070/http-bind/

Pay attention to the / at the bottom of the string.

Title: strophe connect openfire error

Body:
I input a jid and pwd on a html form, and use Strophe to connect to openfire, but when I press the login button, the xmpp server response is error 302.
I enabled the option on openfire, and restarted it.

var BOSH_SERVICE = 'http://ip:7070/http-bind';
    $('#btn-login').click(function() {
    if(!connected) {
        connection = new Strophe.Connection(BOSH_SERVICE);
        connection.connect($("#input-jid").val(), $("#input-pwd").val(), onConnect);
        jid = $("#input-jid").val();
    }
});

It seems a little harder than to use smack in java because of the network problem?


问:
Correct way to catch an error with fluent ffmpeg
I'm using Fluent FFMpeg in my NodeJS application and I'm trying to add some error handling in the event an input doesn't exist. At the moment it's just crashing out with this message:

```<code>events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ffmpeg exited with code 1: http://localhost:9001: Connection refused
</code>```

When an input source doesn't exist I want to wait some time (say 1 second) and try again. This is currently my code:

```<code>var command = FFmpeg("http://localhost:9001")
  // set options here
;

var stream = command.pipe();
stream.on('data', function(chunk) {
  // do something with the data
});
</code>```

How do correctly cater to an error when the input doesn't (yet) exist?

答:
you can get the error infomation in the "error" handler like:</p>

```<code>stream.on('error', function(err, stdout, stderr) {
  console.log("ffmpeg stdout:\n" + stdout);
  console.log("ffmpeg stderr:\n" + stderr);
})
</code>```

Body:
I'm using Fluent FFMpeg in my NodeJS application and I'm trying to add some error handling in the event an input doesn't exist. At the moment it's just crashing out with this message:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: ffmpeg exited with code 1: http://localhost:9001: Connection refused

When an input source doesn't exist I want to wait some time (say 1 second) and try again. This is currently my code:

var command = FFmpeg("http://localhost:9001")
  // set options here
;

var stream = command.pipe();
stream.on('data', function(chunk) {
  // do something with the data
});

How do correctly cater to an error when the input doesn't (yet) exist?

Body:
you can get the error infomation in the "error" handler like:

stream.on('error', function(err, stdout, stderr) {
  console.log("ffmpeg stdout:\n" + stdout);
  console.log("ffmpeg stderr:\n" + stderr);
})


问:
SQL convert column headers to convert row values
I have a table like this:

but what I am trying to achieve is this:

Please can anyone offer some much needed help to this SQL newbie.

Thanks

答:
First your database model seems to be quite bad. You should have 2 tables and not only 1.

But anyway here is a solution

```<code>SELECT Jobno,
OPNo,
OperationType,
CASE OPNo
     WHEN 'OP1' then Op1
     WHEN 'OP2' then Op2
     WHEN 'OP3' then Op3
END as Operator
FROM pd
</code>```

Body:
First your database model seems to be quite bad. You should have 2 tables and not only 1.

But anyway here is a solution

SELECT Jobno,
OPNo,
OperationType,
CASE OPNo
     WHEN 'OP1' then Op1
     WHEN 'OP2' then Op2
     WHEN 'OP3' then Op3
END as Operator
FROM pd


答:
"Standard" in this context refers to a style guide that dictates no semicolons as a default.  It shouldn't be taken as meaning "standard" as in a ECMA standard.

You can see the styleguide here: https://standardjs.com/

Title: Why is not using semicolon is encouraged in standard configuration of eslint?

Body:
My project extends 'standard' rules for javascript in .eslintrc.js file, and according to that Javascript code shouldn't have semicolon at the end of lines. I have never seen something like that. Is it useful to leave it like that? Or am I misunderstanding the whole thing?

"semi" rule from standard eslint rules:

"semi": ["error", "never"]

Usage from eslint documentation:

/*eslint semi: ["error", "never"]*/

var name = "ESLint"

object.method = function() {
    // ...
}

var name = "ESLint"

;(function() {
    // ...
})()


答: WP7 doesn't support c++.  you would also probably need to recompile the c++ dll anyways, even if it was supported.</p>

Title: import c++ dll to windows phone project

Body:
I'm new on windows phone developement and i have one problem that i don't know how to resolve....

the problem is....

i have a c++ project that i had complided with visual c++ 2010 and this create one dll with code compiled...

so i know that C# import dll libraries but when i add refrences it's make this error "Unable to retrieve assembly fullname ""Parameter name: AssemblyPath" and i dont kown what it means...

I searched on google and i found one method to import c++ dll manualy with DllImport and calling a external method... that causes one error because it's dont find the dll location... it's happens because wp7 don't suport C++???

thanks for help me