问:
How to pass UIViewController as a parameter swift 3?
I'm trying to create a common method for that i have to pass self(current UIViewController ) as a parameter. Below is the method:

```<code>  func getFBUserData(){

        if let token = FBSDKAccessToken.current(){

        print("Access Token: \(token.tokenString!)")

            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
                if (error == nil){
                    self.dict = result as! [String : AnyObject]
                    print(result!)
                    print(self.dict)
                    var jsonObj = JSON(result!)
                    if let first_name = jsonObj["first_name"].string {
                        NSLog("first_name : \(first_name)")
                    }
                    NSLog("RESULT JSON : \(JSON(result!))")
                    //print("Access Token: \(FBSDKAccessToken.current())")
                }
            })
        }

    }
</code>```

I modified this as follows:

```<code>func IsFaceBookPermisssionGranted(_ completion: @escaping (_ IsPermissionGranted: Bool, _ error_type:ErrorType)->()) {

    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()

    fbLoginManager.logIn(withReadPermissions: ["email"], from: UIViewController?) { (result, error) in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    completion(true,nil)
                }
            }else{
                completion(false,.AUTH_FAILED)
            }
        }else{
            print("Error : \(error)")
            completion(false,.AUTH_FAILED)
        }
    }
}
</code>```

But when i pass UIViewController like above it says
Cannot convert value of type 'UIViewController.Type' to expected argument type 'UIViewController!'

What can i do on this ?

答:
In swift 3.0,
you cannot pass directly your UIViewController.
First you can create a view controller object.

For example,

```<code>let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "your_view_controller_Identifier") as! YourViewController
</code>```

Body:
I'm trying to create a common method for that i have to pass self(current UIViewController ) as a parameter. Below is the method:

  func getFBUserData(){

        if let token = FBSDKAccessToken.current(){

        print("Access Token: \(token.tokenString!)")

            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
                if (error == nil){
                    self.dict = result as! [String : AnyObject]
                    print(result!)
                    print(self.dict)
                    var jsonObj = JSON(result!)
                    if let first_name = jsonObj["first_name"].string {
                        NSLog("first_name : \(first_name)")
                    }
                    NSLog("RESULT JSON : \(JSON(result!))")
                    //print("Access Token: \(FBSDKAccessToken.current())")
                }
            })
        }

    }

I modified this as follows:

func IsFaceBookPermisssionGranted(_ completion: @escaping (_ IsPermissionGranted: Bool, _ error_type:ErrorType)->()) {

    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()

    fbLoginManager.logIn(withReadPermissions: ["email"], from: UIViewController?) { (result, error) in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    completion(true,nil)
                }
            }else{
                completion(false,.AUTH_FAILED)
            }
        }else{
            print("Error : \(error)")
            completion(false,.AUTH_FAILED)
        }
    }
}

But when i pass UIViewController like above it says
Cannot convert value of type 'UIViewController.Type' to expected argument type 'UIViewController!'

What can i do on this ?

Body:
In swift 3.0,
you cannot pass directly your UIViewController.
First you can create a view controller object.

For example,

let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "your_view_controller_Identifier") as! YourViewController


来源: stackexchange

问:
Selenium Webdriver : How to navigate to child div and move foucs over specific div
Currently facing the issue in navigating to many div tags.
In my application, I have a grid which populates or load data in multiple div tags.

On mouseover, I have to click add comment option which gets loaded as lightbox popup.

Please guide me how to select add comment option.

```<code> <div ng-cell="">
<div class="inCell ng-scope">
<div class="cellDarkGray" ng2-class="{cellDarkGray: (row.getProperty('returnedRecordsNumber') != '0'),cellDarkGray: (row.getProperty('activityid') != '0'),cellDarkGray: (row.getProperty('returnedRecordsNumber') != '0')}">
<div class="cellOrange" ng-class="{cellRed: (row.getProperty('Impact') == '0'),cellOrange: (row.getProperty('activityid') != '0'), cellBlue: (row.getProperty('Impact') == '2')}"/>
<div class="cellWhite">
<div style="height:60px">
<div class="ng-hide" ng-show="(row.getProperty('commentFlag')== true) && (userRole =='ROLE_2') ">
<div class="ng-hide" ng-show="(row.getProperty('commentFlag')== true) && (userRole =='ROLE_1') ">
</div>
<div class="inCellData">
<div class="line1" ng-click="openDetails(row,'viewDetail')">
<span class="title1 ng-binding" ng-hide="row.getProperty('planned_typ')== 'NULL'">ORANGE PLANNED MAINTENANCE - </span>
<span class="title2 ng-binding" ng-hide="row.getProperty('deviceid')== 'NULL'">  BLCY810</span>
<!-- <span ng-hide="row.getProperty('myRouterName')== ''"> ||{{row.getProperty('myRouterName')}} ||</span> -->
</div>
<div class="line2">
<span class="title3"/>
<span class="ng-binding" ng-hide="row.getProperty('service_impact')== ''"> 1 - 5 MINS ||</span>
<span class="title3 ng-binding">09/JUN/2017 01:30:00 AM</span>
up to
<span class="title2 ng-binding">09/JUN/2017 03:30:00 AM</span>
||
<span class="ng-binding">EQUANT SHARED NETWORK</span>
</div>
<div class="line3">
</div>
<div>
<nav id="cbp-spmenu-s1" class="cbp-spmenu cbp-spmenu-vertical cbp-spmenu-left cbp-spmenu-open">
<a ng-click="openDetails(row,'viewDetail')">view details</a>
<div class="" ng-show="userRole =='ROLE_1'">
<a class="" ng-show="row.getProperty('internalFlag')=='Y'" ng-click="setUnsetInternal(row)">invisible to customer</a>
<a class="ng-hide" ng-show="row.getProperty('internalFlag')=='Z'" ng-click="row.getProperty('sourcesystem')=='Carrier Changes' && (row.getProperty('urgency')=='EMERGENCY' || row.getProperty('urgency')=='EXPEDITE') ? alertPastDataZEmergency() : alertPastDataZ() ">invisible to customer</a>
<a class="ng-hide" ng-show="row.getProperty('internalFlag')=='N'" ng-click="setUnsetInternal(row)">visible to customer</a>
<a class="ng-hide" ng-show="row.getProperty('internalFlag')=='X' || row.getProperty('internalFlag')=='H'" ng-click="alertPastDataX()">visible to customer</a>
</div>
<!-- Prod Consol Start -->
<a ng-show="userRole =='ROLE_1'" ng-click="openDetails(row, 'comment')">add a comment</a>
<!-- Prod Consol End -->
</nav>
</div>
</div>
</div>
</code>```

答:
First of all you have to move the mouse using Action class to the element so that Comment link will be visible. Then you have to perform action on that element.

You can do so like this -

```<code>WebElement elem = driver.findElement(By.xpath("//a[contains(text(), 'add a comment')]"));

Actions action = new Actions(driver);
action.moveToElement(elem).click().build().perform();
</code>```

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
Currently facing the issue in navigating to many div tags.
In my application, I have a grid which populates or load data in multiple div tags.

On mouseover, I have to click add comment option which gets loaded as lightbox popup.

Please guide me how to select add comment option.

ORANGE PLANNED MAINTENANCE -
  BLCY810

 1 - 5 MINS ||
09/JUN/2017 01:30:00 AM
up to
09/JUN/2017 03:30:00 AM
||
EQUANT SHARED NETWORK

view details

invisible to customer
invisible to customer
visible to customer
visible to customer

add a comment

Body:
First of all you have to move the mouse using Action class to the element so that Comment link will be visible. Then you have to perform action on that element.

You can do so like this -

WebElement elem = driver.findElement(By.xpath("//a[contains(text(), 'add a comment')]"));

Actions action = new Actions(driver);
action.moveToElement(elem).click().build().perform();

Hope this helps.


问:
How to properly use Git. Using CodeIgniter w/ DEVELOPMENT, TESTING, and PRODUCTION servers
Basically, I have a file index.php which should be different in each server. The file indicates which server it is on.

It has something like this:

On the DEVELOPMENT environment:

```<code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');
</code>```

On the TESTING environment:

```<code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing');
</code>```

On the PRODUCTION environment:

```<code>define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production');
</code>```

What's the proper way to maintain these files on each server without Git touching it?

I've added the file to .gitignore now, and I've untracked it using git rm --cached index.php then git push origin master for TESTING server and stable for PRODUCTION server.

答:
fyi,

if you use apache you don't really have to change the index.php file because you can use your htaccess file to define your environment

for example :

```<code>SetEnvIf Host yourdevdomain$ CI_ENV=development
SetEnvIf Host yourtestdomain$ CI_ENV=testing
SetEnvIf Host example.com$ CI_ENV=production
</code>```

In this case, you can set your needed Environments in your htaccess file, and you don't have to worry about overwriting some stuff with different files from different environments.

i think there is an option on nginx too

Take a look here

You can get more information from the official CI Documentation here.

Body:
Basically, I have a file index.php which should be different in each server. The file indicates which server it is on.

It has something like this:

On the DEVELOPMENT environment:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development');

On the TESTING environment:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'testing');

On the PRODUCTION environment:

define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'production');

What's the proper way to maintain these files on each server without Git touching it?

I've added the file to .gitignore now, and I've untracked it using git rm --cached index.php then git push origin master for TESTING server and stable for PRODUCTION server.

Body:
fyi,

if you use apache you don't really have to change the index.php file because you can use your htaccess file to define your environment

for example :

SetEnvIf Host yourdevdomain$ CI_ENV=development
SetEnvIf Host yourtestdomain$ CI_ENV=testing
SetEnvIf Host example.com$ CI_ENV=production

In this case, you can set your needed Environments in your htaccess file, and you don't have to worry about overwriting some stuff with different files from different environments.

i think there is an option on nginx too

Take a look here

You can get more information from the official CI Documentation here.


问:
Changing the domain name causes my image to not load in Wordpress
I have recently changed my wordpress installation a bit. I have configred IIS to have the website run as an application under a common domain name i have for multiple website.

So the main website name is www.example.com

The application is configured as www.example.com/sitename

Now i can access the site as www.example.com/sitename but all the images on the site have the src as "/wp-content/uploads/image.jpg" which causes the links to be broken as they point to www.example.com/wp-content.... instead of www.example.com/sitename/wp-content . how can i fix this.

I have tried the following.

Change the wp_options table. Set SiteURL and home to  http://www.example.com/sitename

Changed the Wp-Config.php file with the following parameters.

define( 'WP_ALLOW_MULTISITE', true );

define('MULTISITE', false);

define('SUBDOMAIN_INSTALL', false);

define('DOMAIN_CURRENT_SITE', 'www.abs-projects.co.uk/absuk');

define('WP_HOME','http://www.abs-projects.co.uk/absuk');

define('WP_SITEURL','http://www.abs-projects.co.uk/absuk');

define('PATH_CURRENT_SITE', '/');

答: Use WP Migrate DB or Velvet Blues Update URLs plugin to update all occurrences of 'www.example.com' to 'www.example.com/sitename' throughout the whole database. This should fix the problem.</p>


问:
Adding property to python dictionary not working according to hasattr
According to https://www.tutorialspoint.com/python/python_dictionary.htm I should be able to add a property to a dictionary quite easily, however the hasattr function does not seem to notice any change on the dictionary:

```<code>obj = {}
obj["foo"] = "bar"
print hasattr(obj, "foo") # prints False
</code>```

Why is this, and is there a workaround?

答:
You haven't added a property, you've added a key, which is what dictionaries are for.

The way to tell it a key exists in a dict is to use in:

```<code>print("foo" in bar)
</code>```

Body:
According to https://www.tutorialspoint.com/python/python_dictionary.htm I should be able to add a property to a dictionary quite easily, however the hasattr function does not seem to notice any change on the dictionary:

obj = {}
obj["foo"] = "bar"
print hasattr(obj, "foo") # prints False

Why is this, and is there a workaround?

Body:
You haven't added a property, you've added a key, which is what dictionaries are for.

The way to tell it a key exists in a dict is to use in:

print("foo" in bar)


问:
The application was unable to start correctly (0xc000007b)
I have a client/server app which I have been developing on a single PC. Now it needs two serial ports, so I borrowed a PC from a friend.

When I build my app and try to run or debug it (whether in the Delphi IDE or from Windows File manager), it errors "The application was unable to start correctly (0xc000007b)".

Googling doesn't bring up much, but seems to indicate that this is nothing Delphi specific and happens with other apps. It seems to be caused by calling into a 32 bit DLL from a 64 bit app or vice versa.

both PCs are Windows 7, 64 bit

both have Delphi Xe2 starter edition which can only handle 32 bits

The app runs fine on my PC, but not on my friend's

Other Delphi apps run just fine on both PCs

Can anyone give me a hint as to how to track this down?

答: I just ran into this issue. I searched for "C++" under my "Apps & Features" in Windows 10 control panel and noticed that some kind of update had just run a few days prior and installed VC++ Redistributable 2012-2017. The app that was running into the error message only required VC++ 2010. I uninstalled all of them and then reinstalled just 2010 x86/x64, and the error went away and the application functioned as expected. </p>


问:
Type detection: using variadic arguments to properly implement a function that calculates the mean
I am trying to understand how to properly implement a function to calculate the mathematical sample mean, with two initial required characteristics:

1) using variadic arguments.

2) not using two functions to do the job, that is, not using a caller function and then a second function that actually does the calculation.

3) function should be as generic as possible

I am very aware that a pretty similar question has been already asked: Calculate the average of several values using a variadic-template function However, while the accepted answer to that question seems to have taught the OP how to do the small part he didn't know, it presents a code that is actually wrong and does not compile.

So, my own first attempt was along these lines:

```<code>template <class... Args>
double mean(const Args & ... args)
{
    auto total = 0;
    for (auto value : { ...args })
    {
        total += value;
    }
    return (double)total / sizeof...(args);
}
</code>```

The problem here is that in the line auto total = 0; the compile naturally can't automatically identify the type that object total should have.

Then, my second attempt:

```<code>template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    T total = 0;
    for (auto value : { args... })
    {
        total += value;
    }
    return (T)(total / sizeof...(args));
}
</code>```

That version the following problem. It does not work if the caller calls the function with arguments of mixed type, like in mean(1, 2.5), where the first arguments is automatically detected as an int and the second is detected as a double.

I was able to solve that by doing the following:

```<code>template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    size_t argsSize = sizeof...(args);
    T total = t;
    T arg_array[] = { args... };
    for (size_t i = 0; i< argsSize; i++)
    {
        total += (T)arg_array[i];
    }
    return (T)(total / argsSize) ;
}
</code>```

This one works even when passed arguments are of different types (of course, provided that such types can be converted to T). The problem now, however, is that the function only works with a minimum of two arguments. If it is called like in mean(3.14), while it should return 3.14, it actually raises an error because T arg_array[] = { args... } can't be compiled because it is impossible to have a static array be created with size 0. Sure, I could substitute it for a dynamic array, but that would make me have to do one memory allocation and one memory deallocation every time that the function is called - which is an unacceptable waste.

So, what would be the correct way to implement such a function that avoids the mentioned problems and that follows my two initial conditions?

答:
To solve the problem of "the function only works with a minimum of two arguments" you can create a simple type traits to extract the first type

```<code>template <typename T0, typename ...>
struct firstType
 { using type = T0; };
</code>```

or, if you prefer (and, IMHO, is better), follow the std::common_type_t suggestion from Diego91b (+1).

You can write mean(), in C++11, as follows

```<code>template <typename ... Args>
typename firstType<Args...>::type mean (Args const & ... args)
// or typename std::common_type<Args...>::type mean (Args const & ... args)
 {
   using unused = int[];

   typename firstType<Args...>::type  total { 0 };
   // or typename std::common_type<Args...>::type  total { 0 };

   (void)unused { (total += args, 0)... };

   return total / sizeof...(args);
 }
</code>```

In C++14 can be semplified (and transformed in constexpr) as follows

```<code>template <typename ... Args>
constexpr auto mean (Args const & ... args)
 {
   using unused = int[];

   //typename firstType<Args...>::type  total { 0 };
   std::common_type_t<Args...>  total { 0 };

   (void)unused { (total += args, 0)... };

   return total / sizeof...(args);
 }
</code>```

In C++17 you can use fold expressions (as suggested by Passer By) and become realy easy

```<code>template <typename ... Args>
constexpr typename firstType<Args...>::type mean (Args const & ... args)
// or constexpr auto mean (Args const & ... args)
{
    return (... + args) / sizeof...(Args);
}
</code>```

The following is a full compilable C++11 example

```<code>#include <iostream>
#include <type_traits>

template <typename T0, typename ...>
struct firstType
 { using type = T0; };

template <typename ... Args>
typename firstType<Args...>::type mean (Args const & ... args)
// or typename std::common_type<Args...>::type mean (Args const & ... args)
 {
   using unused = int[];

   typename firstType<Args...>::type  total { 0 };
   // or typename std::common_type<Args...>::type  total { 0 };

   (void)unused { (total += args, 0)... };

   return total / sizeof...(args);
 }

int main()
 {
   std::cout << mean(2, 5.5) << std::endl; // print 3 (3.75 with common_type)
   std::cout << mean(5.5, 2) << std::endl; // print 3.75
   std::cout << mean(2) << std::endl;      // print 2
   // std::cout << mean() << std::endl; compilation error
 }
</code>```

-- EDIT --

The OP ask

do you know why exactly your solution gives 3 while using common_type gives 3.75 when calling mean(2, 5.5)?

Sure.

When you call mean(2, 5.5) using firstType, the type of the first argument is the type of 2, that is int. So total is declared as int and when 5.5 is added to total, is converted to int, so become 5, ad added to 2. The total become 7 and divided by 2, so (integer division) become 3.

On the countrary, if you call mean(5.5, 2) the firstType is the type of 5.5 that is double. So total become a double, add 2 and 5.5 and obtain 7.5. The last division (7.5 / 2) is a double division that give 3.75.

When you call mean(2, 5.5) (or mean(5.5, 2)) using std::common_type_t, the common type between int and double is double; so total is defined as double and the function return 7.5 / 2 that is 3.75.

-- EDIT 2 --

The OP ask

Is there a particular reason why using unused has to be specifically assigned an int[]? I tried changing it to typename std::common_type<Args...>::type, which seems to me would make the function more generic, but then it does not compile. Also, it does not work with double[].

The unused variable is ... unused.
Take in count that is declared only to permit, in it's initialization, to add in total the values of args, unpacking they.

The trick is the comma: observe

```<code>(total += args, 0)...
</code>```

The comma discard the left value (that is computed, so total is modified, but discarted) and return the right value. That is zero. An integer zero. And for this reason is int[].

The final result is that unused is initialized with { 0, 0, 0, ... }.

There is no need to transform it in something of different type; it's only a trick to use the args pack.

If you want, you can do it (by example) float; as follows

```<code>using unused = float[];

(void)unused { (total += args, 0.0f)... };
</code>```

(observe the 0.0f) but... why we should do it?

Body:
I am trying to understand how to properly implement a function to calculate the mathematical sample mean, with two initial required characteristics:

1) using variadic arguments.

2) not using two functions to do the job, that is, not using a caller function and then a second function that actually does the calculation.

3) function should be as generic as possible

I am very aware that a pretty similar question has been already asked: Calculate the average of several values using a variadic-template function However, while the accepted answer to that question seems to have taught the OP how to do the small part he didn't know, it presents a code that is actually wrong and does not compile.

So, my own first attempt was along these lines:

template <class... Args>
double mean(const Args & ... args)
{
    auto total = 0;
    for (auto value : { ...args })
    {
        total += value;
    }
    return (double)total / sizeof...(args);
}

The problem here is that in the line auto total = 0; the compile naturally can't automatically identify the type that object total should have.

Then, my second attempt:

template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    T total = 0;
    for (auto value : { args... })
    {
        total += value;
    }
    return (T)(total / sizeof...(args));
}

That version the following problem. It does not work if the caller calls the function with arguments of mixed type, like in mean(1, 2.5), where the first arguments is automatically detected as an int and the second is detected as a double.

I was able to solve that by doing the following:

template <class T, class... Args>
T mean(const T &t, const Args & ... args)
{
    size_t argsSize = sizeof...(args);
    T total = t;
    T arg_array[] = { args... };
    for (size_t i = 0; i< argsSize; i++)
    {
        total += (T)arg_array[i];
    }
    return (T)(total / argsSize) ;
}

This one works even when passed arguments are of different types (of course, provided that such types can be converted to T). The problem now, however, is that the function only works with a minimum of two arguments. If it is called like in mean(3.14), while it should return 3.14, it actually raises an error because T arg_array[] = { args... } can't be compiled because it is impossible to have a static array be created with size 0. Sure, I could substitute it for a dynamic array, but that would make me have to do one memory allocation and one memory deallocation every time that the function is called - which is an unacceptable waste.

So, what would be the correct way to implement such a function that avoids the mentioned problems and that follows my two initial conditions?

Body:
To solve the problem of "the function only works with a minimum of two arguments" you can create a simple type traits to extract the first type

template <typename T0, typename ...>
struct firstType
 { using type = T0; };

or, if you prefer (and, IMHO, is better), follow the std::common_type_t suggestion from Diego91b (+1).

You can write mean(), in C++11, as follows

template <typename ... Args>
typename firstType<Args...>::type mean (Args const & ... args)
// or typename std::common_type<Args...>::type mean (Args const & ... args)
 {
   using unused = int[];

   typename firstType<Args...>::type  total { 0 };
   // or typename std::common_type<Args...>::type  total { 0 };

   (void)unused { (total += args, 0)... };

   return total / sizeof...(args);
 }

In C++14 can be semplified (and transformed in constexpr) as follows

template <typename ... Args>
constexpr auto mean (Args const & ... args)
 {
   using unused = int[];

   //typename firstType<Args...>::type  total { 0 };
   std::common_type_t<Args...>  total { 0 };

   (void)unused { (total += args, 0)... };

   return total / sizeof...(args);
 }

In C++17 you can use fold expressions (as suggested by Passer By) and become realy easy

template <typename ... Args>
constexpr typename firstType<Args...>::type mean (Args const & ... args)
// or constexpr auto mean (Args const & ... args)
{
    return (... + args) / sizeof...(Args);
}

The following is a full compilable C++11 example

#include <iostream>
#include <type_traits>

template <typename T0, typename ...>
struct firstType
 { using type = T0; };

template <typename ... Args>
typename firstType<Args...>::type mean (Args const & ... args)
// or typename std::common_type<Args...>::type mean (Args const & ... args)
 {
   using unused = int[];

   typename firstType<Args...>::type  total { 0 };
   // or typename std::common_type<Args...>::type  total { 0 };

   (void)unused { (total += args, 0)... };

   return total / sizeof...(args);
 }

int main()
 {
   std::cout << mean(2, 5.5) << std::endl; // print 3 (3.75 with common_type)
   std::cout << mean(5.5, 2) << std::endl; // print 3.75
   std::cout << mean(2) << std::endl;      // print 2
   // std::cout << mean() << std::endl; compilation error
 }

-- EDIT --

The OP ask

do you know why exactly your solution gives 3 while using common_type gives 3.75 when calling mean(2, 5.5)?

Sure.

When you call mean(2, 5.5) using firstType, the type of the first argument is the type of 2, that is int. So total is declared as int and when 5.5 is added to total, is converted to int, so become 5, ad added to 2. The total become 7 and divided by 2, so (integer division) become 3.

On the countrary, if you call mean(5.5, 2) the firstType is the type of 5.5 that is double. So total become a double, add 2 and 5.5 and obtain 7.5. The last division (7.5 / 2) is a double division that give 3.75.

When you call mean(2, 5.5) (or mean(5.5, 2)) using std::common_type_t, the common type between int and double is double; so total is defined as double and the function return 7.5 / 2 that is 3.75.

-- EDIT 2 --

The OP ask

Is there a particular reason why using unused has to be specifically assigned an int[]? I tried changing it to typename std::common_type<Args...>::type, which seems to me would make the function more generic, but then it does not compile. Also, it does not work with double[].

The unused variable is ... unused.
Take in count that is declared only to permit, in it's initialization, to add in total the values of args, unpacking they.

The trick is the comma: observe

(total += args, 0)...

The comma discard the left value (that is computed, so total is modified, but discarted) and return the right value. That is zero. An integer zero. And for this reason is int[].

The final result is that unused is initialized with { 0, 0, 0, ... }.

There is no need to transform it in something of different type; it's only a trick to use the args pack.

If you want, you can do it (by example) float; as follows

using unused = float[];

(void)unused { (total += args, 0.0f)... };

(observe the 0.0f) but... why we should do it?


问:
Need to set timing for this animation in Jquery
I need to set timing (Delay between two words) in this animation.

I'm following this link for reference.

Provide your suggestions.

答: More details would be useful, but based on what you've given it seems like you can achieve this by using setTimeout() function of JavaScript to call a function after a fixed delay.


问:
Django - How to add data to a ManyToMany field model?
I have the following models, view and template:

models.py:

```<code>class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id
</code>```

views.py:

```<code>def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})
</code>```

snippet from template:

```<code><form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">
    <table class="table table-striped" id="myTable">
        <tr>
            <th>ID</th>
            <th>Material ID</th>
            <th>Series Title</th>
            <th>Season Tile</th>
            <th>Season Number</th>
            <th>Episode Title</th>
            <th>Episode Number</th>
            <th>Create Batch</th>
        </tr>
        {%  for i in assets %}<tr>
            <td>{{i.pk}}</td>
            <td><a href="/repo/{{ i.id}}">{{i.material_id}}</a></td>
            <td>{{i.series_title}}</td>
            <td>{{i.season_title}}</td>
            <td>{{i.season_number}}</td>
            <td>{{i.episode_title}}</td>
            <td>{{i.episode_number}}</td>
            <td>
                <input type="checkbox" name="batch" value="{{i.pk}}">
            </td>
        </tr>{% endfor %}
    </table>
    </form>
</code>```

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.

答:
Thanks to help from both answers I was able to get this working, this is how i did it:</p>

```<code>def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')

        info = Batch.objects.create(user_id=request.user.id)
        for item in batch_list:
            info.material_id.add(item)
</code>```

Body:
I have the following models, view and template:

models.py:

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

views.py:

def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})

snippet from template:

<form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">

            ID
            Material ID
            Series Title
            Season Tile
            Season Number
            Episode Title
            Episode Number
            Create Batch

        {%  for i in assets %}

            {{i.pk}}
            {{i.material_id}}
            {{i.series_title}}
            {{i.season_title}}
            {{i.season_number}}
            {{i.episode_title}}
            {{i.episode_number}}

                <input type="checkbox" name="batch" value="{{i.pk}}">

{% endfor %}

    </form>

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.

Body:
Thanks to help from both answers I was able to get this working, this is how i did it:

def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')

        info = Batch.objects.create(user_id=request.user.id)
        for item in batch_list:
            info.material_id.add(item)


问:
Khan academy: JavaScript loop taking too long

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insertion-sort. So far I have:

```<code>var insert = function(array, rightIndex, value) {
for(var j = rightIndex;
    j >= 0 && array[j] > value;
    j--) {
    array[j + 1] = array[j];
}
array[j + 1] = value;
};

var insertionSort = function(array) {

for(var i= 1;  i < array.length ; i++ ) {
    insert(array, i ,array[i+1] );
}

};

var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);
</code>```

You can see the line of code in the screenshot which appears to be the problem , but it looks fine to me. What am I doing wrong?

答:
You’re starting rightIndex off at i and moving the value array[i + 1], but i reaches array.length and insert starts by setting the element at rightIndex + 1. This will cause the array to grow.

Move the current element and start at the previous index instead:

```<code>for (var i = 1; i < array.length; i++) {
    insert(array, i - 1,array[i]);
}
</code>```

One way to catch this when debugging is to seal your array so it can’t grow:

```<code>var array = Object.seal([22, 11, 99, 88, 9, 7, 42]);
</code>```

This only works in strict mode, though. If you’re in sloppy mode, it will just hide mistakes.

Body:
I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/insertion-sort/p/challenge-implement-insertion-sort. So far I have:

var insert = function(array, rightIndex, value) {
for(var j = rightIndex;
    j >= 0 && array[j] > value;
    j--) {
    array[j + 1] = array[j];
}
array[j + 1] = value;
};

var insertionSort = function(array) {

for(var i= 1;  i < array.length ; i++ ) {
    insert(array, i ,array[i+1] );
}

};

var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);

You can see the line of code in the screenshot which appears to be the problem , but it looks fine to me. What am I doing wrong?

Body:
You’re starting rightIndex off at i and moving the value array[i + 1], but i reaches array.length and insert starts by setting the element at rightIndex + 1. This will cause the array to grow.

Move the current element and start at the previous index instead:

for (var i = 1; i < array.length; i++) {
    insert(array, i - 1,array[i]);
}

One way to catch this when debugging is to seal your array so it can’t grow:

var array = Object.seal([22, 11, 99, 88, 9, 7, 42]);

This only works in strict mode, though. If you’re in sloppy mode, it will just hide mistakes.


问:
React Native PushNotification onNotification method
I am Getting notification from server. After receiving the notification, When I click on it, then again the same notification is coming. More I click on it more the notifications are coming.

My question is whether I am following the right approach in the above code? If not then please suggest me the correct one. How to handle the click of notification? So, that i can show the particular view on its click.

I'm using the following link
https://github.com/zo0r/react-native-push-notification

Thanks in advance :)

```<code>PushNotification.configure({

      onNotification: function (notification) {
        console.log('NOTIFICATION:', notification)
         PushNotification.localNotification({
          largeIcon: "ic_launcher",
          title: notification.title,
          message: notification.message,
        });

      },
      senderID: "my sender ID",
      popInitialNotification: true,
      requestPermissions: true,
    });
</code>```

答:
I have tried the following approach to solve this problem</p>

```<code>PushNotification.configure({

      onNotification: function (notification) {
        console.log('NOTIFICATION:', notification)
        const clicked = notification.userInteraction;
        if (clicked) {
         ToastAndroid.show(notification.message,ToastAndroid.CENTER);
        } else {
          PushNotification.localNotification({
            largeIcon: "ic_launcher",
            title: "Test",
            //message: JSON.stringify(xyz.notificationResponse.bookingId),
          });
        }
        ToastAndroid.show(notification.message,ToastAndroid.CENTER);
      },

      senderID: "your sender id",
      popInitialNotification: true,
      requestPermissions: true,
    });
</code>```

Body:
I am Getting notification from server. After receiving the notification, When I click on it, then again the same notification is coming. More I click on it more the notifications are coming.

My question is whether I am following the right approach in the above code? If not then please suggest me the correct one. How to handle the click of notification? So, that i can show the particular view on its click.

I'm using the following link
https://github.com/zo0r/react-native-push-notification

Thanks in advance :)

PushNotification.configure({

      onNotification: function (notification) {
        console.log('NOTIFICATION:', notification)
         PushNotification.localNotification({
          largeIcon: "ic_launcher",
          title: notification.title,
          message: notification.message,
        });

      },
      senderID: "my sender ID",
      popInitialNotification: true,
      requestPermissions: true,
    });

Body:
I have tried the following approach to solve this problem

PushNotification.configure({

      onNotification: function (notification) {
        console.log('NOTIFICATION:', notification)
        const clicked = notification.userInteraction;
        if (clicked) {
         ToastAndroid.show(notification.message,ToastAndroid.CENTER);
        } else {
          PushNotification.localNotification({
            largeIcon: "ic_launcher",
            title: "Test",
            //message: JSON.stringify(xyz.notificationResponse.bookingId),
          });
        }
        ToastAndroid.show(notification.message,ToastAndroid.CENTER);
      },

      senderID: "your sender id",
      popInitialNotification: true,
      requestPermissions: true,
    });


问:
Authentication Refresh Token
Building a login form using Reactjs, redux, axios and redux-thunk. I have two tokens - one named access token and refresh token.

When the user is authenticated, store the access token which should last for 12 hours. The refresh token is also provided and will last 30 days.

Once the access token has expired need to check the timestamp (date) if access token is expired.

How can I update the access token once expired? Token data looks like this so I have a timestamp to check against:

```<code>{
  "access_token": "toolongtoinclude",
  "token_type": "bearer",
  "refresh_token": "toolongtoinclude",
  "expires_in": 43199,
  "scope": "read write",
  "roles": [
    "USER"
  ],
  "profile_id": "b4d1e37d-7d05-4eb3-98de-0580d3074a0d",
  "jti": "e975db65-e3b7-4034-a6e4-9a3023c3d175"
}
</code>```

Here are my actions to save, get and update tokens from storage. I'm just unsure on how to refresh the token.

```<code>export function submitLoginUser(values, dispatch) {
    dispatch({type: constants.LOADING_PAGE, payload: { common: true }})
    return axios.post(Config.API_URL + '/oauth/token', {
            username: values.email,
            password: values.password,
            scope: Config.WEBSERVICES_SCOPE,
            grant_type: Config.WEBSERVICES_GRANT_TYPE_PASSWORD
        },
        {
            transformRequest: function (data) {
                var str = [];
                for (var p in data) {
                    str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]));
                }

                return str.join('&');
            },
            headers: {
                'Authorization': 'Basic ' + window.btoa(Config.WEBSERVICES_AUTH),
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            const {access_token, refresh_token} = response.data;
            dispatch({type: constants.LOADING_PAGE, payload: { common: false }})
            dispatch({
                type: constants.LOGIN_SUCCESS,
                payload: {
                    access_token: access_token,
                    refresh_token: refresh_token
                }
            });
            saveTokens(response)
            browserHistory.push('/questions');
            refreshToken(response);
        })
        .catch(error => {
            dispatch({type: constants.LOADING_PAGE, payload: { common: false }})
            //401 Error catch
            if(error.response.status === 401) {
              throw new SubmissionError({username: 'User is not authenticated', _error: message.LOGIN.loginUnAuth})
            }
            //Submission Error
            throw new SubmissionError({username: 'User does not exist', _error: message.LOGIN.loginFailed})
        })
}

/**
 * Save tokens in local storage and automatically add token within request
 * @param params
 */
export function saveTokens(params) {
    const {access_token, refresh_token} = params.data;
    localStorage.setItem('access_token', access_token);
    if (refresh_token) {
        localStorage.setItem('refresh_token', refresh_token);
    }
    //todo fix this later
    getinstanceAxios().defaults.headers.common['Authorization'] = `bearer ${access_token}`
}

/**
 *
 */
export function getTokens() {
    let accessToken = localStorage.getItem('access_token');
    return accessToken
}

/**
 * update the get requests
 */
export function updateTokenFromStorage() {
    const tokenLocalStorage = getTokens();
    getinstanceAxios().defaults.headers.common['Authorization'] = `bearer ${tokenLocalStorage}`;
}

/**
 * Refresh user access token
 */
export function refreshToken(dispatch) {
    //check timestamp
    //check access expired - 401

    //request new token, pass refresh token
    //store both new access and refresh tokens

}
</code>```

答:
check this out:

https://github.com/mzabriskie/axios#interceptors

I think this can help you. You intercept your request and make your validations.

EDIT

Here is the code I've tried to use in my store to test, not getting any log back

```<code>import { createStore, applyMiddleware, compose } from 'redux'
import { devTools, persistState } from 'redux-devtools'
import axios from 'axios'
import Middleware from '../middleware'
import Reducer from '../reducers/reducer'
import DevTools from '../containers/DevTools'

let finalCreateStore

if (__DEVELOPMENT__ && __DEVTOOLS__) {

  finalCreateStore = compose(
   applyMiddleware.apply(this, Middleware),
   // Provides support for DevTools:
      DevTools.instrument(),
   // Optional. Lets you write ?debug_session=<key> in address bar to persist debug sessions
   persistState(getDebugSessionKey())
 )(createStore)
} else {
  finalCreateStore = compose(
   applyMiddleware.apply(this, Middleware)
 )(createStore)
}

function getDebugSessionKey() {
  // You can write custom logic here!
  // By default we try to read the key from ?debug_session=<key> in the address bar
  const matches = window.location.href.match(/[?&]debug_session=([^&]+)\b/)
  return (matches && matches.length > 0)? matches[1] : null
}

axios.interceptors.response.use((err) => {
    if (err.status === 401) {
        console.log('ACCESS TOKEN EXPIRED!');
    }
});

export const store = finalCreateStore(Reducer)
</code>```

Title: Authentication Refresh Token

Body:
Building a login form using Reactjs, redux, axios and redux-thunk. I have two tokens - one named access token and refresh token.

When the user is authenticated, store the access token which should last for 12 hours. The refresh token is also provided and will last 30 days.

Once the access token has expired need to check the timestamp (date) if access token is expired.

How can I update the access token once expired? Token data looks like this so I have a timestamp to check against:

{
  "access_token": "toolongtoinclude",
  "token_type": "bearer",
  "refresh_token": "toolongtoinclude",
  "expires_in": 43199,
  "scope": "read write",
  "roles": [
    "USER"
  ],
  "profile_id": "b4d1e37d-7d05-4eb3-98de-0580d3074a0d",
  "jti": "e975db65-e3b7-4034-a6e4-9a3023c3d175"
}

Here are my actions to save, get and update tokens from storage. I'm just unsure on how to refresh the token.

export function submitLoginUser(values, dispatch) {
    dispatch({type: constants.LOADING_PAGE, payload: { common: true }})
    return axios.post(Config.API_URL + '/oauth/token', {
            username: values.email,
            password: values.password,
            scope: Config.WEBSERVICES_SCOPE,
            grant_type: Config.WEBSERVICES_GRANT_TYPE_PASSWORD
        },
        {
            transformRequest: function (data) {
                var str = [];
                for (var p in data) {
                    str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]));
                }

                return str.join('&');
            },
            headers: {
                'Authorization': 'Basic ' + window.btoa(Config.WEBSERVICES_AUTH),
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            const {access_token, refresh_token} = response.data;
            dispatch({type: constants.LOADING_PAGE, payload: { common: false }})
            dispatch({
                type: constants.LOGIN_SUCCESS,
                payload: {
                    access_token: access_token,
                    refresh_token: refresh_token
                }
            });
            saveTokens(response)
            browserHistory.push('/questions');
            refreshToken(response);
        })
        .catch(error => {
            dispatch({type: constants.LOADING_PAGE, payload: { common: false }})
            //401 Error catch
            if(error.response.status === 401) {
              throw new SubmissionError({username: 'User is not authenticated', _error: message.LOGIN.loginUnAuth})
            }
            //Submission Error
            throw new SubmissionError({username: 'User does not exist', _error: message.LOGIN.loginFailed})
        })
}

/**
 * Save tokens in local storage and automatically add token within request
 * @param params
 */
export function saveTokens(params) {
    const {access_token, refresh_token} = params.data;
    localStorage.setItem('access_token', access_token);
    if (refresh_token) {
        localStorage.setItem('refresh_token', refresh_token);
    }
    //todo fix this later
    getinstanceAxios().defaults.headers.common['Authorization'] = `bearer ${access_token}`
}

/**
 *
 */
export function getTokens() {
    let accessToken = localStorage.getItem('access_token');
    return accessToken
}

/**
 * update the get requests
 */
export function updateTokenFromStorage() {
    const tokenLocalStorage = getTokens();
    getinstanceAxios().defaults.headers.common['Authorization'] = `bearer ${tokenLocalStorage}`;
}

/**
 * Refresh user access token
 */
export function refreshToken(dispatch) {
    //check timestamp
    //check access expired - 401

    //request new token, pass refresh token
    //store both new access and refresh tokens

}

Body:
check this out:

https://github.com/mzabriskie/axios#interceptors

I think this can help you. You intercept your request and make your validations.

EDIT

Here is the code I've tried to use in my store to test, not getting any log back

import { createStore, applyMiddleware, compose } from 'redux'
import { devTools, persistState } from 'redux-devtools'
import axios from 'axios'
import Middleware from '../middleware'
import Reducer from '../reducers/reducer'
import DevTools from '../containers/DevTools'

let finalCreateStore

if (__DEVELOPMENT__ && __DEVTOOLS__) {

  finalCreateStore = compose(
   applyMiddleware.apply(this, Middleware),
   // Provides support for DevTools:
      DevTools.instrument(),
   // Optional. Lets you write ?debug_session=<key> in address bar to persist debug sessions
   persistState(getDebugSessionKey())
 )(createStore)
} else {
  finalCreateStore = compose(
   applyMiddleware.apply(this, Middleware)
 )(createStore)
}

function getDebugSessionKey() {
  // You can write custom logic here!
  // By default we try to read the key from ?debug_session=<key> in the address bar
  const matches = window.location.href.match(/[?&]debug_session=([^&]+)\b/)
  return (matches && matches.length > 0)? matches[1] : null
}

axios.interceptors.response.use((err) => {
    if (err.status === 401) {
        console.log('ACCESS TOKEN EXPIRED!');
    }
});

export const store = finalCreateStore(Reducer)


问:
Converting object to CLOB
I have a object array( it is an output of a native query in Oracle database) out of which the first element is of CLOB data type which needs to converted to a java String object. How would I achieve this? Please help.

```<code> String sql = "select id, data from mytable";
            List< Object[] > results = getEntityManager().createNativeQuery(sql).getResultList();
Map< Long, String > map = new HashMap<>();
        for (Object[] result : results) {
            map.put(((Number) result[0]).longValue(), (String) result[1]);
        }
</code>```

data is a column in mydata table with CLOB data type.
result(1) would have my CLOB data

While putting in the HashMap I need to parse the result(1) as String.

答:
If the length of the CLOB is small enough ( <Integer.MAX_VALUE) you can do the following :

```<code>clob.getSubString(1, (int) clob.length());
</code>```

(Just have a look at this question)

EDIT :

The code you submitted in your question should become:

```<code>String sql = "select id, data from mytable";
List< Object[] > results = getEntityManager().createNativeQuery(sql).getResultList();
Map< Long, String > map = new HashMap<>();
Clob clob = (Clob)result[1];
String value = clob.getSubString(1, (int) clob.length());
map.put(((Number) result[0]).longValue(), value);
</code>```

Please note that the loop in your original code was absolutely useless so I removed it.

Check also that result[1] is a java.sql.Clob

Title: Converting object to CLOB

Body:
I have a object array( it is an output of a native query in Oracle database) out of which the first element is of CLOB data type which needs to converted to a java String object. How would I achieve this? Please help.

 String sql = "select id, data from mytable";
            List< Object[] > results = getEntityManager().createNativeQuery(sql).getResultList();
Map< Long, String > map = new HashMap<>();
        for (Object[] result : results) {
            map.put(((Number) result[0]).longValue(), (String) result[1]);
        }

data is a column in mydata table with CLOB data type.
result(1) would have my CLOB data

While putting in the HashMap I need to parse the result(1) as String.

Body:
If the length of the CLOB is small enough ( <Integer.MAX_VALUE) you can do the following :

clob.getSubString(1, (int) clob.length());

(Just have a look at this question)

EDIT :

The code you submitted in your question should become:

String sql = "select id, data from mytable";
List< Object[] > results = getEntityManager().createNativeQuery(sql).getResultList();
Map< Long, String > map = new HashMap<>();
Clob clob = (Clob)result[1];
String value = clob.getSubString(1, (int) clob.length());
map.put(((Number) result[0]).longValue(), value);

Please note that the loop in your original code was absolutely useless so I removed it.

Check also that result[1] is a java.sql.Clob


问:
JSTree - disable selection on a parent node, but allow expansion on click
I'm trying out the excellent JSTree 3.0.2.  I have a tree with one level of child nodes.  When a parent node is clicked I want it to expand, but I don't want the parent node to be selectable - only the child nodes should be selectable.

I can get the parent nodes to open on click using:

```<code>$("#jstree_div").bind("select_node.jstree", function (e, data) {
return data.instance.toggle_node(data.node);
});
</code>```

But I can't figure out how to make the parent nodes non-selectable.

I've created a type and have set "select_node" to false:

```<code>"treeParent" : {
    "hover_node" : true,
    "select_node" : false
}
</code>```

And then assigned that to the parent node using:

```<code>data-jstree='{"type":"treeParent"}'
</code>```

But the parent nodes are still selectable.  I've created a jsfiddle here:
http://jsfiddle.net/john_otoole/RY7n6/7/
In that example I am using the following to show whether something is selectable:

```<code>$('#jstree_div').on("changed.jstree", function (e, data) {
  $("#selected_element_div").text("Selected built-in: " + data.selected);
});
</code>```

Any ideas on how to prevent selection of a parent node?

答:
I had different issue to prevent select_node.jstree event for disabled items, but I think it can work for your case.

I solved my problem by using 'conditionalselect' plugin.

```<code>$('#jstree').jstree({
  'conditionalselect' : function (node) {
    // Check node and call some method
    return (node['someProperty']) ? true : false;
  },
  'plugins' : ['conditionalselect'],
  'core' : {
    <core options>
  }
});
</code>```

You can check the node on click and trigger some expand collapse logic.
You can also check this post : prevent jsTree node select

Body:
I'm trying out the excellent JSTree 3.0.2.  I have a tree with one level of child nodes.  When a parent node is clicked I want it to expand, but I don't want the parent node to be selectable - only the child nodes should be selectable.

I can get the parent nodes to open on click using:

$("#jstree_div").bind("select_node.jstree", function (e, data) {
return data.instance.toggle_node(data.node);
});

But I can't figure out how to make the parent nodes non-selectable.

I've created a type and have set "select_node" to false:

"treeParent" : {
    "hover_node" : true,
    "select_node" : false
}

And then assigned that to the parent node using:

data-jstree='{"type":"treeParent"}'

But the parent nodes are still selectable.  I've created a jsfiddle here:
http://jsfiddle.net/john_otoole/RY7n6/7/
In that example I am using the following to show whether something is selectable:

$('#jstree_div').on("changed.jstree", function (e, data) {
  $("#selected_element_div").text("Selected built-in: " + data.selected);
});

Any ideas on how to prevent selection of a parent node?

Body:
I had different issue to prevent select_node.jstree event for disabled items, but I think it can work for your case.

I solved my problem by using 'conditionalselect' plugin.

$('#jstree').jstree({
  'conditionalselect' : function (node) {
    // Check node and call some method
    return (node['someProperty']) ? true : false;
  },
  'plugins' : ['conditionalselect'],
  'core' : {
    <core options>
  }
});

You can check the node on click and trigger some expand collapse logic.
You can also check this post : prevent jsTree node select


问:
my code get stuck in infinte loop after pressing yes button in dialog builder in function onRequestPermissionsResult
my code get stuck in infinte loop after pressing yes button in dialog builder in function onRequestPermissionsResult .Again and again builder came out when i press yes.Also after pressing no ,my app exit but when i open it again it shows the dialog builder

```<code>@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {

        switch (requestCode) {
            case 0: {
                boolean anyPermissionDenied = false;
                boolean neverAskAgainSelected = false;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        anyPermissionDenied = true;
                    }
                }
                if (!anyPermissionDenied)
                {
                    getConfigFromServer();
                } else {
                    String message = "";
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))  {

                        requestPermission();
                    }
                    else
                    {
                        message = "You have to give all permission to continue";
                    }
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setMessage(message);
                            alertDialogBuilder.setPositiveButton("yes",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int arg1) {
                                        requestPermission();

                                        }
                                    });

                    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }
</code>```

code for request permission

```<code>    void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        } else {

            getConfigFromServer();
            //navigateToNextActivity();
        }
    }
</code>```

答:
I test your code and its having loop so have edited your code you it will help you.

```<code>import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

String[] MY_PERMISSIONS={
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION,
};
ArrayList<Integer> deniedPermissionPosition=new ArrayList<>();
String[] AGAINPERMISSIONS;
boolean firstTime=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission(firstTime);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {

    switch (requestCode) {
        case 0: {
            boolean anyPermissionDenied = false;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    anyPermissionDenied = true;
                    firstTime=false;
                    deniedPermissionPosition.add(i);
                }
            }
            if (!anyPermissionDenied)
            {
                getConfigFromServer();
            } else {
                Log.e("DEBUG","Permission Denied");
                String message = "";
                    message = "You have to give all permission to continue";
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setMessage(message);
                    alertDialogBuilder.setPositiveButton("yes",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    requestPermission(firstTime);
                                }
                            });

                    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
            }
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
void requestPermission(boolean firstTime) {
    if(firstTime){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, MY_PERMISSIONS, 0);
        } else {

            getConfigFromServer();
        }
    }else {
        AGAINPERMISSIONS=new String[deniedPermissionPosition.size()];
        for (int permissions = 0; permissions < deniedPermissionPosition.size(); permissions++) {
            AGAINPERMISSIONS[permissions]=MY_PERMISSIONS[deniedPermissionPosition.get(permissions)];
        }
        ActivityCompat.requestPermissions(this, AGAINPERMISSIONS, 0);
    }
}

private void getConfigFromServer() {
    Log.e("DEBUG","Method call");
}
}
</code>```

If you have any question you can post in comment.

Body:
my code get stuck in infinte loop after pressing yes button in dialog builder in function onRequestPermissionsResult .Again and again builder came out when i press yes.Also after pressing no ,my app exit but when i open it again it shows the dialog builder

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {

        switch (requestCode) {
            case 0: {
                boolean anyPermissionDenied = false;
                boolean neverAskAgainSelected = false;
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        anyPermissionDenied = true;
                    }
                }
                if (!anyPermissionDenied)
                {
                    getConfigFromServer();
                } else {
                    String message = "";
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))  {

                        requestPermission();
                    }
                    else
                    {
                        message = "You have to give all permission to continue";
                    }
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setMessage(message);
                            alertDialogBuilder.setPositiveButton("yes",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int arg1) {
                                        requestPermission();

                                        }
                                    });

                    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

code for request permission

    void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA,
                    Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        } else {

            getConfigFromServer();
            //navigateToNextActivity();
        }
    }

Body:
I test your code and its having loop so have edited your code you it will help you.

import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

String[] MY_PERMISSIONS={
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_FINE_LOCATION,
};
ArrayList<Integer> deniedPermissionPosition=new ArrayList<>();
String[] AGAINPERMISSIONS;
boolean firstTime=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    requestPermission(firstTime);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull final int[] grantResults) {

    switch (requestCode) {
        case 0: {
            boolean anyPermissionDenied = false;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    anyPermissionDenied = true;
                    firstTime=false;
                    deniedPermissionPosition.add(i);
                }
            }
            if (!anyPermissionDenied)
            {
                getConfigFromServer();
            } else {
                Log.e("DEBUG","Permission Denied");
                String message = "";
                    message = "You have to give all permission to continue";
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setMessage(message);
                    alertDialogBuilder.setPositiveButton("yes",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    requestPermission(firstTime);
                                }
                            });

                    alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });

                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
            }
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

}
void requestPermission(boolean firstTime) {
    if(firstTime){

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, MY_PERMISSIONS, 0);
        } else {

            getConfigFromServer();
        }
    }else {
        AGAINPERMISSIONS=new String[deniedPermissionPosition.size()];
        for (int permissions = 0; permissions < deniedPermissionPosition.size(); permissions++) {
            AGAINPERMISSIONS[permissions]=MY_PERMISSIONS[deniedPermissionPosition.get(permissions)];
        }
        ActivityCompat.requestPermissions(this, AGAINPERMISSIONS, 0);
    }
}

private void getConfigFromServer() {
    Log.e("DEBUG","Method call");
}
}

If you have any question you can post in comment.


问:
Share single string via Apache 2
Is it possible to have a Apache 2 server that shares only one string - "Hello World!" ?
I want to use GET request and get only "Hello World!" from the server. How can I do this ?</p>

答: You can simply change the content of index.html in your www folder to be Hello World

Title: Share single string via Apache 2


问:
Cannot read file within jar file
I developped an application using spring-boot, I need to read a csv file that contain emails.

this is a snippet how I do:

```<code>public Set<String> readFile() {
        Set<String> setOfEmails = new HashSet<String>();

        try {
            ClassPathResource cl = new ClassPathResource("myFile.csv");
            File file = cl.getFile();
            Stream<String> stream = Files.lines(Paths.get(file.getPath()));
            setOfEmails = stream.collect(Collectors.toSet());

        } catch (IOException e) {
            logger.error("file error " + e.getMessage());
        }
        return setOfEmails;
    }
</code>```

It works when I execute the application using eclipse: run As --> spring-boot app

But when I put the jar into a container docker the method readFile() return an empty set.

I use gradle for build the application

Would you have any ideas ?

答:
I do not work with Spring, but I found the Javadoc of ClassPathResource that states:

Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.

try with getURL() instead of getFile().

ContentLicense: CC BY-SA 4.0

Title: Cannot read file within jar file

Body:
I developped an application using spring-boot, I need to read a csv file that contain emails.

this is a snippet how I do:

public Set<String> readFile() {
        Set<String> setOfEmails = new HashSet<String>();

        try {
            ClassPathResource cl = new ClassPathResource("myFile.csv");
            File file = cl.getFile();
            Stream<String> stream = Files.lines(Paths.get(file.getPath()));
            setOfEmails = stream.collect(Collectors.toSet());

        } catch (IOException e) {
            logger.error("file error " + e.getMessage());
        }
        return setOfEmails;
    }

It works when I execute the application using eclipse: run As --> spring-boot app

But when I put the jar into a container docker the method readFile() return an empty set.

I use gradle for build the application

Would you have any ideas ?


问:
Spring Boot Integration Test Results in 401
We've got a Spring Boot 1.4 web app the exposes a REST api, and we want to run some integration tests.

In our test, we get Spring Boot to spin up the web app locally and then we make some calls against the api.

If we simply run the web app itself and hit the endpoint, we get 200/OK response, which is expected. Running the test, however, we are getting a 401/Unauthorized server response.

Where would I look to see what might be causing the authorization error?

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplication3IT {
    private final Logger log = LoggerFactory.getLogger(DemoApplication3IT.class);

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void getFunky() throws IOException {
        ResponseEntity<String> response =
            this.restTemplate.getForEntity("http://localhost:8080/api/funky", String.class);
        log.info("TestRestTemplate response Code: " + response.getStatusCode());
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); // Expected :200, Actual   :401
    }
}
</code>```

It's strange that hitting the endpoint with a browser works fine, but the integration test fails.

答:
You can also add it like this in your test class to save duplicating the application.properties:

```<code> @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = { TestDataSourceConfig.class },
        properties = {
                "security.basic.enabled=false"
        })
</code>```

It should also be turned off by this annotation:

```<code>@AutoConfigureMockMvc(secure = false)
</code>```

but currently I can't get that to work (maybe there'll be an answer in future: Spring Boot integration test ignoring secure=false in AutoConfigureMockMvc annotation, get 401 )

Body:
We've got a Spring Boot 1.4 web app the exposes a REST api, and we want to run some integration tests.

In our test, we get Spring Boot to spin up the web app locally and then we make some calls against the api.

If we simply run the web app itself and hit the endpoint, we get 200/OK response, which is expected. Running the test, however, we are getting a 401/Unauthorized server response.

Where would I look to see what might be causing the authorization error?

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class DemoApplication3IT {
    private final Logger log = LoggerFactory.getLogger(DemoApplication3IT.class);

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void getFunky() throws IOException {
        ResponseEntity<String> response =
            this.restTemplate.getForEntity("http://localhost:8080/api/funky", String.class);
        log.info("TestRestTemplate response Code: " + response.getStatusCode());
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); // Expected :200, Actual   :401
    }
}

It's strange that hitting the endpoint with a browser works fine, but the integration test fails.

Body:
You can also add it like this in your test class to save duplicating the application.properties:

 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = { TestDataSourceConfig.class },
        properties = {
                "security.basic.enabled=false"
        })

It should also be turned off by this annotation:

@AutoConfigureMockMvc(secure = false)

but currently I can't get that to work (maybe there'll be an answer in future: Spring Boot integration test ignoring secure=false in AutoConfigureMockMvc annotation, get 401 )


问:
Can you use WebAudioMidi to send midi notes to a DAW?
Can you use Javascript to send notes from the browser to a DAW (ableton, cubase etc)?

I'm thinking of writing a demo for webaudiomidi and want to have functions that generate midi notes that would be played by a VSTi in a DAW. Has anyone had a chance to try this?

答: I've managed to do this. All I needed was a virtual midi device created in OSX, and the browser just sends midi data to that virtual device, whilst the DAW was listening on the midi in from that virtual device</p>


问:
how to set proxy in casperjs code
Here are some options i already try but none of them work for me

is there any way to change proxy before we hit any particular website ?

```<code>var casper = require("casper").create({
setProxy: "proxy here",
// --proxy: "proxy here",
webSecurityEnabled: false,
verbose: true,
logLevel: "debug",
waitTimeout: 100000,
pageSettings: {
    userAgent: "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0",
    proxy: 'proxy here'
}});
var url = 'http://whatismyipaddress.com/';
var fs = require('fs');
var path = 'ip_check.txt';
casper.start(url, function() {
    casper.cli.options["proxy"] = "proxy here";
    var js = this.evaluate(function() {
        return document;
    });
    fs.write(path,js.all[0].outerHTML,'w');
});
casper.run();
</code>```

答:
You can send a proxy argument like this

casperjs --proxy="switchproxy.proxify.net:7498" xyz.js

Title: how to set proxy in casperjs code

Body:
Here are some options i already try but none of them work for me

is there any way to change proxy before we hit any particular website ?

var casper = require("casper").create({
setProxy: "proxy here",
// --proxy: "proxy here",
webSecurityEnabled: false,
verbose: true,
logLevel: "debug",
waitTimeout: 100000,
pageSettings: {
    userAgent: "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0",
    proxy: 'proxy here'
}});
var url = 'http://whatismyipaddress.com/';
var fs = require('fs');
var path = 'ip_check.txt';
casper.start(url, function() {
    casper.cli.options["proxy"] = "proxy here";
    var js = this.evaluate(function() {
        return document;
    });
    fs.write(path,js.all[0].outerHTML,'w');
});
casper.run();


问:
hibernate persist not working
I have a simple AppUser entity class and table in db APP_USERS.
when i do a addAppUser from DAO class, I get below exception:

HTTP Status 500 - Request processing failed; nested exception is
  org.hibernate.PersistentObjectException: detached entity passed to
  persist: com.spring.model.AppUser

```<code>@Override
public void addAppUser(AppUser p) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(p);
    logger.info("AppUser saved successfully, AppUser Details="+p);
}
</code>```

Not sure how to resolve it. Same code works fine for persisting a different class's object. Did some research but could not find anything that could help.

答:
The problem is that your AppUser comes from the outside, so it is not managed by hibernate. Call merge to reattach your DAO, i.e. make hibernate handle it again:

```<code>session.merge(p);
</code>```

If you still run into an exception, you can try to see if the object is already in the session first, and then call update(obj) if it is, otherwise call merge(obj).

For example:

```<code>if(session.contains(obj)) session.update(obj);
else session.merge(obj);
</code>```

Title: hibernate persist not working

Body:
I have a simple AppUser entity class and table in db APP_USERS.
when i do a addAppUser from DAO class, I get below exception:

HTTP Status 500 - Request processing failed; nested exception is
  org.hibernate.PersistentObjectException: detached entity passed to
  persist: com.spring.model.AppUser

@Override
public void addAppUser(AppUser p) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(p);
    logger.info("AppUser saved successfully, AppUser Details="+p);
}

Not sure how to resolve it. Same code works fine for persisting a different class's object. Did some research but could not find anything that could help.

Body:
The problem is that your AppUser comes from the outside, so it is not managed by hibernate. Call merge to reattach your DAO, i.e. make hibernate handle it again:

session.merge(p);

If you still run into an exception, you can try to see if the object is already in the session first, and then call update(obj) if it is, otherwise call merge(obj).

For example:

if(session.contains(obj)) session.update(obj);
else session.merge(obj);


问:
How to add cassandra table column dynamically?
I'm trying to add a new columns to cassandra table dynamically. I'm using below version -

```<code>cqlsh 5.0.1
</code>```

I'm using python to interact with Cassandra. I have one python list which I wish to add as a column names to Cassandra table.

Python List -

```<code>['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']
</code>```

Currently, I'm iterating a list and then adding each column one by one to cassandra table like below -

```<code>from cassandra.cluster import Cluster
cluster = Cluster(['localhost'])
session = cluster.connect()

session.execute("CREATE KEYSPACE IF NOT EXISTS data WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};")
session.execute("use my_data")
session.execute("CREATE TABLE IF NOT EXISTS data.my_data (pk uuid PRIMARY KEY);")
names = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']

for val in names:
   try:
      session.execute("alter table data.my_data add "+ val +" ascii;")
   except:
      pass
</code>```

It is working fine but actual problem is, if in my python list more than 1000 entries are available then there should be more than 1000 hits to the cassandra which will be time consuming. Is any different approach available to add a column names to existing table in cassandra?

答:
Cassandra internally stores data as rows, each row has a key (Partition key) and dynamic number of columns (clustering key). So, you can use Clustering Key value for your column names, e.g

```<code>CREATE TABLE my_data (
     pk text,
     column text,
     value text,
     PRIMARY KEY (pk, column)
);
</code>```

Insert new columns and values by a regular INSERT query:

```<code>INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'A', 'value A');
INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'B', 'value B');
INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'C', 'value C');
...
</code>```

Get all columns for pk1:

```<code>SELECT * FROM my_data WHERE pk='pk1';
</code>```

Updated

Assume, you have table my_data as described above and
you want to add some columns and data for a specific pk value.
In python code perform insert query:

```<code>pk = 'pk'
columns_data = {'A':'value for A','B':'value  for B','C': 'value for C'} #dynamic column data
for col_name, col_value in columns_data.iteritems():
   try:
      session.execute("INSERT INTO my_data (pk, column, value) VALUES (%s, %s, %s)", (pk, col_name, col_value))
   except:
      pass
</code>```

Moreover, you can use asynchronous driver's methods, to achieve more performance of inserting.

Body:
I'm trying to add a new columns to cassandra table dynamically. I'm using below version -

cqlsh 5.0.1

I'm using python to interact with Cassandra. I have one python list which I wish to add as a column names to Cassandra table.

Python List -

['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']

Currently, I'm iterating a list and then adding each column one by one to cassandra table like below -

from cassandra.cluster import Cluster
cluster = Cluster(['localhost'])
session = cluster.connect()

session.execute("CREATE KEYSPACE IF NOT EXISTS data WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};")
session.execute("use my_data")
session.execute("CREATE TABLE IF NOT EXISTS data.my_data (pk uuid PRIMARY KEY);")
names = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']

for val in names:
   try:
      session.execute("alter table data.my_data add "+ val +" ascii;")
   except:
      pass

It is working fine but actual problem is, if in my python list more than 1000 entries are available then there should be more than 1000 hits to the cassandra which will be time consuming. Is any different approach available to add a column names to existing table in cassandra?

Body:
Cassandra internally stores data as rows, each row has a key (Partition key) and dynamic number of columns (clustering key). So, you can use Clustering Key value for your column names, e.g

CREATE TABLE my_data (
     pk text,
     column text,
     value text,
     PRIMARY KEY (pk, column)
);

Insert new columns and values by a regular INSERT query:

INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'A', 'value A');
INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'B', 'value B');
INSERT INTO my_data (pk, column, value) VALUES ('pk1', 'C', 'value C');
...

Get all columns for pk1:

SELECT * FROM my_data WHERE pk='pk1';

Updated

Assume, you have table my_data as described above and
you want to add some columns and data for a specific pk value.
In python code perform insert query:

pk = 'pk'
columns_data = {'A':'value for A','B':'value  for B','C': 'value for C'} #dynamic column data
for col_name, col_value in columns_data.iteritems():
   try:
      session.execute("INSERT INTO my_data (pk, column, value) VALUES (%s, %s, %s)", (pk, col_name, col_value))
   except:
      pass

Moreover, you can use asynchronous driver's methods, to achieve more performance of inserting.


问:
Need an AVERAGE from a MULTIPLE CRITERIA VLOOKUP
I'm not an Excel expert. I've tried to achieve something that for me seems simple at the beginning but than I've spend a few hours in searching and trying different solutions but couldn't find something that fits my problem. I hope some of you guys will find a solution for me?

This is my problem:
The sample table:

```<code>A    B    C    D    E    F
1st  A    ?    ?    ?    12.58%
1st  B    ?    ?    ?    10.25%
1st  A    ?    ?    ?    8.56%
2nd  A    ?    ?    ?    10.23%
2nd  B    ?    ?    ?    15.26%
etc.
</code>```

What I want to achieve is to find the AVERAGE percent for all 1st (column A) and A's (column B) if possible. The percentage is calculated in column F and the other columns contain other number irrelevant to the problem.

I've tried some VLOOKUP and INDEX&MATCH but with no success.
I hope someone here can help me.
Thanks for reading.

Body:
I'm not an Excel expert. I've tried to achieve something that for me seems simple at the beginning but than I've spend a few hours in searching and trying different solutions but couldn't find something that fits my problem. I hope some of you guys will find a solution for me?

This is my problem:
The sample table:

A    B    C    D    E    F
1st  A    ?    ?    ?    12.58%
1st  B    ?    ?    ?    10.25%
1st  A    ?    ?    ?    8.56%
2nd  A    ?    ?    ?    10.23%
2nd  B    ?    ?    ?    15.26%
etc.

What I want to achieve is to find the AVERAGE percent for all 1st (column A) and A's (column B) if possible. The percentage is calculated in column F and the other columns contain other number irrelevant to the problem.

I've tried some VLOOKUP and INDEX&MATCH but with no success.
I hope someone here can help me.
Thanks for reading.

Body: Try =AVERAGEIFS(F2:F6,A2:A6,"1st",B2:B6,"A")