问:
Composer PSR-4 for php file
In my project I have a folder lib\custom  which contains Web folder and functions.php file. In my functions.php I have some functions which I need to use in another classes and in this file on the first line I have a defined namespace  look like this

```<code><?php
namespace Custom;

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

And in Web folder I have some classes with namespace Custom\Web;

In my composer.json file I have defined namespace look like this

```<code>"Custom\\":"lib/custom/"
</code>```

So , now I am using the  abc()  look like this

```<code>use Custom;
$abc = Custom\abc("abc")
</code>```

but as a response I am getting

Call to undefined function Custom\abc()

How can I solve this problem?

答:
PSR-4 describes a specification for autoloading classes from file paths. It doesn't cover loading functions from files.

Use the files autoloader to load a file with functions on each request automatically. This will make your function available as long as you included the autoloader:

```<code>{
    "autoload": {
        "files": ["lib/custom/functions.php"]
    }
}
</code>```

Since your functions are namespaced you'll need to import them with the use statement or use the fully qualified name.

If your Web folder contains PSR-4 compatible classes, load them as before with the PSR-4 autoloader (you can define multiple autoloaders in your composer.json).

Title: Composer PSR-4 for php file

Body:
In my project I have a folder lib\custom  which contains Web folder and functions.php file. In my functions.php I have some functions which I need to use in another classes and in this file on the first line I have a defined namespace  look like this

<?php
namespace Custom;

function abc(){....}

And in Web folder I have some classes with namespace Custom\Web;

In my composer.json file I have defined namespace look like this

"Custom\\":"lib/custom/"

So , now I am using the  abc()  look like this

use Custom;
$abc = Custom\abc("abc")

but as a response I am getting

Call to undefined function Custom\abc()

How can I solve this problem?

Body:
PSR-4 describes a specification for autoloading classes from file paths. It doesn't cover loading functions from files.

Use the files autoloader to load a file with functions on each request automatically. This will make your function available as long as you included the autoloader:

{
    "autoload": {
        "files": ["lib/custom/functions.php"]
    }
}

Since your functions are namespaced you'll need to import them with the use statement or use the fully qualified name.

If your Web folder contains PSR-4 compatible classes, load them as before with the PSR-4 autoloader (you can define multiple autoloaders in your composer.json).


来源: stackexchange

问:
Ansible yml copy file from network location
So I have an ansible playbook as follows:

```<code>#WINDOWS#
---
- hosts: windows   tasks:

  - name:  copy file
    raw: '"net use M: "\\somemachinename\someLocation" /user:username password"'
    raw: '"xcopy M:\isntaller.exe C:\installerlocation /Y"'
    raw: '"net use M: /delete /y"'
</code>```

The file does exist at the network location and the username password are valid. The task doesn't report any errors. But the file never gets copied across.

Does anyone know if I am doing the playbook syntax wrong? Or is there a better way to get files across network location in ansible setup?

P.S. I do not have access to the ansible server. Although I know it is a Red Hat Linux server.

答:
Having tried many combinations, this is what finally worked for me. Seems hacky, but possibly helpful to others who may face the same situation.

I added a batch file at a http location where ansible can get it and execute on the machine.

```<code>REM @echo off

set Source=%1%
set Destination=%2%

net use M: \\nwb-somemachinename /user:username password
xcopy /F M:\%Source% %Destination% /Y
net use M: /delete /y
</code>```

And the yml file looks as follows:

```<code>#WINDOWS#
---
- hosts: windows
  tasks:

  - name: get batch file
    raw: httptool.exe http://somelocation/ourbatchfile.bat

  - name: run batch file
    raw: c:\location\ourbatchfile.bat location_remote_machine\installer.exe c:\location
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have an ansible playbook as follows:

#WINDOWS#
---
- hosts: windows   tasks:

  - name:  copy file
    raw: '"net use M: "\\somemachinename\someLocation" /user:username password"'
    raw: '"xcopy M:\isntaller.exe C:\installerlocation /Y"'
    raw: '"net use M: /delete /y"'

The file does exist at the network location and the username password are valid. The task doesn't report any errors. But the file never gets copied across.

Does anyone know if I am doing the playbook syntax wrong? Or is there a better way to get files across network location in ansible setup?

P.S. I do not have access to the ansible server. Although I know it is a Red Hat Linux server.

Body:
Having tried many combinations, this is what finally worked for me. Seems hacky, but possibly helpful to others who may face the same situation.

I added a batch file at a http location where ansible can get it and execute on the machine.

REM @echo off

set Source=%1%
set Destination=%2%

net use M: \\nwb-somemachinename /user:username password
xcopy /F M:\%Source% %Destination% /Y
net use M: /delete /y

And the yml file looks as follows:

#WINDOWS#
---
- hosts: windows
  tasks:

  - name: get batch file
    raw: httptool.exe http://somelocation/ourbatchfile.bat

  - name: run batch file
    raw: c:\location\ourbatchfile.bat location_remote_machine\installer.exe c:\location


问:
Select all records if parameter is null else return specfic item in JPA Criteria query
I am using JPA and I want to write search query for fetching all the records if search field is empty and if search parameter is not null then apply criteria query.

```<code>CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<String> query = cq.from(String.class);
cq.where(cb.equal(query.get("id"), '1234567'));

TypedQuery<String> q = entityManager.createQuery(cq);
List<String> results = q.getResultList();
return results;
</code>```

Thanks

答:
I had a solution finally using Criteria API. Have a look at the code below.</p>

```<code>public List < Object > retrieveAll(Object obj) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery < Object > cq = cb.createQuery(Object.class);
    Root < Object > objQuery = cq.from(Object.class);

    List < Predicate > predicates = new ArrayList < Predicate > ();

    // You can add as many as Predicate you want.
    if (null != obj.getName() && !obj.getName().isEmpty()) {
        predicates.add(cb.equal(objQuery.get("Name"), obj.getName()));
    }

    List < Object > results = new ArrayList < Object > ();
    if (!predicates.isEmpty()) {
        cq.select(objQuery).where(predicates.toArray(new Predicate[] {}));
        cq.orderBy(cb.asc(objQuery.get("Name")));
        results = entityManager.createQuery(cq).getResultList();
    } else {
        results = entityManager.createQuery("from Emplyee ORDER BY Name asc").getResultList();
    }
    return results;
}
</code>```

Body:
I am using JPA and I want to write search query for fetching all the records if search field is empty and if search parameter is not null then apply criteria query.

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<String> cq = cb.createQuery(String.class);
Root<String> query = cq.from(String.class);
cq.where(cb.equal(query.get("id"), '1234567'));

TypedQuery<String> q = entityManager.createQuery(cq);
List<String> results = q.getResultList();
return results;

Thanks

Body:
I had a solution finally using Criteria API. Have a look at the code below.

public List < Object > retrieveAll(Object obj) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery < Object > cq = cb.createQuery(Object.class);
    Root < Object > objQuery = cq.from(Object.class);

    List < Predicate > predicates = new ArrayList < Predicate > ();

    // You can add as many as Predicate you want.
    if (null != obj.getName() && !obj.getName().isEmpty()) {
        predicates.add(cb.equal(objQuery.get("Name"), obj.getName()));
    }

    List < Object > results = new ArrayList < Object > ();
    if (!predicates.isEmpty()) {
        cq.select(objQuery).where(predicates.toArray(new Predicate[] {}));
        cq.orderBy(cb.asc(objQuery.get("Name")));
        results = entityManager.createQuery(cq).getResultList();
    } else {
        results = entityManager.createQuery("from Emplyee ORDER BY Name asc").getResultList();
    }
    return results;
}


问:
How to trigger language in Nuxt js internationalization (i18n) example explanation?
In Nuxt.Js doc, there is an example of internationalization(i18n). I get most part but What I don't get is how clicking on the Language option on the Navbar menu changing the locale from 'en' to 'fr' or vice versa, which triggers the language swapping.

Here is the code: https://nuxtjs.org/examples/i18n

in default layout

```<code><nuxt-link class="Header__Link" v-if="$i18n.locale === 'en'" :to="`/fr` + $route.fullPath" active-class="none" exact>
     {{ $t('links.french') }}
</nuxt-link>
<nuxt-link class="Header__Link" v-else :to="$route.fullPath.replace(/^\/[^\/]+/, '')" active-class="none" exact>
     {{ $t('links.english') }}
</nuxt-link>
</code>```

And here is the live demo: https://i18n.nuxtjs.org/

Anyone please care to explain?

Thanks.

答: It uses vue-i18n. Have a look plugins/i18n.js and middleware/i18n.js. So when accessing /fr/... for example the locale in the store is set to fr.

Body:
In Nuxt.Js doc, there is an example of internationalization(i18n). I get most part but What I don't get is how clicking on the Language option on the Navbar menu changing the locale from 'en' to 'fr' or vice versa, which triggers the language swapping.

Here is the code: https://nuxtjs.org/examples/i18n

in default layout

<nuxt-link class="Header__Link" v-if="$i18n.locale === 'en'" :to="`/fr` + $route.fullPath" active-class="none" exact>
     {{ $t('links.french') }}
</nuxt-link>
<nuxt-link class="Header__Link" v-else :to="$route.fullPath.replace(/^\/[^\/]+/, '')" active-class="none" exact>
     {{ $t('links.english') }}
</nuxt-link>

And here is the live demo: https://i18n.nuxtjs.org/

Anyone please care to explain?

Thanks.


问:
Is there processor/plugin out there that would enforce referential-transparency, immutabiliyt, etc. in Java?
It seems pretty straightforward:
For example, an @Immutable on a class that the processor would then give error if there were any non-final field accesses. It would have to ensure that all collaborators were also immutable.

A @ReferentiallyTransparent (better name?) could be put on methods that would then check to ensure that all calls and collaborators were also marked @RefTrans and @Immutable...

答:
You may be interested by the following paper : Verifiable Functional Purity in Java

Abstract :

Proving that particular methods within a code base are functionally
  pure — deterministic and side-effect free — would aid verification of
  security properties including function invertibility, reproducibility
  of computation, and safety of untrusted code execution. Until now it
  has not been possible to automatically prove a method is functionally
  pure within a high-level imperative language in wide use, such as
  Java. We discuss a technique to prove that methods are functionally
  pure by writing programs in a subset of Java called Joe-E; a static
  verifier ensures that programs fall within the subset. In Joe-E, pure
  methods can be trivially recognized from their method signature. To
  demonstrate the practicality of our approach, we refactor an AES
  library, an experimental voting machine implementation, and an HTML
  parser to use our techniques. We prove that their top-level methods
  are verifiably pure and show how this provides high-level security
  guarantees about these rou- tines. Our approach to verifiable purity
  is an attractive way to permit functional-style reasoning about
  security properties while leveraging the familiarity, convenience, and
  legacy code of imperative languages.

ContentLicense: CC BY-SA 2.5


问:
IllegalArgumentException in ActivityManagerProxy
Issue: ActivityA starts ActivityB with shared element transitions intermittently crashes
Not consistently reproducible
Api levels: 23, 24 and 25

Code to launch activity:

```<code>Intent intent = new Intent(this, ActivityB.class);
Pair<View, String> logoTransition = Pair.create(logo, getString(R.string.transition_logo));
Pair<View, String> logoTextTransition = Pair.create(logoText, getString(R.string.transition_logo_text));
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, logoTransition, logoTextTransition);
ActivityCompat.startActivity(this, intent, options.toBundle());
</code>```

Stacktrace (API 23):

```<code>Exception java.lang.IllegalArgumentException:
android.os.Parcel.readException (Parcel.java:1606)
android.os.Parcel.readException (Parcel.java:1555)
android.app.ActivityManagerProxy.isTopOfTask (ActivityManagerProxy.java:4787)
android.app.Activity.isTopOfTask (Activity.java:5753)
android.app.Activity.cancelInputsAndStartExitTransition (Activity.java:4075)
android.app.Activity.startActivityForResult (Activity.java:4052)
android.app.Activity.startActivity (Activity.java:4312)
android.support.v4.content.ContextCompat.startActivity (ContextCompat.java)
__null__.getDrawable (ContextCompat.java)
__null__.isDeviceProtectedStorage (ContextCompat.java)
com.my.app.activity.ActivityA.startMainActivity (ActivityA.java)
</code>```

Does anyone know what causes this behaviour?
Any proposed fix for this?

答:
in my case this happen because i subscribe on click action two times, so startActivity was called twice in a row.

hope this can be helpful for some one :)

Body:
Issue: ActivityA starts ActivityB with shared element transitions intermittently crashes
Not consistently reproducible
Api levels: 23, 24 and 25

Code to launch activity:

Intent intent = new Intent(this, ActivityB.class);
Pair<View, String> logoTransition = Pair.create(logo, getString(R.string.transition_logo));
Pair<View, String> logoTextTransition = Pair.create(logoText, getString(R.string.transition_logo_text));
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, logoTransition, logoTextTransition);
ActivityCompat.startActivity(this, intent, options.toBundle());

Stacktrace (API 23):

Exception java.lang.IllegalArgumentException:
android.os.Parcel.readException (Parcel.java:1606)
android.os.Parcel.readException (Parcel.java:1555)
android.app.ActivityManagerProxy.isTopOfTask (ActivityManagerProxy.java:4787)
android.app.Activity.isTopOfTask (Activity.java:5753)
android.app.Activity.cancelInputsAndStartExitTransition (Activity.java:4075)
android.app.Activity.startActivityForResult (Activity.java:4052)
android.app.Activity.startActivity (Activity.java:4312)
android.support.v4.content.ContextCompat.startActivity (ContextCompat.java)
__null__.getDrawable (ContextCompat.java)
__null__.isDeviceProtectedStorage (ContextCompat.java)
com.my.app.activity.ActivityA.startMainActivity (ActivityA.java)

Does anyone know what causes this behaviour?
Any proposed fix for this?


问:
Ansible execute script not working
I'm tying to run a .sh command in anisble from a task.

So an server backup module installs a .sh file on a designated linux VM and a run module then runs the .sh file.

When I run the job in jenkins, I see the database_backup.sh file has been installed in /temp which is correct.

However when it comes to run the execute module, nothing happens.

Below is the execute script.

```<code>name: Execute Backup Script

command: ./tmp/database_backup.sh

 become: true

become_user: root
</code>```

Am I missing something from the script?

答:
You should work with absolute paths: (remove the dot in front of /tmp)

```<code>name: Execute Backup Script
command: /tmp/database_backup.sh
become: true
become_user: root
</code>```

Title: Ansible execute script not working

Body:
I'm tying to run a .sh command in anisble from a task.

So an server backup module installs a .sh file on a designated linux VM and a run module then runs the .sh file.

When I run the job in jenkins, I see the database_backup.sh file has been installed in /temp which is correct.

However when it comes to run the execute module, nothing happens.

Below is the execute script.

name: Execute Backup Script

command: ./tmp/database_backup.sh

 become: true

become_user: root

Am I missing something from the script?

Body:
You should work with absolute paths: (remove the dot in front of /tmp)

name: Execute Backup Script
command: /tmp/database_backup.sh
become: true
become_user: root


问:
Corda Error during node deployment
After I ./gradlew deployNodes, I get this error, any clue as to why this is happening?

```<code>* What went wrong:
A problem occurred evaluating project ':java-source'.
Could not find method jcent∫er() for arguments [] on repository container of type org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler.
</code>```

This is what I have in my gradle buildscript, and I believe I am checked out the release 13, but am not sure where to check.

```<code>ext.corda_release_version = '0.13.0'
    ext.corda_gradle_plugins_version = '0.12.4'
    ext.kotlin_version = '1.1.2'
    ext.quasar_version = '0.7.6'
    ext.junit_version = '4.12'
</code>```

Thanks!

答: Looks as if a spurious character has been added to jcent∫er(). Can you do a quick search ?

Title: Corda Error during node deployment

Body:
After I ./gradlew deployNodes, I get this error, any clue as to why this is happening?

* What went wrong:
A problem occurred evaluating project ':java-source'.
Could not find method jcent∫er() for arguments [] on repository container of type org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler.

This is what I have in my gradle buildscript, and I believe I am checked out the release 13, but am not sure where to check.

ext.corda_release_version = '0.13.0'
    ext.corda_gradle_plugins_version = '0.12.4'
    ext.kotlin_version = '1.1.2'
    ext.quasar_version = '0.7.6'
    ext.junit_version = '4.12'

Thanks!


问:
Newbie SQL error; missing expression
Newbie to sql here

I am attempting return sa_id from the query below but I am getting a 'missing expression' error.

```<code>select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in {
      select *
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI'}
    ;
</code>```

The sa_id exists in both tables; ci_sa and ci_intv_pf.

I need the sa_id to have a intv_pf_typ_cd of 'SMPCHGRI' in the ci_intv_pf table.
And I need the matching sa_id to have an sa_type_cd of 'LEURIBIL' from the ci_sa table.

Have tried ending the query with group by and having but not having any luck.

Any help much appreciated

答:
Endorsing Prdp, however, please consider following code that is little bit faster as it reads count instead of values -</p>

```<code>select s.sa_id
from cisadm.ci_sa s
where s.sa_status_flg = '20'
and s.sa_type_cd = 'LEURIBIL'
and exist (
                    select  1
                    from    cisadm.ci_intv_pf pf
                    where   pf.intv_pf_typ_cd = 'SMPCHGRI'
                    and s.sa_id = pf.sa_id
        );
</code>```

Title: Newbie SQL error; missing expression

Body:
Newbie to sql here

I am attempting return sa_id from the query below but I am getting a 'missing expression' error.

select s.sa_id
    from cisadm.ci_sa s
    where s.sa_status_flg = '20'
    and s.sa_type_cd = 'LEURIBIL'
    and s.sa_id in {
      select *
      from cisadm.ci_intv_pf pf
      where pf.intv_pf_typ_cd = 'SMPCHGRI'}
    ;

The sa_id exists in both tables; ci_sa and ci_intv_pf.

I need the sa_id to have a intv_pf_typ_cd of 'SMPCHGRI' in the ci_intv_pf table.
And I need the matching sa_id to have an sa_type_cd of 'LEURIBIL' from the ci_sa table.

Have tried ending the query with group by and having but not having any luck.

Any help much appreciated

Body:
Endorsing Prdp, however, please consider following code that is little bit faster as it reads count instead of values -

select s.sa_id
from cisadm.ci_sa s
where s.sa_status_flg = '20'
and s.sa_type_cd = 'LEURIBIL'
and exist (
                    select  1
                    from    cisadm.ci_intv_pf pf
                    where   pf.intv_pf_typ_cd = 'SMPCHGRI'
                    and s.sa_id = pf.sa_id
        );


问:
Where can i find a how-to for writing a wagon for maven 3?
Maven has changed from version 2 to 3 and so it has changed the ioc container from plexus to google guice.

So my wagon (to download artifacts from sourceforge file release area) for maven 2 must be rewritten to maven 3 to satisfy guice.
Is there a tutorial / api description / to learn how to change from plexus wagon to guice wagon?

答: org.sonatype.aether.connector.wagon.WagonRepositoryConnector is a good example to use wagon in maven 3</p>


问:
What are some valid use cases for using stack and queue in Java?
I am studying this part of collections in Java, but I'm still confused about when I should use them?  What are some valid use cases where they are the best option to use?</p>

答:
You've been to a cafeteria, right? and seen a stack of plates? When a clean plate is added to the stack, it is put on top. When a plate is removed, it is removed from the top. So it is called Last-In-First-Out (LIFO). A computer stack is like that, except it holds numbers, and you can make one out of an array or a list, if you like. (If the stack of plates has a spring underneath, they say you "push" one onto the top, and when you remove one you "pop" it off. That's where those words come from.)

In the cafeteria, go in back, where they wash dishes. They have a conveyor-belt where they put plates to be washed in one end, and they come out the other end, in the same order. That's a queue or First-In-First-Out (FIFO). You can also make one of those out of an array or a list if you like.

What are they good for? Well, suppose you have a tree data structure (which is like a real tree made of wood except it is upside down), and you want to write a program to walk completely through it, so as to print out all the leaves.

One way is to do a depth-first walk. You start at the trunk and go to the first branch, and then go to the first branch of that branch, and so on, until you get to a leaf, and print it. But how do you back up to get to the next branch? Well, every time you go down a branch, you "push" some information in your stack, and when you back up you "pop" it back out, and that tells you which branch to take next. That's how you keep track of which branch to do next at each point.

Another way is a breadth-first walk. Starting from the trunk, you number all the branches off the trunk, and put those numbers in the queue. Then you take a number out the other end, go to that branch, and for every branch coming off of it, you again number them (consecutively with the first) and put those in the queue. As you keep doing this you are going to visit first the branches that are 1 branch away from the trunk. Then you are going to visit all the branches that are 2 branches away from the trunk, and so on. Eventually you will get to the leaves and you can print them.

These are two very basic concepts in programming.  [Copied]

ContentLicense: CC BY-SA 4.0


问:
GOOGLE_APPLICATION_CREDENTIALS error
I am trying to use the google speech API for converting an audio file to text, but facing some problems with the documentation.I have enabled the speech API and created an service account file. I also got the service account credentials activated. Then I wrote the following command to retrieve the authorization token using my service account.

gcloud auth application-default print-access-token

But it is returning this message

I don't understand why this is happening because I already have an VM instance created in my Compute Engine. Can anybody explain where am I going wrong with this? Also, is there any other way to authenticate my account and call the google speech API?

答:
gcloud credentials and and application default credentials are managed separately. If you activated service account key file this only can be used for gcloud commands but not for application default credentials.

gcloud auth application-default set of commands are there only to manage application default and having nothing to do with commands in gcloud auth.

There a few ways to "activate" application default credentials:

Use your user account

Run gcloud auth application-default login, or

Use service account (preferred)

set environment variable GOOGLE_APPLICATION_CREDENTIALS=path/to/your/service_accont_key_file.json

copy path/to/your/service_accont_key_file.json to ~/.config/gcloud/application_default_credentials.json`

On windows this might be different, run

```<code>gcloud info --format="value(config.paths.global_config_dir)"
</code>```

to get a path to your config directory.

now command like

```<code>gcloud auth application-default print-access-token
</code>```

should work.

Title: GOOGLE_APPLICATION_CREDENTIALS error

Body:
gcloud credentials and and application default credentials are managed separately. If you activated service account key file this only can be used for gcloud commands but not for application default credentials.

gcloud auth application-default set of commands are there only to manage application default and having nothing to do with commands in gcloud auth.

There a few ways to "activate" application default credentials:

Use your user account

Run gcloud auth application-default login, or

Use service account (preferred)

set environment variable GOOGLE_APPLICATION_CREDENTIALS=path/to/your/service_accont_key_file.json

copy path/to/your/service_accont_key_file.json to ~/.config/gcloud/application_default_credentials.json`

On windows this might be different, run

gcloud info --format="value(config.paths.global_config_dir)"

to get a path to your config directory.

now command like

gcloud auth application-default print-access-token

should work.


问:
Binary coded decimal (BCD) to Hexadecimal conversion
can someone explain to me how to convert BCD to Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal.
Thanks.</p>

答: I'd create a table of 256 entries, mapping all BCD bytes into their binary equivalent; you can then use hex printing of your programming language.</p>


问:
does false sharing occur when data is read in openmp?
If I have a C++ program with OpenMP parallelization, where different threads constantly use some small shared array only for reading data from it, does false sharing occur in this case? in other words, is false sharing related only to memory write operations, or it can also happen with memory read operations.

答:
False sharing is a performance issue because it causes additional movement of a cache line which takes time. When two variables which are not really shared reside in the same line and separate threads update each of them, the line has to bounce around the machine which increases the latency of each access. In this case if the variables were in separate lines each thread would keep a locally modified copy of "its" line and no data movement would be required.

However, if you are not updating a line, then no data movement is necessary and there is no performance impact from the sharing beyond the fact that you might have been able to have data each thread does need in there, rather than data it doesn't. That is a small, second order, effect. though. So unless you know you are cache capacity limited ignore it!


问:
Email Alerts when service or server automatically comes up
I am working on a bash script that helps to ping and get the network interface level status of the host machines and services.
This script will send a email alerts in case of failure.

```<code>#!/bin/bash
HOSTS="192.168.8.200"
COUNT=4
for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
    echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail    -s “Mail       subject” anymail@anydomain.com

  fi
done
</code>```

This works fine.
But need help to get a one single email alert when host automatically comes up (ping success).

答:
You need to save the state of the host (up/down) during the calls of your script.
if the host is "up" and the former state was "down" then you need to send an email.
You can just write the result of the "check command" to a file in /tmp/
if the check returns that the server is up you read the content of the file. if the state is "down" in the file, then send an email an write "up" to the file.
on the next check if the server is up, there will be no additional email sent, because the server was also "up" before.

```<code>#!/bin/bash
HOSTS="192.168.8.200 192.168.8.201 192.168.122.1"
COUNT=4
STATE="/tmp/ping_state.txt"

for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
    #echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail    -s “Mail       subject” anymail@anydomain.com
     echo "host $myHost down"
    #delete all previous entries of that ip
    sed -i "/$myHost/d" $STATE
    #mark host as down
    echo "$myHost - down" >> $STATE
  else
    CHECK=`grep "$myHost" $STATE | grep -o "down"`
    if [ "$CHECK" = "down" ]; then
      echo "host $myHost up again"
      #insert email for host up here
    fi

    #delete all previous entries of that ip
    sed -i "/$myHost/d" $STATE
    echo "$myHost - up" >> $STATE
  fi
done
</code>```

for simple testing I just used an echo statement instead of sending an email.

Body:
I am working on a bash script that helps to ping and get the network interface level status of the host machines and services.
This script will send a email alerts in case of failure.

#!/bin/bash
HOSTS="192.168.8.200"
COUNT=4
for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
    echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail    -s “Mail       subject” anymail@anydomain.com

  fi
done

This works fine.
But need help to get a one single email alert when host automatically comes up (ping success).

Body:
You need to save the state of the host (up/down) during the calls of your script.
if the host is "up" and the former state was "down" then you need to send an email.
You can just write the result of the "check command" to a file in /tmp/
if the check returns that the server is up you read the content of the file. if the state is "down" in the file, then send an email an write "up" to the file.
on the next check if the server is up, there will be no additional email sent, because the server was also "up" before.

#!/bin/bash
HOSTS="192.168.8.200 192.168.8.201 192.168.122.1"
COUNT=4
STATE="/tmp/ping_state.txt"

for myHost in $HOSTS
do
  count=$(ping -c $COUNT $myHost | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
    #echo -e "HOST:$myHost is down (ping failed) at $(date)" | mailx -A gmail    -s “Mail       subject” anymail@anydomain.com
     echo "host $myHost down"
    #delete all previous entries of that ip
    sed -i "/$myHost/d" $STATE
    #mark host as down
    echo "$myHost - down" >> $STATE
  else
    CHECK=`grep "$myHost" $STATE | grep -o "down"`
    if [ "$CHECK" = "down" ]; then
      echo "host $myHost up again"
      #insert email for host up here
    fi

    #delete all previous entries of that ip
    sed -i "/$myHost/d" $STATE
    echo "$myHost - up" >> $STATE
  fi
done

for simple testing I just used an echo statement instead of sending an email.


问:
NLog get messages in C#
I am recently using Nlog in an ASP.Net project for a client with good success. I need to connect to an existing application that has its own event log management and provide them with a copy of my log information.

Is there any way to get the strings that I provided to Nlog using any of the log functions?

Example:

```<code>logger.Info("My info");
logger.Debug("My debug");
logger.Error("My error");
logger.Warn("My warn");
List<string> messages = logger.getStrings() <-- this is what I need
</code>```

How I can get strings "My info", "My debug", "My error" and "My warn" as an array or List<>?

答:
You could use the MemoryTarget for it:

nlog.config:

<nlog internalLogFile="c:\tempp\nlog-internal.log" internalLogLevel="Info">
    <targets>
        <target xsi:type="Memory" name="target1" layout="${message}" />
    </targets>
    <rules>
        <logger name="*" writeTo="target1" />
    </rules>
</nlog>
```

<p>C#:</p>

<pre class="lang-cs prettyprint-override"><code>var target = LogManager.Configuration.FindTargetByName<MemoryTarget>("target1");
IList<string> messages = target.Logs;
</code>```

The messages are strings, rendered from the layout attribute in nlog.config

API docs for MemoryTarget

If you need to write them to another component, I would recommend to create a custom target

Title: NLog get messages in C#

Body:
I am recently using Nlog in an ASP.Net project for a client with good success. I need to connect to an existing application that has its own event log management and provide them with a copy of my log information.

Is there any way to get the strings that I provided to Nlog using any of the log functions?

Example:

logger.Info("My info");
logger.Debug("My debug");
logger.Error("My error");
logger.Warn("My warn");
List<string> messages = logger.getStrings() <-- this is what I need

How I can get strings "My info", "My debug", "My error" and "My warn" as an array or List<>?

Body:
You could use the MemoryTarget for it:

nlog.config:

<nlog internalLogFile="c:\tempp\nlog-internal.log" internalLogLevel="Info">
    <targets>
        <target xsi:type="Memory" name="target1" layout="${message}" />
    </targets>
    <rules>
        <logger name="*" writeTo="target1" />
    </rules>
</nlog>

C#:

var target = LogManager.Configuration.FindTargetByName<MemoryTarget>("target1");
IList<string> messages = target.Logs;

The messages are strings, rendered from the layout attribute in nlog.config

API docs for MemoryTarget

If you need to write them to another component, I would recommend to create a custom target


问:
Mocking methods from different class than tested one
I have an issue with writing a unit test for one of my methods. It calls a method from a different class and to make it worse it makes some processing depending on a server connection so I would need to mock it somehow however I couldn't find an answer how to do that. I also want to point that tested method does not take this different class object as a parameter but is instantiating it within itself so it looks something like this:

```<code>public class Class1 {
    public MyEnum method1(String myString){
        Class2 class2 = new Class2();
        return class2.method2(myString);
    }
}
public class Class2 {
    public MyEnum method2(String myString){
       //returns some value after communication with a server
    }
}
</code>```

So basically I would need to mock method2 return value however as it's class is instantiated inside the method1 I can't see a way to do that. Is there any way of testing that without the actual server connection?

答:
As a rule of thumb your unit test should test only one class, everything else should be mocked.

As a rule of good design all dependencies should be injectable, i.e. your Class2 should not be instantiated inside your Class1 (and definitely not inside a method in this class as it creates a fresh instance every time the method is called).

If any of the above rules are broken you should consider rewriting the code.

Body:
I have an issue with writing a unit test for one of my methods. It calls a method from a different class and to make it worse it makes some processing depending on a server connection so I would need to mock it somehow however I couldn't find an answer how to do that. I also want to point that tested method does not take this different class object as a parameter but is instantiating it within itself so it looks something like this:

public class Class1 {
    public MyEnum method1(String myString){
        Class2 class2 = new Class2();
        return class2.method2(myString);
    }
}
public class Class2 {
    public MyEnum method2(String myString){
       //returns some value after communication with a server
    }
}

So basically I would need to mock method2 return value however as it's class is instantiated inside the method1 I can't see a way to do that. Is there any way of testing that without the actual server connection?


问:
How can I add a trigger to a label using C# instead of XAML?
Here is the XAML code that I have:

```<code><Label x:Name="faveLabel" FontFamily="FontAwesome"
   XAlign="Center" FontSize="23">
   <Label.Triggers>
      <DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="true">
         <Setter Property="TextColor" Value="Red"/>
      </DataTrigger>
      <DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="false">
         <Setter Property="TextColor" Value="Gray"/>
      </DataTrigger>
   </Label.Triggers>
</Label>
</code>```

What I would like to do is to change this to C#

```<code>        var label = new Label ()
        {
            FontFamily = "FontAwesome",
            HorizontalTextAlignment = TextAlignment.Center,
            FontSize = 23,
        }

        var labelTrigger = new DataTrigger(label)
        {
            Target

        }
</code>```

I tried starting to do this below but soon after just defining the outer label I realized I do not know how to define the trigger. Can anyone give me advice on how I can do this?

答:
I didn't test this, but this should bring you on the right track:

```<code>// Trigger for Favorite = true
DataTrigger triggerTrue = new DataTrigger(typeof(Label));
triggerTrue.Value = true;
triggerTrue.Binding = new Binding() { Path = "Favorite" };
Setter setterTrue = new Setter();
setterTrue.Property = Label.TextColorProperty;
setterTrue.Value = Color.Red;
triggerTrue.Setters.Clear();
triggerTrue.Setters.Add(setterTrue);
label.Triggers.Add(triggerTrue);

// Trigger for Favorite = false
DataTrigger triggerFalse = new DataTrigger(typeof(Label));
triggerFalse.Value = false;
triggerFalse.Binding = new Binding() { Path = "Favorite" };
Setter setterFalse = new Setter();
setterFalse.Property = Label.TextColorProperty;
setterFalse.Value = Color.Red;
triggerFalse.Setters.Clear();
triggerFalse.Setters.Add(setterFalse);
label.Triggers.Add(triggerFalse);
</code>```

source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/797753f4-5db2-4852-a9fb-1ed989fe6413/add-datatrigger-programmatically?forum=wpf

Body:
Here is the XAML code that I have:

      <DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="true">
         <Setter Property="TextColor" Value="Red"/>
      </DataTrigger>
      <DataTrigger TargetType="Label" Binding="{Binding Favorite}" Value="false">
         <Setter Property="TextColor" Value="Gray"/>
      </DataTrigger>

What I would like to do is to change this to C#

        var label = new Label ()
        {
            FontFamily = "FontAwesome",
            HorizontalTextAlignment = TextAlignment.Center,
            FontSize = 23,
        }

        var labelTrigger = new DataTrigger(label)
        {
            Target

        }

I tried starting to do this below but soon after just defining the outer label I realized I do not know how to define the trigger. Can anyone give me advice on how I can do this?

Body:
I didn't test this, but this should bring you on the right track:

// Trigger for Favorite = true
DataTrigger triggerTrue = new DataTrigger(typeof(Label));
triggerTrue.Value = true;
triggerTrue.Binding = new Binding() { Path = "Favorite" };
Setter setterTrue = new Setter();
setterTrue.Property = Label.TextColorProperty;
setterTrue.Value = Color.Red;
triggerTrue.Setters.Clear();
triggerTrue.Setters.Add(setterTrue);
label.Triggers.Add(triggerTrue);

// Trigger for Favorite = false
DataTrigger triggerFalse = new DataTrigger(typeof(Label));
triggerFalse.Value = false;
triggerFalse.Binding = new Binding() { Path = "Favorite" };
Setter setterFalse = new Setter();
setterFalse.Property = Label.TextColorProperty;
setterFalse.Value = Color.Red;
triggerFalse.Setters.Clear();
triggerFalse.Setters.Add(setterFalse);
label.Triggers.Add(triggerFalse);

source: https://social.msdn.microsoft.com/Forums/vstudio/en-US/797753f4-5db2-4852-a9fb-1ed989fe6413/add-datatrigger-programmatically?forum=wpf


问:
Running the same SQL script on different tables
I have a manually created conversion script that changes a product ID to another. It does it for a thousand products and I need to run it on 10 different tables. Can I do it without duplicating the script?

I hoped to do it like this, but it is not supported:

convert_one.sql:

```<code>UPDATE @table SET product_id=12345 where product_id=123
... a thousand similar lines
</code>```

convert_all.sql:

```<code>SET @table = 'table1';
SOURCE convert_one.sql;

SET @table = 'table2';
SOURCE convert_one.sql;
</code>```

答:
You have to use prepared statements. Otherwise your variable is simply treated like a string and you can't select from or update a string.

Try it like this:

```<code>SET @table = 'table1';
PREPARE stmt FROM CONCAT('UPDATE ', @table, ' SET product_id=12345 where product_id=123;');
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

Body:
I have a manually created conversion script that changes a product ID to another. It does it for a thousand products and I need to run it on 10 different tables. Can I do it without duplicating the script?

I hoped to do it like this, but it is not supported:

convert_one.sql:

UPDATE @table SET product_id=12345 where product_id=123
... a thousand similar lines

convert_all.sql:

SET @table = 'table1';
SOURCE convert_one.sql;

SET @table = 'table2';
SOURCE convert_one.sql;

Body:
You have to use prepared statements. Otherwise your variable is simply treated like a string and you can't select from or update a string.

Try it like this:

SET @table = 'table1';
PREPARE stmt FROM CONCAT('UPDATE ', @table, ' SET product_id=12345 where product_id=123;');
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


问:
Java Static
Duplicate: What does the 'static' keyword do in a class?

I've read this post already.

What does the "static" keyword in a method do?

I remember being told that static != clingy...but that is pretty much all I know about this keyword.

答:
Static class variables can be thought of as a global class.  No matter how many instances of the class you have, there is just one instance of each static variable.

Static methods don't use any non-static class variables and they can be called directly from outside of the class without having to instantiate the class itself.

OwnerDisplayName: koldfyre

Title: Java Static

LastEditorDisplayName: nemo

OwnerDisplayName: Starkii


问:
How to get current function into a variable?
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

```<code>import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])
</code>```

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

答:
OK after reading the question and comments again, I think this is a decent test case:

```<code>def foo(n):
  """ print numbers from 0 to n """
  if n: foo(n-1)
  print n

g = foo    # assign name 'g' to function object
foo = None # clobber name 'foo' which refers to function object
g(10)      # dies with TypeError because function object tries to call NoneType
</code>```

I tried solving it by using a decorator to temporarily clobber the global namespace and reassigning the function object to the original name of the function:

```<code>def selfbind(f):
   """ Ensures that f's original function name is always defined as f when f is executed """
   oname = f.__name__
   def g(*args, **kwargs):

      # Clobber global namespace
      had_key = None
      if globals().has_key(oname):
         had_key = True
         key = globals()[oname]
      globals()[oname] = g

      # Run function in modified environment
      result = f(*args, **kwargs)

      # Restore global namespace
      if had_key:
         globals()[oname] = key
      else:
         del globals()[oname]

      return result

   return g

@selfbind
def foo(n):
   if n: foo(n-1)
   print n

g = foo   # assign name 'g' to function object
foo = 2   # calling 'foo' now fails since foo is an int
g(10)     # print from 0..10, even though foo is now an int
print foo # prints 2 (the new value of Foo)
</code>```

I'm sure I haven't thought through all the use cases. The biggest problem I see is the function object intentionally changing what its own name points to (an operation which would be overwritten by the decorator), but that should be ok as long as the recursive function doesn't redefine its own name in the middle of recursing.

Still not sure I'd ever need to do this, but thinking about was interesting.

Body:
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

Body:
OK after reading the question and comments again, I think this is a decent test case:

def foo(n):
  """ print numbers from 0 to n """
  if n: foo(n-1)
  print n

g = foo    # assign name 'g' to function object
foo = None # clobber name 'foo' which refers to function object
g(10)      # dies with TypeError because function object tries to call NoneType

I tried solving it by using a decorator to temporarily clobber the global namespace and reassigning the function object to the original name of the function:

def selfbind(f):
   """ Ensures that f's original function name is always defined as f when f is executed """
   oname = f.__name__
   def g(*args, **kwargs):

      # Clobber global namespace
      had_key = None
      if globals().has_key(oname):
         had_key = True
         key = globals()[oname]
      globals()[oname] = g

      # Run function in modified environment
      result = f(*args, **kwargs)

      # Restore global namespace
      if had_key:
         globals()[oname] = key
      else:
         del globals()[oname]

      return result

   return g

@selfbind
def foo(n):
   if n: foo(n-1)
   print n

g = foo   # assign name 'g' to function object
foo = 2   # calling 'foo' now fails since foo is an int
g(10)     # print from 0..10, even though foo is now an int
print foo # prints 2 (the new value of Foo)

I'm sure I haven't thought through all the use cases. The biggest problem I see is the function object intentionally changing what its own name points to (an operation which would be overwritten by the decorator), but that should be ok as long as the recursive function doesn't redefine its own name in the middle of recursing.

Still not sure I'd ever need to do this, but thinking about was interesting.


问:
SQL Server Profiler: How to inspect/understand the duration for the Audit Logout event in more detail?
I am profiling some MS SQL queries with the SQL Server Profiler for my C# Application that I develop with Visual Studio and IIS Express:

The duration that is given for the event "Audit Logout" (16876 ms) is the total time between login and logout. The duration for the query is only 60 ms.

Login/Logout events are related to the setting up / tearing down.

From What is "Audit Logout" in SQL Server Profiler?

I would like to understand the time difference of 16816 ms (= 16876 ms - 60ms) in more detail.

a) Is it possible to log more events (like a "debug mode")?

b) Is it right to assume that the time difference is only due to tearing down because the end time of the "Audit Login" event is the same as the start time of the query execution?

c) Is there some other tool for analyzing (setup and) tear down times?

d) Does the time difference depend on my query? With other words: would  an optimization of the query also help to reduce that time difference?

What I observed so far for @DevTime is that it makes a difference if I start my application the first time (IIS Express is started by Visual Studio, the database is created using the entity framework, example data is written to the database) or if I start it the second time when the database already exists.

For a login after the first start the time difference is about 15 s larger than for a login after the second start. The query that is marked in the example above is executed after user login. Therefore I would expect that the initialization of the database already has been finished at that time and that the initialization would not have any effect on the time difference. Nevertheless it seems to have an influence.

Some related articles:

What is "Audit Logout" in SQL Server Profiler?

Fixing slow initial load for IIS

SQL Server audit logout creates huge number of reads

https://learn.microsoft.com/de-de/sql/relational-databases/event-classes/audit-logout-event-class

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/84ecfe9e-ff0e-4fc5-962b-cffdcbc619ee/audit-logout-event-seems-slow-on-occasion?forum=sqldatabaseengine

答:
When starting the SQL Profiler a window Trace Properties is shown.
The second tab Events Selection is the place where the considered events can be selected.

Activate the option Show all events.

Enable for example the option "Showplan XML FOR Query Compile" under the section "Performance" to log more events.

Also see How to determine what is compiling in SQL Server


问:
Not able to install angularfire2 via npm
I am trying to install angularfire2 from npm by running, but I keep getting this error</p>

```<code>D:\angular\firebase\apartment>npm install angularfire2 firebase --save
apartment@0.0.0 D:\angular\firebase\apartment
+-- angularfire2@4.0.0-rc.1
`-- firebase@4.1.3

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/common@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/compiler@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/core@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/platform-browser@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/platform-browser-dynamic@^4.0.0 but none was installed.
</code>```

答:
Last 5 of npm warn's are due to dependencies. You don't have the required modules to install angularfire. </p>

<p>Two possible solutions are, either downgrade your npm i.e. lower than 3.
npm < 3 can download the depending modules by itself or install the 5  depending modules first. </p>

Body:
I am trying to install angularfire2 from npm by running, but I keep getting this error

D:\angular\firebase\apartment>npm install angularfire2 firebase --save
apartment@0.0.0 D:\angular\firebase\apartment
+-- angularfire2@4.0.0-rc.1
`-- firebase@4.1.3

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/common@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/compiler@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/core@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/platform-browser@^4.0.0 but none was installed.
npm WARN angularfire2@4.0.0-rc.1 requires a peer of @angular/platform-browser-dynamic@^4.0.0 but none was installed.

Body:
Last 5 of npm warn's are due to dependencies. You don't have the required modules to install angularfire.

Two possible solutions are, either downgrade your npm i.e. lower than 3.
npm < 3 can download the depending modules by itself or install the 5  depending modules first.


问:
phpMyAdmin can't connect to remote sever on Windows 7 from Linux client
I cannot connect to mysql server on Windows 7 from my phpMyAdmin on Linux machine.

I've configured phpMyAdmin by modifying common.inc.php.
I've added at the bottom of common.inc.php the following lines:

```<code>$i=2;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
$i++;
</code>```

I see a drop down menu with remote server listed, but when I selected a remote server phphMyAdmin returns to localhost and it doesn't connect to remote without error messages.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

The versions are:

```<code>PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)
</code>```

The request is initiated from the post
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
where I have entered a request regarding the configuration of phpMyAdmin

答: Using the port number in the 'host' directive is not supported. Use the '$cfg['Servers'][$i]['port']' directive to indicate the port number. https://docs.phpmyadmin.net/en/latest/config.html#cfg_Servers_port</p>

Body:
I cannot connect to mysql server on Windows 7 from my phpMyAdmin on Linux machine.

I've configured phpMyAdmin by modifying common.inc.php.
I've added at the bottom of common.inc.php the following lines:

$i=2;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
$i++;

I see a drop down menu with remote server listed, but when I selected a remote server phphMyAdmin returns to localhost and it doesn't connect to remote without error messages.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

The versions are:

PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)

The request is initiated from the post
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
where I have entered a request regarding the configuration of phpMyAdmin


问:
Generate date range in between 2 dates
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

```<code>2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...
</code>```

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

```<code>;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]
</code>```

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

```<code>Select *
From (
    TheQuery
) as t1
</code>```

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

答:
```<code>DECLARE @fromdate DATE
DECLARE @todate DATE
DECLARE @tcaldate Table (CalenderDate Date);

set @fromdate='2017-04-17'
set @todate='2017-05-13'

INSERT INTO @tcaldate SELECT  TOP (DATEDIFF(DAY, @fromdate, @todate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @fromdate)
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

Select * from @tcaldate
</code>```

Hope this helps...

Title: Generate date range in between 2 dates

Body:
for the last couple of hours I have been breaking my head over this.

I want to create a result set which contains a series of dates like this:

2011-07-05
2011-07-04
2011-07-03
2011-07-02
2011-07-01
2011-06-30
2011-06-29
2011-06-28
...

Ideally between 2 dates given. But If I can say the last 30 days or the last 100 days from now that would be fine also.

Normally I would this with a CTE like this

;WITH Dates AS
(
    SELECT CONVERT(DATE, GETDATE()) [Date]
    UNION ALL
    SELECT DATEADD(DAY,-1, [Date])
    FROM Dates
    WHERE [Date] > DATEADD(DAY, -30, CONVERT(DATE, GETDATE()))
)
SELECT [Date]

But I am not allowed to use any statements that can't be executed in a subquery. The program I am using executes queries like this:

Select *
From (
    TheQuery
) as t1

This means I can't use declares, no stored procedures, no CTEs..

Is there any way I can obtain the dataset I need with these limitations?

I am using azure SQL

Body:
DECLARE @fromdate DATE
DECLARE @todate DATE
DECLARE @tcaldate Table (CalenderDate Date);

set @fromdate='2017-04-17'
set @todate='2017-05-13'

INSERT INTO @tcaldate SELECT  TOP (DATEDIFF(DAY, @fromdate, @todate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @fromdate)
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

Select * from @tcaldate

Hope this helps...


问:
PowerShell length function
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}
```

<p>Loop is not working, it was working till yesterday.</p>

```Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'
```

答:
Try this:

```<code>$a = "test" | out-File C:\temp\text1.txt
</code>```

if you call $a back it has no value

With this:

```<code>$a = "test"

Set-Content -Value $a -Path C:\temp\text1.txt
or
$a | Out-File C:\temp\text1.txt
</code>```

$a has the value test

You need to store your value in a variable and then output it to a file or use Tee-Object as JosefZ suggested.

Title: PowerShell length function

Body:
Just yesterday I posted a question for getting the length of a text file. It was working perfectly. I haven't changed anything, but still I am unable to get the length of $select1.

Param([string]$servername)

$filePath1 = "D:\temp\result.txt"

try {
  $SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection

  $SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
  #write-host $SqlConnection.ConnectionString
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $version = $DataSet.Tables[0].rows[0].Column1
  #Write-Host $version
  $DataSet.Tables[0] | Out-File "C:\temp\version.csv"

  switch -exact ($version) {
    '8'  {$version = 80}    # SQL Server 2000 =  8.00.xxxx
    '9'  {$version = 90}    # SQL Server 2005 =  9.00.xxxx
    '10' {$version = 100}   # SQL Server 2008 = 10.00.xxxx
    '11' {$version = 110}   # SQL Server 2012 = 11.00.xxxx
    '12' {$version = 120}   # SQL Server 2014 = 12.00.xxxx
    '13' {$version = 130}   # SQL Server 2016 = 13.00.xxxx
  }

  Write-Host $version
  $filePath="C:\Program Files\Microsoft SQL Server\$version\Setup Bootstrap\Log\Summary.txt"
  Write-Host $filePath

  $select = Select-String -Pattern "Final result:" -Path $filePath #| Out-File c:\pattern.txt
  $select1 = Select-String -Pattern "Final result:" -Path $filePath | Out-File D:\temp\pattern.txt

  Write-Host($select1.Line.Length)
  Write-Host($select1.Matches.Count)

  if ($select1.Line.Length -gt 0) {
  #   Write-Host 'Contains String'
    $select2 = Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
    Write-Host($select2.Line.Length)
    if ($select2.Line.Length -gt 0) {
      Out-File -FilePath $filePath1
      'Success'| Out-File -FilePath $filePath1
    } else {
      Out-File -FilePath $filePath1
      'failed'| Out-File -FilePath $filePath1
    }
  } else {
    Write-Host 'Does not contain String'
  }
} catch {
  Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
  $errText =  $Error[0].ToString()

  if ($errText.Contains("network-related")) {
    Write-Host "Connection Error. Check server name, port, firewall."
  }

  Write-Host $errText
  continue
}

Loop is not working, it was working till yesterday.

Write-Host($select1.Line.Length)
Write-Host($select1.Matches.Count)

if($select1.Line.Length -gt 0) {
#  Write-Host 'Contains String'

Body:
Try this:

$a = "test" | out-File C:\temp\text1.txt

if you call $a back it has no value

With this:

$a = "test"

Set-Content -Value $a -Path C:\temp\text1.txt
or
$a | Out-File C:\temp\text1.txt

$a has the value test

You need to store your value in a variable and then output it to a file or use Tee-Object as JosefZ suggested.


问:
Selecting row with multiple parameters (ajax and PHP)
Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?

AJAX (Jquery):

```<code>function readLine(name, firstname) {
$.ajax({
        type: "post",
        url: "./php/readLine.php",
        dataType: 'json',
        data: { name: name, firstname: firstname },
        success: function(data) {
         console.log(data);
        }
        error: function(data) {
         console.log("An error occured!");
        }
});
}
</code>```

PHP:

```<code><?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
  die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
  $to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>
</code>```

Thanks for your help.

答:
```<code>$stmt = $con->prepare("SELECT * FROM table1 WHERE name=? and firstname=?");
$stmt->bind_param($name ,$firstname);

// set parameters and execute
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$name = mysqli_real_escape_string($con, $_POST['name']);
$stmt->execute();
$stmt->bind_result($to_encode);

$stmt->fetch();

echo json_encode($to_encode);
</code>```

Body:
Good Day,
I'm new to PHP/MySQL and I try to send a request from ajax and select a row in a database with multiple parameters.
Is this the good way to do that ?

AJAX (Jquery):

function readLine(name, firstname) {
$.ajax({
        type: "post",
        url: "./php/readLine.php",
        dataType: 'json',
        data: { name: name, firstname: firstname },
        success: function(data) {
         console.log(data);
        }
        error: function(data) {
         console.log("An error occured!");
        }
});
}

PHP:

<?php
$sql = "SELECT * FROM table1 WHERE firstname=".intval($_POST['firstname'])." AND name=".intval($_POST['name']);
$con = mysqli_connect("localhost", "root", "", "myDB");
if (!$con) {
  die("Connection failed: " . mysqli_error($con));
}
$result = mysqli_query($con, $sql);
$to_encode = array();
while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
  $to_encode[] = $row;
}
echo json_encode($to_encode);
mysqli_close($con);
?>

Thanks for your help.


问:
python2.7: dataframe date_format="%Y-%m-%d" doesn't work
I want the dataframe as following, saved as csv file, and datetime index format is
"%Y-%m-%d".

```<code>    date       price_am   price_pm
2017-06-01       E      E
2017-06-02       D      E
2017-06-03       C       D
</code>```

I used the following code, and it doesn't work:

```<code>df.to_csv('move.csv', date_format='%Y-%m-%d')
</code>```

But when I opened saved cvs file, the datetime format is shown as following:

```<code>     date         price_am    price_pm
    2017/6/1         E      E
    2017/6/2         D      E
    2017/6/3         C       D
</code>```

How to change datatime format index in the csv file. Thanks!

```<code><class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2011-01-01 to 2017-12-31
Data columns (total 2 columns):
price_am    2527 non-null object
price_pm    2526 non-null object
dtypes: object(2)
memory usage: 59.9+ KB
</code>```

答:
It looks like you verify data in Excel - original dates are changed.

Try some text editor like Notepad++ - csv file data are correct.

If use default options:

```<code>print (df.head().to_csv())
date,price_am,price_pm
2017-06-01,E,E
2017-06-02,D,E
2017-06-03,C,D
</code>```

Body:
I want the dataframe as following, saved as csv file, and datetime index format is
"%Y-%m-%d".

    date       price_am   price_pm
2017-06-01       E      E
2017-06-02       D      E
2017-06-03       C       D

I used the following code, and it doesn't work:

df.to_csv('move.csv', date_format='%Y-%m-%d')

But when I opened saved cvs file, the datetime format is shown as following:

     date         price_am    price_pm
    2017/6/1         E      E
    2017/6/2         D      E
    2017/6/3         C       D

How to change datatime format index in the csv file. Thanks!

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2557 entries, 2011-01-01 to 2017-12-31
Data columns (total 2 columns):
price_am    2527 non-null object
price_pm    2526 non-null object
dtypes: object(2)
memory usage: 59.9+ KB

Body:
It looks like you verify data in Excel - original dates are changed.

Try some text editor like Notepad++ - csv file data are correct.

If use default options:

print (df.head().to_csv())
date,price_am,price_pm
2017-06-01,E,E
2017-06-02,D,E
2017-06-03,C,D


问:
Catch-all or error routes in Sammy.js
Is it possible to define a catch-all route or an error route in Sammy.js? I know I can bind to 'error' but if no route matches that does not seem to be triggered.

Thanks!

答:
According to the documentation for Sammy routes,

Paths can be defined as strings or
  regular expressions.

As such, it should be possible to create a route like this, at the end of your routes, that is a catch-all:

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

Title: Catch-all or error routes in Sammy.js

Body:
According to the documentation for Sammy routes,

Paths can be defined as strings or
  regular expressions.

As such, it should be possible to create a route like this, at the end of your routes, that is a catch-all:

get(/.*/, function() {
  ...
});


答:
You have the vegan library with metaMDS function that generates coordinates for each sample using such a distance matrix as the input.

Let's call M to your matrix, you need to run this code:

```<code>    # Load the library
      library(vegan)
    # Use metaMDS function for 2D - plot
      NMDS <- metaMDS(distance = M, k = 2)
    # Plot your individuals
      plot(NMDS$points[,1], NMDS$points[,2])
</code>```

In NMDS$points you have the coordinates for each of the samples. I suggest to colour the individuals according to a factor of interest such as cases and controls for example in biomedical analyses.

Title: How to generate an ordination plot from a distance matrix in R

Body:
Here I have another 'graphical' problem:

I have obtained from MOTHUR the following distance matrix (coming from a weighted unifrac analysis):

20
F3D0
F3D1        0.222664
F3D141      0.157368    0.293308
F3D142      0.180278    0.319198    0.0944511
F3D143      0.157659    0.290975    0.0545202   0.0761392
F3D144      0.199909    0.34045 0.104358    0.086418    0.089473
F3D145      0.207946    0.348532    0.107841    0.076302    0.0940067   0.051632
F3D146      0.117877    0.253996    0.0891617   0.130867    0.0882064   0.134407    0.138415
F3D147      0.197256    0.336583    0.102114    0.0764106   0.0890669   0.0514887   0.0479297   0.135324
F3D148      0.173824    0.311951    0.0606815   0.0648557   0.056463    0.074914    0.0811015   0.111996    0.0709027
F3D149      0.145614    0.276632    0.0462779   0.105512    0.0628737   0.10902 0.114584    0.0739466   0.107123    0.0690412
F3D150      0.129557    0.277624    0.0840909   0.128305    0.0863231   0.140256    0.145381    0.0744572   0.13672 0.113564    0.0659831
F3D2        0.133531    0.216587    0.160832    0.186833    0.176061    0.214934    0.215261    0.152591    0.205629    0.188325    0.156313    0.153841
F3D3        0.213102    0.305651    0.123818    0.113021    0.139376    0.148558    0.13853 0.174377    0.139851    0.126329    0.131294    0.166738    0.137784
F3D5        0.128668    0.185235    0.167733    0.205183    0.176585    0.224806    0.230984    0.14497 0.223492    0.18933 0.153624    0.148617    0.127574    0.192433
F3D6        0.139411    0.236633    0.135418    0.124848    0.134198    0.175098    0.166205    0.118905    0.166144    0.151842    0.120964    0.12724 0.0950943   0.119852    0.129523
F3D7        0.198884    0.315888    0.130385    0.0989168   0.131945    0.14625 0.126203    0.173689    0.128993    0.121373    0.140199    0.152123    0.152893    0.0906675   0.186674    0.111134
F3D8        0.178656    0.18783 0.205737    0.22104 0.219858    0.268701    0.2644  0.184943    0.268051    0.229503    0.1979  0.20035 0.164427    0.203089    0.119084    0.142398    0.185551
F3D9        0.153265    0.186706    0.196143    0.21504 0.20728 0.262127    0.255558    0.174563    0.2607  0.221969    0.192437    0.185154    0.13976 0.195538    0.0973901   0.127619    0.177605    0.0558726
Mock        0.653789    0.645344    0.633297    0.623553    0.633903    0.633135    0.63394 0.635815    0.645332    0.636453    0.629143    0.646918    0.663222    0.639517    0.649722    0.64073 0.654882    0.63988 0.646155

As this distance matrix come from a PCoA, what I want to do is to plot these distances in an ordination plot with R.

Any idea on how to doing this?

Thanks a lot

Body:
You have the vegan library with metaMDS function that generates coordinates for each sample using such a distance matrix as the input.

Let's call M to your matrix, you need to run this code:

    # Load the library
      library(vegan)
    # Use metaMDS function for 2D - plot
      NMDS <- metaMDS(distance = M, k = 2)
    # Plot your individuals
      plot(NMDS$points[,1], NMDS$points[,2])

In NMDS$points you have the coordinates for each of the samples. I suggest to colour the individuals according to a factor of interest such as cases and controls for example in biomedical analyses.


问:
Implementing SSO on React-Redux app
I'm trying to implement SSO on a React-Redux app using Keycloak as an external Identity Provider. The intent is to redirect to the IdP's login page if the user is not authenticated and after successful authentication use the access_token to access protected resources on another REST API microservice.

I tried to use Keycloak's NodeJS adapter (https://keycloak.gitbooks.io/documentation/securing_apps/topics/oidc/nodejs-adapter.html) and it is able to redirect me to the IdP for logging in and I can get the access_token but this all happens in the express-session and uses the MemoryStore. I was wondering if this is okay? Saving JWTs in the express store and retrieving them from the store while making an API call?

Or should I try doing something like saving the authentication status (JWT token) in Redux's store? Would it be better when compared with session cookies? Session cookies might be more secure but would involve accessing the store every time, right?

Above all, how can I achieve the approach where Redux store has the JWT?

Any help would be much appreciated.

Thanks in advance.

答:
For all those who are interested, I managed to implement it in the following way:

Load Keycloak.js (Keycloak's JS adapter) from the keycloak server

Initialize the Keycloak Script using the configuration parameters of the client.

Create a Reducer to fetch JWT tokens by invoking the Keycloak script when the main React component is about to be rendered.

Add the token to the state.

Anyways, we now believe that dynamically loading Keycloak.js from the server wouldn't be a good idea and above all, this would tightly couple our app to Keycloak. We are now looking for a more generic OIDC implementation.

As for storing the token, we've thought that the Redux store might not be the best place for JWTs. We're considering saving tokens in the localStorage instead.

Hope this helps someone!

Title: Implementing SSO on React-Redux app


问:
How to fetch data from same class for different objects
I have a two component in ExtJS. I am creating one class separately.

```<code>{
    xtype: 'component',
    id: 'myComponentId',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data.json"
            });
        }
    }
}, {
    xtype: 'component',
    width: 30,
    style: {
        color: '#FFFFFF',
        backgroundColor: '#000000'
    }
}, {
    xtype: 'component',
    id: 'myComponentId2',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data2.json"
            });
        }
    }
}
</code>```

Afterrendering I am creating an object of a that class.

```<code>SomeClass = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" myOpen = "openingList()" myOpen="openingList()" style="width:100% " >' +
        '<ul id="myUL" hidden=false>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }
    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '<li><a href="#">' + jsonc[i]['VALUE'] + '</a></li>';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
    myOpen = function() {
        var input, filter, ul, li, a, i;
        ul = document.getElementById("myUL");
        ul.hidden = false;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        var splitedVal = filter.split(";");
        filter = (splitedVal[splitedVal.length - 1]);
        li = ul.getElementsByTagName("li");
        for (i = 0; i < li.length; i++) {
            a = li[i].getElementsByTagName("a")[0];
            if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
                li[i].style.display = "";
            } else {
                li[i].style.display = "none";

            }
        }
    }
    return div;
}
</code>```

Now I am creating two object with two different divID for two different component. When I creating second object the data (which is coming from data.json) is getting lost and second object data is appeared. Also ul tag for the second objecte is not shown.

Can anybody help me to solve this. Or explain me where I am doing wrong.

答:
You can not use ids inside a reusable component like this:

```<code>'<input type="text" id="myInput"

'<ul id="myUL"

document.getElementById('myUL')

document.getElementById("myInput")
</code>```

IDs have to be global for the entire page, so you cannot reuse them.

What you may want to do is address these elements in a non-global way. Not sure what pure Javascript has to offer; IIRC, the ExtJS down() method only works on ExtJS objects.

Or you could add the id of the mother component to the ids you use, to make them unique:

```<code>'<input type="text" id="myInput-'+divID+'"

'<ul id="myUL-'+divID+'"

document.getElementById('myUL-'+divID)

document.getElementById("myInput"+divID)
</code>```

Body:
I have a two component in ExtJS. I am creating one class separately.

{
    xtype: 'component',
    id: 'myComponentId',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data.json"
            });
        }
    }
}, {
    xtype: 'component',
    width: 30,
    style: {
        color: '#FFFFFF',
        backgroundColor: '#000000'
    }
}, {
    xtype: 'component',
    id: 'myComponentId2',
    listeners: {
        afterrender: function(me, eOpts) {
            var myObj = new SomeClass({
                "divID": this.id,
                "url": "data2.json"
            });
        }
    }
}

Afterrendering I am creating an object of a that class.

SomeClass = function(args) {
    var dataUrl = args.url;
    var divID = args.divID;
    var div = document.getElementById(divID);

    var myTable = '<input type="text" id="myInput"  list="myUL" myOpen = "openingList()" myOpen="openingList()" style="width:100% " >' +
        '
' + '
' + '' + '
' + '
';
    div.innerHTML = myTable;

    function getData(callback) {
        var httpRequest = new XMLHttpRequest();
        httpRequest.open('GET', dataUrl, true);
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                callback(httpRequest.responseText);
            }
        };
        httpRequest.send();
    }
    getData(function(data) {
        var jsonc = JSON.parse(data);
        var new_opt = "";
        for (i = 0; i < jsonc.length; i++) {
            new_opt += '
' + jsonc[i]['VALUE'] + '
';
        }
        document.getElementById('myUL').innerHTML = new_opt;
    });
    myOpen = function() {
        var input, filter, ul, li, a, i;
        ul = document.getElementById("myUL");
        ul.hidden = false;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        var splitedVal = filter.split(";");
        filter = (splitedVal[splitedVal.length - 1]);
        li = ul.getElementsByTagName("li");
        for (i = 0; i
 -1) {
                li[i].style.display = "";
            } else {
                li[i].style.display = "none";

            }
        }
    }
    return div;
}

Now I am creating two object with two different divID for two different component. When I creating second object the data (which is coming from data.json) is getting lost and second object data is appeared. Also ul tag for the second objecte is not shown.

Can anybody help me to solve this. Or explain me where I am doing wrong.

Body:
You can not use ids inside a reusable component like this:

'<input type="text" id="myInput"

'<ul id="myUL"

document.getElementById('myUL')

document.getElementById("myInput")

IDs have to be global for the entire page, so you cannot reuse them.

What you may want to do is address these elements in a non-global way. Not sure what pure Javascript has to offer; IIRC, the ExtJS down() method only works on ExtJS objects.

Or you could add the id of the mother component to the ids you use, to make them unique:

'<input type="text" id="myInput-'+divID+'"

'<ul id="myUL-'+divID+'"

document.getElementById('myUL-'+divID)

document.getElementById("myInput"+divID)


问:
Why is a trait needed in order to constrain the type parameter?
Why is the trait needed in the following code? The commented variant without a trait does not compile, even if it looks as if it has the same information available.

```<code>trait ReliabilityConstructor<T> {
    fn new(a: T) -> Reliability;
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

//impl<T> Reliability
impl<T> ReliabilityConstructor<T> for Reliability
where
    f64: std::convert::From<T>,
{
    fn new(a: T) -> Reliability {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}
</code>```

When the commented line is uncommented:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:10:6
   |
10 | impl<T> Reliability
   |      ^ unconstrained type parameter
```

答:
Just change the trait from From to Into (because From<T> for U implies Into for T) - the intention is much more clear:

```<code>#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

impl Reliability {
    fn new<T: Into<f64>>(a: T) -> Reliability { // <T> is only here
        let mut a_f64: f64 = a.into(); // into() is used here
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability { alpha: (100f64 * a_f64) as i8 }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}
</code>```

Body:
Why is the trait needed in the following code? The commented variant without a trait does not compile, even if it looks as if it has the same information available.

trait ReliabilityConstructor<T> {
    fn new(a: T) -> Reliability;
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

//impl<T> Reliability
impl<T> ReliabilityConstructor<T> for Reliability
where
    f64: std::convert::From<T>,
{
    fn new(a: T) -> Reliability {
        let mut a_f64 = f64::from(a);
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability {
            alpha: (100f64 * a_f64) as i8,
        }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}

When the commented line is uncommented:

error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:10:6
   |
10 | impl<T> Reliability
   |      ^ unconstrained type parameter

Body:
Just change the trait from From to Into (because From<T> for U implies Into<U> for T) - the intention is much more clear:

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Reliability {
    alpha: i8,
}

impl Reliability {
    fn new<T: Into<f64>>(a: T) -> Reliability { // <T> is only here
        let mut a_f64: f64 = a.into(); // into() is used here
        a_f64 = if a_f64 < -1f64 {
            -1f64
        } else if a_f64 > 1f64 {
            1f64
        } else {
            a_f64
        };
        Reliability { alpha: (100f64 * a_f64) as i8 }
    }
}

fn main() {
    println!("{:?}", Reliability::new(-1));
}


问:
SQL error while converting varchar to int by joining two tables
I need to find missing numbers in my database. I am comparing two databases, tempdb created in query with numbers 1 - 999 and MYDAT.

MYDAT looks like:

```<code>+-------+
|  id   |
+-------+
| A-001 |
| A-002 |
| A-004 |
| A-... |
| A-952 |
| A-... |
+-------+
</code>```

I am running this query:

```<code>declare @tempid int

set @tempid = 1

create table tempdb (tempid int)

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT)
where
MYDAT.ID IS NULL and
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

drop table tempdb
</code>```

Without droping temdb, select * from tempdb looks good and i am getting what i want.

The part with selecting and converting data from MYDAT works good and i am getting only integers

```<code>select CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT) fom MYDAT
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'
</code>```

I am getting an error "converting varchar to int" but i have no idea why. When i change left join to right join, i get no errors.

I also checked both databases manually and there are no strings or characters, only integers.

I also tried the CONVERT() but with same result.

Any suggestions or ideas what is the problem?

Edit:

1 - I see one mistake as i tried it on rextester. I added MYDAT.ID IS NULL to the query so i get correct results.

2 - Examples
I need this: http://rextester.com/KFG73206

But CAST or CONVERT just does not seems to work http://rextester.com/WJIAH52304

答:
The problem is that the where clause is not necessarily executed before the on clause.  SQL Server can rearrange the operations.

I would guess that you really want to compare to the first three characters of MYDAT.ID.  That simplifies things a bit, because you can use LEFT() as in the code below.  In fact, your where conditions don't look right, so I fixed them.

The best solution is try_convert():

```<code>select tempdb.tempid
from tempdb left join
     MYDAT
     on tempdb.tempid = try_convert(int, left(MYDAT.ID, 3) )
where MYDAT.ID <> '' and
      left(MYDAT.ID, 3) <> '000' and
      left(MYDAT.ID, 3) NOT LIKE '%[^0-9]%';
</code>```

In pre-SQL Server 2012 versions, you can use a case instead:

```<code>select tempdb.tempid
from tempdb left join
     MYDAT
     on tempdb.tempid = (case when left(MYDAT.ID, 1, 3) not like '%[^0-9]%')
                              then convert(int, left(MYDAT.ID, 3)
                         end)
where MYDAT.ID <> '' and
      left(MYDAT.ID, 3) <> '000' and
      left(MYDAT.ID, 3) NOT LIKE '%[^0-9]%';
</code>```

case does guarantee the order of evaluation.

Body:
I need to find missing numbers in my database. I am comparing two databases, tempdb created in query with numbers 1 - 999 and MYDAT.

MYDAT looks like:

+-------+
|  id   |
+-------+
| A-001 |
| A-002 |
| A-004 |
| A-... |
| A-952 |
| A-... |
+-------+

I am running this query:

declare @tempid int

set @tempid = 1

create table tempdb (tempid int)

while @tempid < 1000
begin
    insert into tempdb values(@tempid)
    set @tempid = @tempid + 1
end

select tempdb.tempid from tempdb
left join MYDAT on tempdb.tempid = CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT)
where
MYDAT.ID IS NULL and
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

drop table tempdb

Without droping temdb, select * from tempdb looks good and i am getting what i want.

The part with selecting and converting data from MYDAT works good and i am getting only integers

select CAST(SUBSTRING(MYDAT.ID, 3, 3) as INT) fom MYDAT
where
SUBSTRING(MYDAT.ID, 3, 3) <> '' and
SUBSTRING(MYDAT.ID, 3, 3) <> '000'and
SUBSTRING(MYDAT.ID, 3, 3)  NOT LIKE '%[^0-9]%'

I am getting an error "converting varchar to int" but i have no idea why. When i change left join to right join, i get no errors.

I also checked both databases manually and there are no strings or characters, only integers.

I also tried the CONVERT() but with same result.

Any suggestions or ideas what is the problem?

Edit:

1 - I see one mistake as i tried it on rextester. I added MYDAT.ID IS NULL to the query so i get correct results.

2 - Examples
I need this: http://rextester.com/KFG73206

But CAST or CONVERT just does not seems to work http://rextester.com/WJIAH52304

Body:
The problem is that the where clause is not necessarily executed before the on clause.  SQL Server can rearrange the operations.

I would guess that you really want to compare to the first three characters of MYDAT.ID.  That simplifies things a bit, because you can use LEFT() as in the code below.  In fact, your where conditions don't look right, so I fixed them.

The best solution is try_convert():

select tempdb.tempid
from tempdb left join
     MYDAT
     on tempdb.tempid = try_convert(int, left(MYDAT.ID, 3) )
where MYDAT.ID <> '' and
      left(MYDAT.ID, 3) <> '000' and
      left(MYDAT.ID, 3) NOT LIKE '%[^0-9]%';

In pre-SQL Server 2012 versions, you can use a case instead:

select tempdb.tempid
from tempdb left join
     MYDAT
     on tempdb.tempid = (case when left(MYDAT.ID, 1, 3) not like '%[^0-9]%')
                              then convert(int, left(MYDAT.ID, 3)
                         end)
where MYDAT.ID <> '' and
      left(MYDAT.ID, 3) <> '000' and
      left(MYDAT.ID, 3) NOT LIKE '%[^0-9]%';

case does guarantee the order of evaluation.