问:
Automatic ordering of exports in index.ts makes app crash
Every time I generate something in my shared folder the index.ts file is rebuilt and exports are put in alphabetical order. This seems to break dependencies for me. Changing order manually so that dependencies is exported before classes with the dependencies makes it work again.

If we have app/shared/auth.guard.ts:

```<code>import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AuthService, User } from './';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private accountService: AuthService, private router: Router) { }

    canActivate(next: ActivatedRouteSnapshot): Observable<boolean> {
        let result = this.accountService.currentUser.first().map(user => user != null);

        let route: any[] = ['/login'];

        if (next.url.length) {
            route.push({ redirectUrl: next.url });
        }

        result.subscribe(isLoggedIn => {
            if (!isLoggedIn) {
                this.router.navigate(route);
            }
        });

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

and app/shared/account.service.ts:

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { User } from './';

const LOCAL_STORAGE_KEY = 'currentUser';

@Injectable()
export class AuthService {
  private currentUserSubject: BehaviorSubject<User>;

  constructor() {
    this.currentUserSubject = new BehaviorSubject<User>(this.getUserFromLocalStorage())
    this.currentUserSubject.subscribe(user => this.setUserToLocalStorage(user));
  }

  logIn(userName: string, password: string) : Observable<User> {
    this.currentUserSubject.next({
      id: userName,
      userName: userName,
      email: userName
    });

    return this.currentUser.first();
  }

  logOut() {
    this.currentUserSubject.next(null);
  }

  get currentUser(): Observable<User> {
    return this.currentUserSubject.asObservable();
  }

  private getUserFromLocalStorage(): User {
    let userString = localStorage.getItem(LOCAL_STORAGE_KEY);

    if (!userString) {
      return null;
    }

    return JSON.parse(userString);
  }

  private setUserToLocalStorage(user: User) {
    if (user) {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(user));
    }
    else {
      localStorage.removeItem(LOCAL_STORAGE_KEY);
    }
  }

}
</code>```

This doesn't work:

```<code>export * from './auth.guard';
export * from './auth.service';
</code>```

Unhandled Promise rejection: Error: Cannot resolve all parameters for 'AuthGuard'(undefined, Router). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthGuard' is decorated with Injectable.

This works:

```<code>export * from './auth.service';
export * from './auth.guard';
</code>```

From what I noticed this doesn't apply to all. For example can my user model be exported after auth service and it works fine.

I wish I didn't have to change this manually every time. Is there a workaround available? Could I structure the files in a different way?

Dependencies from package.json:

```<code>"@angular/common": "^2.0.0-rc.2",
"@angular/compiler": "^2.0.0-rc.2",
"@angular/core": "^2.0.0-rc.2",
"@angular/forms": "^0.1.0",
"@angular/http": "^2.0.0-rc.2",
"@angular/platform-browser": "^2.0.0-rc.2",
"@angular/platform-browser-dynamic": "^2.0.0-rc.2",
"@angular/router": "^3.0.0-alpha.7",
"bootstrap": "^3.3.6",
"es6-shim": "0.35.1",
"moment": "^2.13.0",
"ng2-bootstrap": "^1.0.17",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"slideout": "^0.1.12",
"systemjs": "0.19.26",
"zone.js": "0.6.12"
</code>```

devDependencies:

```<code>"angular-cli": "1.0.0-beta.6"
</code>```

答:
I had this issue and this was caused by circular reference. Explanations :
within the 'provider service class' I had a reference to a UI page that the constructor referenced this same service causing the circular reference...

```<code>import { MyUIPage } from "../pages/example/myuipage";
</code>```

So what I had to do, is remove the reference from the service and built a function receiving a callback.  No need to reference the UI page from the service and error goes away.

```<code>public setCallBackSpy(callback)
{
   this.callBackSpy = callback;
}
</code>```

In the app.component class constructor, the one referencing the service, I simply set the link to the callback function like below.

```<code>this.servicingClass.setCallBackSpy(this.myCallBackFunctionUsingUIPage);
</code>```

Hope that helps, my first answer ever :)

Body:
Every time I generate something in my shared folder the index.ts file is rebuilt and exports are put in alphabetical order. This seems to break dependencies for me. Changing order manually so that dependencies is exported before classes with the dependencies makes it work again.

If we have app/shared/auth.guard.ts:

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';

import { AuthService, User } from './';

@Injectable()
export class AuthGuard implements CanActivate {

    constructor(private accountService: AuthService, private router: Router) { }

    canActivate(next: ActivatedRouteSnapshot): Observable<boolean> {
        let result = this.accountService.currentUser.first().map(user => user != null);

        let route: any[] = ['/login'];

        if (next.url.length) {
            route.push({ redirectUrl: next.url });
        }

        result.subscribe(isLoggedIn => {
            if (!isLoggedIn) {
                this.router.navigate(route);
            }
        });

        return result;
    }
}

and app/shared/account.service.ts:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

import { User } from './';

const LOCAL_STORAGE_KEY = 'currentUser';

@Injectable()
export class AuthService {
  private currentUserSubject: BehaviorSubject<User>;

  constructor() {
    this.currentUserSubject = new BehaviorSubject<User>(this.getUserFromLocalStorage())
    this.currentUserSubject.subscribe(user => this.setUserToLocalStorage(user));
  }

  logIn(userName: string, password: string) : Observable<User> {
    this.currentUserSubject.next({
      id: userName,
      userName: userName,
      email: userName
    });

    return this.currentUser.first();
  }

  logOut() {
    this.currentUserSubject.next(null);
  }

  get currentUser(): Observable<User> {
    return this.currentUserSubject.asObservable();
  }

  private getUserFromLocalStorage(): User {
    let userString = localStorage.getItem(LOCAL_STORAGE_KEY);

    if (!userString) {
      return null;
    }

    return JSON.parse(userString);
  }

  private setUserToLocalStorage(user: User) {
    if (user) {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(user));
    }
    else {
      localStorage.removeItem(LOCAL_STORAGE_KEY);
    }
  }

}

This doesn't work:

export * from './auth.guard';
export * from './auth.service';

Unhandled Promise rejection: Error: Cannot resolve all parameters for 'AuthGuard'(undefined, Router). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'AuthGuard' is decorated with Injectable.

This works:

export * from './auth.service';
export * from './auth.guard';

From what I noticed this doesn't apply to all. For example can my user model be exported after auth service and it works fine.

I wish I didn't have to change this manually every time. Is there a workaround available? Could I structure the files in a different way?

Dependencies from package.json:

"@angular/common": "^2.0.0-rc.2",
"@angular/compiler": "^2.0.0-rc.2",
"@angular/core": "^2.0.0-rc.2",
"@angular/forms": "^0.1.0",
"@angular/http": "^2.0.0-rc.2",
"@angular/platform-browser": "^2.0.0-rc.2",
"@angular/platform-browser-dynamic": "^2.0.0-rc.2",
"@angular/router": "^3.0.0-alpha.7",
"bootstrap": "^3.3.6",
"es6-shim": "0.35.1",
"moment": "^2.13.0",
"ng2-bootstrap": "^1.0.17",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"slideout": "^0.1.12",
"systemjs": "0.19.26",
"zone.js": "0.6.12"

devDependencies:

"angular-cli": "1.0.0-beta.6"

Body:
I had this issue and this was caused by circular reference. Explanations :
within the 'provider service class' I had a reference to a UI page that the constructor referenced this same service causing the circular reference...

import { MyUIPage } from "../pages/example/myuipage";

So what I had to do, is remove the reference from the service and built a function receiving a callback.  No need to reference the UI page from the service and error goes away.

public setCallBackSpy(callback)
{
   this.callBackSpy = callback;
}

In the app.component class constructor, the one referencing the service, I simply set the link to the callback function like below.

this.servicingClass.setCallBackSpy(this.myCallBackFunctionUsingUIPage);

Hope that helps, my first answer ever :)


来源: stackexchange

问:
Why won't RANK and DENSE_RANK functions work?
In trying to use Sequel Pro and MySQL Workbench, I cannot get RANK or DENSE_RANK to work.

Here's a generic query I'm using:

```<code>SELECT
DENSE_RANK() OVER(ORDER BY `Ticket Sales`) ,
School
FROM schools;
</code>```

Sequel Pro returns this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(ORDER BY `Ticket Sales`) ,
  School
  FROM schools' at line 2

MySQL Workbench returns this error:

Error Code: 1305. FUNCTION RANK does not exist.

Any idea why this isn't working?

答:
Have a look here: http://www.folkstalk.com/2013/03/grouped-dense-rank-function-mysql-sql-query.html.

It explains that there is no DENSE_RANK function in MySQL and offers an alternative approach.

ContentLicense: CC BY-SA 3.0

Body:
In trying to use Sequel Pro and MySQL Workbench, I cannot get RANK or DENSE_RANK to work.

Here's a generic query I'm using:

SELECT
DENSE_RANK() OVER(ORDER BY `Ticket Sales`) ,
School
FROM schools;

Sequel Pro returns this error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(ORDER BY `Ticket Sales`) ,
  School
  FROM schools' at line 2

MySQL Workbench returns this error:

Error Code: 1305. FUNCTION RANK does not exist.

Any idea why this isn't working?


问:
Returning the Maximum of Date1 and Date2 in Cognos 10.2
At my company we've recently moved from SSRS to a Cognos-based Reporting System, I don't have much experience with Cognos as a whole and am running into some issues that seem trivially easy to fix but I am struggling so far.

In our DB we segregate two kinds of contact date information [Date Emailed] and [Date Called], I'm attempting to combine both to get a [Date Contacted] field returned.

Is there a way for me in Cognos report builder to find the max of both of these data items?

I would have expected some kind of "c = MAX(a,b)" function like the below to be available but from what I've seen, apparently not.

[Date Contacted] = MAX([Date Emailed], [Date Called])

Also, we have no access to modify SQL or any Cognos related part except the Report Builder which makes this all the more fun.

I feel like the answer will be building a CASE statement to do this, but I'd rather stay away from CASE if I can.

Thanks,

Blu

答:
I wonder if you could use _days_between to determine which is the newer date.
Something like this:

Case
(_days_between (X, Y) > 0 )

then (x)

// or Y; I can't remember whether the value returned is a negative or positive if the first parameter is greater than the second.  The expression editor's help will say.  Anyway, this is just to point you in a direction rather than me coming down from Mount Sinai.

case

(_days_between (X, Y) > 0 )

then

(x) // or Y;

Else (x or y but it doesn't matter as there's no difference )


问:
SelectFromModel scikit-learn: Resulting Feature Matrix Dimensions During Training and Testing Stages
I just started to use feature selection on my dataset and I came across SelectFromModel module which automatically transformed an original n x m feature matrix into n x k where k << m. However, k is unknown a priori.

I wonder how I should use this to train a model and then use the existing model to predict on new data. As we know the training data instance and test data instance must be represented in a feature vector of the same dimensions.

But this dimension will depend on the data, and cannot be controlled with SelectFromModel.

I have written a code presented below:

```<code>X_train = ... # feature matrix

print("BEFORE FEATURE SELECTION, FEATURE MATRIX shape={}".format(X_train.shape))
# output of this line is 24771, 11680

select = SelectFromModel(LogisticRegression(class_weight='balanced',penalty="l1",C=0.01))
X_train = select.fit_transform(X_train, y_train)

print("AFTER FEATURE SELECTION, FEATURE MATRIX shape={}".format(M.shape))
# output of this line is 24771, 170
</code>```

During testing, the pre-trained model is loaded, and new data instances need to be represented in the same feature vector:

```<code>X_test = ... # feature matrix

# the next line maps test set features to the feature vectors observed on training data, using corresponding vocabularies

X_test=map_test_to_train_featurevectors(X_test, X_train)

print("BEFORE FEATURE SELECTION, FEATURE MATRIX shape={}".format(X_test.shape))
# output of this line is 550, 11680, so test instances has same vector dimension as training instances

select = SelectFromModel(LogisticRegression(class_weight='balanced',penalty="l1",C=0.01))
X_test = select.fit_transform(X_test, y_test)

print("AFTER FEATURE SELECTION, FEATURE MATRIX shape={}".format(M.shape))
# output of this line is 550, 5, but the pre-trained model will expect 170

best_estimator = util.load_classifier_model(model_file)
prediction_dev = best_estimator.predict_proba(X_test)
</code>```

The last line obviously generates the following error, because the resulting feature matrix after feature selection during training and testing are different dimensions:

```<code>ValueError: X has 5 features per sample; expecting 169
</code>```

Does it mean that you cannot use SelectFromModel in this way? Can it only be used for training and evaluation?

答:
You cannot use the SelectFromModel() module in this way. It does not simply reduce the dimension complexity. By contrast, PCA().fit_transform(**data) does and will work the way you want. The documentation on SelectFromModel() says the following:

Meta-transformer for selecting features based on importance weights.

That being stated, you pass a desired model to SelectFromModel() and fit it with the input data. After you have done that, it extracts the most viable features based on the importance of model weights. In contrast to this approach, PCA() works with the explained variance of the data and strives to save as much of it as possible, while reducing the complexity of the data dimensionality. It is very handy since you may manually set the explained variance ratio to the original input data.

However, you try to transform (i. e. reduce) the dimensionality of the test data by implementing another fit of LogisticRegression(). It will calculate its own weights for this set as it absolutely differs from the set during the training stage. It thus chooses the most vital features based on the importance of the weights related to the test set, not the training set.

There are two approaches you may encounter the problem with:

Observe what 170 features are used after the select.fit_transform(X_train, y_train) and create a new variable with the same features from X_test. Thus, you will escape from an error pointing at a difference of sizes.

Implement a dimensionality reduction method, such as PCA or SVD

I hope that helps!

Body:
I just started to use feature selection on my dataset and I came across SelectFromModel module which automatically transformed an original n x m feature matrix into n x k where k << m. However, k is unknown a priori.

I wonder how I should use this to train a model and then use the existing model to predict on new data. As we know the training data instance and test data instance must be represented in a feature vector of the same dimensions.

But this dimension will depend on the data, and cannot be controlled with SelectFromModel.

I have written a code presented below:

X_train = ... # feature matrix

print("BEFORE FEATURE SELECTION, FEATURE MATRIX shape={}".format(X_train.shape))
# output of this line is 24771, 11680

select = SelectFromModel(LogisticRegression(class_weight='balanced',penalty="l1",C=0.01))
X_train = select.fit_transform(X_train, y_train)

print("AFTER FEATURE SELECTION, FEATURE MATRIX shape={}".format(M.shape))
# output of this line is 24771, 170

During testing, the pre-trained model is loaded, and new data instances need to be represented in the same feature vector:

X_test = ... # feature matrix

# the next line maps test set features to the feature vectors observed on training data, using corresponding vocabularies

X_test=map_test_to_train_featurevectors(X_test, X_train)

print("BEFORE FEATURE SELECTION, FEATURE MATRIX shape={}".format(X_test.shape))
# output of this line is 550, 11680, so test instances has same vector dimension as training instances

select = SelectFromModel(LogisticRegression(class_weight='balanced',penalty="l1",C=0.01))
X_test = select.fit_transform(X_test, y_test)

print("AFTER FEATURE SELECTION, FEATURE MATRIX shape={}".format(M.shape))
# output of this line is 550, 5, but the pre-trained model will expect 170

best_estimator = util.load_classifier_model(model_file)
prediction_dev = best_estimator.predict_proba(X_test)

The last line obviously generates the following error, because the resulting feature matrix after feature selection during training and testing are different dimensions:

ValueError: X has 5 features per sample; expecting 169

Does it mean that you cannot use SelectFromModel in this way? Can it only be used for training and evaluation?


问:
How do I retrieve the value of a specific XML node by path?
I am looking for a Javascript solution to this problem:

I have an XML document which is loaded by way of a typical AJAX method:

var xml = http.responseXML;

Consider the following example xml snippet:

```<code><main>
    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>
 </main>
</code>```

I would like to get the value of a node by specifying the path as follows:

```<code>var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);
</code>```

I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName and the like.

How would I construct the method getNodeValueByPath or is there some construct in Javascript that allows for this?

I am not well versed in Javascript.

EDIT: Here is an example that shows my attempt at using XPath and how it is failing:

XML:

```<code><?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>
</code>```

JavaScript: (these are the relevant functions only)

```<code>function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}
</code>```

I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.

Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com" from the XML document, the alert dialog appears with the text "false" as desired.

Debugging using Firebug shows that resultNode is an empty string as long as the namespace is declared.

答:
I've been playing around with the same thing, I tried a few XPath JS libraries, here's one: http://js-xpath.sourceforge.net/, but having said that, I couldn't get stuff working so I'll be watching this question avidly :)

Also, at SO: Cross-browser XPath implementation in JavaScript

Body:
I am looking for a Javascript solution to this problem:

I have an XML document which is loaded by way of a typical AJAX method:

var xml = http.responseXML;

Consider the following example xml snippet:

    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>

I would like to get the value of a node by specifying the path as follows:

var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);

I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName and the like.

How would I construct the method getNodeValueByPath or is there some construct in Javascript that allows for this?

I am not well versed in Javascript.

EDIT: Here is an example that shows my attempt at using XPath and how it is failing:

XML:

<?xml version="1.0" ?>

  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>

JavaScript: (these are the relevant functions only)

function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}

I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.

Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com" from the XML document, the alert dialog appears with the text "false" as desired.

Debugging using Firebug shows that resultNode is an empty string as long as the namespace is declared.

ContentLicense: CC BY-SA 2.5


问:
org.apache.sling.commons.json.JSONArray is deprecated in AEM 6.3
In AEM 6.3,The JSONArray API is deprecated ,so what is the alternative in place of JSONArray API?</p>

答: The best way forward is to change your Json API from org.apache.sling.commons.json to com.google.gson. Since it is already being used in AEM elsewhere.


问:
Create folder in batch script and ignore if it exists
How do I create folder (and any subfolders) in batch script? But the important thing is that, if the folder (or any subfolders) already exists, it should not return error.

For example, something like this:

mkdir mydir - success(directory is now created)

mkdir mydir\subdir - success(now mydir contains subdir)

mkdir mydir - success(folder already exists, should not throw an error)

mkdir mydir\subdir - success(folders already exists, should not throw an error)

What I actually need is just to ensure that the folder structure exists.

答:
A standard method to create a directory structure is:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"

md "%Directory%" 2>nul
if not exist "%Directory%\*" (
    echo Failed to create directory "%Directory%"
    pause
    goto :EOF
)

rem Other commands after successful creation of the directory.
endlocal
</code>```

By default command extensions are enabled and delayed expansion is disabled. The batch code above explicitly sets up this environment.

The command MD creates the complete directory structure to specified directory with enabled command extensions.

MD outputs an error if the directory already exists. This might be useful to inform a user entering the command manually about a possible mistake in entered directory path as it could be that the user wanted to create a new directory and has entered just by mistake the name of an already existing directory.

But for scripted usage of command MD it is often a problem that this command outputs an error message if the directory to create already exists. It would be really helpful if command MD would have an option to not output an error message in case of directory to create already existing and exiting with return code 0 in this case. But there is no such option.

The solution above creates the directory and suppresses a perhaps output error message with redirecting it from handle STDERR to device NUL.

But the creation of the directory could fail because of invalid character in directory path, drive not available (on using full path), there is anywhere in path a file with name of a specified directory, NTFS permissions don't permit creation of the directory, etc.

So it is advisable to verify if the directory really exists which is done with:

```<code>if not exist "%Directory%\*"
</code>```

It is important that the directory path ends now with \* or at least with a backslash. Otherwise it could be possible for the example that there is a file with name subdir 2 in directory mydir\subdir 1 which on usage of the condition if not exist "%Directory%" would evaluate to false although there is no directory subdir 2.

It is of course also possible to do the directory check first and create the directory if not already existing.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"

if not exist "%Directory%\*" (
    md "%Directory%"
    if errorlevel 1 (
        pause
        goto :EOF
    )
)

rem Other commands after successful creation of the directory.
endlocal
</code>```

The user can see now the error message output by command MD if the directory structure could not be created explaining briefly the reason.

This batch code could be written more compact using operator ||:

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"

if not exist "%Directory%\*" md "%Directory%" || (pause & goto :EOF)

rem Other commands after successful creation of the directory.
endlocal
</code>```

For details about the operators || and & read the answer on Single line with multiple commands using Windows batch file.

The command ENDLOCAL is not used before goto :EOF because this command requires also enabled command extensions. Windows command interpreter executes this command implicit on leaving execution of the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

goto /?

if /?

md /?

pause /?

set /?

setlocal /?

Read also the Microsoft article about Using Command Redirection Operators.

ContentLicense: CC BY-SA 4.0

Body:
A standard method to create a directory structure is:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"

md "%Directory%" 2>nul
if not exist "%Directory%\*" (
    echo Failed to create directory "%Directory%"
    pause
    goto :EOF
)

rem Other commands after successful creation of the directory.
endlocal

By default command extensions are enabled and delayed expansion is disabled. The batch code above explicitly sets up this environment.

The command MD creates the complete directory structure to specified directory with enabled command extensions.

MD outputs an error if the directory already exists. This might be useful to inform a user entering the command manually about a possible mistake in entered directory path as it could be that the user wanted to create a new directory and has entered just by mistake the name of an already existing directory.

But for scripted usage of command MD it is often a problem that this command outputs an error message if the directory to create already exists. It would be really helpful if command MD would have an option to not output an error message in case of directory to create already existing and exiting with return code 0 in this case. But there is no such option.

The solution above creates the directory and suppresses a perhaps output error message with redirecting it from handle STDERR to device NUL.

But the creation of the directory could fail because of invalid character in directory path, drive not available (on using full path), there is anywhere in path a file with name of a specified directory, NTFS permissions don't permit creation of the directory, etc.

So it is advisable to verify if the directory really exists which is done with:

if not exist "%Directory%\*"

It is important that the directory path ends now with \* or at least with a backslash. Otherwise it could be possible for the example that there is a file with name subdir 2 in directory mydir\subdir 1 which on usage of the condition if not exist "%Directory%" would evaluate to false although there is no directory subdir 2.

It is of course also possible to do the directory check first and create the directory if not already existing.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"

if not exist "%Directory%\*" (
    md "%Directory%"
    if errorlevel 1 (
        pause
        goto :EOF
    )
)

rem Other commands after successful creation of the directory.
endlocal

The user can see now the error message output by command MD if the directory structure could not be created explaining briefly the reason.

This batch code could be written more compact using operator ||:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "Directory=mydir\subdir 1\subdir 2"

if not exist "%Directory%\*" md "%Directory%" || (pause & goto :EOF)

rem Other commands after successful creation of the directory.
endlocal

For details about the operators || and & read the answer on Single line with multiple commands using Windows batch file.

The command ENDLOCAL is not used before goto :EOF because this command requires also enabled command extensions. Windows command interpreter executes this command implicit on leaving execution of the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

endlocal /?

goto /?

if /?

md /?

pause /?

set /?

setlocal /?

Read also the Microsoft article about Using Command Redirection Operators.


问:
Tensorflow- estimation of basic linear equation using neural net
I am trying to learn Tensorflow. I am doing a basic example- model the equation y = x + 0.1, train it using a neural net, and then make predictions. I am actually taking a sigmoid approach (not ideal), so not using the standard softmax/relu way (which didn't work for me). The code runs, but the answer is wrong: all predictions in a batch give nearly identical answers, like y_true = [[0.356], [0.356], [0.356],[0.356]], for input= [[0.1, 0.2, 0.3, 0.4]]. What am I doing wrong? Code is below:</p>

```<code>import tensorflow as tf
import numpy as np

epochs = 1000
# For equation y = b + 0.1, sample data below
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float)
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float)

c = tf.constant(0.1, name='c')
b = tf.placeholder(tf.float32, [None, 1], name='b')
y = tf.add(b, c, name='y')

y_true = tf.placeholder(tf.float32, [None, 1], name='y_true')

W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([3]), name='b1')
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([1]), name='b2')

hidden_out = tf.add(tf.matmul(b, W1), b1)
hidden_out = tf.sigmoid(hidden_out)

y_ = tf.sigmoid(tf.add(tf.matmul(hidden_out, W2), b2))

cost = tf.reduce_mean(tf.square(y_ - y_true))
optimiser = tf.train.GradientDescentOptimizer(0.005).minimize(cost)

init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    # initialise the variables
    sess.run(init_op)
    for epoch in range(epochs):
        _, cost_now = sess.run([optimiser, cost], {b: myImportedDatax_np, y_true: myImportedDatay_np})
    print("Predicted values are:")
    print(sess.run(y_, {b: myImportedDatax_np}))
</code>```

答:
There few things that are wrong with your code:

Yours is a regression problem, y = x + c, so remove the sigmoid output:

```<code>y_ = tf.add(tf.matmul(hidden_out, W2), b2)
</code>```

You will be better served by a single hidden layer, your multiple hidden unit for such a simple task will require it to train it longer.

To handle 2, increase your epoch to higher value say, 10000 and your learning rate also higher, say 0.1

EDIT:
Adding the code:

```<code>#increased the number of epoch
epochs = 10000
# For equation y = b + 0.1, sample data below
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float)
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float)

c = tf.constant(0.1, name='c')
b = tf.placeholder(tf.float32, [None, 1], name='b')
y = tf.add(b, c, name='y')

y_true = tf.placeholder(tf.float32, [None, 1], name='y_true')

W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([3]), name='b1')
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([1]), name='b2')

hidden_out = tf.add(tf.matmul(b, W1), b1)
hidden_out = tf.sigmoid(hidden_out)
# Removed the activation
y_ = tf.add(tf.matmul(hidden_out, W2), b2)

cost = tf.reduce_mean(tf.square(y_ - y_true)

#changed the learning rate
optimiser = tf.train.GradientDescentOptimizer(0.1).minimize(cost)

init_op = tf.global_variables_initializer()

#Predicted values are:
#[[ 0.19917184]
#[ 0.30153054]
#[ 0.40164429]
#[ 0.4976812 ]]
</code>```

Body:
I am trying to learn Tensorflow. I am doing a basic example- model the equation y = x + 0.1, train it using a neural net, and then make predictions. I am actually taking a sigmoid approach (not ideal), so not using the standard softmax/relu way (which didn't work for me). The code runs, but the answer is wrong: all predictions in a batch give nearly identical answers, like y_true = [[0.356], [0.356], [0.356],[0.356]], for input= [[0.1, 0.2, 0.3, 0.4]]. What am I doing wrong? Code is below:

import tensorflow as tf
import numpy as np

epochs = 1000
# For equation y = b + 0.1, sample data below
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float)
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float)

c = tf.constant(0.1, name='c')
b = tf.placeholder(tf.float32, [None, 1], name='b')
y = tf.add(b, c, name='y')

y_true = tf.placeholder(tf.float32, [None, 1], name='y_true')

W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([3]), name='b1')
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([1]), name='b2')

hidden_out = tf.add(tf.matmul(b, W1), b1)
hidden_out = tf.sigmoid(hidden_out)

y_ = tf.sigmoid(tf.add(tf.matmul(hidden_out, W2), b2))

cost = tf.reduce_mean(tf.square(y_ - y_true))
optimiser = tf.train.GradientDescentOptimizer(0.005).minimize(cost)

init_op = tf.initialize_all_variables()

with tf.Session() as sess:
    # initialise the variables
    sess.run(init_op)
    for epoch in range(epochs):
        _, cost_now = sess.run([optimiser, cost], {b: myImportedDatax_np, y_true: myImportedDatay_np})
    print("Predicted values are:")
    print(sess.run(y_, {b: myImportedDatax_np}))

Body:
There few things that are wrong with your code:

Yours is a regression problem, y = x + c, so remove the sigmoid output:

y_ = tf.add(tf.matmul(hidden_out, W2), b2)

You will be better served by a single hidden layer, your multiple hidden unit for such a simple task will require it to train it longer.

To handle 2, increase your epoch to higher value say, 10000 and your learning rate also higher, say 0.1

EDIT:
Adding the code:

#increased the number of epoch
epochs = 10000
# For equation y = b + 0.1, sample data below
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float)
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float)

c = tf.constant(0.1, name='c')
b = tf.placeholder(tf.float32, [None, 1], name='b')
y = tf.add(b, c, name='y')

y_true = tf.placeholder(tf.float32, [None, 1], name='y_true')

W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1')
b1 = tf.Variable(tf.random_normal([3]), name='b1')
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2')
b2 = tf.Variable(tf.random_normal([1]), name='b2')

hidden_out = tf.add(tf.matmul(b, W1), b1)
hidden_out = tf.sigmoid(hidden_out)
# Removed the activation
y_ = tf.add(tf.matmul(hidden_out, W2), b2)

cost = tf.reduce_mean(tf.square(y_ - y_true)

#changed the learning rate
optimiser = tf.train.GradientDescentOptimizer(0.1).minimize(cost)

init_op = tf.global_variables_initializer()

#Predicted values are:
#[[ 0.19917184]
#[ 0.30153054]
#[ 0.40164429]
#[ 0.4976812 ]]


问:
How to format unicode strings to utf-8 in Python?
I'm reading in a JSON string which is littered with u'string' style strings.  Example:

```<code> [
     {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        },
        "year": {
          "value": "1996"
        }
      },
      "guid": "#9202a8c04000641f80000000003a0ee6",
      "type": "\/games\/game",
      "id": "\/en\/el_grande",
      "name": "El Grande"
    },
    {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        },
        "year": {
          "value": "1995"
        }
      },
      "guid": "#9202a8c04000641f80000000000495ec",
      "type": "\/games\/game",
      "id": "\/en\/settlers_of_catan",
      "name": "Settlers of Catan"
    }
  ]
</code>```

If I assign name = result.name.  Then when I log of pass that value to a Django template, it displays as u'Dominion'

How do I format it to display as Dominion?

++ UPDATE ++

I think the problem has to do with printing values from a list or dictionary.  For example:

```<code>result = freebase.mqlread(query)

games = {}
count = 0
r = result[0]
name = r.name
games["name"] = name,
self.response.out.write(games["name"])
self.response.out.write(name)
</code>```

This displays as:

```<code>(u'Dominion',)  // saved response to dictionary, and then printed
Dominion        // when calling the value directly from the response
</code>```

I need to iterate through an array of JSON items and the values are being shown with the unicode.  Why?

答: The comma at the end of games["name"] = name, makes it a 1-tuple. Remove it.

Body:
I'm reading in a JSON string which is littered with u'string' style strings.  Example:

 [
     {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        },
        "year": {
          "value": "1996"
        }
      },
      "guid": "#9202a8c04000641f80000000003a0ee6",
      "type": "\/games\/game",
      "id": "\/en\/el_grande",
      "name": "El Grande"
    },
    {
      "!\/award\/award_honor\/honored_for": {
        "award": {
          "id": "\/en\/spiel_des_jahres"
        },
        "year": {
          "value": "1995"
        }
      },
      "guid": "#9202a8c04000641f80000000000495ec",
      "type": "\/games\/game",
      "id": "\/en\/settlers_of_catan",
      "name": "Settlers of Catan"
    }
  ]

If I assign name = result.name.  Then when I log of pass that value to a Django template, it displays as u'Dominion'

How do I format it to display as Dominion?

++ UPDATE ++

I think the problem has to do with printing values from a list or dictionary.  For example:

result = freebase.mqlread(query)

games = {}
count = 0
r = result[0]
name = r.name
games["name"] = name,
self.response.out.write(games["name"])
self.response.out.write(name)

This displays as:

(u'Dominion',)  // saved response to dictionary, and then printed
Dominion        // when calling the value directly from the response

I need to iterate through an array of JSON items and the values are being shown with the unicode.  Why?


问:
How to Check Each Row of GridView and Display Message on Error?
I have an ASPX gridview with a checkbox in the first column and a comment textbox in the last column. I'd like to require users to leave a comment if they uncheck the checkbox.

Originally, I thought that I could use a For Each on the VB-side and push a message through, alerting the user that they forgot to include a comment. From looking around, it looks like MsgBox and MessageBox are unusable in this context. One other option I saw mentioned using Response.Write and scripting in some java, but I couldn't get that to work. Other users have mentioned that using Response.Write like this could cause issues if there's ever an error.

Is there any way to do this? Again, I'd like to check each row, and if the checkbox is unchecked, make sure that there's something in the comment textbox. I'm intermediate in my VB knowledge, but this is my first time messing with ASP.net. Any help or advice would be greatly appreciated.

答:
After failing to find an easy way to push a message to the user, I decided to make use of a button that I was already using on the front end to send my updates.

```<code><asp:Button ID="ApproveList"
    runat="server"
    style="width:200px;"
    Text="Approve List"
    CausesValidation="true"
    OnClick="UpdateSelectedRecords_Click"
    OnClientClick="return confirm('YOUR RECORDS WILL NOT BE APPROVED UNLESS ALL UNAPPROVED RECORDS HAVE A COMMENT. Are you sure you want to approve these records?');"/>
</code>```

When the user hits the button and confirms that they'd like to proceed, it runs the UpdateSelectedRecords_Click sub on the VB-side. The first part of that sub checks each row for my conditions, and if it finds any issues, it just ends the sub.

```<code>' Verify that every unchecked row has a comment, else fail
For Each row As GridViewRow In GridUnapprovedRecords.Rows
    cb = CType(row.FindControl("CheckBox1"),CheckBox)
    strComment = row.FindControl("Comment")
    If Not cb.Checked Then
        If strComment.Text Is Nothing Or Len(strComment.Text) = 0 Then
            intErrors = intErrors + 1
        End If
    End If
Next

' If no unchecked boxes without comments, run updates
If intErrors = 0 Then
    ...
Else
    Exit Sub
End If
</code>```

I'm sure there are more eligant options, but this gets the job done.

Body:
After failing to find an easy way to push a message to the user, I decided to make use of a button that I was already using on the front end to send my updates.

<asp:Button ID="ApproveList"
    runat="server"
    style="width:200px;"
    Text="Approve List"
    CausesValidation="true"
    OnClick="UpdateSelectedRecords_Click"
    OnClientClick="return confirm('YOUR RECORDS WILL NOT BE APPROVED UNLESS ALL UNAPPROVED RECORDS HAVE A COMMENT. Are you sure you want to approve these records?');"/>

When the user hits the button and confirms that they'd like to proceed, it runs the UpdateSelectedRecords_Click sub on the VB-side. The first part of that sub checks each row for my conditions, and if it finds any issues, it just ends the sub.

' Verify that every unchecked row has a comment, else fail
For Each row As GridViewRow In GridUnapprovedRecords.Rows
    cb = CType(row.FindControl("CheckBox1"),CheckBox)
    strComment = row.FindControl("Comment")
    If Not cb.Checked Then
        If strComment.Text Is Nothing Or Len(strComment.Text) = 0 Then
            intErrors = intErrors + 1
        End If
    End If
Next

' If no unchecked boxes without comments, run updates
If intErrors = 0 Then
    ...
Else
    Exit Sub
End If

I'm sure there are more eligant options, but this gets the job done.


问:
React NPM packages to prevent, search and monitor places where state is mutated
Do you know any worth recommending npm packages (for the DEV environment needs) to find spots in React app where redux store state is mutated ?

Currently I'm using Redux Freeze State package but unfortunatelly the indicated package is outdated, not supported any more and causes IE11 arguments caller exception.

https://www.npmjs.com/package/redux-freeze-state

```<code>import { createStore } from 'redux';
import freezeState from 'redux-freeze-state';

let reducer = ...
let store = createStore(freezeState(reducer));
</code>```

答:
Yes, there's several, and I have them listed in the Redux DevTools#Linting section of my Redux addons catalog.

Listing those specifically:

https://github.com/leoasis/redux-immutable-state-invariant

https://github.com/jfpalacios/redux-freeze-state (the one you're using)

https://github.com/buunguyen/redux-freeze

https://github.com/tarodenberg/redux-freezer

Body:
Do you know any worth recommending npm packages (for the DEV environment needs) to find spots in React app where redux store state is mutated ?

Currently I'm using Redux Freeze State package but unfortunatelly the indicated package is outdated, not supported any more and causes IE11 arguments caller exception.

https://www.npmjs.com/package/redux-freeze-state

import { createStore } from 'redux';
import freezeState from 'redux-freeze-state';

let reducer = ...
let store = createStore(freezeState(reducer));


问:
Why is different spacing displaying between different div classes with the same margin settings?
I am creating a FAQ page here: http://staging.nwcm.com/2017/07/06/faq-custom-css/

Here is my css:

```<code>/*TAB SETUP FORMATTING*/

div.tab_counter_0, div.tab_counter_0 active_tab, div#tab-id-1-container {
border-color: #339966 !important;
}

div.tab_counter_1, div.tab_counter_1 active_tab, div#tab-id-2-container {
border-color: #009999 !important;
}

div.tab_counter_2, div.tab_counter_2 active_tab, div#tab-id-3-container {
border-color: #3399ff !important;
}

.tab {
font-size: 1.5em !important;
}

/*END TAB SETUP FORMATTING*/

div.ufaq-faq-category h4 {
font-size: 1.5em !important;
margin: -5px !important;
}

div.ufaq-faq-category-inner {
margin-top: 1.5em;
margin-bottom: -1em;
}

div.ufaq-faq-body {
margin-top: -18px !important;
}

.ufaq-faq-post p, .ufaq-faq-post li {
font-weight: 800 !important;
clear: left;
font-size: 14px;
margin-top: 0px;
margin-bottom: 10px;
}

.ufaq-faq-title, .ufaq-faq-category-title {
margin-bottom: 4px;
}
</code>```

WEBSITE INFORMATION (not sure if this is important): I am using the Ultimate FAQ (1) plugin on a Wordpress site with the Enfold theme (2) with the Avia Layout Builder, both by Kriesi.  The tabs are built-in inside my theme, the content inside of the tabs are all my individual categories of FAQ Questions.  Here is the shortcode for the content of the first tab:

```<code>[ultimate-faqs include_category='your-contributions']
[ultimate-faqs include_category='employer-contributions']
[ultimate-faqs include_category='roth']
[ultimate-faqs include_category='eligibility']
[ultimate-faqs include_category='vesting']
[ultimate-faqs include_category='401k-distributions']
[ultimate-faqs include_category='rollovers']
[ultimate-faqs include_category='loans']
</code>```

THE PROBLEM: The spacing between different div classes, with the same styling, results in variable spacing between these elements.  I need the space after each title, before each answer, to be consistent.  It appears that this difference happens when the question is longer than one line.  To get a good picture of the issue, please see:

Your Contributions:

Must my employer offer a 401(k) plan?

I changed jobs this year.  What if I contributed...?

How much can I contribute?

Vesting:

If I after I leave the employment of a company...?

LINKS:

(1) https://wordpress.org/plugins/ultimate-faqs/

(2) http://www.kriesi.at/themes/enfold-2017/

答:
You are facing this issue because of the '+' and '-' minus symbols. They are assigned a height and the space between the question and answer is because of this height. It's a bit complicated to explain. I will post a solution. See if it works for you.

```<code>.ewd-ufaq-post-margin-symbol{height:21px;}
.ufaq-faq-title-text{margin-bottom:10px;}
</code>```

Add this at the bottom of the FAQ plugin's CSS file or better yet hunt down the styles responsible and change them. Let me know how it goes.

Body:
I am creating a FAQ page here: http://staging.nwcm.com/2017/07/06/faq-custom-css/

Here is my css:

/*TAB SETUP FORMATTING*/

div.tab_counter_0, div.tab_counter_0 active_tab, div#tab-id-1-container {
border-color: #339966 !important;
}

div.tab_counter_1, div.tab_counter_1 active_tab, div#tab-id-2-container {
border-color: #009999 !important;
}

div.tab_counter_2, div.tab_counter_2 active_tab, div#tab-id-3-container {
border-color: #3399ff !important;
}

.tab {
font-size: 1.5em !important;
}

/*END TAB SETUP FORMATTING*/

div.ufaq-faq-category h4 {
font-size: 1.5em !important;
margin: -5px !important;
}

div.ufaq-faq-category-inner {
margin-top: 1.5em;
margin-bottom: -1em;
}

div.ufaq-faq-body {
margin-top: -18px !important;
}

.ufaq-faq-post p, .ufaq-faq-post li {
font-weight: 800 !important;
clear: left;
font-size: 14px;
margin-top: 0px;
margin-bottom: 10px;
}

.ufaq-faq-title, .ufaq-faq-category-title {
margin-bottom: 4px;
}

WEBSITE INFORMATION (not sure if this is important): I am using the Ultimate FAQ (1) plugin on a Wordpress site with the Enfold theme (2) with the Avia Layout Builder, both by Kriesi.  The tabs are built-in inside my theme, the content inside of the tabs are all my individual categories of FAQ Questions.  Here is the shortcode for the content of the first tab:

[ultimate-faqs include_category='your-contributions']
[ultimate-faqs include_category='employer-contributions']
[ultimate-faqs include_category='roth']
[ultimate-faqs include_category='eligibility']
[ultimate-faqs include_category='vesting']
[ultimate-faqs include_category='401k-distributions']
[ultimate-faqs include_category='rollovers']
[ultimate-faqs include_category='loans']

THE PROBLEM: The spacing between different div classes, with the same styling, results in variable spacing between these elements.  I need the space after each title, before each answer, to be consistent.  It appears that this difference happens when the question is longer than one line.  To get a good picture of the issue, please see:

Your Contributions:

Must my employer offer a 401(k) plan?

I changed jobs this year.  What if I contributed...?

How much can I contribute?

Vesting:

If I after I leave the employment of a company...?

LINKS:

(1) https://wordpress.org/plugins/ultimate-faqs/

(2) http://www.kriesi.at/themes/enfold-2017/

Body:
You are facing this issue because of the '+' and '-' minus symbols. They are assigned a height and the space between the question and answer is because of this height. It's a bit complicated to explain. I will post a solution. See if it works for you.

.ewd-ufaq-post-margin-symbol{height:21px;}
.ufaq-faq-title-text{margin-bottom:10px;}

Add this at the bottom of the FAQ plugin's CSS file or better yet hunt down the styles responsible and change them. Let me know how it goes.


问:
Show objects without tibble information (R)
I have the following problem.

When I was looking up a specific value it usually looked like this:

```<code>df1[383,54]
[1] "This is a Test-String."
</code>```

But when I load something from excel:

```<code>library(readxl)
df2 <- read_excel("~/Test.xls", col_names = FALSE)
</code>```

It started looking like this:

```<code>df1[383,54]
# A tibble: 1 x 1
               X__54
               <chr>
1 This is a Test-String.
</code>```

What have I done wrong? It is not because of the tibble package, because when I detach it, it is the same output. Why does the output of my dataframe change, when I load a different dataset. I tried a lot but did not find an answer. Hopefully this is not a question with an overly obvious answer.

答: df2 <- as.data.frame(df2) should prevent the header from showing by changing from a tibble back to a standard data.frame.

Body:
I have the following problem.

When I was looking up a specific value it usually looked like this:

df1[383,54]
[1] "This is a Test-String."

But when I load something from excel:

library(readxl)
df2 <- read_excel("~/Test.xls", col_names = FALSE)

It started looking like this:

df1[383,54]
# A tibble: 1 x 1
               X__54
               <chr>
1 This is a Test-String.

What have I done wrong? It is not because of the tibble package, because when I detach it, it is the same output. Why does the output of my dataframe change, when I load a different dataset. I tried a lot but did not find an answer. Hopefully this is not a question with an overly obvious answer.


问:
FitnessActivities.getName(int i) method is deprecated, what method to use instead?
In the following library:
 com.google.android.gms:play-services-fitness:9.8.0

In the following class: com.google.android.gms.fitness.FitnessActivities

There is this method: public static java.lang.String getName(int i)

However, in the library com.google.android.gms:play-services-fitness:10.2.0 the above mentioned method is removed.

What method to use instead of the above mentioned method?

答:
Use the method below. I have used it with argument 9 which stands for aerobics.

```<code>zza.getName(9)
</code>```

Do not forget to import the class:

```<code>import com.google.android.gms.fitness.zza;
</code>```

Body:
Use the method below. I have used it with argument 9 which stands for aerobics.

zza.getName(9)

Do not forget to import the class:

import com.google.android.gms.fitness.zza;


问:
Can I detect XHTML parsing errors using Javascript?
When I have a markup error in my XHTML page, Mozilla Firefox displays the "Yellow Screen of Death", showing only a large red error message on a yellow background.

While these errors are rare, they are extremely user-unfriendly.

Is there a way I can detect these using Javascript, and thereby send a message back to the server?

What I've discovered so far:
 - Scripts placed before the parsing error still run. (Of course.)
 - Timeouts and intervals that were set in these scripts will still execute after the parsing error.
 - In Firefox, the DOM is a <parsererror> with a <sourcetext> inside it. I can detect this if I query document.firstChild.tagName.

Remaining questions:
 - What events are available that I could listen for to detect this happening? (Polling sucks.)
 - How can I detect this in other browsers?

答: This doesn't answer your question but, instead, why not validate your XHTML on your server, after/when you generate it and before you send it to the browser?</p>

OwnerDisplayName: phyzome

OwnerDisplayName: ChrisW


问:
Can I start a windows form from a console program
I'd like to start a new windows form from a console program. Is this possible?</p>

答:
Add a reference to Windows.Forms, then:</p>

```<code>static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.Run(new Form()); //of course you can put your own custom Form here.
}
</code>```

Body:
Add a reference to Windows.Forms, then:

static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.Run(new Form()); //of course you can put your own custom Form here.
}


问:
Using relative url in QT stylesheet
I'm working with a qt project and want to set all the image files relative but I can't access the images using the usual parent url reference.

```<code>image:url('../sources/status/status.png');
</code>```

I can however load the image using the image's absolute path.

答:
It's better to use the Qt Resource System. The dependencies of your resources will be included with you executable file and then you don't have to share the folder tree.

You can use the resource url to set up the image in your QSS code.

Create resource with all your image, you can use the Qt Creator IDE to set up it easily. If you want you can add your own prefix to distinguish with the rest of the resources.

```<code><!DOCTYPE RCC><RCC version="1.0" prefix="/">
<qresource>
   <file>../sources/status/status.png</file>
   <file>../sources/status/example_1.png</file>
   <file>../sources/status/example_2.png</file>
   <file>../sources/status/example_3.png</file>
</qresource>
</RCC>
</code>```

Then if your prefix, its "/", then use this for your QSS:

```<code>image:url(':/../sources/status/status.png');
</code>```

Title: Using relative url in QT stylesheet

Body:
I'm working with a qt project and want to set all the image files relative but I can't access the images using the usual parent url reference.

image:url('../sources/status/status.png');

I can however load the image using the image's absolute path.

Body:
It's better to use the Qt Resource System. The dependencies of your resources will be included with you executable file and then you don't have to share the folder tree.

You can use the resource url to set up the image in your QSS code.

Create resource with all your image, you can use the Qt Creator IDE to set up it easily. If you want you can add your own prefix to distinguish with the rest of the resources.

<!DOCTYPE RCC><RCC version="1.0" prefix="/">
<qresource>
   <file>../sources/status/status.png</file>
   <file>../sources/status/example_1.png</file>
   <file>../sources/status/example_2.png</file>
   <file>../sources/status/example_3.png</file>
</qresource>
</RCC>

Then if your prefix, its "/", then use this for your QSS:

image:url(':/../sources/status/status.png');


问:
What's the usual way to setup a React and Express webApp
I am working on a project that requires developing a SPA using React, Node and Express. I understand Node/Express can serve static files and so my initial thought was I will write a react app and serve it via Express server.
But my Node/Express server also has other roles like, connecting with other microservices and fetch data, which will eventually passed to the UI controlled by react SPA.Sort of a controller! I am also planning to use Graphql instead of Rest.

Will the approach of using the Express server to do both serving the SPA and as a controller has any complication, or should I separate them as two different webapps.

I couldn't find many usecases  for my first approach (keeping both together),but I could see that splitting them as  two,like here https://dev-blog.apollodata.com/full-stack-react-graphql-tutorial-582ac8d24e3b

Any suggestions on what is the right approach?
Thanks

答:
If you just wanna serve a static file you can use Amazon S3 bucket to serve your React app and throw a a CDN in front of it for optimal load times.

Its nice to keep the separated but it also depends on the size and scope of the project. If you wanna expand it later it might hurt that your API is also serving the app and all its assets.

Where as separating them will split the load from actual API usage and static asset requests (images, index.html ect...).


问:
loading page shows for three seconds
I'm making a personal portfolio and want to show my site tagline for like 3 seconds (full screen), then fade out to show the actual website. What code is used to show some initial div then fade out to the actual website?</p>

答:
This works, with setTimeout(). After 3000 ms, we add the class hidden to the "loading element" that will hide it. You can customize the classes in order to achieve other types of animations. For example, now the animation is set to run for 500 ms.

setTimeout(function() {
  $('#loading').addClass('hidden');
}, 3000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#loading{
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color: gray;
  color: white;
  opacity: 1;
  transition: 0.5s;
  visibility: visible;
}
#loading.hidden{
  opacity: 0;
  visibility: hidden;
}</code>```

Loading site...

My site

Lorem ipsum

```
</div>
</div>
</p>

<p>If you prefer regular javascript, you can do it like this:</p>

```setTimeout(function() {
  var element = document.getElementById('loading');
  element.classList += " hidden";
}, 3000);
```

Title: loading page shows for three seconds

Body:
This works, with setTimeout(). After 3000 ms, we add the class hidden to the "loading element" that will hide it. You can customize the classes in order to achieve other types of animations. For example, now the animation is set to run for 500 ms.

setTimeout(function() {
  $('#loading').addClass('hidden');
}, 3000);

#loading{
  position:fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  background-color: gray;
  color: white;
  opacity: 1;
  transition: 0.5s;
  visibility: visible;
}
#loading.hidden{
  opacity: 0;
  visibility: hidden;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="loading">Loading site...</div>
<div id="site">
<h1>My site</h1>
<p>Lorem ipsum</p>
</div>

If you prefer regular javascript, you can do it like this:

setTimeout(function() {
  var element = document.getElementById('loading');
  element.classList += " hidden";
}, 3000);


问:
How can I dynamically add property from .cfg (OSGI) to persistence.xml (Hibernate)
The following case:

in my test_property.cfg file i have the property line:

```<code>...
hibernate/persistence.schema=TEST_1
...
</code>```

in the persistence.xml i have the setting line:

```<code>...
<property name="hibernate.default_schema" value="${hibernate/persistence.schema}" />
....
</code>```

But after build the project the value ${hibernate/persistence.schema} - did not replaced

xml files where I use blueprint tag - is ok, but I try to find out how to use replaceable values for persistence.xml from test property.cfg

答:
Cfg files are used only at runtime and not at build phase.

-At build phase you can resolve maven variables as you like by enabling ressources feltering on the folder containing your persistance.xml (here is some useful documentation).

-At runtime, it is not possible to bind a property from cfg file to an xml other file. Don't forget that the bundle is already built so it is a jar which is immutable.

My solution:

-define a new bean that consume the property from cfg. Here we are sure that any changes in the cfg at runtime will be immediately detected.

-in that bean, read the xml file and override the wanted property from the one already read from cfg.

Body:
The following case:

in my test_property.cfg file i have the property line:

...
hibernate/persistence.schema=TEST_1
...

in the persistence.xml i have the setting line:

...
<property name="hibernate.default_schema" value="${hibernate/persistence.schema}" />
....

But after build the project the value ${hibernate/persistence.schema} - did not replaced

xml files where I use blueprint tag - is ok, but I try to find out how to use replaceable values for persistence.xml from test property.cfg


问:
How to manually deploy artifacts in Nexus Repository Manager OSS 3
After installing Nexus Repository Manager OSS 3 I do not see option Artifact Upload to upload artifacts through web page.

In Nexus Repository Manager OSS 2.13 there is option to do that operation.

Anyone can show me the way how to upload artifacts to hosted repository in Nexus 3?

EDIT: From 3.9.0 version, this functionality is implemented.

答: My Team built a command line tool for uploading artifacts to nexus 3.x repository, Maybe it's will be helpful for you - Maven Artifacts Uploader</p>


问:
Updating sql-server table from mysql DB
Integrating 2 systems, we need to insert records from mysql to sql-server:

```<code>MYSQL                              SQLServer
  Table (Trigger) -----Insert----->  Table
</code>```

How do we do this integration between databases?

答: The trigger level integration is not possible, because MySQL does not have the mechanisms to do this work.</p>

Title: Updating sql-server table from mysql DB

Body:
Integrating 2 systems, we need to insert records from mysql to sql-server:

MYSQL                              SQLServer
  Table (Trigger) -----Insert----->  Table

How do we do this integration between databases?


问:
Self-installing a service that executes with parameters
I have a console application that will optionally self-install itself as a service. This works fine, but I'd like to embed some arguments into the service startup - similar to (for example) Google's Update Service (which has the parameter /medsvc)

So let's say I'd like my service to start

MyService.exe RUN Test1

.. so that'd start up MyService.exe with the parameters RUN and Test1.

I can install the service fine, using

```<code>  ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location});
</code>```

However, there's no parameters on the service. So if I try:

```<code>  ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location +" RUN Test1"});
</code>```

I get a FileNotFoundException. Giving that it's a array, I thought I'd try:

```<code>ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location,"RUN","Test1"});
</code>```

.. which gives the same exception, except that it's trying to find the file RUN now.

I can't find any specific documentation on how to achieve this - does anyone know if it is possible to embed parameters in with the service executable path? As another example, here's Google's Update Service with parameters - I'd like to ultimately achieve the same.

答:
I use a console application inside my windows service.  The Main method in Program.cs processes the command line args.  The OnStart method starts the console application.  It works great.

Windows Service to Run Constantly

HybridService Easily Switch Between Console Application and Service

Body:
I have a console application that will optionally self-install itself as a service. This works fine, but I'd like to embed some arguments into the service startup - similar to (for example) Google's Update Service (which has the parameter /medsvc)

So let's say I'd like my service to start

MyService.exe RUN Test1

.. so that'd start up MyService.exe with the parameters RUN and Test1.

I can install the service fine, using

  ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location});

However, there's no parameters on the service. So if I try:

  ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location +" RUN Test1"});

I get a FileNotFoundException. Giving that it's a array, I thought I'd try:

ManagedInstallerClass.InstallHelper(new[] {Assembly.GetExecutingAssembly().Location,"RUN","Test1"});

.. which gives the same exception, except that it's trying to find the file RUN now.

I can't find any specific documentation on how to achieve this - does anyone know if it is possible to embed parameters in with the service executable path? As another example, here's Google's Update Service with parameters - I'd like to ultimately achieve the same.


答:
At the bottom of your HTML document, add a fixed div:

```<code><div class="fixed">Tagline...</div>
</code>```

Then make it fixed and fill 100% with CSS:

```<code>.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
</code>```

So, now you have the tagline element on top of everything else. Last thing you need to do is fade out that element after 3 seconds. This can easily get achieved with jQuery for example:

```<code>setTimeout(function() {
  jQuery('.fixed').fadeOut();
}, 3000);
</code>```

That's all it takes

Title: loading page shows for three seconds

Body: I'm making a personal portfolio and want to show my site tagline for like 3 seconds (full screen), then fade out to show the actual website. What code is used to show some initial div then fade out to the actual website?

Body:
At the bottom of your HTML document, add a fixed div:

<div class="fixed">Tagline...</div>

Then make it fixed and fill 100% with CSS:

.fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

So, now you have the tagline element on top of everything else. Last thing you need to do is fade out that element after 3 seconds. This can easily get achieved with jQuery for example:

setTimeout(function() {
  jQuery('.fixed').fadeOut();
}, 3000);

That's all it takes


问:
AWS Elastic Beanstalk django app is not accepting AWS SES credentials
I am writing a simple Django app to send emails, and I am hosting on AWS' Elastic Beanstalk. Before I hosted on EB, the credentials worked (located in my ~/.aws/credentials). I am getting an AccessDenied error when I try to run the SES sendEmail function. I even put the AWS_ACCESS_KEY_ID and the AWS_SECRET_ACCESS_KEY in the settings.py file. I made sure my keys were correct, my email was verified with AWS, etc.</p>

答:
I couldn't find any other solution so I did the following:

client = boto3.client('ses', aws_access_key_id = "my key", aws_secret_access_key = "my secret key")

This solved the credentials problem. Not sure why boto3 couldn't find my credentials.


问:
c# Updating arrays in a dictionary and tuple in a loop?
I'm relatively new to C#, so your pardon for asking a question if posed before.

I need to populate the elements of arrays (e.g., double[]) 'on the fly' in a loop.  I know the maximum array length, but not the individual array values until run-time.

I have this code which initializes the Dictionary which contains a Tuple of arrays.  Given the allocation of the arrays in the tuple with empty slots, how do I add a double or string to the appropriate array in the tuple as the data are generated?

I demark my question below in the code.

```<code>public void Execute(SceneNode Parent)
{
    int maxAircraft = 10000;
    string vehicleState = "";
    double vehicleAlt;
    double vehicleVR;
    double vehicleTime;
    Dictionary<string, Tuple<double[], double[], double[], string[]>> flightData
            = new Dictionary<string, Tuple<double[], double[], double[], string[]>>(maxAircraft);

     //initializes flight state data dictionaries
     // flightList is a string[] already populated
     flightData = initializeFlightData(flightList, maxRecordCount);

//let's say that we start obtaining data for each entry in the dictionary
    foreach( var item in flightData )
    {
        //get the current values for the vehicle item at this time
        vehicleState = getVehicleStateMethod( item );
        vehicleAlt = getVehicleAltMethod( item );
        vehicleVR = getVehicleVrMethod( item );
        vehicleTime = getVehicleTimeMethod( item );
        var thisFlightData = flightData[aircraftName] as Tuple<double[], double[], double[], string[]>;
        //------------------------------------------------------

        ***// Question: how do I progressively add the values (vehicle*)
        // to each respective array such that the arrays are updated
        // (e.g., new value at bottom) with each new set of values?
        //------------------------------------------------------***

    }
}
//------------------------------------------------------------------------
private Dictionary<string, Tuple<double[], double[], double[], string[]>> initializeFlightData(string[] flightList, int maxRecordCount)
{
//values for the arrays are unknown at this point
    double[] dt = new double[maxRecordCount];
    double[] vr = new double[maxRecordCount];
    double[] FL = new double[maxRecordCount];
    string[] altState = new string[maxRecordCount];
    var flightStateData = new Tuple<double[], double[], double[], string[]>(dt, vr, FL, altState);

    Dictionary<string, Tuple<double[], double[], double[], string[]>> flightData
      = new Dictionary<string, Tuple<double[], double[], double[], string[]>>(flightList.Count());
    for (int i = 0; i < flightList.Count(); i++)
    {
        flightData.Add(flightList[i], flightStateData);
    }
    return flightData;
}
//----------------------------------------------------------------------------
</code>```

答:
To answer your specific question, create an index variable and use .Item1, .Item2, etc. Like so

```<code>int index = 0;
foreach( var item in flightData )
{
    //get the current values for the vehicle item at this time
    vehicleState = getVehicleStateMethod( item );
    vehicleAlt = getVehicleAltMethod( item );
    vehicleVR = getVehicleVrMethod( item );
    vehicleTime = getVehicleTimeMethod( item );
    var thisFlightData = flightData[aircraftName] as Tuple<double[], double[], double[], string[]>;
    //------------------------------------------------------

    ***// Question: how do I progressively add the values (vehicle*)
    // to each respective array such that the arrays are updated
    // (e.g., new value at bottom) with each new set of values?
    //------------------------------------------------------***
    thisFlightData.Item1[index] = // whatever
    // repeat for each array
    index++;
}
</code>```

However, this is a brittle solution that I don't think you're going to want in the long run. Create a class with meaningful names for each array. And better yet, as @EdPlunkett commented, use lists instead and just add each new item to the end of the appropriate list.

Also note that you don't need to cast the Tuple after retrieving it from your dictionary.

Body:
I'm relatively new to C#, so your pardon for asking a question if posed before.

I need to populate the elements of arrays (e.g., double[]) 'on the fly' in a loop.  I know the maximum array length, but not the individual array values until run-time.

I have this code which initializes the Dictionary which contains a Tuple of arrays.  Given the allocation of the arrays in the tuple with empty slots, how do I add a double or string to the appropriate array in the tuple as the data are generated?

I demark my question below in the code.

public void Execute(SceneNode Parent)
{
    int maxAircraft = 10000;
    string vehicleState = "";
    double vehicleAlt;
    double vehicleVR;
    double vehicleTime;
    Dictionary<string, Tuple<double[], double[], double[], string[]>> flightData
            = new Dictionary<string, Tuple<double[], double[], double[], string[]>>(maxAircraft);

     //initializes flight state data dictionaries
     // flightList is a string[] already populated
     flightData = initializeFlightData(flightList, maxRecordCount);

//let's say that we start obtaining data for each entry in the dictionary
    foreach( var item in flightData )
    {
        //get the current values for the vehicle item at this time
        vehicleState = getVehicleStateMethod( item );
        vehicleAlt = getVehicleAltMethod( item );
        vehicleVR = getVehicleVrMethod( item );
        vehicleTime = getVehicleTimeMethod( item );
        var thisFlightData = flightData[aircraftName] as Tuple<double[], double[], double[], string[]>;
        //------------------------------------------------------

        ***// Question: how do I progressively add the values (vehicle*)
        // to each respective array such that the arrays are updated
        // (e.g., new value at bottom) with each new set of values?
        //------------------------------------------------------***

    }
}
//------------------------------------------------------------------------
private Dictionary<string, Tuple<double[], double[], double[], string[]>> initializeFlightData(string[] flightList, int maxRecordCount)
{
//values for the arrays are unknown at this point
    double[] dt = new double[maxRecordCount];
    double[] vr = new double[maxRecordCount];
    double[] FL = new double[maxRecordCount];
    string[] altState = new string[maxRecordCount];
    var flightStateData = new Tuple<double[], double[], double[], string[]>(dt, vr, FL, altState);

    Dictionary<string, Tuple<double[], double[], double[], string[]>> flightData
      = new Dictionary<string, Tuple<double[], double[], double[], string[]>>(flightList.Count());
    for (int i = 0; i < flightList.Count(); i++)
    {
        flightData.Add(flightList[i], flightStateData);
    }
    return flightData;
}
//----------------------------------------------------------------------------

Body:
To answer your specific question, create an index variable and use .Item1, .Item2, etc. Like so

int index = 0;
foreach( var item in flightData )
{
    //get the current values for the vehicle item at this time
    vehicleState = getVehicleStateMethod( item );
    vehicleAlt = getVehicleAltMethod( item );
    vehicleVR = getVehicleVrMethod( item );
    vehicleTime = getVehicleTimeMethod( item );
    var thisFlightData = flightData[aircraftName] as Tuple<double[], double[], double[], string[]>;
    //------------------------------------------------------

    ***// Question: how do I progressively add the values (vehicle*)
    // to each respective array such that the arrays are updated
    // (e.g., new value at bottom) with each new set of values?
    //------------------------------------------------------***
    thisFlightData.Item1[index] = // whatever
    // repeat for each array
    index++;
}

However, this is a brittle solution that I don't think you're going to want in the long run. Create a class with meaningful names for each array. And better yet, as @EdPlunkett commented, use lists instead and just add each new item to the end of the appropriate list.

Also note that you don't need to cast the Tuple after retrieving it from your dictionary.


问:
How do I retrieve the value of a specific XML node by path?
I am looking for a Javascript solution to this problem:

I have an XML document which is loaded by way of a typical AJAX method:

var xml = http.responseXML;

Consider the following example xml snippet:

```<code><main>
    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>
 </main>
</code>```

I would like to get the value of a node by specifying the path as follows:

```<code>var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);
</code>```

I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName and the like.

How would I construct the method getNodeValueByPath or is there some construct in Javascript that allows for this?

I am not well versed in Javascript.

EDIT: Here is an example that shows my attempt at using XPath and how it is failing:

XML:

```<code><?xml version="1.0" ?>
<main xmlns="example.com">
  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>
</main>
</code>```

JavaScript: (these are the relevant functions only)

```<code>function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}
</code>```

I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.

Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com" from the XML document, the alert dialog appears with the text "false" as desired.

Debugging using Firebug shows that resultNode is an empty string as long as the namespace is declared.

答:
```<code>var xpathtosearchfor = '//div';
var result = new XPathEvaluator().evaluate(xpathtosearchfor,
    document.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
</code>```

In firefox at least

Body:
I am looking for a Javascript solution to this problem:

I have an XML document which is loaded by way of a typical AJAX method:

var xml = http.responseXML;

Consider the following example xml snippet:

    <primary>
         <enabled>true</enabled>
     </primary>
     <secondary>
         <enabled>true</enabled>
     </secondary>

I would like to get the value of a node by specifying the path as follows:

var second_enabled = getNodeValueByPath('main/secondary/enabled', xml);

I cannot find any concise way of doing something like this. I seem to be forced to iterate through node collections after using getElementsByTagName and the like.

How would I construct the method getNodeValueByPath or is there some construct in Javascript that allows for this?

I am not well versed in Javascript.

EDIT: Here is an example that shows my attempt at using XPath and how it is failing:

XML:

<?xml version="1.0" ?>

  <primary>
    <enabled>true</enabled>
  </primary>
  <secondary>
    <enabled>false</enabled>
  </secondary>

JavaScript: (these are the relevant functions only)

function useHttpResponse()
{
    if (http.readyState == 4)
    {
        if(http.status == 200)
        {
            var xml = http.responseXML;
            var evalue = getXMLValueByPath('/main/secondary/enabled', xml);
            alert(evalue);
        }
    }
}

function getXMLValueByPath(nodepath, xml)
{
    var result = xml.evaluate(nodepath, xml, null, XPathResult.STRING_TYPE, null).stringValue;
    return result;
}

I am using the above JavaScript without any additional libraries. I am using Mozilla Firefox 3.6.13 which uses the document.evaluate method to select nodes (according to this information from w3schools). This application is for internal use and does not have to work on multiple browsers.

Given these examples, the alert dialog will appear, but contain no text. If I remove the string xmlns="example.com" from the XML document, the alert dialog appears with the text "false" as desired.

Debugging using Firebug shows that resultNode is an empty string as long as the namespace is declared.

Body:
var xpathtosearchfor = '//div';
var result = new XPathEvaluator().evaluate(xpathtosearchfor,
    document.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

In firefox at least


问:
How to group by multiple values in same column in Oracle DB
I have a table for user access to a software application. A user may have multiple accesses with different aspects of the application denoted by alphanumeric ids. Similarly, multiple users may have same or different set of accesses.
For eg.

```<code>Table ACCESSTAB
USER             |       USERACCESS
-----------------------------------------
Cust1            |       BA1
Cust1            |       BB2
Cust2            |       BA1
Cust2            |       BB2
Cust3            |       CB1
Cust3            |       BA1
</code>```

I would like to group the customers based the same set of accesses. For eg:

```<code>USER             |       GROUP
-----------------------------------------
Cust1            |       Group1
Cust2            |       Group1
Cust3            |       Group2
</code>```

Currently, I have table created for some important users for this purpose as follows:

```<code>Table USERGROUP
GROUP             |       ACCESS
-----------------------------------------
Group1            |       BA1
Group1            |       BB2
Group2            |       CB1
Group2            |       BA1
</code>```

And the below query comparing both tables.

```<code>select a.USER,u.GROUP from ACCESSTAB a, USERGROUP u where not exists
(select USERACCESS from ACCESSTAB where USER=a.USER order by 1
MINUS
select ACCESS from USERGROUP where GROUP=u.GROUP order by 1)
</code>```

I would like to group the users without using the USERGROUP table as it is difficult to maintain for all users,not to mention addition of accesses would require manual configuration. Performance doesnt matter.

Any advice/assistance is welcome. Thanks in advance.

答:
Just a quick dirty example:

```<code>with AccessTab as
(SELECT '1' muser ,'BA1' useraccess from dual UNION ALL
SELECT '1','BB2' from dual UNION ALL
SELECT '2','BA1' from dual UNION ALL
SELECT '2','BB2' from dual UNION ALL
SELECT '3','CB1' from dual UNION ALL
SELECT '3','BA1' from dual),
cte as (SELECT muser, listagg(userAccess,',') within group (order by useraccess) GRP From AccessTab group by muser)
SELECT A.muser, dense_Rank() over ( order by a.GRP) as mGroup
FROM cte a
</code>```

Results in:

```<code>Muser    mGroup
2        1
1        1
3        2
</code>```

Body:
I have a table for user access to a software application. A user may have multiple accesses with different aspects of the application denoted by alphanumeric ids. Similarly, multiple users may have same or different set of accesses.
For eg.

Table ACCESSTAB
USER             |       USERACCESS
-----------------------------------------
Cust1            |       BA1
Cust1            |       BB2
Cust2            |       BA1
Cust2            |       BB2
Cust3            |       CB1
Cust3            |       BA1

I would like to group the customers based the same set of accesses. For eg:

USER             |       GROUP
-----------------------------------------
Cust1            |       Group1
Cust2            |       Group1
Cust3            |       Group2

Currently, I have table created for some important users for this purpose as follows:

Table USERGROUP
GROUP             |       ACCESS
-----------------------------------------
Group1            |       BA1
Group1            |       BB2
Group2            |       CB1
Group2            |       BA1

And the below query comparing both tables.

select a.USER,u.GROUP from ACCESSTAB a, USERGROUP u where not exists
(select USERACCESS from ACCESSTAB where USER=a.USER order by 1
MINUS
select ACCESS from USERGROUP where GROUP=u.GROUP order by 1)

I would like to group the users without using the USERGROUP table as it is difficult to maintain for all users,not to mention addition of accesses would require manual configuration. Performance doesnt matter.

Any advice/assistance is welcome. Thanks in advance.

Body:
Just a quick dirty example:

with AccessTab as
(SELECT '1' muser ,'BA1' useraccess from dual UNION ALL
SELECT '1','BB2' from dual UNION ALL
SELECT '2','BA1' from dual UNION ALL
SELECT '2','BB2' from dual UNION ALL
SELECT '3','CB1' from dual UNION ALL
SELECT '3','BA1' from dual),
cte as (SELECT muser, listagg(userAccess,',') within group (order by useraccess) GRP From AccessTab group by muser)
SELECT A.muser, dense_Rank() over ( order by a.GRP) as mGroup
FROM cte a

Results in:

Muser    mGroup
2        1
1        1
3        2


问:
Vuejs v-model special characters
Can you escape special characters with v-model? I am seeing an issue where I edit text that I receive from a data call. 'this' is showing as '&'#39;this'&#39' in the textarea when editing. I know of v-html, but can you use that with v-model? If not, what is another option?</p>

答:
The issue is that you have encoded text and you need to convert it to plain text. If it is proper HTML, one common trick is to set it as the innerHTML of a scratch div, and then extract the textContent from that div. I've created a little helper function in my snippet below to do that.

The text you give looks like it has some extra quotes in it, so there may be some more massaging of the data that you need to do to unpollute it, but the approach is still what I show here: fetch the text, unpollute it, and assign the unpolluted text to the variable you want to edit.

const scratchDiv = document.createElement('div');
function toPlainText(html) {
  scratchDiv.innerHTML = html;
  return scratchDiv.textContent;
}

new Vue({
  el: '#app',
  data: {
    plainText: ''
  },
  mounted() {
    // fetching code-polluted text
    this.plainText = toPlainText("'this&#39");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <textarea>
  {{plainText}}
  </textarea>
</div></code>```

Title: Vuejs v-model special characters

Body:
The issue is that you have encoded text and you need to convert it to plain text. If it is proper HTML, one common trick is to set it as the innerHTML of a scratch div, and then extract the textContent from that div. I've created a little helper function in my snippet below to do that.

The text you give looks like it has some extra quotes in it, so there may be some more massaging of the data that you need to do to unpollute it, but the approach is still what I show here: fetch the text, unpollute it, and assign the unpolluted text to the variable you want to edit.

const scratchDiv = document.createElement('div');
function toPlainText(html) {
  scratchDiv.innerHTML = html;
  return scratchDiv.textContent;
}

new Vue({
  el: '#app',
  data: {
    plainText: ''
  },
  mounted() {
    // fetching code-polluted text
    this.plainText = toPlainText("&#39;this&#39");
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <textarea>
  {{plainText}}
  </textarea>
</div>


问:
String concatenation in NATS server config
Can I make a concatenation of  variables and strings in NATS configuration file. For instance:

```<code>authorization {

  VERSION = "v1"

  REQUSTOR = {
    publish = ["msg." + $VERSION + ".bazz", "msg." + $VERSION + ".spam"]
    subscribe = "inbox." + $VERSION
  }

  users = [
     {
       user: foo,
       password: bar,
       permissions: $REQUSTOR
     }
  ]

}
</code>```

答: No this is not possible. I have even tried with "msg.$VERSION.bazz", but then it does not replace with the variable value and uses the string as-is.

Body:
Can I make a concatenation of  variables and strings in NATS configuration file. For instance:

authorization {

  VERSION = "v1"

  REQUSTOR = {
    publish = ["msg." + $VERSION + ".bazz", "msg." + $VERSION + ".spam"]
    subscribe = "inbox." + $VERSION
  }

  users = [
     {
       user: foo,
       password: bar,
       permissions: $REQUSTOR
     }
  ]

}


答:
Lambda layers don't have parameters.

Parameters, in the summary, are the variables that can "learn". Lambda layers never learn, they're functions created by you.

If you do intend to use a "Convolutional Layer", use it outside of the lambda layer.

Now, if you want to use a "convolution operation", then use it inside the lambda layer, but there is no learnable parameter, you define the filters yourself.

If you want to create a special layer that learns in a different way, then create a custom layer.

Title: Keras: Vanishing parameters in Conv2D layer within Lambda function

Body:
I am defining a Lambda layer with a function that uses the Conv2D layer.

def lambda_func(x,k):
    y = Conv2D(k, (3,3), padding='same')(x)
    return y

And calling it using

k = 64
x = Conv2D(k, (3,3), data_format='channels_last', padding='same', name='block1_conv1')(inputs)
y = Lambda(lambda_func, arguments={'k':k}, name = 'block1_conv1_loc')(x)

But in model.summary(), the lambda layer is showing no parameters!

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 224, 224, 3)       0
_________________________________________________________________
block1_conv1 (Conv2D)        (None, 224, 224, 64)      1792
_________________________________________________________________
block1_conv1_loc (Lambda)    (None, 224, 224, 64)      0
_________________________________________________________________
activation_1 (Activation)    (None, 224, 224, 64)      0
_________________________________________________________________
block1_pool (MaxPooling2D)   (None, 112, 112, 64)      0
_________________________________________________________________
flatten (Flatten)            (None, 802816)            0
_________________________________________________________________

(There is a Dense layer under it, and a Softmax 2-class classifier under that). How can I ensure the Conv2D parameters of the Lambda layer show up and are also trainable? I have also tried using trainable=True in the Lambda function.

def lambda_func(x,k):
    y = Conv2D(k, (3,3), padding='same', trainable=True)(x)
    return y

But that did not make any difference.


答:
This can be done with a LISTAGG() function.

```<code>SELECT USER, LISTAGG(USERACCESS, ', ') WITHIN GROUP (ORDER BY USER) AS USER_ACCESS_GROUP
FROM ACCESSTAB
GROUP BY USER
</code>```

The result will be

```<code>USERNAME| USER_ACCESS_GROUP
Cust1     BA1, BB2
Cust2     BA1, BB2
Cust3     BA1, CB1
</code>```

If you have a special name for each of these groups, you can wrap the LISTAGG() in a DECODE() function.

Title: How to group by multiple values in same column in Oracle DB

Body:
This can be done with a LISTAGG() function.

SELECT USER, LISTAGG(USERACCESS, ', ') WITHIN GROUP (ORDER BY USER) AS USER_ACCESS_GROUP
FROM ACCESSTAB
GROUP BY USER

The result will be

USERNAME| USER_ACCESS_GROUP
Cust1     BA1, BB2
Cust2     BA1, BB2
Cust3     BA1, CB1

If you have a special name for each of these groups, you can wrap the LISTAGG() in a DECODE() function.


问:
Add FB pixel event code into button into Squarespace
trying to get FB event code to fire on a button click (Download button on this page: https://frequencydigital.com/guide-download/).

I saw this earlier post, however the code suggested by Brandon is not working for me:
Add FB pixel event code into button - Squarespace

Per Facebook, they provide this code to use, however not working either:

```<code><!-- The below method uses jQuery, but that is not required -->
<button id="addToCartButton">Add To Cart</button>
<!-- Add event to the button's click handler -->
<script type="text/javascript">
$( '#addToCartButton' ).click(function() {
fbq('track', 'AddToCart', {
content_ids: ['1234'],
content_type: 'product',value: 2.99,currency: 'USD'
});
});
</script>
</code>```

When I view source for the page I'm trying to update, the button code is:

```<code><div class="form-button-wrapper form-button-wrapper--align-center">
    <input class="button sqs-system-button sqs-editable-button"
type="submit" value="Download"/>
  </div>
</code>```

Not sure what I'm doing wrong here.

答:
The code from the answer to which you linked needs to be modified slightly for your case, where a form submit button is used rather than a button block.

```<code><script>
    (function() {
        var btns = document.querySelectorAll('form input[type="submit"]');
        var i, I;

        for (i=0, I=btns.length; i<I; i++) {
            btns[i].addEventListener("click", function() {
                fbq("track", "Lead");
            });
        }
    })();
</script>
</code>```

This code is written so that it will work even if multiple such forms are used on a single page. If you were sure to only have one such form/button, it could be simplified a bit.

Note that all of the suggestions and considerations from the previous answer still apply. In addition, you may choose a different code other than "lead".

Body:
trying to get FB event code to fire on a button click (Download button on this page: https://frequencydigital.com/guide-download/).

I saw this earlier post, however the code suggested by Brandon is not working for me:
Add FB pixel event code into button - Squarespace

Per Facebook, they provide this code to use, however not working either:

<button id="addToCartButton">Add To Cart</button>

When I view source for the page I'm trying to update, the button code is:

    <input class="button sqs-system-button sqs-editable-button"
type="submit" value="Download"/>

Not sure what I'm doing wrong here.

Body:
The code from the answer to which you linked needs to be modified slightly for your case, where a form submit button is used rather than a button block.

<script>
    (function() {
        var btns = document.querySelectorAll('form input[type="submit"]');
        var i, I;

        for (i=0, I=btns.length; i<I; i++) {
            btns[i].addEventListener("click", function() {
                fbq("track", "Lead");
            });
        }
    })();
</script>

This code is written so that it will work even if multiple such forms are used on a single page. If you were sure to only have one such form/button, it could be simplified a bit.

Note that all of the suggestions and considerations from the previous answer still apply. In addition, you may choose a different code other than "lead".


问:
How to create a summary using dictionaries based on an excel with empty cells using python? (vlookup with python)
I have an Excel spreadsheet. In column A I have an ID, column B I have the description.

The same ID and same text repeats x times, but the final row of that ID has no description. And then the ID changes.

Here is a screenshot of the file:

I want with Python to read downwards. When it finds a new ID, append it to a dictionary with its description, and then go to the next ID with its description.

It´s like the vlookup formula, but with Python.

答:
I think this does what you're trying to achieve:

```<code>import csv
datafile = open('asdf.csv', 'r')
datareader = csv.reader(datafile,delimiter=',')
data = []
for row in datareader:
    data.append(row)

output = []
ids = []
for d in data:
    if d[0] not in ids:
        ids.append(d[0])
        output.append(d)

print(output)
</code>```

From this:

You get this:

```<code>[['\xef\xbb\xbf1', 'ab'], ['1', 'b'], ['2', 'ab'], ['3', 'z'], ['33', 'ab']]
</code>```

Body:
I think this does what you're trying to achieve:

import csv
datafile = open('asdf.csv', 'r')
datareader = csv.reader(datafile,delimiter=',')
data = []
for row in datareader:
    data.append(row)

output = []
ids = []
for d in data:
    if d[0] not in ids:
        ids.append(d[0])
        output.append(d)

print(output)

From this:

You get this:

[['\xef\xbb\xbf1', 'ab'], ['1', 'b'], ['2', 'ab'], ['3', 'z'], ['33', 'ab']]