问:
Hiding all elements that doesn't have a particular class nested deep in them
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

```<code>let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}
</code>```

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

答:
The following snippet should resolve your problem. valid cards (ie having pro content) are turned red in this example, and invalid are turned blue. You can adjust the hit and not-hit classes to your wishes (ie "display:none" or "display:block". Hopefully this solves your issue.

If you have any problems please ask in the comments.

(function($) {
  let cardoo = $('.card')

  cardoo.each(function() {
   if($(this).find('.pro-content').length !== 0) {
    $(this).addClass("hit");
     } else {
     $(this).addClass("not-hit");
     }
  });

})( jQuery );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
  background: black;
  color: white;
  margin: 5px;
}

.hit {
  background:red;
}

.not-hit {
  background:blue;
}</code>```

x

x

x

PRO

x

x

x

PRO

PRO

x

```

Body:
In this very webpage, have about 70 elements, all with the class "card".

Some of the about 70 elements holds another element with the class "pro-content", which is nested deep inside them.

In this image you could see 2 elements. One with the "pro-content" class and an one without, from left to right.

My aim is to hide all elements with this "pro-content" class and keep all others that doesn't have it.

Given the elements with "pro-content" are childNodes, I tried to use the following for...of loop:

let cardoo = document.querySelectorAll(".card");

for ( const element of cardoo ) {
    if ( !$(element).hasClass('pro-content') ) {
        element.style.display = "none";
    }
}

Yet, this code doesn't work properly - It deletes all elements, instead just these without the "pro-content" class.

Note: I would have proffered a pure vanilla ES16 solution, especially to practice more of the ES16-DOMapi relations but if there is no other option, I would use a pure jQuery/ES16-jQuery solution.

Body:
The following snippet should resolve your problem. valid cards (ie having pro content) are turned red in this example, and invalid are turned blue. You can adjust the hit and not-hit classes to your wishes (ie "display:none" or "display:block". Hopefully this solves your issue.

If you have any problems please ask in the comments.

(function($) {
  let cardoo = $('.card')

  cardoo.each(function() {
   if($(this).find('.pro-content').length !== 0) {
    $(this).addClass("hit");
     } else {
     $(this).addClass("not-hit");
     }
  });

})( jQuery );

.card {
  background: black;
  color: white;
  margin: 5px;
}

.hit {
  background:red;
}

.not-hit {
  background:blue;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="pro-content">PRO</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="pro-content">PRO</div></div></div>
<div>
<div class="card"><div class="depeer-we-go"><div class="pro-content">PRO</div></div></div>
<div class="card"><div class="depeer-we-go"><div class="other_content">x</div></div></div>


来源: stackexchange

问:
Run node module from powershell
Say that I have a folder with a node module installed inside. How can I, using powershell, run this module ? For example, I have a folder with webpack installed inside and I'd like to be able to do something like

```<code>node webpack
</code>```

This does not work because it can't find the module. However, it works if I do:

```<code>node ".\node_module\webpack\bin\webpack.js"
</code>```

However, I can't really use this because I'm working on a powershell script that allows the user to define a json file with actions. For example:

```<code>{
  "type": "run-node",
  "options": {
    "module": "webpack",
    "parameters": "--configFile=config/webpack.prod.js"
  }
}
</code>```

As the module to execute is dynamic, I don't know where it will be (except if all module are installed in ".\node_modules\module\bin\module.js" ?), so I can't launch it.

答:
If you're trying to execute the command within the node.js script, use the __dirname variable.

__dirname (almost) always refers to the directory that contains the script.

ContentLicense: CC BY-SA 3.0

Title: Run node module from powershell

Body:
Say that I have a folder with a node module installed inside. How can I, using powershell, run this module ? For example, I have a folder with webpack installed inside and I'd like to be able to do something like

node webpack

This does not work because it can't find the module. However, it works if I do:

node ".\node_module\webpack\bin\webpack.js"

However, I can't really use this because I'm working on a powershell script that allows the user to define a json file with actions. For example:

{
  "type": "run-node",
  "options": {
    "module": "webpack",
    "parameters": "--configFile=config/webpack.prod.js"
  }
}

As the module to execute is dynamic, I don't know where it will be (except if all module are installed in ".\node_modules\module\bin\module.js" ?), so I can't launch it.


问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答: The ability to fall through several cases (intentionally leaving out the break statement) can be useful, and as a few people have already said it's faster as well. Perhaps the most important and least important consideration though, is that it just makes for prettier code than if/else. :)</p>

OwnerDisplayName: Casey

LastEditorDisplayName: Casey

OwnerDisplayName: Marc Charbonneau

ContentLicense: CC BY-SA 2.5


问:
Apply different textures to multiple materials (Unity3D)
I have a folder, called "Walls" in the Ressorce-folder, which contains multiple textures, calling "wallRoi[1-26]". Now I would like to apply those to my model in Unity via C# scripting.
Explaning my code: The model has multiple segmentation of the whole wall, each of them has a tag ("Wall[1-26]"). The tag of the whole wall is "Wall". Now I'm trying to loop through the whole wall and apply to each segmenation of the wall a different texture from the folder. My Code doesn't work, any purposes? Thank you!</p>

```<code>private UnityEngine.Object[] walltextures;

    void mapTexturesOverWalls() {
        walltextures = Resources.LoadAll ("Walls", typeof(Texture2D));

        Texture2D[] wallTex = (Texture2D)walltextures [walltextures.Length];

        GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
        Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();

        for (int i = 0; i < wallTex.Length; i++) {
            foreach (Renderer r in renders) {
                r.material.mainTexture = wallTex[i];
                UnityEngine.Debug.Log (wallTex + "");
            }
        }
    }
</code>```

答:
Create a new script named TexturesOverWall.cs Then copy and paste the below code. All you need to do is name each wall segmentation gameobject with the same name of the texture to apply. Hope this help you  :)</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TexturesOverWall : MonoBehaviour
{

private Texture2D[] walltextures;

void Awake ()
{
    mapTexturesOverWalls ();
}

void mapTexturesOverWalls ()
{
    walltextures = Resources.LoadAll<Texture2D> ("Walls");

    GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
    Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();

    foreach (Renderer r in renders) {
        // all you need to do is name each wall segmentation gameobject with the same name of the texture to apply
        r.material.mainTexture = getTextureByName(r.gameObject.name);
    }
}

Texture2D getTextureByName (string name)
{
    foreach (var tex in walltextures) {
        if (tex.name == name)
            return tex;
    }

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

Body:
I have a folder, called "Walls" in the Ressorce-folder, which contains multiple textures, calling "wallRoi[1-26]". Now I would like to apply those to my model in Unity via C# scripting.
Explaning my code: The model has multiple segmentation of the whole wall, each of them has a tag ("Wall[1-26]"). The tag of the whole wall is "Wall". Now I'm trying to loop through the whole wall and apply to each segmenation of the wall a different texture from the folder. My Code doesn't work, any purposes? Thank you!

private UnityEngine.Object[] walltextures;

    void mapTexturesOverWalls() {
        walltextures = Resources.LoadAll ("Walls", typeof(Texture2D));

        Texture2D[] wallTex = (Texture2D)walltextures [walltextures.Length];

        GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
        Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();

        for (int i = 0; i < wallTex.Length; i++) {
            foreach (Renderer r in renders) {
                r.material.mainTexture = wallTex[i];
                UnityEngine.Debug.Log (wallTex + "");
            }
        }
    }

Body:
Create a new script named TexturesOverWall.cs Then copy and paste the below code. All you need to do is name each wall segmentation gameobject with the same name of the texture to apply. Hope this help you  :)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TexturesOverWall : MonoBehaviour
{

private Texture2D[] walltextures;

void Awake ()
{
    mapTexturesOverWalls ();
}

void mapTexturesOverWalls ()
{
    walltextures = Resources.LoadAll<Texture2D> ("Walls");

    GameObject walls = GameObject.FindGameObjectWithTag ("Wall");
    Renderer[] renders = walls.GetComponentsInChildren<Renderer> ();

    foreach (Renderer r in renders) {
        // all you need to do is name each wall segmentation gameobject with the same name of the texture to apply
        r.material.mainTexture = getTextureByName(r.gameObject.name);
    }
}

Texture2D getTextureByName (string name)
{
    foreach (var tex in walltextures) {
        if (tex.name == name)
            return tex;
    }

    return null;
    }
}


问:
Angular 4 animation state changes
I have an animation applied to two divs to animate them in and out of the void state.

See: https://plnkr.co/edit/uCdBafYG7NZxVVppiTpo?p=preview

Html:

```<code> <div *ngIf="shown" [@flipEnterExitAnimation]="state">
      <div style="border: 1px solid black">Front</div>
    </div>

    <div *ngIf="!shown" [@flipEnterExitAnimation]="state">
      <div style="border: 1px solid black">Back</div>
    </div>
</code>```

Typescript:

```<code>     this.state = this.state === 'backwards' ? null : 'backwards';
      this.shown = !this.shown;

      /*
    setTimeout(() => {
      this.shown = !this.shown;
      },
      1);*/
</code>```

These animations work, however when the state changes it is not applied to the first animation. I can fix this by delaying the animation for 1ms, but this is ugly and feels a bit hacky.

Is there a neater way to achieve this

答:
A better way is to use change detection (ChangeDetectorRef):

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

 // snip

private changeDetectorRef: ChangeDetectorRef;

constructor(changeDetectorRef: ChangeDetectorRef) {
   this.changeDetectorRef = changeDetectorRef;
}

beginAnim() {
  this.state = this.state === 'backwards' ? null : 'backwards';
  this.changeDetectorRef.detectChanges();
  this.shown = !this.shown;
}
</code>```

Title: Angular 4 animation state changes

Body:
I have an animation applied to two divs to animate them in and out of the void state.

See: https://plnkr.co/edit/uCdBafYG7NZxVVppiTpo?p=preview

Html:

Front

Back

Typescript:

     this.state = this.state === 'backwards' ? null : 'backwards';
      this.shown = !this.shown;

      /*
    setTimeout(() => {
      this.shown = !this.shown;
      },
      1);*/

These animations work, however when the state changes it is not applied to the first animation. I can fix this by delaying the animation for 1ms, but this is ugly and feels a bit hacky.

Is there a neater way to achieve this

Body:
A better way is to use change detection (ChangeDetectorRef):

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

 // snip

private changeDetectorRef: ChangeDetectorRef;

constructor(changeDetectorRef: ChangeDetectorRef) {
   this.changeDetectorRef = changeDetectorRef;
}

beginAnim() {
  this.state = this.state === 'backwards' ? null : 'backwards';
  this.changeDetectorRef.detectChanges();
  this.shown = !this.shown;
}


问:
How to read a repetead tag in a xml with pentaho?
I am trying to load and XML file with pentaho:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<scapplication>
<heading>
  <dispatchingcode>GML</dispatchingcode>
  <version>001</version>
  <dispatchingcompany>1232</dispatchingcompany>
</heading>
<F456>
  <reqcode>0019682125</reqcode>
  <comreferencenum>30104</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
<F456>
  <reqcode>0019657723</reqcode>
  <comreferencenum>29676</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
</scapplication>
</code>```

The main problem that I found loading this with pentaho is that F456 tag should be iterated in the load.
This means that I need to detect every node inside every F456 node because later I will load this in two different rows in a table output statement.

How can be readed both tags in a loop with pentaho?
I guess that if both tags were inside another one it would be easy but I do not have a tag above these two, so I do not know how to load with GET DATA FROM XML Step

I tried seeting F456 as a field in the step and set repeat option as Y. But it does not works...

答:
If you use /scapplication/F456 as your XPath loop node, you will get one record per F456 node and using "Get Fields" will get you the child elements as fields.

Assuming there is only one [heading] section per [scapplication], you can manually enter the additional fields to get them for each record:

```
Name           |XPath                     |Element |Result type |Type
dispatchingcode|../heading/dispatchingcode|Node    |Value of    |String
```

Body:
I am trying to load and XML file with pentaho:

<?xml version="1.0" encoding="ISO-8859-1"?>
<scapplication>
<heading>
  <dispatchingcode>GML</dispatchingcode>
  <version>001</version>
  <dispatchingcompany>1232</dispatchingcompany>
</heading>
<F456>
  <reqcode>0019682125</reqcode>
  <comreferencenum>30104</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
<F456>
  <reqcode>0019657723</reqcode>
  <comreferencenum>29676</comreferencenum>
  <responsedate>2017-06-29</responsedate>
</F456>
</scapplication>

The main problem that I found loading this with pentaho is that F456 tag should be iterated in the load.
This means that I need to detect every node inside every F456 node because later I will load this in two different rows in a table output statement.

How can be readed both tags in a loop with pentaho?
I guess that if both tags were inside another one it would be easy but I do not have a tag above these two, so I do not know how to load with GET DATA FROM XML Step

I tried seeting F456 as a field in the step and set repeat option as Y. But it does not works...

Body:
If you use /scapplication/F456 as your XPath loop node, you will get one record per F456 node and using "Get Fields" will get you the child elements as fields.

Assuming there is only one [heading] section per [scapplication], you can manually enter the additional fields to get them for each record:

Name           |XPath                     |Element |Result type |Type
dispatchingcode|../heading/dispatchingcode|Node    |Value of    |String


问:
xcode breakpoints not resolved with included cpp files - MacOS
Update: Based on the answer given by Jason Molenda, I realize that the settings command isn't the issue at all - it is being read properly and has the correct value, and yet breakpoints still aren't resolved. I've changed the topic name to more accurately fit the problem.

Summary of problem: I include cpp files, Xcode can't resolve them when setting breakpoints using the gutter, application is built externally (not developed in Xcode), and my .lldbinit already has settings set target.inline-breakpoint-strategy always set.

Previous version:
My issue is that I cannot get Xcode's debugger to break at breakpoints in included .cpp files (from an externally built application, just trying to use Xcode as the debugger).

I found that the answer is to add the following to the .lldbinit file:

settings set target.inline-breakpoint-strategy always

And I did. It doesn't seem to be read at all and doesn't change anything. When running the command myself using:

command source ~/.lldbinit

It tells me:

-bash: settings: command not found

I do not understand why it can't figure out the 'settings' command. I'll add that I have very little knowledge of how this file is supposed to work, but I see this command used in many lldbinit files without issue.

I searched for information about this and Google gives me absolutely nothing even a little bit related to it, no matter how I search.

Other notes:

-Application is built with debug information.

-To set up Xcode, I created an empty project, set a new scheme's executable to debug to the one I built, and added code folder references for code browsing.

-I add breakpoints using the Xcode gutter.

-I'm using MacOS 10.12 - Sierra, not Linux, and Xcode 8.2.1.

-If I run LLDB through the command line and set breakpoints using: b filename.cpp:line, everything works fine. This is true even despite the 'settings: command not found' error I get when running manually. But it never works in Xcode's visual debugger. Perhaps I'm being misled by this error?

-Breakpoints work fine in the base .cpp file that includes the others, but not in any included ones.

Thanks for any help.

答:
Okay, this is issue has been haunting me for the last few days, and there is literally nothing on the internet that would help - but I finally figured it out! Kinda accidentally - I fiddled with stuff and now it works for some completely mysterious reason.

This is for Xcode 8 - macOS Sierra - mid 2010 computer

The Issue:

On an external build, break points work for the main cpp file, but breakpoints are not working for any included files - cpp files included with "#include".
lldbinit settings do nothing to improve the situation.

Symptoms:

Run the program with some new breakpoints created in the included files, and then press the pause key in the xcode debugger.
In the LLDB console (bottom right of the screen), type:
breakpoint list
You'll see all your broken breakpoints say "location = 0 (pending)" at the end of them. If you add a working breakpoint from you main file, you will see it says "location = 1".

Solution:

In the Project manager, click on the main project file, then click on your Target, goto "Info" - since I'm assuming you're able to build properly, you will have the path to your build.sh file in the Build Tool box. But make sure the Directory box is empty (My arguments box is also empty, but I doubt this is related.)

Once that Directory box is empty, build.sh will no longer work because it won't be able to find your file. To fix this, hardcode your paths like so:

```<code>clang++ -g -I/usr/local/include/SDL2 -lSDL2 /absolute/path/to/sdl_mygame.cpp -o /absolute/path/to/mygameexecutable
</code>```

Now the build works, and mysteriously, now your breakpoints all work!

Other notes about my setup:

I created this project as an External Build

I created a target which
points to my build file and unchecked "Pass build settings in
environment"

I selected this target in my Scheme under Build.

I selected the executable in my scheme under run and checked Debug
Executable

Most other xcode settings don't seem to be necessary.

I'm following along with Handmade Hero

Hope this helps!

Body:
Okay, this is issue has been haunting me for the last few days, and there is literally nothing on the internet that would help - but I finally figured it out! Kinda accidentally - I fiddled with stuff and now it works for some completely mysterious reason.

This is for Xcode 8 - macOS Sierra - mid 2010 computer

The Issue:

On an external build, break points work for the main cpp file, but breakpoints are not working for any included files - cpp files included with "#include".
lldbinit settings do nothing to improve the situation.

Symptoms:

Run the program with some new breakpoints created in the included files, and then press the pause key in the xcode debugger.
In the LLDB console (bottom right of the screen), type:
breakpoint list
You'll see all your broken breakpoints say "location = 0 (pending)" at the end of them. If you add a working breakpoint from you main file, you will see it says "location = 1".

Solution:

In the Project manager, click on the main project file, then click on your Target, goto "Info" - since I'm assuming you're able to build properly, you will have the path to your build.sh file in the Build Tool box. But make sure the Directory box is empty (My arguments box is also empty, but I doubt this is related.)

Once that Directory box is empty, build.sh will no longer work because it won't be able to find your file. To fix this, hardcode your paths like so:

clang++ -g -I/usr/local/include/SDL2 -lSDL2 /absolute/path/to/sdl_mygame.cpp -o /absolute/path/to/mygameexecutable

Now the build works, and mysteriously, now your breakpoints all work!

Other notes about my setup:

I created this project as an External Build

I created a target which
points to my build file and unchecked "Pass build settings in
environment"

I selected this target in my Scheme under Build.

I selected the executable in my scheme under run and checked Debug
Executable

Most other xcode settings don't seem to be necessary.

I'm following along with Handmade Hero

Hope this helps!


问:
Access hadoop nodes web UI from multiple links
i am using the following setup for hadoop's nodes web ui access :

```<code>dfs.namenode.http-address : 127.0.0.1:50070
</code>```

By which i am able to access the nodes web ui link only form the local machine as :

```<code>http://127.0.0.1:50070
</code>```

Is there any way by which i can make it accessible from outside as well ? say like :

```<code>http://<Machine-IP>:50070
</code>```

Thanks in Advance !!

答:
From http://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-web-interfaces.html

The following table lists web interfaces that you can view on the core
  and task nodes. These Hadoop interfaces are available on all clusters.
  To access the following interfaces, replace slave-public-dns-name in
  the URI with the public DNS name of the node. For more information
  about retrieving the public DNS name of a core or task node instance,
  see Connecting to Your Linux/Unix Instances Using SSH in the Amazon
  EC2 User Guide for Linux Instances. In addition to retrieving the
  public DNS name of the core or task node, you must also edit the
  ElasticMapReduce-slave security group to allow SSH access over TCP
  port 22. For more information about modifying security group rules,
  see Adding Rules to a Security Group in the Amazon EC2 User Guide for
  Linux Instances.

YARN ResourceManager

YARN NodeManager

Hadoop HDFS NameNode

Hadoop HDFS DataNode

Spark HistoryServer

Because there are several application-specific interfaces available on
  the master node that are not available on the core and task nodes, the
  instructions in this document are specific to the Amazon EMR master
  node. Accessing the web interfaces on the core and task nodes can be
  done in the same manner as you would access the web interfaces on the
  master node.

There are several ways you can access the web interfaces on the master
  node. The easiest and quickest method is to use SSH to connect to the
  master node and use the text-based browser, Lynx, to view the web
  sites in your SSH client. However, Lynx is a text-based browser with a
  limited user interface that cannot display graphics. The following
  example shows how to open the Hadoop ResourceManager interface using
  Lynx (Lynx URLs are also provided when you log into the master node
  using SSH).

```<code>Copy lynx http://ip-###-##-##-###.us-west-2.compute.internal:8088/
</code>```

There are two remaining options for accessing web interfaces on the
  master node that provide full browser functionality. Choose one of the
  following:

Option 1 (recommended for more technical users): Use an SSH client to connect to the master node, configure SSH tunneling with local port
  forwarding, and use an Internet browser to open web interfaces hosted
  on the master node. This method allows you to configure web interface
  access without using a SOCKS proxy.

to do this use the command

```<code>$ ssh -gnNT -L 9002:localhost:8088 user@example.com
</code>```

where user@example.com is your username.  Note the use of -g to open access to external ip addresses (beware this is a security risk)

you can check this is running using

```<code>nmap localhost
</code>```

to close this ssh tunnel when done use

```<code>ps aux | grep 9002
</code>```

to find the pid of your running ssh process and kill it.

Option 2 (recommended for new users): Use an SSH client to connect to the master node, configure SSH tunneling with dynamic port
  forwarding, and configure your Internet browser to use an add-on such
  as FoxyProxy or SwitchySharp to manage your SOCKS proxy settings. This
  method allows you to automatically filter URLs based on text patterns
  and to limit the proxy settings to domains that match the form of the
  master node's DNS name. The browser add-on automatically handles
  turning the proxy on and off when you switch between viewing websites
  hosted on the master node, and those on the Internet. For more
  information about how to configure FoxyProxy for Firefox and Google
  Chrome, see Option 2, Part 2: Configure Proxy Settings to View
  Websites Hosted on the Master Node.

This seems like insanity to me but I have been unable to find how to configure access in core-site.xml to override the web interface for the ResourceManager which by default it is available at localhost:8088/ and if Amazon think this is the way then I tend to go along with it

Body:
i am using the following setup for hadoop's nodes web ui access :

dfs.namenode.http-address : 127.0.0.1:50070

By which i am able to access the nodes web ui link only form the local machine as :

http://127.0.0.1:50070

Is there any way by which i can make it accessible from outside as well ? say like :

http://<Machine-IP>:50070

Thanks in Advance !!

Body:
From http://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-web-interfaces.html

The following table lists web interfaces that you can view on the core
  and task nodes. These Hadoop interfaces are available on all clusters.
  To access the following interfaces, replace slave-public-dns-name in
  the URI with the public DNS name of the node. For more information
  about retrieving the public DNS name of a core or task node instance,
  see Connecting to Your Linux/Unix Instances Using SSH in the Amazon
  EC2 User Guide for Linux Instances. In addition to retrieving the
  public DNS name of the core or task node, you must also edit the
  ElasticMapReduce-slave security group to allow SSH access over TCP
  port 22. For more information about modifying security group rules,
  see Adding Rules to a Security Group in the Amazon EC2 User Guide for
  Linux Instances.

YARN ResourceManager

YARN NodeManager

Hadoop HDFS NameNode

Hadoop HDFS DataNode

Spark HistoryServer

Because there are several application-specific interfaces available on
  the master node that are not available on the core and task nodes, the
  instructions in this document are specific to the Amazon EMR master
  node. Accessing the web interfaces on the core and task nodes can be
  done in the same manner as you would access the web interfaces on the
  master node.

There are several ways you can access the web interfaces on the master
  node. The easiest and quickest method is to use SSH to connect to the
  master node and use the text-based browser, Lynx, to view the web
  sites in your SSH client. However, Lynx is a text-based browser with a
  limited user interface that cannot display graphics. The following
  example shows how to open the Hadoop ResourceManager interface using
  Lynx (Lynx URLs are also provided when you log into the master node
  using SSH).

Copy lynx http://ip-###-##-##-###.us-west-2.compute.internal:8088/

There are two remaining options for accessing web interfaces on the
  master node that provide full browser functionality. Choose one of the
  following:

Option 1 (recommended for more technical users): Use an SSH client to connect to the master node, configure SSH tunneling with local port
  forwarding, and use an Internet browser to open web interfaces hosted
  on the master node. This method allows you to configure web interface
  access without using a SOCKS proxy.

to do this use the command

$ ssh -gnNT -L 9002:localhost:8088 user@example.com

where user@example.com is your username.  Note the use of -g to open access to external ip addresses (beware this is a security risk)

you can check this is running using

nmap localhost

to close this ssh tunnel when done use

ps aux | grep 9002

to find the pid of your running ssh process and kill it.

Option 2 (recommended for new users): Use an SSH client to connect to the master node, configure SSH tunneling with dynamic port
  forwarding, and configure your Internet browser to use an add-on such
  as FoxyProxy or SwitchySharp to manage your SOCKS proxy settings. This
  method allows you to automatically filter URLs based on text patterns
  and to limit the proxy settings to domains that match the form of the
  master node's DNS name. The browser add-on automatically handles
  turning the proxy on and off when you switch between viewing websites
  hosted on the master node, and those on the Internet. For more
  information about how to configure FoxyProxy for Firefox and Google
  Chrome, see Option 2, Part 2: Configure Proxy Settings to View
  Websites Hosted on the Master Node.

This seems like insanity to me but I have been unable to find how to configure access in core-site.xml to override the web interface for the ResourceManager which by default it is available at localhost:8088/ and if Amazon think this is the way then I tend to go along with it

ContentLicense: CC BY-SA 4.0


问:
Bootstrap Icons not displaying properly in IOS device
Can anyone help me in resolving the bootstrap icons on IOS devices? The below screenshot shows how it is displaying in iOS.

When I refresh the page it is back to normal bootstrap.

I have changed the relative path for icon-font-path but it didn't fix the issue.

答: You should try font-awesome...</p>

Body: You should try font-awesome...


问:
Failing to search for full names while querying mysql with php
First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:

```<code>player_id | first_name   | last_name
   191         John          Smith
   192         Larry         Citizen
   193         Benjamin      Example
</code>```

I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.

```<code>session_start();

include '../con.php';

$player = $_POST['name'];

$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";

$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {

    echo "Found no-one with the name $player. <a href='../search.php'>Try Again?</a>";

} else {

    $_SESSION['selplate'] = $row['plate'];
    $_SESSION['selname'] = $row['first_name, last_name'];

    header("Location: ../profile.php?player=$player");

}
</code>```

No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"

This was supposed to be the easy part of this project and I am pulling my hair out.

I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.

答:
you need qoutes ' ' around player because its a text and  also concatinated.
if you search Johnsmith it will return nothing
if you search John Smith it will give you result, because in your concat you are adding a space between words

```<code>"SELECT * FROM characters WHERE concat(first_name,' ',last_name) =('".$player."')"
</code>```

Body:
First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:

player_id | first_name   | last_name
   191         John          Smith
   192         Larry         Citizen
   193         Benjamin      Example

I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.

session_start();

include '../con.php';

$player = $_POST['name'];

$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";

$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {

    echo "Found no-one with the name $player. Try Again?";

} else {

    $_SESSION['selplate'] = $row['plate'];
    $_SESSION['selname'] = $row['first_name, last_name'];

    header("Location: ../profile.php?player=$player");

}

No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"

This was supposed to be the easy part of this project and I am pulling my hair out.

I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.

Body:
you need qoutes ' ' around player because its a text and  also concatinated.
if you search Johnsmith it will return nothing
if you search John Smith it will give you result, because in your concat you are adding a space between words

"SELECT * FROM characters WHERE concat(first_name,' ',last_name) =('".$player."')"


问:
Python sort by custom {key:order} pair
I currently have code that, given a list, splits the names by the regexp in the selector (user defined) and sorts by the key (location - also user defined).

The key can be a list of keys in the order in which they should be sorted.

For example:

```<code>selector = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
key = [2,1,3]
</code>```

Would sort by temp, voltage, secondary process.

That part of the code works perfectly.  Now, I need help figuring out how to sort if given a custom {key:order} paired dictionary. For example:

```<code>{
  0: ['FF', 'TT', 'SS'],
  3: ['SS', 'TT', 'FF']
}
</code>```

Basically, this would sort key 0 with FF TT SS order and then sort key 3 with SS TT FF.

Here's what I have so far:

```<code>import re
def sort_names(format_ids, selector, key=1, forced_order=None):

    if isinstance(key, int):
        key = [key]

    def convert(x):
        try:
            return float(x[:-1])
        except ValueError:
            return x

    def sort_keys(ik):
        def split_fid(x):
            x = re.findall(selector,x)[0]
            return tuple([convert(x[i]) for i in ik])
        return split_fid

    if forced_order:
        format_ids.sort(key=sort_keys(forced_order.keys()))
        return list(format_ids)
    else:
        format_ids.sort(key=sort_keys(key))
        return list(format_ids)
</code>```

Need help with the forced_order section.  Here's my input:

```<code>fids = ["synopsys_SS_2v_-40c_FF.lib",
        "synopsys_SS_1v_-40c_TT.lib",
        "synopsys_SS_1.2v_-40c_SS.lib",
        "synopsys_SS_1.4v_-40c_SS.lib",
        "synopsys_SS_2v_-40c_TT.lib",
        "synopsys_FF_3v_25c_FF.lib",
        "synopsys_TT_4v_125c_TT.lib",
        "synopsys_TT_1v_85c_TT.lib",
        "synopsys_TT_10v_85c_TT.lib",
        "synopsys_FF_3v_-40c_SS.lib",
        "synopsys_FF_3v_-40c_TT.lib"]

se = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
k = 3
fo = {
      0: ['FF', 'TT', 'SS'],
      3: ['SS', 'TT', 'FF']
     }

retlist = sort_names(fids, se, k, fo)
</code>```

Expected output for the forced_order part:

```<code>["synopsys_FF_3v_-40c_SS.lib",
 "synopsys_FF_3v_-40c_TT.lib",
 "synopsys_FF_3v_25c_FF.lib",
 "synopsys_TT_4v_125c_TT.lib",
 "synopsys_TT_1v_85c_TT.lib",
 "synopsys_TT_10v_85c_TT.lib",
 "synopsys_SS_1.2v_-40c_SS.lib",
 "synopsys_SS_1.4v_-40c_SS.lib",
 "synopsys_SS_1v_-40c_TT.lib",
 "synopsys_SS_2v_-40c_TT.lib",
 "synopsys_SS_2v_-40c_FF.lib"]
</code>```

答:
I would call what you are trying to do here: Category Ordering.  The dictionary you are passing in shows how to order certain fields.  But what your dictionary does not, because it can not, show is how to order the fields.  Python dicts are un-ordered on the keys.  I would suggest keeping the meaning of the key field regardless of whether or not you pass in the dict which shows the category ordering.

Code:

As to how to make use of the information in the category_order, I think you need to change the convert() routine to something like:

```<code>def convert(i, x):
    if i in category_order:
        return category_order[i].index(x)
    try:
        return float(x[:-1])
    except ValueError:
        return x
</code>```

Called like:

```<code>return tuple([convert(i, fields[i]) for i in key])
</code>```

Full Routine:

```<code>def sort_names(format_ids, selector, key=1, category_order=None):

    if isinstance(key, int):
        key = [key]

    if category_order is None:
        category_order = {}

    SELECTOR_RE = re.compile(selector)

    def convert(i, x):
        if i in category_order:
            return category_order[i].index(x)
        try:
            return float(x[:-1])
        except ValueError:
            return x

    def sort_keys():
        def split_fid(fid):
            fields = SELECTOR_RE.findall(fid)[0]
            return tuple([convert(i, fields[i]) for i in key])
        return split_fid

    result = list(format_ids)
    result.sort(key=sort_keys())
    return result
</code>```

Test Code:

```<code>fids = ["synopsys_SS_2v_-40c_FF.lib",
        "synopsys_SS_1v_-40c_TT.lib",
        "synopsys_SS_1.2v_-40c_SS.lib",
        "synopsys_SS_1.4v_-40c_SS.lib",
        "synopsys_SS_2v_-40c_TT.lib",
        "synopsys_FF_3v_25c_FF.lib",
        "synopsys_TT_4v_125c_TT.lib",
        "synopsys_TT_1v_85c_TT.lib",
        "synopsys_TT_10v_85c_TT.lib",
        "synopsys_FF_3v_-40c_SS.lib",
        "synopsys_FF_3v_-40c_TT.lib"]

se = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
k = [0, 3]
fo = {
      0: ['FF', 'TT', 'SS'],
      3: ['SS', 'TT', 'FF']
     }

print('\n'.join(sort_names(fids, se, k, fo)))
</code>```

Results:

```<code>synopsys_FF_3v_-40c_SS.lib
synopsys_FF_3v_-40c_TT.lib
synopsys_FF_3v_25c_FF.lib
synopsys_TT_4v_125c_TT.lib
synopsys_TT_1v_85c_TT.lib
synopsys_TT_10v_85c_TT.lib
synopsys_SS_1.2v_-40c_SS.lib
synopsys_SS_1.4v_-40c_SS.lib
synopsys_SS_1v_-40c_TT.lib
synopsys_SS_2v_-40c_TT.lib
synopsys_SS_2v_-40c_FF.lib
</code>```

Alternate Sort Key Results:

```<code>print('\n'.join(sort_names(fids, se, [2, 1, 3], fo)))
</code>```

Gives:

```<code>synopsys_SS_1v_-40c_TT.lib
synopsys_SS_1.2v_-40c_SS.lib
synopsys_SS_1.4v_-40c_SS.lib
synopsys_SS_2v_-40c_TT.lib
synopsys_SS_2v_-40c_FF.lib
synopsys_FF_3v_-40c_SS.lib
synopsys_FF_3v_-40c_TT.lib
synopsys_FF_3v_25c_FF.lib
synopsys_TT_1v_85c_TT.lib
synopsys_TT_10v_85c_TT.lib
synopsys_TT_4v_125c_TT.lib
</code>```

Title: Python sort by custom {key:order} pair

Body:
I currently have code that, given a list, splits the names by the regexp in the selector (user defined) and sorts by the key (location - also user defined).

The key can be a list of keys in the order in which they should be sorted.

For example:

selector = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
key = [2,1,3]

Would sort by temp, voltage, secondary process.

That part of the code works perfectly.  Now, I need help figuring out how to sort if given a custom {key:order} paired dictionary. For example:

{
  0: ['FF', 'TT', 'SS'],
  3: ['SS', 'TT', 'FF']
}

Basically, this would sort key 0 with FF TT SS order and then sort key 3 with SS TT FF.

Here's what I have so far:

import re
def sort_names(format_ids, selector, key=1, forced_order=None):

    if isinstance(key, int):
        key = [key]

    def convert(x):
        try:
            return float(x[:-1])
        except ValueError:
            return x

    def sort_keys(ik):
        def split_fid(x):
            x = re.findall(selector,x)[0]
            return tuple([convert(x[i]) for i in ik])
        return split_fid

    if forced_order:
        format_ids.sort(key=sort_keys(forced_order.keys()))
        return list(format_ids)
    else:
        format_ids.sort(key=sort_keys(key))
        return list(format_ids)

Need help with the forced_order section.  Here's my input:

fids = ["synopsys_SS_2v_-40c_FF.lib",
        "synopsys_SS_1v_-40c_TT.lib",
        "synopsys_SS_1.2v_-40c_SS.lib",
        "synopsys_SS_1.4v_-40c_SS.lib",
        "synopsys_SS_2v_-40c_TT.lib",
        "synopsys_FF_3v_25c_FF.lib",
        "synopsys_TT_4v_125c_TT.lib",
        "synopsys_TT_1v_85c_TT.lib",
        "synopsys_TT_10v_85c_TT.lib",
        "synopsys_FF_3v_-40c_SS.lib",
        "synopsys_FF_3v_-40c_TT.lib"]

se = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
k = 3
fo = {
      0: ['FF', 'TT', 'SS'],
      3: ['SS', 'TT', 'FF']
     }

retlist = sort_names(fids, se, k, fo)

Expected output for the forced_order part:

["synopsys_FF_3v_-40c_SS.lib",
 "synopsys_FF_3v_-40c_TT.lib",
 "synopsys_FF_3v_25c_FF.lib",
 "synopsys_TT_4v_125c_TT.lib",
 "synopsys_TT_1v_85c_TT.lib",
 "synopsys_TT_10v_85c_TT.lib",
 "synopsys_SS_1.2v_-40c_SS.lib",
 "synopsys_SS_1.4v_-40c_SS.lib",
 "synopsys_SS_1v_-40c_TT.lib",
 "synopsys_SS_2v_-40c_TT.lib",
 "synopsys_SS_2v_-40c_FF.lib"]

Body:
I would call what you are trying to do here: Category Ordering.  The dictionary you are passing in shows how to order certain fields.  But what your dictionary does not, because it can not, show is how to order the fields.  Python dicts are un-ordered on the keys.  I would suggest keeping the meaning of the key field regardless of whether or not you pass in the dict which shows the category ordering.

Code:

As to how to make use of the information in the category_order, I think you need to change the convert() routine to something like:

def convert(i, x):
    if i in category_order:
        return category_order[i].index(x)
    try:
        return float(x[:-1])
    except ValueError:
        return x

Called like:

return tuple([convert(i, fields[i]) for i in key])

Full Routine:

def sort_names(format_ids, selector, key=1, category_order=None):

    if isinstance(key, int):
        key = [key]

    if category_order is None:
        category_order = {}

    SELECTOR_RE = re.compile(selector)

    def convert(i, x):
        if i in category_order:
            return category_order[i].index(x)
        try:
            return float(x[:-1])
        except ValueError:
            return x

    def sort_keys():
        def split_fid(fid):
            fields = SELECTOR_RE.findall(fid)[0]
            return tuple([convert(i, fields[i]) for i in key])
        return split_fid

    result = list(format_ids)
    result.sort(key=sort_keys())
    return result

Test Code:

fids = ["synopsys_SS_2v_-40c_FF.lib",
        "synopsys_SS_1v_-40c_TT.lib",
        "synopsys_SS_1.2v_-40c_SS.lib",
        "synopsys_SS_1.4v_-40c_SS.lib",
        "synopsys_SS_2v_-40c_TT.lib",
        "synopsys_FF_3v_25c_FF.lib",
        "synopsys_TT_4v_125c_TT.lib",
        "synopsys_TT_1v_85c_TT.lib",
        "synopsys_TT_10v_85c_TT.lib",
        "synopsys_FF_3v_-40c_SS.lib",
        "synopsys_FF_3v_-40c_TT.lib"]

se = r'.*(FF|TT|SS)_([-\.\d]+v)_([-\.\d]+c)_(FF|TT|SS).*'
k = [0, 3]
fo = {
      0: ['FF', 'TT', 'SS'],
      3: ['SS', 'TT', 'FF']
     }

print('\n'.join(sort_names(fids, se, k, fo)))

Results:

synopsys_FF_3v_-40c_SS.lib
synopsys_FF_3v_-40c_TT.lib
synopsys_FF_3v_25c_FF.lib
synopsys_TT_4v_125c_TT.lib
synopsys_TT_1v_85c_TT.lib
synopsys_TT_10v_85c_TT.lib
synopsys_SS_1.2v_-40c_SS.lib
synopsys_SS_1.4v_-40c_SS.lib
synopsys_SS_1v_-40c_TT.lib
synopsys_SS_2v_-40c_TT.lib
synopsys_SS_2v_-40c_FF.lib

Alternate Sort Key Results:

print('\n'.join(sort_names(fids, se, [2, 1, 3], fo)))

Gives:

synopsys_SS_1v_-40c_TT.lib
synopsys_SS_1.2v_-40c_SS.lib
synopsys_SS_1.4v_-40c_SS.lib
synopsys_SS_2v_-40c_TT.lib
synopsys_SS_2v_-40c_FF.lib
synopsys_FF_3v_-40c_SS.lib
synopsys_FF_3v_-40c_TT.lib
synopsys_FF_3v_25c_FF.lib
synopsys_TT_1v_85c_TT.lib
synopsys_TT_10v_85c_TT.lib
synopsys_TT_4v_125c_TT.lib


问:
Python (Pandas) - Working with numeric data but adding non numeric data back
I have a CSV file that looks like this:

```<code>Build,Avg,Min,Max
BuildA,56.190,39.123,60.1039
BuildX,57.11,40.102,60.200
BuildZER,55.1134,35.129404123,60.20121
</code>```

I want to get the average, min, max of each column and have each of these stats be as a new row. I exclude the non numeric column (the build column) and then run the statistics. I accomplish this by doing:

```<code>df = pd.read_csv('fakedata.csv')
columns = []
builds = []

for column in df.columns:
    if(df[column].dtype == 'float64'):
        columns.append(column)
    else:
        builds.append(column)

save = df[builds]
df = df[columns]

print(df)

df.loc['Min']= df.min()
df.loc['Average']= df.mean()
df.loc['Max']= df.max()
</code>```

If I were then to write this data to a CSV it would look like:

```<code>,Avg,Min,Max
0,56.19,39.123,60.1039
1,57.11,40.102,60.2
2,55.1134,35.129404123,60.20121
Min,55.1134,35.129404123,60.1039
Average,55.8817,37.3709520615,60.1522525
Max,57.11,40.102,60.20121
</code>```

Which is close to what I want but I want the Build column to be column one again and have the build names exist on top of the Min, Average, Max. Basically this:

```<code>Builds,Avg,Min,Max
BuildA,56.19,39.123,60.1039
BuildX,57.11,40.102,60.2
BuildZER,55.1134,35.129404123,60.20121
Min,55.1134,35.129404123,60.1039
Average,55.8817,37.3709520615,60.1522525
Max,57.11,40.102,60.20121
</code>```

I have attempted to accomplish this by doing:

```<code>df.insert(0,'builds', save)
with open('fakedata.csv', 'w') as f:
    df.to_csv(f)
</code>```

But this gives me this CSV:

```<code>,builds,Avg,Min,Max
0,Build1,56.19,39.123,60.1039
1,Build2,57.11,40.102,60.2
2,Build3,55.1134,35.129404123,60.20121
Min,,55.1134,35.129404123,60.1039
Average,,55.8817,37.3709520615,60.1522525
Max,,57.11,40.102,60.20121
</code>```

How can I fix this?

Body:
I have a CSV file that looks like this:

Build,Avg,Min,Max
BuildA,56.190,39.123,60.1039
BuildX,57.11,40.102,60.200
BuildZER,55.1134,35.129404123,60.20121

I want to get the average, min, max of each column and have each of these stats be as a new row. I exclude the non numeric column (the build column) and then run the statistics. I accomplish this by doing:

df = pd.read_csv('fakedata.csv')
columns = []
builds = []

for column in df.columns:
    if(df[column].dtype == 'float64'):
        columns.append(column)
    else:
        builds.append(column)

save = df[builds]
df = df[columns]

print(df)

df.loc['Min']= df.min()
df.loc['Average']= df.mean()
df.loc['Max']= df.max()

If I were then to write this data to a CSV it would look like:

,Avg,Min,Max
0,56.19,39.123,60.1039
1,57.11,40.102,60.2
2,55.1134,35.129404123,60.20121
Min,55.1134,35.129404123,60.1039
Average,55.8817,37.3709520615,60.1522525
Max,57.11,40.102,60.20121

Which is close to what I want but I want the Build column to be column one again and have the build names exist on top of the Min, Average, Max. Basically this:

Builds,Avg,Min,Max
BuildA,56.19,39.123,60.1039
BuildX,57.11,40.102,60.2
BuildZER,55.1134,35.129404123,60.20121
Min,55.1134,35.129404123,60.1039
Average,55.8817,37.3709520615,60.1522525
Max,57.11,40.102,60.20121

I have attempted to accomplish this by doing:

df.insert(0,'builds', save)
with open('fakedata.csv', 'w') as f:
    df.to_csv(f)

But this gives me this CSV:

,builds,Avg,Min,Max
0,Build1,56.19,39.123,60.1039
1,Build2,57.11,40.102,60.2
2,Build3,55.1134,35.129404123,60.20121
Min,,55.1134,35.129404123,60.1039
Average,,55.8817,37.3709520615,60.1522525
Max,,57.11,40.102,60.20121

How can I fix this?

Body:
IIUC:

df_out = pd.concat([df.set_index('Build'),df.set_index('Build').agg(['max','min','mean'])]).rename(index={'max':'Max','min':'Min','mean':'Average'}).reset_index()

Output:

      index      Avg        Min       Max
0    BuildA  56.1900  39.123000  60.10390
1    BuildX  57.1100  40.102000  60.20000
2  BuildZER  55.1134  35.129404  60.20121
3       Max  57.1100  40.102000  60.20121
4       Min  55.1134  35.129404  60.10390
5   Average  56.1378  38.118135  60.16837


问:
How do I get a reference to the currently displayed Java Swing JDialog box?
I am using a Java Swing based framework that shows popup messages using Java Swing JDialog boxes. I need to get a reference the them so I cam close them programatically. The framework creates dialog boxes but doesn't keep a reference to them. Can I get a reference to the currently displayed box?

Thanks.

答:
either set the dialog as modal, which makes your life really easy...<br>
OR, when you're initialising your JDialog have the following:  </p>

```<code>JDialog d = new JDialog();
d.addWindowListener(new WindowAdapter(){
    public void windowClosed(WindowEvent e){
        dialogClosedAlertFunction(); //goes wherever you want it to go
    }
});
</code>```

OwnerDisplayName: Dave

LastEditorDisplayName: Dave

Body:
either set the dialog as modal, which makes your life really easy...

OR, when you're initialising your JDialog have the following:

JDialog d = new JDialog();
d.addWindowListener(new WindowAdapter(){
    public void windowClosed(WindowEvent e){
        dialogClosedAlertFunction(); //goes wherever you want it to go
    }
});


问:
Pycharm - Anaconda2 - Windows7 - py35 environment - SDK error
I've been trying to set a virtual environment for some time now, but with no success. I read many topics regarding this manner, but couldn't find a solution for my problem.

I am running:

Windows 7

Pycharm Community Edition 2017.1.4

Anaconda 2

Python 2.7.13

I am trying to set up an environment of Python 3.5.3 - Anaconda
I used this command:

conda create -n py35 python=3.5 anaconda

(also tried : conda create -n py35 python=3.5.3 anaconda) same result

via PyCharm terminal.
It does seem that it sets up an environment and I am able to switch between them in the terminal, but when I try to add it as a local Interpreter I keep receiving a message:

Cannot set up a python SDK  at Python 3.5.3
  (C:\Users\Cossack\Anaconda2\envs\py35\python.exe)
  (C:\Users\Cossack\Anaconda2\envs\py35\python.exe). The SDK seems
  invalid.

I also tried creating conda Env via PyCharm settings, but same error appears.
I tried creating environment for python 3.6 just to see if that was the problem source, but again, the same error appeared.

I really need both Python 2.7 and 3.5, but I keep getting errors which I have no Idea on how to solve.

Thank you very much in advance, hope that someone can help me in solving this issue.

答:
Thank you for your answers and help.

After I've completely removed Anaconda and all the side packages, and reinstalled everything from scratch, the method I mention in the question worked fine and without any setbacks.

Although it's frustrating to reinstall everything from scratch, it solved the problem.

For some reason, changing the Path backfired and nothing worked at all after that and even when I tried to restore the previous Path, it wouldn't work anymore.
So if anyone has the same issue when mentioned above doesn't work, all I can suggest is to fully reinstall the program.


问:
how to change my android app's window appearance in apps list when my app is in background?
I'll try to explain my question:

I have an app developed by me, that is now open on my android device with some activity that contains some data.

I want to hide this data if my app goes to background and I have some other apps open and looking on the open apps list.

Is there any way to change current activity's layout (I have many activities) when the app goes to background? For example to blur it or just show some default layout/image instead of current activity with the real data that I have?

viewing open apps

答:
and you can disable thumbnail on the activity containing sensitive data by adding FLAG_SECURE to your window:

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
</code>```

Or exclude it from recents in the manifest

```<code>android:excludeFromRecents="true"
</code>```

Body:
and you can disable thumbnail on the activity containing sensitive data by adding FLAG_SECURE to your window:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

Or exclude it from recents in the manifest

android:excludeFromRecents="true"


问:
TensorFlow while_loop converts variable to constant?
I'm trying to update a two dimensional tensor in a nested while_loop(). When passing the variable to the second loop however, I cannot updated it using tf.assign() as it throws this error:

```<code>ValueError: Sliced assignment is only supported for variables
</code>```

Somehow it works fine if I create the variable outside the while_loop and use it only in the first loop.

How can I modify my 2D tf variable in the second while loop?

(I'm using python 2.7 and TensorFlow 1.2)

My code:

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

tf.reset_default_graph()

BATCH_SIZE = 10
LENGTH_MAX_OUTPUT = 31

it_batch_nr = tf.constant(0)
it_row_nr = tf.Variable(0, dtype=tf.int32)
it_col_nr = tf.constant(0)
cost = tf.constant(0)

it_batch_end = lambda it_batch_nr, cost: tf.less(it_batch_nr, BATCH_SIZE)
it_row_end = lambda it_row_nr, cost_matrix: tf.less(it_row_nr, LENGTH_MAX_OUTPUT+1)

def iterate_batch(it_batch_nr, cost):
    cost_matrix = tf.Variable(np.ones((LENGTH_MAX_OUTPUT+1, LENGTH_MAX_OUTPUT+1)), dtype=tf.float32)
    it_rows, cost_matrix = tf.while_loop(it_row_end, iterate_row, [it_row_nr, cost_matrix])
    cost = cost_matrix[0,0] # IS 1.0, SHOULD BE 100.0
    return tf.add(it_batch_nr,1), cost

def iterate_row(it_row_nr, cost_matrix):
    # THIS THROWS AN ERROR:
    cost_matrix[0,0].assign(100.0)
    return tf.add(it_row_nr,1), cost_matrix

it_batch = tf.while_loop(it_batch_end, iterate_batch, [it_batch_nr, cost])

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
out = sess.run(it_batch)
print(out)
</code>```

答:
tf.Variable objects cannot be used as loop variables in a while loop, as loop variables are implemented differently.

So either create your variable outside the loop and update it yourself with tf.assign in each iteration or manually keep track of the updates as you do with loop variables (by returning their updated values from the loop lambdas, and in your case using the value from the inner loop as the new value for the outer loop).

Body:
I'm trying to update a two dimensional tensor in a nested while_loop(). When passing the variable to the second loop however, I cannot updated it using tf.assign() as it throws this error:

ValueError: Sliced assignment is only supported for variables

Somehow it works fine if I create the variable outside the while_loop and use it only in the first loop.

How can I modify my 2D tf variable in the second while loop?

(I'm using python 2.7 and TensorFlow 1.2)

My code:

import tensorflow as tf
import numpy as np

tf.reset_default_graph()

BATCH_SIZE = 10
LENGTH_MAX_OUTPUT = 31

it_batch_nr = tf.constant(0)
it_row_nr = tf.Variable(0, dtype=tf.int32)
it_col_nr = tf.constant(0)
cost = tf.constant(0)

it_batch_end = lambda it_batch_nr, cost: tf.less(it_batch_nr, BATCH_SIZE)
it_row_end = lambda it_row_nr, cost_matrix: tf.less(it_row_nr, LENGTH_MAX_OUTPUT+1)

def iterate_batch(it_batch_nr, cost):
    cost_matrix = tf.Variable(np.ones((LENGTH_MAX_OUTPUT+1, LENGTH_MAX_OUTPUT+1)), dtype=tf.float32)
    it_rows, cost_matrix = tf.while_loop(it_row_end, iterate_row, [it_row_nr, cost_matrix])
    cost = cost_matrix[0,0] # IS 1.0, SHOULD BE 100.0
    return tf.add(it_batch_nr,1), cost

def iterate_row(it_row_nr, cost_matrix):
    # THIS THROWS AN ERROR:
    cost_matrix[0,0].assign(100.0)
    return tf.add(it_row_nr,1), cost_matrix

it_batch = tf.while_loop(it_batch_end, iterate_batch, [it_batch_nr, cost])

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
out = sess.run(it_batch)
print(out)


问:
How to access history.listen in a React component?
I have a specific component who would like to be notified every time the user navigates. Is there some way to access the history passed into the router?

```<code><Router history={history}>
   {// ...}
</Router>
</code>```

Child component:

```<code>var Component = React.createClass({
   componentDidMount: function() {
     // history.listen(this.onRouteChange);
   },
   onRouteChange: function() {},
   render: function() {...},
});
</code>```

答:
Use withRouter from 'react-router' like this:

```<code>import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'
</code>```

Following a simple component that shows the pathname of the current location. Works the same for history prop, just use history instead of location then.

```<code>class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}
</code>```

Create a new component that is "connected" (to borrow redux // terminology) to the router.

```<code>const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
</code>```

From: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md

Body:
I have a specific component who would like to be notified every time the user navigates. Is there some way to access the history passed into the router?

<Router history={history}>
   {// ...}
</Router>

Child component:

var Component = React.createClass({
   componentDidMount: function() {
     // history.listen(this.onRouteChange);
   },
   onRouteChange: function() {},
   render: function() {...},
});

Body:
Use withRouter from 'react-router' like this:

import React from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'react-router'

Following a simple component that shows the pathname of the current location. Works the same for history prop, just use history instead of location then.

class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

Create a new component that is "connected" (to borrow redux // terminology) to the router.

const ShowTheLocationWithRouter = withRouter(ShowTheLocation)

From: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md


问:
How work with collections in YAML
I have

```<code>init:
   test: yasha,grisha
      my: ${init.test[0]}
</code>```

And it's now working.
How work with list/arrays in YAML?

答:
A list in YAML (normally called a sequence) can be specified in in block style:

```<code>a:
- 1
- 2
</code>```

and flow style:

```<code>a: [1, 2]
</code>```

both depicting a mapping with one key a, for which the value is the sequence/list consisting of elements 1 and 2

The dashes before the elements in block style can, but do not have to be, indented further than the "parent" element

Title: How work with collections in YAML

Body:
I have

init:
   test: yasha,grisha
      my: ${init.test[0]}

And it's now working.
How work with list/arrays in YAML?

Body:
A list in YAML (normally called a sequence) can be specified in in block style:

a:
- 1
- 2

and flow style:

a: [1, 2]

both depicting a mapping with one key a, for which the value is the sequence/list consisting of elements 1 and 2

The dashes before the elements in block style can, but do not have to be, indented further than the "parent" element


问:
Updating tab badge dynamically on Ionic 2
I wish to update dynamically a badge value, when I click on a button.

tabs.html

```<code>...
        <ion-tab [root]="tab1Root" tabTitle="Product" tabIcon="search"></ion-tab>
        <ion-tab [root]="tab2Root" tabTitle="Cart" tabIcon="cart" tabBadge="{{cartCount}}" tabBadgeStyle="danger"></ion-tab>
...
</code>```

tabs.ts

```<code>export class TabsPage {
...
    cartCount = 0;

    tab1Root = ProductPage;
    tab2Root = CartPage;
...
}
</code>```

product.html

```<code><button ion-button full (click)="updateCart('add', p.id)">Buy Now</button>
</code>```

product.ts

```<code>export class ProductPage {
...
    updateCart(action, id) {
        let cartCount = 1;

        let alert = this.alertCtrl.create({
            title: 'Success!',
            subTitle: 'You have added 1 product to the cart.',
            buttons: ['OK']
        });

        alert.present();
    }
...
}
</code>```

As I tought, let cartCount = 1; does nothing. I've searched for a solution, but most of them are for Ionic 1 or AngularJS, which didn't helped me at all.

答:
You could use Ionic events for that. Please take a look at this working plunker. Like you can see there, in the first tab we publish an event when the badge needs to be updated:

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

@Component({..})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}
</code>```

And then we subscribe to that event in the page that contains both tabs:

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

@Component({...})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}
</code>```

And in the view:

```<code><ion-header>
  <ion-navbar>
    <ion-title>Tabs</ion-title>
  </ion-navbar>
</ion-header>
<ion-tabs #myTabs>
  <ion-tab [root]="tab1Root" tabTitle="First Tab"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Second Tab" [tabBadge]="cartCount"></ion-tab>
</ion-tabs>
</code>```

Please also notice that property binding should be used instead of string interpolation to bind the tabBadge property: [tabBadge]="cartCount"

UPDATE

Just like @skinny_jones mentioned in the comments, you could also use Subjects/Observables to achieve the same result. You can find more information in this blog post

Body:
I wish to update dynamically a badge value, when I click on a button.

tabs.html

...
        <ion-tab [root]="tab1Root" tabTitle="Product" tabIcon="search"></ion-tab>
        <ion-tab [root]="tab2Root" tabTitle="Cart" tabIcon="cart" tabBadge="{{cartCount}}" tabBadgeStyle="danger"></ion-tab>
...

tabs.ts

export class TabsPage {
...
    cartCount = 0;

    tab1Root = ProductPage;
    tab2Root = CartPage;
...
}

product.html

<button ion-button full (click)="updateCart('add', p.id)">Buy Now</button>

product.ts

export class ProductPage {
...
    updateCart(action, id) {
        let cartCount = 1;

        let alert = this.alertCtrl.create({
            title: 'Success!',
            subTitle: 'You have added 1 product to the cart.',
            buttons: ['OK']
        });

        alert.present();
    }
...
}

As I tought, let cartCount = 1; does nothing. I've searched for a solution, but most of them are for Ionic 1 or AngularJS, which didn't helped me at all.

Body:
You could use Ionic events for that. Please take a look at this working plunker. Like you can see there, in the first tab we publish an event when the badge needs to be updated:

import { Component } from '@angular/core';
import { Events } from 'ionic-angular';

@Component({..})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}

And then we subscribe to that event in the page that contains both tabs:

import { Component } from '@angular/core';
import { Events } from 'ionic-angular';

@Component({...})
export class FirstTabPage {

  private count: number = 0;

  constructor(public events: Events) {}

  public updateTabBadge(): void {
    this.events.publish('cart:updated', ++this.count);
  }

}

And in the view:

<ion-header>
  <ion-navbar>
    <ion-title>Tabs</ion-title>
  </ion-navbar>
</ion-header>
<ion-tabs #myTabs>
  <ion-tab [root]="tab1Root" tabTitle="First Tab"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Second Tab" [tabBadge]="cartCount"></ion-tab>
</ion-tabs>

Please also notice that property binding should be used instead of string interpolation to bind the tabBadge property: [tabBadge]="cartCount"

UPDATE

Just like @skinny_jones mentioned in the comments, you could also use Subjects/Observables to achieve the same result. You can find more information in this blog post


问:
NDepend Average Cyclomatic Complexity without get and set
We are using NDepend 5 and I did have some doubts about our Average Cyclomatic Complexity.

When checking how this query is made, I found out that it includes getters and setters of our properties. It seems to also includes auto properties methods. Those methodes are usually equivalent to a CC of 1. I don't like that because it lower our average CC and show us not the real average of methods we code.

Is there a way to remove properties from this calculation ?

答:
You can define a custom complexity metric with a code query that can be transformed into a rule if needed (with the prefix warnif count > 0 and a threshold condition):

```<code>from t in JustMyCode.Types
let complexity = t.Methods.Where(m => !(m.IsPropertyGetter || m.IsPropertySetter))
                 .Sum(m => m.CyclomaticComplexity)
orderby complexity descending
select new { t, complexity, t.CyclomaticComplexity }
</code>```

The screenshot below compares the obtained values.

Btw, NDepend v5 is not supported anymore and v6 and v2017 brought a lot of new features.

Body:
You can define a custom complexity metric with a code query that can be transformed into a rule if needed (with the prefix warnif count > 0 and a threshold condition):

from t in JustMyCode.Types
let complexity = t.Methods.Where(m => !(m.IsPropertyGetter || m.IsPropertySetter))
                 .Sum(m => m.CyclomaticComplexity)
orderby complexity descending
select new { t, complexity, t.CyclomaticComplexity }

The screenshot below compares the obtained values.

Btw, NDepend v5 is not supported anymore and v6 and v2017 brought a lot of new features.


问:
How To Properly Create a Histogram: Displaying the Frequency of the Tweets for Each Day Spanning 2 Years
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

```<code>timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']
</code>```

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

Body:
Unfortunately, I'm not experienced at all with matplotlib (and similar libraries), and I find some of the avaiable tutorials confusing.

This is my problem:

I have list of timestamps in string format, like this:

timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']

Each timestamp represents a tweet. I would like to build a histogram similar to this, but grouping my tweets per day. So, ultimately, I would like this histogram to show how many tweets are being tweeted on a daily basis from my list.

I have no idea how to group these tweets day by day (or any other grouping, i.e. monthly). I don't know which is the most easy and painless way to do it, and most importantly, when I'm reading posts on how to use matplotlib to create histograms (and similar things, like CDFs), I don't understand what each line specifically does, and thus, I cannot edit these posts according to my needs and expand my knowledge.

Can someone please provide a sample solution of to create such a histogram using matplotlib (or similar), but also comment each line so that I can fully understand how to produce similar plots in the future?

Thank you.

EDIT: I think that my original question wasn't clear enough, since none of the solutions suggested solve my problem. I'm sorry for not being more explicit. I will try to elaborate:

Let's say that I have a set of tweets of a specific topic spanning a duration of two years. This sums up to 730 days. timestamp_list is a list containing the unique timestamps of each tweet, in string format.

Every day in the duration of these two years is a unique day. That means that I have 730 unique days. What I want is to find out how many tweets of that specific topic were tweeted on every day of the 730 days. For instance, on 2017-01-20 there might have been 10 tweets, on 2017-01-21 45 tweets, and so on. I would like to create a histogram based on this. Some people suggested creating a dictionary.

How can I create a dictionary containing 730 keys and their respective number of tweets?

How can I plot a histogram based on the previous dictionary?

Or, if there is another, more efficient way to do (instead of using dictionaries), it's also welcome.

What I want is to somehow take this string list and create a histogram, like this, showing the number of tweets tweeted on a daily basis, spanning the duration of the dates (in my case, 2 years).

Bounty:

Thank you all for your submissions. Both @cphlewis' and @TobiasRibizel' answers are correct. However, I'm inclined to pick @TobiasRibizel' answer as the winning answer, since it doesn't use third party libraries, it is very well explained, and it produces a very nice histogram, just like the one I asked. Thank you.

Body:
You could use default dict and group them by date like this:

from collections import defaultdict

groups = defaultdict(list)
timestamp_list = ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-30 05:54', '2017-01-29 03:10']

for obj in timestamp_list:
    groups[obj[8:-6]].append(obj)

new_list = list(groups.values())

print(new_list)

[
 ['2017-01-30 23:45', '2017-01-30 20:30', '2017-01-30 18:22', '2017-01-30 05:54'],
 ['2017-01-29 17:39', '2017-01-29 15:39', '2017-01-29 14:45', '2017-01-29 11:51', '2017-01-29 11:15', '2017-01-29 09:41', '2017-01-29 03:10']
]


问:
How to download and unzip a raster zipped file directly in r from github
I am trying to download 'Landsat.rar` file (included 6 Landsat bands) and unzip it directly in r, but It doesn't work as I expected. Thank you for your help!</p>

```<code>library(raster)

ls_url<-"https://github.com/tuyenhavan/Landsat-Data/blob/LS7/Landsat.rar"

temp<-tempfile()

download.file(ls_url,temp)

unzip(temp,"tif$")

myls<-stack("tif$")
</code>```

答:
Especially if you are using Windows, it might be that you need to use the binary mode in download.file:

```<code>download.file(ls_url, temp, mode="wb")
</code>```

otherwise the file gets corrupted.

Also, the URL you are using is incorrect. You used the one for the web interface. If you want to get the file itself you need to use (check the link associated with the "Download" button):

```<code>https://github.com/tuyenhavan/Landsat-Data/raw/LS7/Landsat.rar
</code>```

Finally, unzip() doesn't know how to deal with rar archive files. If you created this archive yourself, use the zip format instead; or unrar the file with another program (that you could call from R using system()).

Body:
I am trying to download 'Landsat.rar` file (included 6 Landsat bands) and unzip it directly in r, but It doesn't work as I expected. Thank you for your help!

library(raster)

ls_url<-"https://github.com/tuyenhavan/Landsat-Data/blob/LS7/Landsat.rar"

temp<-tempfile()

download.file(ls_url,temp)

unzip(temp,"tif$")

myls<-stack("tif$")

Body:
Especially if you are using Windows, it might be that you need to use the binary mode in download.file:

download.file(ls_url, temp, mode="wb")

otherwise the file gets corrupted.

Also, the URL you are using is incorrect. You used the one for the web interface. If you want to get the file itself you need to use (check the link associated with the "Download" button):

https://github.com/tuyenhavan/Landsat-Data/raw/LS7/Landsat.rar

Finally, unzip() doesn't know how to deal with rar archive files. If you created this archive yourself, use the zip format instead; or unrar the file with another program (that you could call from R using system()).


问:
Detect Phone Number & Link in xamarin.Form
assume we have the following text :

Contact us on 015546889 or email@hotmail.com

How I can display the above text in same label in xamarin.forms and handle click on email by send email and handle phone call by click on the number.

I can use the the following code to make clickable label

```<code>Label label = new Label;
     label.GestureRecognizers.Add(new TapGestureRecognizer()
    {
         Command = new Command(() => {
           //do some function here
        })
   });
</code>```

How to hyperlink same as messaging app or Whatsapp application

答:
After a lot of search i found the perfect solution Here :

https://theconfuzedsourcecode.wordpress.com/tag/xamarin-hyperlink-label/

Hope this will help others :)

Body:
assume we have the following text :

Contact us on 015546889 or email@hotmail.com

How I can display the above text in same label in xamarin.forms and handle click on email by send email and handle phone call by click on the number.

I can use the the following code to make clickable label

Label label = new Label;
     label.GestureRecognizers.Add(new TapGestureRecognizer()
    {
         Command = new Command(() => {
           //do some function here
        })
   });

How to hyperlink same as messaging app or Whatsapp application


问:
Grails - Class "org.grails.tomcat.TomcatLoader" was not found in the CLASSPATH
grails run-app from within Eclipse is currently giving me the exception below for my Google App Engine/Grails test application:

```<code>Enhancing JDO classes
  [enhance] DataNucleus Enhancer (version 1.1.4) : Enhancement of classes
  [enhance] Jan 24, 2010 5:11:42 AM org.datanucleus.metadata.MetaDataManager loadClasses
  [enhance] SEVERE: Class "org.grails.tomcat.TomcatLoader" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
  [enhance] org.datanucleus.exceptions.ClassNotResolvedException: Class "org.grails.tomcat.TomcatLoader" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
  [enhance]     at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:250)
  [enhance]     at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:415)
  [enhance]     at org.datanucleus.metadata.MetaDataManager.loadClasses(MetaDataManager.java:379)
  [enhance]     at org.datanucleus.enhancer.DataNucleusEnhancer.getFileMetadataForInput(DataNucleusEnhancer.java:743)
  [enhance]     at org.datanucleus.enhancer.DataNucleusEnhancer.enhance(DataNucleusEnhancer.java:545)
  [enhance]     at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1252)
  [enhance]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  [enhance]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  [enhance]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  [enhance]     at java.lang.reflect.Method.invoke(Method.java:597)
  [enhance]     at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:57)
  [enhance]     at com.google.appengine.tools.enhancer.Enhance.<init>(Enhance.java:60)
  [enhance]     at com.google.appengine.tools.enhancer.Enhance.main(Enhance.java:41)
  [enhance] DataNucleus Enhancer completed with success for 0 classes. Timings : input=487 ms, enhance=0 ms, total=487 ms. Consult the log for full details
  [enhance] DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details
</code>```

I get this error after creating a Grails project with Spring Tools Suite (STS) and then installing the app-engine plugin "grails install-plugin app-engine". Before, I install the app-engine plugin the Grails project runs correctly.

Any ideas?

答: More than likely, the error message from DataNucleus Enhancer is deceiving.  It probably can't find the dependent classes of org.grails.tomcat.TomcatLoader.  Are all the dependent libs of the grails TomcatLoader class in your classpath?  I had a similar situation  -- the error message was incorrect.  </p>

Body:
grails run-app from within Eclipse is currently giving me the exception below for my Google App Engine/Grails test application:

Enhancing JDO classes
  [enhance] DataNucleus Enhancer (version 1.1.4) : Enhancement of classes
  [enhance] Jan 24, 2010 5:11:42 AM org.datanucleus.metadata.MetaDataManager loadClasses
  [enhance] SEVERE: Class "org.grails.tomcat.TomcatLoader" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
  [enhance] org.datanucleus.exceptions.ClassNotResolvedException: Class "org.grails.tomcat.TomcatLoader" was not found in the CLASSPATH. Please check your specification and your CLASSPATH.
  [enhance]     at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:250)
  [enhance]     at org.datanucleus.JDOClassLoaderResolver.classForName(JDOClassLoaderResolver.java:415)
  [enhance]     at org.datanucleus.metadata.MetaDataManager.loadClasses(MetaDataManager.java:379)
  [enhance]     at org.datanucleus.enhancer.DataNucleusEnhancer.getFileMetadataForInput(DataNucleusEnhancer.java:743)
  [enhance]     at org.datanucleus.enhancer.DataNucleusEnhancer.enhance(DataNucleusEnhancer.java:545)
  [enhance]     at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1252)
  [enhance]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  [enhance]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  [enhance]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  [enhance]     at java.lang.reflect.Method.invoke(Method.java:597)
  [enhance]     at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:57)
  [enhance]     at com.google.appengine.tools.enhancer.Enhance.<init>(Enhance.java:60)
  [enhance]     at com.google.appengine.tools.enhancer.Enhance.main(Enhance.java:41)
  [enhance] DataNucleus Enhancer completed with success for 0 classes. Timings : input=487 ms, enhance=0 ms, total=487 ms. Consult the log for full details
  [enhance] DataNucleus Enhancer completed and no classes were enhanced. Consult the log for full details

I get this error after creating a Grails project with Spring Tools Suite (STS) and then installing the app-engine plugin "grails install-plugin app-engine". Before, I install the app-engine plugin the Grails project runs correctly.

Any ideas?


问:
Inject inline templates into $templateCache for Jasmine tests
If all of my templates are in my index.html, with each inside its own  block, how can I get them into the $templatecache so that Jasmine knows they exist?

Currently, Jasmine treats all of my templateUrl values as if they were all remote paths. I have looked through karma-ng-html2js-preprocessor, but it appears that this is for getting discrete template files into $templatecache, rather than script blocks.

Here is a plunker showing how the inline templates are loaded.

Body:
Use the karma-ng-template-preprocessor module:

Preprocessor for taking HTML files that have <script type="ng/template"> and putting them into the AngularJS Template Cache Thanks to karma-ng-html2js-preprocessor for the idea and code snippets

For example, set up karma.conf.js as follows:

// preprocess HTML files before serving them to phantomJS
    preprocessors: {'app/**/*.html': 'ng-template'},
// include HTML files in the karma session
    files: ['**/*.html'],

// if you have defined plugins explicitly, add karma-ng-template-script-to-template-cache-preprocessor
// plugins: ['karma-ng-template-preprocessor']

ngTemplatePreprocessor: { moduleName: 'inlineTemplates'}

Use it in your tests as such:

function foo()
  {
  beforeEach(module('inlineTemplates'));
  }

describe('example test', foo);

References

karma-ng-template-preprocessor

karma-ng-html2js-preprocessor


问:
Exporting a session variable in a CSV file. PHP
I'm trying to export some data from my session array as a CSV but when I include the session_start() at the head of the file instead of creating a downloadable document it echoes it to the browser. Do I need to take a different approach or is there a way to fix this from happening? Without the session_start() it creates and downloads the file but its empty because my session array is missing.

```<code>    header( "Content-Type: text/csv;charset=utf-8" );
    header( "Content-Disposition: attachment;filename=\"$filename\"" );
    header("Pragma: no-cache");
    header("Expires: 0");

    session_start();
    include $_SERVER['DOCUMENT_ROOT']."/Includes/object_one.php";
    include $_SERVER['DOCUMENT_ROOT']."/Includes/object_two.php";

    $fp= fopen('php://output', 'w');

    foreach ($_SESSION['data'] as $fields){
        fputcsv($fp, $fields);
    }
    fclose($fp);
    exit();
</code>```

if it helps my array is in this format:

```<code>$data = array(dataset1(array, of, data), dataset2(array, of, data), dataset#(array, of, data));
</code>```

EDIT: Session_Start doesn't seem to be causing the issue but the includes do.

答: It could be a header problem. If you print something before the header function (like a space from a file inclusion dued to a wrong php-tag closing), all headers doesn't works. Try to put ob_clean() before declaring headers and check if works.

Body:
I'm trying to export some data from my session array as a CSV but when I include the session_start() at the head of the file instead of creating a downloadable document it echoes it to the browser. Do I need to take a different approach or is there a way to fix this from happening? Without the session_start() it creates and downloads the file but its empty because my session array is missing.

    header( "Content-Type: text/csv;charset=utf-8" );
    header( "Content-Disposition: attachment;filename=\"$filename\"" );
    header("Pragma: no-cache");
    header("Expires: 0");

    session_start();
    include $_SERVER['DOCUMENT_ROOT']."/Includes/object_one.php";
    include $_SERVER['DOCUMENT_ROOT']."/Includes/object_two.php";

    $fp= fopen('php://output', 'w');

    foreach ($_SESSION['data'] as $fields){
        fputcsv($fp, $fields);
    }
    fclose($fp);
    exit();

if it helps my array is in this format:

$data = array(dataset1(array, of, data), dataset2(array, of, data), dataset#(array, of, data));

EDIT: Session_Start doesn't seem to be causing the issue but the includes do.


问:
JS: How to compare 2 dates converting from UTC to defined timezone?
I stored a string of UTC Date (without time):

```<code>var limitDateStr = "2017-07-04T00:00:00.000Z";
</code>```

And a TIMEZONE in hours (based on this), not in Zone Name (like America/Antigua)

```<code>var timezone = "-6.0"; //could be from -12.0 to 12.0
</code>```

The problem is: Verify if actual date, is greater than limitDate in the same Timezone.

What I Do with Moment.js

I Used moment for change the timezone, but when y change the offset. The date is changed too:

```<code>  var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();
  // "2017-07-03T18:00:00-06:00"
</code>```

Instead of 2017-07-04T00:00:00-06:00

Actual date, works great: (except for Days Savings)

```<code>var today = moment.utc().utcOffset(parseFloat(timezone)).format();
//"2017-07-04T15:32:49-06:00"
</code>```

And I want to compare... maybe with moment function:

```<code>today.isAfter(_expirationDateUTC);
</code>```

but the expiration date is now working like expect.

答:
Primitive solution was: "add the difference in hours"</p>

```<code>function validateDateBefore(date, timezone){
  /** enable this for end day limit **/
  //var _expirationDateUTC = moment.utc(date).utcOffset(parseFloat(timezone)).startOf('hour').add((parseFloat(timezone) * -1) + 23, 'hours').add(59, 'minute').add(59, 'second').format();
  var _expirationDateUTC = moment.utc(date).utcOffset(parseFloat(timezone)).startOf('hour').add((parseFloat(timezone) * -1), 'hours').format();
  var _todayUTC = moment.utc().utcOffset(parseFloat(timezone)).format();

  var today = moment(_todayUTC);
  var expiration = moment(_expirationDateUTC);

  return expiration.isAfter(today);
}
</code>```

Body:
I stored a string of UTC Date (without time):

var limitDateStr = "2017-07-04T00:00:00.000Z";

And a TIMEZONE in hours (based on this), not in Zone Name (like America/Antigua)

var timezone = "-6.0"; //could be from -12.0 to 12.0

The problem is: Verify if actual date, is greater than limitDate in the same Timezone.

What I Do with Moment.js

I Used moment for change the timezone, but when y change the offset. The date is changed too:

  var _expirationDateUTC = moment.utc(limitDateStr).utcOffset(parseFloat(timezone)).format();
  // "2017-07-03T18:00:00-06:00"

Instead of 2017-07-04T00:00:00-06:00

Actual date, works great: (except for Days Savings)

var today = moment.utc().utcOffset(parseFloat(timezone)).format();
//"2017-07-04T15:32:49-06:00"

And I want to compare... maybe with moment function:

today.isAfter(_expirationDateUTC);

but the expiration date is now working like expect.

Body:
Primitive solution was: "add the difference in hours"

function validateDateBefore(date, timezone){
  /** enable this for end day limit **/
  //var _expirationDateUTC = moment.utc(date).utcOffset(parseFloat(timezone)).startOf('hour').add((parseFloat(timezone) * -1) + 23, 'hours').add(59, 'minute').add(59, 'second').format();
  var _expirationDateUTC = moment.utc(date).utcOffset(parseFloat(timezone)).startOf('hour').add((parseFloat(timezone) * -1), 'hours').format();
  var _todayUTC = moment.utc().utcOffset(parseFloat(timezone)).format();

  var today = moment(_todayUTC);
  var expiration = moment(_expirationDateUTC);

  return expiration.isAfter(today);
}


问:
AFNetworking 3.0 can't download image
I am trying to download an image using AFNetworking 3.0 doing this way:

```<code>- (UIImage *) loadImage:(NSString *) link
 {
    __block UIImage *image = [UIImage imageNamed:@"no_user_profile_pic.png"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFImageResponseSerializer serializer];
    [manager GET:[link stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]
      parameters:nil
        progress:nil
         success:^(NSURLSessionTask *task, id responseObject) {
             image = (UIImage *) responseObject;
         } failure:^(NSURLSessionTask *operation, NSError *error) {
             NSLog(@"Load Image error - %@", [error description]);
         }];
    return image;
}
</code>```

and every time I am getting this error:

*** Assertion failure in -[AFHTTPRequestSerializer requestWithMethod:URLString:parameters:error:], /Users/.../AFNetworking/AFURLRequestSerialization.m:353

I can't figure out what I am doing wrong. What is that error happening?

答:
If you use AFNetworking 3.0 you need add the header file AFImageDownloader.h:

```<code>#import <AFNetworking/AFImageDownloader.h>
</code>```

and use the method downloadImageForURLRequest:

    NSString *stringVideo = [NSString stringWithFormat:@"https:%@", your link];
    AFImageDownloader *downloader = [[AFImageDownloader alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: stringVideo]];
    [downloader downloadImageForURLRequest:request success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {

        NSLog(@"Succes download image");

    }failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {

        NSLog(@"Error download image");
    }];
```

Title: AFNetworking 3.0 can't download image

Body:
I am trying to download an image using AFNetworking 3.0 doing this way:

- (UIImage *) loadImage:(NSString *) link
 {
    __block UIImage *image = [UIImage imageNamed:@"no_user_profile_pic.png"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFImageResponseSerializer serializer];
    [manager GET:[link stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]
      parameters:nil
        progress:nil
         success:^(NSURLSessionTask *task, id responseObject) {
             image = (UIImage *) responseObject;
         } failure:^(NSURLSessionTask *operation, NSError *error) {
             NSLog(@"Load Image error - %@", [error description]);
         }];
    return image;
}

and every time I am getting this error:

*** Assertion failure in -[AFHTTPRequestSerializer requestWithMethod:URLString:parameters:error:], /Users/.../AFNetworking/AFURLRequestSerialization.m:353

I can't figure out what I am doing wrong. What is that error happening?

Body:
If you use AFNetworking 3.0 you need add the header file AFImageDownloader.h:

#import <AFNetworking/AFImageDownloader.h>

and use the method downloadImageForURLRequest:

    NSString *stringVideo = [NSString stringWithFormat:@"https:%@", your link];
    AFImageDownloader *downloader = [[AFImageDownloader alloc] init];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: stringVideo]];
    [downloader downloadImageForURLRequest:request success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) {

        NSLog(@"Succes download image");

    }failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {

        NSLog(@"Error download image");
    }];


问:
strange behaviour when populating a select list in razor
I'm populating a select list using razor and its giving me some strange results.  The items in the list contain spaces, the text created is ok, but the value has been split into sections for each word in the text description.  Here's my razor code

<select name="fromReport[]" id="multiselectReport" class="form-control" size="15" multiple="multiple">
                                                        @foreach (var item in Model.AvailableReports)
                                                        {
                                                            <option value=@item>@item</option>
                                                        }
                                                    </select>```
</div>
</div>
</p>

<p>and the resulting HTML</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="multiselect_toRpt" class="form-control" name="toReport[]" size="15" multiple="multiple">
<option value="All" trades="" activity="" last="" week="">All Trades Activity Last Week</option>
<option value="All" trades="" for="" delivery="" last="" month="">All Trades For Delivery Last Month</option>
<option value="Energy" costs="" report="">Energy Costs Report</option>
</select></code>```

so its created a section in the definition for each word in the text, why is this ?

答:
Wrap the value attribute value in quotes. Single quotes or double quotes will work.

<option value="@item">@item</option>

Body:
I'm populating a select list using razor and its giving me some strange results.  The items in the list contain spaces, the text created is ok, but the value has been split into sections for each word in the text description.  Here's my razor code

<select name="fromReport[]" id="multiselectReport" class="form-control" size="15" multiple="multiple">
                                                        @foreach (var item in Model.AvailableReports)
                                                        {
                                                            <option value=@item>@item</option>
                                                        }
                                                    </select>

and the resulting HTML

<select id="multiselect_toRpt" class="form-control" name="toReport[]" size="15" multiple="multiple">
<option value="All" trades="" activity="" last="" week="">All Trades Activity Last Week</option>
<option value="All" trades="" for="" delivery="" last="" month="">All Trades For Delivery Last Month</option>
<option value="Energy" costs="" report="">Energy Costs Report</option>
</select>

so its created a section in the definition for each word in the text, why is this ?