问:
Infobox in Bing V8 maps get cropped when pushpin is near map boundary
I am displaying map infobox when I click on a pushpin in Bing V8 maps. The infobox moves out of the map boundary(cropped) when pushpin is near edges of map boundary. Is there any inherent way of solving it or we have to perform the tedious task of repositioning infobox or the map itself in order to show complete infobox.</p>

答:
There are two options:

Move the map when a user clicks on the pushpin and then display the infobox, often users will center the map on the clicked pushpin (ideal for mobile solutions).

When loading the map, add the following map option; allowInfoboxOverflow: true This will allow the infobox to appear outside the map edges and overflow. This is better suited in non-mobile apps.


来源: stackexchange

问:
How to install intellisense for bootstrap 3 in netbeans?
I am using netbeans for developing a website in java. I am using bootstrap 3 CDN but it does not show me any hints (intellisense). May be it is not installed in it so how can I install bootstrap intellisense in netbeans?</p>

答:
AFAIK there are no plugins for the Bootstrap intellisense plugin for Netbeans.

I am using bootstrap 3 CDN but it does not show me any hints (intellisense).

Yes, this will not work and this applies to other CSS frameworks like Foundation too.

When you're developing the website on local computer just download Bootstrap CSS and JS files. Include it in your project. Once you complete the code just replace those local file links with CDN and host it on a live server.

When you're using local files Netbeans will give you intellisence without any problems.

P.S: If you're interested check BootstrapPalette plugin for Netbeans

ContentLicense: CC BY-SA 3.0


问:
How do you create a fake install of a debian package for use in testing?
I have a package that previously only targeted RPM based distros for which I am now building .deb packages for Debian based distros.

The aim is to simulate a test installation from user-space that is isolated from the system you are building on. It may be multi-user and you do not want to require root access just to build the software. Many of our tests simulate the installation directory structure already. This is for the next step up to simulate an actual installation using packages built.

For the RPM packages I was able to create test installations using:

```<code>WSDIR=/where/I/want/my/tests/to/run
rpmdb --initdb --dbpath "$WSDIR"/rpmdb
rpm --relocate /opt="$WSDIR"/opt --dbpath $WSDIR/rpmdb -i <package>.rpm
</code>```

The equivalent in the Debian world is something like:

```<code>dpkg --force-not-root --admindir=$WSDIR/dpkg --root=$WSDIR/install --install "$DEB"
</code>```

However, I am stuck over the equivalent to the rpmdb --initdb step.

Note that I can just unpack the archive using:

```<code>dpkg-deb -x "$DEB" $WSDIR/install
</code>```

But I would prefer to be closer to how a real package is installed.
Also I don't think this will run preinstall and postinstall scripts.

Similar questions have suggested using deboostrap to create a chroot environment but this creates a complete new installation. As well as being overkill it is too slow for an automated test. I intend to use this for quick tests of the installation package prior to further testing in actual test environments.

My experiments so far:

```<code>(cd $WSDIR/dpkg && mkdir alternatives info parts triggers updates)
cp /var/lib/dpkg/status $WSDIR/dpkg/status
</code>```

have at best resulted in:

```<code>dpkg: error: unable to access dpkg status area: No such file or directory
</code>```

which does not indicate clear what is wrong.

So how do you create a dpkg admin directory?

Cross posted as https://superuser.com/questions/1271145/how-do-you-create-a-dpkg-admin-directory

Update 24/11/2017

I've tried copying using the dpkg dir from an environment created by [cowdancer][1] (which uses deboostrap under the hood) or copying the real one from /var/lib/dpkg but I still get the same error message so perhaps the error (and/or the --admindir option) doesn't mean quite what I think it means.

Note that:

```<code>sudo dpkg --force-not-root --root=$WSDIR/install  --admindir=/var/lib/dpkg --install "$DEB"
</code>```

does work. So it is something to do with the admin dir.
I've also retitled the question as "How do you create a dpkg admin directory" is interesting question but the answer is not necessarily the solution to my problem.

答:
The minimal way to create a dpkg database is something like this:

```<code>$ mkdir -p db/{updates,info}
$ touch db/{status,diversions,statoverride}
</code>```

If you want to use that as non-root, currently the best way is to use fakeroot.

```<code>$ mkdir -p fsys
$ PATH=/sbin:/usr/sbin:$PATH fakeroot dpkg --log=/dev/null --admindir=db --instdir=fsys -i pkg.deb
</code>```

But take into account that passing --root after --admindir or --instdir will reset those paths, which is I think the problem you have been having here.

Also using sudo and --force-not-root does not make much sense? :) And is definitely less confined than using just fakeroot. In the near future it will be possible to run dpkg fully unprivileged in some local tree.

Body:
I have a package that previously only targeted RPM based distros for which I am now building .deb packages for Debian based distros.

The aim is to simulate a test installation from user-space that is isolated from the system you are building on. It may be multi-user and you do not want to require root access just to build the software. Many of our tests simulate the installation directory structure already. This is for the next step up to simulate an actual installation using packages built.

For the RPM packages I was able to create test installations using:

WSDIR=/where/I/want/my/tests/to/run
rpmdb --initdb --dbpath "$WSDIR"/rpmdb
rpm --relocate /opt="$WSDIR"/opt --dbpath $WSDIR/rpmdb -i <package>.rpm

The equivalent in the Debian world is something like:

dpkg --force-not-root --admindir=$WSDIR/dpkg --root=$WSDIR/install --install "$DEB"

However, I am stuck over the equivalent to the rpmdb --initdb step.

Note that I can just unpack the archive using:

dpkg-deb -x "$DEB" $WSDIR/install

But I would prefer to be closer to how a real package is installed.
Also I don't think this will run preinstall and postinstall scripts.

Similar questions have suggested using deboostrap to create a chroot environment but this creates a complete new installation. As well as being overkill it is too slow for an automated test. I intend to use this for quick tests of the installation package prior to further testing in actual test environments.

My experiments so far:

(cd $WSDIR/dpkg && mkdir alternatives info parts triggers updates)
cp /var/lib/dpkg/status $WSDIR/dpkg/status

have at best resulted in:

dpkg: error: unable to access dpkg status area: No such file or directory

which does not indicate clear what is wrong.

So how do you create a dpkg admin directory?

Cross posted as https://superuser.com/questions/1271145/how-do-you-create-a-dpkg-admin-directory

Update 24/11/2017

I've tried copying using the dpkg dir from an environment created by [cowdancer][1] (which uses deboostrap under the hood) or copying the real one from /var/lib/dpkg but I still get the same error message so perhaps the error (and/or the --admindir option) doesn't mean quite what I think it means.

Note that:

sudo dpkg --force-not-root --root=$WSDIR/install  --admindir=/var/lib/dpkg --install "$DEB"

does work. So it is something to do with the admin dir.
I've also retitled the question as "How do you create a dpkg admin directory" is interesting question but the answer is not necessarily the solution to my problem.

Body:
The minimal way to create a dpkg database is something like this:

$ mkdir -p db/{updates,info}
$ touch db/{status,diversions,statoverride}

If you want to use that as non-root, currently the best way is to use fakeroot.

$ mkdir -p fsys
$ PATH=/sbin:/usr/sbin:$PATH fakeroot dpkg --log=/dev/null --admindir=db --instdir=fsys -i pkg.deb

But take into account that passing --root after --admindir or --instdir will reset those paths, which is I think the problem you have been having here.

Also using sudo and --force-not-root does not make much sense? :) And is definitely less confined than using just fakeroot. In the near future it will be possible to run dpkg fully unprivileged in some local tree.


问:
Dagger2 Optimal way to inject dependencies from two different classes
After searching and trying too many things i'm stuck in some what seems like an easy problem.
Below is my module which is reponsible for injecting retrofit.

```<code>@Module
public class NetworkingModule
{
    @Provides
    public Retrofit providesRetrofit()
    {
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        Retrofit retrofit = new Retrofit.Builder()
                                        .baseUrl(Constants.BASE_URL)
                                        .addConverterFactory(GsonConverterFactory.create(gson))
                                        .build();

        return retrofit;
    }

}
</code>```

My NetworkComponent

```<code>@Component( modules = NetworkingModule.class)
public interface NetworkingComponent {
    void inject(DashboardPresenterImpl target);

    void inject(PicksPresenterImpl picksPresenter);

    void inject(LoadsPresenterImpl loadsPresenter);

    void inject(ShippingPresenterImpl shippingPresenter);

    void inject(GeneralFilePresenterImpl generalFilePresenter);
}
</code>```

A utility class with constructor injection. Please note this class also has injection of AppPreferences.

```<code>public class AppUtils {
    private Context context;

    @Inject
    AppPreferences preferences;

    @Inject
    public AppUtils(@ActivityContext Context context)
    {
        this.context = context;

        /*ActivityComponent component = DaggerActivityComponent.builder()
                .activityModule(new ActivityModule((Activity) context))
                .build();
        component.inject(this);*/
    }
}
</code>```

Now in my Code i want to achieve this

```<code>Class MyPresenterImpl{
@Inject
    Retrofit retrofit;

    @Inject
    AppUtils appUtils;
}
</code>```

Please suggest an optimize and good way to achieve the above.

EDIT

Added AppPreference.java

```<code>public class AppPreferences {
    @Inject
    SharedPreferences sharedPreferences;

    private SharedPreferences.Editor editor;

    @Inject
    public AppPreferences(@ActivityContext Context context)
    {
        ApplicationComponent component = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule((Application) context.getApplicationContext()))
                .build();
        component.inject(this);

        editor = sharedPreferences.edit();
    }

    public void putString(String key, String value)
    {
        editor.putString(key, value).commit();
    }

    public String getString(String key)
    {
        return sharedPreferences.getString(key, null);
    }

}
</code>```

答:
Please decide on whether you want to use field injection or constructor injection, and hopefully choose constructor injection.

```<code>public class AppUtils {
  private Context context;

  @Inject // field injection?
  AppPreferences preferences;

  @Inject // constructor injection?
  public AppUtils(@ActivityContext Context context)
  {
    // ...
  }
}
</code>```

Dagger won't inject your fields if you use constructor injection and you should not call it yourself afterwards either. Your component should really not contain all those methods to inject your presenter etc.

If you need something, put it in the constructor.

```<code>public class AppUtils {
  private Context context;
  private AppPreferences preferences;

  @Inject // constructor injection!
  public AppUtils(@ActivityContext Context context, AppPreferences preferences)
  {
    // ...
  }
}
</code>```

The same applies for MyPresenterImpl. If you depend on something, put it in the constructor, mark the constructor with @Inject, and Dagger will create the object for you with all the dependencies provided.

Your components should only contain .inject(..) method for Android framework types (Activities, Fragments, ...) and nothing else.

I also wrote an article recently with some general concepts about the use of Dagger.

Body:
After searching and trying too many things i'm stuck in some what seems like an easy problem.
Below is my module which is reponsible for injecting retrofit.

@Module
public class NetworkingModule
{
    @Provides
    public Retrofit providesRetrofit()
    {
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
        Retrofit retrofit = new Retrofit.Builder()
                                        .baseUrl(Constants.BASE_URL)
                                        .addConverterFactory(GsonConverterFactory.create(gson))
                                        .build();

        return retrofit;
    }

}

My NetworkComponent

@Component( modules = NetworkingModule.class)
public interface NetworkingComponent {
    void inject(DashboardPresenterImpl target);

    void inject(PicksPresenterImpl picksPresenter);

    void inject(LoadsPresenterImpl loadsPresenter);

    void inject(ShippingPresenterImpl shippingPresenter);

    void inject(GeneralFilePresenterImpl generalFilePresenter);
}

A utility class with constructor injection. Please note this class also has injection of AppPreferences.

public class AppUtils {
    private Context context;

    @Inject
    AppPreferences preferences;

    @Inject
    public AppUtils(@ActivityContext Context context)
    {
        this.context = context;

        /*ActivityComponent component = DaggerActivityComponent.builder()
                .activityModule(new ActivityModule((Activity) context))
                .build();
        component.inject(this);*/
    }
}

Now in my Code i want to achieve this

Class MyPresenterImpl{
@Inject
    Retrofit retrofit;

    @Inject
    AppUtils appUtils;
}

Please suggest an optimize and good way to achieve the above.

EDIT

Added AppPreference.java

public class AppPreferences {
    @Inject
    SharedPreferences sharedPreferences;

    private SharedPreferences.Editor editor;

    @Inject
    public AppPreferences(@ActivityContext Context context)
    {
        ApplicationComponent component = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule((Application) context.getApplicationContext()))
                .build();
        component.inject(this);

        editor = sharedPreferences.edit();
    }

    public void putString(String key, String value)
    {
        editor.putString(key, value).commit();
    }

    public String getString(String key)
    {
        return sharedPreferences.getString(key, null);
    }

}

Body:
Please decide on whether you want to use field injection or constructor injection, and hopefully choose constructor injection.

public class AppUtils {
  private Context context;

  @Inject // field injection?
  AppPreferences preferences;

  @Inject // constructor injection?
  public AppUtils(@ActivityContext Context context)
  {
    // ...
  }
}

Dagger won't inject your fields if you use constructor injection and you should not call it yourself afterwards either. Your component should really not contain all those methods to inject your presenter etc.

If you need something, put it in the constructor.

public class AppUtils {
  private Context context;
  private AppPreferences preferences;

  @Inject // constructor injection!
  public AppUtils(@ActivityContext Context context, AppPreferences preferences)
  {
    // ...
  }
}

The same applies for MyPresenterImpl. If you depend on something, put it in the constructor, mark the constructor with @Inject, and Dagger will create the object for you with all the dependencies provided.

Your components should only contain .inject(..) method for Android framework types (Activities, Fragments, ...) and nothing else.

I also wrote an article recently with some general concepts about the use of Dagger.


问:
Custom Python extension - Import error: undefined symbol
Learning how to write a C extension in Python. Running into the following error when executing ptest.py

```<code>Traceback (most recent call last):
  File "ptest.py", line 1, in <module>
    import euler_py as eul
ImportError: /usr/local/lib/python3.6/site-packages/euler_py.cpython-
36m-x86_64-linux-gnu.so: undefined symbol: problem_one
</code>```

I'm assuming this is some type of linking issue.

setup.py

```<code>sources = glob.glob('ext/*.c')

euler = Extension(
    'euler_py',
    include_dirs=['src'],
    sources=sources,
    extra_compile_args=['-std=c99']
)

setup(
    name='euler_py',
    version='0.1',
    description='Project Euler Solutions',
    ext_modules=[euler]
)
</code>```

ptest.py

```<code>import euler_py as eul

print(eul.problem_one(10))
</code>```

The underlying functions are in /src and I wrote test.c to test purely in C. My extension is in /ext/euler_py.c shown below

ext/euler_py.c

```<code>#include <Python.h>
#include "../src/euler.h"

static char module_docstring[] = "Provides interface to Project Euler problems";

/*
 * Function implementations
 */

static PyObject* euler_py_problem_one(PyObject *self, PyObject *args)
{
    int max, result;

    if (!PyArg_ParseTuple(args, "i", &max))
        return NULL;

    result = problem_one(max);

    return Py_BuildValue("i", result);
}
// END function implementations

// Wire in functions to module
static PyMethodDef module_methods[] = {
        {"problem_one", euler_py_problem_one, METH_VARARGS, "Solution to problem 1"},
        {NULL, NULL, 0, NULL}
};

// Module definition
static struct PyModuleDef euler_py_module = {
        PyModuleDef_HEAD_INIT,
        "euler_py",
        module_docstring,
        -1,
        module_methods
};

// Module initialization function
PyMODINIT_FUNC PyInit_euler_py(void)
{
    return PyModule_Create(&euler_py_module);
}
</code>```

Repo is here. I've played around with library_dirs & include_dirs on the Extension() initiation and no luck. Python version 3.6. Need a second look.

EDIT

Repo linked to has changed since original ask. Added linking for other 3 functions in the same manor as previous.

答:
You forget to include all source files:

```<code>sources = glob.glob('ext/*.c') + glob.glob('src/*.c')
</code>```

you could see c extension build detail with setup.py build -fv:

```<code>$ python setup.py build -fv
...
clang -bundle -undefined dynamic_lookup build/temp.macosx-10.13-x86_64-3.6/ext/euler_py.o build/temp.macosx-10.13-x86_64-3.6/src/euler.o build/temp.macosx-10.13-x86_64-3.6/src/helpers.o -o build/lib.macosx-10.13-x86_64-3.6/euler_py.cpython-36m-darwin.so
</code>```

now helpers.o and euler.o properly linked.

Body:
Learning how to write a C extension in Python. Running into the following error when executing ptest.py

Traceback (most recent call last):
  File "ptest.py", line 1, in <module>
    import euler_py as eul
ImportError: /usr/local/lib/python3.6/site-packages/euler_py.cpython-
36m-x86_64-linux-gnu.so: undefined symbol: problem_one

I'm assuming this is some type of linking issue.

setup.py

sources = glob.glob('ext/*.c')

euler = Extension(
    'euler_py',
    include_dirs=['src'],
    sources=sources,
    extra_compile_args=['-std=c99']
)

setup(
    name='euler_py',
    version='0.1',
    description='Project Euler Solutions',
    ext_modules=[euler]
)

ptest.py

import euler_py as eul

print(eul.problem_one(10))

The underlying functions are in /src and I wrote test.c to test purely in C. My extension is in /ext/euler_py.c shown below

ext/euler_py.c

#include <Python.h>
#include "../src/euler.h"

static char module_docstring[] = "Provides interface to Project Euler problems";

/*
 * Function implementations
 */

static PyObject* euler_py_problem_one(PyObject *self, PyObject *args)
{
    int max, result;

    if (!PyArg_ParseTuple(args, "i", &max))
        return NULL;

    result = problem_one(max);

    return Py_BuildValue("i", result);
}
// END function implementations

// Wire in functions to module
static PyMethodDef module_methods[] = {
        {"problem_one", euler_py_problem_one, METH_VARARGS, "Solution to problem 1"},
        {NULL, NULL, 0, NULL}
};

// Module definition
static struct PyModuleDef euler_py_module = {
        PyModuleDef_HEAD_INIT,
        "euler_py",
        module_docstring,
        -1,
        module_methods
};

// Module initialization function
PyMODINIT_FUNC PyInit_euler_py(void)
{
    return PyModule_Create(&euler_py_module);
}

Repo is here. I've played around with library_dirs & include_dirs on the Extension() initiation and no luck. Python version 3.6. Need a second look.

EDIT

Repo linked to has changed since original ask. Added linking for other 3 functions in the same manor as previous.

Body:
You forget to include all source files:

sources = glob.glob('ext/*.c') + glob.glob('src/*.c')

you could see c extension build detail with setup.py build -fv:

$ python setup.py build -fv
...
clang -bundle -undefined dynamic_lookup build/temp.macosx-10.13-x86_64-3.6/ext/euler_py.o build/temp.macosx-10.13-x86_64-3.6/src/euler.o build/temp.macosx-10.13-x86_64-3.6/src/helpers.o -o build/lib.macosx-10.13-x86_64-3.6/euler_py.cpython-36m-darwin.so

now helpers.o and euler.o properly linked.


问:
ESP32/ESP8266 connect to localhost server using WiFi
I have made a simple Node.js local server to receive POST requests from ESP32 and put it in a database. The server is working fine as I tested it using postman. The server is listening to port 127.0.0.1:3000. My problem is that client.connect(host, port) always returns false. I cannot connect to the client in order to make POST requests.

```<code>#include "Arduino.h"
#include "Arduino.h"
#include "WiFi.h"

WiFiClient client;
const IPAddress server(192,168,1,10);
const int httpPort = 3000;
const char* ssid = "******";
const char* password =  "********";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booted");
  Serial.println("Connecting to Wi-Fi");
  WiFi.begin (ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
    yield();
  }
  Serial.println("WiFi connected");
  if (client.connect(server,httpPort )) {
    Serial.println("Client Connected");
  } else {
    Serial.println("No Connection");
  }

void loop() {
}
</code>```

答: The solution was to make the server listen to 0.0.0.0, which includes all IPv4 addresses on the server machine, instead of the loopback IP address 127.0.0.1</p>

Body:
I have made a simple Node.js local server to receive POST requests from ESP32 and put it in a database. The server is working fine as I tested it using postman. The server is listening to port 127.0.0.1:3000. My problem is that client.connect(host, port) always returns false. I cannot connect to the client in order to make POST requests.

#include "Arduino.h"
#include "Arduino.h"
#include "WiFi.h"

WiFiClient client;
const IPAddress server(192,168,1,10);
const int httpPort = 3000;
const char* ssid = "******";
const char* password =  "********";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booted");
  Serial.println("Connecting to Wi-Fi");
  WiFi.begin (ssid, password);
  WiFi.mode(WIFI_STA);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
    yield();
  }
  Serial.println("WiFi connected");
  if (client.connect(server,httpPort )) {
    Serial.println("Client Connected");
  } else {
    Serial.println("No Connection");
  }

void loop() {
}


问:
Yarn install command error No such file or directory: 'install'
I am installing sylius bundle and while install sylius I need to run yarn install So
While I run the command:

```<code>yarn install
</code>```

I get the error:

ERROR: [Errno 2] No such file or directory: 'install'
```

答:
Note: This solution works well on Ubuntu 16.04, Ubuntu 17.04 and Ubuntu 18.04.

Try to remove the existing cmdtest and yarn (which is the module of legacy black box command line tool of *nix systems) :

```
sudo apt remove cmdtest
sudo apt remove yarn
```

Install it simple via npm

```
npm install -g yarn
```

OR

```
sudo npm install -g yarn
```

Now yarn is installed. Run your command.

```
yarn install sylius
```

I hope this will work. Cheers!

Edit:

Do remember to re-open the terminal for changes to take effect.

ContentLicense: CC BY-SA 4.0

Body:
I am installing sylius bundle and while install sylius I need to run yarn install So
While I run the command:

yarn install

I get the error:

ERROR: [Errno 2] No such file or directory: 'install'

Body:
Note: This solution works well on Ubuntu 16.04, Ubuntu 17.04 and Ubuntu 18.04.

Try to remove the existing cmdtest and yarn (which is the module of legacy black box command line tool of *nix systems) :

sudo apt remove cmdtest
sudo apt remove yarn

Install it simple via npm

npm install -g yarn

OR

sudo npm install -g yarn

Now yarn is installed. Run your command.

yarn install sylius

I hope this will work. Cheers!

Edit:

Do remember to re-open the terminal for changes to take effect.


问:
Passing a string variable between two functions in Python
I am having trouble passing a variable from one function to another:

```<code>def name():

    first_name=input("What is your name? ")

    if len(first_name)==0:
            print("\nYou did not enter a name!")
            return name()

    else:
            print("\nHello %s." % first_name)
            return surname()

def surname():

    last_name=input("\nCan you tell my your last name please?")

    if len(last_name)==0:
            print("\nYou did not enter a last name!")
            return surname()
    else:

            print("Nice to meet you %s %s." % (first_name,last_name))
</code>```

I want the last command to print the inputed first_name from def name() and last name from def surname()

I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:

```<code>    print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined
</code>```

What am I doing wrong?

答:
You can also use while loop to ask the names constantly until there is a valid input.</p>

```<code>def name_find():
   while True:
       first_name=raw_input("What is your name? ")
       if len(first_name)==0:
           print("\nYou did not enter a name!")
           return name_find()
       else:
           print("\nHello %s." % first_name)
           return surname(first_name)
def surname(first_name):
   while True:
      last_name=raw_input("\nCan you tell me your last name please?")
      if len(last_name)==0:
          print("\nYou did not enter a last name!")
     else:
          print "Nice to meet you %s %s." % (first_name, last_name)
          break
</code>```

Body:
I am having trouble passing a variable from one function to another:

def name():

    first_name=input("What is your name? ")

    if len(first_name)==0:
            print("\nYou did not enter a name!")
            return name()

    else:
            print("\nHello %s." % first_name)
            return surname()

def surname():

    last_name=input("\nCan you tell my your last name please?")

    if len(last_name)==0:
            print("\nYou did not enter a last name!")
            return surname()
    else:

            print("Nice to meet you %s %s." % (first_name,last_name))

I want the last command to print the inputed first_name from def name() and last name from def surname()

I always get the error that first_name is not defined and I do not know how to import it from the first function. The error I get is:

    print("Nice to meet you %s %s." % (first_name,last_name))
NameError: name 'first_name' is not defined

What am I doing wrong?

Body:
You can also use while loop to ask the names constantly until there is a valid input.

def name_find():
   while True:
       first_name=raw_input("What is your name? ")
       if len(first_name)==0:
           print("\nYou did not enter a name!")
           return name_find()
       else:
           print("\nHello %s." % first_name)
           return surname(first_name)
def surname(first_name):
   while True:
      last_name=raw_input("\nCan you tell me your last name please?")
      if len(last_name)==0:
          print("\nYou did not enter a last name!")
     else:
          print "Nice to meet you %s %s." % (first_name, last_name)
          break


问:
reusable custom-filter components reset after dropdownlist lost focus
I'm trying to use the example of Reusable Custom-Filter Components. If I check the provided Plunker example I changed the filter. After I clicked somewhere else the filter is reseted to default item. How can I achieve that the filter stays so I can do other stuff on grid?

Here an excerpt from package.json:

```<code>"@angular/animations": "^5.0.4",
"@angular/common": "~5.0.0",
"@angular/compiler": "~5.0.0",
"@angular/core": "~5.0.0",
"@angular/forms": "~5.0.0",
"@angular/http": "~5.0.0",
"@angular/platform-browser": "~5.0.0",
"@angular/platform-browser-dynamic": "~5.0.0",
"@angular/router": "~5.0.0",
"@angular/upgrade": "~5.0.0",
"@progress/kendo-angular-buttons": "^2.0.0",
"@progress/kendo-angular-dateinputs": "^1.4.1",
"@progress/kendo-angular-dialog": "^1.3.0",
"@progress/kendo-angular-dropdowns": "^1.2.2",
"@progress/kendo-angular-excel-export": "^1.0.4",
"@progress/kendo-angular-grid": "^1.6.0",
"@progress/kendo-angular-inputs": "^1.3.3",
"@progress/kendo-angular-intl": "^1.3.0",
"@progress/kendo-angular-l10n": "^1.0.5",
"@progress/kendo-data-query": "^1.1.0",
"@progress/kendo-drawing": "^1.4.0",
"@progress/kendo-theme-default": "^2.43.2",
"angular2-jwt": "^0.2.3",
"angular2-moment": "^1.7.0",
"angular2-toaster": "^4.0.1",
"animate.css": "3.5.2",
"awesome-bootstrap-checkbox": "1.0.0",
"bootstrap": "4.0.0-beta",
"cldr-data": "^32.0.0",
"core-js": "^2.4.1",
"font-awesome": "4.7.0",
"glyphicons-halflings": "1.9.0",
"ng2-redux": "^5.1.2",
"ngx-bootstrap": "2.0.0-beta.5",
"pace": "git://github.com/HubSpot/pace.git#v0.7.7",
"popper.js": "1.12.5",
"redux": "^3.7.2",
"reflect-metadata": "0.1.10",
"rxjs": "^5.5.0",
"tassign": "^1.0.0",
"widgster": "0.0.3",
"zone.js": "^0.8.4"
</code>```

答:
There was an issue with the DropDownList losing the value on blur, but it is fixed in the latest version of the DropDowns package:

DOCS Changelog

Upgrading to the latest versions of the Kendo UI for Angular packages should resolve the described problem.

Body:
I'm trying to use the example of Reusable Custom-Filter Components. If I check the provided Plunker example I changed the filter. After I clicked somewhere else the filter is reseted to default item. How can I achieve that the filter stays so I can do other stuff on grid?

Here an excerpt from package.json:

"@angular/animations": "^5.0.4",
"@angular/common": "~5.0.0",
"@angular/compiler": "~5.0.0",
"@angular/core": "~5.0.0",
"@angular/forms": "~5.0.0",
"@angular/http": "~5.0.0",
"@angular/platform-browser": "~5.0.0",
"@angular/platform-browser-dynamic": "~5.0.0",
"@angular/router": "~5.0.0",
"@angular/upgrade": "~5.0.0",
"@progress/kendo-angular-buttons": "^2.0.0",
"@progress/kendo-angular-dateinputs": "^1.4.1",
"@progress/kendo-angular-dialog": "^1.3.0",
"@progress/kendo-angular-dropdowns": "^1.2.2",
"@progress/kendo-angular-excel-export": "^1.0.4",
"@progress/kendo-angular-grid": "^1.6.0",
"@progress/kendo-angular-inputs": "^1.3.3",
"@progress/kendo-angular-intl": "^1.3.0",
"@progress/kendo-angular-l10n": "^1.0.5",
"@progress/kendo-data-query": "^1.1.0",
"@progress/kendo-drawing": "^1.4.0",
"@progress/kendo-theme-default": "^2.43.2",
"angular2-jwt": "^0.2.3",
"angular2-moment": "^1.7.0",
"angular2-toaster": "^4.0.1",
"animate.css": "3.5.2",
"awesome-bootstrap-checkbox": "1.0.0",
"bootstrap": "4.0.0-beta",
"cldr-data": "^32.0.0",
"core-js": "^2.4.1",
"font-awesome": "4.7.0",
"glyphicons-halflings": "1.9.0",
"ng2-redux": "^5.1.2",
"ngx-bootstrap": "2.0.0-beta.5",
"pace": "git://github.com/HubSpot/pace.git#v0.7.7",
"popper.js": "1.12.5",
"redux": "^3.7.2",
"reflect-metadata": "0.1.10",
"rxjs": "^5.5.0",
"tassign": "^1.0.0",
"widgster": "0.0.3",
"zone.js": "^0.8.4"


Title: plotting bar graph in python

Body:
Someone Please tell me how to plot a bar graph or line graph in python.
I want to plot a bar graph with x-axis as month and y-axis with the mean values of different columns.

A Sample of my dataset:

Month   Bedroom Outlets Cellar Outlets  Bedroom Lights  DisposalDishwasher  DuctHeaterHRV   FridgeRange FurnaceHRV  KitchenLights   MasterLights    MasterOutlets   WashingMachine
Jan-16  0.008704    0.074089    0.006081    0.000116    0.000058    0.001162    0.176832    0.000024    0.014887    0.009617    0.000378
Feb-16  0.008187    0.075153    0.005993    0.000102    0.000059    0.001905    0.172289    0.000023    0.01448 0.007724    0.000367
Mar-16  0.007725    0.072855    0.005536    0.000073    0.000048    0.001469    0.1261  0.000015    0.014242    0.005848    0.00024
Apr-16  0.007678    0.074465    0.005729    0.000061    0.000042    0.001129    0.093861    0.000014    0.014267    0.005899    0.000152
May-16  0.007864    0.075408    0.005823    0.000096    0.000102    0.001691    0.116811    0.000029    0.014387    0.007111    0.000406
Jun-16  0.006876    0.07829 0.005587    0.000143    0.000134    0.000937    0.176654    0.000046    0.014229    0.005706    0.000654
Jul-16  0.006032    0.093383    0.006214    0.000193    0.000236    0.000831    0.228637    0.000082    0.014352    0.005174    0.001004

For example I want that my values on y-axis and jan 2016 on x- axis and there is a bar graph on it showing the usage of different attribute of that particular month.

Body:
For the most versatile way to use data use pandas.
import matplotlib.pyplot and pandas as follow:

import matplotlib.pyplot as plt
import pandas as pd

format your data in pandas like so:
the header list and a list of lists for the data:

data = ['Month', 'Bedroom Outlets', 'Cellar Outlets', 'Bedroom Lights', 'DisposalDishwasher', 'DuctHeaterHRV', 'FridgeRange', 'FurnaceHRV', 'KitchenLights', 'MasterLights', 'MasterOutlets', 'WashingMachine']
list_01 = [['Jan-16', 0.008704, 0.074089, 0.006081, 0.000116, 0.000058, 0.001162, 0.176832, 0.000024, 0.014887, 0.009617, 0.000378], ['Feb-16', 0.008187, 0.075153, 0.005993, 0.000102, 0.000059, 0.001905, 0.172289, 0.000023, 0.01448, 0.007724, 0.000367], ['Mar-16', 0.007725, 0.072855, 0.005536, 0.000073, 0.000048, 0.001469, 0.1261, 0.000015, 0.014242, 0.005848, 0.00024], ['Apr-16', 0.007678, 0.074465, 0.005729, 0.000061, 0.000042, 0.001129, 0.093861, 0.000014, 0.014267, 0.005899, 0.000152], ['May-16', 0.007864, 0.075408, 0.005823, 0.000096, 0.000102, 0.001691, 0.116811, 0.000029, 0.014387, 0.007111, 0.000406], ['Jun-16', 0.006876, 0.07829, 0.005587, 0.000143, 0.000134, 0.000937, 0.176654, 0.000046, 0.014229, 0.005706, 0.000654], ['Jul-16', 0.006032, 0.093383, 0.006214, 0.000193, 0.000236, 0.000831, 0.228637, 0.000082, 0.014352, 0.005174, 0.001004]]
data_frame = pd.DataFrame(list_01, columns=data)
data_frame2 = data_frame.set_index(['Month'])
data_frame2.plot.bar()
plt.show()

This will give you the months as indices and the columns represented by a color code for each category with a legend.


问:
Get Merged Cell Area with EPPLus
I'm using EPPlus to read excel files.

I have a single cell that is part of merged cells. How do I get the merged range that this cell is part of?

For example:

Assume Range ("A1:C1") has been merged.

Given Range "B1" it's Merge property will be true but there isn't a way to get the merged range given a single cell.

How do you get the merged range?

I was hoping for a .MergedRange which would return Range("A1:C1")

答:
You can get all merged cells from worksheet, hence
you can find the merged range a specific cell belongs to  using the following:

```<code> public string GetMergedRange(ExcelWorksheet worksheet, string cellAddress)
    {
        ExcelWorksheet.MergeCellsCollection mergedCells = worksheet.MergedCells;
        foreach (var merged in mergedCells)
        {
            ExcelRange range = worksheet.Cells[merged];
            ExcelCellAddress cell = new ExcelCellAddress(cellAddress);
            if (range.Start.Row<=cell.Row && range.Start.Column <= cell.Column)
            {
                if (range.End.Row >= cell.Row && range.End.Column >= cell.Column)
                {
                    return merged.ToString();
                }
            }
        }
        return "";
    }
</code>```

Update:

Turns out that there is a much easier way using EPPLUS, just do the following:

```<code>var mergedadress = worksheet.MergedCells[row, column];
</code>```

For example, if B1 is in a merged range "A1:C1":

```<code> var mergedadress = worksheet.MergedCells[1, 2]; //value of mergedadress will be "A1:C1".
</code>```

2 is the column number because B is the 2nd column.

Title: Get Merged Cell Area with EPPLus

Body:
You can get all merged cells from worksheet, hence
you can find the merged range a specific cell belongs to  using the following:

 public string GetMergedRange(ExcelWorksheet worksheet, string cellAddress)
    {
        ExcelWorksheet.MergeCellsCollection mergedCells = worksheet.MergedCells;
        foreach (var merged in mergedCells)
        {
            ExcelRange range = worksheet.Cells[merged];
            ExcelCellAddress cell = new ExcelCellAddress(cellAddress);
            if (range.Start.Row<=cell.Row && range.Start.Column <= cell.Column)
            {
                if (range.End.Row >= cell.Row && range.End.Column >= cell.Column)
                {
                    return merged.ToString();
                }
            }
        }
        return "";
    }

Update:

Turns out that there is a much easier way using EPPLUS, just do the following:

var mergedadress = worksheet.MergedCells[row, column];

For example, if B1 is in a merged range "A1:C1":

 var mergedadress = worksheet.MergedCells[1, 2]; //value of mergedadress will be "A1:C1".

2 is the column number because B is the 2nd column.


问:
Is it possible to add a methodMissing hook via a category in Groovy?
I wanted to add the methodMissing() to a class which I don't have source code control over. I've tried:

```<code>class MyClass {} // class I'm not allowed to edit

class MyCategory {

  static def methodMissing(MyClass self, String name, Object args) {
      "I was hoping this was called on a.nonexisting()"
  }

  static def test(MyClass self) {
      "test works"
  }
}

def a = new MyClass()

use(MyCategory) {
    println a.test()
    println a.nonexisting()
}
</code>```

But I still get a groovy.lang.MissingMethodException: No signature of method: MyClass.nonexisting() is applicable for argument types: () values: []

Is it possible to add a temporary methodMissing to a class?

I was trying to avoid to mess with the meta class since that change will be global and non-reversible.

答:
According to Groovy in Action, 2nd Edition published in 2015:

Category method names can well take the form of property accessors
  (pretending property access), operator methods, and GroovyObject
  methods. MOP hook methods (propertyMissing, methodMissing) cannot be added through a category
  class. This is a restriction as of Groovy 2.4. The feature may become available in later versions.

So it's not possible to do it in 2.4.12,

The release notes for Groovy 2.5 (still in development as 2017-11) don't mention any changes regarding this.

The release notes for Groovy 2.6 don't mention it either.

And finally unfortunately the release notes for Groovy 3.0 say nothing about methodMissing

Body:
I wanted to add the methodMissing() to a class which I don't have source code control over. I've tried:

class MyClass {} // class I'm not allowed to edit

class MyCategory {

  static def methodMissing(MyClass self, String name, Object args) {
      "I was hoping this was called on a.nonexisting()"
  }

  static def test(MyClass self) {
      "test works"
  }
}

def a = new MyClass()

use(MyCategory) {
    println a.test()
    println a.nonexisting()
}

But I still get a groovy.lang.MissingMethodException: No signature of method: MyClass.nonexisting() is applicable for argument types: () values: []

Is it possible to add a temporary methodMissing to a class?

I was trying to avoid to mess with the meta class since that change will be global and non-reversible.


问:
Force Outlook Add-in popup to open with embedded browser
I'm seeing an issue with my Outlook Add-in (running in Outlook 2016) where when I open a popup window using window.open, it sometimes opens in the user's default browser (e.g. Chrome) instead of the browser running the add-in (e.g. the IE11 web view embedded in Outlook 2016). This is a problem because it prevents the popup window from communicating with the add-in, which is necessary for clickjacking protection.

Is there a way to force the popup window to be opened in the same browser that is running the add-in, without using the Dialog API? I would like to support requirement set 1.3.

答:
You  should check to see if the displayDialogAsync API exists. It was added in requirement set 1.4.

If it exists, we recommend using it. Please note that the dialog can only call the Office.context.ui.messageParent API. This API allows the dialog to communicate one-way with the add-in. The add-in can use those messages to leverage the Office.js APIs.

If the displayDialogAsync API doesn’t exist you can leverage window.open. However, in this case the default browser will not be launched.


问:
Why CloudKit notification doesn't arrive when app is installed from testflight while it works when compiled from Xcode?
CloudKit notifications doesn't arrive on production (AppStore, TestFlight), but works in development mode (installed from Xcode).

Why?

This is how I register for remote notifications:

```<code>    let center = UNUserNotificationCenter.current()

    center.delegate = self
    center.requestAuthorization(options: [.alert, .badge, .sound]) { authorised, error in

        DispatchQueue.main.sync {
            application.registerForRemoteNotifications()
        }
    }
</code>```

and this is how I save subscriptions:

```<code>func subscribeForChanges() {

    let options: CKQuerySubscriptionOptions = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]

    let serviceSubscription = CKQuerySubscription(recordType: "Service", predicate: NSPredicate(value: true), options: options)
    let goalSubscription = CKQuerySubscription(recordType: "Goal", predicate: NSPredicate(value: true), options: options)
    let territorySubscription = CKQuerySubscription(recordType: "Territory", predicate: NSPredicate(value: true), options: options)
    let addressSubscription = CKQuerySubscription(recordType: "Address", predicate: NSPredicate(value: true), options: options)
    let noteSubscription = CKQuerySubscription(recordType: "Note", predicate: NSPredicate(value: true), options: options)
    let daySubscription = CKQuerySubscription(recordType: "Day", predicate: NSPredicate(value: true), options: options)
    let shareSubscription = CKQuerySubscription(recordType: "cloudkit.share", predicate: NSPredicate(value: true), options: options)

    let notificationInfo = CKNotificationInfo()
    notificationInfo.shouldBadge = false
    notificationInfo.shouldSendContentAvailable = true

    serviceSubscription.notificationInfo = notificationInfo
    goalSubscription.notificationInfo = notificationInfo
    territorySubscription.notificationInfo = notificationInfo
    addressSubscription.notificationInfo = notificationInfo
    noteSubscription.notificationInfo = notificationInfo
    daySubscription.notificationInfo = notificationInfo
    shareSubscription.notificationInfo = notificationInfo

    let privateSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [serviceSubscription, goalSubscription, territorySubscription, addressSubscription, noteSubscription, daySubscription, shareSubscription], subscriptionIDsToDelete: nil)
    privateSubscriptionsOperation.database = CloudAssistant.shared.privateDatabase

    let notificationInfoDatabaseSubscription = CKNotificationInfo()
    notificationInfoDatabaseSubscription.shouldSendContentAvailable = true

    let subscription = CKDatabaseSubscription(subscriptionID: "pl.blue-world.fieldservice.sharedDatabase")
    subscription.notificationInfo = notificationInfoDatabaseSubscription
    let sharedSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
    sharedSubscriptionsOperation.database = CloudAssistant.shared.sharedDatabase

    let queue = OperationQueue()
    queue.maxConcurrentOperationCount = 1
    queue.addOperation(privateSubscriptionsOperation)
    queue.addOperation(sharedSubscriptionsOperation)
    privateDatabase.save(CKRecordZone(zoneName: "fieldservice")) { _, _ in }
}
</code>```

答:
When something similar happened to me, it was caused by mixing up the server change tokens between the dev and prod environments. In my case, the dev change token was, say aaabbb, while the prod change token was something earlier, like, aaaaab. Since I was inadvertently using the dev change token, it was "ahead" of prod.

I see you've edited your question, but as I recall from the prior version, I believe you have already configured xcode builds to use the prod env. But, there's a simple test to prove or disprove if this theory is related to your problem. After you app inits in the env where you are not receiving notifs, call

CKFetchNotificationChangesOperation

Using Nil for the server change token. That should return every notif since the very start for that user. If the results include the missing notifs, then the problem is probably in the way you're handling change tokens.

Otherwise, I would dump all subs for that user using

CKFetchSubscriptionOperation

on both an xcode build and a testflight build, and compare the two sets, paying close attention to the predicates. I would expect the lists to be identical since you were already using the prod env, but I would rule this simple test out before looking for more complicated causes.

Body:
CloudKit notifications doesn't arrive on production (AppStore, TestFlight), but works in development mode (installed from Xcode).

Why?

This is how I register for remote notifications:

    let center = UNUserNotificationCenter.current()

    center.delegate = self
    center.requestAuthorization(options: [.alert, .badge, .sound]) { authorised, error in

        DispatchQueue.main.sync {
            application.registerForRemoteNotifications()
        }
    }

and this is how I save subscriptions:

func subscribeForChanges() {

    let options: CKQuerySubscriptionOptions = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]

    let serviceSubscription = CKQuerySubscription(recordType: "Service", predicate: NSPredicate(value: true), options: options)
    let goalSubscription = CKQuerySubscription(recordType: "Goal", predicate: NSPredicate(value: true), options: options)
    let territorySubscription = CKQuerySubscription(recordType: "Territory", predicate: NSPredicate(value: true), options: options)
    let addressSubscription = CKQuerySubscription(recordType: "Address", predicate: NSPredicate(value: true), options: options)
    let noteSubscription = CKQuerySubscription(recordType: "Note", predicate: NSPredicate(value: true), options: options)
    let daySubscription = CKQuerySubscription(recordType: "Day", predicate: NSPredicate(value: true), options: options)
    let shareSubscription = CKQuerySubscription(recordType: "cloudkit.share", predicate: NSPredicate(value: true), options: options)

    let notificationInfo = CKNotificationInfo()
    notificationInfo.shouldBadge = false
    notificationInfo.shouldSendContentAvailable = true

    serviceSubscription.notificationInfo = notificationInfo
    goalSubscription.notificationInfo = notificationInfo
    territorySubscription.notificationInfo = notificationInfo
    addressSubscription.notificationInfo = notificationInfo
    noteSubscription.notificationInfo = notificationInfo
    daySubscription.notificationInfo = notificationInfo
    shareSubscription.notificationInfo = notificationInfo

    let privateSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [serviceSubscription, goalSubscription, territorySubscription, addressSubscription, noteSubscription, daySubscription, shareSubscription], subscriptionIDsToDelete: nil)
    privateSubscriptionsOperation.database = CloudAssistant.shared.privateDatabase

    let notificationInfoDatabaseSubscription = CKNotificationInfo()
    notificationInfoDatabaseSubscription.shouldSendContentAvailable = true

    let subscription = CKDatabaseSubscription(subscriptionID: "pl.blue-world.fieldservice.sharedDatabase")
    subscription.notificationInfo = notificationInfoDatabaseSubscription
    let sharedSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
    sharedSubscriptionsOperation.database = CloudAssistant.shared.sharedDatabase

    let queue = OperationQueue()
    queue.maxConcurrentOperationCount = 1
    queue.addOperation(privateSubscriptionsOperation)
    queue.addOperation(sharedSubscriptionsOperation)
    privateDatabase.save(CKRecordZone(zoneName: "fieldservice")) { _, _ in }
}


问:
ImportXML function in Google Sheets #ERROR
Have often frequented these pages but never needed to raise a new question...

I've searched high and low for a solution to, what should be, a fairly simple ImportXML function in Google sheets and I simply cannot grab the data I'm looking for.

Companies House in the UK make their basic company data freely available in various formats. For example, for company number 06732413 (I've picked that entirely at random as a usable example), their data can be accessed at http://data.companieshouse.gov.uk/doc/company/06732413 (or alternatively at http://data.companieshouse.gov.uk/doc/company/06732413.xml, and a range of other types.)

I simply cannot find a way for ImportXML to return a specific element within that data, say the <Accounts>/<NextDueDate> data.

Is there an obvious solution?

答:
Please try:</p>

```<code>=index(importxml("http://data.companieshouse.gov.uk/doc/company/06732413","//*[3]/td"),3,1)
</code>```

Body:
Please try:

=index(importxml("http://data.companieshouse.gov.uk/doc/company/06732413","//*[3]/td"),3,1)


问:
DataTables column search for exact match with regex
I am using jQuery Datatables plugin in my application. I am trying to search for a string that exactly matches the data in a column. I checked jQuery DataTables - Filter column by an exact match which is not working for my case. My search string is a regular expression with | symbols which might look like s1|s2|s12. When the search string contains only s1 at that time s1 record is shown , but when i search multiple values s1|s2 then no records are shown

```<code>jQuery("#myTable").DataTable()
                    .columns("#")
                    .search("^"+'s1|s2'+"$",true,false)
                    .draw();
</code>```

Result: No result found .

when i tried below code then addtional  records are shown up

```<code>$('#myTable').DataTable().search('s1|s2').draw();
</code>```

Result: s1,s2,s11,s14,s22,s25 etc.

Any help would be much appreciated ..

答:
You missed by two brackets.

```<code>jQuery("#myTable").DataTable()
                    .columns("#")
                    .search('^(s1|s2)$',true,false)
                    .draw();
</code>```

And search('s1|s2') did not give desired results because by default regex is disabled in search method. So it is considering s1|s2 as a string which will match s, 1, 2, |, s1, 1| .. etc. You have to provide second parameter as true and third parameter as false to avoid conflict and cause unexpected results. See search() method for more information.

Body:
I am using jQuery Datatables plugin in my application. I am trying to search for a string that exactly matches the data in a column. I checked jQuery DataTables - Filter column by an exact match which is not working for my case. My search string is a regular expression with | symbols which might look like s1|s2|s12. When the search string contains only s1 at that time s1 record is shown , but when i search multiple values s1|s2 then no records are shown

jQuery("#myTable").DataTable()
                    .columns("#")
                    .search("^"+'s1|s2'+"$",true,false)
                    .draw();

Result: No result found .

when i tried below code then addtional  records are shown up

$('#myTable').DataTable().search('s1|s2').draw();

Result: s1,s2,s11,s14,s22,s25 etc.

Any help would be much appreciated ..

Body:
You missed by two brackets.

jQuery("#myTable").DataTable()
                    .columns("#")
                    .search('^(s1|s2)$',true,false)
                    .draw();

And search('s1|s2') did not give desired results because by default regex is disabled in search method. So it is considering s1|s2 as a string which will match s, 1, 2, |, s1, 1| .. etc. You have to provide second parameter as true and third parameter as false to avoid conflict and cause unexpected results. See search() method for more information.


问:
How to make child process die after parent exits?
Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure or anything else) I want the child process to die. How to do that correctly?

Some similar question on stackoverflow:

(asked earlier) How can I cause a child process to exit when the parent does?

(asked later) Are child processes created with fork() automatically killed when the parent is killed?

Some similar question on stackoverflow for Windows:

How do I automatically destroy child processes in Windows?

Kill child process when parent process is killed

答:
Another way to do this that is Linux specific is to have the parent be created in a new PID namespace. It will then be PID 1 in that namespace, and when it exits it all of it's children will be immediately killed with SIGKILL.

Unfortunately, in order to create a new PID namespace you have to have CAP_SYS_ADMIN. But, this method is very effective and requires no real change to the parent or the children beyond the initial launch of the parent.

See clone(2), pid_namespaces(7), and unshare(2).

OwnerDisplayName: phjr

LastEditorDisplayName: dmckee


问:
How to filter a dataframe by multiple columns and add a value
```<code>df = mdb.read_table(mdbfile, "table")
invoices = pd.read_csv(file, delimiter=';')

lst = df[(df['El4'] == el4)] #contains specific rows of df

for i, row in lst.iterrows():
    prop = row['propertyid']
    mouvement = (row['Mouvements']*-1)

    a = invoices[(invoices['propertyReference'] == prop) & (invoices.invoiceGrossAmount == mouvement)]
    invoiceid = a['invoiceId'].values

    mouvement = (mouvement*-1)

    if df[(df.propertyid == prop) & (df.Mouvements == mouvement)]:
        df['id'] = invoiceid
</code>```

I receive the following error:

```<code>The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

I would like to fill in specific values (invoiceId) in the rows of the dataframe where propertyid equals prop and mouvements equals mouvement.

答:
Another idea is to use the combine first method.

To use this method, you need to ensure the index in both data frames are equal.  Something like:

```<code># Its not clear is the sign on Movement needs to be changed to merge with invoices. If so, comment out the line below
df.loc[:,'Mouvement] = df.loc[:,'Mouvement]*-1
df = df.set_index('propertyid','Mouvement')
invoices = invoices.set_index('propertyReference', 'invoiceGrossAmount')
df = df.combine_first(invoices)
</code>```

This is very similar to the merge method @RagingRoosevelt suggested.

Body:
df = mdb.read_table(mdbfile, "table")
invoices = pd.read_csv(file, delimiter=';')

lst = df[(df['El4'] == el4)] #contains specific rows of df

for i, row in lst.iterrows():
    prop = row['propertyid']
    mouvement = (row['Mouvements']*-1)

    a = invoices[(invoices['propertyReference'] == prop) & (invoices.invoiceGrossAmount == mouvement)]
    invoiceid = a['invoiceId'].values

    mouvement = (mouvement*-1)

    if df[(df.propertyid == prop) & (df.Mouvements == mouvement)]:
        df['id'] = invoiceid

I receive the following error:

The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I would like to fill in specific values (invoiceId) in the rows of the dataframe where propertyid equals prop and mouvements equals mouvement.

Body:
Another idea is to use the combine first method.

To use this method, you need to ensure the index in both data frames are equal.  Something like:

# Its not clear is the sign on Movement needs to be changed to merge with invoices. If so, comment out the line below
df.loc[:,'Mouvement] = df.loc[:,'Mouvement]*-1
df = df.set_index('propertyid','Mouvement')
invoices = invoices.set_index('propertyReference', 'invoiceGrossAmount')
df = df.combine_first(invoices)

This is very similar to the merge method @RagingRoosevelt suggested.


问:
using AlamofireObjectMapper for mapping model - swift
I'm using AlamofierObjectMapper to map my json came from server to my model. The json receiving from server is like this:

```<code>[
  {
    "Title": "string",
    "ImageUrl": "string",
    "Url": "string",
    "UrlType": "none"
  }
]
</code>```

and the class I'm using for mapping is :

```<code>class Banner: Mappable {
    var Title: String?
    var ImageUrl: String?
    var Url: String?
    var UrlType: String?

    required init?(map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        Title <- map["Title"]
        ImageUrl <- map["ImageUrl"]
        Url <- map["Url"]
        UrlType <- map["UrlType"]
    }
}
</code>```

My class is not an array but my json is an array. how can I get data without ding sth like this:

```<code>{
  "result" : [
  {
    "Title": "string",
    "ImageUrl": "string",
    "Url": "string",
    "UrlType": "none"
  }
  ]
}
</code>```

Edit:

my request:

```<code>Alamofire.request(url, method: .get)
        .responseObject { (response: DataResponse<Banner>) in

            }
</code>```

答:
It's very simple, you just need to use the method responseArray:</p>

```<code>Alamofire.request(url, method: .get).responseArray { (response: DataResponse<[Banner]>) in

    let bannersArray = response.result.value

    if let bannersArray = bannersArray {
        for banner in bannersArray {
            // Do anything with it
        }
    }
}
</code>```

Body:
I'm using AlamofierObjectMapper to map my json came from server to my model. The json receiving from server is like this:

[
  {
    "Title": "string",
    "ImageUrl": "string",
    "Url": "string",
    "UrlType": "none"
  }
]

and the class I'm using for mapping is :

class Banner: Mappable {
    var Title: String?
    var ImageUrl: String?
    var Url: String?
    var UrlType: String?

    required init?(map: Map) {

    }

    // Mappable
    func mapping(map: Map) {
        Title <- map["Title"]
        ImageUrl <- map["ImageUrl"]
        Url <- map["Url"]
        UrlType <- map["UrlType"]
    }
}

My class is not an array but my json is an array. how can I get data without ding sth like this:

{
  "result" : [
  {
    "Title": "string",
    "ImageUrl": "string",
    "Url": "string",
    "UrlType": "none"
  }
  ]
}

Edit:

my request:

Alamofire.request(url, method: .get)
        .responseObject { (response: DataResponse<Banner>) in

            }

Body:
It's very simple, you just need to use the method responseArray:

Alamofire.request(url, method: .get).responseArray { (response: DataResponse<[Banner]>) in

    let bannersArray = response.result.value

    if let bannersArray = bannersArray {
        for banner in bannersArray {
            // Do anything with it
        }
    }
}


问:
How do I get the number of elements in a list (length of a list) in Python?
How do I get the number of elements in the list items?

```<code>items = ["apple", "orange", "banana"]

# There are 3 items.
</code>```

答:
And for completeness (primarily educational), it is possible without using the len() function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.

```<code>def count(list):   # list is an iterable object but no type checking here!
    item_count = 0
    for item in list:
        item_count += 1
    return item_count

count([1,2,3,4,5])
</code>```

(The list object must be iterable, implied by the for..in stanza.)

The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.

Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:

```<code>class MyList(object):
    def __init__(self):
        self._data = []
        self.length = 0 # length tracker that takes up memory but makes length op O(1) time

        # the implicit iterator in a list class
    def __iter__(self):
        for elem in self._data:
            yield elem

    def add(self, elem):
        self._data.append(elem)
        self.length += 1

    def remove(self, elem):
        self._data.remove(elem)
        self.length -= 1

mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2
</code>```

Body:
How do I get the number of elements in the list items?

items = ["apple", "orange", "banana"]

# There are 3 items.

Body:
And for completeness (primarily educational), it is possible without using the len() function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.

def count(list):   # list is an iterable object but no type checking here!
    item_count = 0
    for item in list:
        item_count += 1
    return item_count

count([1,2,3,4,5])

(The list object must be iterable, implied by the for..in stanza.)

The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);, does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.

Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:

class MyList(object):
    def __init__(self):
        self._data = []
        self.length = 0 # length tracker that takes up memory but makes length op O(1) time

        # the implicit iterator in a list class
    def __iter__(self):
        for elem in self._data:
            yield elem

    def add(self, elem):
        self._data.append(elem)
        self.length += 1

    def remove(self, elem):
        self._data.remove(elem)
        self.length -= 1

mylist = MyList()
mylist.add(1)
mylist.add(2)
mylist.add(3)
print(mylist.length) # 3
mylist.remove(3)
print(mylist.length) # 2


问:
Cygwin and Python 2.6
New to python (and programming).  What exactly do I need from Cygwin?  I'm running python 2.6 on winxp.  Can I safely download the complete Cygwin?  It just seems like a huge bundle of stuff.

Well, I keep running into modules and functionality (i.e. piping output) which suggest downloading various cygwin components. Will cygwin change or modify any other os functionality or have any other side effects?

答:
cygwin is effectively a Unix subkernel. Setup and installed in its default manner it won't interrupt or change any existing Windows XP functionality. However, you'll have to start the cygwin equivalent of the command prompt before you can use its functionality.

With that said, some of the functionality you're talking about is available in Windows. Piping definitely is. For instance:

netstat -ano | findstr :1433

is a command line I use to make sure my SQL Server is listening on the default port. The output of netstat is being piped to findstr so I only have to see any lines containing :1433.

Title: Cygwin and Python 2.6

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: K. Brian Kelley

ContentLicense: CC BY-SA 2.5


问:
PowerShell: How to source a function like source a file?
In my main script, I will first call an init function to initiate many variables which I expected to be used in the script. One way is to use variables whose name are like $script:var1 which are script level variable. But that's kind of ugly and I'd like to use normal variable name, so I need a mechanism to source a function just like source a file.

When source a file, all the variables in that file are available in the calling script.

答:
You can also do it in a scriptblock and dot-source that, but the rules are slightly different. You must have a space after the period to dot-source a function, and you don't with a scriptblock.

Both of these will produce 42

```<code>$a=0
function init {$a=42}
. init
$a

$a=0
$init={$a=42}
.$init
$a
</code>```

Body:
You can also do it in a scriptblock and dot-source that, but the rules are slightly different. You must have a space after the period to dot-source a function, and you don't with a scriptblock.

Both of these will produce 42

$a=0
function init {$a=42}
. init
$a

$a=0
$init={$a=42}
.$init
$a


问:
Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)
I'm developing using the GSSAPI, and I have code which works with a vanilla MIT Kerberos 5 server to do some client/server work. I'm now verifying it's functionality against Active Directory and I've hit an issue.

I have my server authenticated and listening. I can get the client to login. For the record, this is code based off of http://thejavamonkey.blogspot.com/2008/04/clientserver-hello-world-in-kerberos.html. However, I cannot get the client to get the ticket back from AD to get the session between it and the server. I get KrbException: Server not found in Kerberos database (7), and I cannot figure out where the proper place is to add it. I've tried putting the server name with ip in the hosts file, updating dns, putting in server records, etc, with no luck.

If anyone knows where the proper place is to update AD to set a server in the Kerberos Database, that would be great!

答:
"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.

You can check that with:

```<code>$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )
</code>```

Body:
"Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.

You can check that with:

$ SetSPN -Q ServicePrincipalName
( SetSPN -Q HTTP/my.server.local@MYDOMAIN )


问:
How to Handle Loading Data Based on Selection in MVC?
I have always worked with Web APIs, so I don't know how to handle this very basic problem in .NET Core MVC (I am only familiar with MVC conceptually). My problem:

I need a user to select an option from a dropdown on the front end and then show some data based on the option (after fetching it).

If I were writing an SPA consuming an API, I would simply make a call to the backend to get the data and then generate the html to display it on the front end.

How is this handled in MVC? Isn't the convention to return entirely new views? How are things like these handled?

I just need a pointer in the right direction conceptually - I can figure out the code.

Edit: Should I just pretend it's an SPA despite it being a view and create an API endpoint in the same app that provides the view and consume it from the cshtml?

答:
It works exactly the same way. You make an AJAX call to fetch some data. You can either return the data directly, and utilize JS to render the HTML or return HTML directly. Either way, you use the AJAX callback to replace the appropriate content on the page.

Even in older ASP.NET MVC projects it worked this way, though you basically had to decide whether you were going to use an MVC controller or a Web Api controller to do the work. Either would work, but there were advantages/disadvantages to each approach. MVC/Web Api could always coexist in the same project.

In ASP.NET Core, the difference is purely semantic. There's really no such thing as MVC and Web Api anymore - just ASP.NET Core. A controller is a controller is a controller, so just add an endpoint and go to town.


问:
MYSQL Foreign Key Set
Abstract: Table A has a row which contains a list of Integers that reference IDs in Table B.

Why not just create a column in table B that references Table A? Because the items in Table B are reusable, and apply to many rows in table A.

Specific example: An educational software, which consists of lessons and line items. Each lesson incorporates many line items, and each line item is used in many lessons.

This many-to-many linking is a common task and I have probably been doing it wrong forever. The easiest way I have done it in the past is to have Table A contain a varchar with a delimited list, interpret that list in code and then run another query to get the needed information from table B.

Is there more elegant way? Some way of combining the functionality of SET data type with Foreign Keys index?

答:
For a Many to Many relationship you will be using 3 tables:

Table Lesson:

Columns: ln_id, ln_lesson_name

Table LineItem

Columns: li_id, li_line_detail

And a relation table LineOfLesson

Columns: ls_lesson_id (references the id in the Lesson table), ls_line_item_id (references the id in the LineItem table)

In this way by querying the three tables you can get either the lessons where a particular line is used or the lines that make up a particular lesson.

Side note: In the relation table the two ids together would be the natural primary key of the table.

Also if there were aditional information regarding the relation it would also be added here for example, you could add when was the line item was added.

Title: MYSQL Foreign Key Set


问:
Matching complex patterns with intent filters and data
My intent filter looks like this:

```<code><intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.SENDTO" />
    <category android:name="android.intent.category.DEFAULT"></category>
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="http" android:host="mywebsite" android:pathPattern="/oauth/authorize?.*oauth_verifier=.*" />
</intent-filter>
</code>```

however this fails to match.

If I remove the ? and everything after it, it matches but the site I am matching uses that URL several times, and the only one I am interested in is the oauth_verifier.

Is there anyway to make an intent filter match the bit (query parameters?) after the /oauth/authorize

答:
Is there anyway to make an intent filter match the bit (query parameters?) after the /oauth/authorize

No, sorry.

Body:
My intent filter looks like this:

<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <action android:name="android.intent.action.SENDTO" />
    <category android:name="android.intent.category.DEFAULT"></category>
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="http" android:host="mywebsite" android:pathPattern="/oauth/authorize?.*oauth_verifier=.*" />
</intent-filter>

however this fails to match.

If I remove the ? and everything after it, it matches but the site I am matching uses that URL several times, and the only one I am interested in is the oauth_verifier.

Is there anyway to make an intent filter match the bit (query parameters?) after the /oauth/authorize


问:
architecture for high availability
I have this scenario:

You have a factory process line which runs 24/7. Downtime is extremely expensive.
The software controlling all different parts must use a shared form of database storage
The main reason for this is to know in which state the factory is in.  For example some products can be mixed when using the same set of equipement and others DEFINITELY not.

requirements:

I want to the software be able to detect that an error in one part of
the plant must result in some machine shutdown more then 1 km away. so stoing data in the plc's is not an option.

Updates and upgrades to the factory environment are frequent

load (in computer terms) will be really low.

The systems handles a few hunderd assignments a day for which calculations / checks are done followed by instructions send for the factory machines. Systems will be bored most of the time. Most important requirement is the central computer system must be correct and always working.

I was thinking to use a dynamo based database (riak or cassandra) where data gets written to multiple machines with each machine having the whole database

When one system goes down it will go down unoticed. A Traditional sql databse might be more of a pain to upgrade when tables changes and this master slave is harder to configure.

What would be your solution?

Network has been made redundant and most other single points of failure to. The database system is critical because downtime of the db means downtime for the entire plant not just one of the machines which is acceptable.

How to solve shared state problem.

complexity in the database will not be a problem. I will be more like a simple key value store to get the most current and correct data.

答:
You need to avoid single points of failure.

All the major players in our dbms world offer at least one way to avoid making the database itself a single point of failure. I might question whether they can propagate changes fast enough for your manufacturing processes. (Or is data update not really an issue? Can't really tell from your question.) My db work in manufacturing is limited to the car and the chemical industry. Microseconds didn't matter to them.

But the dbms isn't the only thing that can fail. "Always working" means that the clients have to always be working, too. Client hardware, connections to the network, the network and network servers themselves all probably have single points of failure. Failure-tolerant servers have multiple power supplies, multiple NICs, etc.

"Always working" is really expensive. I have a feeling that the database isn't going to be the biggest problem for your company.

Title: architecture for high availability


问:
create a folder on an SD card
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

```<code>public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}
</code>```

答:
you have to import that ;) when you copy and paste it doesn't import automatically. Make sure you have similar imports like this:                                        </p>

```<code>package [your package name];

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.util.Calendar;
//upto here
public class Jobselection extends AppCompatActivity
</code>```

Title: create a folder on an SD card

Body:
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}

Body:
you have to import that ;) when you copy and paste it doesn't import automatically. Make sure you have similar imports like this:

package [your package name];

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.util.Calendar;
//upto here
public class Jobselection extends AppCompatActivity


问:
reverse for ' chat_room' not found. ' chat_room' is not a valid view function or pattern name
I got error and don't know how to fix it
reverse for chat_room not found. chat_room is not a valid view function or pattern name

/home/mbae/.local/lib/python3.5/site-packages/channels/handler.py in process_exception_by_middleware

```<code>            return super(AsgiHandler, self).process_exception_by_middleware(exception, request)

 ...
</code>```

▶ Local vars
/home/mbae/.local/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response

```<code>                response = wrapped_callback(request, *callback_args, **callback_kwargs)

 ...
</code>```

▶ Local vars
/home/mbae/465/mysite/prj/views.py in new_room

```<code>    return redirect(chat_room, label=label)

 ...
</code>```

▶ Local vars

views.py

```<code>def new_room(request):
    new_room = None
    while not new_room:
        with transaction.atomic():
            l = Haikunator()
            label=l.haikunate()
            if Room.objects.filter(label=label).exists():
                continue
            new_room = Room.objects.create(label=label)
    return redirect(chat_room, label=label)

def chat_room(request, label):

    room, created = Room.objects.get_or_create(label=label)

    messages = reversed(room.messages.order_by('-timestamp')[:50])

    return render(request, "prj/chat.html", {
        'room': room,
        'messages': messages,
})
</code>```

urls.py

```<code>url(r'^new/$', views.new_room, name='new_room'),
url(r'^(?P<label>[\w-]{,50})/$', views.chat_room, name='chat_room'),
</code>```

room.html:

```<code><h1>{{ room.label }}</h1>
<p class="quiet">
    Anyone with this URL can join the room and chat:
    <code>{{ request.scheme }}://{{ request.get_host }}/{{ room.label }}</code>
</p>
<p>
    <label for="handle">Your name:</label>
    <input id="handle" type="text" placeholder="handle">
</p>
<form id="chatform">
    <table id="chat">
        <tbody>
            {% for message in messages %}
                <tr>
                    <td>{{ message.formatted_timestamp }}</td>
                    <td>{{ message.handle }}</td>
                    <td>{{ message.message }}</td>
                </tr>
            {% endfor %}
        </tbody>
        <tfoot>
        <tr>
            <td>Say something:</td>
            <td colspan=2>
                <input id="message" type="text" placeholder="message">
                <button type="submit" id="go">Say it</button>
            </td>
        </tfoot>
    </table>
</form>
</code>```

答:
I think this is the problem line:

```<code>return redirect(chat_room, label=label)
</code>```

Try passing "chat_room" instead of chat_room!

See also: django redirect to view

Body:
I got error and don't know how to fix it
reverse for chat_room not found. chat_room is not a valid view function or pattern name

/home/mbae/.local/lib/python3.5/site-packages/channels/handler.py in process_exception_by_middleware

            return super(AsgiHandler, self).process_exception_by_middleware(exception, request)

 ...

▶ Local vars
/home/mbae/.local/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response

                response = wrapped_callback(request, *callback_args, **callback_kwargs)

 ...

▶ Local vars
/home/mbae/465/mysite/prj/views.py in new_room

    return redirect(chat_room, label=label)

 ...

▶ Local vars

views.py

def new_room(request):
    new_room = None
    while not new_room:
        with transaction.atomic():
            l = Haikunator()
            label=l.haikunate()
            if Room.objects.filter(label=label).exists():
                continue
            new_room = Room.objects.create(label=label)
    return redirect(chat_room, label=label)

def chat_room(request, label):

    room, created = Room.objects.get_or_create(label=label)

    messages = reversed(room.messages.order_by('-timestamp')[:50])

    return render(request, "prj/chat.html", {
        'room': room,
        'messages': messages,
})

urls.py

url(r'^new/$', views.new_room, name='new_room'),
url(r'^(?P[\w-]{,50})/$', views.chat_room, name='chat_room'),

room.html:

{{ room.label }}

    Anyone with this URL can join the room and chat:
    {{ request.scheme }}://{{ request.get_host }}/{{ room.label }}

    Your name:
    <input id="handle" type="text" placeholder="handle">

<form id="chatform">

            {% for message in messages %}

                    {{ message.formatted_timestamp }}
                    {{ message.handle }}
                    {{ message.message }}

            {% endfor %}

            Say something:

                <input id="message" type="text" placeholder="message">
                <button type="submit" id="go">Say it</button>

</form>

Body:
I think this is the problem line:

return redirect(chat_room, label=label)

Try passing "chat_room" instead of chat_room!

See also: django redirect to view


问:
Unit testing of potential concurrency problems
I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.

Let us suppose that we have a some "black-box" class FooUnknown taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter).

Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?

My conclusion, that it is not possible. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.

Also I believe, that this question is not too broad. For certainty let us say we have a class some.FooUnknown and we want to use it in the following way:

```<code>@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}
</code>```

How to test it to be sure that it is thread-safe, that we don't need to wrap it into ThreadLocal<FooUnknown> for instance?

答: You are correct - as a black box, you can't possibly say if it's thread safe or not.. Even if you test it for 2 weeks and throw everything at it on a million VMs, maybe it is thread-safe now, but will become thread-unsafe in 2018 (e.g. by internally checking what the date is and intentionally dead-locking on 2018-01-01)</p>

Body:
I have had recently a small contest with one of my colleagues (whom I very respect) regarding a theoretical possibility to test whether some code is thread-safe or not.

Let us suppose that we have a some "black-box" class FooUnknown taken from the 3rd party library, so we don't have an access to its original source code. Furthermore, it might be that it internally uses some native methods (if this is a matter).

Can we write such an unit test which will tell us that usage of this class (for example, its instance shared between several threads) is 100% thread-safe or not?

My conclusion, that it is not possible. For me it is obvious and straightforward: although one can write a code which will lead to some concurrency problems which is possible to detect. But an absent of such results doesn't guarantee that there are not concurrency issues at all.

Also I believe, that this question is not too broad. For certainty let us say we have a class some.FooUnknown and we want to use it in the following way:

@ApplicationScoped
public class FooService {
    private some.FooUnkown foo = new some.FooUnknown();

    public void someStuff() {
        // ...
        String result = foo.doSomeStuff();
        // ...
    }
}

How to test it to be sure that it is thread-safe, that we don't need to wrap it into ThreadLocal<FooUnknown> for instance?


问:
K-means clustering doesn't find all clusters in data
The set of data I am using is shown below. As one can see you would think the k-means cluster analysis would find the centers of these clusters easily.

However, when I run K-means cluster analysis and plot the centers I get this.

I am using just the basic kmeans code:

```<code>cluster <- kmeans(mydata,90)
cluster$centers
</code>```

答:
A little-known fact about kmeans is that to get reliable results, you need to run the algorithm repeatedly with many random initializations. I typically use kmeans(, nstart = 1000).

In theory, the kmeans++ algorithm does not suffer as much from the initialization problem, but I often find that kmeans with many random restarts performs better than kmeans++. Still, you might want to try kmeans++ using the flexclust R package.

Body:
The set of data I am using is shown below. As one can see you would think the k-means cluster analysis would find the centers of these clusters easily.

However, when I run K-means cluster analysis and plot the centers I get this.

I am using just the basic kmeans code:

cluster <- kmeans(mydata,90)
cluster$centers


问:
Where can I find listings of "taken" identifiers in standard libraries
With the large size of current C/C++ libraries like STL, Win32, Boost, posix etc. the question of what identifiers are problematic arises. Even with namespaces it is nice to be able to select identifiers which don't clash with the most used identifiers of other libraries when desiging a new library designed to work togheter with existing ones.

At least for the C++ standard libraries (including 0x) there should be listings available. It would be reasonable to think that someone has done a tool for this purpose, which reads a set of header files and creates a list of all names ordered by namespace. Anyone who knows of such a tool? The tool should preferably read all headers in a directory tree rather than only those #included by a particular cpp file.

答: How about using egrep? [Mumble mumble to get 30 characters]</p>


问:
How to get text response directly on Dialogflow?
I'm trying to get a direct text response from dialogflow. I do get an answer from the example code on github, but thats not user-friendly at all. How can I get the "Speech-Only" response?

```<code>import os.path
import sys

try:
    import apiai
except ImportError:
    sys.path.append(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
    )
    import apiai

CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'

def main():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'de'  # optional, default value equal 'en'

    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    request.query = "Hello"

    response = request.getresponse()

    print (response.read())

if __name__ == '__main__':
    main()
</code>```

I just expect a a simple result. A plain hello text.

What I get instead = b'{\n  "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n  "timestamp": "2017-12-05T22:18:15.563Z",\n  "lang": "en",\n  "result": {\n    "source": "agent",\n    "resolvedQuery": "hi",\n    "action": "input.welcome",\n    "actionIncomplete": false,\n    "parameters": {},\n    "contexts": [],\n    "metadata": {\n      "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n      "webhookUsed": "false",\n      "webhookForSlotFillingUsed": "false",\n      "intentName": "Default Welcome Intent"\n    },\n    "fulfillment": {\n      "speech": "Hi there!",\n      "messages": [\n        {\n          "type": 0,\n          "speech": "Hi there!"\n        }\n      ]\n    },\n    "score": 1.0\n  },\n  "alternateResult": {\n    "source": "domains",\n    "resolvedQuery": "hi",\n    "action": "smalltalk.greetings.hello",\n    "actionIncomplete": false,\n    "parameters": {},\n    "contexts": [],\n    "metadata": {},\n    "fulfillment": {\n      "speech": "Hey!",\n      "source": "agent"\n    },\n    "score": 1.0\n  },\n  "status": {\n    "code": 200,\n    "errorType": "success",\n    "webhookTimedOut": false\n  },\n  "sessionId": "mr.9000"\n}'

答:
Looks like you're using Dialogflow's query API. The format of the response is documented here.  You'll have to parse the JSON.  The most common way to do this would be ...

Use the json module which you'll need to import (i.e. import json at the top of you file).

Next you'll need to load the JSON string you're received with the load method (i.e. add a line after you define response: response_dict = json.loads(response.read())

Lastly you'll need to retrieve the correct string from the response_dict object: print(response_dict.['result']['resolvedQuery'])

Body:
I'm trying to get a direct text response from dialogflow. I do get an answer from the example code on github, but thats not user-friendly at all. How can I get the "Speech-Only" response?

import os.path
import sys

try:
    import apiai
except ImportError:
    sys.path.append(
        os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
    )
    import apiai

CLIENT_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN'

def main():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'de'  # optional, default value equal 'en'

    request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    request.query = "Hello"

    response = request.getresponse()

    print (response.read())

if __name__ == '__main__':
    main()

I just expect a a simple result. A plain hello text.

What I get instead = b'{\n  "id": "306fd06a-d9e6-4c2e-8c05-98ff7fc0ecd5",\n  "timestamp": "2017-12-05T22:18:15.563Z",\n  "lang": "en",\n  "result": {\n    "source": "agent",\n    "resolvedQuery": "hi",\n    "action": "input.welcome",\n    "actionIncomplete": false,\n    "parameters": {},\n    "contexts": [],\n    "metadata": {\n      "intentId": "8406ea3a-a0c9-4470-829f-aba0ce2da2e5",\n      "webhookUsed": "false",\n      "webhookForSlotFillingUsed": "false",\n      "intentName": "Default Welcome Intent"\n    },\n    "fulfillment": {\n      "speech": "Hi there!",\n      "messages": [\n        {\n          "type": 0,\n          "speech": "Hi there!"\n        }\n      ]\n    },\n    "score": 1.0\n  },\n  "alternateResult": {\n    "source": "domains",\n    "resolvedQuery": "hi",\n    "action": "smalltalk.greetings.hello",\n    "actionIncomplete": false,\n    "parameters": {},\n    "contexts": [],\n    "metadata": {},\n    "fulfillment": {\n      "speech": "Hey!",\n      "source": "agent"\n    },\n    "score": 1.0\n  },\n  "status": {\n    "code": 200,\n    "errorType": "success",\n    "webhookTimedOut": false\n  },\n  "sessionId": "mr.9000"\n}'