问:
Training caffe library and Loss does not converge
I use caffe for my recognition and I have an issue that loss data never converge.

My training parameters in the configuration are

```<code>      Conf.base_lr = 0.2;
      Conf.max_iter = 800001;
      Conf.test_iter = 100;
      Conf.test_interval = 1000;
      Conf.momentum = 0.5;
      Conf.random_seed = 2;
      Conf.clip_gradients = 0.1;
      Conf.gamma = 0.8;
      Conf.stepsize = 100000;
      Conf.weights = "";
      //logging
      Conf.display_interval = 100;
      Conf.snapshot_prefix_folder = "../tmp";
      Conf.snapshot_interval = 10000;
      Conf.schematic_path = "../tmp/reinspect.png";
      Conf.graph_prefix = "../tmp/history";
      Conf.log_file = "../tmp/log_brainwash.txt";
      Conf.graph_interval = 500;
      //net
      Conf.init_range = 0.1;
</code>```

Then when I check Backward data

```<code>All net params (data, diff): L1 norm = (208684, 3.43485e+11); L2 norm = (135.231, 3.96399e+08)
</code>```

Diff values of L1 and L2 norms are huge and not normal. What could be wrong with my parameters in configuration and how to tune them?

Some of my log data for forward and backward can be seen in this link.

EDIT:

Previously I have problem of some layers are not included in the Backward propagation. So now I force them and all are included except these with no bottom layers like Input and DummyData. They are shown below.
This development is similar implementation to this Lib (only Python and C++ are different). They include all those layers in Backward propagation, DummyData is NumpyData in Python in their implementation. If necessary, how to include those into Backward propagation.

```<code>layer {
  name: "image"
  type: "Input"
  top: "image"
  input_param { shape: { dim: 1 dim: 3 dim: 480 dim: 640 } }
}
layer {
  name: "box_flags"
  type: "Input"
  top: "box_flags"
  input_param { shape: { dim: 300 dim: 1 dim: 5 dim: 1 } }
}

layer {
  name: "boxes"
  type: "Input"
  top: "boxes"
  input_param { shape: { dim: 300 dim: 4 dim: 5 dim: 1 } }
}

layer {
  name: "lstm_hidden_seed"
  type: "DummyData"
  top: "lstm_hidden_seed"
  dummy_data_param {
    shape { dim: 300 dim: 250 }
    data_filler { type: "constant" value: 0 }
  }
}
layer {
  name: "lstm_mem_seed"
  type: "DummyData"
  top: "lstm_mem_seed"
  dummy_data_param {
    shape { dim: 300 dim: 250 }
    data_filler { type: "constant" value: 0 }
  }
}
</code>```

DummyData layer was NumpyData when it was in Python, when I convert to C++, it is changed to DummyData with initialization data 0.

Do I need to include all those Input and DummyData into Backward propagation?
I still have this abnormal big values at L1 and L2 norm.

```<code>[Backward] All net params (data, diff): L1 norm = (208696, 4.09333e+06); L2 norm = (135.23, 4791.7)
</code>```

答: Your learning  rate is very high, making your optimization process diverge. Try reduce it by factor of at least 50 and re-start the training.</p>

Body:
I use caffe for my recognition and I have an issue that loss data never converge.

My training parameters in the configuration are

      Conf.base_lr = 0.2;
      Conf.max_iter = 800001;
      Conf.test_iter = 100;
      Conf.test_interval = 1000;
      Conf.momentum = 0.5;
      Conf.random_seed = 2;
      Conf.clip_gradients = 0.1;
      Conf.gamma = 0.8;
      Conf.stepsize = 100000;
      Conf.weights = "";
      //logging
      Conf.display_interval = 100;
      Conf.snapshot_prefix_folder = "../tmp";
      Conf.snapshot_interval = 10000;
      Conf.schematic_path = "../tmp/reinspect.png";
      Conf.graph_prefix = "../tmp/history";
      Conf.log_file = "../tmp/log_brainwash.txt";
      Conf.graph_interval = 500;
      //net
      Conf.init_range = 0.1;

Then when I check Backward data

All net params (data, diff): L1 norm = (208684, 3.43485e+11); L2 norm = (135.231, 3.96399e+08)

Diff values of L1 and L2 norms are huge and not normal. What could be wrong with my parameters in configuration and how to tune them?

Some of my log data for forward and backward can be seen in this link.

EDIT:

Previously I have problem of some layers are not included in the Backward propagation. So now I force them and all are included except these with no bottom layers like Input and DummyData. They are shown below.
This development is similar implementation to this Lib (only Python and C++ are different). They include all those layers in Backward propagation, DummyData is NumpyData in Python in their implementation. If necessary, how to include those into Backward propagation.

layer {
  name: "image"
  type: "Input"
  top: "image"
  input_param { shape: { dim: 1 dim: 3 dim: 480 dim: 640 } }
}
layer {
  name: "box_flags"
  type: "Input"
  top: "box_flags"
  input_param { shape: { dim: 300 dim: 1 dim: 5 dim: 1 } }
}

layer {
  name: "boxes"
  type: "Input"
  top: "boxes"
  input_param { shape: { dim: 300 dim: 4 dim: 5 dim: 1 } }
}

layer {
  name: "lstm_hidden_seed"
  type: "DummyData"
  top: "lstm_hidden_seed"
  dummy_data_param {
    shape { dim: 300 dim: 250 }
    data_filler { type: "constant" value: 0 }
  }
}
layer {
  name: "lstm_mem_seed"
  type: "DummyData"
  top: "lstm_mem_seed"
  dummy_data_param {
    shape { dim: 300 dim: 250 }
    data_filler { type: "constant" value: 0 }
  }
}

DummyData layer was NumpyData when it was in Python, when I convert to C++, it is changed to DummyData with initialization data 0.

Do I need to include all those Input and DummyData into Backward propagation?
I still have this abnormal big values at L1 and L2 norm.

[Backward] All net params (data, diff): L1 norm = (208696, 4.09333e+06); L2 norm = (135.23, 4791.7)


来源: stackexchange

问:
Better way to secure REST resources in Spring?
I have a RESTful service that exposes resources like /user/{id}

Now, the user can provide the credentials, get the token and access the resource. However, once authenticated, the user can access the resources for any id.

Meaning, user1 can access the URIs like /user/1 as well as user/2 and so on. I ended up using a Principal in the controller methods and started checking the id of the Principal with the id the user is trying to access.

Further, the user has multiple resources associated with it. Say, user1 owns res1 and res2, user2 owns res3 and res4. These can be accessed via /user/1/res/2. I need a way where I can prevent /user/1/res/3 as res3 is owned by user1 and not user2.

But I believe that this problem is very common and I am not really convinced with my solution.

Is there a better way to deal with this problem?

Thanks

答:
What you want is user roles and permissions + cross user control. To find out user roles and permissions refer this

Also additionally you may want to cross check their user ID to the resource ID. Since you cannot let user1's resource ID 1 to view by user2, you will need to add userID as part of the resource id ex:- /user/user_id_1.
Otherwise we don't have a logical way to separate which resources are applicable to which users.

ContentLicense: CC BY-SA 3.0


问:
jQuery read AJAX stream incrementally?
I have read this question but it doesn't exactly answer my question.
Unfortunately, it looks like things have changed in in the XHR object since I last looked at AJAX, so it is no longer possible to directly access responseText before it is finished being populated.

I have to write a page that uses AJAX (preferably jQuery, but I am open to suggestions) to retrieve CSV data via HTTP from a server I have no control over.  The response data could be quite large; a megabyte of text is not uncommon.

The server is stream-friendly. Is there still any way to get access to a stream of data as it is being returned, directly from JavaScript?

I do have the option of writing some PHP code that lives in the middle and uses some sort of "Comet" tech (long-polling, EventSource, etc), but I would prefer to avoid that if possible.

In case it is relevant, assume for this question that users have the latest version of Firefox/Chrome/Opera and old browser compatibility is not an issue.

答:
Here is a straightforward way to achieve this using JQuery (as requested by the OP):

First, extend the ajax object to support onreadystatechange by running the below code from https://gist.github.com/chrishow/3023092 (appended at the bottom of this response). Then just call ajax using an onreadystatechange function that will check xhr.responseText for new text.

If you wanted to get even fancier, you could clear the responseText data each time you read it, such as described here).

For example, see https://jsfiddle.net/g1jmwcmw/1/, which will download the response from https://code.jquery.com/jquery-1.5.js and output it in chunks inside your console window, using the code below (which you can just copy into an html page and then open in your browser):

```<code><!-- jquery >= 1.5. maybe earlier too but not sure -->
<script src=https://code.jquery.com/jquery-1.5.min.js></script>
<script>
/* One-time setup (run once before other code)
 *   adds onreadystatechange to $.ajax options
 *   from https://gist.github.com/chrishow/3023092)
 *   success etc will still fire if provided
 */
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if ( options.onreadystatechange ) {
        var xhrFactory = options.xhr;
        options.xhr = function() {
            var xhr = xhrFactory.apply( this, arguments );
            function handler() {
                options.onreadystatechange( xhr, jqXHR );
            }
            if ( xhr.addEventListener ) {
                xhr.addEventListener( "readystatechange", handler, false );
            } else {
                setTimeout( function() {
                    var internal = xhr.onreadystatechange;
                    if ( internal ) {
                        xhr.onreadystatechange = function() {
                            handler();
                            internal.apply( this, arguments );
                        };
                    }
                }, 0 );
            }
            return xhr;
        };
    }
});

// ----- myReadyStateChange(): this will do my incremental processing -----
var last_start = 0; // using global var for over-simplified example
function myReadyStateChange(xhr /*, jqxhr */) {
    if(xhr.readyState >= 3 && xhr.responseText.length > last_start) {
        var chunk = xhr.responseText.slice(last_start);
        alert('Got chunk: ' + chunk);
        console.log('Got chunk: ', chunk);
        last_start += chunk.length;
    }
}

// ----- call my url and process response incrementally -----
last_start = 0;
$.ajax({
  url: "https://code.jquery.com/jquery-1.5.js", // whatever your target url is goes here
  onreadystatechange: myReadyStateChange
});

</script>
</code>```

Title: jQuery read AJAX stream incrementally?

Body:
Here is a straightforward way to achieve this using JQuery (as requested by the OP):

First, extend the ajax object to support onreadystatechange by running the below code from https://gist.github.com/chrishow/3023092 (appended at the bottom of this response). Then just call ajax using an onreadystatechange function that will check xhr.responseText for new text.

If you wanted to get even fancier, you could clear the responseText data each time you read it, such as described here).

For example, see https://jsfiddle.net/g1jmwcmw/1/, which will download the response from https://code.jquery.com/jquery-1.5.js and output it in chunks inside your console window, using the code below (which you can just copy into an html page and then open in your browser):

<!-- jquery >= 1.5. maybe earlier too but not sure -->
<script src=https://code.jquery.com/jquery-1.5.min.js></script>
<script>
/* One-time setup (run once before other code)
 *   adds onreadystatechange to $.ajax options
 *   from https://gist.github.com/chrishow/3023092)
 *   success etc will still fire if provided
 */
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if ( options.onreadystatechange ) {
        var xhrFactory = options.xhr;
        options.xhr = function() {
            var xhr = xhrFactory.apply( this, arguments );
            function handler() {
                options.onreadystatechange( xhr, jqXHR );
            }
            if ( xhr.addEventListener ) {
                xhr.addEventListener( "readystatechange", handler, false );
            } else {
                setTimeout( function() {
                    var internal = xhr.onreadystatechange;
                    if ( internal ) {
                        xhr.onreadystatechange = function() {
                            handler();
                            internal.apply( this, arguments );
                        };
                    }
                }, 0 );
            }
            return xhr;
        };
    }
});

// ----- myReadyStateChange(): this will do my incremental processing -----
var last_start = 0; // using global var for over-simplified example
function myReadyStateChange(xhr /*, jqxhr */) {
    if(xhr.readyState >= 3 && xhr.responseText.length > last_start) {
        var chunk = xhr.responseText.slice(last_start);
        alert('Got chunk: ' + chunk);
        console.log('Got chunk: ', chunk);
        last_start += chunk.length;
    }
}

// ----- call my url and process response incrementally -----
last_start = 0;
$.ajax({
  url: "https://code.jquery.com/jquery-1.5.js", // whatever your target url is goes here
  onreadystatechange: myReadyStateChange
});

</script>


问:
Detect the end of scrollToRow function
How can i detect the end of scrollToRow function in my tableview? i have tried to implement scrollViewDidEndScrollingAnimation function, however it doesn't get called when end of scrollToRow.</p>

答:
```<code> func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let  height = scrollView.frame.size.height
    let contentYoffset = scrollView.contentOffset.y
    let distanceFromBottom = scrollView.contentSize.height - contentYoffset
    if distanceFromBottom < height {
        print(" you reached end of the table")
    }
}
</code>```

Title: Detect the end of scrollToRow function


问:
Git setup and pushing local repo to a virtualbox vm remote repo
New to version control completely, and trying my hand at using git for web development.

My setup is a Windows host with an Ubuntu guest (using Virtualbox). SSH works between them.

I'm simply trying to get my head around all the "basic" commands by trying to "convert" one of my existing website's root directory to a "git" repo, then attempting to mirror that repo to the remote repo which I want on the Ubuntu instance's /var/www/html folder.

It appears I have the "repo" part set up on both sides, but I keep failing at pushing the local directory and files to the VM.

I'm getting a little lost with all the tutorials and blogs. Some mention command line stuff, some recommend GUI applications... bit overwhelming. I'm using "Git for Windows" on host and standard git on guest.

I have this on Guest:

```<code>web@web-VirtualBox:/var/www/html/repos/zen.git$ sudo git init --bare
Initialized empty Git repository in /var/www/html/repos/zen.git/
web@web-VirtualBox:/var/www/html/repos/zen.git$ ls
branches  config  description  HEAD  hooks  info  objects  refs
</code>```

How do I now push all the content on my local website's root directory to the guest using the git commands?

EDIT: wanting to learn the command line stuff first before using any GUI applications. Right now I have "GUI Bash" and "GUI Cmd" available on the Windows host.

答:
First, make sure to have a simplified PATH on your Windows host side.

Second, check that you can open an ssh session on your remote Linux server from your CMD shell, with the VirtualBox IP

```<code>ssh web@<VBox ip address>
</code>```

That means you have created first an ssh public/private key (see "Creating SSH keys", I recommend one without passphrase), and copied the public key in ~web/.ssh/authorized_keys

Finally, the git clone URL would be web@web-VirtualBox:/var/www/html/repos/zen.git

But I don't recommend putting the .git directly in /var/www/html, as that folder is generally server by an http server. (Meaning the .git folder would be served as well)

Body:
New to version control completely, and trying my hand at using git for web development.

My setup is a Windows host with an Ubuntu guest (using Virtualbox). SSH works between them.

I'm simply trying to get my head around all the "basic" commands by trying to "convert" one of my existing website's root directory to a "git" repo, then attempting to mirror that repo to the remote repo which I want on the Ubuntu instance's /var/www/html folder.

It appears I have the "repo" part set up on both sides, but I keep failing at pushing the local directory and files to the VM.

I'm getting a little lost with all the tutorials and blogs. Some mention command line stuff, some recommend GUI applications... bit overwhelming. I'm using "Git for Windows" on host and standard git on guest.

I have this on Guest:

web@web-VirtualBox:/var/www/html/repos/zen.git$ sudo git init --bare
Initialized empty Git repository in /var/www/html/repos/zen.git/
web@web-VirtualBox:/var/www/html/repos/zen.git$ ls
branches  config  description  HEAD  hooks  info  objects  refs

How do I now push all the content on my local website's root directory to the guest using the git commands?

EDIT: wanting to learn the command line stuff first before using any GUI applications. Right now I have "GUI Bash" and "GUI Cmd" available on the Windows host.

Body:
First, make sure to have a simplified PATH on your Windows host side.

Second, check that you can open an ssh session on your remote Linux server from your CMD shell, with the VirtualBox IP

ssh web@<VBox ip address>

That means you have created first an ssh public/private key (see "Creating SSH keys", I recommend one without passphrase), and copied the public key in ~web/.ssh/authorized_keys

Finally, the git clone URL would be web@web-VirtualBox:/var/www/html/repos/zen.git

But I don't recommend putting the .git directly in /var/www/html, as that folder is generally server by an http server. (Meaning the .git folder would be served as well)


问:
GZip or Deflate for HTTP compression
Which compression method is better? I've heard lots of back and forth about GZip being more widely used, but Deflate being faster (in some instances). Is there an accepted standard on which one to use and why?</p>

答:
Answers:

http://www.stardeveloper.com/articles/display.html?article=2008111201&page=1

http://blog.usweb.com/archives/mod_deflate-vs-mod_gzip-comparing-the-two/

Why use deflate instead of gzip for text files served by Apache?

Basically, deflate is faster, so if it's avaible to you, use it.

ContentLicense: CC BY-SA 2.5

Title: GZip or Deflate for HTTP compression


问:
How to execute FreeSwitch command using java code
I am new to freeswitch, I have tried originate command in freeswitch from fs_cli console and it was working properly. now my requirement is to execute the same from a java application. I have tried following code.</p>

```<code>package org.freeswitch.esl.client.outbound.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Call {
Call() throws IOException {
    Process pr = Runtime.getRuntime().exec("fs_cli -x reloadxml");
    BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String str = null;
    while ((str = br.readLine()) != null) {
        System.out.println(str);
    }
    System.out.print("success");
}

public static void main(String[] args) throws IOException {
    Call call;
    call = new Call();
}
}
</code>```

答:
Above problem get resolved :
I have created a .sh script with the bellow code snippet:

#!/bin/bash
fs_cli -x "reloadxml"
echo "executed at : $(date)" >> /var/tmp/testlog.txt
```

and execute this .sh file using java code. That's it.
I have created a testlog.txt file to check weather the fs_cli -x "reloadxml" command is executed or not.

Body:
I am new to freeswitch, I have tried originate command in freeswitch from fs_cli console and it was working properly. now my requirement is to execute the same from a java application. I have tried following code.

package org.freeswitch.esl.client.outbound.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Call {
Call() throws IOException {
    Process pr = Runtime.getRuntime().exec("fs_cli -x reloadxml");
    BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String str = null;
    while ((str = br.readLine()) != null) {
        System.out.println(str);
    }
    System.out.print("success");
}

public static void main(String[] args) throws IOException {
    Call call;
    call = new Call();
}
}

Body:
Above problem get resolved :
I have created a .sh script with the bellow code snippet:

#!/bin/bash
fs_cli -x "reloadxml"
echo "executed at : $(date)" >> /var/tmp/testlog.txt

and execute this .sh file using java code. That's it.
I have created a testlog.txt file to check weather the fs_cli -x "reloadxml" command is executed or not.


问:
declare variable inside or outside a loop, does it make big difference?
for example

```<code>int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}
</code>```

and

```<code>while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}
</code>```

Does it make big difference in terms of performance?

答: It makes a difference...When you declare a variable outside the loop you can get its value after the loop ends but if you declare it inside the loop you can't use it after the loop because it is not defined</p>

Body:
for example

int i, a, c, d; // these vars will only be used in while
while(bigNumber--) {
    i = doSomething();
    // **

}

and

while(bigNumber--) {
   int i, a, b, c; // i'd like to put it here for readability
   i = doSomething();
   // **
}

Does it make big difference in terms of performance?


问:
Android - findViewById returns null while trying to set value from Serializable
I cannot figure out how to pass this User class Object. I am simply trying to take input from an editText stored in the first activity and then send it to a textView in another activity. I've done this before, but for some reason, I am wrong here, and I keep getting this error "                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{example.com.avatar/example.com.avatar.DisplayActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference". Can anyone help me out here?</p>

```<code>//1st Activity
findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
                User user = new User();
                textViewNameLocal = findViewById(R.id.textViewName);
                intent.putExtra("USER", user);
                startActivity(intent);
            }
        });
    }

//2nd Activity
public class DisplayActivity extends AppCompatActivity {
    TextView textViewName, textViewEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        textViewName = findViewById(R.id.textViewName); //this was the error, it needs to be below the "setContentView(R.layout.activity_display)".
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Intent intent = getIntent();
        User user = (User) intent.getSerializableExtra("USER");
        textViewName.setText(user.getName().toString);

    }
}
</code>```

答:
Implement your class with Serializable. Let's suppose that this is your entity class:

```<code>import java.io.Serializable;

@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class User implements Serializable {

    public User(double id, String name) {
        this.id = id;
        this.name = name;
    }

    public double getId() {
        return id;
    }

    public void setId(double id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private double id;
    private String name;
}
</code>```

We are sending the object called user from X activity to Y activity. Somewhere in X activity;

```<code>User obj = new User(4,"Yuvi");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", obj);
startActivity(i);
</code>```

In Y activity we are getting the object.

```<code>Intent i = getIntent();
User obj = (User)i.getSerializableExtra("sampleObject");
</code>```

That's it.

Body:
I cannot figure out how to pass this User class Object. I am simply trying to take input from an editText stored in the first activity and then send it to a textView in another activity. I've done this before, but for some reason, I am wrong here, and I keep getting this error "                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{example.com.avatar/example.com.avatar.DisplayActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference". Can anyone help me out here?

//1st Activity
findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
                User user = new User();
                textViewNameLocal = findViewById(R.id.textViewName);
                intent.putExtra("USER", user);
                startActivity(intent);
            }
        });
    }

//2nd Activity
public class DisplayActivity extends AppCompatActivity {
    TextView textViewName, textViewEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        textViewName = findViewById(R.id.textViewName); //this was the error, it needs to be below the "setContentView(R.layout.activity_display)".
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Intent intent = getIntent();
        User user = (User) intent.getSerializableExtra("USER");
        textViewName.setText(user.getName().toString);

    }
}

Body:
Implement your class with Serializable. Let's suppose that this is your entity class:

import java.io.Serializable;

@SuppressWarnings("serial") //With this annotation we are going to hide compiler warnings
public class User implements Serializable {

    public User(double id, String name) {
        this.id = id;
        this.name = name;
    }

    public double getId() {
        return id;
    }

    public void setId(double id) {
        this.id = id;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private double id;
    private String name;
}

We are sending the object called user from X activity to Y activity. Somewhere in X activity;

User obj = new User(4,"Yuvi");
Intent i = new Intent(this, Y.class);
i.putExtra("sampleObject", obj);
startActivity(i);

In Y activity we are getting the object.

Intent i = getIntent();
User obj = (User)i.getSerializableExtra("sampleObject");

That's it.


问:
Apache .htaccess: CORS * on localhost only
I have 2 projects, one is a PHP web API with the following .htaccess:

```<code>Header add Access-Control-Allow-Origin "http://app.domain.com"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header always set Access-Control-Allow-Credentials true

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1
</code>```

Note the Access-Control-Allow-Origin header which contains the base URL of the second project (an angularjs application).

This does work, however I'd like to change the origin to * if both projects are being run on localhost, so that every developer within this project can simply test changes without deploying first.

How can I achieve this?

We do not want to use a separate .htaccess for local tests. We prefer to use a single one.

答:
Are you searching for this ?

replace "Error Document" with "Acces control"

https://www.html-seminar.de/forum/thread/4027-if-abfrage-in-htaccess-unterscheiden-zwischen-localhost-xampp-und-webserver/

# Localhost / XAMPP
<IfModule mod_win32.c>
    ErrorDocument 403 http://localhost/phip/www/404.html
    ErrorDocument 404 http://localhost/phip/www/404.html
</IfModule>

# Webserver
<IfModule !mod_win32.c>
    ErrorDocument 403 http://***/404.html
    ErrorDocument 404 http://***/404.html
</IfModule>```

Body:
I have 2 projects, one is a PHP web API with the following .htaccess:

Header add Access-Control-Allow-Origin "http://app.domain.com"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
Header always set Access-Control-Allow-Credentials true

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(.*)$ index.php/$1

Note the Access-Control-Allow-Origin header which contains the base URL of the second project (an angularjs application).

This does work, however I'd like to change the origin to * if both projects are being run on localhost, so that every developer within this project can simply test changes without deploying first.

How can I achieve this?

We do not want to use a separate .htaccess for local tests. We prefer to use a single one.


问:
How to get only first 50 files from all subdirectories of a directory in Python?
I am trying to get first 50 .jpg files from different subdirectories of a particular directory. Till now, I have only succedded in getting the path name of all using the following list of commands:

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

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".jpg")]:
        print os.path.join(dirpath, filename)
</code>```

Can someone please tell as to how to extract only first 50 files from the subdirectories?

答:
the best way would be to avoid to

create a list comprehension

slice it using naive slicing [:50]

that creates 2 useless lists and is not that performant.

I would suggest to generate the names using a generator comprehension rather than list comprehension, and use islice on it. Like that no temporary list is created. Only works with 1 value at a time:

```<code>import itertools,os

for dirpath, dirnames, filenames in os.walk("."):
    for filename in itertools.islice((f for f in filenames if f.endswith(".jpg")),50):
        print(os.path.join(dirpath, filename))
</code>```

also be careful: some weird filesystems won't necessarily sort the files by name, maybe you'll need to first sort the list, then slice.

```<code>for filename in itertools.islice(sorted([f for f in filenames if f.endswith(".jpg")]),50):
</code>```

Body:
I am trying to get first 50 .jpg files from different subdirectories of a particular directory. Till now, I have only succedded in getting the path name of all using the following list of commands:

import os
import os.path

for dirpath, dirnames, filenames in os.walk("."):
    for filename in [f for f in filenames if f.endswith(".jpg")]:
        print os.path.join(dirpath, filename)

Can someone please tell as to how to extract only first 50 files from the subdirectories?

Body:
the best way would be to avoid to

create a list comprehension

slice it using naive slicing [:50]

that creates 2 useless lists and is not that performant.

I would suggest to generate the names using a generator comprehension rather than list comprehension, and use islice on it. Like that no temporary list is created. Only works with 1 value at a time:

import itertools,os

for dirpath, dirnames, filenames in os.walk("."):
    for filename in itertools.islice((f for f in filenames if f.endswith(".jpg")),50):
        print(os.path.join(dirpath, filename))

also be careful: some weird filesystems won't necessarily sort the files by name, maybe you'll need to first sort the list, then slice.

for filename in itertools.islice(sorted([f for f in filenames if f.endswith(".jpg")]),50):


问:
How to make the a code repeat itself while changing the month date in C?
I have done this code and I have made a loop where my code will restart from scratch however I want the program to restart while changing the month date and also asking the user how many months they would like so the program will run a certain amount of times, as I have added the month 1 being the first month.</p>

```<code>#include<stdio.h>
#include<stdlib.h>
float twag(float amount,float rate)
{
    float si;
    si = (amount * rate) / 100;
    return si;
}

float twag2(float amount,float rate)
{
    float er;
    er = twag(amount, rate) + amount;
    return er;
}

int main()
{
    char answer;
    do {
        float amount;
        float rate;
        float si;
        float er;

        printf("Month1\n");

        printf("\nEnter intial deposit : ");
        scanf("%f", &amount);

        printf("\nEnter Rate of Interest : ");
        scanf("%f", &rate);

        printf("\nSimple Interest : %.2f \n", twag(amount,rate));

        printf("\nEnd Payment: %.2f \n",twag2(amount,rate));

        if (amount <= 100)
            printf("interest rate should be 10%%\n");

        else if (amount <= 200)
            printf("interest rate should be 50%%\n");

        else if (amount <= 500)
            printf("interest rate should be 80%%\n");

        else if (amount >= 500)
            printf("interest rate should be 90%%\n");
        system("PAUSE");

        printf("\nPress Y to continue to the second month or Press any Key To
        Exit");
        scanf(" %c", &answer); //
    }
     while (answer == 'y' || answer == 'Y');

    return 0;
}
</code>```

答:
Assuming you're applying monthly interest, you at least need to keep record of the current month and year, starting at today's date, so the way to do that is by using localtime

```<code>void get_date(int *month, int *day, int *year)
{
    struct tm *current;
    time_t timenow;
    time(&timenow);
    current = localtime(&timenow);
    *month = current->tm_mon+1;
    *day = current->tm_mday;
    *year = current->tm_year+1900;
}
</code>```

I suggest you read here on why system("PAUSE") is bad, besides that, You defined your loop variables inside the loop, which means they're going to reset each time you loop, and your interest should be constant during the loop, so your code should look like this

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

float twag(float amount,float rate);
float twag2(float amount,float rate);
void get_date(int *month, int *day, int *year);

int main()
{
    char answer;
    float amount, rate, si, er;
    int day, month, year;

    printf("\nEnter intial deposit : ");
    scanf("%f", &amount);

    printf("\nEnter Rate of Interest : ");
    scanf("%f", &rate);

    get_date(&month, &day, &year);

    do
    {
        // increment date by 1 month
        if (++month > 12) month=1, year++;

        printf("\nDate %d/%d/%d \n", day,month,year);
        printf("\nSimple Interest : %.2f \n", twag(amount,rate));
        printf("\nEnd Payment: %.2f \n",twag2(amount,rate));
        amount = twag2(amount,rate);

        printf("\nPress Y to continue to the next month or Press any Key To Exit");
        scanf("%c", &answer);
    }
    while (answer == 'y' || answer == 'Y');

    return 0;
}
</code>```

Body:
I have done this code and I have made a loop where my code will restart from scratch however I want the program to restart while changing the month date and also asking the user how many months they would like so the program will run a certain amount of times, as I have added the month 1 being the first month.

#include<stdio.h>
#include<stdlib.h>
float twag(float amount,float rate)
{
    float si;
    si = (amount * rate) / 100;
    return si;
}

float twag2(float amount,float rate)
{
    float er;
    er = twag(amount, rate) + amount;
    return er;
}

int main()
{
    char answer;
    do {
        float amount;
        float rate;
        float si;
        float er;

        printf("Month1\n");

        printf("\nEnter intial deposit : ");
        scanf("%f", &amount);

        printf("\nEnter Rate of Interest : ");
        scanf("%f", &rate);

        printf("\nSimple Interest : %.2f \n", twag(amount,rate));

        printf("\nEnd Payment: %.2f \n",twag2(amount,rate));

        if (amount <= 100)
            printf("interest rate should be 10%%\n");

        else if (amount <= 200)
            printf("interest rate should be 50%%\n");

        else if (amount <= 500)
            printf("interest rate should be 80%%\n");

        else if (amount >= 500)
            printf("interest rate should be 90%%\n");
        system("PAUSE");

        printf("\nPress Y to continue to the second month or Press any Key To
        Exit");
        scanf(" %c", &answer); //
    }
     while (answer == 'y' || answer == 'Y');

    return 0;
}

Body:
Assuming you're applying monthly interest, you at least need to keep record of the current month and year, starting at today's date, so the way to do that is by using localtime

void get_date(int *month, int *day, int *year)
{
    struct tm *current;
    time_t timenow;
    time(&timenow);
    current = localtime(&timenow);
    *month = current->tm_mon+1;
    *day = current->tm_mday;
    *year = current->tm_year+1900;
}

I suggest you read here on why system("PAUSE") is bad, besides that, You defined your loop variables inside the loop, which means they're going to reset each time you loop, and your interest should be constant during the loop, so your code should look like this

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

float twag(float amount,float rate);
float twag2(float amount,float rate);
void get_date(int *month, int *day, int *year);

int main()
{
    char answer;
    float amount, rate, si, er;
    int day, month, year;

    printf("\nEnter intial deposit : ");
    scanf("%f", &amount);

    printf("\nEnter Rate of Interest : ");
    scanf("%f", &rate);

    get_date(&month, &day, &year);

    do
    {
        // increment date by 1 month
        if (++month > 12) month=1, year++;

        printf("\nDate %d/%d/%d \n", day,month,year);
        printf("\nSimple Interest : %.2f \n", twag(amount,rate));
        printf("\nEnd Payment: %.2f \n",twag2(amount,rate));
        amount = twag2(amount,rate);

        printf("\nPress Y to continue to the next month or Press any Key To Exit");
        scanf("%c", &answer);
    }
    while (answer == 'y' || answer == 'Y');

    return 0;
}


问:
Set Fragment on Tab with multi line title
I'm working with two fragments that I'm setting on the Tabs.

I have two issues:

I want to set the title of the fragment in multi line instead of "..."

here's the code to add fragment and set its title

```<code>ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Current\nSubscription");
</code>```

I want to remove the extra space from around the icon and text on the tab to make it more compact and save some space.

答:
Try this set Your TabLayout title using below code

```<code>TextView tabOne = new TextView(this);
tabOne.setText("Current"+ System.getProperty("line.separator") +"Subscription");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working with two fragments that I'm setting on the Tabs.

I have two issues:

I want to set the title of the fragment in multi line instead of "..."

here's the code to add fragment and set its title

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Current\nSubscription");

I want to remove the extra space from around the icon and text on the tab to make it more compact and save some space.

Body:
Try this set Your TabLayout title using below code

TextView tabOne = new TextView(this);
tabOne.setText("Current"+ System.getProperty("line.separator") +"Subscription");
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
tabLayout.getTabAt(0).setCustomView(tabOne);


问:
c# - StreamWriter Issue when adding Date to the filename
I'm having a small issue with the System.IO.StreamWriter.

```<code>StreamWriter Write =
   new StreamWriter(@"../Debug/Payments/_" + dp.Value.ToString() + ".txt");
</code>```

When I run the application, it returns:

An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
  Additional information: The given path's format is not supported.

答:
Try this:

```<code>string filename= DateTime.Now.ToString("yyyy_MM_dd");
string strpath = Server.MapPath("~/Debug/Payments/_"+ filename + ".txt");
StreamWriter Write = new StreamWriter(strpath);
</code>```

Your problem is with the format.

Body:
I'm having a small issue with the System.IO.StreamWriter.

StreamWriter Write =
   new StreamWriter(@"../Debug/Payments/_" + dp.Value.ToString() + ".txt");

When I run the application, it returns:

An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
  Additional information: The given path's format is not supported.

Body:
Try this:

string filename= DateTime.Now.ToString("yyyy_MM_dd");
string strpath = Server.MapPath("~/Debug/Payments/_"+ filename + ".txt");
StreamWriter Write = new StreamWriter(strpath);

Your problem is with the format.


答:
Since you say dp is a datepicker, the ToString() is almost certainly going to be inserting invalid characters like : into the file name, e.g.

```<code>Payments/_2017/11/13 1:14:13 PM.txt
</code>```

Also, as per the comments, you'll need to change the slash direction.

You'll need to use a safer date format, like so:

```<code>$@"..\Debug\Payments\_{dp.Value:yyyy-MM-dd}.txt"
</code>```

Title: c# - StreamWriter Issue when adding Date to the filename

Body:
Since you say dp is a datepicker, the ToString() is almost certainly going to be inserting invalid characters like : into the file name, e.g.

Payments/_2017/11/13 1:14:13 PM.txt

Also, as per the comments, you'll need to change the slash direction.

You'll need to use a safer date format, like so:

$@"..\Debug\Payments\_{dp.Value:yyyy-MM-dd}.txt"


问:
How to Upload Image & Text Together in Jmeter?
I have successfully uploaded images and text separately or one by one, but I have trouble to experiment upload images and text simultaneously, is there a solution ?? </p>

答:
If you are uncertain regarding how to mimic this or that request you can just record it using JMeter's HTTP(S) Test Script Recorder. JMeter should be smart enough to capture the request and populate the relevant HTTP Request sampler configuration.

Just keep in mind one hint: put the file(s) you will be uploading using browser in JMeter's "bin" folder, this way JMeter will be able to intercept the requests. See Recording File Uploads with JMeter article for more details.


问:
how to create two processes from a single Parent
I know I'm going to need to use fork(), but this just creates a single child process. Do i simply call fork again from within the child process? Also, I need them to communicate through a signal or pipe, which is easier to implement and what do i need to know for doing that (functions, etc..)</p>

答:
```<code>#include <stdio.h>
#include <unistd.h>

void main(){
  int pi_d ;
  int pid ;
  pi_d = fork();
  if(pi_d == 0){
    printf("Child Process B:\npid :%d\nppid:%d\n",getpid(),getppid());
  }
  if(pi_d > 0){
    pid = fork();
    if(pid > 0){
      printf("\nParent Process:\npid:%d\nppid :%d\n",getpid(),getppid());
    }
    else if(pid == 0){
      printf("Child Process A:\npid :%d\nppid:%d\n",getpid(),getppid());
    }
  }
}
</code>```

output :

```<code>Parent Process:
pid:3648
ppid :2379
Child Process B:
pid :3649
ppid:3648
Child Process A:
pid :3650
ppid:3648
</code>```

Body:
#include <stdio.h>
#include <unistd.h>

void main(){
  int pi_d ;
  int pid ;
  pi_d = fork();
  if(pi_d == 0){
    printf("Child Process B:\npid :%d\nppid:%d\n",getpid(),getppid());
  }
  if(pi_d > 0){
    pid = fork();
    if(pid > 0){
      printf("\nParent Process:\npid:%d\nppid :%d\n",getpid(),getppid());
    }
    else if(pid == 0){
      printf("Child Process A:\npid :%d\nppid:%d\n",getpid(),getppid());
    }
  }
}

output :

Parent Process:
pid:3648
ppid :2379
Child Process B:
pid :3649
ppid:3648
Child Process A:
pid :3650
ppid:3648


问:
Azure hybrid connection not working with SQL Server Named Instance
I have tried to create a hybrid connection for my on premises SQL Server running on Windows Server 2012 with a named instance. I did provided my server address as the endpoint along with the 1433 port. I have also configured the SQL Server to static ports and also allowed outbound connections to these ports (9350 – 9354, 5671, 80, 443) as per documentation. However, when I try to access the database from my azure web application I get the "A connection was successfully established with the server, but then an error occurred during the pre-login handshake." (Full stack trace mentioned in comments).

However, when I try to create the hybrid connection to another on-premises SQL Server with default instance, with the same settings as above, it works fine.

Could not find a strong enough explanation for this behavior so far.

答:
After quite some research and experimentation finally I was able to work out the solution for the problem. Actually one need to enable TLS 1.0 (from windows registry) for both your client and server.

Following are the correct value for registry to have your named instance work out:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Client] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS
1.0\Server] "DisabledByDefault"=dword:00000000 "Enabled"=dword:00000001

Also note that Hybrid connection communicates via ports so be careful to see that if you have multiple instance of your SQL Server make sure each is listening at a different static TCP port.


问:
Jmeter 3.2 not counting all attributes
I have a 10MB page that we have to download in json format it has various headings with data under 2000 headings to be exact.

When I select a the page to be under 1996 headings in the request I retrive the exact count as soon as I select 2000 as the limit for the page it still will only retrive or count 1996 headings.

I know the script is working as it works with lower page sizes, Firefox and curl return the correct page of 2000.

Is there a limit on the size of Jmeter pages that needs changing?

答:
Try upgrading to JMeter 3.3, as per the changelog:

JMeter will not truncate anymore by default responses exceeding 10 MB. If you want to enable this truncation, see property httpsampler.max_bytes_to_store_per_request

If you are not in position to perform the upgrade - add the next line to user.properties file:

```<code>httpsampler.max_bytes_to_store_per_request=0
</code>```

and after JMeter restart you should be able to see/process the full response

Title: Jmeter 3.2 not counting all attributes

Body:
Try upgrading to JMeter 3.3, as per the changelog:

JMeter will not truncate anymore by default responses exceeding 10 MB. If you want to enable this truncation, see property httpsampler.max_bytes_to_store_per_request

If you are not in position to perform the upgrade - add the next line to user.properties file:

httpsampler.max_bytes_to_store_per_request=0

and after JMeter restart you should be able to see/process the full response


答:
Q. Does it make big difference in terms of performance?

A. There is no performance difference at all.  The only difference is whether the scope of the variable is visible outside the loop.

Title: declare variable inside or outside a loop, does it make big difference?


问:
In meteor if I use template name instead of body then its not working
I am in a basic level and having a problem and that is , In meteor if I use template name instead of body in Javascript file then its not working..

here is my html code :

```<code>    <head>
  <title>simple</title>
</head>

<body>
  <ul>

    {{#each player}}

      <li> {{text}}</li>

    {{/each}}

  </ul>
</body>

<template name="shahin">

  {{player}}

</template>
</code>```

javascript code:

```<code>Template.shahin.helpers({
      player: [
         { text: "This is paragraph 1..." },
         { text: "This is paragraph 2..." },
         { text: "This is paragraph 3..." },
         { text: "This is paragraph 4..." },
         { text: "This is paragraph 5..." }
      ]
   });
</code>```

Now if i run this code then it does not show anything. But i change to my Tamplate name with this

```<code>Template.body.helpers
</code>```

then the code is working. Can somebody please explain why is this like so? let me know why this is not working :

```<code>Template.shahin.helpers
</code>```

答:
It doesn't work because you are not calling the template anywhere in your body.

Try this:

```<code>     <head>
  <title>simple</title>
</head>

<body>
  {{> shahin}} <!-- this is where the contents of template="shahin" will render. If you don't call this, "shahin" will never get displayed -->
</body>

<template name="shahin">

  <ul>

    {{#each player}}

      <li> {{text}}</li>

    {{/each}}

  </ul>

</template>
</code>```

Body:
I am in a basic level and having a problem and that is , In meteor if I use template name instead of body in Javascript file then its not working..

here is my html code :

  <title>simple</title>

    {{#each player}}

 {{text}}

    {{/each}}

<template name="shahin">

  {{player}}

</template>

javascript code:

Template.shahin.helpers({
      player: [
         { text: "This is paragraph 1..." },
         { text: "This is paragraph 2..." },
         { text: "This is paragraph 3..." },
         { text: "This is paragraph 4..." },
         { text: "This is paragraph 5..." }
      ]
   });

Now if i run this code then it does not show anything. But i change to my Tamplate name with this

Template.body.helpers

then the code is working. Can somebody please explain why is this like so? let me know why this is not working :

Template.shahin.helpers

Body:
It doesn't work because you are not calling the template anywhere in your body.

Try this:

     <head>
  <title>simple</title>
</head>

<body>
  {{> shahin}} <!-- this is where the contents of template="shahin" will render. If you don't call this, "shahin" will never get displayed -->
</body>

<template name="shahin">

  <ul>

    {{#each player}}

      <li> {{text}}</li>

    {{/each}}

  </ul>

</template>


问:
Android: Application active
When the application is started there will be an icon in the status bar that shows; of the application is active.

And when the application have paused the icon remains on.
 When the application is closed the Icon should disappear.

I don't have any idea how I should do this, can anybody help me..some snippets or tutorials are welcome!

Many Many Many Thanks!

答:
I think you want to look at the Status Bar Notifications article, then hide/show your application appropriately on onCreate/onPause/onResume/onDestroy (I'm not sure of what your rules are)

More here:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

Title: Android: Application active


问:
ionic3--how can I show tabs in sub page when I set app config 'tabsHideOnSubPages=true'
In my app.module.ts:

```<code>IonicModule.forRoot(MyApp, {
  backButtonIcon: 'ios-arrow-back' ,
  backButtonText: '',
  pageTransition: 'md-transition',
  activator: 'ripple',
  mode: 'md',
  tabsHideOnSubPages: true
})
</code>```

then, my all sub page will show without tabs,but now, I need show tabs in a special sub page.

I try to set config before I push the sub page like this:

```<code>import { NavController, Config } from 'ionic-angular';

constructor(
  public navCtrl: NavController,
  public config: Config
) {
  ......
}

ionViewDidEnter(){
  this.config.set('tabsHideOnSubPages', false)
  this.navCtrl.push(LoginPage)
}
</code>```

but it not work,how can I do?

答:
```<code>import { NavController, App, Config } from 'ionic-angular';

constructor(public app:App,public navCtrl: NavController,
  public config: Config) {}

ionViewDidEnter(){
  this.config.set('tabsHideOnSubPages', false)
  let nav = this.app.getRootNav();
  nav.setRoot(LoginPage);
}
</code>```

You can try this code.

Body:
In my app.module.ts:

IonicModule.forRoot(MyApp, {
  backButtonIcon: 'ios-arrow-back' ,
  backButtonText: '',
  pageTransition: 'md-transition',
  activator: 'ripple',
  mode: 'md',
  tabsHideOnSubPages: true
})

then, my all sub page will show without tabs,but now, I need show tabs in a special sub page.

I try to set config before I push the sub page like this:

import { NavController, Config } from 'ionic-angular';

constructor(
  public navCtrl: NavController,
  public config: Config
) {
  ......
}

ionViewDidEnter(){
  this.config.set('tabsHideOnSubPages', false)
  this.navCtrl.push(LoginPage)
}

but it not work,how can I do?

Body:
import { NavController, App, Config } from 'ionic-angular';

constructor(public app:App,public navCtrl: NavController,
  public config: Config) {}

ionViewDidEnter(){
  this.config.set('tabsHideOnSubPages', false)
  let nav = this.app.getRootNav();
  nav.setRoot(LoginPage);
}

You can try this code.


问:
How do I create an IAM policy to control access to Amazon EC2 resources based on the subnet name tag?
I need to restrict a specific user role from performing any EC2 instance actions in public subnets across any VPC. Is there a way to achieve this by leveraging subnet tags? I know how to use EC2 Resource Tags to control access to EC2 resources like in the code snippet below but in my case I need to base it off vpc or subnet tags. Is there something like a vpc:ResourceTag condition I could leverage?

```<code>{
                "Effect" : "Allow",
                "Action" : "ec2:*",
                "Resource" : "*",
                "Condition" : {
                     "StringEquals" : {
                          "ec2:ResourceTag/UserName" : "${aws:username}"
                     }
</code>```

答:
@Chris Thank you for the tip it worked out for me: I used the below statement and was not able to launch an instance into my labeled public subnets</p>

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Condition": {
                "StringLike": {
                    "ec2:ResourceTag/Name": "*public*"
                }
            },
            "Action": [
                "ec2:Run*",
                "ec2:Terminate*",
                "ec2:Cancel*",
                "ec2:Create*",
                "ec2:Delete*",
                "ec2:Modify*",
                "ec2:Start*",
                "ec2:Stop*"
            ],
            "Resource": "arn:aws:ec2:ap-southeast-2:106625493890:subnet/*",
            "Effect": "Deny",
            "Sid": "DenyInstanceActionsForPublicSubnets"
        },
</code>```

Body:
I need to restrict a specific user role from performing any EC2 instance actions in public subnets across any VPC. Is there a way to achieve this by leveraging subnet tags? I know how to use EC2 Resource Tags to control access to EC2 resources like in the code snippet below but in my case I need to base it off vpc or subnet tags. Is there something like a vpc:ResourceTag condition I could leverage?

{
                "Effect" : "Allow",
                "Action" : "ec2:*",
                "Resource" : "*",
                "Condition" : {
                     "StringEquals" : {
                          "ec2:ResourceTag/UserName" : "${aws:username}"
                     }

Body:
@Chris Thank you for the tip it worked out for me: I used the below statement and was not able to launch an instance into my labeled public subnets

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Condition": {
                "StringLike": {
                    "ec2:ResourceTag/Name": "*public*"
                }
            },
            "Action": [
                "ec2:Run*",
                "ec2:Terminate*",
                "ec2:Cancel*",
                "ec2:Create*",
                "ec2:Delete*",
                "ec2:Modify*",
                "ec2:Start*",
                "ec2:Stop*"
            ],
            "Resource": "arn:aws:ec2:ap-southeast-2:106625493890:subnet/*",
            "Effect": "Deny",
            "Sid": "DenyInstanceActionsForPublicSubnets"
        },


问:
The 'this' context is lost during assignment, but not quite?
In the following example there is a simple object. Two instances were created for me to test variable scope.

When test1a (and test2a) is assigned to the method ShowNum it behaves identically as when calling oneObj.ShowNum() by itself. However, when test1b is assigned to the method ShowNum2, then it behaves differently than calling oneObj.ShowNum2() directly.

This is a little puzzling to me because it seems that the 'this' scope is being lost during assignment, but at the same time it is NOT lost because 'num' is still found (and num is as unique to the object instance as this.num2 is).

What is the esoteric explanation for this behavior ?

```<code>function TestObject ()
{
    var num   = 25;
    this.num2 = 50;
    this.ShowNum  = function () {return num;}
    this.ShowNum2 = function () {return this.num2;}
    this.SetNum   = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;

var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;

console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());

console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());
</code>```

Result:

```<code>25
50
25
undefined

100
-12
100
undefined
</code>```

EDIT:
This question does seem like a variant of the one -->here as pointed out by the replies.
My instinctive expectation was that var test1b = oneObj.ShowNum; should imply
var test1b = oneObj.ShowNum2.bind(oneObj); making it for consistent behavior across languages (as Mahesha999 mentioned with the following)

The this keyword behaves differently in JavaScript compared to other
  language. In Object Oriented languages, the this keyword refers to the
  current instance of the class. In JavaScript the value of this is
  determined mostly by the invocation context of function
  (context.function()) and where it is called.

Right now I don't feel like pressing further and I consider this matter closed.

答:
Reason :

```<code>// you are not assigning the whole object , but just passing refernce to the function
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2; // so from here it will lose the context of this
</code>```

test1a is like

```<code>function () {return num;}
</code>```

and test1b is like

```<code>function () {return this.num2;}
</code>```

Here, if you directly assign the function, here this is not pointing to parent function anymore. as you have just assigned the function

You can check that by just putting console.log inside like,

```<code>this.ShowNum2 = function () { console.log(this); return this.num2;}
</code>```

Debugging : Run the below code snippet and you will get idea :

function TestObject ()
{
    var num   = 25;
    this.num2 = 50;
    this.ShowNum  = function () {return num;}
    this.ShowNum2 = function () { console.log(this); return this.num2;}
    this.SetNum   = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;

var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;

console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());

console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());```
</div>
</div>
</p>

<blockquote>
  <p><strong>Solution :</strong></p>
</blockquote>

```//.bind(parent_object);

var test1b = oneObj.ShowNum2.bind(oneObj);
var test2b = twoObj.ShowNum2.bind(twoObj);
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function TestObject ()
{
    var num   = 25;
    this.num2 = 50;
    this.ShowNum  = function () {return num;}
    this.ShowNum2 = function () {return this.num2;}
    this.SetNum   = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;

var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2.bind(oneObj);
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2.bind(twoObj);

console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());

console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());</code>```

Body:
In the following example there is a simple object. Two instances were created for me to test variable scope.

When test1a (and test2a) is assigned to the method ShowNum it behaves identically as when calling oneObj.ShowNum() by itself. However, when test1b is assigned to the method ShowNum2, then it behaves differently than calling oneObj.ShowNum2() directly.

This is a little puzzling to me because it seems that the 'this' scope is being lost during assignment, but at the same time it is NOT lost because 'num' is still found (and num is as unique to the object instance as this.num2 is).

What is the esoteric explanation for this behavior ?

function TestObject ()
{
    var num   = 25;
    this.num2 = 50;
    this.ShowNum  = function () {return num;}
    this.ShowNum2 = function () {return this.num2;}
    this.SetNum   = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;

var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;

console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());

console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());

Result:

25
50
25
undefined

100
-12
100
undefined

EDIT:
This question does seem like a variant of the one -->here as pointed out by the replies.
My instinctive expectation was that var test1b = oneObj.ShowNum; should imply
var test1b = oneObj.ShowNum2.bind(oneObj); making it for consistent behavior across languages (as Mahesha999 mentioned with the following)

The this keyword behaves differently in JavaScript compared to other
  language. In Object Oriented languages, the this keyword refers to the
  current instance of the class. In JavaScript the value of this is
  determined mostly by the invocation context of function
  (context.function()) and where it is called.

Right now I don't feel like pressing further and I consider this matter closed.

Body:
Reason :

// you are not assigning the whole object , but just passing refernce to the function
var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2; // so from here it will lose the context of this

test1a is like

function () {return num;}

and test1b is like

function () {return this.num2;}

Here, if you directly assign the function, here this is not pointing to parent function anymore. as you have just assigned the function

You can check that by just putting console.log inside like,

this.ShowNum2 = function () { console.log(this); return this.num2;}

Debugging : Run the below code snippet and you will get idea :

function TestObject ()
{
    var num   = 25;
    this.num2 = 50;
    this.ShowNum  = function () {return num;}
    this.ShowNum2 = function () { console.log(this); return this.num2;}
    this.SetNum   = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;

var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2;
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2;

console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());

console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());

Solution :

//.bind(parent_object);

var test1b = oneObj.ShowNum2.bind(oneObj);
var test2b = twoObj.ShowNum2.bind(twoObj);

function TestObject ()
{
    var num   = 25;
    this.num2 = 50;
    this.ShowNum  = function () {return num;}
    this.ShowNum2 = function () {return this.num2;}
    this.SetNum   = function (newnum) {num = newnum;}
}
var oneObj = new TestObject();
var twoObj = new TestObject(); twoObj.SetNum(100); twoObj.num2 = -12;

var test1a = oneObj.ShowNum;
var test1b = oneObj.ShowNum2.bind(oneObj);
var test2a = twoObj.ShowNum;
var test2b = twoObj.ShowNum2.bind(twoObj);

console.log(oneObj.ShowNum());
console.log(oneObj.ShowNum2());
console.log(test1a());
console.log(test1b());

console.log(twoObj.ShowNum());
console.log(twoObj.ShowNum2());
console.log(test2a());
console.log(test2b());


问:
Is either GET or POST more secure than the other?
When comparing an HTTP GET to an HTTP POST, what are the differences from a security perspective? Is one of the choices inherently more secure than the other? If so, why?

I realize that POST doesn't expose information on the URL, but is there any real value in that or is it just security through obscurity? Is there ever a reason that I should prefer POST when security is a concern?

Edit:

Over HTTPS, POST data is encoded, but could URLs be sniffed by a 3rd party? Additionally, I am dealing with JSP; when using JSP or a similar framework, would it be fair to say the best practice is to avoid placing sensitive data in the POST or GET altogether and using server side code to handle sensitive information instead?

答:
You have no greater security provided because the variables are sent over HTTP POST than you have with variables sent over HTTP GET.

HTTP/1.1 provides us with a bunch of methods to send a request:

OPTIONS

GET

HEAD

POST

PUT

DELETE

TRACE

CONNECT

Lets suppose you have the following HTML document using GET:

```<code><html>
<body>
<form action="http://example.com" method="get">
    User: <input type="text" name="username" /><br/>
    Password: <input type="password" name="password" /><br/>
    <input type="hidden" name="extra" value="lolcatz" />
    <input type="submit"/>
</form>
</body>
</html>
</code>```

What does your browser ask? It asks this:

```<code> GET /?username=swordfish&password=hunter2&extra=lolcatz HTTP/1.1
 Host: example.com
 Connection: keep-alive
 Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/ [...truncated]
 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) [...truncated]
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
</code>```

Now lets pretend we changed that request method to a POST:

```<code> POST / HTTP/1.1
 Host: example.com
 Connection: keep-alive
 Content-Length: 49
 Cache-Control: max-age=0
 Origin: null
 Content-Type: application/x-www-form-urlencoded
 Accept: application/xml,application/xhtml+xml,text/ [...truncated]
 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; [...truncated]
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

 username=swordfish&password=hunter2&extra=lolcatz
</code>```

BOTH of these HTTP requests are:

Not encrypted

Included in both examples

Can be evesdroped on, and subject to MITM attacks.

Easily reproduced by third party, and script bots.

Many browsers do not support HTTP methods other than POST/GET.

Many browsers behaviors store the page address, but this doesn't mean you can ignore any of these other issues.

So to be specific:

Is one inherently more secure then another? I realize that POST doesn't expose information on the URL but is there any real value in that or is it just security through obscurity? What is the best practice here?

This is correct, because the software you're using to speak HTTP tends to store the request variables with one method but not another only prevents someone from looking at your browser history or some other naive attack from a 10 year old who thinks they understand h4x0r1ng, or scripts that check your history store. If you have a script that can check your history store, you could just as easily have one that checks your network traffic, so this entire security through obscurity is only providing obscurity to script kiddies and jealous girlfriends.

Over https, POST data is encoded, but could urls be sniffed by a 3rd party?

Here's how SSL works. Remember those two requests I sent above? Here's what they look like in SSL:
(I changed the page to https://encrypted.google.com/ as example.com doesn't respond on SSL).

POST over SSL

```<code>q5XQP%RWCd2u#o/T9oiOyR2_YO?yo/3#tR_G7 2_RO8w?FoaObi)
oXpB_y?oO4q?`2o?O4G5D12Aovo?C@?/P/oOEQC5v?vai /%0Odo
QVw#6eoGXBF_o?/u0_F!_1a0A?Q b%TFyS@Or1SR/O/o/_@5o&_o
9q1/?q$7yOAXOD5sc$H`BECo1w/`4?)f!%geOOF/!/#Of_f&AEI#
yvv/wu_b5?/o d9O?VOVOFHwRO/pO/OSv_/8/9o6b0FGOH61O?ti
/i7b?!_o8u%RS/Doai%/Be/d4$0sv_%YD2_/EOAO/C?vv/%X!T?R
_o_2yoBP)orw7H_yQsXOhoVUo49itare#cA?/c)I7R?YCsg ??c'
(_!(0u)o4eIis/S8Oo8_BDueC?1uUO%ooOI_o8WaoO/ x?B?oO@&
Pw?os9Od!c?/$3bWWeIrd_?( `P_C?7_g5O(ob(go?&/ooRxR'u/
T/yO3dS&??hIOB/?/OI?$oH2_?c_?OsD//0/_s%r
</code>```

GET over SSL

```<code>rV/O8ow1pc`?058/8OS_Qy/$7oSsU'qoo#vCbOO`vt?yFo_?EYif)
43`I/WOP_8oH0%3OqP_h/cBO&24?'?o_4`scooPSOVWYSV?H?pV!i
?78cU!_b5h'/b2coWD?/43Tu?153pI/9?R8!_Od"(//O_a#t8x?__
bb3D?05Dh/PrS6_/&5p@V f $)/xvxfgO'q@y&e&S0rB3D/Y_/fO?
_'woRbOV?_!yxSOdwo1G1?8d_p?4fo81VS3sAOvO/Db/br)f4fOxt
_Qs3EO/?2O/TOo_8p82FOt/hO?X_P3o"OVQO_?Ww_dr"'DxHwo//P
oEfGtt/_o)5RgoGqui&AXEq/oXv&//?%/6_?/x_OTgOEE%v (u(?/
t7DX1O8oD?fVObiooi'8)so?o??`o"FyVOByY_ Supo? /'i?Oi"4
tr'9/o_7too7q?c2Pv
</code>```

(note: I converted the HEX to ASCII, some of it should obviously not be displayable)

The entire HTTP conversation is encrypted, the only visible portion of communication is on the TCP/IP layer (meaning the IP address and connection port information).

So let me make a big bold statement here. Your website is not provided greater security over one HTTP method than it is another, hackers and newbs all over the world know exactly how to do what I've just demonstrated here. If you want security, use SSL. Browsers tend to store history, it's recommended by RFC2616 9.1.1 to NOT use GET to perform an action, but to think that POST provides security is flatly wrong.

The only thing that POST is a security measure towards? Protection against your jealous ex flipping through your browser history. That's it. The rest of the world is logged into your account laughing at you.

To further demonstrate why POST isn't secure, Facebook uses POST requests all over the place, so how can software such as FireSheep exist?

Note that you may be attacked with CSRF even if you use HTTPS and your site does not contain XSS vulnerabilities. In short, this attack scenario assumes that the victim (the user of your site or service) is already logged in and has a proper cookie and then the victim's browser is requested to do something with your (supposedly secure) site. If you do not have protection against CSRF the attacker can still execute actions with the victims credentials. The attacker cannot see the server response because it will be transferred to the victim's browser but the damage is usually already done at that point.

OwnerDisplayName: nemo

Body:
You have no greater security provided because the variables are sent over HTTP POST than you have with variables sent over HTTP GET.

HTTP/1.1 provides us with a bunch of methods to send a request:

OPTIONS

GET

HEAD

POST

PUT

DELETE

TRACE

CONNECT

Lets suppose you have the following HTML document using GET:

<html>
<body>
<form action="http://example.com" method="get">
    User: <input type="text" name="username" /><br/>
    Password: <input type="password" name="password" /><br/>
    <input type="hidden" name="extra" value="lolcatz" />
    <input type="submit"/>
</form>
</body>
</html>

What does your browser ask? It asks this:

 GET /?username=swordfish&password=hunter2&extra=lolcatz HTTP/1.1
 Host: example.com
 Connection: keep-alive
 Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/ [...truncated]
 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) [...truncated]
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Now lets pretend we changed that request method to a POST:

 POST / HTTP/1.1
 Host: example.com
 Connection: keep-alive
 Content-Length: 49
 Cache-Control: max-age=0
 Origin: null
 Content-Type: application/x-www-form-urlencoded
 Accept: application/xml,application/xhtml+xml,text/ [...truncated]
 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; [...truncated]
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: en-US,en;q=0.8
 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

 username=swordfish&password=hunter2&extra=lolcatz

BOTH of these HTTP requests are:

Not encrypted

Included in both examples

Can be evesdroped on, and subject to MITM attacks.

Easily reproduced by third party, and script bots.

Many browsers do not support HTTP methods other than POST/GET.

Many browsers behaviors store the page address, but this doesn't mean you can ignore any of these other issues.

So to be specific:

Is one inherently more secure then another? I realize that POST doesn't expose information on the URL but is there any real value in that or is it just security through obscurity? What is the best practice here?

This is correct, because the software you're using to speak HTTP tends to store the request variables with one method but not another only prevents someone from looking at your browser history or some other naive attack from a 10 year old who thinks they understand h4x0r1ng, or scripts that check your history store. If you have a script that can check your history store, you could just as easily have one that checks your network traffic, so this entire security through obscurity is only providing obscurity to script kiddies and jealous girlfriends.

Over https, POST data is encoded, but could urls be sniffed by a 3rd party?

Here's how SSL works. Remember those two requests I sent above? Here's what they look like in SSL:
(I changed the page to https://encrypted.google.com/ as example.com doesn't respond on SSL).

POST over SSL

q5XQP%RWCd2u#o/T9oiOyR2_YO?yo/3#tR_G7 2_RO8w?FoaObi)
oXpB_y?oO4q?`2o?O4G5D12Aovo?C@?/P/oOEQC5v?vai /%0Odo
QVw#6eoGXBF_o?/u0_F!_1a0A?Q b%TFyS@Or1SR/O/o/_@5o&_o
9q1/?q$7yOAXOD5sc$H`BECo1w/`4?)f!%geOOF/!/#Of_f&AEI#
yvv/wu_b5?/o d9O?VOVOFHwRO/pO/OSv_/8/9o6b0FGOH61O?ti
/i7b?!_o8u%RS/Doai%/Be/d4$0sv_%YD2_/EOAO/C?vv/%X!T?R
_o_2yoBP)orw7H_yQsXOhoVUo49itare#cA?/c)I7R?YCsg ??c'
(_!(0u)o4eIis/S8Oo8_BDueC?1uUO%ooOI_o8WaoO/ x?B?oO@&
Pw?os9Od!c?/$3bWWeIrd_?( `P_C?7_g5O(ob(go?&/ooRxR'u/
T/yO3dS&??hIOB/?/OI?$oH2_?c_?OsD//0/_s%r

GET over SSL

rV/O8ow1pc`?058/8OS_Qy/$7oSsU'qoo#vCbOO`vt?yFo_?EYif)
43`I/WOP_8oH0%3OqP_h/cBO&24?'?o_4`scooPSOVWYSV?H?pV!i
?78cU!_b5h'/b2coWD?/43Tu?153pI/9?R8!_Od"(//O_a#t8x?__
bb3D?05Dh/PrS6_/&5p@V f $)/xvxfgO'q@y&e&S0rB3D/Y_/fO?
_'woRbOV?_!yxSOdwo1G1?8d_p?4fo81VS3sAOvO/Db/br)f4fOxt
_Qs3EO/?2O/TOo_8p82FOt/hO?X_P3o"OVQO_?Ww_dr"'DxHwo//P
oEfGtt/_o)5RgoGqui&AXEq/oXv&//?%/6_?/x_OTgOEE%v (u(?/
t7DX1O8oD?fVObiooi'8)so?o??`o"FyVOByY_ Supo? /'i?Oi"4
tr'9/o_7too7q?c2Pv

(note: I converted the HEX to ASCII, some of it should obviously not be displayable)

The entire HTTP conversation is encrypted, the only visible portion of communication is on the TCP/IP layer (meaning the IP address and connection port information).

So let me make a big bold statement here. Your website is not provided greater security over one HTTP method than it is another, hackers and newbs all over the world know exactly how to do what I've just demonstrated here. If you want security, use SSL. Browsers tend to store history, it's recommended by RFC2616 9.1.1 to NOT use GET to perform an action, but to think that POST provides security is flatly wrong.

The only thing that POST is a security measure towards? Protection against your jealous ex flipping through your browser history. That's it. The rest of the world is logged into your account laughing at you.

To further demonstrate why POST isn't secure, Facebook uses POST requests all over the place, so how can software such as FireSheep exist?

Note that you may be attacked with CSRF even if you use HTTPS and your site does not contain XSS vulnerabilities. In short, this attack scenario assumes that the victim (the user of your site or service) is already logged in and has a proper cookie and then the victim's browser is requested to do something with your (supposedly secure) site. If you do not have protection against CSRF the attacker can still execute actions with the victims credentials. The attacker cannot see the server response because it will be transferred to the victim's browser but the damage is usually already done at that point.


问:
How to get information(Model, Serial, ...) of Samsung Gear S3 smartwatch?
I am trying to get the information(Model number, Serial, ...) in a tizen application running on Gear S3. On the watch, this information can be found - Settings -> Gear info -> About Device

Is there any method or API to get the value in a tizen application ?

答:
Tizen'SystemInfo' API provides such System Information.You can check SystemInfo Web API documentations:

SystemInfo API: Tip&Tech

SystemInfo Web API Guide

SystemInfo Web API References

Here's a sample code to get model number and software version. You can check in the API references for the specific properties you are looking for (only if they are available).

```<code> function onSuccessCallbackBuild(info) {
         alert("Model:" + info.model+ "\n"+"Manufacture:"+ info.manufacturer+ "\n"+"Build:"+ info.buildVersion);
     }

 function onErrorCallback(error) {
         alert("Not supported: " + error.message);
     }

 tizen.systeminfo.getPropertyValue("BUILD", onSuccessCallbackBuild, onErrorCallback);
</code>```

There is also Tizen native API for System Information. May have a look If you are going for a Tizen Native application.

SystemInfo Native API Guide

SystemInfo Native API References

Body:
Tizen'SystemInfo' API provides such System Information.You can check SystemInfo Web API documentations:

SystemInfo API: Tip&Tech

SystemInfo Web API Guide

SystemInfo Web API References

Here's a sample code to get model number and software version. You can check in the API references for the specific properties you are looking for (only if they are available).

 function onSuccessCallbackBuild(info) {
         alert("Model:" + info.model+ "\n"+"Manufacture:"+ info.manufacturer+ "\n"+"Build:"+ info.buildVersion);
     }

 function onErrorCallback(error) {
         alert("Not supported: " + error.message);
     }

 tizen.systeminfo.getPropertyValue("BUILD", onSuccessCallbackBuild, onErrorCallback);

There is also Tizen native API for System Information. May have a look If you are going for a Tizen Native application.

SystemInfo Native API Guide

SystemInfo Native API References


问:
Changing int result `15` to `{ "result" : 15 }`
I am creating an ASP.NET Web API that calls an addition function from a dll file and finds the sum of the numbers that user input in the URL. E.g: http://localhost:52241/api/dlladdition/9/6 (user inputs numbers 9 and 6). The result will be 15. I want the result to be something like { "result" : 15 }. How do i achieve that?

Here are my codes:

dll file

Mathclass.cs

```<code>public static class MathClass
{
    //method for Addition
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}
</code>```

ASP.NET Web API

Addition.cs

```<code>using ClassLibraryDll;
public class Addition
{
    public static int num1 { get; set; }
    public static int num2 { get; set; }

    public static int sum = MathClass.Add(num1, num2);
}
</code>```

AdditionController.cs

```<code>private Addition addition = new Addition();

public int GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return result;
}
</code>```

WebApiConfig.cs

```<code>public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DllAdditionApi",
            routeTemplate: "api/dlladdition/{num1}/{num2}",
            defaults: new { action = "Get", controller = "DllAddition" }
        );
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept","text/html",
            StringComparison.InvariantCultureIgnoreCase,true,"application/json")
       );

    }
</code>```

答:
Here is what you can do. Create a new model for your return data like this</p>

```<code>public class AdditionResult
{
    public int Result {get; set;}
}

public AdditionResult GET(int num1, int num2)
{
    int sum = ClassLibraryDll.MathClass.Add(num1, num2);
    var addResult = new AdditionResult();
    addResult.Result = sum;
    return addResult;
}
</code>```

Body:
I am creating an ASP.NET Web API that calls an addition function from a dll file and finds the sum of the numbers that user input in the URL. E.g: http://localhost:52241/api/dlladdition/9/6 (user inputs numbers 9 and 6). The result will be 15. I want the result to be something like { "result" : 15 }. How do i achieve that?

Here are my codes:

dll file

Mathclass.cs

public static class MathClass
{
    //method for Addition
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }
}

ASP.NET Web API

Addition.cs

using ClassLibraryDll;
public class Addition
{
    public static int num1 { get; set; }
    public static int num2 { get; set; }

    public static int sum = MathClass.Add(num1, num2);
}

AdditionController.cs

private Addition addition = new Addition();

public int GET(int num1, int num2)
{
    int result = ClassLibraryDll.MathClass.Add(num1, num2);
    return result;
}

WebApiConfig.cs

public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DllAdditionApi",
            routeTemplate: "api/dlladdition/{num1}/{num2}",
            defaults: new { action = "Get", controller = "DllAddition" }
        );
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
            .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept","text/html",
            StringComparison.InvariantCultureIgnoreCase,true,"application/json")
       );

    }

Body:
Here is what you can do. Create a new model for your return data like this

public class AdditionResult
{
    public int Result {get; set;}
}

public AdditionResult GET(int num1, int num2)
{
    int sum = ClassLibraryDll.MathClass.Add(num1, num2);
    var addResult = new AdditionResult();
    addResult.Result = sum;
    return addResult;
}


问:
Can't view CSV with Shinydashboard app
I'm just starting to learn shiny, and I've been having an issue with just viewing the uploaded csv. I was able to view the data when I didn't have a sidebar menu, but now that I am trying to expand on my app with other tabs, the data does now show up. Is there something wrong with my formatting? My code is attached, and it could be used for any csv. Thanks</p>

```<code>library(shiny)
library(shinydashboard)
library(DT)

options(shiny.maxRequestSize=400*1024^2)

data<- read.csv("shiny.app.data.csv", header=TRUE, sep=',')

ui <- dashboardPage(skin="red",
  dashboardHeader(title="PRIZM Segment Analysis", titleWidth=350),
  dashboardSidebar(width=350,
                   sidebarMenu(menuItem("Segment Counts and Summaries", tabname="segments", icon=icon("pie-chart")),
                   menuItem("Raw Data", tabname="raw", icon=icon("book")),
                   menuItem("Plots", tabname="plots", icon=icon("line-chart")))),
  dashboardBody(tabItems(
    tabItem(tabName="segments",
                box(DT::dataTableOutput("test"), width = 12, status="success", solidHeader = TRUE)))

))

server <- function(input, output, session) {
  is.num<- sapply(data, is.numeric)
  data[is.num] <-lapply(data[is.num], round,2)

  output$test <- DT::renderDataTable({
                datatable(data,
                extensions = c('ColReorder','Buttons'),
                options = list(colReorder = list(realtime = FALSE),scrollX = TRUE,dom = 'Bfrtip', buttons = I('colvis'), list(scrollX = TRUE)),
                rownames=FALSE,
                class = 'display cell-border', width=15)

    })
    }

    shinyApp <- shinyApp(ui, server)
    runApp(shinyApp, launch.browser=TRUE)
</code>```

答:
It's just a typo in your code in tabName (notice the capital N) within the menuItem:

```<code>library(shiny)
library(shinydashboard)
library(DT)

options(shiny.maxRequestSize=400*1024^2)

data<- read.csv("shiny.app.data.csv", header=TRUE, sep=',')

ui <- dashboardPage(skin="red",
  dashboardHeader(title="PRIZM Segment Analysis", titleWidth=350),
  dashboardSidebar(width=350,
                   sidebarMenu(menuItem("Segment Counts and Summaries", tabName="segments", icon=icon("pie-chart")),
                   menuItem("Raw Data", tabName="raw", icon=icon("book")),
                   menuItem("Plots", tabName="plots", icon=icon("line-chart")))),
  dashboardBody(tabItems(
    tabItem(tabName="segments",
                box(DT::dataTableOutput("test"), width = 12, status="success", solidHeader = TRUE)))

))

server <- function(input, output, session) {
  is.num<- sapply(data, is.numeric)
  data[is.num] <-lapply(data[is.num], round,2)

  output$test <- DT::renderDataTable({
                datatable(data,
                extensions = c('ColReorder','Buttons'),
                options = list(colReorder = list(realtime = FALSE),scrollX = TRUE,dom = 'Bfrtip', buttons = I('colvis'), list(scrollX = TRUE)),
                rownames=FALSE,
                class = 'display cell-border', width=15)

    })
    }

    shinyApp <- shinyApp(ui, server)
    runApp(shinyApp, launch.browser=TRUE)
</code>```

Reference: https://rstudio.github.io/shinydashboard/structure.html#sidebar-menu-items-and-tabs

Title: Can't view CSV with Shinydashboard app

Body:
I'm just starting to learn shiny, and I've been having an issue with just viewing the uploaded csv. I was able to view the data when I didn't have a sidebar menu, but now that I am trying to expand on my app with other tabs, the data does now show up. Is there something wrong with my formatting? My code is attached, and it could be used for any csv. Thanks

library(shiny)
library(shinydashboard)
library(DT)

options(shiny.maxRequestSize=400*1024^2)

data<- read.csv("shiny.app.data.csv", header=TRUE, sep=',')

ui <- dashboardPage(skin="red",
  dashboardHeader(title="PRIZM Segment Analysis", titleWidth=350),
  dashboardSidebar(width=350,
                   sidebarMenu(menuItem("Segment Counts and Summaries", tabname="segments", icon=icon("pie-chart")),
                   menuItem("Raw Data", tabname="raw", icon=icon("book")),
                   menuItem("Plots", tabname="plots", icon=icon("line-chart")))),
  dashboardBody(tabItems(
    tabItem(tabName="segments",
                box(DT::dataTableOutput("test"), width = 12, status="success", solidHeader = TRUE)))

))

server <- function(input, output, session) {
  is.num<- sapply(data, is.numeric)
  data[is.num] <-lapply(data[is.num], round,2)

  output$test <- DT::renderDataTable({
                datatable(data,
                extensions = c('ColReorder','Buttons'),
                options = list(colReorder = list(realtime = FALSE),scrollX = TRUE,dom = 'Bfrtip', buttons = I('colvis'), list(scrollX = TRUE)),
                rownames=FALSE,
                class = 'display cell-border', width=15)

    })
    }

    shinyApp <- shinyApp(ui, server)
    runApp(shinyApp, launch.browser=TRUE)

Body:
It's just a typo in your code in tabName (notice the capital N) within the menuItem:

library(shiny)
library(shinydashboard)
library(DT)

options(shiny.maxRequestSize=400*1024^2)

data<- read.csv("shiny.app.data.csv", header=TRUE, sep=',')

ui <- dashboardPage(skin="red",
  dashboardHeader(title="PRIZM Segment Analysis", titleWidth=350),
  dashboardSidebar(width=350,
                   sidebarMenu(menuItem("Segment Counts and Summaries", tabName="segments", icon=icon("pie-chart")),
                   menuItem("Raw Data", tabName="raw", icon=icon("book")),
                   menuItem("Plots", tabName="plots", icon=icon("line-chart")))),
  dashboardBody(tabItems(
    tabItem(tabName="segments",
                box(DT::dataTableOutput("test"), width = 12, status="success", solidHeader = TRUE)))

))

server <- function(input, output, session) {
  is.num<- sapply(data, is.numeric)
  data[is.num] <-lapply(data[is.num], round,2)

  output$test <- DT::renderDataTable({
                datatable(data,
                extensions = c('ColReorder','Buttons'),
                options = list(colReorder = list(realtime = FALSE),scrollX = TRUE,dom = 'Bfrtip', buttons = I('colvis'), list(scrollX = TRUE)),
                rownames=FALSE,
                class = 'display cell-border', width=15)

    })
    }

    shinyApp <- shinyApp(ui, server)
    runApp(shinyApp, launch.browser=TRUE)

Reference: https://rstudio.github.io/shinydashboard/structure.html#sidebar-menu-items-and-tabs


问:
JavaScript smooth scroll - iphone
Are there any plugins or does anyone know of a good way to achieve the iPhone elastic band scroll?
working example in flash
http://www.shinedraw.com/text-effect/silverlight-3-and-flash-iphone-dragging-effect/

I'm looking to drag and scroll a div, but if it goes past a certain point it bounces back.

Thanks

答: Check out iScroll.</p>

Title: JavaScript smooth scroll - iphone

Body: Check out iScroll.


问:
Android - findViewById returns null while trying to set value from Serializable
I cannot figure out how to pass this User class Object. I am simply trying to take input from an editText stored in the first activity and then send it to a textView in another activity. I've done this before, but for some reason, I am wrong here, and I keep getting this error "                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{example.com.avatar/example.com.avatar.DisplayActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference". Can anyone help me out here?</p>

```<code>//1st Activity
findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
                User user = new User();
                textViewNameLocal = findViewById(R.id.textViewName);
                intent.putExtra("USER", user);
                startActivity(intent);
            }
        });
    }

//2nd Activity
public class DisplayActivity extends AppCompatActivity {
    TextView textViewName, textViewEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        textViewName = findViewById(R.id.textViewName); //this was the error, it needs to be below the "setContentView(R.layout.activity_display)".
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Intent intent = getIntent();
        User user = (User) intent.getSerializableExtra("USER");
        textViewName.setText(user.getName().toString);

    }
}
</code>```

答:
There is nothing wrong with Serialization in your code.

You are getting the error at:

```<code>textViewName.setText(user.getName());
</code>```

Because the variable textViewName is null.

Consider assigning its reference to it using findViewById only after the call to the method setContentView

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
textViewName = findViewById(R.id.textViewName); //call after setContentView

Intent intent = getIntent();
User user = (User) intent.getSerializableExtra("USER");
textViewName.setText(user.getName());
</code>```

Body:
I cannot figure out how to pass this User class Object. I am simply trying to take input from an editText stored in the first activity and then send it to a textView in another activity. I've done this before, but for some reason, I am wrong here, and I keep getting this error "                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{example.com.avatar/example.com.avatar.DisplayActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference". Can anyone help me out here?

//1st Activity
findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DisplayActivity.class);
                User user = new User();
                textViewNameLocal = findViewById(R.id.textViewName);
                intent.putExtra("USER", user);
                startActivity(intent);
            }
        });
    }

//2nd Activity
public class DisplayActivity extends AppCompatActivity {
    TextView textViewName, textViewEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        textViewName = findViewById(R.id.textViewName); //this was the error, it needs to be below the "setContentView(R.layout.activity_display)".
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Intent intent = getIntent();
        User user = (User) intent.getSerializableExtra("USER");
        textViewName.setText(user.getName().toString);

    }
}

Body:
There is nothing wrong with Serialization in your code.

You are getting the error at:

textViewName.setText(user.getName());

Because the variable textViewName is null.

Consider assigning its reference to it using findViewById only after the call to the method setContentView

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
textViewName = findViewById(R.id.textViewName); //call after setContentView

Intent intent = getIntent();
User user = (User) intent.getSerializableExtra("USER");
textViewName.setText(user.getName());


问:
Sqoop import statement
The below mentioned sqoop import statements worked for me the other day and today the same statements is showing error. Below is the error and import statement.

ERROR:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sqoop import

```<code>sqoop import \
--connect jdbc:mysql://localhost/loudacre \
--username training --password training \
--table device \
-- target-dir /loudacre/device
-m 1
</code>```

答:
Yes you may face the error saying that --target-dir /loudacre/device already exists. when you run the command for the first as there is no target-dir defined in hdfs the script runs fine but for the second time as target-dir is already available in hdfs dir it throws error saying dir already exists.

Solutions to resolve this error:
1. Give another new directory or delete existing directory and try script again.
2. you can also import mysql data in sqoop append mode or overwride mode. Refer the below link for reference:
Using sqoop import, How to append rows into existing hive table?

Kindly let me know if it works.

Title: Sqoop import statement

Body:
The below mentioned sqoop import statements worked for me the other day and today the same statements is showing error. Below is the error and import statement.

ERROR:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'sqoop import

sqoop import \
--connect jdbc:mysql://localhost/loudacre \
--username training --password training \
--table device \
-- target-dir /loudacre/device
-m 1