问:
How do I convert a JSON string to a function in javascript?
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

```<code>json = { "one": 700, "two": "function(e){alert(e);}" }
</code>```

Then in my code:

```<code>parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})
</code>```

答:
You are eval'ing an anonymous function, which of course won't be called by anything. If you really wanted to run the code in the json then the text would need to be alert(e).

However it doesn't sound like a very sensible thing to do. You'd be better off writing code to deal with the contents of the json object, rather than trying to run code embedded in the json.

Body:
How can I convert a string in javascript/jquery to a function?

I am trying to use a JSON parameter list to initialize a function.  However, one of the parameters is a function, which I store as a string, and I get an error when I try to use eval() to return the function.

For example, if my JSON is:

json = { "one": 700, "two": "function(e){alert(e);}" }

Then in my code:

parameters = eval(json);
$('myDiv').addThisFeature({
 parameter_1: json.one,
 parameter_2: eval(json.two)  // <= generates error
})


来源: stackexchange

问:
Re-ordering entries in a model using drag-and-drop
Say I have a blogging app in Django. How can i re-order the posts using a draggable table in the default admin?

It would be best if i didn't have to add any extra fields to the model, but if i really have to i can.

答:
The order can only be determined if you add a field in your model.Let's add a position field in your model.

```<code>In your models.py

class MainModel(models.Model):

    name = models.CharField(max_length=255)
    position = models.PositiveSmallIntegerField(null=True)

    class Meta:
        ordering = ('position',)

In your apps admin.py

class IdeaCardTagInline(nested_admin.NestedStackedInline):
    model = MainModel
    extra = 0
    min_num = 1
    sortable_field_name = "position"
</code>```

ordering = ('position',) in Meta will order the MainModel according to the value in the position field.
sortable_field_name = "position" will help in autofill of the value in position when an user drag and drop the multiple models.

To see the same order in your api, use order_by(x) in views_model.py.
Just a model example:

```<code>Model.objects.filter().order_by('position').
</code>```

OwnerDisplayName: joshhunt

ContentLicense: CC BY-SA 2.5

Body:
The order can only be determined if you add a field in your model.Let's add a position field in your model.

In your models.py

class MainModel(models.Model):

    name = models.CharField(max_length=255)
    position = models.PositiveSmallIntegerField(null=True)

    class Meta:
        ordering = ('position',)

In your apps admin.py

class IdeaCardTagInline(nested_admin.NestedStackedInline):
    model = MainModel
    extra = 0
    min_num = 1
    sortable_field_name = "position"

ordering = ('position',) in Meta will order the MainModel according to the value in the position field.
sortable_field_name = "position" will help in autofill of the value in position when an user drag and drop the multiple models.

To see the same order in your api, use order_by(x) in views_model.py.
Just a model example:

Model.objects.filter().order_by('position').

ContentLicense: CC BY-SA 3.0


问:
Regular Expression: if, else if to use in Java
I am trying to write a regular expression in which I want to compare the URL's.

Any URL Matches
http://*.xyz.com
Except or Excluding
http://m.xyz.com and http://m.product.xyz.com

So far I was trying to do it by using if else in RegExp but I couldn't be able to do it right...

```<code>(^http:\/\/)(((1)<!(m|m\.product))\.xyz\.co\.jp)?
</code>```

答:
https?:\/\/(?!m\.|m\.product\.).*\.xyz\..*

This regex accepts all *.xyz.* domains except m.xyz.* and m.product.xyz.*. Also takes care of http or https.

Demo

Body:
I am trying to write a regular expression in which I want to compare the URL's.

Any URL Matches
http://*.xyz.com
Except or Excluding
http://m.xyz.com and http://m.product.xyz.com

So far I was trying to do it by using if else in RegExp but I couldn't be able to do it right...

(^http:\/\/)(((1)<!(m|m\.product))\.xyz\.co\.jp)?


问:
Regex to Extract Update Columns from a Sql Statement
I need a Regex Statement (run in c#) that will take a string containing a Sql Update statement as input, and will return a list of columns to be updated. It should be able to handle columns surrounded by brackets or not.

```<code>// Example Sql Statement
Update Employees
Set FirstName = 'Jim', [LastName] = 'Smith', CodeNum = codes.Num
From Employees as em
Join CodeNumbers as codes on codes.EmployeeID = em.EmployeeID
</code>```

In the end I would want to return an IEnumerable or List containing:

FirstName

LastName

CodeNum

Anyone have any good suggestions on implementation?

Update: The sql is user-generated, so I have to parse the Sql as it is given. The purpose of extracting the column names in my case is to validate that the user has permission to update the columns included in the query.

答:
Regular expressions cannot do this task, because SQL is not a regular language.

You can do this, but not with a regular expression.  You need a full-blown parser.

You can use ANTLR to generate parsers in C#, and there are free grammars  available for parsing SQL in ANTLR.

However, I agree with Glomek that allowing user-supplied SQL to be run against your system, even after you have tried to validate that it includes no "unauthorized actions," is foolish.  There are too many cases that may circumvent your validation.

Instead, if you have only a single text field, you should define a simplified Domain-Specific Language that permits users to specify only actions that they are authorized to do.  From this input, you can build the SQL yourself.

OwnerDisplayName: Yaakov Ellis

Body:
I need a Regex Statement (run in c#) that will take a string containing a Sql Update statement as input, and will return a list of columns to be updated. It should be able to handle columns surrounded by brackets or not.

// Example Sql Statement
Update Employees
Set FirstName = 'Jim', [LastName] = 'Smith', CodeNum = codes.Num
From Employees as em
Join CodeNumbers as codes on codes.EmployeeID = em.EmployeeID

In the end I would want to return an IEnumerable or List containing:

FirstName

LastName

CodeNum

Anyone have any good suggestions on implementation?

Update: The sql is user-generated, so I have to parse the Sql as it is given. The purpose of extracting the column names in my case is to validate that the user has permission to update the columns included in the query.

LastEditorDisplayName: Yaakov Ellis

OwnerDisplayName: Bill Karwin


答: Neither way is particularly nice, but if you can get rid of the function(e) wrapper bits, then you can use var myDynamicFunction = new Function("e", "alert(e);"); Otherwise, you're looking at using eval(). Eval() is evil in general. If this is JSON that you're getting back from a $.getJSON call or something, you're opening yourself up to security concerns.

Title: How do I convert a JSON string to a function in javascript?


问:
Getting "The path to the driver executable must be set by the webdriver.gecko.driver " while try to run selenium Grid code with Gecko driver
I am running basic selenium code with the help of selenium Grid.

Below are the steps:

Step 1 :- Downloaded the latest version of selenium Standalone server (3.4.0);

Step 2 :- Created HUB by using command java - jar <path of selenium standalone server>\\selenium-server-standalone-3.4.0.jar -role hub -> run successfully;

Step 3 :- Created node using command java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register -> run successfully;

Step 4 :- Created a simple selenium program with below code:

```<code>public class ClassName {

  public static void main(String args[]) throws InterruptedException, MalformedURLException {
    System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
    DesiredCapabilities cap=DesiredCapabilities.firefox();
    cap.setPlatform(Platform.WINDOWS);
    cap.setBrowserName("firefox");
    URL url = new URL("http://localhost:4444/wd/hub");

    WebDriver wd1 = new RemoteWebDriver(url, cap);
    wd1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    wd1.manage().window().maximize();

    wd1.get("http://www.clickindia.com/");
    wd1.findElement(By.linkText("Post Free Ad")).click();
    Thread.sleep(3000);
    wd1.findElement(By.linkText("Select category manually")).click();
    Thread.sleep(3000);
    WebElement country = wd1.findElement(By.id("combo_0"));
    Select sel = new Select(country);
    sel.selectByVisibleText("Jobs");
  }
}
</code>```

While running above code the following exception was thrown:

Note : If I run above code without remoteDriver and as a common WebDriver programm then it is working and running properly.

Location of selenium standalone server and Gecko file is same.

Gecko version is v0.16.0

Thanks in advance

答:
The error message indicates that Selenium cannot find GeckoDriver binary in:

Any of the locations that are part of  the PATH environment variable and

It could not find any valid value via the JVM argument (System.getProperty("webdriver.gecko.driver")) which represents geckodriver binary's location .

The line

```<code>System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
</code>```

ensures that only the current JVM (The JVM in which your ClassName.main() method is executing) knows of the location of the geckodriver binary. That is why your code runs fine when you work with FirefoxDriver.

But when you are working with RemoteWebDriver i.e., in the Grid mode, wherein you are trying to run against a Grid setup, setting the geckodriver location via the JVM argument "webdriver.gecko.driver" will not have any effect on the other JVMs (remember that the node which is responsible for supporting your browser interaction is spun off under a separate JVM using the command java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register (Your step 3).

To fix this, you have two options.

You use the JVM argument -Dwebdriver.gecko.driver when you are spawning the node and specify the location of the geckodriver.

You download geckodriver binary into a folder and include its location as part of your PATH variable (i.e., add C:\\geckodriver.exe to your PATH variable)

Body:
I am running basic selenium code with the help of selenium Grid.

Below are the steps:

Step 1 :- Downloaded the latest version of selenium Standalone server (3.4.0);

Step 2 :- Created HUB by using command java - jar <path of selenium standalone server>\\selenium-server-standalone-3.4.0.jar -role hub -> run successfully;

Step 3 :- Created node using command java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register -> run successfully;

Step 4 :- Created a simple selenium program with below code:

public class ClassName {

  public static void main(String args[]) throws InterruptedException, MalformedURLException {
    System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
    DesiredCapabilities cap=DesiredCapabilities.firefox();
    cap.setPlatform(Platform.WINDOWS);
    cap.setBrowserName("firefox");
    URL url = new URL("http://localhost:4444/wd/hub");

    WebDriver wd1 = new RemoteWebDriver(url, cap);
    wd1.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    wd1.manage().window().maximize();

    wd1.get("http://www.clickindia.com/");
    wd1.findElement(By.linkText("Post Free Ad")).click();
    Thread.sleep(3000);
    wd1.findElement(By.linkText("Select category manually")).click();
    Thread.sleep(3000);
    WebElement country = wd1.findElement(By.id("combo_0"));
    Select sel = new Select(country);
    sel.selectByVisibleText("Jobs");
  }
}

While running above code the following exception was thrown:

Note : If I run above code without remoteDriver and as a common WebDriver programm then it is working and running properly.

Location of selenium standalone server and Gecko file is same.

Gecko version is v0.16.0

Thanks in advance

Body:
The error message indicates that Selenium cannot find GeckoDriver binary in:

Any of the locations that are part of  the PATH environment variable and

It could not find any valid value via the JVM argument (System.getProperty("webdriver.gecko.driver")) which represents geckodriver binary's location .

The line

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

ensures that only the current JVM (The JVM in which your ClassName.main() method is executing) knows of the location of the geckodriver binary. That is why your code runs fine when you work with FirefoxDriver.

But when you are working with RemoteWebDriver i.e., in the Grid mode, wherein you are trying to run against a Grid setup, setting the geckodriver location via the JVM argument "webdriver.gecko.driver" will not have any effect on the other JVMs (remember that the node which is responsible for supporting your browser interaction is spun off under a separate JVM using the command java -jar selenium-server-standalone-3.4.0.jar -role hub -node http://localhost:4444/grid/register (Your step 3).

To fix this, you have two options.

You use the JVM argument -Dwebdriver.gecko.driver when you are spawning the node and specify the location of the geckodriver.

You download geckodriver binary into a folder and include its location as part of your PATH variable (i.e., add C:\\geckodriver.exe to your PATH variable)


问:
Excel - Conditional Formatting - Cell not blank and equals 0
I'm trying to check if a cell is:

blank,  and if false (not blank)

If value equals 0. I have tried:

=IF( NOT( ISBLANK($D:$D) ) & $D:$D=0 ,TRUE,FALSE)

=IF( AND( NOT( ISBLANK($D:$D) ),$D:$D=0) ,TRUE,FALSE)

I am use Excel 2013 with Conditional Formatting rule: Use a formula to determine which cells to format > Format values where this formula is true

What am I doing wrong? The problem is, the IF($D:$D=0) recognises cells with value 0 and those which are blank as true. I only want it to recognise 0 values. Not blank.

答: Before the rule specifying "0" you should add the rule "cell contains empty (blank) value". Then set the format to "no formatting" and then select "stop if true".</p>


问:
MySQL to Azure SQL through CSV file
If I export a MySQL table into a .csv file, is there any extra work needed to now push this .csv file onto an Azure SQL database?</p>

答:
is there any extra work needed to now push this .csv file onto an Azure SQL database?

For flat CSV file, you could create the destination table in your Azure SQL Database first, then use the bcp command-line utility for importing data from a CSV file into your Azure SQL Database. For more details, you could refer to Load data from CSV into Azure SQL Database.

Additionally, you could migrate your MySQL database objects to SQL Azure, then migrate the data to SQL Azure. For more details, you could refer to the following tutorials:

Migrating MySQL Databases to SQL Server - Azure SQL DB

Migrating MySQL Data into SQL Server - Azure SQL DB

Title: MySQL to Azure SQL through CSV file


问:
What is the runtime complexity of a switch statement?
I'd like to know what the worst-case runtime complexity of a switch statement is, assuming you have n cases.

I always assumed it was O(n). I don't know if compilers do anything clever, though. If the answer is implementation-specific, I'd like to know for the following languages:

Java

C/C++

C#

PHP

Javascript

答:
C++ compilers can turn switch statements into a jump table (i.e. construct an array of jump offsets, then take the value and use it as an index into the table). This is O(1).

The C# compiler uses a similar approach, except that it can assemble a hash table.


问:
How to get a direct download URL from Google Picker JavaScript API?
I'm trying to get a direct download URL for a file using Google's Picker API so that I can choose a file and pass this URL to server side code to download and store a copy of the item on the server.

I'm able to authorize through the picker API and get info of a picked file including the file name and preview URL (which is confusingly referred to as simply "A URL to this item" in the JSON response docs: https://developers.google.com/picker/docs/results)

I noticed that there is a post about using the Drive API to get a direct download URL here: Get google drive file download URL

However when I do this in my picker callback function (based on the docs here: https://developers.google.com/picker/docs/)

I get an error of:

```<code> "Project [number here] is not found and cannot be used for API calls. If it is recently created, enable Drive API by visiting https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=[project number here] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
</code>```

I have the API enabled in my developer console and the URL added to the JS allowed origins.

The documentation is very confusing and there seems to be 3 versions of the REST API to use with Drive which is based on an gapi.auth2 object whereas the picker api uses gapi.auth object.

I'm not sure if I need to authenticate again using the Google Drive API before performing the GET request. This all seems very messy and I believe there must be an easier approach for what is a simple request!

My picker callback function:

```<code>  pickerCallback: function(data) {
    if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
      var doc = data[google.picker.Response.DOCUMENTS][0];
      var fileName = doc[google.picker.Document.NAME];
      var url = doc[google.picker.Document.URL];
      var docId = doc[google.picker.Document.ID];
      var request = null;

      gapi.client.load('drive', 'v2', function() {
        request = gapi.client.drive.files.get({
          'fileId': docId
        });
        request.execute(function(resp){
          console.log(resp);
        });
      });

     //Write upload details to page
     //Populate hidden field
    }
</code>```

Developer console screen - The first app is the picker API the second is for the Drive API:

答:
You may want to try the simple callback implementation shown in this documentation. Notice that url was initialized before the if statement:

```<code>function pickerCallback(data) {
        var url = 'nothing';
        if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
          var doc = data[google.picker.Response.DOCUMENTS][0];
          url = doc[google.picker.Document.URL];
        }
        var message = 'You picked: ' + url;
        document.getElementById('result').innerHTML = message;
}
</code>```

Also, in authorizing, set the AppId value and choose the user account with the app's current OAuth 2.0 token. Note that the AppId set and the client ID used for authorizing access to a user's files must be contained in the same app. Then, after successfully obtaining the fileId, you can then send request using files.get. By default, this responds with a Files resource in the response body which includes downloadUrl.

For additional insights, see this related SO post.

Body:
I'm trying to get a direct download URL for a file using Google's Picker API so that I can choose a file and pass this URL to server side code to download and store a copy of the item on the server.

I'm able to authorize through the picker API and get info of a picked file including the file name and preview URL (which is confusingly referred to as simply "A URL to this item" in the JSON response docs: https://developers.google.com/picker/docs/results)

I noticed that there is a post about using the Drive API to get a direct download URL here: Get google drive file download URL

However when I do this in my picker callback function (based on the docs here: https://developers.google.com/picker/docs/)

I get an error of:

 "Project [number here] is not found and cannot be used for API calls. If it is recently created, enable Drive API by visiting https://console.developers.google.com/apis/api/drive.googleapis.com/overview?project=[project number here] then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."

I have the API enabled in my developer console and the URL added to the JS allowed origins.

The documentation is very confusing and there seems to be 3 versions of the REST API to use with Drive which is based on an gapi.auth2 object whereas the picker api uses gapi.auth object.

I'm not sure if I need to authenticate again using the Google Drive API before performing the GET request. This all seems very messy and I believe there must be an easier approach for what is a simple request!

My picker callback function:

  pickerCallback: function(data) {
    if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
      var doc = data[google.picker.Response.DOCUMENTS][0];
      var fileName = doc[google.picker.Document.NAME];
      var url = doc[google.picker.Document.URL];
      var docId = doc[google.picker.Document.ID];
      var request = null;

      gapi.client.load('drive', 'v2', function() {
        request = gapi.client.drive.files.get({
          'fileId': docId
        });
        request.execute(function(resp){
          console.log(resp);
        });
      });

     //Write upload details to page
     //Populate hidden field
    }

Developer console screen - The first app is the picker API the second is for the Drive API:

Body:
You may want to try the simple callback implementation shown in this documentation. Notice that url was initialized before the if statement:

function pickerCallback(data) {
        var url = 'nothing';
        if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
          var doc = data[google.picker.Response.DOCUMENTS][0];
          url = doc[google.picker.Document.URL];
        }
        var message = 'You picked: ' + url;
        document.getElementById('result').innerHTML = message;
}

Also, in authorizing, set the AppId value and choose the user account with the app's current OAuth 2.0 token. Note that the AppId set and the client ID used for authorizing access to a user's files must be contained in the same app. Then, after successfully obtaining the fileId, you can then send request using files.get. By default, this responds with a Files resource in the response body which includes downloadUrl.

For additional insights, see this related SO post.


问:
android SQLite register won't save data
I'm trying to make simple android SQLite register but when i try to save data the app crash

Database code:

```<code>public class RegistrationDB extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "registration.db";
    private static final String TABLE_NAME = "profile";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_EMAIL = "email";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";

    private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT, " + ")";

    private String DROP_TAPLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public RegistrationDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL(DROP_TAPLE);
        onCreate(sqLiteDatabase);

    }

    public long addUser(String email, String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COLUMN_EMAIL, email); // Email
        values.put(COLUMN_USERNAME, username); // username
        values.put(COLUMN_PASSWORD, password); // password

        // Inserting Row
//        long id = db.insert(TABLE_NAME, null, values);
        db.insert(TABLE_NAME, null, values);
        db.close(); // Closing database connection
        return 0;
    }

}
</code>```

I'm sorry but I get error when I try to type code here that's why I use image

答:
I think there is problem in your query of create table:

COLUMN_PASSWORD + " TEXT, " + ")";

there should not be a comma "," after TEXT if its the end of the query.
Remove that comma.
Try if it works.

Title: android SQLite register won't save data

Body:
I'm trying to make simple android SQLite register but when i try to save data the app crash

Database code:

public class RegistrationDB extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "registration.db";
    private static final String TABLE_NAME = "profile";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_EMAIL = "email";
    private static final String COLUMN_USERNAME = "username";
    private static final String COLUMN_PASSWORD = "password";

    private static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_USERNAME + " TEXT, "+
                    COLUMN_EMAIL + " TEXT, " +
                    COLUMN_PASSWORD + " TEXT, " + ")";

    private String DROP_TAPLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

    public RegistrationDB(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        sqLiteDatabase.execSQL(DROP_TAPLE);
        onCreate(sqLiteDatabase);

    }

    public long addUser(String email, String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COLUMN_EMAIL, email); // Email
        values.put(COLUMN_USERNAME, username); // username
        values.put(COLUMN_PASSWORD, password); // password

        // Inserting Row
//        long id = db.insert(TABLE_NAME, null, values);
        db.insert(TABLE_NAME, null, values);
        db.close(); // Closing database connection
        return 0;
    }

}

I'm sorry but I get error when I try to type code here that's why I use image


问:
only allow specific URL to access my sites
i need a code written in any language, which is secure and only allow a specific url to be mypage's refferer url. you can use passwords, cookies and anything you want but at last, the page only viewable when coming from a specific URL.(edited:)i-want-the-complete-code-to-copy-and-paste, then i will learn it slowly in the future by modifying and improving your provided code.</p>

答:
Try using HTTP_REFERER which return the address of the page which referred to the user agent. Example:

```<code>if ($_SERVER['HTTP_REFERER']  !== "ACCESSABLE_URL_HERE") {
    // do something you want
}
</code>```

Body:
Try using HTTP_REFERER which return the address of the page which referred to the user agent. Example:

if ($_SERVER['HTTP_REFERER']  !== "ACCESSABLE_URL_HERE") {
    // do something you want
}


问:
JMETER jp@gc - WebDriver Sampler
I would like to know how to run jmeter - webdriver sampler by using chrome browser. Is there any new plugins need to be downloaded for chrome? And this is my sample script to open in chrome browser,

```<code>WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
WDS.sampleResult.sampleEnd()
</code>```

And I have configured jp@gc - Chrome Driver Config config element in my test plan.

答:
If you need to use Chrome browser you need to download ChromeDriver binary and drop it somewhere to your local disk.

Once done you need to specify the full path to the ChromeDriver executable under Chrome Driver Config like:

This way you should be able to integrate WebDriver and Chrome with JMeter.

See The WebDriver Sampler: Your Top 10 Questions Answered for the most commonly asked questions regarding the WebDriver sampler solutions.

Title: JMETER jp@gc - WebDriver Sampler

Body:
I would like to know how to run jmeter - webdriver sampler by using chrome browser. Is there any new plugins need to be downloaded for chrome? And this is my sample script to open in chrome browser,

WDS.sampleResult.sampleStart()
WDS.browser.get('http://jmeter-plugins.org')
WDS.sampleResult.sampleEnd()

And I have configured jp@gc - Chrome Driver Config config element in my test plan.


问:
Android Studio configuration problems
I'm new in the android development world.
After Android Studio download I've tried to run my first HelloWorld.
But Android Studio give me any problem that I'm not understand how to solve.

In the first basic code in the class MainActivity.java

```<code>package com.example.elavora.helloworldandroid;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
   }
</code>```

To the override it tells me

"method does not override any method from its superclass".
   Is it a serious problem?

And when I try to run project , the console tells me

Error:A problem occurred configuring project ':app'.
  Could not resolve all dependencies for configuration ':app:_debugUnitTestApkCopy'.
  Could not resolve junit:junit:4.12.
       Required by:
           HelloWorldAndroid2:app:unspecified
  Could not resolve junit:junit:4.12.
  Could not get resource 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.pom'.
  Could not GET 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.pom'.
  Received fatal alert: access_denied

Can anyone help me?
thanks :)

答:
I had the same error, it appears to be simple proxy configuration in android studio, so in case you'r working under some organization proxy it might solve your problem.
go to File->settings->HTTP Proxy and setup your proxy properly. </p>

Title: Android Studio configuration problems

Body:
I'm new in the android development world.
After Android Studio download I've tried to run my first HelloWorld.
But Android Studio give me any problem that I'm not understand how to solve.

In the first basic code in the class MainActivity.java

package com.example.elavora.helloworldandroid;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

    public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
   }

To the override it tells me

"method does not override any method from its superclass".
   Is it a serious problem?

And when I try to run project , the console tells me

Error:A problem occurred configuring project ':app'.
  Could not resolve all dependencies for configuration ':app:_debugUnitTestApkCopy'.
  Could not resolve junit:junit:4.12.
       Required by:
           HelloWorldAndroid2:app:unspecified
  Could not resolve junit:junit:4.12.
  Could not get resource 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.pom'.
  Could not GET 'https://jcenter.bintray.com/junit/junit/4.12/junit-4.12.pom'.
  Received fatal alert: access_denied

Can anyone help me?
thanks :)


问:
How do i access the object created inside constructor?
I want to create an array for each object i create, but i cant get access to it. since its scope is within the constructor.

```<code>class Constructor{

Constructor(int vsl)
{
        int[] array = new int[vsl];
    }

}
</code>```

If i call this constructor by Constructor c = new Constructor(4);

how can i use array in my code?

Note: i want to specifically create the object inside the constructor and manipulate it using values i get from scanner object.

答:
You can not, that array is scoped and visible only inside of the constructor

what you have to do is declare that array as a member class and initialize it in the constructor:

```<code>class Constructor {
    private int[] array;
    Constructor(int vsl) {
        array = new int[vsl];
    }

}
</code>```

Body:
I want to create an array for each object i create, but i cant get access to it. since its scope is within the constructor.

class Constructor{

Constructor(int vsl)
{
        int[] array = new int[vsl];
    }

}

If i call this constructor by Constructor c = new Constructor(4);

how can i use array in my code?

Note: i want to specifically create the object inside the constructor and manipulate it using values i get from scanner object.

Body:
You can not, that array is scoped and visible only inside of the constructor

what you have to do is declare that array as a member class and initialize it in the constructor:

class Constructor {
    private int[] array;
    Constructor(int vsl) {
        array = new int[vsl];
    }

}


问:
I am getting error Unfortunately app has stopped.Where is the mistake?
These are the sections of code mentioned.As I run these errors pop up in logcat file and the app crashes when opened.There are so many of them that I could not figure out where the actual mistake is.Please Help me out where there is need of modification and replacement as I am trying to build a splash screen.

logcat:

```<code>06-08 11:36:18.203 17265-17265/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.elvero.telecom.voipapp, PID: 17265
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elvero.telecom.voipapp/com.elvero.telecom.voipapp.splash}: android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:182)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1515)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                    Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                       at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                       at com.elvero.telecom.voipapp.splash.onCreate(splash.java:13)
                                                       at android.app.Activity.performCreate(Activity.java:6092)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2514)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:182)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1515)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                    Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x6
                                                       at android.content.res.TypedArray.getDimensionPixelOffset(TypedArray.java:533)
                                                       at android.view.View.<init>(View.java:3927)
                                                       at android.widget.ImageView.<init>(ImageView.java:139)
                                                       at android.widget.ImageView.<init>(ImageView.java:135)
                                                       at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                       at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                       at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                       at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                       at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                       at com.elvero.telecom.voipapp.splash.onCreate(splash.java:13)
                                                       at android.app.Activity.performCreate(Activity.java:6092)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2514)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:182)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1515)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
06-08 11:36:22.207 17265-17265/? I/Process: Sending signal. PID: 17265 SIG: 9
</code>```

MainActivity.java:

```<code>package com.elvero.telecom.voipapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar= (Toolbar)findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

    }
}
</code>```

AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.elvero.telecom.voipapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">

        </activity>

        <activity android:name=".splash">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

splashactivity:

```<code>  <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        tools:context="com.elvero.telecom.voipapp.splash">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:background="@android:color/holo_blue_light"
            android:elevation="@android:dimen/dialog_min_width_minor"
            android:scaleType="fitCenter"
            android:src="@drawable/logo_elvero"/>
        </RelativeLayout>
</code>```

Splash.java:

```<code>package com.elvero.telecom.voipapp;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class splash extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        Handler handler=new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run(){
                startActivity(new Intent(splash.this,MainActivity.class));
                finish();

            }
        },1000);
    }
}
</code>```

答:
error caused because code

```<code>android:elevation="@android:dimen/dialog_min_width_minor"
</code>```

its better to give direct value to it like

```<code>android:elevation="5dp"
</code>```

Body:
These are the sections of code mentioned.As I run these errors pop up in logcat file and the app crashes when opened.There are so many of them that I could not figure out where the actual mistake is.Please Help me out where there is need of modification and replacement as I am trying to build a splash screen.

logcat:

06-08 11:36:18.203 17265-17265/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.elvero.telecom.voipapp, PID: 17265
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.elvero.telecom.voipapp/com.elvero.telecom.voipapp.splash}: android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:182)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1515)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                    Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class ImageView
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                       at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                       at com.elvero.telecom.voipapp.splash.onCreate(splash.java:13)
                                                       at android.app.Activity.performCreate(Activity.java:6092)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2514)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:182)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1515)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                    Caused by: java.lang.UnsupportedOperationException: Can't convert to dimension: type=0x6
                                                       at android.content.res.TypedArray.getDimensionPixelOffset(TypedArray.java:533)
                                                       at android.view.View.<init>(View.java:3927)
                                                       at android.widget.ImageView.<init>(ImageView.java:139)
                                                       at android.widget.ImageView.<init>(ImageView.java:135)
                                                       at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:60)
                                                       at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:56)
                                                       at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1029)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1087)
                                                       at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:47)
                                                       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:725)
                                                       at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
                                                       at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
                                                       at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                       at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                       at com.elvero.telecom.voipapp.splash.onCreate(splash.java:13)
                                                       at android.app.Activity.performCreate(Activity.java:6092)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2514)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2641)
                                                       at android.app.ActivityThread.access$800(ActivityThread.java:182)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1515)
                                                       at android.os.Handler.dispatchMessage(Handler.java:111)
                                                       at android.os.Looper.loop(Looper.java:194)
                                                       at android.app.ActivityThread.main(ActivityThread.java:5717)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at java.lang.reflect.Method.invoke(Method.java:372)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
06-08 11:36:22.207 17265-17265/? I/Process: Sending signal. PID: 17265 SIG: 9

MainActivity.java:

package com.elvero.telecom.voipapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.ActionBarActivity;

public class MainActivity extends AppCompatActivity {
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar= (Toolbar)findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

    }
}

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.elvero.telecom.voipapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">

        </activity>

        <activity android:name=".splash">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

splashactivity:

  <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        tools:context="com.elvero.telecom.voipapp.splash">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:background="@android:color/holo_blue_light"
            android:elevation="@android:dimen/dialog_min_width_minor"
            android:scaleType="fitCenter"
            android:src="@drawable/logo_elvero"/>
        </RelativeLayout>

Splash.java:

package com.elvero.telecom.voipapp;

import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class splash extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        Handler handler=new Handler();
        handler.postDelayed(new Runnable(){
            @Override
            public void run(){
                startActivity(new Intent(splash.this,MainActivity.class));
                finish();

            }
        },1000);
    }
}

Body:
error caused because code

android:elevation="@android:dimen/dialog_min_width_minor"

its better to give direct value to it like

android:elevation="5dp"


问:
How to find duplicate values while importing excel and displays an error message on the same table where imported data displays?
I am using MVC with C#, I am trying to import an excel sheet and validate those sheet and displays the excel data along with error message on one column in a table. If got any error my selection checkbox will not available, so the user cannot select and save the particular record. my page is actually working. What is my issue right now is, I wanna add Unique id validation. which means I have one Id column, where I don't want duplicate value. I added validation to check with my table and if found any same id, it returns an error message. but, if let say, user upload duplicate values on the excel sheet when they upload means, how to find out while uploading and how to prevent them from adding duplicate id records.

my sample coding below.

```<code>if (theFile != null && theFile.ContentLength > 0)
{
    try
    {
        string[,] data = ExportUtil.GetData(theFile);

        int rowValue = data.GetLength(0);
        int colValue = data.GetLength(1);

        Info _I;
        ViewModel _VM;

        for (int i = 0; i < rowValue; i++)
        {

            _VM= new ViewModel();
           // _VM.Id = i;
            _VM.Id = data[i, 0].ToString() != null ? data[i, 0].ToString() : "";
            _VM.Description = data[i, 1].ToString() != null ? data[i, 1].ToString() : "";

            if (string.IsNullOrWhiteSpace(_VM.Id))
            {
                _VM.Message = "Id cannot be empty" + System.Environment.NewLine;
            }
            _ID = TagInfo.Where(a => !string.IsNullOrEmpty(_VM.Id) && a.Id.ToUpper() == _VM.Id.ToUpper()).FirstOrDefault();
            if (_ID != null)
            {
                _VM.Message += "Duplicate ID" + System.Environment.NewLine;
                _ID =null;
            }
            if (string.IsNullOrEmpty(_VM.Description))
            {
                _VM.Message += "Description cannot be empty" + System.Environment.NewLine;
            }

            if (!string.IsNullOrEmpty(_VM.Message))
            {
                _VM.Message = string.Format("{0}{1}", "Row Number " + (i + 1) + " has " + Environment.NewLine, _VM.Message);

            }

            listvm.Add(_VM);

        }

        TempData["ID_DOWNLOAD"] = listvm;

    }
}
</code>```

_ID I declared with table name TableID _ID; above the try block. kindly help.

答:
Add your unique ID to a list of int then find duplicate ids in that list by linq

```<code>var duplicateKeys = list.GroupBy(x => x)
                        .Where(group => group.Count() > 1)
                        .Select(group => group.Key);
</code>```

if duplicateKeys count is greater than 1 then you know there are some IDs duplicated.

Body:
I am using MVC with C#, I am trying to import an excel sheet and validate those sheet and displays the excel data along with error message on one column in a table. If got any error my selection checkbox will not available, so the user cannot select and save the particular record. my page is actually working. What is my issue right now is, I wanna add Unique id validation. which means I have one Id column, where I don't want duplicate value. I added validation to check with my table and if found any same id, it returns an error message. but, if let say, user upload duplicate values on the excel sheet when they upload means, how to find out while uploading and how to prevent them from adding duplicate id records.

my sample coding below.

if (theFile != null && theFile.ContentLength > 0)
{
    try
    {
        string[,] data = ExportUtil.GetData(theFile);

        int rowValue = data.GetLength(0);
        int colValue = data.GetLength(1);

        Info _I;
        ViewModel _VM;

        for (int i = 0; i < rowValue; i++)
        {

            _VM= new ViewModel();
           // _VM.Id = i;
            _VM.Id = data[i, 0].ToString() != null ? data[i, 0].ToString() : "";
            _VM.Description = data[i, 1].ToString() != null ? data[i, 1].ToString() : "";

            if (string.IsNullOrWhiteSpace(_VM.Id))
            {
                _VM.Message = "Id cannot be empty" + System.Environment.NewLine;
            }
            _ID = TagInfo.Where(a => !string.IsNullOrEmpty(_VM.Id) && a.Id.ToUpper() == _VM.Id.ToUpper()).FirstOrDefault();
            if (_ID != null)
            {
                _VM.Message += "Duplicate ID" + System.Environment.NewLine;
                _ID =null;
            }
            if (string.IsNullOrEmpty(_VM.Description))
            {
                _VM.Message += "Description cannot be empty" + System.Environment.NewLine;
            }

            if (!string.IsNullOrEmpty(_VM.Message))
            {
                _VM.Message = string.Format("{0}{1}", "Row Number " + (i + 1) + " has " + Environment.NewLine, _VM.Message);

            }

            listvm.Add(_VM);

        }

        TempData["ID_DOWNLOAD"] = listvm;

    }
}

_ID I declared with table name TableID _ID; above the try block. kindly help.

Body:
Add your unique ID to a list of int then find duplicate ids in that list by linq

var duplicateKeys = list.GroupBy(x => x)
                        .Where(group => group.Count() > 1)
                        .Select(group => group.Key);

if duplicateKeys count is greater than 1 then you know there are some IDs duplicated.


问:
$interval not running, angularjs
I'm not sure why this code isn't running.  I'm trying to set up a simple counter that increases every second using angulars $interval wrapper.</p>

```<code>angular.module('app').controller('testController', function($scope, $interval){
  var set_counter = function(){
    var start_time = new Date(2014, 09, 02, 0,0,0,0).getTime()
    var time_counter = new Date().getTime()
    $scope.counter = Math.ceil(time_counter / 1000000 + ((time_counter / 1000 - start_time / 1000) * 0.5)).toLocaleString();
    console.log($scope.counter);
  }
  $interval(set_counter(), 1000);
});
</code>```

答:
The issue is in on that line

```<code>$interval(set_counter(), 1000);
</code>```

you are calling the "set_counter" right away not passing it to "$interval" as a callback.

Fix:

```<code>$interval(set_counter, 1000);
</code>```

Title: $interval not running, angularjs

Body:
I'm not sure why this code isn't running.  I'm trying to set up a simple counter that increases every second using angulars $interval wrapper.

angular.module('app').controller('testController', function($scope, $interval){
  var set_counter = function(){
    var start_time = new Date(2014, 09, 02, 0,0,0,0).getTime()
    var time_counter = new Date().getTime()
    $scope.counter = Math.ceil(time_counter / 1000000 + ((time_counter / 1000 - start_time / 1000) * 0.5)).toLocaleString();
    console.log($scope.counter);
  }
  $interval(set_counter(), 1000);
});

Body:
The issue is in on that line

$interval(set_counter(), 1000);

you are calling the "set_counter" right away not passing it to "$interval" as a callback.

Fix:

$interval(set_counter, 1000);


问:
Silent push notifications only delivered if device is charging and/or app is foreground
I have implemented silent push notifications but I have noticed some strange behaviour.  The silent push notifications are handled via:

```<code>- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
</code>```

The silent push messages only seem to be received if the device is charging (ie cable connected) and/or if my app is foreground.

If I disconnect the device from the charger (or Mac) then the silent push notifications are no longer received unless the app is foreground.

I get non-silent push notifications normally in both cases.

If I plug in the USB cable again, then I get the expected behaviour and silent push notifications are received irrespective of whether the app is foreground or background.

I am using UILocalNotification so I know what is being received.

The fact that it all works fine with the device connected suggests that my silent pushes notifications are configured correctly and that the app has the correct background modes set in the plist etc.

This behaviour is repeatable on iPhone 5s, 6 and iPad 2 all running either IOS 8 or 8.1.

Has anyone else experienced this?  It should be easy to reproduce.  Why should the simple act of plugging a device into a charger change the ability to receive silent push notifications?

答: I hope you are using APNS delivering priority as "CONSERVE_POWER" (5), try to change it as "IMMEDIATE" (10)

Body:
I have implemented silent push notifications but I have noticed some strange behaviour.  The silent push notifications are handled via:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

The silent push messages only seem to be received if the device is charging (ie cable connected) and/or if my app is foreground.

If I disconnect the device from the charger (or Mac) then the silent push notifications are no longer received unless the app is foreground.

I get non-silent push notifications normally in both cases.

If I plug in the USB cable again, then I get the expected behaviour and silent push notifications are received irrespective of whether the app is foreground or background.

I am using UILocalNotification so I know what is being received.

The fact that it all works fine with the device connected suggests that my silent pushes notifications are configured correctly and that the app has the correct background modes set in the plist etc.

This behaviour is repeatable on iPhone 5s, 6 and iPad 2 all running either IOS 8 or 8.1.

Has anyone else experienced this?  It should be easy to reproduce.  Why should the simple act of plugging a device into a charger change the ability to receive silent push notifications?


答:
The worst case might be O(n), but at least for languages like C/C++, Java and C# where the cases are compile-time constants, a jump table can often be used (and quite often is used) to get the complexity to O(1).

I don't know if the more dynamic languages like PHP or Javascript try to set up jump tables or not.

Title: What is the runtime complexity of a switch statement?

Body:
I'd like to know what the worst-case runtime complexity of a switch statement is, assuming you have n cases.

I always assumed it was O(n). I don't know if compilers do anything clever, though. If the answer is implementation-specific, I'd like to know for the following languages:

Java

C/C++

C#

PHP

Javascript


问:
Validate mobile number into 10 digit numbers in php jquery
I am trying to validate phone number jquery when alphabets are pressed it as to display error message. Below code takes enters digits but doesnt validate to 10 digits. How to validate to 10 digit number. </p>

```<code><script type="text/javascript" >
 $(function() {
   $("#phno").bind("keypress", function (event) {
                if (event.charCode != 0) {
                       var regex = new RegExp("^[0-9]{10}$");
                    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                    if (!regex.test(key)) {
                      alert("Please enter valid Student Phone No");
                        event.preventDefault();
                        return false;
                    }
                }
            });
 });
</code>```

答:
Just use this jquery function and restrict only ten digits in your html code as

```<code><input type="text" name="phone" maxlength="10" id="phone"/>
</code>```

and use this below jquery function

```<code>$("#phone").bind("keypress", function (event) {
    var phoneno = /^\d{10}$/;
    var phone_val=$('#phone').val();
    if((phoneno.test(phone_val)))
    {
     return true;
    }
    else
    {
     return false;
    }
});
</code>```

Body:
Just use this jquery function and restrict only ten digits in your html code as

<input type="text" name="phone" maxlength="10" id="phone"/>

and use this below jquery function

$("#phone").bind("keypress", function (event) {
    var phoneno = /^\d{10}$/;
    var phone_val=$('#phone').val();
    if((phoneno.test(phone_val)))
    {
     return true;
    }
    else
    {
     return false;
    }
});


问:
Node.js unable to display the text file from a link on webpage
I am trying to display the link to a text file on the local machine using node.js. While, the file is being read properly, the link is not working. It says, "FILE NOT FOUND".

Snippet of code:

```<code>file = (doc[0].filename)
fs = require('fs');
var varname ='/home/mingupta/test/public/coords/'+file;
var varname1 = '/home/mingupta/test/public/coords/'+file;

fs.readFile(varname,'utf8',function(err,data){
    if(err) console.log(err);
    else{
        res.send('<a href=\"'+varname1+'\">'+file+'<\a>'+'<br>'+'Contents:'+'<br>'+data);
    }
}
</code>```

What changes are to be made in the file path?

答:
If you open your developer tools you will find a message in the console says

Not allowed to load local resource: file:///...

If you need to allow loading local resources try the following comands

You need to use both arguments. This is how I run it on my mac.

open -a Google\ Chrome --args --disable-web-security
  -–allow-file-access-from-files

This is how it should be for windows:

"C:\PathTo\Chrome.exe" –allow-file-access-from-files
  -disable-web-security

It is not the best approach here, you have to make a real URL for your files to be served over the internet then your click will work properly.

Body:
I am trying to display the link to a text file on the local machine using node.js. While, the file is being read properly, the link is not working. It says, "FILE NOT FOUND".

Snippet of code:

file = (doc[0].filename)
fs = require('fs');
var varname ='/home/mingupta/test/public/coords/'+file;
var varname1 = '/home/mingupta/test/public/coords/'+file;

fs.readFile(varname,'utf8',function(err,data){
    if(err) console.log(err);
    else{
        res.send(''+file+'<\a>'+'
'+'Contents:'+'
'+data);
    }
}

What changes are to be made in the file path?


问:
How to arrange array spirally but anticlockwise - Javascript
```<code>var sampleArray = [[1,2,3,4],
                  [5,6,7,8],
                  [9,10,11,12],
                  [13,14,15,16],
                  [17,18,19,20]
                  ];

function printSpiral(myArray, clockwise) {
  //anti-clockwise:
  //1,5,9,13,17, 18,19,20, 16,12,8,4, 3,2, 6,10,14, 15,11,7

   if(!clockwise) {

     myArray = transpose(myArray)

     //console.log(myArray)
  }

  var rows = myArray.length;

  var cols = myArray[0].length;
  if(rows <= 1) {
    return myArray[0];
  }

  if(cols === 0) {
    return myArray[0];
  }

      var firstRow = myArray[0];
      var newMatrix = [];
      var newRow;
      var rowIdx;
      var colIdx = myArray[1].length - 1;

  for(colIdx; colIdx >=0; colIdx--) {

      newRow = [];

     for(rowIdx = 1; rowIdx < rows; rowIdx++) {
       newRow.push(myArray[rowIdx][colIdx])
       //console.log(newRow)
     }

    newMatrix.push(newRow)
  }

  //console.log(newMatrix)

  firstRow.push.apply(firstRow,printSpiral(newMatrix));

  //console.log(firstRow)

  return firstRow

  //return newMatrix

  // Spiral Order
  // 1,2,3,4, 8,12,16,20, 19,18,17, 13,9,5, 6,7, 11,15, 14, 10

}

var result = printSpiral(sampleArray, false);

console.log(result)
</code>```

I am trying to print the array spirally but anticlockwise. I have tried to transpose the matrix but it doesn't help how do I print the following array.

//1,5,9,13,17, 18,19,20, 16,12,8,4, 3,2, 6,10,14, 15,11,7

Please help

答:
Its not very elegant, but here's the juiste of the algorithm:

```<code><script>
var array = [[1,2,3,4],
             [5,6,7,8],
             [9,10,11,12],
             [13,14,15,16],
             [17,18,19,20]];

function spiral(array) {
    var list = [];

    var array = array[0].map(function(col, i) {
        return array.map(function(row) {
            return row[i]
        })
    });

    list.push(array[0]);
    array.shift()

    while (typeof array[0] !== 'undefined'){

        var array = array[0].map(function(col, i) {
            return array.map(function(row) {
                return row[i]
            })
        });

        array.reverse();
        list.push(array[0]);
        array.shift();
    }
    return list
}

var list = spiral(array)
document.writeln(list);
</script>
</code>```

basically the idea is as follows, a rotate 90 degrees counterclockwise is done with a transpose and flip. then we pop the top row, and do it again.
so we transpose the array, array.reverse to flip it, push our row into a list, array.shift to pop the row, repeat.

Also the main benefit of this method is that it wont care what the dimensions of your array are. they can be asymmetric or not.

Body:
var sampleArray = [[1,2,3,4],
                  [5,6,7,8],
                  [9,10,11,12],
                  [13,14,15,16],
                  [17,18,19,20]
                  ];

function printSpiral(myArray, clockwise) {
  //anti-clockwise:
  //1,5,9,13,17, 18,19,20, 16,12,8,4, 3,2, 6,10,14, 15,11,7

   if(!clockwise) {

     myArray = transpose(myArray)

     //console.log(myArray)
  }

  var rows = myArray.length;

  var cols = myArray[0].length;
  if(rows <= 1) {
    return myArray[0];
  }

  if(cols === 0) {
    return myArray[0];
  }

      var firstRow = myArray[0];
      var newMatrix = [];
      var newRow;
      var rowIdx;
      var colIdx = myArray[1].length - 1;

  for(colIdx; colIdx >=0; colIdx--) {

      newRow = [];

     for(rowIdx = 1; rowIdx < rows; rowIdx++) {
       newRow.push(myArray[rowIdx][colIdx])
       //console.log(newRow)
     }

    newMatrix.push(newRow)
  }

  //console.log(newMatrix)

  firstRow.push.apply(firstRow,printSpiral(newMatrix));

  //console.log(firstRow)

  return firstRow

  //return newMatrix

  // Spiral Order
  // 1,2,3,4, 8,12,16,20, 19,18,17, 13,9,5, 6,7, 11,15, 14, 10

}

var result = printSpiral(sampleArray, false);

console.log(result)

I am trying to print the array spirally but anticlockwise. I have tried to transpose the matrix but it doesn't help how do I print the following array.

//1,5,9,13,17, 18,19,20, 16,12,8,4, 3,2, 6,10,14, 15,11,7

Please help

Body:
Its not very elegant, but here's the juiste of the algorithm:

<script>
var array = [[1,2,3,4],
             [5,6,7,8],
             [9,10,11,12],
             [13,14,15,16],
             [17,18,19,20]];

function spiral(array) {
    var list = [];

    var array = array[0].map(function(col, i) {
        return array.map(function(row) {
            return row[i]
        })
    });

    list.push(array[0]);
    array.shift()

    while (typeof array[0] !== 'undefined'){

        var array = array[0].map(function(col, i) {
            return array.map(function(row) {
                return row[i]
            })
        });

        array.reverse();
        list.push(array[0]);
        array.shift();
    }
    return list
}

var list = spiral(array)
document.writeln(list);
</script>

basically the idea is as follows, a rotate 90 degrees counterclockwise is done with a transpose and flip. then we pop the top row, and do it again.
so we transpose the array, array.reverse to flip it, push our row into a list, array.shift to pop the row, repeat.

Also the main benefit of this method is that it wont care what the dimensions of your array are. they can be asymmetric or not.


问:
Why doesn't it work when I hover on the image?
I'm sure this is incredibly stupid once I get a hint, but I can't see why the hover doesn't work. I added the jQuery just to check whether or not it works with a click.

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover .popover {
  opacity: 1;
}</code>```

      Bla bla

```

答:
Try changing classes into id´s and than make hover.

JSFiddle link

```<code>#figure:hover + #popover {
   opacity:1;
}
</code>```

Body:
I'm sure this is incredibly stupid once I get a hint, but I can't see why the hover doesn't work. I added the jQuery just to check whether or not it works with a click.

$(document).on("click", ".figure", function() {
  $(".popover").css("opacity", "1");
})

.container {
  position: relative;
}

.popover {
  background-color: blue;
  position: absolute;
  top: 0;
  left: 200px;
  opacity: 0;
  transition: opacity 0.5s ease-in-out 0s;
}

.figure:hover .popover {
  opacity: 1;
}

      Bla bla

Body:
Try changing classes into id´s and than make hover.

JSFiddle link

#figure:hover + #popover {
   opacity:1;
}


问:
Create a bookmark between 2 different views in MVC
I have two views; Index and Giftworx. In the Index I have icons and when each is clicked it should direct user to a specific point in the GiftWorx page. I've tried the below code  but it didnt work. Any help would be appreciated.

Index View:

                            @*

*@

Who uses GiftWorx

See who uses GiftWorx and more.

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

<p>GiftWorxView</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="why-convertible-box" id="GiftWorxUsers">
    <div class="container" id="GiftWorxUsers">
        <h1>Who uses GiftWorx<i class="fa fa-question-circle"></i></h1>
    </div>
</div>
<div class="hoc container clear" id="GiftWorxUsers">
    <div class="row">
        <div class="col-md-2" style="padding: 2px;">
            <div style="border: lightgrey solid thin; border-radius: 2px">
                <img class="img-responsive" style="height:auto;" src="~/Content/myTemplate/Logos/1.jpg" />
            </div>
        </div>
        <div class="col-md-2" style="padding: 2px;">
            <div style="border: lightgrey solid thin; border-radius: 2px">
                <img class="img-responsive" src="~/Content/myTemplate/Logos/17.jpg" />
            </div>
        </div>
        <div class="col-md-2" style="padding: 2px;">
            <div style="border: lightgrey solid thin; border-radius: 2px">
                <img class="img-responsive" src="~/Content/myTemplate/Logos/15.jpg" />
            </div>
        </div></code>```

答:
This is a little bit tricky but should work fine. First I declare the variable with concatenated section of your page:

```<code>@{
    var strLink = Url.Action("GiftWorxUsers", "GiftWorx") + "#GiftworxArea";
}
</code>```

Then on your Index View, put this on your a href link:

```<code><div class="agile_feature_grid">
     <a href='@strLink'>
      <i class="fa fa-gift" aria-hidden="true">
      </i>
     Link text here
     </a>
</div>
</code>```

Make sure you have an area in your View of Giftworx which has a name in this example: Giftworx by adding this piece of code:

```<code><a name="GiftworxArea"></a>
<div class="col-md-4 w3_agileits_features_grid">
   //Other stuffs here
</div>
</code>```

Now when you click on that link, you will be directed on your page on that exact spot with a section name GiftworxArea.

Body:
I have two views; Index and Giftworx. In the Index I have icons and when each is clicked it should direct user to a specific point in the GiftWorx page. I've tried the below code  but it didnt work. Any help would be appreciated.

Index View:

                            @*

*@

Who uses GiftWorx

See who uses GiftWorx and more.

GiftWorxView

Who uses GiftWorx

Body:
This is a little bit tricky but should work fine. First I declare the variable with concatenated section of your page:

@{
    var strLink = Url.Action("GiftWorxUsers", "GiftWorx") + "#GiftworxArea";
}

Then on your Index View, put this on your a href link:

<div class="agile_feature_grid">
     <a href='@strLink'>
      <i class="fa fa-gift" aria-hidden="true">
      </i>
     Link text here
     </a>
</div>

Make sure you have an area in your View of Giftworx which has a name in this example: Giftworx by adding this piece of code:

<a name="GiftworxArea"></a>
<div class="col-md-4 w3_agileits_features_grid">
   //Other stuffs here
</div>

Now when you click on that link, you will be directed on your page on that exact spot with a section name GiftworxArea.


问:
nginx + php5-fpm.sock is not found
I have several subdomains, each with a socket:

In /etc/php5/fpm/pool.d/album.conf ::

```<code>user = album
group = album
listen = /var/run/php5-fpm-album.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
php_admin_value[disable_functions] = exec,passthru,shell_exec,system
php_admin_flag[allow_url_fopen] = off
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
chdir = /
</code>```

In /etc/php5/fpm/pool.d/www.conf ::

```<code>user = www-data
group = www-data
listen = /var/run/php5-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
</code>```

In /etc/nginx/nginx.conf ::

```<code>upstream php5-fpm-album-sock {
    server unix:/var/run/php5-fpm-album.sock;
}

server {
            ## Escucha en el puerto 80 (HTTP)
            listen 80;

            ## Raíz donde se encuentra la página Web
            root /srv/www/album/;

            ## Orden de prioridad de los archivos index
            index index.php index.html index.htm;

            server_name album.bichomen.com;
            access_log /srv/www/album/access.log;

                location ~ \.php$ {
                   root /srv/www/album;
                   try_files $uri =404;
                   fastcgi_split_path_info ^(.+\.php)(/.+)$;
                   fastcgi_pass php5-fpm-album-sock;
                   fastcgi_index index.php;
                   fastcgi_param SCRIPT_FILENAME
                   $document_root$fastcgi_script_name;
                   include fastcgi_params;
            }
    }
</code>```

The problem is to disbelieve the socket in /var/run/

Error in nginx.log:

```<code>1 connect() to unix:/var/run/php5-fpm-album.sock failed
(2: No such file or directory)
</code>```

Where is the problem? Thank you.

答: At the end restart the server and it works.</p>

Title: nginx + php5-fpm.sock is not found

Body:
I have several subdomains, each with a socket:

In /etc/php5/fpm/pool.d/album.conf ::

user = album
group = album
listen = /var/run/php5-fpm-album.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
php_admin_value[disable_functions] = exec,passthru,shell_exec,system
php_admin_flag[allow_url_fopen] = off
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
chdir = /

In /etc/php5/fpm/pool.d/www.conf ::

user = www-data
group = www-data
listen = /var/run/php5-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660

In /etc/nginx/nginx.conf ::

upstream php5-fpm-album-sock {
    server unix:/var/run/php5-fpm-album.sock;
}

server {
            ## Escucha en el puerto 80 (HTTP)
            listen 80;

            ## Raíz donde se encuentra la página Web
            root /srv/www/album/;

            ## Orden de prioridad de los archivos index
            index index.php index.html index.htm;

            server_name album.bichomen.com;
            access_log /srv/www/album/access.log;

                location ~ \.php$ {
                   root /srv/www/album;
                   try_files $uri =404;
                   fastcgi_split_path_info ^(.+\.php)(/.+)$;
                   fastcgi_pass php5-fpm-album-sock;
                   fastcgi_index index.php;
                   fastcgi_param SCRIPT_FILENAME
                   $document_root$fastcgi_script_name;
                   include fastcgi_params;
            }
    }

The problem is to disbelieve the socket in /var/run/

Error in nginx.log:

1 connect() to unix:/var/run/php5-fpm-album.sock failed
(2: No such file or directory)

Where is the problem? Thank you.


问:
replace column name with file name shell script
How to replace the 2nd column name in a .csv file with its corresponding file name for all files within a directory?
Does anyone know how to do this with shell scripting? sed or awk

input file name CDXV1.csv

```<code>Gene,RPKM(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638
</code>```

output file name CDXV1.csv (same)

```<code>Gene,CDXV1(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638
</code>```

Body:
How to replace the 2nd column name in a .csv file with its corresponding file name for all files within a directory?
Does anyone know how to do this with shell scripting? sed or awk

input file name CDXV1.csv

Gene,RPKM(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638

output file name CDXV1.csv (same)

Gene,CDXV1(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638

Body:
awk -F, -v OFS=,  'NR==1{split(FILENAME,a,".");split($2,b,"(");$2= a[1] "(" b[2]}1' CDXV1.csv
Gene,CDXV1(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638

If your awk support inplace replacement then use -i inplace :

awk -i inplace -F, -v OFS=,  'NR==1{split(FILENAME,a,".");split($2,b,"(");$2= a[1] "(" b[2]}1' *.csv


问:
Camera permission is not working on Marshmallow and above devices and crashes
Since I have made a flashlight application and it works properly on the device which have SDK 22 and below. But when I come to check on marshmallow and above devices, it doesn't run and crashes at the beginning only I asked for permission using following code but it doesn't seems to be working at all. here is my code for requesting permission of camera at run time. here is my code:

```<code>if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.CAMERA},
                    5);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]  permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 5) {
            if  (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Now user should be able to use camera
            }
            else {
                // Your app will not have this permission. Turn off all functions
                // if permission not granted it will force close the app

            }
        }
</code>```

I have tried in marshmallow, nougat devices but it doesnt ask for camera permission and i have to go through manually from setting-app-flashlight-permission-allow. can anyone help me please. Currently I am testing my app in Lineage os 7.1.1

答:
I also had the same problem but managed to fixed it. Here's my case (I don't know if its the same as yours but it's worth a try)

So I have this two activities namely: MainActivity, and FlashlightActivity.

I used to ask for camera permission explicitly in FlaslightActivity just before I tap the switch button but I forgot that I was checking if a user's phone has a camera in the onCreate() method. while I was asking for permission onClick of the switch button of the flashlight, in which that was after I checked if a user's phone has a camera. So what I did was to ask for the permission in my MainActivity just before I start FlashlightActivity.

```<code>flashBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(hasPermission()){
                Intent flashIntent = new Intent("FlashlightActivity");
                startActivity(flashIntent);
            }else{
                requestPermission();
            }
        }
    });
</code>```

So basically ask for the permission before you call any Camera related stuffs

Body:
Since I have made a flashlight application and it works properly on the device which have SDK 22 and below. But when I come to check on marshmallow and above devices, it doesn't run and crashes at the beginning only I asked for permission using following code but it doesn't seems to be working at all. here is my code for requesting permission of camera at run time. here is my code:

if( ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{android.Manifest.permission.CAMERA},
                    5);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]  permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 5) {
            if  (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Now user should be able to use camera
            }
            else {
                // Your app will not have this permission. Turn off all functions
                // if permission not granted it will force close the app

            }
        }

I have tried in marshmallow, nougat devices but it doesnt ask for camera permission and i have to go through manually from setting-app-flashlight-permission-allow. can anyone help me please. Currently I am testing my app in Lineage os 7.1.1

Body:
I also had the same problem but managed to fixed it. Here's my case (I don't know if its the same as yours but it's worth a try)

So I have this two activities namely: MainActivity, and FlashlightActivity.

I used to ask for camera permission explicitly in FlaslightActivity just before I tap the switch button but I forgot that I was checking if a user's phone has a camera in the onCreate() method. while I was asking for permission onClick of the switch button of the flashlight, in which that was after I checked if a user's phone has a camera. So what I did was to ask for the permission in my MainActivity just before I start FlashlightActivity.

flashBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(hasPermission()){
                Intent flashIntent = new Intent("FlashlightActivity");
                startActivity(flashIntent);
            }else{
                requestPermission();
            }
        }
    });

So basically ask for the permission before you call any Camera related stuffs


问:
What does "while True" mean in Python?
```<code>def play_game(word_list):
    hand = deal_hand(HAND_SIZE) # random init
    while True:
        cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        if cmd == 'n':
            hand = deal_hand(HAND_SIZE)
            play_hand(hand.copy(), word_list)
            print
        elif cmd == 'r':
            play_hand(hand.copy(), word_list)
            print
        elif cmd == 'e':
            break
        else:
            print "Invalid command."
</code>```

While WHAT is True?

I reckon saying 'while true' is shorthand, but for what? While the variable 'hand' is being assigned a value? And what if the variable 'hand' is not being assigned a value?

答: Anything can be taken as True until the opposite is presented. This is the way duality works. It is a way that opposites are compared. Black can be True until white at which point it is False. Black can also be False until white at which point it is True. It is not a state but a comparison of opposite states. If either is True the other is wrong. True does not mean it is correct or is accepted. It is a state where the opposite is always False. It is duality.</p>

ContentLicense: CC BY-SA 4.0

Title: What does "while True" mean in Python?

Body:
def play_game(word_list):
    hand = deal_hand(HAND_SIZE) # random init
    while True:
        cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        if cmd == 'n':
            hand = deal_hand(HAND_SIZE)
            play_hand(hand.copy(), word_list)
            print
        elif cmd == 'r':
            play_hand(hand.copy(), word_list)
            print
        elif cmd == 'e':
            break
        else:
            print "Invalid command."

While WHAT is True?

I reckon saying 'while true' is shorthand, but for what? While the variable 'hand' is being assigned a value? And what if the variable 'hand' is not being assigned a value?