问:
Using Spark and R for trending detection in time series
I am new to both R and to Spark, but I am trying to create a scalable R application to detect increasing/decreasing query executed by users.

I have a Spark DataFrame containing data in the following format:

```<code>+-------+------------------------+-------------------------+
| user  |         query          |       query_time        |
+-------+------------------------+-------------------------+
| user1 | Hp tablet              | 2011-08-21T11:07:57.346 |
| user2 | Hp tablet              | 2011-08-21T22:22:32.599 |
| user3 | Hp tablet              | 2011-08-22T19:08:57.412 |
| user4 | hp laptop              | 2011-09-05T15:33:31.489 |
| user5 | Samsung LCD 550        | 2011-09-01T10:28:33.547 |
| user6 | memory stick           | 2011-09-06T17:15:42.852 |
| user7 | Castle                 | 2011-08-28T22:06:37.618 |
+-------+------------------------+-------------------------+
</code>```

This dataset has hundreds of thousand of rows. I need to be able to visualise somehow that, for example, "hp tablet" is trending up.

I have looked at some libraries (e.g. Breakout Detection, Anomaly Detection and this question) that could help me achieve this, but I do not know if they play well with Spark. And if they do, I couldn't find any examples on how to go about the programming.

I'm using R version 3.4.0 and SparkR version 2.1.0, running on a Zeppelin Notebook.

Does anyone have any ideas? I am also open to any other approaches.
Thank you!

Body:
I am new to both R and to Spark, but I am trying to create a scalable R application to detect increasing/decreasing query executed by users.

I have a Spark DataFrame containing data in the following format:

+-------+------------------------+-------------------------+
| user  |         query          |       query_time        |
+-------+------------------------+-------------------------+
| user1 | Hp tablet              | 2011-08-21T11:07:57.346 |
| user2 | Hp tablet              | 2011-08-21T22:22:32.599 |
| user3 | Hp tablet              | 2011-08-22T19:08:57.412 |
| user4 | hp laptop              | 2011-09-05T15:33:31.489 |
| user5 | Samsung LCD 550        | 2011-09-01T10:28:33.547 |
| user6 | memory stick           | 2011-09-06T17:15:42.852 |
| user7 | Castle                 | 2011-08-28T22:06:37.618 |
+-------+------------------------+-------------------------+

This dataset has hundreds of thousand of rows. I need to be able to visualise somehow that, for example, "hp tablet" is trending up.

I have looked at some libraries (e.g. Breakout Detection, Anomaly Detection and this question) that could help me achieve this, but I do not know if they play well with Spark. And if they do, I couldn't find any examples on how to go about the programming.

I'm using R version 3.4.0 and SparkR version 2.1.0, running on a Zeppelin Notebook.

Does anyone have any ideas? I am also open to any other approaches.
Thank you!

Body:
For using library(AnomalyDetection), the data should be in this format

head(raw_data)
                timestamp   count
14393 1980-10-05 13:53:00 149.801
14394 1980-10-05 13:54:00 151.492
14395 1980-10-05 13:55:00 151.724
14396 1980-10-05 13:56:00 153.776
14397 1980-10-05 13:57:00 150.481
14398 1980-10-05 13:58:00 146.638

if your query_time is X-axis how will you define Y-axis in numeric, and in 2011-08-21T11:07:57.346 what T means, is that time taken is 11:07:57.346. Need more clarification


来源: stackexchange

问:
How to create a custom route for show action in rails 5?
I have a model 'Item'. It all works fine, however am not completely satisfied with its show path. I want to use certain parameters from items table to construct a more SEO friendly url. So here is my question..

How can I change my Show action url
from
'mysite.com/items/1'
to
'mysite.com/items/item-name/item-city/item-id' where item-name, item-city, and item-id are dynamic for each specific item.

Is it possible to achieve this without a gem? if yes, how? If no, which gem would you suggest to achieve this in simplest way?

Thanks

答:
One approach to this problem is to use route globbing:

http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments

You should be able to do something like this:

```<code>get 'items/*names/:id', to: 'items#show', as: :item_names_path
</code>```

And put whatever you want in *names. This would take a little experimentation to get it right.  I might add a method to item to create the names array.

```<code>def names
  [city.name, name].uniq.compact
end
</code>```

Then I believe you would call item_names_path(@item.names, @item)

ContentLicense: CC BY-SA 3.0

Body:
One approach to this problem is to use route globbing:

http://guides.rubyonrails.org/routing.html#route-globbing-and-wildcard-segments

You should be able to do something like this:

get 'items/*names/:id', to: 'items#show', as: :item_names_path

And put whatever you want in *names. This would take a little experimentation to get it right.  I might add a method to item to create the names array.

def names
  [city.name, name].uniq.compact
end

Then I believe you would call item_names_path(@item.names, @item)


问:
Azure Powershell cmdlets fails
I have requirement to configure secondary interface on azure vm.For this we require Add-AzureNetworkInterfaceConfig cmdlets which is not recognized when i am executing the command.Could someone help me to install cmdlets on azure powershell.</p>

答: You can download the release you require from here AzurePowershell Release</p>

Title: Azure Powershell cmdlets fails


问:
Is it possible to configure embedded cassandra instance using properties file not the storage-conf.xml?
I'm lunching cassandra in embedded mode and want to configure seeds for its nodes in .property file. By default cassandra config contained in storage-conf.xml.</p>

答: No, it is not possible.</p>

ContentLicense: CC BY-SA 2.5

Body: No, it is not possible.


问:
How to query a child from another child. Firebase(SWIFT)
im developing a delivery app. So I have productos and popular products in firebase this way:

Products

PopularProducts(ID of the product as key and true as value)

How I can query only the products who are popular using those childs?

答:
You need to get array of productosPopulares and then get each object.

```<code>let referenceToProductosPopulares = FIRDatabase.database().reference(withPath: "productosPopulares")

referenceToProductosPopulares.observeSingleEvent(of: .value, with: { snapshot in
        if let value = snapshot.value as? NSDictionary {
           let productosPopIds = value.allKeys as! [String]
           // get every object
           for id in productosPopIds {
               let refToProd = FIRDatabase.database().reference(withPath: "productos").child(id)
               refToProd.observeSingleEvent(of: .value, with: { snapshot in
                   // your value
               })
           }
        } else {
          print("productosPopulares")
        }
     })
</code>```

Not perfect code. Should make more functions. But this is idea.

Hope it helps

Body:
You need to get array of productosPopulares and then get each object.

let referenceToProductosPopulares = FIRDatabase.database().reference(withPath: "productosPopulares")

referenceToProductosPopulares.observeSingleEvent(of: .value, with: { snapshot in
        if let value = snapshot.value as? NSDictionary {
           let productosPopIds = value.allKeys as! [String]
           // get every object
           for id in productosPopIds {
               let refToProd = FIRDatabase.database().reference(withPath: "productos").child(id)
               refToProd.observeSingleEvent(of: .value, with: { snapshot in
                   // your value
               })
           }
        } else {
          print("productosPopulares")
        }
     })

Not perfect code. Should make more functions. But this is idea.

Hope it helps


问:
How to read File using PDFReader
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

```<code>public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}
</code>```

答:
thanks for the update, I am using Itext5, below is the code snippet:

```<code>public void readFile(File inputFile, File outputFile){

    //i am reading the inputFile here

    PdfReader reader = new PdfReader(inputFile);

    //doing some logic to manipulate the pdf and then saving the pdf to outputFile

    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
}
</code>```

//Then calling the readFile method in main class

```<code>private File showDialogBox(){

    if(getSelectedFile() != null){
        File inputFile = jfc.getSelectedFile();
        //JFileChooser in java swing
        //The selected File name will be given by the user before exporting it.
        readFile(inputFile, outputFile);
    }
}
</code>```

Title: How to read File using PDFReader

Body:
I have a method public void readFile(File inputFile, File outputFile), I want to read the File using PDFReader, but the reader reads only String values, I cant hardcode the string value because it is given by the user while exporting the file.

I used FileUtils.readFileToString(inputFile) but I get exception on the line PdfReader reader = new PdfReader(input);

Kindly suggest a way to achieve this.

Code Snippet:

public void readFile(File inputFile, File outputFile){
String input = FileUtils.readFileToString(inputFile);
PdfReader reader = new PdfReader(input);

//some more code
}

Body:
thanks for the update, I am using Itext5, below is the code snippet:

public void readFile(File inputFile, File outputFile){

    //i am reading the inputFile here

    PdfReader reader = new PdfReader(inputFile);

    //doing some logic to manipulate the pdf and then saving the pdf to outputFile

    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
}

//Then calling the readFile method in main class

private File showDialogBox(){

    if(getSelectedFile() != null){
        File inputFile = jfc.getSelectedFile();
        //JFileChooser in java swing
        //The selected File name will be given by the user before exporting it.
        readFile(inputFile, outputFile);
    }
}


问:
aspnetcore.dll failed to load
I usually dev on a windows 7 desktop, using visual studio 2015 update 3.  I have the same vs2015.3 on my windows 10 laptop.  I copied an asp mvc 5 app I am working on to the laptop but it wont run when I try to launch it from VS.  I get the "aspnetcore.dll failed to load" error.  I looked around and most solutions are to repair the asp net core install, but my laptop does not have asp net core installed on it, because I don't use core yet.  My project is targeting .Net 4.6.

My desktop does have Core on it.  So do I have to install .net core just because? Or is there some other solution?  I am using the default IIS 10.

答:
Installing the recently released Anniversary Update (version 1607) of Windows 10 seems to destabilize IIS by shutting down Application Pools, thus resulting in a 503 error when trying to run an application, which is caused by some DLLs failing to load when the worker process starts.

Check out the Windows Event Viewer (Win+X, V) to see what you need to fix: Open "Windows Logs", then "Application" and look for "Error" level entries with the source "IIS-W3SVC-WP" (may be different if the name of your IIS instance is not the default one). In the details, you will see a short message, like this:

```<code>The Module DLL <path-to-DLL> failed to load.  The data is the error.
</code>```

Depending on your configuration, there may be different DLLs causing this kind of problem and they will occur one by one, so you will need to keep checking the Event Logs and fix the issues until your application properly starts up. To be sure, before every attempt, stop IIS and close IIS Manager.

Here are two specific issues we've experienced so far and how to fix them, but you may bump into completely different ones:

```<code>1."C:\WINDOWS\system32\inetsrv\rewrite.dll" (reference) ◦Go to "Programs and Features" (Win+X, F) and repair "IIS URL Rewrite Module 2".

2."C:\WINDOWS\system32\inetsrv\aspnetcore.dll" (reference) ◦Go to "Programs and Features" (Win+X, F) and repair "Microsoft .NET Core 1.0.0 - VS 2015 Tooling ...".
</code>```

Original source

Title: aspnetcore.dll failed to load

Body:
Installing the recently released Anniversary Update (version 1607) of Windows 10 seems to destabilize IIS by shutting down Application Pools, thus resulting in a 503 error when trying to run an application, which is caused by some DLLs failing to load when the worker process starts.

Check out the Windows Event Viewer (Win+X, V) to see what you need to fix: Open "Windows Logs", then "Application" and look for "Error" level entries with the source "IIS-W3SVC-WP" (may be different if the name of your IIS instance is not the default one). In the details, you will see a short message, like this:

The Module DLL <path-to-DLL> failed to load.  The data is the error.

Depending on your configuration, there may be different DLLs causing this kind of problem and they will occur one by one, so you will need to keep checking the Event Logs and fix the issues until your application properly starts up. To be sure, before every attempt, stop IIS and close IIS Manager.

Here are two specific issues we've experienced so far and how to fix them, but you may bump into completely different ones:

1."C:\WINDOWS\system32\inetsrv\rewrite.dll" (reference) ◦Go to "Programs and Features" (Win+X, F) and repair "IIS URL Rewrite Module 2".

2."C:\WINDOWS\system32\inetsrv\aspnetcore.dll" (reference) ◦Go to "Programs and Features" (Win+X, F) and repair "Microsoft .NET Core 1.0.0 - VS 2015 Tooling ...".

Original source


问:
How to do session based filtering servlet authentication
I am currently using filter to authenticate credentials given in the REST and servlet calls done in the servlet.

Everytime when a request made it fetches the credentials from the database which is expensive operation everytime.

Is there any way to authenticate based on session so that need not go everytime to retrieve details from db.

Thanks.

答:
Best thing would be Token based mechanism. Once the user logged in he's given a token and resending API calls with that token from the client will give the client to access the API.

Refer this : Implementing authentication with tokens


问:
JSON data divided by using segmented control
I have some JSON data. The data is like below and I took a segmented control which contains active state and pending state, by using segmented control separate the JSON data. If order_status = 0 (below JSON data) that will store in pending state, if order_status = 1 that will store in active state.

I know how to parse JSON but I do not know how to separate the data by using segmented control.

```<code>{
    "status": "done",
    "order_data": [{

        "price": "1000",
        "qty": "1",
        "total_price": "1000",
        "voucher_id": "NIL",
        "purchase_id": "1005",
        "purchase_on": "NIL",
        "validity": "30 days from the date of purchase",
        "left_day": "NIL",
        "order_status": 0
    }, {

        "price": "3000",
        "qty": "1",
        "total_price": "3000",
        "voucher_id": "NIL",
        "purchase_id": "10070",
        "purchase_on": "NIL",
        "validity": "30 days from the date of purchase",
        "left_day": "NIL",
        "order_status": 1
    }, {

        "price": "3000",
        "qty": "1",
        "total_price": "3000",
        "voucher_id": "NIL",
        "purchase_id": "1076767",
        "purchase_on": "NIL",
        "validity": "30 days from the date of purchase",
        "left_day": "NIL",
        "order_status": 1
    }]
}
</code>```

答:
Let suppose that your data is in a variable named as jsonData, then firstly parse the json data and get two array of dictionary, one for pending state data and another one for active state data, then use both of the dictionary for segment control.

```<code>if let orderData = jsonData["order_data"] as? [[String:Any]] {
let pendingStateData = orderData.filter({ (newOrder) -> Bool in
    return (newOrder["order_status"] as? Int) == 0
})

let activeStateData = orderData.filter({ (newOrder) -> Bool in
    return (newOrder["order_status"] as? Int) == 1
})
}
</code>```

So, using these filter you can filter the data and can get the desired filter data according to you.

Body:
I have some JSON data. The data is like below and I took a segmented control which contains active state and pending state, by using segmented control separate the JSON data. If order_status = 0 (below JSON data) that will store in pending state, if order_status = 1 that will store in active state.

I know how to parse JSON but I do not know how to separate the data by using segmented control.

{
    "status": "done",
    "order_data": [{

        "price": "1000",
        "qty": "1",
        "total_price": "1000",
        "voucher_id": "NIL",
        "purchase_id": "1005",
        "purchase_on": "NIL",
        "validity": "30 days from the date of purchase",
        "left_day": "NIL",
        "order_status": 0
    }, {

        "price": "3000",
        "qty": "1",
        "total_price": "3000",
        "voucher_id": "NIL",
        "purchase_id": "10070",
        "purchase_on": "NIL",
        "validity": "30 days from the date of purchase",
        "left_day": "NIL",
        "order_status": 1
    }, {

        "price": "3000",
        "qty": "1",
        "total_price": "3000",
        "voucher_id": "NIL",
        "purchase_id": "1076767",
        "purchase_on": "NIL",
        "validity": "30 days from the date of purchase",
        "left_day": "NIL",
        "order_status": 1
    }]
}

Body:
Let suppose that your data is in a variable named as jsonData, then firstly parse the json data and get two array of dictionary, one for pending state data and another one for active state data, then use both of the dictionary for segment control.

if let orderData = jsonData["order_data"] as? [[String:Any]] {
let pendingStateData = orderData.filter({ (newOrder) -> Bool in
    return (newOrder["order_status"] as? Int) == 0
})

let activeStateData = orderData.filter({ (newOrder) -> Bool in
    return (newOrder["order_status"] as? Int) == 1
})
}

So, using these filter you can filter the data and can get the desired filter data according to you.


问:
.Net Master Page Performance
I'm looking for some help on my discussion.  We're discussing two solutions to a customization problem.  One uses (nested) master-pages.  One master page per customized page.  Plus there is a standard master page for all pages.  The second uses a standard page, which redirects to the custom page if it exists.

My question is, which is more desirable?  Having to Load 2 master pages every time OR only having to load 1 master page and sometimes redirecting (Response.Redirect or Server.Transfer) to the customized page.

I can't really find any information on master page performance.  Should I just think of them as another (somewhat inverted) user-control or should they be used lightly?

Edit:
You can assume Response.Redirect for the transfer.
You can assume the Redirect occurs in the PreInit stage of the lifecycle.

答:
Master pages are in a sense inverted user controls (they "surround" content as opposed to user control content that is pushed into the page). There isn't a rule of thumb that says use master pages lightly--a master page's performance cost is directly proportionate to how much code (HTML and otherwise) it causes to be pushed into the HTTP data stream.

For my money, I'd land on the side what makes for the most readable and maintainable code.

OwnerDisplayName: jhoven

ContentLicense: CC BY-SA 4.0

Title: .Net Master Page Performance

OwnerDisplayName: rp


问:
timeout for 10 seconds while loop in python
What is the best way to timeout while loop in python

say:

```<code>while not buff.endswith('/abc #'):
</code>```

After 10 secs, if it does not match, break the  loop.

Thanks

答:
You can record the time before the loop, then inside the while loop you can compare the current time, and if it's > 10 seconds, you can break out of the while loop.

Something like:

```<code>from datetime import datetime

start_time = datetime.now()
print(start_time)

while not buff.endswith('/abc #'):
    print('waiting')
    time_delta = datetime.now() - start_time
    print(time_delta)
    if time_delta.total_seconds() >= 10:
        break
</code>```

Body:
What is the best way to timeout while loop in python

say:

while not buff.endswith('/abc #'):

After 10 secs, if it does not match, break the  loop.

Thanks

Body:
You can record the time before the loop, then inside the while loop you can compare the current time, and if it's > 10 seconds, you can break out of the while loop.

Something like:

from datetime import datetime

start_time = datetime.now()
print(start_time)

while not buff.endswith('/abc #'):
    print('waiting')
    time_delta = datetime.now() - start_time
    print(time_delta)
    if time_delta.total_seconds() >= 10:
        break


问:
Java for loop i++ as a string
Let's say we have a for loop

```<code>for(int i = 0; i < 10; i++) {
    ...
}
</code>```

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

```<code>for(int i = 0; i < 10; increment) {
    ...
}
</code>```

How can I make this work?

答:
i++ is just code : it's not a string as you thought.

Here's an analogy to demonstrate your assumption:

```<code>String someString =
    "public static void doStuff()
    {
        System.out.println("this is working");
    }";
</code>```

Now if you refer to the String someString in a separate method, do you think that the doStuff() method will be called? Of course not, because String is just text that the interpreter doesn't go through. The interpreter can only go through executable code, which includes the i++ in question.

Title: Java for loop i++ as a string

Body:
Let's say we have a for loop

for(int i = 0; i < 10; i++) {
    ...
}

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

for(int i = 0; i < 10; increment) {
    ...
}

How can I make this work?

Body:
i++ is just code : it's not a string as you thought.

Here's an analogy to demonstrate your assumption:

String someString =
    "public static void doStuff()
    {
        System.out.println("this is working");
    }";

Now if you refer to the String someString in a separate method, do you think that the doStuff() method will be called? Of course not, because String is just text that the interpreter doesn't go through. The interpreter can only go through executable code, which includes the i++ in question.


问:
Looping Through Firebase Datasnapshot and storing values in an array
I was working on a simple Android magazine app and I would like to iterate through Firebase DataSnapshot to retrieve stored information about magazines and save them in different arrays.I used this step by step instructions to retrieve data from Firebase database.I tried looking for other questions but they didn't help. </p>

```<code> DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                magazineNameSize(5);
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Magazine magazine = snapshot.getValue(Magazine.class);
                    dateOfIssue[i] =magazine.getDateOfIssue();
                    magazineCover[i]=magazine.getImageUri();
                    magazineName[i]=magazine.getMagazineName();
                    i++;
                }
            }
</code>```

答:
Try this:</p>

```<code>ArrayList<String> dateOfIssue = new ArrayList<>();
ArrayList<String> magazineCover = new ArrayList<>();
ArrayList<String> magazineName = new ArrayList<>();
DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

       for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Magazine magazine = snapshot.getValue(Magazine.class);
                dateOfIssue.add(magazine.getDateOfIssue());
                magazineCover.add(magazine.getImageUri());
                magazineName.add(magazine.getMagazineName());
                //value are store in three different arraylist
            }
        }
</code>```

Body:
I was working on a simple Android magazine app and I would like to iterate through Firebase DataSnapshot to retrieve stored information about magazines and save them in different arrays.I used this step by step instructions to retrieve data from Firebase database.I tried looking for other questions but they didn't help.

 DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                magazineNameSize(5);
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Magazine magazine = snapshot.getValue(Magazine.class);
                    dateOfIssue[i] =magazine.getDateOfIssue();
                    magazineCover[i]=magazine.getImageUri();
                    magazineName[i]=magazine.getMagazineName();
                    i++;
                }
            }

Body:
Try this:

ArrayList<String> dateOfIssue = new ArrayList<>();
ArrayList<String> magazineCover = new ArrayList<>();
ArrayList<String> magazineName = new ArrayList<>();
DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

       for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                Magazine magazine = snapshot.getValue(Magazine.class);
                dateOfIssue.add(magazine.getDateOfIssue());
                magazineCover.add(magazine.getImageUri());
                magazineName.add(magazine.getMagazineName());
                //value are store in three different arraylist
            }
        }


问:
ORACLE:SQL REGEXP_SUBSTR that returns the column value between 1st semicolon and second one. Also other value after last semi clumn
varchar: BLAH:123:678

need value between first semi column and second one: 123
need value after last semi column: 678

答:
Assuming you always have exactly two ':', this is solution without regexp, maybe not so elegant at first sight, but faster than regexp:

```<code>SELECT SUBSTR(
              yourString,
                INSTR(yourString, ':') + 1,
                INSTR(yourString,':', 1, 2 )
                  - INSTR(yourString, ':') - 1
             ),
       SUBSTR(
              yourString,
              INSTR(yourString, ':', 1, 2) +1
             )
  FROM (SELECT 'BLAH:123:678' AS yourString FROM DUAL)
</code>```

Body:
Assuming you always have exactly two ':', this is solution without regexp, maybe not so elegant at first sight, but faster than regexp:

SELECT SUBSTR(
              yourString,
                INSTR(yourString, ':') + 1,
                INSTR(yourString,':', 1, 2 )
                  - INSTR(yourString, ':') - 1
             ),
       SUBSTR(
              yourString,
              INSTR(yourString, ':', 1, 2) +1
             )
  FROM (SELECT 'BLAH:123:678' AS yourString FROM DUAL)


问:
Does ComponentScan order matter?
I'm setting up a very small Spring/REST/JPA project with Boot, using annotations.

I'm getting some Bean not found errors in my REST controller class that has an Autowired repository variable, when I move my JPA repository class out to a different package, and calling componentscan on its package. However, everything was working fine when all my files(5 total) were in the same package.

So I was wondering, however unlikely, if the component scan order matters? For example, if a class is AutoWiring some beans from a package that has not been 'component scanned' yet, will that cause a Bean not found error?

答:
There could be several problems:

You moved your class out of the some package where you have @ComponentScan without arguments. That basically means that components are scan only in this package and its children. Thus, moved class are not scanned and there is no bean to wire.

Wrong package name in @ComponentScan args.

The order isn't matter at all. There is an @Order annotation, but it's purpose is more about loading multiple implementations of sth in a different order.
At first Bean Definitions are created and they have nothing to do with wiring. Then via bean post processors, autowired beans are injected. Since there were no bean definition. There is nothing to inject.

Title: Does ComponentScan order matter?


问:
How to copy all rows from one SQL Server table to a table on a different SQL Server
I have a database in SQL Server 2008 and the same database (backup) in SQL Server 2016. All the schema and tables are exactly the same.

I need to copy all rows from a table in SQL Server 2008 to the same table in SQL Server 2016. How to achieve this?

答:
Linked Server

BCP

Create new DB, copy the data to that new DB, back it up, restore on target server as a new DB, update the data from Target new DB to existing target DB.


答: Yes You can create token when user getting first time successfully login and save that token in caching  server and set in cookies also whenever request comes from client check from caching server instead of Data base.Set token expire time as per session expire time.</p>

Title: How to do session based filtering servlet authentication

Body:
I am currently using filter to authenticate credentials given in the REST and servlet calls done in the servlet.

Everytime when a request made it fetches the credentials from the database which is expensive operation everytime.

Is there any way to authenticate based on session so that need not go everytime to retrieve details from db.

Thanks.


问:
ToggleGroup with a ChangeListener<Toggle> always throws a null value to the oldValue
hope someone can help me. I have menu  in javafx with 2 RadioMenuItem this way:

```<code>public class SiiController implements Initializable {
 private ToggleGroup companyToggleGroup;
 private RadioMenuItem companyARadio, companyBRadio;
 private MenuBar menuBar;
 private Menu fileMenu,companyMenu;
 private Boolean checked;

@Override
public void initialize(URL url, ResourceBundle rb) {
 /*......*/
    companyMenu = new Menu("Companies");
    companyToggleGroup = new ToggleGroup();
    companyARadio= new RadioMenuItem("Company A");
    companyARadio.setUserData("companya");
    companyARadio.setToggleGroup(companyToggleGroup);
    companyARadio.setSelected(true);
    companyBRadio= new RadioMenuItem("Company B");
    companyBRadio.setUserData("companyb");
    companyBRadio.setToggleGroup(companyToggleGroup);
    companyMenu.getItems().addAll(companyARadio, companyBRadio);

 companyToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
        @Override
        public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {

            if(checked){
                //do something
            }else{
                //remains the oldValue selected
                //The next line is just for checking the old value
                System.out.println("oldValue UserData"+oldValue.getUserData().toString());
            }

        }
    });
}
      menuBar.getMenus().addAll(fileMenu, companyMenu);
}
</code>```

The error is that the listener returns a null value to the Toggle oldValue. The exception I get is this one:

```<code>    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at controller.SiiController$4.changed(SiiController.java:284)
at controller.SiiController$4.changed(SiiController.java:280)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:137)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:119)
at javafx.scene.control.ToggleGroup.selectToggle(ToggleGroup.java:149)
at javafx.scene.control.RadioMenuItem$2.invalidated(RadioMenuItem.java:195)
at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
at javafx.scene.control.RadioMenuItem.setSelected(RadioMenuItem.java:180)
at javafx.scene.control.ToggleGroup.setSelected(ToggleGroup.java:166)
at javafx.scene.control.ToggleGroup.access$100(ToggleGroup.java:54)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:135)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:119)
at javafx.scene.control.ToggleGroup.selectToggle(ToggleGroup.java:149)
at javafx.scene.control.RadioMenuItem$2.invalidated(RadioMenuItem.java:193)
at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
at javafx.scene.control.RadioMenuItem.setSelected(RadioMenuItem.java:180)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1401)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)
</code>```

In the end what I'm trying to do is if the Boolean checkedis false then the previous selection on the ToggleGroupremains.
Thanks a lot for you time

答:
Did you try this in the listenter: </p>

```<code>if (oldValue != null) {
    System.out.println("old value: " + oldValue.getUserData());
}
</code>```

Body:
hope someone can help me. I have menu  in javafx with 2 RadioMenuItem this way:

public class SiiController implements Initializable {
 private ToggleGroup companyToggleGroup;
 private RadioMenuItem companyARadio, companyBRadio;
 private MenuBar menuBar;
 private Menu fileMenu,companyMenu;
 private Boolean checked;

@Override
public void initialize(URL url, ResourceBundle rb) {
 /*......*/
    companyMenu = new Menu("Companies");
    companyToggleGroup = new ToggleGroup();
    companyARadio= new RadioMenuItem("Company A");
    companyARadio.setUserData("companya");
    companyARadio.setToggleGroup(companyToggleGroup);
    companyARadio.setSelected(true);
    companyBRadio= new RadioMenuItem("Company B");
    companyBRadio.setUserData("companyb");
    companyBRadio.setToggleGroup(companyToggleGroup);
    companyMenu.getItems().addAll(companyARadio, companyBRadio);

 companyToggleGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
        @Override
        public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {

            if(checked){
                //do something
            }else{
                //remains the oldValue selected
                //The next line is just for checking the old value
                System.out.println("oldValue UserData"+oldValue.getUserData().toString());
            }

        }
    });
}
      menuBar.getMenus().addAll(fileMenu, companyMenu);
}

The error is that the listener returns a null value to the Toggle oldValue. The exception I get is this one:

    Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
at controller.SiiController$4.changed(SiiController.java:284)
at controller.SiiController$4.changed(SiiController.java:280)
at com.sun.javafx.binding.ExpressionHelper$SingleChange.fireValueChangedEvent(ExpressionHelper.java:182)
at com.sun.javafx.binding.ExpressionHelper.fireValueChangedEvent(ExpressionHelper.java:81)
at javafx.beans.property.ReadOnlyObjectPropertyBase.fireValueChangedEvent(ReadOnlyObjectPropertyBase.java:74)
at javafx.beans.property.ReadOnlyObjectWrapper.fireValueChangedEvent(ReadOnlyObjectWrapper.java:102)
at javafx.beans.property.ObjectPropertyBase.markInvalid(ObjectPropertyBase.java:112)
at javafx.beans.property.ObjectPropertyBase.set(ObjectPropertyBase.java:146)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:137)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:119)
at javafx.scene.control.ToggleGroup.selectToggle(ToggleGroup.java:149)
at javafx.scene.control.RadioMenuItem$2.invalidated(RadioMenuItem.java:195)
at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
at javafx.scene.control.RadioMenuItem.setSelected(RadioMenuItem.java:180)
at javafx.scene.control.ToggleGroup.setSelected(ToggleGroup.java:166)
at javafx.scene.control.ToggleGroup.access$100(ToggleGroup.java:54)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:135)
at javafx.scene.control.ToggleGroup$3.set(ToggleGroup.java:119)
at javafx.scene.control.ToggleGroup.selectToggle(ToggleGroup.java:149)
at javafx.scene.control.RadioMenuItem$2.invalidated(RadioMenuItem.java:193)
at javafx.beans.property.BooleanPropertyBase.markInvalid(BooleanPropertyBase.java:109)
at javafx.beans.property.BooleanPropertyBase.set(BooleanPropertyBase.java:144)
at javafx.scene.control.RadioMenuItem.setSelected(RadioMenuItem.java:180)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.doSelect(ContextMenuContent.java:1401)
at com.sun.javafx.scene.control.skin.ContextMenuContent$MenuItemContainer.lambda$createChildren$343(ContextMenuContent.java:1358)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:748)

In the end what I'm trying to do is if the Boolean checkedis false then the previous selection on the ToggleGroupremains.
Thanks a lot for you time

Body:
Did you try this in the listenter:

if (oldValue != null) {
    System.out.println("old value: " + oldValue.getUserData());
}


问:
How to show local notification on iWatch when iPhone disconnected?
How to show local notification in iWatch when iPhone disconnected  with iWatch ? any methods that continuously check iWatch reachability or called when watch reachability status change? I want to show local notification in iWatch

e.g whenever watch connected or disconnected it's show location notification on iWatch.

thanks in advance :)

答:
When your iWatch is connected to your iPhone. If your iPhone screen is lock then notification will be passed to iWatch. You don't have to do anything to pass it to iWatch you can see the Apple documentation for more clarification.

Check this link


问:
Create multiple Entry boxes in a loop tkinter
I was making an application using tkinter and came across an error. I wanted people to input a variable, which I have made, and then have that many Entry boxes popup on the screen for input. I was wondering what is wrong with my code, if it is possible, or if there is a better way. Thanks in advance!

p.s. the NoOfBoxes has been predefined

```<code>    int(NoOfBoxes)
    x = 1
    while(NoOfBoxes>=x):
        a = a + 50
        fill_empty(a)
        x = x + 1

    def fill_empty():
        empty = tk.Entry(self)
        empty.grid(row=200,column=a)
        return empty
</code>```

答:
In first line of shown code, you are converting NoOfBoxes to an integer but you are not assigning back it to NoOfBoxes hence, when while line comes, NoOfBoxes is still not an integer. Also, there is no parameter on your fill_empty definition.

Most likely you will need those Entry widgets at some point in your code, so it'll be much better if you keep references.

```<code>listOfEntries = [fill_empty(idx) for idx in range(int(NoOfBoxes))]

def fill_empty(a):
    empty = tk.Entry(self)
    empty.grid(row=200,column=a)
    return empty
</code>```

When you want to make any operation on those, you can easily do something like:

```<code>listOfEntries[0].get()
</code>```

Body:
I was making an application using tkinter and came across an error. I wanted people to input a variable, which I have made, and then have that many Entry boxes popup on the screen for input. I was wondering what is wrong with my code, if it is possible, or if there is a better way. Thanks in advance!

p.s. the NoOfBoxes has been predefined

    int(NoOfBoxes)
    x = 1
    while(NoOfBoxes>=x):
        a = a + 50
        fill_empty(a)
        x = x + 1

    def fill_empty():
        empty = tk.Entry(self)
        empty.grid(row=200,column=a)
        return empty

Body:
In first line of shown code, you are converting NoOfBoxes to an integer but you are not assigning back it to NoOfBoxes hence, when while line comes, NoOfBoxes is still not an integer. Also, there is no parameter on your fill_empty definition.

Most likely you will need those Entry widgets at some point in your code, so it'll be much better if you keep references.

listOfEntries = [fill_empty(idx) for idx in range(int(NoOfBoxes))]

def fill_empty(a):
    empty = tk.Entry(self)
    empty.grid(row=200,column=a)
    return empty

When you want to make any operation on those, you can easily do something like:

listOfEntries[0].get()


问:
how to get the page source and search with Watin
i'm using Watin and i want to search in the page source (HTML), like the ctrl+F search, what is the best way to do it? </p>

<p>thanx for any help,
Shiran </p>

答: You can use the IE.Text property to get the text of the whole page equivalent to innerText of the body element. Otherwise if you want the raw HTML you can use IE.Html.</p>

Body:
i'm using Watin and i want to search in the page source (HTML), like the ctrl+F search, what is the best way to do it?

thanx for any help,
Shiran


问:
What's the best way to unit test a controller in Laravel without testing the route too
I've read lots of documentation about testing controllers using $this->call($destination, $parameters, 'GET'); but this seems to rely on the route being set up too, and knowing the right $destination to use.

Generally this is OK, but accessing a controller from a route doesn't seem right for unit testing. I want to unit test the controller, not the route. Is there a standard way to unit test controllers, without dealing with routes?

Is simply manually instantiating the controller and calling the method enough? E.g.

```<code>$controller = new MyController;
$response = $controller->someMethod($param);
$this->assertSomething($response);
</code>```

Perhaps controllers shouldn't be unit tested (and only have acceptance tests) and my request is a sign that my controllers are too heavy.

答: The action method has been removed from Laravel 5.4 testing api

Body:
I've read lots of documentation about testing controllers using $this->call($destination, $parameters, 'GET'); but this seems to rely on the route being set up too, and knowing the right $destination to use.

Generally this is OK, but accessing a controller from a route doesn't seem right for unit testing. I want to unit test the controller, not the route. Is there a standard way to unit test controllers, without dealing with routes?

Is simply manually instantiating the controller and calling the method enough? E.g.

$controller = new MyController;
$response = $controller->someMethod($param);
$this->assertSomething($response);

Perhaps controllers shouldn't be unit tested (and only have acceptance tests) and my request is a sign that my controllers are too heavy.


问:
startService() throws java.lang.IllegalStateException
From onCreate() of my Activity,

I am trying to start a service via following code:

```<code>Intent intent = new Intent();
intent.setClassName(SERVICE_PKG_NAME, SERVICE_NAME);
context.startService(intent); //context = MainActivity.this
</code>```

However, I receive following exception:

java.lang.IllegalStateException: Not allowed to start service Intent (service-name) : app is in background

Any idea what could be reason for this? Stuck on it for few hours now.

答:
For cases involving need to invoke service of Background app from a foreground app, We can follow the sequence:

call bindService() first

after OnServiceConnected() due to bind call

call StartService().

Body:
From onCreate() of my Activity,

I am trying to start a service via following code:

Intent intent = new Intent();
intent.setClassName(SERVICE_PKG_NAME, SERVICE_NAME);
context.startService(intent); //context = MainActivity.this

However, I receive following exception:

java.lang.IllegalStateException: Not allowed to start service Intent (service-name) : app is in background

Any idea what could be reason for this? Stuck on it for few hours now.


问:
Differences between xp_instance_RegRead and xp_RegRead
Whats the difference between XP_REGREAD and XP_INSTANCE_REGREAD.
How to use them, is there any docs on these?</p>

答:
xp_regread reads the literal registry path that you specify. xp_instance_regread "converts" the path you specify so that it matches the instance of SQL Server that you're currently using.

As an example, I have Developer and Express editions of SQL Server installed on my machine. I connect to the Express instance and run these two commands:

```<code>declare @dir nvarchar(4000)

exec master.dbo.xp_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\Setup',
    N'SQLPath',
    @dir output
select @dir

exec master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\Setup',
    N'SQLPath',
    @dir output
select @dir
</code>```

The first returns C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL which is the value found at the location I specified but it is not the correct installation path for my Express instance.

The second returns c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL which is the correct path for my Express instance. This value was actually read from HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server\MSSQL.1\Setup which is quite different from the path I supplied to xp_instance_regread.

Body:
xp_regread reads the literal registry path that you specify. xp_instance_regread "converts" the path you specify so that it matches the instance of SQL Server that you're currently using.

As an example, I have Developer and Express editions of SQL Server installed on my machine. I connect to the Express instance and run these two commands:

declare @dir nvarchar(4000)

exec master.dbo.xp_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\Setup',
    N'SQLPath',
    @dir output
select @dir

exec master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\Setup',
    N'SQLPath',
    @dir output
select @dir

The first returns C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL which is the value found at the location I specified but it is not the correct installation path for my Express instance.

The second returns c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL which is the correct path for my Express instance. This value was actually read from HKEY_LOCAL_MACHINE\Software\Microsoft\Microsoft SQL Server\MSSQL.1\Setup which is quite different from the path I supplied to xp_instance_regread.


问:
Detect Chrome running in headless mode from JavaScript
With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/
```

<p>In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of <code>navigator</code>, including the current browser plugins:</p>

<pre class="lang-js prettyprint-override"><code>JSON.stringify(Array.from(navigator.plugins).map(p => p.name))
</code>```

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]
```

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.

For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.

Is there any way to detect if Chrome is running in headless mode from JavaScript?

答:
The best solution I have so far is this hack. I wouldn't use it in prod code, but might in testing.

Chrome's pop-up blocker is usually enabled for all web sites, but it's disabled in headless mode. We can use the ability to open pop-ups as a fairly accurate proxy for being in headless mode. The implementation is simple: try to open(...) a window, and check whether we get null (indicating that it was blocked) instead of a Window object. If we do open one, close it as quickly as possible.

```<code>function canPopUp() {
  var w = open("");
  if (w !== null) {
    w.close();
    return true;
  } else {
    return false;
  }
}

var isHeadless = canPopUp;
</code>```

For a quick example, you can try the following with and without the --headless flag:

chrome --headless --disable-gpu --dump-dom 'data:text/html,<!doctype html>'

Body:
With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/

In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of navigator, including the current browser plugins:

JSON.stringify(Array.from(navigator.plugins).map(p => p.name))

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.

For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.

Is there any way to detect if Chrome is running in headless mode from JavaScript?

Body:
The best solution I have so far is this hack. I wouldn't use it in prod code, but might in testing.

Chrome's pop-up blocker is usually enabled for all web sites, but it's disabled in headless mode. We can use the ability to open pop-ups as a fairly accurate proxy for being in headless mode. The implementation is simple: try to open(...) a window, and check whether we get null (indicating that it was blocked) instead of a Window object. If we do open one, close it as quickly as possible.

function canPopUp() {
  var w = open("");
  if (w !== null) {
    w.close();
    return true;
  } else {
    return false;
  }
}

var isHeadless = canPopUp;

For a quick example, you can try the following with and without the --headless flag:

chrome --headless --disable-gpu --dump-dom 'data:text/html,<!doctype html><body><script>document.body.innerHTML = `headless: ${open("") !== null}`;</script>'


问:
Get checked radio table data value when change the div
Here I am append table element after ajax success response and its working good and the code is ...

```<code> $.ajax({
          type: 'GET',
          url: '{{ route("shipping_address") }}',
          dataType: 'JSON',
          data: myData,
          success: function(data) {
                var x=data['rates'];
                var table = '<table class="rates"><tr><th>Providers</th><th>Days</th><th>Price</th></tr>'
                $.each(data['rates'], function (key, val) {
                  table +=  '<tr><td><input type="radio" name="shipment_radio" id="shipment_radio"></td><td id="providers">'+val.provider+'</td><td id="days">'+val.days+'</td><td id="amount">'+val.amount+'</td></tr>'
               });
               table += '</table>';
               var result = $('#shipping').append(table);
          },
          error: function(jqXHR, textStatus, errorThrown) {
              console.log(JSON.stringify(jqXHR));
          }
    });
</code>```

It append inside the div which is in html element

```<code><div id="shipping">
</div>
</code>```

I want to get the checked table value which  means when i click the first radio button i want that table data price then i check second radio i want that table price..
I try this

```<code> $(document).on('change', '#shipment_radio' ,function() {
      $('.rates').removeClass("checked");
      $(this).parent().parent().addClass("checked");
      var price = $('.checked').find('td#days').text();
      alert(price);
        });
</code>```

But i didnot get the correct result

How to achieve this...PLease help me

答:
The issue is here:

```<code>$.each(data['rates'], function (key, val) {
    table +=  '<tr><td><input type="radio" name="shipment_radio" id="shipment_radio"></td><td id="providers">'+val.provider+'</td><td id="days">'+val.days+'</td><td id="amount">'+val.amount+'</td></tr>'
});
</code>```

here you are using shipment_radio as ID, but its occurrence are more than one. So instead of ID use Class selector like:

```<code>class="shipment_radio"
</code>```

and add event listener to it:

```<code>$(document).on('change', '.shipment_radio' ,function() {
</code>```

Body:
Here I am append table element after ajax success response and its working good and the code is ...

 $.ajax({
          type: 'GET',
          url: '{{ route("shipping_address") }}',
          dataType: 'JSON',
          data: myData,
          success: function(data) {
                var x=data['rates'];
                var table = '

Providers	Days	Price
'
                $.each(data['rates'], function (key, val) {
                  table +=  '
<input type="radio" name="shipment_radio" id="shipment_radio">	'+val.provider+'	'+val.days+'	'+val.amount+'
'
               });
               table += '
';
               var result = $('#shipping').append(table);
          },
          error: function(jqXHR, textStatus, errorThrown) {
              console.log(JSON.stringify(jqXHR));
          }
    });

It append inside the div which is in html element

I want to get the checked table value which  means when i click the first radio button i want that table data price then i check second radio i want that table price..
I try this

 $(document).on('change', '#shipment_radio' ,function() {
      $('.rates').removeClass("checked");
      $(this).parent().parent().addClass("checked");
      var price = $('.checked').find('td#days').text();
      alert(price);
        });

But i didnot get the correct result

How to achieve this...PLease help me

Body:
The issue is here:

$.each(data['rates'], function (key, val) {
    table +=  '<tr><td><input type="radio" name="shipment_radio" id="shipment_radio"></td><td id="providers">'+val.provider+'</td><td id="days">'+val.days+'</td><td id="amount">'+val.amount+'</td></tr>'
});

here you are using shipment_radio as ID, but its occurrence are more than one. So instead of ID use Class selector like:

class="shipment_radio"

and add event listener to it:

$(document).on('change', '.shipment_radio' ,function() {


问:
SignalR ASP.NET
I have a problem receiving messages from an application because sometimes works but not always, and I have to F5 side to get back to work. Any ideas what could be?

correct messages:

[19:15:27 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoking question.SendMessage
  jquery.signalR-2.2.0.min.js:8 [19:15:27 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoked question.SendMessage
  jquery.signalR-2.2.0.min.js:8 [19:15:27 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Triggering client hub event 'newMessage' on hub 'question'.
  gameController.js:19 2d856458-6874-44a9-a402-37ab6ca61cec: hello

incorrect messages(no answer):

[19:15:51 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoking question.SendMessage
  jquery.signalR-2.2.0.min.js:8 [19:15:51 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoked question.SendMessage

```<code> $(function () {
        $.connection.hub.logging = true;
        $.connection.hub.start();

    });

    $.connection.hub.error(function (err) {
        alert("error: " + err);
    });

    angular.module('app').value('gameHub', $.connection.question);
</code>```

In CTRL

```<code> $scope.sendMessage = function () {
        gameHub.server.sendMessage($scope.message);

}

gameHub.client.newMessage = function onNewMessage(message) {
    $scope.messages.push({message: message});
    $scope.$apply();
    console.log(message);
}
</code>```

答:
As SignalR is for RealTime Application it will get you message as soon as the other person will send, meanwhile if you are on the other page where you don't have you hub connected then there can be two scenarios

1) If you've appended message through HTML or something then when you'll get back to same page (chat) then the messages will be removed due to page refresh.

-Solution

```<code>you can try saving messages to database so that when you get back you can
retrieve you chat
</code>```

2) The hub might be getting disconnected

```<code>so you should try using OnConnected(), OnDisconnected(), & On ReConnected() methods.
</code>```

P.S. signalR fires OnDisconnected() method when user Closes the Tab/Browser or when user refreshes the Page

Title: SignalR ASP.NET

Body:
I have a problem receiving messages from an application because sometimes works but not always, and I have to F5 side to get back to work. Any ideas what could be?

correct messages:

[19:15:27 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoking question.SendMessage
  jquery.signalR-2.2.0.min.js:8 [19:15:27 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoked question.SendMessage
  jquery.signalR-2.2.0.min.js:8 [19:15:27 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Triggering client hub event 'newMessage' on hub 'question'.
  gameController.js:19 2d856458-6874-44a9-a402-37ab6ca61cec: hello

incorrect messages(no answer):

[19:15:51 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoking question.SendMessage
  jquery.signalR-2.2.0.min.js:8 [19:15:51 GMT+0100 (Środkowoeuropejski czas stand.)] SignalR: Invoked question.SendMessage

 $(function () {
        $.connection.hub.logging = true;
        $.connection.hub.start();

    });

    $.connection.hub.error(function (err) {
        alert("error: " + err);
    });

    angular.module('app').value('gameHub', $.connection.question);

In CTRL

 $scope.sendMessage = function () {
        gameHub.server.sendMessage($scope.message);

}

gameHub.client.newMessage = function onNewMessage(message) {
    $scope.messages.push({message: message});
    $scope.$apply();
    console.log(message);
}

Body:
As SignalR is for RealTime Application it will get you message as soon as the other person will send, meanwhile if you are on the other page where you don't have you hub connected then there can be two scenarios

1) If you've appended message through HTML or something then when you'll get back to same page (chat) then the messages will be removed due to page refresh.

-Solution

you can try saving messages to database so that when you get back you can
retrieve you chat

2) The hub might be getting disconnected

so you should try using OnConnected(), OnDisconnected(), & On ReConnected() methods.

P.S. signalR fires OnDisconnected() method when user Closes the Tab/Browser or when user refreshes the Page


问:
How to center an image inside a list with other elements
I have an unordered list that contains several list elements inside. Also inside is an image element which is to be centered. I tried to center it using the margin: auto; property but since there are list elements on the side, it takes that into account when centering itself. How do I center the image in respect to it's container?

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;
  margin: auto;
  height: 21px;
  width: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="assets/image/twitter-icon.png" alt="Twitter Icon">
  </ul>
</nav></code>```

答:
You may have to position the image absolute into the nav element using:

```<code>position: absolute;
left: 50%;
transform: translateX(-50%);
</code>```

Also position:relative the nav element.

This way the image ignores whatever is inside the nav element.

body{
margin:0px;
}

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  position:relative;
}

.nav li {
  vertical-align: top;
  margin: 5px 10px;
  display: inline;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  height: 21px;
  width: 24px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="assets/image/twitter-icon.png" alt="Twitter Icon">
  </ul>
</nav></code>```

Body:
I have an unordered list that contains several list elements inside. Also inside is an image element which is to be centered. I tried to center it using the margin: auto; property but since there are list elements on the side, it takes that into account when centering itself. How do I center the image in respect to it's container?

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
}

.nav li {
  float: left;
  vertical-align: top;
  margin: 5px 10px;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  display: block;
  margin: auto;
  height: 21px;
  width: 24px;
}

Home

Moments

Notifications

Messages

Body:
You may have to position the image absolute into the nav element using:

position: absolute;
left: 50%;
transform: translateX(-50%);

Also position:relative the nav element.

This way the image ignores whatever is inside the nav element.

body{
margin:0px;
}

.nav {
  width: 1280px;
  margin: 0 auto;
  font-size: 16px;
  font-weight: 500;
  border: 1px solid black;
  position:relative;
}

.nav li {
  vertical-align: top;
  margin: 5px 10px;
  display: inline;
}

nav li:first-child {
  margin-left: 75px;
}

.nav img {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  height: 21px;
  width: 24px;
}

<nav class="nav">
  <ul class="clearfix">
    <li>Home</li>
    <li>Moments</li>
    <li>Notifications</li>
    <li>Messages</li>
    <img src="assets/image/twitter-icon.png" alt="Twitter Icon">
  </ul>
</nav>


问:
jupyter notebook X bootstrap
is it possible to integrate bootstrap components into a Juptyer Notebook.
 ie: Making markdown tabs specific colors(making the whole markdown cell red), using glyph icons, etc

Thank you

答:
Yeah.  At least the alerts, you can just use the html code in a markdown cell.

For example,

```<code><div class="alert alert-info">
   <strong>Hi!</strong> This is a blue note.
</div>
</code>```

would give you the blue alerts.  Change info to success, warning, and danger are your options.

Title: jupyter notebook X bootstrap

Body:
Yeah.  At least the alerts, you can just use the html code in a markdown cell.

For example,

<div class="alert alert-info">
   <strong>Hi!</strong> This is a blue note.
</div>

would give you the blue alerts.  Change info to success, warning, and danger are your options.


问:
Select all selected id's in a multiselect dropdown in laravel 5.4 with harvest chosen
I have a dropdown called designation, where a user can add some information against multiple designation. If I add 1 record against 3 designation, then I need to select those during validation and edit time also.

Ex: Choosed id's {5,7,8} from [1 to 10].

```<code><select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
<option value="">--- Select ---</option>
@foreach ($desgInfo as $key => $value)
<option value="{{ $key }}" {{ old('forWhom',$info->forWhom) == $key ? 'selected' : ''}} />{{ $value }}</option>
@endforeach
</select>
</code>```

After add of those information I store those selected id's in comma(,) separator i.e 5,7,8.

How can I make select this in laravel 5.4

答:
After playing around a bit, I got the result.

Here is the piece of code.

During Add

```<code><select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
    <option value="">--- Select ---</option>
    @foreach ($desgInfo as $key => $value)
        <option value="{{ $key }}"
           {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  />
           {{ $value }}
        </option>
    @endforeach
</select>
</code>```

During Edit
Suppose you got the result of selected ids in

$info->forWhom

```<code><select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
        <option value="">--- Select ---</option>
        @foreach ($desgInfo as $key => $value)
            <option value="{{ $key }}"
               {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}
               {{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}
               />
               {{ $value }}
            </option>
        @endforeach
    </select>
</code>```

I hope this will help some one else.

Body:
I have a dropdown called designation, where a user can add some information against multiple designation. If I add 1 record against 3 designation, then I need to select those during validation and edit time also.

Ex: Choosed id's {5,7,8} from [1 to 10].

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
<option value="">--- Select ---</option>
@foreach ($desgInfo as $key => $value)
<option value="{{ $key }}" {{ old('forWhom',$info->forWhom) == $key ? 'selected' : ''}} />{{ $value }}</option>
@endforeach
</select>

After add of those information I store those selected id's in comma(,) separator i.e 5,7,8.

How can I make select this in laravel 5.4

Body:
After playing around a bit, I got the result.

Here is the piece of code.

During Add

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
    <option value="">--- Select ---</option>
    @foreach ($desgInfo as $key => $value)
        <option value="{{ $key }}"
           {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}  />
           {{ $value }}
        </option>
    @endforeach
</select>

During Edit
Suppose you got the result of selected ids in

$info->forWhom

<select id="forWhom" name="forWhom[]" multiple class="form-control chosen">
        <option value="">--- Select ---</option>
        @foreach ($desgInfo as $key => $value)
            <option value="{{ $key }}"
               {{ (collect(old('forWhom'))->contains($key)) ? 'selected':'' }}
               {{ (in_array($key,$info->forWhom)) ? 'selected' : ''}}
               />
               {{ $value }}
            </option>
        @endforeach
    </select>

I hope this will help some one else.


问:
jQuery show/hide issue on data grid
I am facing a problem with the data gird. I have three to four datagrid one below the other and for each grid i have action buttons[select/del/copy/add] which i showing and hiding using jquery.

Each data grid has different id and show and hide controlled through jquery. But when i am clicking the first grid the next grid is also showing the control eventhough it has a different id.

I understand there is something advanced jquery scripting involved here, would be of great help if someone looks into this.

http://jsfiddle.net/pixelfx/3fwyf/16/

thanks,
ravi.

答:
The problem is that you are toggling both groups of buttons..

If your html is structure as your example then you should remove those two toggles

```<code>$('#actn_btns').toggle();
$('#actn_btns1').toggle();
</code>```

and add $(this).closest('table').next().toggle(); in their place.

example at http://jsfiddle.net/3fwyf/19/

On another issue, you have duplicate id elements on the tables. Don't do that..

Update

the .closest() works like this

Get the first ancestor element that
  matches the selector, beginning at the
  current element and progressing up
  through the DOM tree.

The .minus and .add are not ancestors. So we need to first go up to a place where the .child and .minus elements are children to the current node and then go downwards and find them.

```<code>$(this).closest('tr').find('.minus, .add').toggle();
</code>```

Title: jQuery show/hide issue on data grid

Body:
The problem is that you are toggling both groups of buttons..

If your html is structure as your example then you should remove those two toggles

$('#actn_btns').toggle();
$('#actn_btns1').toggle();

and add $(this).closest('table').next().toggle(); in their place.

example at http://jsfiddle.net/3fwyf/19/

On another issue, you have duplicate id elements on the tables. Don't do that..

Update

the .closest() works like this

Get the first ancestor element that
  matches the selector, beginning at the
  current element and progressing up
  through the DOM tree.

The .minus and .add are not ancestors. So we need to first go up to a place where the .child and .minus elements are children to the current node and then go downwards and find them.

$(this).closest('tr').find('.minus, .add').toggle();


问:
How to make raycast ignore Trigger colliders?
I have a function that checks if a game object can see another game object without anything blocking its view:

```<code>public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?

答:
To have your raycasts ignore all trigger colliders in 5.2 go to:

Edit > Project Settings > Physics > Uncheck "Queries Hit Triggers"

(If you're using an older version of Unity, the check box is called "Raycasts Hit Triggers")

Actually in version 5.2.0f3 it no longer says Raycasts... It now appears as: "Queries Hit Triggers" Uncheck if you want raycasts to pass through trigger colliders.

Body:
I have a function that checks if a game object can see another game object without anything blocking its view:

public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}

The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?


问:
iTunesConnect: cannot transfer app because of "You must turn off TestFlight beta testing for the app that you want to transfer"
Below you can see that testing for external testers are turned off:

same for internal testing:

but when I transfer app, one of the criterias are not met:

Why?

答: i had the same issue i deleted (mark expired) all the versions of app testing version in App TestFlight section and done the trick for me ;) attach is the screen shot of activity.


答:
Ideally you should be having a unique id, so instead of id make use of class since you are looping over it.

```<code> $.each(data['rates'], function (key, val) {
              table +=  '<tr><td><input type="radio" name="shipment_radio" class="shipment_radio"></td><td class="providers">'+val.provider+'</td><td class="days">'+val.days+'</td><td class="amount">'+val.amount+'</td></tr>'
           });
</code>```

and then you can get he required result by getting the next td with class days from the parent of the radio ie. a td element. Also closest is a better option than using multiple parent functions

```<code>$(document).on('change', '.shipment_radio' ,function() {
      $('.rates').removeClass("checked");
      $(this).closest('tr').addClass("checked");
      var price = $(this).parent().next('.days').text();
      alert(price);
});
</code>```

Title: Get checked radio table data value when change the div

Body:
Ideally you should be having a unique id, so instead of id make use of class since you are looping over it.

 $.each(data['rates'], function (key, val) {
              table +=  '<tr><td><input type="radio" name="shipment_radio" class="shipment_radio"></td><td class="providers">'+val.provider+'</td><td class="days">'+val.days+'</td><td class="amount">'+val.amount+'</td></tr>'
           });

and then you can get he required result by getting the next td with class days from the parent of the radio ie. a td element. Also closest is a better option than using multiple parent functions

$(document).on('change', '.shipment_radio' ,function() {
      $('.rates').removeClass("checked");
      $(this).closest('tr').addClass("checked");
      var price = $(this).parent().next('.days').text();
      alert(price);
});


问:
What is the best place to add AVPlayer or MPMoviePlayerController in UITableViewCell?
I try to play video in UITableViewCell when a user clicks on play button in cell.

答:
Scene 1:

If you are willing to auto play video's like Facebook or Instagram in each cell then consider adding AVPlayer in cellForRowAtIndexPath.

AVPlayer will not allow you to change the url being played (AVURLAsset url) once created. So If you are using AVPlayer and providing ur own view to player I afraid creating AVPlayer instance every time in cellForRowAtIndexPath is the only solution.

On the other hand if you are planning to use AVPlayerViewController, you can create AVPlayer viewController instance in cell's awakeFromNib so you will have only one instance of player per cell and in cellForRowAtIndexPath you can pass different url each time. You can use prepareForReuse method of cell to pause the player and resetting all your player properties.

Scene 2:

If you are planning to play once user taps on button in cell, consider creating AVPlayer/AVPlayerViewController on button tap and play the video. Use prepareForReuse to reset the properties of ur player to ensure you don't play wrong video when u scroll and cell gets reused.

EDIT:

As OP has asked for some code snippet, providing skeleton code. This is not a copy paste code, idea is just to give idea of how to use AVPlayerViewController inside cell the code might have compiler issues.

//create a custom tableViewCell subclass

```<code>class ImageTableViewCell: UITableViewCell {
    @IBOutlet weak var carsImageView: UIImageView!
    var playerController : AVPlayerViewController? = nil
    var passedURL : URL! = nil

    override func awakeFromNib() {
        super.awakeFromNib()
        playerController = AVPlayerViewController()
        // Initialization code
    }

    func configCell(with url : URL) {
        //something like this
        self.passedURL = url
        //show video thumbnail with play button on it.
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

    @IBAction func playOrPauseVideo(_ sender: UIButton) {
        let player = AVPlayer(url: url)
        playerController.player = player
        playerController?.showsPlaybackControls = true
        playerController.player.play()
        //add playerController view as subview to cell
    }

    override func prepareForReuse() {
        //this way once user scrolls player will pause
        self.playerController.player?.pause()
        self.playerController.player = nil
    }
}
</code>```

The code above sets the PlayerController to nil in prepareForReuse() so when user scrolls the tableView and cell goes out of tableView Frame and gets reused, player will pause and will not retain the status. If you simply want to pause and replay when user scrolls back to the same cell u will have to save player somewhere outside the cell and find a way to map player instance to cell.

Finally in cellForRowAtIndexPath call,

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : ImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageTableViewCell
    cell.configCell(with: URL(string: "https://google.com")!)
    ....
}
</code>```

EDIT 2:

As OP has completely filped the question to play only one video at any point in time and pause other playing videos on tapping play button my earlier answer will no longer hold true.

Earlier answer allows user to play multiple video.

Here is a modified answer to make it work.

Modify your custom cell class as below.

```<code>protocol VideoPlayingCellProtocol : NSObjectProtocol {
    func playVideoForCell(with indexPath : IndexPath)
}

class ImageTableViewCell: UITableViewCell {
    @IBOutlet weak var carsImageView: UIImageView!
    var playerController : AVPlayerViewController? = nil
    var passedURL : URL! = nil
    var indexPath : IndexPath! = nil
    var delegate : VideoPlayingCellProtocol = nil

    override func awakeFromNib() {
        super.awakeFromNib()
        playerController = AVPlayerViewController()
        // Initialization code
    }

    func configCell(with url : URL,shouldPlay : Bool) {
        //something like this
        self.passedURL = url
        if shouldPlay == true {
            let player = AVPlayer(url: url)
            if self.playerController == nil {
                playerController = AVPlayerViewController()
            }
            playerController.player = player
            playerController?.showsPlaybackControls = true
            playerController.player.play()
        }
        else {
            if self.playerController != nil {
                self.playerController.player?.pause()
                self.playerController.player = nil
            }
            //show video thumbnail with play button on it.
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func playOrPauseVideo(_ sender: UIButton) {
        self.delegate.playVideoForCell(self.indexPath)
        //add playerController view as subview to cell
    }

    override func prepareForReuse() {
        //this way once user scrolls player will pause
        self.playerController.player?.pause()
        self.playerController.player = nil
    }
}
</code>```

In your TableView VC create a property called

```<code>var currentlyPlayingIndexPath : IndexPath? = nil
</code>```

Make your TableView VC to confirm VideoPlayingCellProtocol

```<code>extension ViewController : VideoPlayingCellProtocol {
    func playVideoForCell(with indexPath: IndexPath) {
    self.currentlyPlayingIndexPath = indexPath
    //reload tableView
    self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .none)
   }
}
</code>```

Finally modify your cellForRowAtIndexPath as

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : ImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageTableViewCell
        //delegate setting here which u missed
        cell.delegate = self
        //let the cell know its indexPath
        cell.indexPath = indexPath

            cell.configCell(with: URL(string: "https://google.com")!, shouldPlay: self.currentlyPlayingIndexPath == indexPath)
        ....
}
</code>```

Thats all you need.

Body:
Scene 1:

If you are willing to auto play video's like Facebook or Instagram in each cell then consider adding AVPlayer in cellForRowAtIndexPath.

AVPlayer will not allow you to change the url being played (AVURLAsset url) once created. So If you are using AVPlayer and providing ur own view to player I afraid creating AVPlayer instance every time in cellForRowAtIndexPath is the only solution.

On the other hand if you are planning to use AVPlayerViewController, you can create AVPlayer viewController instance in cell's awakeFromNib so you will have only one instance of player per cell and in cellForRowAtIndexPath you can pass different url each time. You can use prepareForReuse method of cell to pause the player and resetting all your player properties.

Scene 2:

If you are planning to play once user taps on button in cell, consider creating AVPlayer/AVPlayerViewController on button tap and play the video. Use prepareForReuse to reset the properties of ur player to ensure you don't play wrong video when u scroll and cell gets reused.

EDIT:

As OP has asked for some code snippet, providing skeleton code. This is not a copy paste code, idea is just to give idea of how to use AVPlayerViewController inside cell the code might have compiler issues.

//create a custom tableViewCell subclass

class ImageTableViewCell: UITableViewCell {
    @IBOutlet weak var carsImageView: UIImageView!
    var playerController : AVPlayerViewController? = nil
    var passedURL : URL! = nil

    override func awakeFromNib() {
        super.awakeFromNib()
        playerController = AVPlayerViewController()
        // Initialization code
    }

    func configCell(with url : URL) {
        //something like this
        self.passedURL = url
        //show video thumbnail with play button on it.
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }

    @IBAction func playOrPauseVideo(_ sender: UIButton) {
        let player = AVPlayer(url: url)
        playerController.player = player
        playerController?.showsPlaybackControls = true
        playerController.player.play()
        //add playerController view as subview to cell
    }

    override func prepareForReuse() {
        //this way once user scrolls player will pause
        self.playerController.player?.pause()
        self.playerController.player = nil
    }
}

The code above sets the PlayerController to nil in prepareForReuse() so when user scrolls the tableView and cell goes out of tableView Frame and gets reused, player will pause and will not retain the status. If you simply want to pause and replay when user scrolls back to the same cell u will have to save player somewhere outside the cell and find a way to map player instance to cell.

Finally in cellForRowAtIndexPath call,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : ImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageTableViewCell
    cell.configCell(with: URL(string: "https://google.com")!)
    ....
}

EDIT 2:

As OP has completely filped the question to play only one video at any point in time and pause other playing videos on tapping play button my earlier answer will no longer hold true.

Earlier answer allows user to play multiple video.

Here is a modified answer to make it work.

Modify your custom cell class as below.

protocol VideoPlayingCellProtocol : NSObjectProtocol {
    func playVideoForCell(with indexPath : IndexPath)
}

class ImageTableViewCell: UITableViewCell {
    @IBOutlet weak var carsImageView: UIImageView!
    var playerController : AVPlayerViewController? = nil
    var passedURL : URL! = nil
    var indexPath : IndexPath! = nil
    var delegate : VideoPlayingCellProtocol = nil

    override func awakeFromNib() {
        super.awakeFromNib()
        playerController = AVPlayerViewController()
        // Initialization code
    }

    func configCell(with url : URL,shouldPlay : Bool) {
        //something like this
        self.passedURL = url
        if shouldPlay == true {
            let player = AVPlayer(url: url)
            if self.playerController == nil {
                playerController = AVPlayerViewController()
            }
            playerController.player = player
            playerController?.showsPlaybackControls = true
            playerController.player.play()
        }
        else {
            if self.playerController != nil {
                self.playerController.player?.pause()
                self.playerController.player = nil
            }
            //show video thumbnail with play button on it.
        }
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func playOrPauseVideo(_ sender: UIButton) {
        self.delegate.playVideoForCell(self.indexPath)
        //add playerController view as subview to cell
    }

    override func prepareForReuse() {
        //this way once user scrolls player will pause
        self.playerController.player?.pause()
        self.playerController.player = nil
    }
}

In your TableView VC create a property called

var currentlyPlayingIndexPath : IndexPath? = nil

Make your TableView VC to confirm VideoPlayingCellProtocol

extension ViewController : VideoPlayingCellProtocol {
    func playVideoForCell(with indexPath: IndexPath) {
    self.currentlyPlayingIndexPath = indexPath
    //reload tableView
    self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .none)
   }
}

Finally modify your cellForRowAtIndexPath as

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : ImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "imageCell") as! ImageTableViewCell
        //delegate setting here which u missed
        cell.delegate = self
        //let the cell know its indexPath
        cell.indexPath = indexPath

            cell.configCell(with: URL(string: "https://google.com")!, shouldPlay: self.currentlyPlayingIndexPath == indexPath)
        ....
}

Thats all you need.


答:
You are create element with duplicate identifiers which make HTML invalid as Identifiers in HTML must be unique

Use common classes to bind  event handler

```<code> $.each(data['rates'], function (key, val) {
     table +=  '<tr><td><input type="radio" name="shipment_radio" class="shipment_radio"></td><td class="providers">'+val.provider+'</td><td class="days">'+val.days+'</td><td class="amount">'+val.amount+'</td></tr>'
 });
</code>```

Then you can DOM relationship to traverse and target them

```<code>$(document).on('change', '.shipment_radio' ,function() {
    $('.rates').removeClass("checked");
    var tr = $(this).closest('tr');
    tr.addClass("checked");
    var price = tr .find('.days').text();
    console.log(price);
});
</code>```

Body:
You are create element with duplicate identifiers which make HTML invalid as Identifiers in HTML must be unique

Use common classes to bind  event handler

 $.each(data['rates'], function (key, val) {
     table +=  '<tr><td><input type="radio" name="shipment_radio" class="shipment_radio"></td><td class="providers">'+val.provider+'</td><td class="days">'+val.days+'</td><td class="amount">'+val.amount+'</td></tr>'
 });

Then you can DOM relationship to traverse and target them

$(document).on('change', '.shipment_radio' ,function() {
    $('.rates').removeClass("checked");
    var tr = $(this).closest('tr');
    tr.addClass("checked");
    var price = tr .find('.days').text();
    console.log(price);
});