问:
XSLT to return input xml as is, except replacing a string to another regardless where it may appear
My goal is to produce an XSLT output that is the same as the input, with the exception of the replacement of a string to another, regardless where it may appear. The string to replace can be data, xml tag name, namespace name URI or anything else within the xml document, I'd like it replaced either way.

Example xml input:

```<code><?xml version="1.0" encoding="utf-8"?>

<ns:a xmlns:ns="http://www.toreplace.com" xmlns:nsB="http://www.toreplace.com/anything">
  <nsB:b>
    toreplace
    <toreplace>
      data toreplace
    </toreplace>
    toreplace
  </nsB:b>
</ns:a>
</code>```

Desired output:

```<code><?xml version="1.0" encoding="utf-8"?>

<ns:a xmlns:ns="http://www.replaceto.com" xmlns:nsB="http://www.replaceto.com/anything">
  <nsB:b>
    replaceto
    <replaceto>
      data replaceto
    </replaceto>
    replaceto
  </nsB:b>
</ns:a>
</code>```

My best try so far:

```<code><?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output omit-xml-declaration="no" indent="no"/>

<xsl:template match="*">
    <xsl:copy-of select="replace(., 'toreplace', 'replaceto')"/>
</xsl:template>

</xsl:stylesheet>
</code>```

This produces output:

```<code><?xml version="1.0" encoding="UTF-8"?>

    replaceto

      data replaceto

    replaceto
</code>```

The problem I'm facing is that the output produced by the replace function omits everything but data, even though the same XPath expression (dot) does not omit anything in the following example:

```<code><?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output omit-xml-declaration="no" indent="no"/>

<xsl:template match="*">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>
</code>```

produces:

```<code><?xml version="1.0" encoding="UTF-8"?>
<ns:a xmlns:ns="http://www.toreplace.com" xmlns:nsB="http://www.toreplace.com/anything">
  <nsB:b>
    toreplace
    <toreplace>
      data toreplace
    </toreplace>
    toreplace
  </nsB:b>
</ns:a>
</code>```

What causes the different behavior of the seemingly same XPath expression? How do I resolve this? Do I need a completely different approach to achieve my goal?

答:
You can use this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <!--Template to change namespace -->
    <xsl:template match="*[namespace-uri()[matches(., 'toreplace')]]" priority="1">
        <xsl:element name="{replace(name(), 'toreplace', 'replaceto')}" namespace="{replace(namespace-uri(), 'toreplace', 'replaceto')}">
            <xsl:apply-templates select="node()|@*"></xsl:apply-templates>
        </xsl:element>
    </xsl:template>

    <!--Identical Transform -->
    <xsl:template match="node()|@*">
        <xsl:copy copy-namespaces="no">
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <!--Template for Text Change -->
    <xsl:template match="text()[matches(., 'toreplace')]">
        <xsl:value-of select="replace(., 'toreplace', 'replaceto')"/>
    </xsl:template>

    <!--Template for Element name Change -->
    <xsl:template match="*[matches(local-name(), 'toreplace')]">
        <xsl:element name="{replace(local-name(), 'toreplace', 'replaceto')}">
            <xsl:apply-templates select="node()|@*"></xsl:apply-templates>
        </xsl:element>
    </xsl:template>

    <!--Template for Attribute Name and Value Change -->
    <xsl:template match="@*[matches(., 'toreplace') or matches(name(), 'toreplace')]">
        <xsl:attribute name="{replace(local-name(), 'toreplace', 'replaceto')}">
            <xsl:value-of select="replace(., 'toreplace', 'replaceto')"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>
</code>```

Output

```<code><ns:a xmlns:ns="http://www.replaceto.com">
    <nsB:b xmlns:nsB="http://www.toreplace.com/anything">
        replaceto
        <replaceto>
            data replaceto
        </replaceto>
        replaceto
    </nsB:b>
</ns:a>
</code>```

Body:
My goal is to produce an XSLT output that is the same as the input, with the exception of the replacement of a string to another, regardless where it may appear. The string to replace can be data, xml tag name, namespace name URI or anything else within the xml document, I'd like it replaced either way.

Example xml input:

<?xml version="1.0" encoding="utf-8"?>

<ns:a xmlns:ns="http://www.toreplace.com" xmlns:nsB="http://www.toreplace.com/anything">
  <nsB:b>
    toreplace
    <toreplace>
      data toreplace
    </toreplace>
    toreplace
  </nsB:b>
</ns:a>

Desired output:

<?xml version="1.0" encoding="utf-8"?>

<ns:a xmlns:ns="http://www.replaceto.com" xmlns:nsB="http://www.replaceto.com/anything">
  <nsB:b>
    replaceto
    <replaceto>
      data replaceto
    </replaceto>
    replaceto
  </nsB:b>
</ns:a>

My best try so far:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output omit-xml-declaration="no" indent="no"/>

<xsl:template match="*">
    <xsl:copy-of select="replace(., 'toreplace', 'replaceto')"/>
</xsl:template>

</xsl:stylesheet>

This produces output:

<?xml version="1.0" encoding="UTF-8"?>

    replaceto

      data replaceto

    replaceto

The problem I'm facing is that the output produced by the replace function omits everything but data, even though the same XPath expression (dot) does not omit anything in the following example:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output omit-xml-declaration="no" indent="no"/>

<xsl:template match="*">
    <xsl:copy-of select="."/>
</xsl:template>

</xsl:stylesheet>

produces:

<?xml version="1.0" encoding="UTF-8"?>
<ns:a xmlns:ns="http://www.toreplace.com" xmlns:nsB="http://www.toreplace.com/anything">
  <nsB:b>
    toreplace
    <toreplace>
      data toreplace
    </toreplace>
    toreplace
  </nsB:b>
</ns:a>

What causes the different behavior of the seemingly same XPath expression? How do I resolve this? Do I need a completely different approach to achieve my goal?

Body:
You can use this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="2.0">

    <!--Template to change namespace -->
    <xsl:template match="*[namespace-uri()[matches(., 'toreplace')]]" priority="1">
        <xsl:element name="{replace(name(), 'toreplace', 'replaceto')}" namespace="{replace(namespace-uri(), 'toreplace', 'replaceto')}">
            <xsl:apply-templates select="node()|@*"></xsl:apply-templates>
        </xsl:element>
    </xsl:template>

    <!--Identical Transform -->
    <xsl:template match="node()|@*">
        <xsl:copy copy-namespaces="no">
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <!--Template for Text Change -->
    <xsl:template match="text()[matches(., 'toreplace')]">
        <xsl:value-of select="replace(., 'toreplace', 'replaceto')"/>
    </xsl:template>

    <!--Template for Element name Change -->
    <xsl:template match="*[matches(local-name(), 'toreplace')]">
        <xsl:element name="{replace(local-name(), 'toreplace', 'replaceto')}">
            <xsl:apply-templates select="node()|@*"></xsl:apply-templates>
        </xsl:element>
    </xsl:template>

    <!--Template for Attribute Name and Value Change -->
    <xsl:template match="@*[matches(., 'toreplace') or matches(name(), 'toreplace')]">
        <xsl:attribute name="{replace(local-name(), 'toreplace', 'replaceto')}">
            <xsl:value-of select="replace(., 'toreplace', 'replaceto')"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>

Output

<ns:a xmlns:ns="http://www.replaceto.com">
    <nsB:b xmlns:nsB="http://www.toreplace.com/anything">
        replaceto
        <replaceto>
            data replaceto
        </replaceto>
        replaceto
    </nsB:b>
</ns:a>


来源: stackexchange

问:
Picker Error Message on Exit (encountered while discovering extensions: Error Domain=PlugInKit Code=13) With Swift 4 - Xcode 9
Similar to

PhotoPicker discovery error: Error Domain=PlugInKit Code=13

and also to

https://forums.developer.apple.com/thread/82105

BUT I have tried all of these suggestions and still get an error in the debug log. Running Swift 4 XCode 9A235

What was suggest at the various places was ...

some people said add @objc

some people said add internal

some people suggested adding _ and making sure using Any and not
AnyObject

some people said to use didFinishPickingImageWithInfo (this returns
no image for me)

some people said dismsss the picker, others said dismiss self, others
said dismiss both

some said add the 'Privacy... ' to plist (done)

added import Photos

added prior call to force PHPhotoLibrary.requestAuthorization() {
(status) -> Void in ...

I DID NOT get this issues in Swift 3 - previous xcode.
But with Swift 4, I tried everying I saw suggested and I still get the following error

[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

The picker works fine and I DO end up selecting an image from photos, but I get this error message on picker exit (cancel or select), every time...

Any suggestions how to stop the error message? Other than the list of things offered at the other two links (summarized above)

my method

```<code>@objc internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    imageSelected = nil

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        imageSelected = editedImage
    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
        imageSelected = originalImage
    }

    if  imageSelected != nil {
        handleSelectedImage()   // override in subclass to do something with the returned image
    }
    picker.dismiss(animated: true, completion: nil)   // mess of calling both dismiss to see if it helps - it does not
    dismiss(animated: true, completion: nil)
}
</code>```

答:
It is because your app uses photo library (in this case, using UIImagePickerController) without asking for user permission. As an example, if I want to show the image picker when the add button was tapped:

```<code>@IBAction func addButtonTapped(_ sender: UIBarButtonItem) {
    checkPermission {
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!

        picker.delegate = self
        picker.allowsEditing = false
        self.present(picker, animated: true, completion: nil)
    }
}

func checkPermission(hanler: @escaping () -> Void) {
    let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
    switch photoAuthorizationStatus {
    case .authorized:
        // Access is already granted by user
        hanler()
    case .notDetermined:
        PHPhotoLibrary.requestAuthorization { (newStatus) in
            if newStatus == PHAuthorizationStatus.authorized {
                // Access is granted by user
                hanler()
            }
        }
    default:
        print("Error: no access to photo album.")
    }
}
</code>```

In addition, need to add this to your plist as well:

```<code><key>NSPhotoLibraryUsageDescription</key>
<string>So that you can add images for your cloth. </string>
</code>```

which is the message displayed in the permission dialog.

ContentLicense: CC BY-SA 3.0

Body:
Similar to

PhotoPicker discovery error: Error Domain=PlugInKit Code=13

and also to

https://forums.developer.apple.com/thread/82105

BUT I have tried all of these suggestions and still get an error in the debug log. Running Swift 4 XCode 9A235

What was suggest at the various places was ...

some people said add @objc

some people said add internal

some people suggested adding _ and making sure using Any and not
AnyObject

some people said to use didFinishPickingImageWithInfo (this returns
no image for me)

some people said dismsss the picker, others said dismiss self, others
said dismiss both

some said add the 'Privacy... ' to plist (done)

added import Photos

added prior call to force PHPhotoLibrary.requestAuthorization() {
(status) -> Void in ...

I DID NOT get this issues in Swift 3 - previous xcode.
But with Swift 4, I tried everying I saw suggested and I still get the following error

[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

The picker works fine and I DO end up selecting an image from photos, but I get this error message on picker exit (cancel or select), every time...

Any suggestions how to stop the error message? Other than the list of things offered at the other two links (summarized above)

my method

@objc internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    imageSelected = nil

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        imageSelected = editedImage
    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
        imageSelected = originalImage
    }

    if  imageSelected != nil {
        handleSelectedImage()   // override in subclass to do something with the returned image
    }
    picker.dismiss(animated: true, completion: nil)   // mess of calling both dismiss to see if it helps - it does not
    dismiss(animated: true, completion: nil)
}

Body:
It is because your app uses photo library (in this case, using UIImagePickerController) without asking for user permission. As an example, if I want to show the image picker when the add button was tapped:

@IBAction func addButtonTapped(_ sender: UIBarButtonItem) {
    checkPermission {
        let picker = UIImagePickerController()
        picker.sourceType = .photoLibrary
        picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!

        picker.delegate = self
        picker.allowsEditing = false
        self.present(picker, animated: true, completion: nil)
    }
}

func checkPermission(hanler: @escaping () -> Void) {
    let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
    switch photoAuthorizationStatus {
    case .authorized:
        // Access is already granted by user
        hanler()
    case .notDetermined:
        PHPhotoLibrary.requestAuthorization { (newStatus) in
            if newStatus == PHAuthorizationStatus.authorized {
                // Access is granted by user
                hanler()
            }
        }
    default:
        print("Error: no access to photo album.")
    }
}

In addition, need to add this to your plist as well:

<key>NSPhotoLibraryUsageDescription</key>
<string>So that you can add images for your cloth. </string>

which is the message displayed in the permission dialog.


问:
How do you derive a component's size using @Self() decorator?
I'm working on a mechanism for calculating and setting CSS Grid layouts.  Part of doing this requires my components being able to detect their own size in pixels.  So far I've come across the @Self() decorator, but now that I'm actually at the point of using it I can't figure out how to derive any information from it about the component.

I made a class called GridFactory that I'm using to extend my component classes which is making it extra confusing trying to figure out how to add the super call properly in the constructor.  So far my class looks like this.

```<code>export class GridFactory {
    ScreenCore   : ScrnCore = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener('window:resize', ['$event']) onResize(event){ this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){
        this.checkScrn();
    }

    checkScrn( specs: appSpecs ){
        this.ScreenCore.Width   = specs.width;
        this.ScreenCore.Height  = specs.height;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}
</code>```

So far I'm only trying to call it on the app.component which I have set up like this

```<code>@Component({
  selector    : 'app',
  templateUrl : './app.component.html'
})

export class AppComponent extends GridFactory implements OnInit {
    MainFrame: SiteFrame;

    @HostListener('window:resize', ['$event']) onResize(event){ this.calcScreen(); }

    constructor(public appSpecs: ElementRef){
        super(appSpecs);
    }

    ngOnInit(){ this.calcScreen(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }
}
</code>```

as of right now I'm getting this error in regards to the appScpecs variable

TS2304: Cannot find name 'appSpecs'.

I've been looking up everything I can think of to look up to find more info about this decorator but I just haven't found anything yet.  Can anyone help me figure this out?

UPDATE

I changed the function to this

```<code>checkScrn(){
    this.ScreenCore.Width   = this.appSpecs.nativeElement.width;
    this.ScreenCore.Height  = this.appSpecs.nativeElement.height;

    this.activteGrid( this.ScreenCore );
    console.log(this.appSpecs.nativeElement.width);
}
</code>```

I also decided to make one component class with everything in it just to put it all in one place until I figure out how to get it working.  I'm not getting any errors but the results are turning up null on my screen and undefined in the console.

答:
Try

```<code>checkScrn(){
    this.ScreenCore.Width   = this.appSpecs.width;
    this.ScreenCore.Height  = this.appSpecs.height;

    this.activteGrid( this.ScreenCore );
}
</code>```

appSpecs is a property, not a type, so using it as a parameter type is incorrect. You should be able to access this.appSpecs in any function of the class anyway.

Body:
I'm working on a mechanism for calculating and setting CSS Grid layouts.  Part of doing this requires my components being able to detect their own size in pixels.  So far I've come across the @Self() decorator, but now that I'm actually at the point of using it I can't figure out how to derive any information from it about the component.

I made a class called GridFactory that I'm using to extend my component classes which is making it extra confusing trying to figure out how to add the super call properly in the constructor.  So far my class looks like this.

export class GridFactory {
    ScreenCore   : ScrnCore = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener('window:resize', ['$event']) onResize(event){ this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){
        this.checkScrn();
    }

    checkScrn( specs: appSpecs ){
        this.ScreenCore.Width   = specs.width;
        this.ScreenCore.Height  = specs.height;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}

So far I'm only trying to call it on the app.component which I have set up like this

@Component({
  selector    : 'app',
  templateUrl : './app.component.html'
})

export class AppComponent extends GridFactory implements OnInit {
    MainFrame: SiteFrame;

    @HostListener('window:resize', ['$event']) onResize(event){ this.calcScreen(); }

    constructor(public appSpecs: ElementRef){
        super(appSpecs);
    }

    ngOnInit(){ this.calcScreen(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }
}

as of right now I'm getting this error in regards to the appScpecs variable

TS2304: Cannot find name 'appSpecs'.

I've been looking up everything I can think of to look up to find more info about this decorator but I just haven't found anything yet.  Can anyone help me figure this out?

UPDATE

I changed the function to this

checkScrn(){
    this.ScreenCore.Width   = this.appSpecs.nativeElement.width;
    this.ScreenCore.Height  = this.appSpecs.nativeElement.height;

    this.activteGrid( this.ScreenCore );
    console.log(this.appSpecs.nativeElement.width);
}

I also decided to make one component class with everything in it just to put it all in one place until I figure out how to get it working.  I'm not getting any errors but the results are turning up null on my screen and undefined in the console.

Body:
Try

checkScrn(){
    this.ScreenCore.Width   = this.appSpecs.width;
    this.ScreenCore.Height  = this.appSpecs.height;

    this.activteGrid( this.ScreenCore );
}

appSpecs is a property, not a type, so using it as a parameter type is incorrect. You should be able to access this.appSpecs in any function of the class anyway.


问:
can Socrata's API accept CONJUNCTIONS of WHERE clauses?
i want to combine two WHERE conditions, eg using a FROM-DATE and a TO-DATE to restrict results to a data range, but don't see a way to combine these in SoQL?</p>

答: Sure thing! You can use all the boolean operators listed within https://dev.socrata.com/docs/queries/where.html to combine clauses in a $where query.


问:
Array not populating in subscribe() in Angular
```<code>onButtonClick() {
this.http.get('ip:port/abc')
.subscribe(res => {
  console.log(res);
  [].push.apply(this.dummy, res);
  console.log(this.dummy);
});
}
</code>```

when I check the console, the res object is being printed as below:

```<code>{lat: 29, lon: 82, label: "A", draggable: true}
</code>```

But when I populate thee dummy array with the res object, it is not getting populated. Printing it on the console shows an array with zero length.

答:
Use it like this :</p>

```<code>dummy : any = [];
onButtonClick() {
     this.http.get('ip:port/abc')
     .subscribe(res => {
     console.log(res);
     this.dummy.push(res);
     console.log(this.dummy);
  });
}
</code>```

Body:
onButtonClick() {
this.http.get('ip:port/abc')
.subscribe(res => {
  console.log(res);
  [].push.apply(this.dummy, res);
  console.log(this.dummy);
});
}

when I check the console, the res object is being printed as below:

{lat: 29, lon: 82, label: "A", draggable: true}

But when I populate thee dummy array with the res object, it is not getting populated. Printing it on the console shows an array with zero length.

Body:
Use it like this :

dummy : any = [];
onButtonClick() {
     this.http.get('ip:port/abc')
     .subscribe(res => {
     console.log(res);
     this.dummy.push(res);
     console.log(this.dummy);
  });
}


问:
How do I ensure only single docker image is running?
I'm building an application that I run in docker. I only want a single version of my application running at a given time, so I'm trying to stop the old iterations of containers as I start the new one.

```<code>mvn package docker:build
docker ps -q --filter ancestor="paul/my-app" | xargs docker stop
cd ./target/docker
docker build .
docker run -d paul/my-app
</code>```

This creates the image as I expect and runs it like I want. If I run my script twice, however, I sometimes get two images running at the same time. Trying to diagnose this weirdness I ran this:

```<code>docker ps -a | awk '{ print $1,$2 }'
</code>```

Now I see something I don't understand. The output of docker ps -a is

```<code>CONTAINER ID
aeb4c0486ef5 paul/my-app
b32be5e53df0 6d965c3e84f1
</code>```

which means that I can't reliably stop containers by image name.

Can someone explain to me why the ID is a hash instead of paul/my-app?  How can I reliably ensure only one version of my image exists/is running at any given time?

答:
Thanks to user larsks for the --name argument. I've gotten my application acting as a singleton as I develop it.

I've split this into two discrete scripts.

run-docker.sh

```<code>#!/usr/bin/env bash
set -e
mvn package docker:build
./stop-docker.sh
cd ./target/docker
docker build .
docker run -d --name paul-my-app --restart unless-stopped paul/my-app
docker logs --follow paul-my-app
</code>```

And it's counterpart

stop-docker.sh

```<code>#!/usr/bin/env bash
set -e
docker stop paul-my-app || true
docker image prune -f
docker container prune -f
docker volume prune -f
docker network prune -f
docker system prune -f
</code>```

Body:
I'm building an application that I run in docker. I only want a single version of my application running at a given time, so I'm trying to stop the old iterations of containers as I start the new one.

mvn package docker:build
docker ps -q --filter ancestor="paul/my-app" | xargs docker stop
cd ./target/docker
docker build .
docker run -d paul/my-app

This creates the image as I expect and runs it like I want. If I run my script twice, however, I sometimes get two images running at the same time. Trying to diagnose this weirdness I ran this:

docker ps -a | awk '{ print $1,$2 }'

Now I see something I don't understand. The output of docker ps -a is

CONTAINER ID
aeb4c0486ef5 paul/my-app
b32be5e53df0 6d965c3e84f1

which means that I can't reliably stop containers by image name.

Can someone explain to me why the ID is a hash instead of paul/my-app?  How can I reliably ensure only one version of my image exists/is running at any given time?

Body:
Thanks to user larsks for the --name argument. I've gotten my application acting as a singleton as I develop it.

I've split this into two discrete scripts.

run-docker.sh

#!/usr/bin/env bash
set -e
mvn package docker:build
./stop-docker.sh
cd ./target/docker
docker build .
docker run -d --name paul-my-app --restart unless-stopped paul/my-app
docker logs --follow paul-my-app

And it's counterpart

stop-docker.sh

#!/usr/bin/env bash
set -e
docker stop paul-my-app || true
docker image prune -f
docker container prune -f
docker volume prune -f
docker network prune -f
docker system prune -f


问:
Alternative to finding elements using hard coded Xpath
I have a html below that contains simply div tags that within contain text fields and a display for validation messages:

```<code><div class="payment-form">
   <div class="payment-form__payment-type">
      <div class="false-label">Payment type</div>
      <div class="form-column">
         <div class="false-label">Name on card</div>
         <div class="form-element-wrapper form-element-wrapper--input-text clearfix form-element-wrapper--error form-element-wrapper--show-label"><label for="name-on-card">Name on card</label> <input name="name-on-card" data-payment-jet2="holderName" id="name-on-card" type="text" maxlength="32" data-vv-id="_0zd5ajemk" aria-required="true" aria-invalid="true"></div>
         <p class="validation-message validation-message--active" style="">Please correct the name on card</p>
      </div>
      <div class="form-column">
         <div class="false-label">Card number</div>
         <div class="form-element-wrapper form-element-wrapper--input-text clearfix form-element-wrapper--error form-element-wrapper--show-label"><label for="card-number">e.g 1111-2222-3333-4444</label> <input type="hidden" data-payment-jet2="number"> <input name="card-number" id="card-number" type="tel" maxlength="23" class="js-payment-card-number" data-vv-id="_wn4jqw3yg" aria-required="true" aria-invalid="true"></div>
         <p class="validation-message validation-message--active" style="">Please correct the card number</p>
      </div>
   </div>
</div>
</code>```

Now the problem I am having is with the validation messages which are the same class:

```<code><p class="validation-message validation-message--active" style="">
</code>```

In my selenium I want to ensure the correct validation is displayed but because they have the same class, I cannot differentiate between then unless I use a hard coded dirty xpath like:

```<code>public static By NameOnCardValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[3]/p");
public static By CardNumberValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[4]/p");
</code>```

Thus makes maintenance difficult as if there are any changes to the website, then I will have to keep updating these xpaths.

My question is that can you see a way where I can locate the validation messages a lot easier without entering a hard coded xpath like above? Just to let you know the messages in the validation may change so it would not be a good idea to look for the text within the validation message.

Thanks,

答:
As you mentioned that the messages in the validation may change so we will create xpath those are independent of the Messages. Through our dynamic xpath we will be able to control all the
 tags which may contain any message as follows :

```<code>public static By NameOnCardValidation => By.XPath("//div[@class='payment-form']//following::p[1]");
public static By CardNumberValidation => By.XPath("//div[@class='payment-form']//following::p[2]");
</code>```

Body:
I have a html below that contains simply div tags that within contain text fields and a display for validation messages:

Payment type

Name on card

Name on card <input name="name-on-card" data-payment-jet2="holderName" id="name-on-card" type="text" maxlength="32" data-vv-id="_0zd5ajemk" aria-required="true" aria-invalid="true">

Please correct the name on card

Card number

e.g 1111-2222-3333-4444 <input type="hidden" data-payment-jet2="number"> <input name="card-number" id="card-number" type="tel" maxlength="23" class="js-payment-card-number" data-vv-id="_wn4jqw3yg" aria-required="true" aria-invalid="true">

Please correct the card number

Now the problem I am having is with the validation messages which are the same class:

In my selenium I want to ensure the correct validation is displayed but because they have the same class, I cannot differentiate between then unless I use a hard coded dirty xpath like:

public static By NameOnCardValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[3]/p");
public static By CardNumberValidation => By.XPath("/html/body/div[1]/div[3]/section/div[6]/div[2]/div/div/div/div/div[4]/p");

Thus makes maintenance difficult as if there are any changes to the website, then I will have to keep updating these xpaths.

My question is that can you see a way where I can locate the validation messages a lot easier without entering a hard coded xpath like above? Just to let you know the messages in the validation may change so it would not be a good idea to look for the text within the validation message.

Thanks,

Body:
As you mentioned that the messages in the validation may change so we will create xpath those are independent of the Messages. Through our dynamic xpath we will be able to control all the <p> tags which may contain any message as follows :

public static By NameOnCardValidation => By.XPath("//div[@class='payment-form']//following::p[1]");
public static By CardNumberValidation => By.XPath("//div[@class='payment-form']//following::p[2]");


问:
UITabBar's navigationbar hides navigationbar when view is presented modally
I have app with UItabBarTemplate with navigation controller.

On selecting tab bar ViewControllerA is shown which on button touch pushes UIPieChartTabController which inherits "UIViewController".

Now I want another tab bar in UIPieChartTabController.

so in viewDidLoad of UIPieChartTabController

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

     UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
     contentView.backgroundColor = [UIColor whiteColor];
     self.view = contentView;
     [contentView release];
      UITabBarController *tabbar= [[UITabBarController alloc] init];
     tabbar.view.frame = CGRectMake(0, 0, 320, 460);
    piechartViewController *pr=[[piechartViewController alloc]init];
    pr.tagInAction=1;
    pr.title=@"Type";
    pr.tabBarItem.image=[UIImage imageNamed:@"trend.png"];
    pr.sDate=sDate;
    pr.nDate=nDate;

    piechartViewController *pr1=[[piechartViewController alloc]init];
    pr1.title=@"category";
    pr1.tagInAction=4;
    pr1.sDate=sDate;
    pr1.nDate=nDate;

    piechartViewController *pr2=[[piechartViewController alloc]init];
    pr2.title=@"paidWith";
    pr2.tagInAction=3;
    pr2.sDate=sDate;
    pr2.nDate=nDate;

    //tabbar.tabBar.delegate=self;
//this gave me error

    ExportRep *pr3=[[ExportRep alloc]init];
    pr3.tabBarItem.image=[UIImage imageNamed:@"database.png"];
    pr3.title=@"Export Expenses";

    [tabbar setViewControllers:[NSArray arrayWithObjects:pr,pr1,pr2,pr3,nil]];
    [self.view addSubview:tabbar.view];
    [pr release];
    [pr1 release];
    [pr2 release];
}</code>```

This piece of code worked but now when I select tab of viewController ExportRep type I tried

```<code>[self presentModalViewController:objMFMailComposeViewController animated:YES];
</code>```

but navigationController of objMFMailComposeViewController hides behind navigationController of view that is presenting objMFMailComposeViewController.

Also viewWillAppear viewDidAppear of all the view controller which are bound to tab bar never gets called.

But none of this problem occurs for tabbar and viewcontroller which gets created by UITabbarTemplate.

Why Is it so? Whats wrong when I create Tab bar?

答:
The reason why new view which is being presented modally got its navigation bar hidden lies in  [self.view addSubview:tabbar.view];

so it got room to present its view only in parent controllers view thus got cut its navigation bar.

so to hack it I kept tab selected and instead of presenting it in selected view controller,have presented it in  main view controller only.

ContentLicense: CC BY-SA 2.5

Body:
I have app with UItabBarTemplate with navigation controller.

On selecting tab bar ViewControllerA is shown which on button touch pushes UIPieChartTabController which inherits "UIViewController".

Now I want another tab bar in UIPieChartTabController.

so in viewDidLoad of UIPieChartTabController

- (void)viewDidLoad {
    [super viewDidLoad];

     UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
     contentView.backgroundColor = [UIColor whiteColor];
     self.view = contentView;
     [contentView release];
      UITabBarController *tabbar= [[UITabBarController alloc] init];
     tabbar.view.frame = CGRectMake(0, 0, 320, 460);
    piechartViewController *pr=[[piechartViewController alloc]init];
    pr.tagInAction=1;
    pr.title=@"Type";
    pr.tabBarItem.image=[UIImage imageNamed:@"trend.png"];
    pr.sDate=sDate;
    pr.nDate=nDate;

    piechartViewController *pr1=[[piechartViewController alloc]init];
    pr1.title=@"category";
    pr1.tagInAction=4;
    pr1.sDate=sDate;
    pr1.nDate=nDate;

    piechartViewController *pr2=[[piechartViewController alloc]init];
    pr2.title=@"paidWith";
    pr2.tagInAction=3;
    pr2.sDate=sDate;
    pr2.nDate=nDate;

    //tabbar.tabBar.delegate=self;
//this gave me error

    ExportRep *pr3=[[ExportRep alloc]init];
    pr3.tabBarItem.image=[UIImage imageNamed:@"database.png"];
    pr3.title=@"Export Expenses";

    [tabbar setViewControllers:[NSArray arrayWithObjects:pr,pr1,pr2,pr3,nil]];
    [self.view addSubview:tabbar.view];
    [pr release];
    [pr1 release];
    [pr2 release];
}

This piece of code worked but now when I select tab of viewController ExportRep type I tried

[self presentModalViewController:objMFMailComposeViewController animated:YES];

but navigationController of objMFMailComposeViewController hides behind navigationController of view that is presenting objMFMailComposeViewController.

Also viewWillAppear viewDidAppear of all the view controller which are bound to tab bar never gets called.

But none of this problem occurs for tabbar and viewcontroller which gets created by UITabbarTemplate.

Why Is it so? Whats wrong when I create Tab bar?


问:
Replace spaces with an underscore in PHP while uploading file
I have a script that allows users to upload images. I'm working on something that grabs a random image from the collection of images, however the spaces seem to screw with the url, which means I need to figure out how to replace spaces with _s.

```<code><?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
</code>```

as you can see here, I tried adding $target_file = str_replace(' ', '_', $target_file;) to replace the string, however the image still uploads with spaces. How can I make this work?

答:
In your code only the content of file name string is replaced.

Its not changing the actual file name.

You need to use str_replace before move_uploaded_file.

Body:
I have a script that allows users to upload images. I'm working on something that grabs a random image from the collection of images, however the spaces seem to screw with the url, which means I need to figure out how to replace spaces with _s.

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

as you can see here, I tried adding $target_file = str_replace(' ', '_', $target_file;) to replace the string, however the image still uploads with spaces. How can I make this work?


问:
Eclipse keeps asking for svn password
Whenever I'm trying to synchronize/update my projects with SVN repo it asks me for password. It drives me nuts, I'm checking "save password" checkbox and it doesn't work at all.. what is more, I cant use a simple password.

It might be somehow connected with my company's proxy but eclipse plugin update sites work just fine.

I have a Subversion directory in my AppData dir, maybe I should delete this?
I can also provide additional info, I just don't know what may be relevant.

I'm using Subclipse with JavaHL provider and my Eclipse version is 4.4.2 but I have the same problem on Eclipse 3.7.2

答:
went to Window/Preferences/Team/SVN

set to "SVNKit" from "JavaHL".

I changed this to SVNKit, and have had no problems since.

ContentLicense: CC BY-SA 4.0

Title: Eclipse keeps asking for svn password


问:
How can i write SQL search name?
how can i write SQL to search name in database? Example name : Brul Nol
Note: I can search Brul Nol or Nol Brul and then i get the same result </p>

答:
I would use the LIKE keyword.

For this query, I would use:

```<code>SELECT name
FROM database
WHERE name LIKE '%Brul%'
AND name LIKE '%Nol%';
</code>```

The % wildcard on both sides of the word searches the name column for any name with Brul and Nol in it, so this would return names Brul Nol and Nol Brul.

Title: How can i write SQL search name?

Body:
I would use the LIKE keyword.

For this query, I would use:

SELECT name
FROM database
WHERE name LIKE '%Brul%'
AND name LIKE '%Nol%';

The % wildcard on both sides of the word searches the name column for any name with Brul and Nol in it, so this would return names Brul Nol and Nol Brul.


问:
How to edit a pushed commit message using rebase?
I am having the hardest time trying to figure out how to edit a git commit message that has already been pushed to GitHub. I could have sworn that in the past I have used this same command to edit already pushed git commits and have no issues what so ever. The problem that I'm having right now is when I run git rebase --interactive <SHA of commit> I get something that looks like this...

```<code>noop

# Rebase 5d8e041..5d8e041 onto 5d8e041 (1 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
</code>```

When I run the exact same command but with a git commit that hasn't been pushed up to GitHub yet, everything works perfectly fine. Is there something I'm missing? Like I said before I could have sworn that this at one time worked perfectly fine with pushed and unpushed commits.

Thanks so much for your help I greatly appreciate it.

答:
The final answer to my question of why git rebase -i <sha> isn't bringing up a preferred editor to even choose whether to reword a commit message or any other option like. The answer was that I was using the 64bit architecture instead of the 32bit architecture. Now, I honestly don't know why this is but I did find a post on GitHub that was talking about certain commands failing on the 64bit architecture, specifically git rebase and certain git merge operations according to that post. It also said that...

leaves incomplete git operation and also adds a file on disk, sh.exe.stackdump with STATUS_STACK_OVERFLOW + register dump.

I wasn't getting this error popping up in the git console though. I was getting when I opened my project in SmartGit, which is just a GUI for git. This would happen when I right clicked on the git message before the git commit message that I actually wanted to rebase and then went to Rebase Interactive From. It wouldn't instantly through the error instead, it would try for 10 seconds and then through the error.

So at this point, I've figured out what caused my problem but I just don't know why yet. Why would a 64bit architecture version of git run differently than a 32bit one? The mind boggles. If anyone has a specific reason why this is happening please go ahead and just edit my post.

Body:
I am having the hardest time trying to figure out how to edit a git commit message that has already been pushed to GitHub. I could have sworn that in the past I have used this same command to edit already pushed git commits and have no issues what so ever. The problem that I'm having right now is when I run git rebase --interactive <SHA of commit> I get something that looks like this...

noop

# Rebase 5d8e041..5d8e041 onto 5d8e041 (1 command(s))
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

When I run the exact same command but with a git commit that hasn't been pushed up to GitHub yet, everything works perfectly fine. Is there something I'm missing? Like I said before I could have sworn that this at one time worked perfectly fine with pushed and unpushed commits.

Thanks so much for your help I greatly appreciate it.


问:
Pair items in two lists
i have two lists:

```<code>foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']
</code>```

The result i want is

```<code>('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]
</code>```

Here follows my codes:

```<code>zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

or,

```<code>zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]
</code>```

How to solve such a problem?

答:
I'll throw something in here for fun (that still answers the question).
Why not use Levenshtein Distance when the opportunity arises.

```<code>from fuzzywuzzy import fuzz
import itertools

new_list_y =[]
for num_x, x in enumerate(foo):
    for num_y, y in enumerate(bar):
        if fuzz.ratio(x, y) > 85:
            new_list_y.append(y)
    if num_x > num_y:
        new_list_y.append(x)

list(itertools.zip_longest(foo, new_list_y))
</code>```

Result:

```<code>[('learn.py', 'A.learn.py'),
 ('work.py', '&work.py'),
 ('entertain.py', '3.entertain.py'),
 ('else', 'else')]
</code>```

Title: Pair items in two lists

Body:
i have two lists:

foo = ['learn.py', 'work.py','entertain.py','else']
bar = ['A.learn.py', '3.entertain.py','&work.py']

The result i want is

('learn.py', 'A.learn.py'), ('work.py', '&work.py'),
('entertain.py','3.entertain.py'), ('else','else')]

Here follows my codes:

zoo = []
for j in bar:
    for i in foo:
        if i in j:
            zoo.append((i,j))
In [3]: zoo
Out[3]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

or,

zoo = []
for i in foo:
    for j in bar:
        if i in j:
            zoo.append((i,j))
In [5]: zoo
Out[5]: [('learn.py', 'A.learn.py'), ('work.py', '&work.py')]

How to solve such a problem?

Body:
I'll throw something in here for fun (that still answers the question).
Why not use Levenshtein Distance when the opportunity arises.

from fuzzywuzzy import fuzz
import itertools

new_list_y =[]
for num_x, x in enumerate(foo):
    for num_y, y in enumerate(bar):
        if fuzz.ratio(x, y) > 85:
            new_list_y.append(y)
    if num_x > num_y:
        new_list_y.append(x)

list(itertools.zip_longest(foo, new_list_y))

Result:

[('learn.py', 'A.learn.py'),
 ('work.py', '&work.py'),
 ('entertain.py', '3.entertain.py'),
 ('else', 'else')]


问:
When using git, how do you push the exact working directory to a remote?
I have a a remote git repo and a local clone. Let's say I lose my local .git directory and subsequently add and remove some files to the local working directory.

At some point, I want to re-init the local repo, connect it to the remote, and ultimately push my local working dir to the remote exactly as it is (which is to say, I want to have all the added/deleted files be the same in the remote)

How would I accomplish this?

Here is my current solution, which I don't like (and may not work in all cases).

git init

git remote add origin [some_url]

git add .   # adds all the files in the working dir

git commit -m "adding files"

(At this point, my current idea is to:

make a branch,

fetch the remote into it,

'git diff master branch > my_patch'

apply that patch to the branch,

push from the branch to the remote,

pull into the master,

and kill the branch.)

Clearly my idea is quite complex and ugly. Any ideas?

答:
Here is my current solution (let's say I'm already in the directory that contains the current files, but is not get a git repo)

```<code>git clone -n [git_url] tmp_git_dir
mv tmp_git_dir/.git .
rm -rf tmp_git_dir
git add .
git commit -a -m "commit message"
</code>```

This seems more simple and will automatically add and remove files as necessary. I think it's more efficient as well.

I wonder - is there a way to clone the git repo into the current dir (basically I just want the .git dir in place in the current dir so I don't have to do the mv and rm)?

OwnerDisplayName: Ben Brinckerhoff

Body:
Here is my current solution (let's say I'm already in the directory that contains the current files, but is not get a git repo)

git clone -n [git_url] tmp_git_dir
mv tmp_git_dir/.git .
rm -rf tmp_git_dir
git add .
git commit -a -m "commit message"

This seems more simple and will automatically add and remove files as necessary. I think it's more efficient as well.

I wonder - is there a way to clone the git repo into the current dir (basically I just want the .git dir in place in the current dir so I don't have to do the mv and rm)?

LastEditorDisplayName: Ben Brinckerhoff


问:
Can I Use Google Home To Automatically Chromecast My Own Content
I have a working "Action On Google" that we programmed.

I separately created a website that Chromecasts video (based on Google's sample code).

However, what I would REALLY like to have is speak to my Google Home, then automatically have content (ideally an image + audio, then a video right after) cast to the Chromecast.

Is this technically possible exclusively through the Google Home interaction?

Alternately, is there a way to cast image + audio at the same time through a website (and what code do I need to do so)?

答: Right there is no API for third-party developers to programmatically send content to a Chromecast.</p>


问:
Game view is slower than build - unity 2017.2.0f3
I am creating a sample 2D Unity tutorial.
If I run the game using play mode in the UnityEditor, the game seems very slow, and skips some frames. The standalone version runs smooth.

Did I configure something wrong?

答: The problem is my display driver. The driver installed in my system is Microsoft display adapter, the one which is installed during the WINDOWS 10 OS installation. I just updated the driver to intel HD graphics which is opt for my graphics hardware, now unity works fine.</p>


问:
Parsing irregular JSON fields in Python
Consider this json format:

```<code>{
"HostSystem(\"host-527\")": {},
"HostSystem(\"host-487\")": {},
"HostSystem(\"host-482\")": {
    "hardware.cpuInfo.numCpuThreads": 2,
    "name": "192.168.1.1",
    "config.network.consoleVnic": [],
    "capability.perVmSwapFiles": true,
    "capability.maxRunningVMs": 0,
    "config.dateTimeInfo.timeZone.name": "UTC",
}
</code>```

I'd like to parse out 'name'  and 'hardware.cpuInfo.numCpuThreads' from each 'HostSystem' but I'm failing to read the key properly and it doesn't appear that I can use a wildcard.

This is my starter code to test out reading 'HostSystem *' and its failing miserably.

```<code>import json

with open("blob.json") as json_data:
    data = json.load(json_data)
    print data['HostSystem *']
</code>```

Thanks for your suggestions.

答:
Here it is:</p>

```<code>import json

with open("blob.json") as json_data:
    data = json.load(json_data)

for k in data:
    if 'hardware.cpuInfo.numCpuThreads' in data[k]:
        print data[k]['hardware.cpuInfo.numCpuThreads']
</code>```

Title: Parsing irregular JSON fields in Python

Body:
Consider this json format:

{
"HostSystem(\"host-527\")": {},
"HostSystem(\"host-487\")": {},
"HostSystem(\"host-482\")": {
    "hardware.cpuInfo.numCpuThreads": 2,
    "name": "192.168.1.1",
    "config.network.consoleVnic": [],
    "capability.perVmSwapFiles": true,
    "capability.maxRunningVMs": 0,
    "config.dateTimeInfo.timeZone.name": "UTC",
}

I'd like to parse out 'name'  and 'hardware.cpuInfo.numCpuThreads' from each 'HostSystem' but I'm failing to read the key properly and it doesn't appear that I can use a wildcard.

This is my starter code to test out reading 'HostSystem *' and its failing miserably.

import json

with open("blob.json") as json_data:
    data = json.load(json_data)
    print data['HostSystem *']

Thanks for your suggestions.

Body:
Here it is:

import json

with open("blob.json") as json_data:
    data = json.load(json_data)

for k in data:
    if 'hardware.cpuInfo.numCpuThreads' in data[k]:
        print data[k]['hardware.cpuInfo.numCpuThreads']


问:
VS 2017 and Microsoft Cognitive Toolkit 2.0 RC3 (CNTK)
Can I compile Microsoft Cognitive Toolkit 2.0 RC3 (CNTK) with VS 2017 Preview?

答:
VS2017 does not work.

CNTK needs VS2015 update 3.
2015-1 or 2 also does not work.

Installation takes time so better to check.
To check Visual studio version
click Help => About Visual studio.


问:
PPML package gravity with time fixed effects
I'm trying to include time fixed effects (dummies for years generated with model.matrix) into a PPML regression in R.

Without time fixed effect the regression is:

```<code>require(gravity)
my_model <- PPML(y="v", dist="dist",
            x=c("land","contig","comlang_ethno",
            "smctry","tech","exrate"),
            vce_robust=T, data=database)
</code>```

I've tried to add command fe=c("year") within the PPML function but it doesn't work.

I'd appreciate any help on this.

答:
I would comment on the previous answer but don't have enough reputation. The gravity model in your PPML command specifies v = dist × exp(land + contig + comlang_ethno + smctry + tech + exrate + TimeFE) = exp(log(dist) + land + contig + comlang_ethno + smctry + tech + exrate + TimeFE).

The formula inside of glm should have as its RHS the variables inside the exponential, because it represents the linear predictor produced by the link function (the Poisson default for which is natural log).  So in sum, your command should be

```<code>glm(v ~ log(dist) + land + contig + comlang_ethno + smctry + tech + exrate + factor(year),
      family='quasipoisson')
</code>```

and in particular, you need to have distance in logs on the RHS (unlike the previous answer).

Body:
I'm trying to include time fixed effects (dummies for years generated with model.matrix) into a PPML regression in R.

Without time fixed effect the regression is:

require(gravity)
my_model <- PPML(y="v", dist="dist",
            x=c("land","contig","comlang_ethno",
            "smctry","tech","exrate"),
            vce_robust=T, data=database)

I've tried to add command fe=c("year") within the PPML function but it doesn't work.

I'd appreciate any help on this.

Body:
I would comment on the previous answer but don't have enough reputation. The gravity model in your PPML command specifies v = dist × exp(land + contig + comlang_ethno + smctry + tech + exrate + TimeFE) = exp(log(dist) + land + contig + comlang_ethno + smctry + tech + exrate + TimeFE).

The formula inside of glm should have as its RHS the variables inside the exponential, because it represents the linear predictor produced by the link function (the Poisson default for which is natural log).  So in sum, your command should be

glm(v ~ log(dist) + land + contig + comlang_ethno + smctry + tech + exrate + factor(year),
      family='quasipoisson')

and in particular, you need to have distance in logs on the RHS (unlike the previous answer).


问:
JQuery on Web Extensions APIs
Is it able to import and use JQuery on Firefox Web Extension?

I've tried this on manifest.json

```<code>"background":{
"scripts": ["views/jquery.js", "startup.js"]
},
"permissions": [
"storage"
],
"browser_action": {
"browser_style": true,
"default_title": "iVi - Personalized your Dashboard",
"default_popup": "views/menu.html",
"default_icon": {
  "19": "icons/ivi.png",
  "38": "icons/ivi@2x.png"
}
</code>```

and using `$(document).ready event on menu.HTML like this bellow

```<code><script type="text/javascript">
    $(document).ready(function() {
        $("#url").val("123");
    });
</script>

<div class="panel-form-column2">
  <input type="text" id="url" name="url" value="" />
</div>
</code>```

but it produces error like this bellow :

Content Security Policy: The page’s settings blocked the loading of a
  resource at self (“script-src moz-extension:***”). Source:
  $(document).ready(function() {

And have tried to import JQuery inline on HTML instead on manifest.json

```<code><script type="text/javascript" src="jquery.js"> </script>

<script type="text/javascript">
    $(document).ready(function() {
        $("#url").val("123");
    });
</script>
</code>```

and still got the same issue.

Any idea?

答:
According to this page: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_Security_Policy, inline javascript will not be executed, try putting your Javascript in a file, and linking it in your html, like what you did with jQuery.

Placing jQuery inside your manifest under background scripts doesn't work either, as the background page and the browser action page is separated.

This also extend to any Javascript placed inside strings like

```<code><button onclick="test()">example</button>
</code>```

test() will not run when the button is clicked.

Title: JQuery on Web Extensions APIs

Body:
Is it able to import and use JQuery on Firefox Web Extension?

I've tried this on manifest.json

"background":{
"scripts": ["views/jquery.js", "startup.js"]
},
"permissions": [
"storage"
],
"browser_action": {
"browser_style": true,
"default_title": "iVi - Personalized your Dashboard",
"default_popup": "views/menu.html",
"default_icon": {
  "19": "icons/ivi.png",
  "38": "icons/ivi@2x.png"
}

and using `$(document).ready event on menu.HTML like this bellow

  <input type="text" id="url" name="url" value="" />

but it produces error like this bellow :

Content Security Policy: The page’s settings blocked the loading of a
  resource at self (“script-src moz-extension:***”). Source:
  $(document).ready(function() {

And have tried to import JQuery inline on HTML instead on manifest.json

and still got the same issue.

Any idea?

Body:
According to this page: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_Security_Policy, inline javascript will not be executed, try putting your Javascript in a file, and linking it in your html, like what you did with jQuery.

Placing jQuery inside your manifest under background scripts doesn't work either, as the background page and the browser action page is separated.

This also extend to any Javascript placed inside strings like

<button onclick="test()">example</button>

test() will not run when the button is clicked.


问:
How to pass a printf-style function to another function in F#
I'd like to make a function in F# that accepts a printf-style function as an argument, and uses that argument to output data. Usage would be something like the following:

```<code>OutputStuff printfn
</code>```

My first attempt was to let the compiler figure it all out for me:

```<code>let OutputStuff output =
    output "Header"
    output "Data: %d" 42
</code>```

That fails because it decides that output is a function taking string and returning unit, so the second call fails.

Next I tried declaring output to have the same signature as printfn:

```<code>let OutputStuff (output : Printf.TextWriterFormat<'a> -> 'a) =
    output "Header"
    output "Data: %d" 42
</code>```

This fails because the compiler decides that the real type of output is Printf.TextWriterFormat<string> -> unit, so again the second call fails. It also generates warning FS0064 indicating that the first call to output causes the code to be less generic than the type annotations, which is the crux of the issue here.

Last, I tried declaring the output function as a separate type abbreviation:

```<code>type OutputMe<'a> = Printf.TextWriterFormat<'a> -> 'a
let OutputStuff (output : OutputMe<'a>) =
    output "Header"
    output "Data: %d" 42
</code>```

This fails with the same results as the previous attempt.

How do I convince the compiler to not specialize the type of output and leave it as Printf.TextWriterFormat<'a> -> 'a?

答:
Using the inline feature of FSharp you can pre-configure the Printf.ksprintf function with a "work" function and thereby have a final function that accepts a format string together with its peculiar required parameters similar to printf or sprintf. The work function, which accepts that resulting string, can presumably do whatever it wants such as in the case of this logging example which prints the string to the console:

```<code>let logger = fun (msg:string) -> System.Console.WriteLine msg
let inline log msg = Printf.ksprintf logger msg
</code>```

Usage examples:

```<code>open System
open System.Globalization.CultureInfo.CurrentCulture

log "Hello %s, how is your %s" name Calendar.GetDayOfWeek(DateTime.Today)

log "132 + 6451 = %d" (132+6451)

...
</code>```

Body:
I'd like to make a function in F# that accepts a printf-style function as an argument, and uses that argument to output data. Usage would be something like the following:

OutputStuff printfn

My first attempt was to let the compiler figure it all out for me:

let OutputStuff output =
    output "Header"
    output "Data: %d" 42

That fails because it decides that output is a function taking string and returning unit, so the second call fails.

Next I tried declaring output to have the same signature as printfn:

let OutputStuff (output : Printf.TextWriterFormat<'a> -> 'a) =
    output "Header"
    output "Data: %d" 42

This fails because the compiler decides that the real type of output is Printf.TextWriterFormat<string> -> unit, so again the second call fails. It also generates warning FS0064 indicating that the first call to output causes the code to be less generic than the type annotations, which is the crux of the issue here.

Last, I tried declaring the output function as a separate type abbreviation:

type OutputMe<'a> = Printf.TextWriterFormat<'a> -> 'a
let OutputStuff (output : OutputMe<'a>) =
    output "Header"
    output "Data: %d" 42

This fails with the same results as the previous attempt.

How do I convince the compiler to not specialize the type of output and leave it as Printf.TextWriterFormat<'a> -> 'a?

Body:
Using the inline feature of FSharp you can pre-configure the Printf.ksprintf function with a "work" function and thereby have a final function that accepts a format string together with its peculiar required parameters similar to printf or sprintf. The work function, which accepts that resulting string, can presumably do whatever it wants such as in the case of this logging example which prints the string to the console:

let logger = fun (msg:string) -> System.Console.WriteLine msg
let inline log msg = Printf.ksprintf logger msg

Usage examples:

open System
open System.Globalization.CultureInfo.CurrentCulture

log "Hello %s, how is your %s" name Calendar.GetDayOfWeek(DateTime.Today)

log "132 + 6451 = %d" (132+6451)

...


问:
How to not specify an optional parameter?
The img function for the canvas context has parameters like this:

img, sx (optional), sy (optional), swidth (optional), sheight (optional), x, y

As you can see, there are optional parameters in between img and x. How would I specify that I don't want to use sx sy swidth or sheight and skip to x?

答:
ctx.drawImage can not skip arguments!!

You can not skip any of the optional arguments for this function.

You must pass 3, 5, or 9 arguments.

If you add values that are not numbers like null, undefined, false, true, etc for all but the first argument, the value will be coerced to a number.

If you pass anything but a valid image as the first argument the call will throw an error.

Examples of what throws and not.

const c = document.createElement("canvas");
const ctx = c.getContext("2d");

function test(func, message) {
  try {
    func();
    console.log(message)
  } catch (e) {
    console.log(message + e.message)
  }
}

test(() => ctx.drawImage(c, 0, 0), "drawImage(img,x,y) OK");
test(() => ctx.drawImage(c, 0, 0, 10, 10), "drawImage(img, x, y, w, h) OK");
test(() => ctx.drawImage(c, 0, 0, 10, 10, 0, 0, 10, 10), "drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh) OK");
test(() => ctx.drawImage(c, null, 0), "drawImage(c,null,0)  OK null is converted to 0");
test(() => ctx.drawImage(c, undefined, 0), "drawImage(c,undefined,0) OK undefined is converted to 0");
test(() => ctx.drawImage(c, 0), "drawImage(c,0) Error:");
test(() => ctx.drawImage(c, 0, 0, 10), "drawImage(c,0,0,10) Error:");
test(() => ctx.drawImage(c, 0, 0, 10, 10, 0, 0), "drawImage(c,0,0,10,10,0,0) Error:");
test(() => ctx.drawImage(null, 0, 0), "drawImage(null,0,0) Error:");```


问:
How to query the most recent row for each value in column X?
I'm trying to query the most recent row for each value in a column X.

My current attempt is:

```<code>SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X
</code>```

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?

答:
This only involves one table? Then why not this:</p>

```<code>select * from mytable order by mytimestamp desc limit 1
</code>```

Body:
I'm trying to query the most recent row for each value in a column X.

My current attempt is:

SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?

Body:
This only involves one table? Then why not this:

select * from mytable order by mytimestamp desc limit 1


问:
Angular 4: How to include external js libraries?
I know there were some of this topics, but I didn't find the solution for my problem.

I've tried to include this lib: https://github.com/euoia/hex-grid.js#new_module_hex-grid--HexGrid_new unfortunatelly I couldn't.

I put the unzipped project into src/js folder.
Into angular-cli.json inside the scripts tag I put the url to the hex-grid.js:
"scripts": ["js/hex-grid.js-master/src/hex-grid.js"]. the route is good, because the app was compiled succesfully.
I have a game-map.component.ts file where I want to use this lib.

```<code>import {Component} from '@angular/core';

declare var hexGrid: any;

@Component({
  selector: 'app-game-map',
  templateUrl: './game-map.component.html',
  styleUrls: ['./game-map.component.css']
})
export class GameMapComponent {

hex: any;

constructor() {
  this.hex = new hexGrid({
    width: 20,
    height: 10,
    orientation: 'flat-topped',
    layout: 'odd-q'
  });
  }
}
</code>```

But I got this error: Uncaught ReferenceError: module is not defined
    at scripts.bundle.js:2

And it has problem with this module: module.exports = (function () {
    /**

Someone can help me in this issue?
Thanks!

答:
1.install npm install hex-grid.js in cmd

2.import * as hexGrid from 'hex-grid.js'

3.then use it

Body:
I know there were some of this topics, but I didn't find the solution for my problem.

I've tried to include this lib: https://github.com/euoia/hex-grid.js#new_module_hex-grid--HexGrid_new unfortunatelly I couldn't.

I put the unzipped project into src/js folder.
Into angular-cli.json inside the scripts tag I put the url to the hex-grid.js:
"scripts": ["js/hex-grid.js-master/src/hex-grid.js"]. the route is good, because the app was compiled succesfully.
I have a game-map.component.ts file where I want to use this lib.

import {Component} from '@angular/core';

declare var hexGrid: any;

@Component({
  selector: 'app-game-map',
  templateUrl: './game-map.component.html',
  styleUrls: ['./game-map.component.css']
})
export class GameMapComponent {

hex: any;

constructor() {
  this.hex = new hexGrid({
    width: 20,
    height: 10,
    orientation: 'flat-topped',
    layout: 'odd-q'
  });
  }
}

But I got this error: Uncaught ReferenceError: module is not defined
    at scripts.bundle.js:2

And it has problem with this module: module.exports = (function () {
    /**

Someone can help me in this issue?
Thanks!


问:
Use Python dedupe library to return all matches against messy dataset
First, if you haven't seen the Dedupe library for Python: it's awesome. Much like TensorFlow, it's a great way to bring machine learning to the masses (like me).

I'm trying to do record linkage of names against a single, large, messy data set. I'm using heuristics right now, and it's starting to fall short with more complicated data sets.

Questions:

Is there a way to perform a match of a single record (one-by-one or in batches) and return all the potential matches?

Gazetteer docs say one side must be clean, no duplicates. If names can be duplicated but serial numbers aren't (and serial numbers aren't used in matching) isn't that a duplicate?

Context:

There are 1.6M specialized construction machines in the US. There is a database with the machine type, owner names (up to two, companies included), serial number, and maintenance information like last_service_date.

People often inquire about maintenance and sales of their machines (100-250/day), and I keep a running record. The problem is matching the name on the phone with the machine(s) that they own. I need to match the names I have on the forms with the names on the ownership records to learn more about the machine after the fact and understand the lifecycle of the machines.

Sample Data:

```<code>"""
 This is simplified data. We often have two names on the form, and owner names
 come in first_name, last_name format but are often split in strange ways when
 multiple owners have a single machine.
"""
# Incoming Record (100-250+ per day)
{
'raw_name': 'Maria C Hernandez', 'inquire_date': '2017-11-16', 'inquire_type': 'sale'
}

# Ownership Records (1.6M+, with duplicates of NAME but not SERIAL #)
[
{'owner_1': 'HECTOR & MARIANNE HERNANDEZ', 'owner_2': '', 'serial': '3993892k'},
{'owner_1': 'MARIANA HERNANDEZ', 'owner_2': '', 'serial': '8383883hh'},
{'owner_1': 'MARIA HERNANDEZ', 'owner_2': 'TAMMY ULMER', 'serial': '123fdfe'},
{'owner_1': 'JOSE & MARIA HERNANDEZ', 'owner_2': 'MH CORP', 'serial': '223466y4'},
{'owner_1': 'MARIA C HERNANDEZ', 'owner_2': 'HIPOLITO HERNANDEZ', 'serial': '2433ff3345'},
]
</code>```

Maybe I need some guidance, as well... For our heuristics, I essentially split the name fields in both data sets and compare them in 6 or 7 different ways. Now we are getting inquiries with multiple names that could help matching. Maybe more heuristics would work, but this tool seems perfect for the job.

答:
You may use string metric for one by one analysis. But checking each record even is computationally not very efficient, since you will be doing something similar to full scan. Using string metric you can combine strings and assign weights to it. For example: combine the names and phone numbers, which also helps avoid real duplicates (If you have two entries for the same person) as the combination will be a unique string. Either you can formulate ways to assign weights to it or let dedupe calculate the weight using “Active learning”.

Please use the below documentation for details.

https://dedupe.io/developers/library/en/latest/Matching-records.html

Body:
First, if you haven't seen the Dedupe library for Python: it's awesome. Much like TensorFlow, it's a great way to bring machine learning to the masses (like me).

I'm trying to do record linkage of names against a single, large, messy data set. I'm using heuristics right now, and it's starting to fall short with more complicated data sets.

Questions:

Is there a way to perform a match of a single record (one-by-one or in batches) and return all the potential matches?

Gazetteer docs say one side must be clean, no duplicates. If names can be duplicated but serial numbers aren't (and serial numbers aren't used in matching) isn't that a duplicate?

Context:

There are 1.6M specialized construction machines in the US. There is a database with the machine type, owner names (up to two, companies included), serial number, and maintenance information like last_service_date.

People often inquire about maintenance and sales of their machines (100-250/day), and I keep a running record. The problem is matching the name on the phone with the machine(s) that they own. I need to match the names I have on the forms with the names on the ownership records to learn more about the machine after the fact and understand the lifecycle of the machines.

Sample Data:

"""
 This is simplified data. We often have two names on the form, and owner names
 come in first_name, last_name format but are often split in strange ways when
 multiple owners have a single machine.
"""
# Incoming Record (100-250+ per day)
{
'raw_name': 'Maria C Hernandez', 'inquire_date': '2017-11-16', 'inquire_type': 'sale'
}

# Ownership Records (1.6M+, with duplicates of NAME but not SERIAL #)
[
{'owner_1': 'HECTOR & MARIANNE HERNANDEZ', 'owner_2': '', 'serial': '3993892k'},
{'owner_1': 'MARIANA HERNANDEZ', 'owner_2': '', 'serial': '8383883hh'},
{'owner_1': 'MARIA HERNANDEZ', 'owner_2': 'TAMMY ULMER', 'serial': '123fdfe'},
{'owner_1': 'JOSE & MARIA HERNANDEZ', 'owner_2': 'MH CORP', 'serial': '223466y4'},
{'owner_1': 'MARIA C HERNANDEZ', 'owner_2': 'HIPOLITO HERNANDEZ', 'serial': '2433ff3345'},
]

Maybe I need some guidance, as well... For our heuristics, I essentially split the name fields in both data sets and compare them in 6 or 7 different ways. Now we are getting inquiries with multiple names that could help matching. Maybe more heuristics would work, but this tool seems perfect for the job.


问:
Openstack CLI throwing SSL error
I have installed Openstack CLI and when I try to use any command say

```<code>openstack server list
</code>```

it is throwing the below error

```<code>Failed to discover available identity versions when contacting
https://44.128.19.51:5000/v3. Attempting to parse version from URL.
SSL exception connecting to https://44.128.19.51:5000/v3/auth/tokens:
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
(_ssl.c:765)
</code>```

I tried setting the export OS_CACERT=/path/to/ca.crt, but it is not working.

答:
You must provide a proper authorization url. Sometimes the port of the url can be wrong. Like in my case, the authorization url had port 1300 instead of 5000.

And have you sourced your RC file?

Other than for proper authorization url, proper CACERT path or proper authorization certificates it should show this error.

Title: Openstack CLI throwing SSL error

Body:
I have installed Openstack CLI and when I try to use any command say

openstack server list

it is throwing the below error

Failed to discover available identity versions when contacting
https://44.128.19.51:5000/v3. Attempting to parse version from URL.
SSL exception connecting to https://44.128.19.51:5000/v3/auth/tokens:
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
(_ssl.c:765)

I tried setting the export OS_CACERT=/path/to/ca.crt, but it is not working.


问:
Pass function to optional argument in Python
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:

```<code>NameError: name 'self' is not defined
</code>```

Please see the sample code below:

```<code>class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()
</code>```

Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.

答:
If you have to define num as a method then what @Shadow said is the best way to go, unless num can also be passed a value of None.

Another option is simply defining a function that doesn't take a self, and just calling it in your params as a normal function.

```<code>class Test():
    def rand():
        return 4

    def print_rand(self, num=rand()):
        print num

t = Test()
print t.print_rand()
</code>```

If you actually intend on not accessing anything within the instance, and will be returning some constant value, you could define it as a @staticmethod.

That all being said, I am not sure what the use case is for calling a method to get a default value right within the function parameter declaration. It's better to explicit like @Shadow's post said for something that's uncommon. It'll save you and someone else some good time in the future.

Body:
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:

NameError: name 'self' is not defined

Please see the sample code below:

class Test():
    def rand(self):
        return 4

    def print_rand(self, num=self.rand()):
        print num

t = Test()
print t.print_rand()

Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.

Body:
If you have to define num as a method then what @Shadow said is the best way to go, unless num can also be passed a value of None.

Another option is simply defining a function that doesn't take a self, and just calling it in your params as a normal function.

class Test():
    def rand():
        return 4

    def print_rand(self, num=rand()):
        print num

t = Test()
print t.print_rand()

If you actually intend on not accessing anything within the instance, and will be returning some constant value, you could define it as a @staticmethod.

That all being said, I am not sure what the use case is for calling a method to get a default value right within the function parameter declaration. It's better to explicit like @Shadow's post said for something that's uncommon. It'll save you and someone else some good time in the future.


问:
How can i write SQL search name?
how can i write SQL to search name in database? Example name : Brul Nol
Note: I can search Brul Nol or Nol Brul and then i get the same result </p>

答:
```<code>SELECT name FROM TABLE WHERE name LIKE '%SearchWord%'
</code>```

This gives all the name where your search word appear in any position of the name.

Title: How can i write SQL search name?

Body:
SELECT name FROM TABLE WHERE name LIKE '%SearchWord%'

This gives all the name where your search word appear in any position of the name.


问:
How to convert SQL Query to CodeIgniter?
How to convert this query :

```<code>SELECT pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah
FROM pembelian_detail_tb
INNER JOIN produk_tb ON pembelian_detail_tb.kode_produk = produk_tb.kode_produk;
</code>```

I have try many code, and i still got undefine.

答:
I like to use Query Bindings once a join is involved in a query:

https://www.codeigniter.com/userguide3/database/queries.html

search page for "query bindings"

this escapes values for you of course and if you need to debug dump $this->db->last_query();

Body:
How to convert this query :

SELECT pembelian_detail_tb.kode_beli, pembelian_detail_tb.kode_produk, produk_tb.nama, pembelian_detail_tb.jumlah
FROM pembelian_detail_tb
INNER JOIN produk_tb ON pembelian_detail_tb.kode_produk = produk_tb.kode_produk;

I have try many code, and i still got undefine.


问:
What to do, Learn while Developing the app or Learn first and then develop the app
I am planning to develop a web and mobile application. Have a look on this Question on OnStartups

I have some PHP & MySql knowledge, however I didn't do any major projects so far.

My skills on a scale of 5

PHP&MySql 3/5,

Javascript 3/5

CSS 3/5

Android 1.5/5

IPhone    0/5

web development (2/5)

web    design(2/5)

Software Development &    management
(1.5/5)

My app, as said in one of the answers
in the question, is not much complex
as Mint. If the complexity of Mint is
rated 8. My app would be 5/8

I have lot of interest in programming. Only thing bothering and bogging me is the time to make the app live. I don't understand how to estimate the time as I am not so experienced.

Should I start developing the app and learn all the concepts on the way?

or

should I wait learn programming completely first and then develop the app.?

Edit: A small Edit based on below answers. How should I test myself to know whether I have the minimum web development knowledge to start developing the application.

答: You have offered yourself the option of hiring professionals. That seems the most logical thing to do. Unless of course, you don't have the resources for it. The problem is that if you struggle on your own, chances are that eventually you will have a unsound code base, that cannot be maintained by anybody but you.</p>


问:
Replace spaces with an underscore in PHP while uploading file
I have a script that allows users to upload images. I'm working on something that grabs a random image from the collection of images, however the spaces seem to screw with the url, which means I need to figure out how to replace spaces with _s.

```<code><?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
</code>```

as you can see here, I tried adding $target_file = str_replace(' ', '_', $target_file;) to replace the string, however the image still uploads with spaces. How can I make this work?

答:
Your code should be:</p>

```<code><?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
} else {
    $target_file = str_replace(' ', '_', $target_file);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],  $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
</code>```

Body:
I have a script that allows users to upload images. I'm working on something that grabs a random image from the collection of images, however the spaces seem to screw with the url, which means I need to figure out how to replace spaces with _s.

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $target_file = str_replace(' ', '_', $target_file);
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

as you can see here, I tried adding $target_file = str_replace(' ', '_', $target_file;) to replace the string, however the image still uploads with spaces. How can I make this work?

Body:
Your code should be:

<?php
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
} else {
    $target_file = str_replace(' ', '_', $target_file);
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],  $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}


问:
What is the right way to serve private routes?
I am trying to understand the following security aspect:

If I understand it right, in PHP the URL is routing directly to specific files on the server. e.g. https://mypage.com/secretFunctions.php will route to secretFunctions.php. If I protect this route trough basic authentication, the authentication will happen before the file is processed and served to the client. In result, only the authenticated user will ever get to see the rendered content.

In case of a client-side node.js app, the whole App.js code is sent to the client and processed there. The URL is always pointing at the same file. The routes defined in that file determine which code snippet will be executed and rendered. Even if I protect any specific route by any kind of authentication, the user will get the whole code anyway.

Is there a way to prevent this? To prevent clients receiving the private code of private routes, as long as they are not authenticated?

答:
In node.js the whole App.js code is sent to the client and processed there.

No, that is not how it works at all.  When you run node.js and code on your server that code doesn't go to the client - ever.  It just runs on the server.  The client has no access to it.  If you run your node.js app with the command line node app.js, then the node executable engine is run and it executes app.js on the server.

In a node.js server, you would not typically define private routes and expect to use them only from your server implementation with no client access.  While, it can be done (using some form of authorization token that only the server knows), you typically wouldn't use a private route at all on your public server.  Instead, rather than requesting a private route on your own self, you would just put the relevant code in a function and call that function directly.  Then, it's entirely private to the server implementation.

Then, app.js would start an http server process and define routes that it wants that server to handler.  When a client comes along and requests a route from the server, then the app.js code (or other modules that it loads) will parse the requested route, map it to a defined handler for that route and execute just the node.js code that is supposed to process that route.  When it's done processing that route, it will send a response.  Depending upon what type of request it is, that response might be a web page that the browser will parse and display or it might be a piece of JSON that is the result of the request or it could be any number of other data types.

The only code that is sent to the client is Javascript code that is embedded in a web page and specifically meant to run inside the browser.  That would not be node.js code and is not your server code.  That would be browser Javascript just like one would use with any back-end framework (node.js is no different than any other framework in that regard).

Is there a way to prevent this? To prevent clients receiving the private code of private routes, as long as they are not authenticated?

This part of the question is mostly just misguided as it seems to be based on a misunderstanding of how a node.js back-end app server works.  You prevent code going to the client that shouldn't by not sending it to the client in the first place.  The client can't see anything from your server that you don't specifically have a route to handle and send a response.  By default a node.js web server sends NOTHING to the client.  No pages are sent by default.  So, the only thing that is ever sent to a client is a response that you write code specifically to send.  Note, this is different than other back-ends (like Apache) that may be configured to automatically send lots of things that are requested.

If I understand it right, in PHP the URL is routing directly to specific files on the server. e.g. https://mypage.com/secretFunctions.php will route to secretFunctions.php.

That is PHP.  That is not how node.js web servers work.  For the route https://mypage.com/secretFunctions.php to respond at all to the client, you have to define a route in your server code that was specifically coded to respond to the request /secretFunctions.php and then you'd define what code should run on the server when that request is received.  No code is sent to the client unless you specifically write code in this route handler to send code to the client that you want to run in the browser.

Let me show you a very simple node.js app that responds to three routes (and only three routes).  Let say this is app.js:

```<code>const app = require('express')();

app.get('/', function(req, res) {
    res.send("Hello");
});

app.get('/name', function(req, res) {
    res.send("My name is Bob");
});

app.get('/city', function(req, res) {
    res.send("I am in San Francisco");
});

// start the server
app.listen(80);
</code>```

You start this server with node app.js.  When it runs app.js, it initializes an instance of the express framework, registers three route handlers and then starts the web server.

Now, you have a running web server.  Suppose you have a web browser running on the same server and you type this into the URL bar: http://localhost.  That will trigger the '/' route handler and will display "Hello" in the browser.

Then, you type http://localhost/name into the browser.  That will display "My name is Bob" in the browser.

If you type any other route besides these three that are defined here, nothing will be sent to the browser.  It doesn't matter if there's a contacts.html file sitting in the same directory.  If there isn't a specific coded route to handle a request, nothing is sent.  So, no private code is every sent by default.

Now, there are ways to instruct your server to automatically send some static files, but that takes a special kind of route that is told exactly what route prefixes to look for and what directory on your server to look for files that might match URLs that are requested.  This can be done for static files that you specific locate in a directory by themselves (like .css files, for example) that you intend to send to the client when requested.  And, you have to use the right code to make that happen.  By default that never happens.

Body:
In node.js the whole App.js code is sent to the client and processed there.

No, that is not how it works at all.  When you run node.js and code on your server that code doesn't go to the client - ever.  It just runs on the server.  The client has no access to it.  If you run your node.js app with the command line node app.js, then the node executable engine is run and it executes app.js on the server.

In a node.js server, you would not typically define private routes and expect to use them only from your server implementation with no client access.  While, it can be done (using some form of authorization token that only the server knows), you typically wouldn't use a private route at all on your public server.  Instead, rather than requesting a private route on your own self, you would just put the relevant code in a function and call that function directly.  Then, it's entirely private to the server implementation.

Then, app.js would start an http server process and define routes that it wants that server to handler.  When a client comes along and requests a route from the server, then the app.js code (or other modules that it loads) will parse the requested route, map it to a defined handler for that route and execute just the node.js code that is supposed to process that route.  When it's done processing that route, it will send a response.  Depending upon what type of request it is, that response might be a web page that the browser will parse and display or it might be a piece of JSON that is the result of the request or it could be any number of other data types.

The only code that is sent to the client is Javascript code that is embedded in a web page and specifically meant to run inside the browser.  That would not be node.js code and is not your server code.  That would be browser Javascript just like one would use with any back-end framework (node.js is no different than any other framework in that regard).

Is there a way to prevent this? To prevent clients receiving the private code of private routes, as long as they are not authenticated?

This part of the question is mostly just misguided as it seems to be based on a misunderstanding of how a node.js back-end app server works.  You prevent code going to the client that shouldn't by not sending it to the client in the first place.  The client can't see anything from your server that you don't specifically have a route to handle and send a response.  By default a node.js web server sends NOTHING to the client.  No pages are sent by default.  So, the only thing that is ever sent to a client is a response that you write code specifically to send.  Note, this is different than other back-ends (like Apache) that may be configured to automatically send lots of things that are requested.

If I understand it right, in PHP the URL is routing directly to specific files on the server. e.g. https://mypage.com/secretFunctions.php will route to secretFunctions.php.

That is PHP.  That is not how node.js web servers work.  For the route https://mypage.com/secretFunctions.php to respond at all to the client, you have to define a route in your server code that was specifically coded to respond to the request /secretFunctions.php and then you'd define what code should run on the server when that request is received.  No code is sent to the client unless you specifically write code in this route handler to send code to the client that you want to run in the browser.

Let me show you a very simple node.js app that responds to three routes (and only three routes).  Let say this is app.js:

const app = require('express')();

app.get('/', function(req, res) {
    res.send("Hello");
});

app.get('/name', function(req, res) {
    res.send("My name is Bob");
});

app.get('/city', function(req, res) {
    res.send("I am in San Francisco");
});

// start the server
app.listen(80);

You start this server with node app.js.  When it runs app.js, it initializes an instance of the express framework, registers three route handlers and then starts the web server.

Now, you have a running web server.  Suppose you have a web browser running on the same server and you type this into the URL bar: http://localhost.  That will trigger the '/' route handler and will display "Hello" in the browser.

Then, you type http://localhost/name into the browser.  That will display "My name is Bob" in the browser.

If you type any other route besides these three that are defined here, nothing will be sent to the browser.  It doesn't matter if there's a contacts.html file sitting in the same directory.  If there isn't a specific coded route to handle a request, nothing is sent.  So, no private code is every sent by default.

Now, there are ways to instruct your server to automatically send some static files, but that takes a special kind of route that is told exactly what route prefixes to look for and what directory on your server to look for files that might match URLs that are requested.  This can be done for static files that you specific locate in a directory by themselves (like .css files, for example) that you intend to send to the client when requested.  And, you have to use the right code to make that happen.  By default that never happens.


问:
Framework not found GoogleToolboxForMac
After I update my Firebase via "pod update", I got error like this :

```<code>ld: warning: directory not found for option '-F/Users/bennysantoso/Library/Developer/Xcode/DerivedData/FCM-atfcxuircoryufazlomgwfgmvaqm/Build/Products/Debug-iphonesimulator/GoogleToolboxForMac'
ld: framework not found GoogleToolboxForMac
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Here my Podfile :

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
pod 'Firebase/Core'
pod 'Firebase/Messaging'

target 'BB' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for BB

  target 'BBTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'BBUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end
</code>```

Does anybody know about this error?

I seek out relationships GoogleToolboxForMac and Firebase, but I just get a little bit of information.

FYI, I use Swift 2.3 and Firebase 3.8.0.

I will be grateful for any help you can provide. Thanks!

答:
```
its work's
1. select your project in directories
2. select General
3. Add "GoogleToolboxForMac.framework" to the Linked "frameworks and Libraries"
```

Title: Framework not found GoogleToolboxForMac

Body:
After I update my Firebase via "pod update", I got error like this :

ld: warning: directory not found for option '-F/Users/bennysantoso/Library/Developer/Xcode/DerivedData/FCM-atfcxuircoryufazlomgwfgmvaqm/Build/Products/Debug-iphonesimulator/GoogleToolboxForMac'
ld: framework not found GoogleToolboxForMac
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here my Podfile :

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
pod 'Firebase/Core'
pod 'Firebase/Messaging'

target 'BB' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for BB

  target 'BBTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'BBUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

Does anybody know about this error?

I seek out relationships GoogleToolboxForMac and Firebase, but I just get a little bit of information.

FYI, I use Swift 2.3 and Firebase 3.8.0.

I will be grateful for any help you can provide. Thanks!