问:
var module = require() or const {module} = require()?
Whats the diference between this two require methods:

```<code>1. var xx = require('module')
2. const {xx} = require('module')
</code>```

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks

答:
```<code>1. var xx = require('module')
2. const {xx} = require('module')
</code>```

First, var is a variable type whose value can be modified after defined; the const value cannot be modified after defined.

Second, var xx is referring to the main export of module; const { xx } is referring to a property of module's export.

Example 1. Module

```<code>const xx = {}
module.exports = xx
</code>```

Example 2. Module

```<code>const xx = {}
const yy = {}
module.exports = {
  xx,
  yy,
}
</code>```

Otherwise...

Example 1. Module

```<code>const xx = {}
export default xx
</code>```

Example 2. Module

```<code>const xx = {}
const yy = {}
export default {
  xx,
  yy,
}
</code>```

Body:
Whats the diference between this two require methods:

1. var xx = require('module')
2. const {xx} = require('module')

I saw the first onde I can access xx as variable, with all script exported by module.. and second xx are undefined. How to access second "method" or is it a method too construct module to use {}

thanks

Body:
1. var xx = require('module')
2. const {xx} = require('module')

First, var is a variable type whose value can be modified after defined; the const value cannot be modified after defined.

Second, var xx is referring to the main export of module; const { xx } is referring to a property of module's export.

Example 1. Module

const xx = {}
module.exports = xx

Example 2. Module

const xx = {}
const yy = {}
module.exports = {
  xx,
  yy,
}

Otherwise...

Example 1. Module

const xx = {}
export default xx

Example 2. Module

const xx = {}
const yy = {}
export default {
  xx,
  yy,
}


来源: stackexchange

问:
I don't understand the Fibonacci pair haskell function given (tuples)
Recursion is something I have always struggled with understanding. I hope I can get some assistance here on how this function works. It works but I want to know how:</p>

```<code>fibStep :: (Int,Int) -> (Int,Int)
fibStep    (u,  v)    = (v,  u+v)

fibPair :: Int -> (Int,Int)
fibPair n
    | n==0      = (0,1)
    | otherwise = fibStep (fibPair (n-1))
</code>```

答:
Generally, when ever you're doing recursion, try working backwards and with small values, for example, if we pass fibPair with n=0, it immediately returns (0,1).

Then, if n=1, we get,

fibPair 1 = fibStep (fibPair 0) = fibStep (0, 1) = (1,1)

Then, with n=2 we get,

```<code>fibPair 2 = fibStep (fibPair 1) = fibStep (1,1) = (1,2)
</code>```

So, as we can see, it gives you the nth pair of the fibonacci sequence by bringing it up from (0, 1).

If you still don't really understand it, try to expand out fibPair 2 fully (i.e. expand out fibStep (fibPair 1))

ContentLicense: CC BY-SA 3.0

Body:
Recursion is something I have always struggled with understanding. I hope I can get some assistance here on how this function works. It works but I want to know how:

fibStep :: (Int,Int) -> (Int,Int)
fibStep    (u,  v)    = (v,  u+v)

fibPair :: Int -> (Int,Int)
fibPair n
    | n==0      = (0,1)
    | otherwise = fibStep (fibPair (n-1))

Body:
Generally, when ever you're doing recursion, try working backwards and with small values, for example, if we pass fibPair with n=0, it immediately returns (0,1).

Then, if n=1, we get,

fibPair 1 = fibStep (fibPair 0) = fibStep (0, 1) = (1,1)

Then, with n=2 we get,

fibPair 2 = fibStep (fibPair 1) = fibStep (1,1) = (1,2)

So, as we can see, it gives you the nth pair of the fibonacci sequence by bringing it up from (0, 1).

If you still don't really understand it, try to expand out fibPair 2 fully (i.e. expand out fibStep (fibPair 1))


问:
How to add Mac-address in Django framework
I have a django app that allows user to login but I want to have only one user for one device.After some research getting the mac address of device from which users login and then storing the mac address in database seems to be good logic.How can I do so?Any python packages or so??

答:
You can't get this information on your host server because MAC address uniquely identifies the running computer so it would be a security vulnerability.

There are more user identification options such as local storage or just cookies.

ContentLicense: CC BY-SA 4.0


问:
How to kill thread in Android Studio
Goal: I want to increment the counter when the app is in the background and when the app is now in resume the increment should stop, then the last value of the counter will be displayed in the screen.

Actual: but when I run my code, counter is successfully incremented if the app is in the background. But when I resume, the counter is still incrementing. How can I stop this thread if it is now in resume?

This is my code in MainActivity.java

```<code>package com.example.background;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

TextView timeTextView;
Button buttonCtr;
int counter=0;
boolean isResume;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timeTextView = (TextView) findViewById(R.id.timeLbl);
    buttonCtr = (Button) findViewById(R.id.ctrUp);

    buttonCtr.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            counter++;
            timeTextView.setText(String.valueOf(counter));
        }
    });

}

class backgroundProcess extends Thread {

    @Override
    public void run() {

        while(isResume == false ) {
            counter++;
            System.out.println(counter);
        }

        System.out.println("LAST COUNT:" + counter);

    }
}

@Override
protected void onPause() {
    super.onPause();
    isResume=false;
    System.out.println("IM IN PAUSE");
    System.out.println("IS RESUME: "+ isResume);
    new Thread(new backgroundProcess()).start();
}

@Override
protected void onRestart() {
    super.onRestart();

    isResume=true; //to stop backgroundProcess Thread

    System.out.println("IM IN RESUME");
    System.out.println("IS RESUME: "+ isResume);
    System.out.println("LAST COUNT:"+ counter);
    timeTextView.setText(String.valueOf(counter));

}
</code>```

}

and this is my code for my xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/timeLbl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:textSize="18sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.482"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.397" />

<Button
    android:id="@+id/ctrUp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="196dp"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.475"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/timeLbl"
    app:layout_constraintVertical_bias="0.54" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
2 things, here:

You are not using any synchronization primitives. This means the background thread's read of isResume is unreliable; it may appear to the background thread that isResume is false, even though the UI thread has already set it to true. In this particular instance, you should be able to declare isResume as volatile, and that will eliminate the cache coherency problem.

You are dumping information to logcat at an extremely high rate, probably hundreds of thousands of lines per second (System.out.println(counter)). Android Studio has trouble reading & displaying logcat information at such a rate. It will usually lag behind, in this case, which can lead to the appearance that your thread is running, even though it has already stopped.

I should also mention that your access of counter is not threadsafe. Unlike isResume, you are doing read/write operations (++) on counter from both threads, so the volatile keyword is an insufficient fix. You must ensure all accesses to counter are protected by an actual lock (for example, by wrapping them in a synchronized(MainActivity.this) block).

Title: How to kill thread in Android Studio

Body:
Goal: I want to increment the counter when the app is in the background and when the app is now in resume the increment should stop, then the last value of the counter will be displayed in the screen.

Actual: but when I run my code, counter is successfully incremented if the app is in the background. But when I resume, the counter is still incrementing. How can I stop this thread if it is now in resume?

This is my code in MainActivity.java

package com.example.background;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

TextView timeTextView;
Button buttonCtr;
int counter=0;
boolean isResume;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timeTextView = (TextView) findViewById(R.id.timeLbl);
    buttonCtr = (Button) findViewById(R.id.ctrUp);

    buttonCtr.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            counter++;
            timeTextView.setText(String.valueOf(counter));
        }
    });

}

class backgroundProcess extends Thread {

    @Override
    public void run() {

        while(isResume == false ) {
            counter++;
            System.out.println(counter);
        }

        System.out.println("LAST COUNT:" + counter);

    }
}

@Override
protected void onPause() {
    super.onPause();
    isResume=false;
    System.out.println("IM IN PAUSE");
    System.out.println("IS RESUME: "+ isResume);
    new Thread(new backgroundProcess()).start();
}

@Override
protected void onRestart() {
    super.onRestart();

    isResume=true; //to stop backgroundProcess Thread

    System.out.println("IM IN RESUME");
    System.out.println("IS RESUME: "+ isResume);
    System.out.println("LAST COUNT:"+ counter);
    timeTextView.setText(String.valueOf(counter));

}

}

and this is my code for my xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:id="@+id/timeLbl"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:textSize="18sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.482"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.397" />

<Button
    android:id="@+id/ctrUp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="196dp"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.475"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/timeLbl"
    app:layout_constraintVertical_bias="0.54" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
How to make a Bootstrap dropdown with React
I am a noobie at React and I am trying to make a Bootstrap dropdown.  The html that I am attaching to is here:

```

<p>And here is what I want to put in my <code>render</code> method to insert inside of my html:</p>

<pre class="lang-js prettyprint-override"><code>render: function() {
  return (
      <li>Books</li>
      <li>Podcasts</li>
      <li>Tech I Like</li>
      <li>About me</li>
      <li>Add a Blog</li>
    );
}
</code>```

But of course I can only return one element.  What is the right way of doing this in React?  How could I add multiple
's into a dropdown like this?  I tried wrapping the whole thing in a
, but that messes up my css.

答:
If you don't want to employ rebuilt dependencies like react bootstrap to work with both react and bootstrap, simply do the important js tricks which they do. In your case, basically a dropdown click event toggles the popper wrapper with .show css class. So you can define an onClick method and toggle the class inside it. For example in the following code I get the nextSibling and then toggle the class name for it with .show and finally inner div will be shown:

```<code><div className="dropdown">
    <a className="btn text-light" href="#" onClick={(e) => this.handleOption(e)}>open dropdown</a>
    <div className="dropdown-menu dropdown-menu-left dropdown-menu-arrow">
        <a className="dropdown-item" href="#">edit</a>
        <a className="dropdown-item" href="#">delete</a>
    </div>
</div>
</code>```

Note that this tricks help you in case of few bootstrap functionalities in your project, otherwise employ rebuilt dependencies to have a clean and standard code.

Body:
I am a noobie at React and I am trying to make a Bootstrap dropdown.  The html that I am attaching to is here:

And here is what I want to put in my render method to insert inside of my html:

render: function() {
  return (

Books

Podcasts

Tech I Like

About me

Add a Blog

    );
}

But of course I can only return one element.  What is the right way of doing this in React?  How could I add multiple
's into a dropdown like this?  I tried wrapping the whole thing in a
, but that messes up my css.

Body:
If you don't want to employ rebuilt dependencies like react bootstrap to work with both react and bootstrap, simply do the important js tricks which they do. In your case, basically a dropdown click event toggles the popper wrapper with .show css class. So you can define an onClick method and toggle the class inside it. For example in the following code I get the nextSibling and then toggle the class name for it with .show and finally inner div will be shown:

<div className="dropdown">
    <a className="btn text-light" href="#" onClick={(e) => this.handleOption(e)}>open dropdown</a>
    <div className="dropdown-menu dropdown-menu-left dropdown-menu-arrow">
        <a className="dropdown-item" href="#">edit</a>
        <a className="dropdown-item" href="#">delete</a>
    </div>
</div>

Note that this tricks help you in case of few bootstrap functionalities in your project, otherwise employ rebuilt dependencies to have a clean and standard code.


问:
how in python Remove files with .log Extension
How can I list all file of a directory in Python and remove them by .log?

```<code>for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)

output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log
</code>```

i run this code in Centos7 but i just need list file with .log file extension for delete times

答:
This could be accomplished by calling rm *.log in the bash as well, but for python:

```<code>import os
from glob import glob
log_file_list = glob('folder/*.log')
for file in log_file_list:
    os.remove(file)
</code>```

This is only works for files in the top level of a folder.

Glob does pathname pattern matching as the unix bash does, os.remove removes a file with a given path.

If you want to include subfolders, you can set the recursive=True flag and change the search expression like so:

```<code>import os
from glob import glob
log_file_list = glob('folder/**/*.log', recursive=True)
for file in log_file_list:
    os.remove(file)
</code>```

Body:
How can I list all file of a directory in Python and remove them by .log?

for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)

output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log

i run this code in Centos7 but i just need list file with .log file extension for delete times

Body:
This could be accomplished by calling rm *.log in the bash as well, but for python:

import os
from glob import glob
log_file_list = glob('folder/*.log')
for file in log_file_list:
    os.remove(file)

This is only works for files in the top level of a folder.

Glob does pathname pattern matching as the unix bash does, os.remove removes a file with a given path.

If you want to include subfolders, you can set the recursive=True flag and change the search expression like so:

import os
from glob import glob
log_file_list = glob('folder/**/*.log', recursive=True)
for file in log_file_list:
    os.remove(file)


问:
Calculate ship speed given latitude and longitude in a loop
I would like to read certain lat and lon values and calculate ship speed in a for loop every minute.  One minute represents every 480th row.  I'm not really sure how to do this in a loop.</p>

```<code>Lat = table2array(timepositionrawdata1150seq(:,2));
Lon = table2array(timepositionrawdata1150seq(:,3));

for i=1:480:42072

lat1100 = Lat(1);
lon1100 = Lon(1);
lat1101 = Lat(481);
lon1101 = Lon(481);
dist_1101 = 1000*(deg2km(distance(lat1100, lon1100, lat1101, lon1101)));
speed_1101 = dist_1101./60;
az_1101 = azimuth(lat1100,lon1100,lat1101,lon1101);
heading_1101 = az_1101 + 180;

end
</code>```

答:
You mean just this below?</p>

```<code>Lat = table2array(timepositionrawdata1150seq(:,2));
Lon = table2array(timepositionrawdata1150seq(:,3));

for i=1:480:(42072-480)

  lat1100 = Lat(i);
  lon1100 = Lon(i);
  lat1101 = Lat(i+480);
  lon1101 = Lon(i+480);
  dist_1101 = 1000*(deg2km(distance(lat1100, lon1100, lat1101, lon1101)));
  speed_1101 = dist_1101./60;
  az_1101 = azimuth(lat1100,lon1100,lat1101,lon1101);
  heading_1101 = az_1101 + 180;

end
</code>```

Body:
I would like to read certain lat and lon values and calculate ship speed in a for loop every minute.  One minute represents every 480th row.  I'm not really sure how to do this in a loop.

Lat = table2array(timepositionrawdata1150seq(:,2));
Lon = table2array(timepositionrawdata1150seq(:,3));

for i=1:480:42072

lat1100 = Lat(1);
lon1100 = Lon(1);
lat1101 = Lat(481);
lon1101 = Lon(481);
dist_1101 = 1000*(deg2km(distance(lat1100, lon1100, lat1101, lon1101)));
speed_1101 = dist_1101./60;
az_1101 = azimuth(lat1100,lon1100,lat1101,lon1101);
heading_1101 = az_1101 + 180;

end

Body:
You mean just this below?

Lat = table2array(timepositionrawdata1150seq(:,2));
Lon = table2array(timepositionrawdata1150seq(:,3));

for i=1:480:(42072-480)

  lat1100 = Lat(i);
  lon1100 = Lon(i);
  lat1101 = Lat(i+480);
  lon1101 = Lon(i+480);
  dist_1101 = 1000*(deg2km(distance(lat1100, lon1100, lat1101, lon1101)));
  speed_1101 = dist_1101./60;
  az_1101 = azimuth(lat1100,lon1100,lat1101,lon1101);
  heading_1101 = az_1101 + 180;

end


问:
redirect all /api/.. requests to express
I currently have a nginx server running with a react app as frontend and a express server as backend.

The express server is running at localhost:5000/

```<code>  server {
    listen 80 ;

    server_name siteurl;
    server_name siteip;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf; # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

     location ^~ /api/ {
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header X-NginX-Proxy true;
             proxy_pass http://localhost:5000/;
             proxy_ssl_session_reuse off;
             proxy_set_header Host $http_host;
             proxy_cache_bypass $http_upgrade;
             proxy_redirect off;

    }

    location / {
            # First attempt to serve request as file, then

            # as directory, then fall back to displaying a 404.
            root /usr/share/nginx/site/front;
            try_files $uri /index.html =404;
    }
</code>```

I want all /api/* requests to redirect to my express server, currently when I do site/api/ it goes to my express server, however when doing /api/users it won't go to my express server and will go to my react server.

How would I be able to make this work
thx

答:
When you use the ^~ modifier within the location directive, you actually tell nginx that the path following is a regular expression. If so, you have to format it as a regular expression:

```<code>location ^~ /api/.* {
</code>```

Body:
I currently have a nginx server running with a react app as frontend and a express server as backend.

The express server is running at localhost:5000/

  server {
    listen 80 ;

    server_name siteurl;
    server_name siteip;

    # SSL configuration
    #
    # listen 443 ssl default_server;
    # listen [::]:443 ssl default_server;
    #
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    #
    # Read up on ssl_ciphers to ensure a secure configuration.
    # See: https://bugs.debian.org/765782
    #
    # Self signed certs generated by the ssl-cert package
    # Don't use them in a production server!
    #
    # include snippets/snakeoil.conf; # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

     location ^~ /api/ {
             proxy_set_header X-Real-IP $remote_addr;
             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             proxy_set_header X-NginX-Proxy true;
             proxy_pass http://localhost:5000/;
             proxy_ssl_session_reuse off;
             proxy_set_header Host $http_host;
             proxy_cache_bypass $http_upgrade;
             proxy_redirect off;

    }

    location / {
            # First attempt to serve request as file, then

            # as directory, then fall back to displaying a 404.
            root /usr/share/nginx/site/front;
            try_files $uri /index.html =404;
    }

I want all /api/* requests to redirect to my express server, currently when I do site/api/ it goes to my express server, however when doing /api/users it won't go to my express server and will go to my react server.

How would I be able to make this work
thx

Body:
When you use the ^~ modifier within the location directive, you actually tell nginx that the path following is a regular expression. If so, you have to format it as a regular expression:

location ^~ /api/.* {


问:
Breaking up a string into a list of tokens using another string as a delimiter?
Let's say I have this string:

```<code>char *myTestString = "Hello AND test AND test2";
</code>```

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

```<code>char *myTestString2 = "Hi AND there AND test AND test2";
</code>```

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

答:
strstr can be used to locate the sub-string. Check that the leading and trailing characters are space or trailing terminating zero.

As needed remove whitespace.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main ( void) {
    char *myTestString = "   AND SANDY AND Hello there AND AND test AND test2 AND test3    ";
    char *match = "AND";
    char *first = myTestString;
    char *start = myTestString;
    char *find = myTestString;
    int len = strlen ( match);

    while ( isspace ( (unsigned char)*start)) {//skip leading whitespace
        ++start;
        ++first;
    }
    while ( ( find = strstr ( start, match))) {
        if ( find != first) {
            //check for leading and trailing space or terminating zero
            while ( ! (isspace ( (unsigned char)*(find - 1))
            &&  ( isspace ( (unsigned char)*(find + len)) || 0 == *(find + len)))) {
                find = strstr ( find + 1, match);
                if ( ! find) {
                    find = start + strlen ( start);
                    while ( isspace ( (unsigned char)*(find - 1))) {
                        --find;
                    }
                    break;
                }
            }
            int span = (int)(find - start);
            if ( span) {
                printf ( "%.*s\n", span, start);
            }
        }
        start = find + strlen ( match);
        while ( isspace ( (unsigned char)*start)) {//skip trailing whitespace
            ++start;
        }
    }
    if ( *start) {
        int end = strlen ( start) - 1;
        while ( isspace ( (unsigned char)start[end])) {
            --end;//remove trailing whitspace
        }
        printf ("%.*s\n", end + 1, start);
    }

    return 0;
}
</code>```

Allocate memory to char**, allocate memory and copy each token.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char **freetokens ( char **tokens);
void showtokens ( char **tokens);
char **addtoken ( char **tokens, int *count, char *text, int size);

int main ( void) {
    char *myTestString = "   AND SANDY AND Hello there test AND AND test2 AND test3   ";
    char *match = "AND";
    char *first = myTestString;
    char *start = myTestString;
    char *find = myTestString;
    char **tokens = NULL;
    int items = 0;
    int len = strlen ( match);

    while ( isspace ( (unsigned char)*start)) {//skip leading whitespace
        ++start;
        ++first;
    }
    while ( ( find = strstr ( start, match))) {
        if ( find != first) {
            //check for leading and trailing space or terminating zero
            while ( ! (isspace ( (unsigned char)*(find - 1))
            &&  ( isspace ( (unsigned char)*(find + len)) || 0 == *(find + len)))) {
                find = strstr ( find + 1, match);
                if ( ! find) {
                    find = start + strlen ( start);
                    while ( isspace ( (unsigned char)*(find - 1))) {
                        --find;//remove trailing whitespace
                    }
                    break;
                }
            }
            int span = (int)(find - start);
            if ( span) {
                tokens = addtoken ( tokens, &items, start, span);
            }
        }
        start = find + strlen ( match);
        while ( isspace ( (unsigned char)*start)) {//skip trailing whitespace
            ++start;
        }
    }
    if ( *start) {
        int end = strlen ( start);
        while ( isspace ( (unsigned char)start[end - 1])) {
            --end;
        }
        tokens = addtoken ( tokens, &items, start, end);
    }

    showtokens ( tokens);

    tokens = freetokens ( tokens);

    return 0;
}

char **addtoken ( char **tokens, int *count, char *text, int size) {
    char **temp = NULL;
    if ( NULL == ( temp = realloc ( tokens, sizeof *tokens * ( *count + 2)))) {
        fprintf ( stderr, "problem realloc tokens\n");
        return tokens;
    }
    tokens = temp;
    tokens[*count + 1] = NULL;//sentinel
    if ( NULL == ( tokens[*count] = malloc ( size + 1))) {
        fprintf ( stderr, "problem realloc tokens[]\n");
        return tokens;
    }
    memmove ( tokens[*count], text, size);
    tokens[*count][size] = 0;//terminate
    ++*count;

    return tokens;
}

char **freetokens ( char **tokens) {
    int each = 0;
    while ( tokens && tokens[each]) {
        free ( tokens[each]);
        ++each;
    }
    free ( tokens);

    return NULL;
}
</code>```

Body:
Let's say I have this string:

char *myTestString = "Hello AND test AND test2";

I want to break this down into the set { Hello, test, test2 }, which I can finally iterate over.

Or I have

char *myTestString2 = "Hi AND there AND test AND test2";

I want to break this down into the set { Hi, there, test, test2 }, which I can later iterate over.

How do I achieve this using C?

EDIT:
Another example is splitting "Hello there AND test" should give out set { Hello there, test }.
For clarification "AND" is delimiter here.

Body:
strstr can be used to locate the sub-string. Check that the leading and trailing characters are space or trailing terminating zero.

As needed remove whitespace.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main ( void) {
    char *myTestString = "   AND SANDY AND Hello there AND AND test AND test2 AND test3    ";
    char *match = "AND";
    char *first = myTestString;
    char *start = myTestString;
    char *find = myTestString;
    int len = strlen ( match);

    while ( isspace ( (unsigned char)*start)) {//skip leading whitespace
        ++start;
        ++first;
    }
    while ( ( find = strstr ( start, match))) {
        if ( find != first) {
            //check for leading and trailing space or terminating zero
            while ( ! (isspace ( (unsigned char)*(find - 1))
            &&  ( isspace ( (unsigned char)*(find + len)) || 0 == *(find + len)))) {
                find = strstr ( find + 1, match);
                if ( ! find) {
                    find = start + strlen ( start);
                    while ( isspace ( (unsigned char)*(find - 1))) {
                        --find;
                    }
                    break;
                }
            }
            int span = (int)(find - start);
            if ( span) {
                printf ( "%.*s\n", span, start);
            }
        }
        start = find + strlen ( match);
        while ( isspace ( (unsigned char)*start)) {//skip trailing whitespace
            ++start;
        }
    }
    if ( *start) {
        int end = strlen ( start) - 1;
        while ( isspace ( (unsigned char)start[end])) {
            --end;//remove trailing whitspace
        }
        printf ("%.*s\n", end + 1, start);
    }

    return 0;
}

Allocate memory to char**, allocate memory and copy each token.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char **freetokens ( char **tokens);
void showtokens ( char **tokens);
char **addtoken ( char **tokens, int *count, char *text, int size);

int main ( void) {
    char *myTestString = "   AND SANDY AND Hello there test AND AND test2 AND test3   ";
    char *match = "AND";
    char *first = myTestString;
    char *start = myTestString;
    char *find = myTestString;
    char **tokens = NULL;
    int items = 0;
    int len = strlen ( match);

    while ( isspace ( (unsigned char)*start)) {//skip leading whitespace
        ++start;
        ++first;
    }
    while ( ( find = strstr ( start, match))) {
        if ( find != first) {
            //check for leading and trailing space or terminating zero
            while ( ! (isspace ( (unsigned char)*(find - 1))
            &&  ( isspace ( (unsigned char)*(find + len)) || 0 == *(find + len)))) {
                find = strstr ( find + 1, match);
                if ( ! find) {
                    find = start + strlen ( start);
                    while ( isspace ( (unsigned char)*(find - 1))) {
                        --find;//remove trailing whitespace
                    }
                    break;
                }
            }
            int span = (int)(find - start);
            if ( span) {
                tokens = addtoken ( tokens, &items, start, span);
            }
        }
        start = find + strlen ( match);
        while ( isspace ( (unsigned char)*start)) {//skip trailing whitespace
            ++start;
        }
    }
    if ( *start) {
        int end = strlen ( start);
        while ( isspace ( (unsigned char)start[end - 1])) {
            --end;
        }
        tokens = addtoken ( tokens, &items, start, end);
    }

    showtokens ( tokens);

    tokens = freetokens ( tokens);

    return 0;
}

char **addtoken ( char **tokens, int *count, char *text, int size) {
    char **temp = NULL;
    if ( NULL == ( temp = realloc ( tokens, sizeof *tokens * ( *count + 2)))) {
        fprintf ( stderr, "problem realloc tokens\n");
        return tokens;
    }
    tokens = temp;
    tokens[*count + 1] = NULL;//sentinel
    if ( NULL == ( tokens[*count] = malloc ( size + 1))) {
        fprintf ( stderr, "problem realloc tokens[]\n");
        return tokens;
    }
    memmove ( tokens[*count], text, size);
    tokens[*count][size] = 0;//terminate
    ++*count;

    return tokens;
}

char **freetokens ( char **tokens) {
    int each = 0;
    while ( tokens && tokens[each]) {
        free ( tokens[each]);
        ++each;
    }
    free ( tokens);

    return NULL;
}


问:
How do you load .js files with ASP.NET?
```<code><%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  <script runat="server">

Sub Page_Load(ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptInclude("basicjs", "basic.js")
End Sub

</script>
    <title>RegisterClientScriptBlock Example</title>
  </head>
  <body>
<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>
  </body>
</html>
</code>```

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

答:
Is the basic.js is accessible from the page? I mean if the page and js file located under one folder?

You can get more idea from here:

http://blog.janjonas.net/2011-01-19/asp_net-add-script-tags-include-javascript-master-pages-head-tag

Thanks!

Dhananjay

Title: How do you load .js files with ASP.NET?

Body:
<%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>RegisterClientScriptBlock Example</title>

<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?


问:
Distinguish between one-, two- and three-word commands
Right now, I am using this method to check if the user just typed in a command with wrong arguments:

```<code>    private boolean relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return false;
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .anyMatch(patternText -> patternText.startsWith(command + " ");
    }
</code>```

(COMMAND_PACKAGE contains all registered commands)

Now, this works perfectly fine for one-word commands. E. g. get <argument1> <argument2>, remove <argument1>.

However, I am currently working on a project that has both one-word and two-word commands.
Here is a range of commands that doesn't really work with this method:
add track <argument1>, add switch <argument1>, step <argument>. In this case, for the command add track <argument1>, "track" is seen as an argument but it really belongs to the command itself.

If the use just types in "add" the error message is "invalid arguments". Instead, the error message should be more precise and tell him that this command doesn't exist (as there is only "add track" or "add switch").

Does anyone have any idea how to distinguish between one-word and two-word commands? The user can also use the command delete rolling stock <argument> which consists of a three-word command.

All in all, it is therefore necessary to differentiate between commands of one, two and three words.

答:
To be honest, the simplest and the most efficient method of solving this is to create the list of commands that have two or three words and then simply perform matching in a separate method, so that if You hit a keyword that is part of longer command you check for the next word to see if it's the part of the command You are expecting.

Depending on the exact specification of the commands and so on, You could perhaps use the HashMap<String, HashMap<String, String>> to represent the commands. This way You could simply do something like storing the prefix as key and then suffixes as values.

Body:
Right now, I am using this method to check if the user just typed in a command with wrong arguments:

    private boolean relatedCommand(String input) {
        // make sure the split afterwards has at least size one
        if (input.matches(" .*")) {
            return false;
        }
        final String command = input.split(" ".toString())[0];
        return COMMAND_PACKAGE
                .keySet()
                .stream()
                .map(Pattern::toString)
                .anyMatch(patternText -> patternText.startsWith(command + " ");
    }

(COMMAND_PACKAGE contains all registered commands)

Now, this works perfectly fine for one-word commands. E. g. get <argument1> <argument2>, remove <argument1>.

However, I am currently working on a project that has both one-word and two-word commands.
Here is a range of commands that doesn't really work with this method:
add track <argument1>, add switch <argument1>, step <argument>. In this case, for the command add track <argument1>, "track" is seen as an argument but it really belongs to the command itself.

If the use just types in "add" the error message is "invalid arguments". Instead, the error message should be more precise and tell him that this command doesn't exist (as there is only "add track" or "add switch").

Does anyone have any idea how to distinguish between one-word and two-word commands? The user can also use the command delete rolling stock <argument> which consists of a three-word command.

All in all, it is therefore necessary to differentiate between commands of one, two and three words.


问:
How to use variable inside the body of the view using swiftUI?
i'm trying to using a variable and modify inside the foreach of swiftui.

below are the code i'm using. please let me know how can i modify the value inside the body of the view.

```<code>struct SearchView : View {
var chatmember = ChatMember(with: JSON())

var body: some View{
    VStack(spacing: 10){
        VStack{
            prefView()
                .padding(.bottom, 30)
            Text("Tap to start making friend")
        }
        ScrollView(.horizontal, content: {
            HStack(spacing: 10) {
                ForEach(userDataList) { user in
                     chatmember = ChatMember(hashValue: 0, email: "", fullName: "", online: "", userId: user.userId, userImage: "", deviceToken: "", deviceType: .iOS, deviceId: "")
                    NavigationLink(destination: ChatView(chatMember: self.chatmember)){
                        SearchUser()
                    }
                }
            }
            .padding(.leading, 10)
        })
            .frame(width: 300, height: 400)

        Spacer()
    }
    .navigationBarTitle("Profile",displayMode: .inline)
    .onAppear {
        self.userList()
    }
}

@State var userDataList = [UserModel]()
func userList() {
    databaseReference.child(DatabaseNode.Users.root.rawValue).observe(.value) { (snapShot) in
        if snapShot.exists(){

            if let friendsDictionary = snapShot.value{

                for each in friendsDictionary as! [String : AnyObject]{
                    print(each)
                    if let user = each.value as? [String : Any]{
                        let data = UserModel(userId: JSON(user["userId"] ?? "").stringValue, name: JSON(user["name"] ?? "").stringValue)
                        print(data)
                        self.userDataList.append(data)
                    }
                }
            }
        }
    }
}
</code>```

}

below are the error message i'm getting:

```<code>'Int' is not convertible to 'CGFloat?'
</code>```

But this error message is not look correct for me. this error i'm getting because i tried to modify chatmember inside of foreach.

Thanks

答:
You can't modify the chatmember in your body function, it should be done in an action clouser or outside of the body function scope.

for populate your chatmember you can try this:

add .onAppear to your destination and set your chatmember

NavigationLink(destination: ChatView(chatMember: self.chatmember).onAppear {
                     chatmember = ChatMember(hashValue: 0, email: "", fullName: "", online: "", userId: user.userId, userImage: "", deviceToken: "", deviceType: .iOS, deviceId: "")
                    }){
                        SearchUser()

don't forget to set your `chatmember` to @State
```

Body:
i'm trying to using a variable and modify inside the foreach of swiftui.

below are the code i'm using. please let me know how can i modify the value inside the body of the view.

struct SearchView : View {
var chatmember = ChatMember(with: JSON())

var body: some View{
    VStack(spacing: 10){
        VStack{
            prefView()
                .padding(.bottom, 30)
            Text("Tap to start making friend")
        }
        ScrollView(.horizontal, content: {
            HStack(spacing: 10) {
                ForEach(userDataList) { user in
                     chatmember = ChatMember(hashValue: 0, email: "", fullName: "", online: "", userId: user.userId, userImage: "", deviceToken: "", deviceType: .iOS, deviceId: "")
                    NavigationLink(destination: ChatView(chatMember: self.chatmember)){
                        SearchUser()
                    }
                }
            }
            .padding(.leading, 10)
        })
            .frame(width: 300, height: 400)

        Spacer()
    }
    .navigationBarTitle("Profile",displayMode: .inline)
    .onAppear {
        self.userList()
    }
}

@State var userDataList = [UserModel]()
func userList() {
    databaseReference.child(DatabaseNode.Users.root.rawValue).observe(.value) { (snapShot) in
        if snapShot.exists(){

            if let friendsDictionary = snapShot.value{

                for each in friendsDictionary as! [String : AnyObject]{
                    print(each)
                    if let user = each.value as? [String : Any]{
                        let data = UserModel(userId: JSON(user["userId"] ?? "").stringValue, name: JSON(user["name"] ?? "").stringValue)
                        print(data)
                        self.userDataList.append(data)
                    }
                }
            }
        }
    }
}

}

below are the error message i'm getting:

'Int' is not convertible to 'CGFloat?'

But this error message is not look correct for me. this error i'm getting because i tried to modify chatmember inside of foreach.

Thanks


问:
Fabricjs - selection only via border
I'm using Fabric.js to draw some rectangles on a canvas. The default behavior is that clicking inside a rectangle selects it. How can I change the behavior such that it is only selected when clicking on the border of the rectangle?

Clicking inside the rectangle but not on the border should do nothing.

You can see this behavior by drawing a rectangle on a TradingView.com chart

It there an option for this in fabric, and if not how could I go around implementing it?

答:
here is my approach, when rect is clicked I am calculating where it is clicked and
if it is not clicked on border I have to set canvas.discardActiveObject , see comments on code

var canvas = new fabric.Canvas('c', {
  selection: false
});
var rect = new fabric.Rect({
  left: 50,
  top: 50,
  width: 100,
  height: 100,
  strokeWidth: 10,
  stroke: 'red',
  selectable: false,
  evented: true,
  hasBorders: true,
  lockMovementY: true,
  lockMovementX: true

})
canvas.on("mouse:move", function(e) {
  if (!e.target || e.target.type != 'rect') return;
  // when selected event is fired get the click position.
  var pointer = canvas.getPointer(e.e);
  // calculate the click distance from object to be exact
  var distanceX = pointer.x - rect.left;
  var distanceY = pointer.y - rect.top;

  // check if click distanceX/Y are less than 10 (strokeWidth) or greater than 90 ( rect width = 100)

  if ((distanceX <= rect.strokeWidth || distanceX >= (rect.width - rect.strokeWidth)) || (distanceY <= rect.strokeWidth || distanceY >= (rect.height - rect.strokeWidth))) {
    rect.set({
      hoverCursor: 'move',
      selectable: true,
      lockMovementY: false,
      lockMovementX: false
    });
    document.getElementById('result').innerHTML = 'on border';
  } else {
    canvas.discardActiveObject();
    document.getElementById('result').innerHTML = 'not  on border';
    rect.set({
      hoverCursor: 'default',
      selectable: false,
      lockMovementY: true,
      lockMovementX: true
    });
  }

});

canvas.add(rect);
canvas.renderAll();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<div id="result" style="width: 100%; "></div>
<canvas id="c" width="600" height="200"></canvas>
```
```</code>```

ps: you can also set the rect property to selectable: false and call canvas.setActiveObject(this); to make it selection inside if statement.

Title: Fabricjs - selection only via border

Body:
here is my approach, when rect is clicked I am calculating where it is clicked and
if it is not clicked on border I have to set canvas.discardActiveObject , see comments on code

var canvas = new fabric.Canvas('c', {
  selection: false
});
var rect = new fabric.Rect({
  left: 50,
  top: 50,
  width: 100,
  height: 100,
  strokeWidth: 10,
  stroke: 'red',
  selectable: false,
  evented: true,
  hasBorders: true,
  lockMovementY: true,
  lockMovementX: true

})
canvas.on("mouse:move", function(e) {
  if (!e.target || e.target.type != 'rect') return;
  // when selected event is fired get the click position.
  var pointer = canvas.getPointer(e.e);
  // calculate the click distance from object to be exact
  var distanceX = pointer.x - rect.left;
  var distanceY = pointer.y - rect.top;

  // check if click distanceX/Y are less than 10 (strokeWidth) or greater than 90 ( rect width = 100)

  if ((distanceX <= rect.strokeWidth || distanceX >= (rect.width - rect.strokeWidth)) || (distanceY <= rect.strokeWidth || distanceY >= (rect.height - rect.strokeWidth))) {
    rect.set({
      hoverCursor: 'move',
      selectable: true,
      lockMovementY: false,
      lockMovementX: false
    });
    document.getElementById('result').innerHTML = 'on border';
  } else {
    canvas.discardActiveObject();
    document.getElementById('result').innerHTML = 'not  on border';
    rect.set({
      hoverCursor: 'default',
      selectable: false,
      lockMovementY: true,
      lockMovementX: true
    });
  }

});

canvas.add(rect);
canvas.renderAll();

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"></script>
<div id="result" style="width: 100%; "></div>
<canvas id="c" width="600" height="200"></canvas>
<pre>
</pre>

ps: you can also set the rect property to selectable: false and call canvas.setActiveObject(this); to make it selection inside if statement.


问:
AWS ECS container logs design pattern
I have a classic scala app, it produces three different logs in the location

```<code>/var/log/myapp/log1/mylog.log
/var/log/myapp/log2/another.log
/var/log/myapp/log3/anotherone.log
</code>```

I containerized the app and working fine, I can get those logs by docker volume mount.

Now the app/container will be deployed in AWS ECS with auto scaling group. in this case multiple container may run on one single ecs host.

I would like to use cloud watch to monitor my application logs.

One solution could be put aws log agent inside my application container.

Is there any better way to get those application logs from container to cloudwatch log.

help is very much appreciated.

答:
You don't need log agent if you can change the code.

You can directly publish Custom Metric Data into ColudWatch like this page said: https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/examples-cloudwatch-publish-custom-metrics.html

Title: AWS ECS container logs design pattern

Body:
I have a classic scala app, it produces three different logs in the location

/var/log/myapp/log1/mylog.log
/var/log/myapp/log2/another.log
/var/log/myapp/log3/anotherone.log

I containerized the app and working fine, I can get those logs by docker volume mount.

Now the app/container will be deployed in AWS ECS with auto scaling group. in this case multiple container may run on one single ecs host.

I would like to use cloud watch to monitor my application logs.

One solution could be put aws log agent inside my application container.

Is there any better way to get those application logs from container to cloudwatch log.

help is very much appreciated.


问:
Android Studio No Input?
I am practicing to build a calc app in Android Studio using Java. here's how it looks like
Yes it is very simple

Now instead of using buttons to enter numbers, I used two EditText views for entering numbers. now I wrote a method to add two numbers like this:

```<code>btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int result;

            first=Integer.valueOf(input1.getText().toString());

            second=Integer.valueOf(input2.getText().toString());

            result = first+second;

            value.setText(""+result);

            Toast.makeText(MainActivity.this, "Please fill the both space with numbers", Toast.LENGTH_LONG).show();
          }
</code>```

the code for adding numbers is fine but if I do not have an input in EditText views, the app crashes. I want to put the codes in an if else clause. if there are inputs in both spaces app does the operation but if not it makes a toast and askes for numbers from the user. but I have no idea how to code the if else conditions. anybody can help me?

答:
You can test if the input1 or input2 is empty as your if else testing criteria. The following code assume you have correctly found and initialized input1 and input2 editText views.

```<code>    @Override
    public void onClick(View v) {

        int result;
        Editable firstInputText = input1.getText();
        Editable secondInputText = input2.getText();

        if(firstInputText != null && firstInputText.length>0 &&
           secondInputText != null && secondInputText.length>0){
             first=Integer.valueOf(firstInputText.toString());
             second=Integer.valueOf(secondInputText.toString());
             result = first+second;
             value.setText(""+result);
        } else{
             Toast.makeText(MainActivity.this, "Please fill the both space with numbers", Toast.LENGTH_LONG).show();
        }
    }
</code>```

Also for your calculator, you want to ensure the inputs are numeric strings. For your layout xml, you can specify it as follows.

```<code>    <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/my_test_editText"
    android:inputType="number"
    />
</code>```

Title: Android Studio No Input?

Body:
I am practicing to build a calc app in Android Studio using Java. here's how it looks like
Yes it is very simple

Now instead of using buttons to enter numbers, I used two EditText views for entering numbers. now I wrote a method to add two numbers like this:

btn_add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            int result;

            first=Integer.valueOf(input1.getText().toString());

            second=Integer.valueOf(input2.getText().toString());

            result = first+second;

            value.setText(""+result);

            Toast.makeText(MainActivity.this, "Please fill the both space with numbers", Toast.LENGTH_LONG).show();
          }

the code for adding numbers is fine but if I do not have an input in EditText views, the app crashes. I want to put the codes in an if else clause. if there are inputs in both spaces app does the operation but if not it makes a toast and askes for numbers from the user. but I have no idea how to code the if else conditions. anybody can help me?

Body:
You can test if the input1 or input2 is empty as your if else testing criteria. The following code assume you have correctly found and initialized input1 and input2 editText views.

    @Override
    public void onClick(View v) {

        int result;
        Editable firstInputText = input1.getText();
        Editable secondInputText = input2.getText();

        if(firstInputText != null && firstInputText.length>0 &&
           secondInputText != null && secondInputText.length>0){
             first=Integer.valueOf(firstInputText.toString());
             second=Integer.valueOf(secondInputText.toString());
             result = first+second;
             value.setText(""+result);
        } else{
             Toast.makeText(MainActivity.this, "Please fill the both space with numbers", Toast.LENGTH_LONG).show();
        }
    }

Also for your calculator, you want to ensure the inputs are numeric strings. For your layout xml, you can specify it as follows.

    <EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/my_test_editText"
    android:inputType="number"
    />


问:
403 error after adding product to cart
I am creating e-commerce site using woocommerce plugin. Everything works well until adding a product to cart on my site. Then, if I go to the cart page - everything breaks down. Only thing that shows up is

```<code>Error occurred: 403 - forbidden
Apache Server at: s1062803-15589.home-whs.pl
</code>```

Now I have no access to the site at all, even to wp-admin site. What can I do?

答: sometimes firewall and something like mod_security make this problem. if you are host administrator try to disable them.</p>

Title: 403 error after adding product to cart

Body:
I am creating e-commerce site using woocommerce plugin. Everything works well until adding a product to cart on my site. Then, if I go to the cart page - everything breaks down. Only thing that shows up is

Error occurred: 403 - forbidden
Apache Server at: s1062803-15589.home-whs.pl

Now I have no access to the site at all, even to wp-admin site. What can I do?


问:
Why can't I read this registry key in C#
Problem

I cannot read from the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen.

Using Code:

```<code>Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen", "", null);
</code>```

Diagnostics of problem

I get a System.NullReferenceException when executing code like the key does not exits, but I know it exist because I can view it in regedit.

I have tried to take ownership of the key.

I have tried viewing subkeys of parent key (CurrentVersion). The parent scan never even showed the key SystemProtectedUserData key same with the key right under TabletPC.

I am guessing this is some permission problem but I dont know how to fix it.

Any help is appreciated.

答:
Your Registry.GetValue method returns null, because it can't find a specified key or value and the default value (the third argument) is set to null. According to documentation, this method can't throw a NullReferenceException, it seems the consuming code causes it.

So, you can try to specify the value name (at my end I see only OSVersion value) or different default value.

If the issue still exist, the problem can be in redirection to WOW6432Node registry node in x64 edition of Windows. You can avoid it by the following code, using OpenBaseKey method and specifying a RegistryView value

var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var key = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-...\AnyoneRead\LockScreen");
var value = key.GetValue("OSVersion"); //for example
```

Body:
Problem

I cannot read from the key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen.

Using Code:

Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\S-1-5-21-436374069-1965331169-839522115-50811\AnyoneRead\LockScreen", "", null);

Diagnostics of problem

I get a System.NullReferenceException when executing code like the key does not exits, but I know it exist because I can view it in regedit.

I have tried to take ownership of the key.

I have tried viewing subkeys of parent key (CurrentVersion). The parent scan never even showed the key SystemProtectedUserData key same with the key right under TabletPC.

I am guessing this is some permission problem but I dont know how to fix it.

Any help is appreciated.


问:
TypeError: date[("get" + method)] is not a function in React-big-calendar
I am trying to change the view from month to week but in meantime it give me an error . I am new to react and react-big-calendar could someone please help me how to solve this problem . When I change calendar view to month it working fine but when I changed it to week or day so it give me an error. please help me Thanks

Code

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import MyCalendar from 'react-big-calendar';
import CustomToolbar from './toolbar';
import Popup from 'react-popup';
import Input from './input';
import moment from 'moment';
import { fetchEvents, createEvent, updateEvent, deleteEvent } from '../actions';

// Setup the localizer by providing the moment (or globalize) Object to the correct localizer.
const localizer = MyCalendar.momentLocalizer(moment); // or globalizeLocalizer

class Calendar extends Component {

    componentDidMount() {
        this.props.fetchEvents();
    }

    //RENDER SINGLE EVENT POPUP CONTENT
    renderEventContent(slotInfo) {
        const date = moment(slotInfo.start).format('MMMM D, YYYY');
        return (
            <div>
                <p>Date: <strong>{date}</strong></p>
                <p>Subject: {slotInfo.taskChage}</p>
                <p>Time : {slotInfo.time}</p>
                <p>Date : { slotInfo.date}</p>
                <p>Notes : {slotInfo.notes}</p>
                <p>User Id : {slotInfo.userId}</p>
            </div>
        );
    }

    //ON SELECT EVENT HANDLER FUNCTION
    onSelectEventHandler = (slotInfo) => {
        Popup.create({
            title: slotInfo.title,
            content: this.renderEventContent(slotInfo),
            buttons: {
                right: [{
                    text: 'Edit',
                    className: 'info',
                    action: function () {
                        Popup.close(); //CLOSE PREVIOUS POPUP
                        this.openPopupForm(slotInfo); //OPEN NEW EDIT POPUP
                    }.bind(this)
                }, {
                    text: 'Delete',
                    className: 'danger',
                    action: function () {
                        //CALL EVENT DELETE ACTION
                        this.props.deleteEvent(slotInfo.id);
                        Popup.close();
                    }.bind(this)
                }]
            }
        });
    }

    //HANDLE FUNCITON ON SELECT EVENT SLOT
    onSelectEventSlotHandler = (slotInfo) => {
        this.openPopupForm(slotInfo); //OPEN POPUP FOR CREATE/EDIT EVENT
    }

    //POPUP-FORM FUNCTION FOR CREATE AND EDIT EVENT
    openPopupForm = (slotInfo) => {
        let newEvent = false;
        let popupTitle = "Update Event";
        if(!slotInfo.hasOwnProperty('id')) {
            slotInfo.id = moment().format('x');  //Generate id with Unix Millisecond Timestamp
            slotInfo.title = null;
            slotInfo.taskChange = null;
            slotInfo.message=null;
            popupTitle = "Create Event";
            newEvent = true;
        }

        let titleChange = function (value) {
            slotInfo.title = value;
        };
        let taskChange = function (value) {
            slotInfo.taskChage = value;
        };

        let timeChange = function (value) {
            slotInfo.time = value;
        };

        let dateChnage = function ( value){
            slotInfo.date=value;
        };

        let notesChange = function ( value){
            slotInfo.notes=value;
        };

        let userId = function ( value){
            slotInfo.userId=value;
        };

        Popup.create({
            title: popupTitle,
            content: <div>
                        <Input onChange={titleChange} placeholder="Subject" />
                        <Input onChange={taskChange} placeholder="Task Type"  />
                        <Input onChange={timeChange} placeholder="Time"/>
                        <Input onChange={dateChnage} placeholder="Date"/>
                        <Input onChange={notesChange} placeholder="Notes"/>
                        <Input onChange={userId} placeholder="User Id"/>
                    </div>,
            buttons: {
                left: ['cancel'],
                right: [{
                    text: 'Save',
                    className: 'success',
                    action: function () {
                        //CHECK THE ID PROPERTY FOR CREATE/UPDATE
                        if(newEvent) {
                            this.props.createEvent(slotInfo); //EVENT CREATE ACTION
                        } else {
                            this.props.updateEvent(slotInfo); //EVENT UPDATE ACTION
                        }
                        Popup.close();
                    }.bind(this)
                }]
            }
        });
    }

    //EVENT STYLE GETTER FOR SLYLING AN EVENT ITEM
    eventStyleGetter(event, start, end, isSelected) {
        let current_time = moment().format('YYYY MM DD');
        let event_time = moment(event.start).format('YYYY MM DD');
        let background = (current_time>event_time) ? '#DE6987' : '#8CBD4C';
        return {
            style: {
                backgroundColor: background
            }
        };
    }

    render() {
        return (
            <div className="calendar-container">
                <MyCalendar
                    popup
                    selectable
                    localizer={localizer}
                    defaultView={MyCalendar.Views.WEEK}
                    components={{toolbar: CustomToolbar}}
                    views={['week']}
                    style={{height: 600}}
                    events={this.props.events}
                    eventPropGetter={(this.eventStyleGetter)}
                    onSelectEvent={(slotInfo) => this.onSelectEventHandler(slotInfo)}
                    onSelectSlot={(slotInfo) => this.onSelectEventSlotHandler(slotInfo)}
                />
                {console.log(this.props.event)}
                <Popup />
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        events: state.events
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        fetchEvents,
        createEvent,
        updateEvent,
        deleteEvent
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Calendar);
</code>```

答:
For anyone finding this, a few things.

Your localizer handles manipulation of dates under the hood. All dates that you pass in (from your getNow and date props, all the way to your individual event.start and event.end dates) should be true JS Date objects.

Your various method props, for working with events or setting styling or whatever, will receive true JS Date objects, not localizer objects or UTC strings or whatever.

RBC will only work with true JS Date objects. If you pass it moment instances or date strings or something else, it might display but it will operate funky, as RBC will handle all conversions under the hood, and it's use of the date-arithmatic library, internally, works with true JS Dates and not your localizer objects.

Body:
I am trying to change the view from month to week but in meantime it give me an error . I am new to react and react-big-calendar could someone please help me how to solve this problem . When I change calendar view to month it working fine but when I changed it to week or day so it give me an error. please help me Thanks

Code

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import MyCalendar from 'react-big-calendar';
import CustomToolbar from './toolbar';
import Popup from 'react-popup';
import Input from './input';
import moment from 'moment';
import { fetchEvents, createEvent, updateEvent, deleteEvent } from '../actions';

// Setup the localizer by providing the moment (or globalize) Object to the correct localizer.
const localizer = MyCalendar.momentLocalizer(moment); // or globalizeLocalizer

class Calendar extends Component {

    componentDidMount() {
        this.props.fetchEvents();
    }

    //RENDER SINGLE EVENT POPUP CONTENT
    renderEventContent(slotInfo) {
        const date = moment(slotInfo.start).format('MMMM D, YYYY');
        return (

Date: {date}

Subject: {slotInfo.taskChage}

Time : {slotInfo.time}

Date : { slotInfo.date}

Notes : {slotInfo.notes}

User Id : {slotInfo.userId}

        );
    }

    //ON SELECT EVENT HANDLER FUNCTION
    onSelectEventHandler = (slotInfo) => {
        Popup.create({
            title: slotInfo.title,
            content: this.renderEventContent(slotInfo),
            buttons: {
                right: [{
                    text: 'Edit',
                    className: 'info',
                    action: function () {
                        Popup.close(); //CLOSE PREVIOUS POPUP
                        this.openPopupForm(slotInfo); //OPEN NEW EDIT POPUP
                    }.bind(this)
                }, {
                    text: 'Delete',
                    className: 'danger',
                    action: function () {
                        //CALL EVENT DELETE ACTION
                        this.props.deleteEvent(slotInfo.id);
                        Popup.close();
                    }.bind(this)
                }]
            }
        });
    }

    //HANDLE FUNCITON ON SELECT EVENT SLOT
    onSelectEventSlotHandler = (slotInfo) => {
        this.openPopupForm(slotInfo); //OPEN POPUP FOR CREATE/EDIT EVENT
    }

    //POPUP-FORM FUNCTION FOR CREATE AND EDIT EVENT
    openPopupForm = (slotInfo) => {
        let newEvent = false;
        let popupTitle = "Update Event";
        if(!slotInfo.hasOwnProperty('id')) {
            slotInfo.id = moment().format('x');  //Generate id with Unix Millisecond Timestamp
            slotInfo.title = null;
            slotInfo.taskChange = null;
            slotInfo.message=null;
            popupTitle = "Create Event";
            newEvent = true;
        }

        let titleChange = function (value) {
            slotInfo.title = value;
        };
        let taskChange = function (value) {
            slotInfo.taskChage = value;
        };

        let timeChange = function (value) {
            slotInfo.time = value;
        };

        let dateChnage = function ( value){
            slotInfo.date=value;
        };

        let notesChange = function ( value){
            slotInfo.notes=value;
        };

        let userId = function ( value){
            slotInfo.userId=value;
        };

        Popup.create({
            title: popupTitle,
            content:

                        <Input onChange={titleChange} placeholder="Subject" />
                        <Input onChange={taskChange} placeholder="Task Type"  />
                        <Input onChange={timeChange} placeholder="Time"/>
                        <Input onChange={dateChnage} placeholder="Date"/>
                        <Input onChange={notesChange} placeholder="Notes"/>
                        <Input onChange={userId} placeholder="User Id"/>

,
            buttons: {
                left: ['cancel'],
                right: [{
                    text: 'Save',
                    className: 'success',
                    action: function () {
                        //CHECK THE ID PROPERTY FOR CREATE/UPDATE
                        if(newEvent) {
                            this.props.createEvent(slotInfo); //EVENT CREATE ACTION
                        } else {
                            this.props.updateEvent(slotInfo); //EVENT UPDATE ACTION
                        }
                        Popup.close();
                    }.bind(this)
                }]
            }
        });
    }

    //EVENT STYLE GETTER FOR SLYLING AN EVENT ITEM
    eventStyleGetter(event, start, end, isSelected) {
        let current_time = moment().format('YYYY MM DD');
        let event_time = moment(event.start).format('YYYY MM DD');
        let background = (current_time>event_time) ? '#DE6987' : '#8CBD4C';
        return {
            style: {
                backgroundColor: background
            }
        };
    }

    render() {
        return (

                <MyCalendar
                    popup
                    selectable
                    localizer={localizer}
                    defaultView={MyCalendar.Views.WEEK}
                    components={{toolbar: CustomToolbar}}
                    views={['week']}
                    style={{height: 600}}
                    events={this.props.events}
                    eventPropGetter={(this.eventStyleGetter)}
                    onSelectEvent={(slotInfo) => this.onSelectEventHandler(slotInfo)}
                    onSelectSlot={(slotInfo) => this.onSelectEventSlotHandler(slotInfo)}
                />
                {console.log(this.props.event)}
                <Popup />

        );
    }
}

function mapStateToProps(state) {
    return {
        events: state.events
    };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        fetchEvents,
        createEvent,
        updateEvent,
        deleteEvent
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Calendar);


问:
Immutable classes and memory in C++
So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes.

When I think about them as a concept, I of course compare them to Strings in Java. But now that I'm in C++, a reassignment operation can potentially create a memory leak (or at least, I think it can). So now if I do this:

```<code>  MyImmutableClass a ("blah");
  a = a.modifyInSomeWay();
</code>```

where modifyInSomeWay returns a new instance of MyImmutableClass, I haven't called the deconstructor. Is there something I'm missing here that would prevent the first assignment of 'a' from sticking around in memory?

答:
In the case you've described, the assignment operator of MyImmutableClass is called to copy the right hand side of the assignment to the left hand side (overwriting whatever was on the left hand side). If your class really is immutable, it won't even have an accessible assignment operator, and you will get a compile error.

If your object is mutable, and you do have a (correct) assignment operator, then there will be no memory leak because destructors for data on the left hand side will run as necessary to release memory. Writing a correct assignment operator can be tricky for some classes, though.

This concept of assigning directly to a (user-defined) object does not exist in Java, since over there everything is a reference.

Title: Immutable classes and memory in C++

Body:
So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes.

When I think about them as a concept, I of course compare them to Strings in Java. But now that I'm in C++, a reassignment operation can potentially create a memory leak (or at least, I think it can). So now if I do this:

  MyImmutableClass a ("blah");
  a = a.modifyInSomeWay();

where modifyInSomeWay returns a new instance of MyImmutableClass, I haven't called the deconstructor. Is there something I'm missing here that would prevent the first assignment of 'a' from sticking around in memory?


问:
How View static constants are loaded in JVM unit test
I have a method that checks visibility is View.GONE or not (just for testing purpose)

```<code>private fun isGoneVisibility(visibility: Int): Boolean {
    return visibility == View.GONE
}
</code>```

Then I call it in my unit test on local JVM. I thought in JVM test we don't have any Android dependency (because the JVM environment doesn't have android.jar). But when the test executing, it can evaluate the exact value of View.GONE (which is 8).

I don't have any idea about how it works.

答: After build, static final primitives variables will be cover to value

Body:
I have a method that checks visibility is View.GONE or not (just for testing purpose)

private fun isGoneVisibility(visibility: Int): Boolean {
    return visibility == View.GONE
}

Then I call it in my unit test on local JVM. I thought in JVM test we don't have any Android dependency (because the JVM environment doesn't have android.jar). But when the test executing, it can evaluate the exact value of View.GONE (which is 8).

I don't have any idea about how it works.


问:
Clear mongodb using spring-mongodb
As so many people before me on stackoverflow I want to do junit-tests for my mongodb application. For this I let an instance run, so my tests can connect. But I want to ensure that the database is in an empty state when starting to test.

Since I'm using spring-mongodb, spring-test and all the funny spring-things I hoped to find a configuration that does this for me, until now successless.

Can anybody give me a hint how to implement this in a clean way. My idea is a InitializingBean that does this for me. But I'm not really happy with ths solution. Any suggestions?

答:
this is the non-deprecated answer:
mongoTemplate.getDb().drop();

Title: Clear mongodb using spring-mongodb


问:
How to "reuse" instance definitions from another typeclass while introduding minor differences?
I want to output my application's logs in JSON, but there are some ubiquitous data-types for which ToJSON instances are not defined - most notably SomeException and the entire Exception hierarchy of types.

I have two choices:

Define instances of ToJSON for such data-types in my application

Write my own type-class, say ToJsonLogs, and make it reuse ToJSON instances as much as possible.

The first is the path of "least resistance" but it has other implications. Since type-class instances are global in nature, I might end-up defining ToJSON instances that break something. Also, for the same data-structure, I might want the JSON in APIs to be different from the JSON in logs (for example, scrubbing keys, auth-tokens, and other sensitive data OR truncating very long text fields).

This questions is about exploring the second option. How do I go about doing something like the following:

```<code>class ToJsonLogs a where
  toJsonLogs :: a -> Aeson.Value

  default toJsonLogs :: (ToJSON a) => a -> Aeson.Value
  toJsonLogs = toJSON

instance ToJsonLogs SomeException where
  toJsonLogs = toJSON . displayException
</code>```

I tried the above idea, but it failed at the very first step itself. Here's an example data-structure:

```<code>data SyncResult = SyncResult
  { resAborted :: !Bool
  , resSuccessful :: !Int
  , resFailed :: ![(Int, SomeException)]
  } deriving (Show)
</code>```

I can't derive ToJsonLogs without first deriving ToJSON for the entire data-structure. Derivation of ToJSON fails because of SomeException. Hence the title of this question.

I even tried fooling around with Generics, but as usual, got stuck again.

答:
You are very close to a possible extension-free solution. The thing you should consider is to create a wrapper for the original ToJson class members:

class ToJsonLogs a where
  toJsonLogs :: a -> Aeson.Value

newtype WrapToJson a = WrapToJson a  -- actually an Identity

instance ToJson a => ToJsonLogs (WrapToJson a) where
  toJsonLogs (WrapToJson x) = toJson x

-- example
logInt :: Int -> Aeson.value
logInt x = toJsonLogs (WrapJson x)
```

<p>If you want to restrict the wrapper only for <code>ToJson</code> instances, you will need to enable few extensions:</p>

```{-# LANGUAGE GADTSyntax, ExistentialQuantifiaction #-}
data WrapToJson a where WrapToJson :: ToJson a => a -> WrapToJson a
```

<p>If you don't enjoy this wrapper, you may hide it under another definition of <code>toJsonLogs</code>:</p>

```toJsonLogs' :: ToJson a => a -> Aeson.value
toJsonLogs' = toJsonLogs . WrapToJson
```

Body:
I want to output my application's logs in JSON, but there are some ubiquitous data-types for which ToJSON instances are not defined - most notably SomeException and the entire Exception hierarchy of types.

I have two choices:

Define instances of ToJSON for such data-types in my application

Write my own type-class, say ToJsonLogs, and make it reuse ToJSON instances as much as possible.

The first is the path of "least resistance" but it has other implications. Since type-class instances are global in nature, I might end-up defining ToJSON instances that break something. Also, for the same data-structure, I might want the JSON in APIs to be different from the JSON in logs (for example, scrubbing keys, auth-tokens, and other sensitive data OR truncating very long text fields).

This questions is about exploring the second option. How do I go about doing something like the following:

class ToJsonLogs a where
  toJsonLogs :: a -> Aeson.Value

  default toJsonLogs :: (ToJSON a) => a -> Aeson.Value
  toJsonLogs = toJSON

instance ToJsonLogs SomeException where
  toJsonLogs = toJSON . displayException

I tried the above idea, but it failed at the very first step itself. Here's an example data-structure:

data SyncResult = SyncResult
  { resAborted :: !Bool
  , resSuccessful :: !Int
  , resFailed :: ![(Int, SomeException)]
  } deriving (Show)

I can't derive ToJsonLogs without first deriving ToJSON for the entire data-structure. Derivation of ToJSON fails because of SomeException. Hence the title of this question.

I even tried fooling around with Generics, but as usual, got stuck again.

Body:
You are very close to a possible extension-free solution. The thing you should consider is to create a wrapper for the original ToJson class members:

class ToJsonLogs a where
  toJsonLogs :: a -> Aeson.Value

newtype WrapToJson a = WrapToJson a  -- actually an Identity

instance ToJson a => ToJsonLogs (WrapToJson a) where
  toJsonLogs (WrapToJson x) = toJson x

-- example
logInt :: Int -> Aeson.value
logInt x = toJsonLogs (WrapJson x)

If you want to restrict the wrapper only for ToJson instances, you will need to enable few extensions:

{-# LANGUAGE GADTSyntax, ExistentialQuantifiaction #-}
data WrapToJson a where WrapToJson :: ToJson a => a -> WrapToJson a

If you don't enjoy this wrapper, you may hide it under another definition of toJsonLogs:

toJsonLogs' :: ToJson a => a -> Aeson.value
toJsonLogs' = toJsonLogs . WrapToJson


问:
How to build a layer that merges two images, in an order determined by a third parameter
I want a layer that takes three tensors as input: Two (n,m,k) tensors and one (1) tensor, i.e. one single number. The output should be a (n,m,2k) tensor, achieved by simply having the first k channels be one image and the remaining being the other. Now, the catch is that the order in which we merge them -- do we put image one on top of image two or vice versa -- should be determined by whether the third input is greater than 0 or not.

By my thinking, this is an entirely static layer without any trainable parameters, so I tried doing the ordering choice with a Lambda layer, as follows:

```<code>def image_scrambler(inp): #inp = [im1, im2, aux_input]
    im1, im2, aux_input = inp[0],inp[1],inp[2]
    assert aux_input==1 or aux_input==0
    if aux_input==0:
        return [im1, im2]
    else:
        return [im2,im1]
paired_images = Lambda(image_scrambler)([image_input, decoder, aux_input])
</code>```

This does not work, because it protests that the layer is dynamic and needs to be built with dynamic=True. When I try that, I get a RecursionError as follows:

```<code>---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-15-a40adb50e97d> in <module>
      7         return [im2,im1]
      8 aux_input = Input(shape=(1))
----> 9 paired_images = Lambda(image_scrambler,dynamic=True)([image_input, decoder, aux_input])

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    791             # TODO(fchollet): consider py_func as an alternative, which
    792             # would enable us to run the underlying graph if needed.
--> 793             outputs = self._symbolic_call(inputs)
    794
    795           if outputs is None:

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in _symbolic_call(self, inputs)
   2126   def _symbolic_call(self, inputs):
   2127     input_shapes = nest.map_structure(lambda x: x.shape, inputs)
-> 2128     output_shapes = self.compute_output_shape(input_shapes)
   2129
   2130     def _make_placeholder_like(shape):

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\utils\tf_utils.py in wrapper(instance, input_shape)
    304     if input_shape is not None:
    305       input_shape = convert_shapes(input_shape, to_tuples=True)
--> 306     output_shape = fn(instance, input_shape)
    307     # Return shapes from `fn` as TensorShapes.
    308     if output_shape is not None:

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\layers\core.py in compute_output_shape(self, input_shape)
    808       with context.eager_mode():
    809         try:
--> 810           return super(Lambda, self).compute_output_shape(input_shape)
    811         except NotImplementedError:
    812           raise NotImplementedError(

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in compute_output_shape(self, input_shape)
    552           try:
    553             if self._expects_training_arg:
--> 554               outputs = self(inputs, training=False)
    555             else:
    556               outputs = self(inputs)

... last 5 frames repeated, from the frame below ...

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    791             # TODO(fchollet): consider py_func as an alternative, which
    792             # would enable us to run the underlying graph if needed.
--> 793             outputs = self._symbolic_call(inputs)
    794
    795           if outputs is None:

RecursionError: maximum recursion depth exceeded while calling a Python object
</code>```

So that doesn't actually tell me anything about why it didn't work, it just crashed.

I'd prefer not to have to fiddle around with building a layer class inhering from Layer if there's any way to get the less complicated method to work.

答:
Always work with "tensor functions" not with "Python functions":

```<code>import keras.backend as K

def image_scrambler(inp): #inp = [im1, im2, aux_input]
    im1, im2, aux_input = inp[0],inp[1],inp[2]

    is_greater = K.greater(aux_input, 0.5)
    return K.switch(is_greater,                     #this is a keras "if"
                    K.concatenate([img2, img1]),    #result if true
                    K.concatenate([img1, img2]))    #result if false

paired_images = Lambda(image_scrambler)([image_input, decoder, aux_input])
</code>```

I don't think the assert would be a good idea, you should do this when checking your data, not in the model.

Although you say it's not trainable, you might be expecting it to be trainable somehow? What decides what the value of aux_input will be? If you expect it to be learned elsewhere I'm in doubt it will work. Maybe it should be a continuous value given by a sigmoid somewhere. Then it "might" have a chance to work, although the if part sort of disrupts (but doesn't break) backpropagation.

Body:
I want a layer that takes three tensors as input: Two (n,m,k) tensors and one (1) tensor, i.e. one single number. The output should be a (n,m,2k) tensor, achieved by simply having the first k channels be one image and the remaining being the other. Now, the catch is that the order in which we merge them -- do we put image one on top of image two or vice versa -- should be determined by whether the third input is greater than 0 or not.

By my thinking, this is an entirely static layer without any trainable parameters, so I tried doing the ordering choice with a Lambda layer, as follows:

def image_scrambler(inp): #inp = [im1, im2, aux_input]
    im1, im2, aux_input = inp[0],inp[1],inp[2]
    assert aux_input==1 or aux_input==0
    if aux_input==0:
        return [im1, im2]
    else:
        return [im2,im1]
paired_images = Lambda(image_scrambler)([image_input, decoder, aux_input])

This does not work, because it protests that the layer is dynamic and needs to be built with dynamic=True. When I try that, I get a RecursionError as follows:

---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-15-a40adb50e97d> in <module>
      7         return [im2,im1]
      8 aux_input = Input(shape=(1))
----> 9 paired_images = Lambda(image_scrambler,dynamic=True)([image_input, decoder, aux_input])

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    791             # TODO(fchollet): consider py_func as an alternative, which
    792             # would enable us to run the underlying graph if needed.
--> 793             outputs = self._symbolic_call(inputs)
    794
    795           if outputs is None:

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in _symbolic_call(self, inputs)
   2126   def _symbolic_call(self, inputs):
   2127     input_shapes = nest.map_structure(lambda x: x.shape, inputs)
-> 2128     output_shapes = self.compute_output_shape(input_shapes)
   2129
   2130     def _make_placeholder_like(shape):

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\utils\tf_utils.py in wrapper(instance, input_shape)
    304     if input_shape is not None:
    305       input_shape = convert_shapes(input_shape, to_tuples=True)
--> 306     output_shape = fn(instance, input_shape)
    307     # Return shapes from `fn` as TensorShapes.
    308     if output_shape is not None:

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\layers\core.py in compute_output_shape(self, input_shape)
    808       with context.eager_mode():
    809         try:
--> 810           return super(Lambda, self).compute_output_shape(input_shape)
    811         except NotImplementedError:
    812           raise NotImplementedError(

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in compute_output_shape(self, input_shape)
    552           try:
    553             if self._expects_training_arg:
--> 554               outputs = self(inputs, training=False)
    555             else:
    556               outputs = self(inputs)

... last 5 frames repeated, from the frame below ...

c:\users\vilhelm\appdata\local\programs\python\python36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    791             # TODO(fchollet): consider py_func as an alternative, which
    792             # would enable us to run the underlying graph if needed.
--> 793             outputs = self._symbolic_call(inputs)
    794
    795           if outputs is None:

RecursionError: maximum recursion depth exceeded while calling a Python object

So that doesn't actually tell me anything about why it didn't work, it just crashed.

I'd prefer not to have to fiddle around with building a layer class inhering from Layer if there's any way to get the less complicated method to work.

Body:
Always work with "tensor functions" not with "Python functions":

import keras.backend as K

def image_scrambler(inp): #inp = [im1, im2, aux_input]
    im1, im2, aux_input = inp[0],inp[1],inp[2]

    is_greater = K.greater(aux_input, 0.5)
    return K.switch(is_greater,                     #this is a keras "if"
                    K.concatenate([img2, img1]),    #result if true
                    K.concatenate([img1, img2]))    #result if false

paired_images = Lambda(image_scrambler)([image_input, decoder, aux_input])

I don't think the assert would be a good idea, you should do this when checking your data, not in the model.

Although you say it's not trainable, you might be expecting it to be trainable somehow? What decides what the value of aux_input will be? If you expect it to be learned elsewhere I'm in doubt it will work. Maybe it should be a continuous value given by a sigmoid somewhere. Then it "might" have a chance to work, although the if part sort of disrupts (but doesn't break) backpropagation.


答:
First check if the include tag is being rendered to the page by viewing the page source from the browser. Once you've established the include tag exists check the path to the script file.

This article explains how to resolve the path correctly

Basically use this in your onload event:

```<code>Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Page.ClientScript.RegisterClientScriptInclude("basicjs", ResolveClientUrl("~/basic.js"))
End Sub
</code>```

Title: How do you load .js files with ASP.NET?

Body:
First check if the include tag is being rendered to the page by viewing the page source from the browser. Once you've established the include tag exists check the path to the script file.

This article explains how to resolve the path correctly

Basically use this in your onload event:

Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    Page.ClientScript.RegisterClientScriptInclude("basicjs", ResolveClientUrl("~/basic.js"))
End Sub


问:
How to increase/decrease count on click of same button in Js/ReactJs
I want to increment/decrement counter based on button click.
Scenario:
There is an initial value on the button- say: 5
When a user clicks on the button, it increments to +1 - o/p: 6
however when the user clicks again on the button it, it'll reduce to 5 again.
this case I dont have 2 buttons- inc and dec to increase/decrease the count.

code:

```<code>class Hello extends React.Component {
constructor() {
   super()
   this.state = {
     count: 10,

   }
 }
 getCount( c ) {

    const clicked = this.state.clicked
if(c == 1){
  this.setState({count: this.state.count +1, clicked: true});
} else {
  this.setState({count: this.state.count -1})
}

  }
  render() {
    return  <div>
                    <button onClick={this.getCount.bind(this, 1)}> click me for increase </button>
                    <button onClick={this.getCount.bind(this, 0)}> click me for decrease </button>
                    <div><h1>{this.state.count}</h1></div>

                     </div>;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('root')
);
</code>```

答:
I have tried the below solution.

```<code>class App extends Component{
 constructor(){
   super()
   this.state={
     count:0,
   }
 }

 increment(){
   this.setState(
     {
       count:this.state.count+1
     }
   );
 };

 decrement(){
   this.setState(
     {
    count:this.state.count-1
     }
   );
 };

 reset(){
   this.setState(
     {
       count:0
     }
   )
 }

 render(){
    return(
        <div style={{
          position: 'absolute', left: '50%', top: '50%',
          transform: 'translate(-50%, -50%)'
      }}>
            <h1>Current Count :{this.state.count}</h1>
            <button className="inc"  onClick={(e)=>this.increment(e)}>Increment!</button>
            <button  className="dec" onClick={(e)=>this.decrement(e)}>Decrement!</button>
            <button className="reset" onClick={(e)=>this.reset(e)}>Reset!</button>

        </div>

    );
 }

}

export default App;
</code>```

In addition to the increment and decrement the above code has a reset button to reset the count to 0.

Body:
I want to increment/decrement counter based on button click.
Scenario:
There is an initial value on the button- say: 5
When a user clicks on the button, it increments to +1 - o/p: 6
however when the user clicks again on the button it, it'll reduce to 5 again.
this case I dont have 2 buttons- inc and dec to increase/decrease the count.

code:

class Hello extends React.Component {
constructor() {
   super()
   this.state = {
     count: 10,

   }
 }
 getCount( c ) {

    const clicked = this.state.clicked
if(c == 1){
  this.setState({count: this.state.count +1, clicked: true});
} else {
  this.setState({count: this.state.count -1})
}

  }
  render() {
    return

                    <button onClick={this.getCount.bind(this, 1)}> click me for increase </button>
                    <button onClick={this.getCount.bind(this, 0)}> click me for decrease </button>

{this.state.count}

;
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('root')
);

Body:
I have tried the below solution.

class App extends Component{
 constructor(){
   super()
   this.state={
     count:0,
   }
 }

 increment(){
   this.setState(
     {
       count:this.state.count+1
     }
   );
 };

 decrement(){
   this.setState(
     {
    count:this.state.count-1
     }
   );
 };

 reset(){
   this.setState(
     {
       count:0
     }
   )
 }

 render(){
    return(
        <div style={{
          position: 'absolute', left: '50%', top: '50%',
          transform: 'translate(-50%, -50%)'
      }}>
            <h1>Current Count :{this.state.count}</h1>
            <button className="inc"  onClick={(e)=>this.increment(e)}>Increment!</button>
            <button  className="dec" onClick={(e)=>this.decrement(e)}>Decrement!</button>
            <button className="reset" onClick={(e)=>this.reset(e)}>Reset!</button>

        </div>

    );
 }

}

export default App;

In addition to the increment and decrement the above code has a reset button to reset the count to 0.