问:
How long does Chrome remember a 301 redirect?
I have a new author site that I want to make available from a domain that I had previously used Apache rewriting to bounce traffic to my Amazon site, [R=301,L], which I want to serve up as my own site. I also have a new domain for the interim at least.

Is there (are there) particular durations of times when Chrome in particular will store 301 cached redirects? Some other questions, How long do browsers cache HTTP 301s? and How is 301 redirect implemented by different browsers? , ask, and the answer is given that some browsers do not cache, some cache for the session, and Chrome and IE10 cache in a way that will survive a browser restart, but don't specify how long. Longer than the other browsers tested, but the amount is still unspecified.

So how long does Chrome store a 301 redirect? The questions cited do not specify what it is for Chrome or IE10.

答: I resolved this by opening dev tools (F12), click "Network", then click the "Preserve log" checkbox, and make the request that results in the cached 301. Right-click the request that results in the 301 and click "clear browser cache". Try again and then 301 should no-longer be cached.</p>


来源: stackexchange

问:
php strstr not detecting substring in a arabic string
Can anyone please tell me ,How to make string matching function work with Arabic keywords?
                 The Following keywords are detected as Unmatched in php. Though these are matching in normal browser searching.

```<code>    if (strstr('الهيئة العامة للقوى العاملة', 'قوى العامله') != false) {
       echo'in';
          } else {
          echo'out';
           }die;
</code>```

Result comes as 'out'.

Thanks

答:
Try this .. I have PHP Version 5.6.23

```<code><?php
$string = 'الهيئة العامة للقوى العاملة';
$find_me = 'قوى العاملة';
if (strstr($string, $find_me) != false) {
       echo'in';
          } else {
          echo'out';
           }die;

?>
</code>```

You can see output here https://eval.in/764085

ContentLicense: CC BY-SA 3.0

Body:
Can anyone please tell me ,How to make string matching function work with Arabic keywords?
                 The Following keywords are detected as Unmatched in php. Though these are matching in normal browser searching.

    if (strstr('الهيئة العامة للقوى العاملة', 'قوى العامله') != false) {
       echo'in';
          } else {
          echo'out';
           }die;

Result comes as 'out'.

Thanks

Body:
Try this .. I have PHP Version 5.6.23

<?php
$string = 'الهيئة العامة للقوى العاملة';
$find_me = 'قوى العاملة';
if (strstr($string, $find_me) != false) {
       echo'in';
          } else {
          echo'out';
           }die;

?>

You can see output here https://eval.in/764085


问:
UILabel text include multiple spaces at the end
In Objective-C I have a UILabel that says 'Loading'. Every 0.5 seconds the string will gain another '.' until there are 3 dots, then it starts over. The problem I'm facing is that my string is centered and when each dot appears, the string jumps. The reason the string jumps is because the UILabel keeps trimming the right whitespace.

Here is an example of whats currently happening.

```<code>+------------+
|  Loading   |
+------------+
|  Loading.  |
+------------+
| Loading..  |
+------------+
| Loading... |
+------------+
</code>```

And this is what I want to happen.

```<code>+------------+
| Loading    |
+------------+
| Loading.   |
+------------+
| Loading..  |
+------------+
| Loading... |
+------------+
</code>```

Telling the UILabel to have a greater width and be left aligned is not an option. This needs to be done with the text.

I found this link, but I still cant figure it out.

What I currently have is this.

```<code>[NSString stringWithFormat:@"%-3.3s", [@"" UTF8String]];
[NSString stringWithFormat:@"%-3.3s", [@"." UTF8String]];
[NSString stringWithFormat:@"%-3.3s", [@".." UTF8String]];
@"...";
</code>```

答:
Set label.textAlignment = NSTextAlignmentNatural. Since ios 9, this is default, before that it used to be NSTextAlignmentLeft.

Now since your text has to be centred, wrap it in a UIView with all the margins of the label anchored with that of the wrapper view. Then center the wrapper instead of label.

Here's the code:

```<code>UIView* wrapper = [[UIView alloc] init];
wrapper.translatesAutoresizingMaskIntoConstraints = NO;
//This sets the wrapper at the center of where you were adding the label previously
[wrapper.centerXAnchor constraintEqualToAnchor: superview.centerXAnchor].active = YES;

label.translatesAutoresizingMaskIntoConstraints = NO;
[label.leadingAnchor constraintEqualToAnchor:wrapper.leadingAnchor].active = YES;
[label.trailingAnchor constraintEqualToAnchor:wrapper.trailingAnchor].active = YES;
[label.topAnchor constraintEqualToAnchor:wrapper.topAnchor].active = YES;
[label.bottomAnchor constraintEqualToAnchor:wrapper.bottomAnchor].active = YES;

label.textAlignment = NSTextAlignmentNatural
...
</code>```

Body:
In Objective-C I have a UILabel that says 'Loading'. Every 0.5 seconds the string will gain another '.' until there are 3 dots, then it starts over. The problem I'm facing is that my string is centered and when each dot appears, the string jumps. The reason the string jumps is because the UILabel keeps trimming the right whitespace.

Here is an example of whats currently happening.

+------------+
|  Loading   |
+------------+
|  Loading.  |
+------------+
| Loading..  |
+------------+
| Loading... |
+------------+

And this is what I want to happen.

+------------+
| Loading    |
+------------+
| Loading.   |
+------------+
| Loading..  |
+------------+
| Loading... |
+------------+

Telling the UILabel to have a greater width and be left aligned is not an option. This needs to be done with the text.

I found this link, but I still cant figure it out.

What I currently have is this.

[NSString stringWithFormat:@"%-3.3s", [@"" UTF8String]];
[NSString stringWithFormat:@"%-3.3s", [@"." UTF8String]];
[NSString stringWithFormat:@"%-3.3s", [@".." UTF8String]];
@"...";

Body:
Set label.textAlignment = NSTextAlignmentNatural. Since ios 9, this is default, before that it used to be NSTextAlignmentLeft.

Now since your text has to be centred, wrap it in a UIView with all the margins of the label anchored with that of the wrapper view. Then center the wrapper instead of label.

Here's the code:

UIView* wrapper = [[UIView alloc] init];
wrapper.translatesAutoresizingMaskIntoConstraints = NO;
//This sets the wrapper at the center of where you were adding the label previously
[wrapper.centerXAnchor constraintEqualToAnchor: superview.centerXAnchor].active = YES;

label.translatesAutoresizingMaskIntoConstraints = NO;
[label.leadingAnchor constraintEqualToAnchor:wrapper.leadingAnchor].active = YES;
[label.trailingAnchor constraintEqualToAnchor:wrapper.trailingAnchor].active = YES;
[label.topAnchor constraintEqualToAnchor:wrapper.topAnchor].active = YES;
[label.bottomAnchor constraintEqualToAnchor:wrapper.bottomAnchor].active = YES;

label.textAlignment = NSTextAlignmentNatural
...


问:
Initialize a static const member with a template argument
I have a few lines that compile well on my system but don't compile on a colleagues system. That's why I would like to ask what the go-to solution for the problem would look like. I have to deal with a enum that implicitly defines how much space I have to provide for an std::array. Other parts of the code also make use of FooSize being static. (Optimization)

My current implementation looks like this

enum class FooType
{
    ShortFoo,
    LongFoo
};

// defined in a different file
template <FooType FType>
class FooContainer
{
public:

    static const unsigned int FooSize {(FType == FooType::ShortFoo) ? 32 : 64 };

    std::array<float, FooSize> fooArray;

};
```

The code seems to create issues on older llvm / clang compilers. 32 and 64 are actually provided via pre processor defines. I could just skip the FooType and use the size as an template argument but I would like to know what the most reliable method of initializing FooSize would be.

答:
Your code seems correct to me and compile without problems with my olds g++ (4.9.2) and clang++ (3.5).

But, according the error message, could be that your compiler doesn't correctly support the C++11 declaration/initialization of static data members

I suggest you to try in the following way

```<code>template <FooType FType>
class FooContainer
{
public:
    static const unsigned int FooSize;

    std::array<float, FooSize> fooArray;

};

template <FooType FType>
int unsigned const FooContainer<FType>::FooSize
   = ((FType == FooType::ShortFoo) ? 32 : 64);
</code>```

or (I suppose is better)

```<code>template <FooType FType>
class FooContainer
{
public:

    static const unsigned int FooSize {(FType == FooType::ShortFoo) ? 32 : 64 };

    std::array<float, FooSize> fooArray;

};

template <FooType FType>
int unsigned const FooContainer<FType>::FooSize;
</code>```

You can also try defining FooSize as constexpr instead of const.

Another solution could be transform FooSize in a template parameter

```<code>template <FooType FType,
   std::size_t FooSize = (FType == FooType::ShortFoo) ? 32 : 64 >
class FooContainer
{
public:
    std::array<float, FooSize> fooArray;
};
</code>```

Body:
I have a few lines that compile well on my system but don't compile on a colleagues system. That's why I would like to ask what the go-to solution for the problem would look like. I have to deal with a enum that implicitly defines how much space I have to provide for an std::array. Other parts of the code also make use of FooSize being static. (Optimization)

My current implementation looks like this

enum class FooType
{
    ShortFoo,
    LongFoo
};

// defined in a different file
template <FooType FType>
class FooContainer
{
public:

    static const unsigned int FooSize {(FType == FooType::ShortFoo) ? 32 : 64 };

    std::array<float, FooSize> fooArray;

};

The code seems to create issues on older llvm / clang compilers. 32 and 64 are actually provided via pre processor defines. I could just skip the FooType and use the size as an template argument but I would like to know what the most reliable method of initializing FooSize would be.

Body:
Your code seems correct to me and compile without problems with my olds g++ (4.9.2) and clang++ (3.5).

But, according the error message, could be that your compiler doesn't correctly support the C++11 declaration/initialization of static data members

I suggest you to try in the following way

template <FooType FType>
class FooContainer
{
public:
    static const unsigned int FooSize;

    std::array<float, FooSize> fooArray;

};

template <FooType FType>
int unsigned const FooContainer<FType>::FooSize
   = ((FType == FooType::ShortFoo) ? 32 : 64);

or (I suppose is better)

template <FooType FType>
class FooContainer
{
public:

    static const unsigned int FooSize {(FType == FooType::ShortFoo) ? 32 : 64 };

    std::array<float, FooSize> fooArray;

};

template <FooType FType>
int unsigned const FooContainer<FType>::FooSize;

You can also try defining FooSize as constexpr instead of const.

Another solution could be transform FooSize in a template parameter

template <FooType FType,
   std::size_t FooSize = (FType == FooType::ShortFoo) ? 32 : 64 >
class FooContainer
{
public:
    std::array<float, FooSize> fooArray;
};


问:
How to parse only one option of XML in PHP?
Hi I want to parse in php

and read only one option of each line. How can I do this?

I tried:

```<code><?php
$xml = file_get_contents("file.xml");
echo $xml;
?>
</code>```

But this read the full xml. I need only one option of the xml

答:
Take a look at simplexml_load_file and turn your xml into a workable object where you can loop through and find whichever properties you need. </p>

```<code>$xml = simplexml_load_file('file.xml');

foreach($xml->ParkingData as $k => $v)
echo $v->ParkingFacility->ParkingName ." - Vacant Spaces: ". $v->ParkingFacility->VacantSpaces."<br />";
</code>```

Body:
Hi I want to parse in php

and read only one option of each line. How can I do this?

I tried:

<?php
$xml = file_get_contents("file.xml");
echo $xml;
?>

But this read the full xml. I need only one option of the xml

Body:
Take a look at simplexml_load_file and turn your xml into a workable object where you can loop through and find whichever properties you need.

$xml = simplexml_load_file('file.xml');

foreach($xml->ParkingData as $k => $v)
echo $v->ParkingFacility->ParkingName ." - Vacant Spaces: ". $v->ParkingFacility->VacantSpaces."<br />";


问:
Re-activating NSLayoutConstraint finds nil while unwrapping optional
I want to set the height of my UITextView programmatically to fit the contents accordingly. I've set the UITextView's default height to follow layout constraints I've set, but wish to change it when the user touches a button.

@IBOutlet weak var descriptionHeight: NSLayoutConstraint!

I've tried to use layoutIfNeeded(), but it doesn't change the size of my text view (as the size is kept by the layout constraint).

I've tried to temporarily disable the constraints like so:

```<code>print("before: \(descriptionTextView.frame)")
descriptionHeight.active = false

descriptionTextView.layoutIfNeeded()
print("after: \(descriptionTextView.frame)")

descriptionHeight.constant = descriptionTextView.frame.height
descriptionHeight.active = true
</code>```

But when when accessing the outlet after deactivating it, it throws an exception:

fatal error: unexpectedly found nil while unwrapping an Optional value

It seems that it is calculating the size properly though:

before: (8.0, 8.0, 398.0, 100.0)

after: (8.0, 8.0, 398.0, 954.666666666667)

Why does this happen?
Is there a better way of calculating and setting the proper size of my UITextView?

答:
Make the outlet strong:

```<code>@IBOutlet strong var descriptionHeight: NSLayoutConstraint!
</code>```

Edit:

It seems like the latest version of Xcode adds the outlets as:

```<code>@IBOutlet var descriptionHeight: NSLayoutConstraint!
</code>```

as @Dan mentioned in the comments.

Body:
I want to set the height of my UITextView programmatically to fit the contents accordingly. I've set the UITextView's default height to follow layout constraints I've set, but wish to change it when the user touches a button.

@IBOutlet weak var descriptionHeight: NSLayoutConstraint!

I've tried to use layoutIfNeeded(), but it doesn't change the size of my text view (as the size is kept by the layout constraint).

I've tried to temporarily disable the constraints like so:

print("before: \(descriptionTextView.frame)")
descriptionHeight.active = false

descriptionTextView.layoutIfNeeded()
print("after: \(descriptionTextView.frame)")

descriptionHeight.constant = descriptionTextView.frame.height
descriptionHeight.active = true

But when when accessing the outlet after deactivating it, it throws an exception:

fatal error: unexpectedly found nil while unwrapping an Optional value

It seems that it is calculating the size properly though:

before: (8.0, 8.0, 398.0, 100.0)

after: (8.0, 8.0, 398.0, 954.666666666667)

Why does this happen?
Is there a better way of calculating and setting the proper size of my UITextView?

Body:
Make the outlet strong:

@IBOutlet strong var descriptionHeight: NSLayoutConstraint!

Edit:

It seems like the latest version of Xcode adds the outlets as:

@IBOutlet var descriptionHeight: NSLayoutConstraint!

as @Dan mentioned in the comments.

ContentLicense: CC BY-SA 4.0


问:
Developer Documentation has gone in xcode 3.2.5?
I used to looking up classes/methods from Help->Developer Documentation, which has API doc in local. But after I just upgraded my xcode to 3.2.5, it becomes totally different. When I type something in the search box (e.g. NSString), it accesses the network slowly and asks my developer account/password.

The even worse thing is after I type the password it keeps saying,
"You Request Is Being Redirected: You may have used an outdated link or typed the address (URL) incorrectly. If you came to this page via a bookmark, please update it accordingly. "

What happened with it? How to get the old Developer Documentation back?

答: Happened to me with an earlier update, 2-3 versions before the official iOS 4.2 SDK. You can easily get it back from your Xcode preferences > Documentation (all the way to the right side)

ContentLicense: CC BY-SA 2.5


问:
Setting value comparing two arrays in Laravel
I have a function that compares 2 arrays.
One array is filled with a group of users.
The other array comes from a formular. It contains a list of IDs.

If an ID matches any ID from the formular, the user should be saved as "released". If not it should be not matched as released.

My formular works if I check them, but when they are unchecked and therefore not in the array, they are still saved as released. Here is my code:

```<code>    public function save_user_list(Requests $request)

    {
        $user_id_list = array();
        $counter = 0;

        if(Auth::user()->role == "owner"){
        $users = User::where('owner_id',Auth::user()->owner_id)
            ->get();
        }else{
            $users = User::where('owner_id',Auth::user()->owner_id)
                ->where('role',"user")
                ->get();
        }
        foreach($users as $user)
        {
            $user_id_list[$counter] = $user->id;
            $counter++;
        }

     for($i=0;$i<count($request->release);$i++)
        {
            $release = 0;
            for($a=0;$a<$counter;$a++)
            {
              if($request->release){

                if($request->release[$i] == $user_id_list[$a])
                {
                    $release = 1;
                }
              }
            }
            $userrelease = User::where('id',$request->release[$i])
                ->where('owner_id',Auth::user()->owner_id)
                ->first();
            if($userrelease)
            {
            $userrelease->active = $release;
            $userrelease->save();
            }
        }

        return back();
</code>```

答:
Fixed it. Just a problem with the loops.</p>

```<code>    for ($a = 0; $a < $counter; $a++) {
        $release = 0;
        for ($i = 0; $i < count($request->release); $i++) {
            if ($request->release) {
                if ($request->release[$i] == $user_id_list[$a]) {
                    $release = 1;
                }
            }
        }
        $userrelease = User::where('id', $user_id_list[$a])
            ->where('owner_id', Auth::user()->owner_id)
            ->first();
        if ($userrelease && $userrelease->role != "owner") {
            $userrelease->active = $release;
            $userrelease->save();
        }
    }
</code>```

Body:
I have a function that compares 2 arrays.
One array is filled with a group of users.
The other array comes from a formular. It contains a list of IDs.

If an ID matches any ID from the formular, the user should be saved as "released". If not it should be not matched as released.

My formular works if I check them, but when they are unchecked and therefore not in the array, they are still saved as released. Here is my code:

    public function save_user_list(Requests $request)

    {
        $user_id_list = array();
        $counter = 0;

        if(Auth::user()->role == "owner"){
        $users = User::where('owner_id',Auth::user()->owner_id)
            ->get();
        }else{
            $users = User::where('owner_id',Auth::user()->owner_id)
                ->where('role',"user")
                ->get();
        }
        foreach($users as $user)
        {
            $user_id_list[$counter] = $user->id;
            $counter++;
        }

     for($i=0;$i<count($request->release);$i++)
        {
            $release = 0;
            for($a=0;$a<$counter;$a++)
            {
              if($request->release){

                if($request->release[$i] == $user_id_list[$a])
                {
                    $release = 1;
                }
              }
            }
            $userrelease = User::where('id',$request->release[$i])
                ->where('owner_id',Auth::user()->owner_id)
                ->first();
            if($userrelease)
            {
            $userrelease->active = $release;
            $userrelease->save();
            }
        }

        return back();

Body:
Fixed it. Just a problem with the loops.

    for ($a = 0; $a < $counter; $a++) {
        $release = 0;
        for ($i = 0; $i < count($request->release); $i++) {
            if ($request->release) {
                if ($request->release[$i] == $user_id_list[$a]) {
                    $release = 1;
                }
            }
        }
        $userrelease = User::where('id', $user_id_list[$a])
            ->where('owner_id', Auth::user()->owner_id)
            ->first();
        if ($userrelease && $userrelease->role != "owner") {
            $userrelease->active = $release;
            $userrelease->save();
        }
    }


问:
Change nodes between pipeline stages
In my pipeline, I am changing from my master to a slave node in one of my stages:

```<code>pipeline {
  agent any
  stages {
    stage('Install Deps...') {
      steps {
        echo 'Do something here'
      }
    }
    stage('Build') {
      steps {
        echo 'Build stuff here...'
        stash includes: 'dist/**/*', name: 'builtSources'
        node('Protractor') {
          dir('/some-dir/deploy') {
            unstash 'builtSources'
          }
        }
      }
    }
    stage('Tests') {
      steps {
        parallel (
          "Chrome": {
            echo 'Chrome testing here...'
          }
        )
      }
    }
  }
}
</code>```

I can see from the console output on Jenkins it correctly says 'running on master' at the start of the first stage, and changes to 'running on Protractor' in my second stage. When the third 'Tests' stage starts, I dont see the node change back to master in the console output, is that expected behaviour?

Should stages run on the master unless explicitly told otherwise with a node() block?

答: The short answer is that if you want stages to run on a specific node/agent then you should specify it. If not then the node that the next stage runs on will be affected by things like the Usage setting for your nodes (i.e. 'Use this node as much as possible' or 'Only build jobs with labels...'). In my setup once execution switches from the master to an agent node it won't switch back unless all of the executors on the agent are in use and the master has an open executor. Sounds like your current setup is similar.</p>

Title: Change nodes between pipeline stages

Body:
In my pipeline, I am changing from my master to a slave node in one of my stages:

pipeline {
  agent any
  stages {
    stage('Install Deps...') {
      steps {
        echo 'Do something here'
      }
    }
    stage('Build') {
      steps {
        echo 'Build stuff here...'
        stash includes: 'dist/**/*', name: 'builtSources'
        node('Protractor') {
          dir('/some-dir/deploy') {
            unstash 'builtSources'
          }
        }
      }
    }
    stage('Tests') {
      steps {
        parallel (
          "Chrome": {
            echo 'Chrome testing here...'
          }
        )
      }
    }
  }
}

I can see from the console output on Jenkins it correctly says 'running on master' at the start of the first stage, and changes to 'running on Protractor' in my second stage. When the third 'Tests' stage starts, I dont see the node change back to master in the console output, is that expected behaviour?

Should stages run on the master unless explicitly told otherwise with a node() block?


问:
JS - Dropdown element dependent
I'm trying to have the user pick "YES" and the other dropdown automatically goes to "NO" and vice versa. I have a code below, I'm not sure why it is not working.

*I'm trying to get it onload so it automatically runs without the user having to press a button.

Code:

<!DOCTYPE html>

Currently:
        <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
          <option value="">Select Option</option>
          <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
          <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
        </select>

Microphone:
        <select id="microphone" class="microphone select2" name = "microphone">
          <option value=" "  selected="selected"> </option>
          <option value="ON. Thank you.">ON</option>
          <option value="OFF. Thank you.">OFF</option>
        </select>

        <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>

```

答:
JsFiddle Example

```<code><html>
<body>
                <div class="cmicrophone" id="cmicrophone">Currently:
                    <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
                        <option value="">Select Option</option>
                        <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
                        <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
                    </select>
                </div>
                <div class="microphone" id="microphone">Microphone:
                    <select id="microphone" class="microphone select2" name = "microphone">
                        <option value=" "  selected="selected"> </option>
                        <option value="ON. Thank you.">ON</option>
                        <option value="OFF. Thank you.">OFF</option>
                    </select>
                </div>

<div class="button updatebutton">
                <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>
            </div>
            </form>
        </div>
</body>
</html>
</code>```

JS Code

```<code>$(document).ready(function(){
    change1('YES')
    change2('OFF')
});

function change1(text1)
{
  $("#cmicrophone option").filter(function() {
    //may want to use $.trim in here
      return $(this).text() == text1;
  }).prop('selected', true);
}

function change2(text2)
{
    $("#microphone option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == text2;
    }).prop('selected', true);
}

$('#cmicrophone').on('change', function() {
  if ($(this).text() == 'YES') {
    change2('ON')
    //$('.elem').not(this).val('off');
  } else {
    //$('.elem').not(this).val('on');
    change2('OFF')
  }
});

$('#microphone').on('change', function() {
  if ($(this).text() == 'ON') {
    change1('NO')
    //$('.elem').not(this).val('off');
  } else {
    //$('.elem').not(this).val('on');
    change1('YES')
  }
});
</code>```

Title: JS - Dropdown element dependent

Body:
JsFiddle Example

<html>
<body>
                <div class="cmicrophone" id="cmicrophone">Currently:
                    <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
                        <option value="">Select Option</option>
                        <option value="'S microphone is currently on. Please remind them to turn it ">YES</option>
                        <option value="'S microphone is currently off. Please remind them to turn it ">NO</option>
                    </select>
                </div>
                <div class="microphone" id="microphone">Microphone:
                    <select id="microphone" class="microphone select2" name = "microphone">
                        <option value=" "  selected="selected"> </option>
                        <option value="ON. Thank you.">ON</option>
                        <option value="OFF. Thank you.">OFF</option>
                    </select>
                </div>

<div class="button updatebutton">
                <button onclick="inputHandler(thisSelect, otherSelect)">UPDATE</button>
            </div>
            </form>
        </div>
</body>
</html>

JS Code

$(document).ready(function(){
    change1('YES')
    change2('OFF')
});

function change1(text1)
{
  $("#cmicrophone option").filter(function() {
    //may want to use $.trim in here
      return $(this).text() == text1;
  }).prop('selected', true);
}

function change2(text2)
{
    $("#microphone option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == text2;
    }).prop('selected', true);
}

$('#cmicrophone').on('change', function() {
  if ($(this).text() == 'YES') {
    change2('ON')
    //$('.elem').not(this).val('off');
  } else {
    //$('.elem').not(this).val('on');
    change2('OFF')
  }
});

$('#microphone').on('change', function() {
  if ($(this).text() == 'ON') {
    change1('NO')
    //$('.elem').not(this).val('off');
  } else {
    //$('.elem').not(this).val('on');
    change1('YES')
  }
});


问:
wso2cep: ERROR - 'distance' is neither a function extension nor an aggregated attribute extension in execution plan "ExecutionPlan"
I am using WSO2 CEP 4.2.0 version and I am writing an execution plan for checking when coordinates from different sensors do not vary by more than 4 meters, through Siddhi query. But getting an error:  'distance' is neither a function extension nor an aggregated attribute extension in execution plan "ExecutionPlan".

I have installed the GPL - Siddhi Geo Extension, but I do not know why there is that error. Please help me in solving this error.

My execution plan is below:

```<code>/* Enter a unique ExecutionPlan */
@Plan:name('ExecutionPlan')

/* Enter a unique description for ExecutionPlan */
-- @Plan:description('ExecutionPlan')

/* define streams/tables and write queries here ... */

@Import('SR_ProcessedStream:1.0.0')
define stream srprocessedstream (meta_resultTime long, meta_procedure string, correlation_latitude double, correlation_longitude double);

@Import('MPD_ProcessedStream:1.0.0')
define stream mpdprocessedstream (meta_resultTime long, meta_procedure string, correlation_latitude double, correlation_longitude double);

@Import('GBSS_ProcessedStream:1.0.0')
define stream gbssprocessedstream (meta_resultTime long, meta_procedure string, correlation_latitude double, correlation_longitude double);

@Export('measuredStream:1.0.0')
define stream measuredStream (meta_procedure1 string, meta_procedure2 string);

define table sensorTable(meta_procedure string, correlation_latitude double, correlation_longitude double);

from gbssprocessedstream
select meta_procedure, correlation_latitude, correlation_longitude
insert into sensorTable;

from mpdprocessedstream
select meta_procedure, correlation_latitude, correlation_longitude
insert into sensorTable;

from srprocessedstream
select meta_procedure, correlation_latitude, correlation_longitude
insert into sensorTable;

from gbssprocessedstream join sensorTable
 on sensorTable.meta_procedure != gbssprocessedstream.meta_procedure and 4 > geo : distance (sensorTable.correlation_latitude, sensorTable.correlation_longitude, meta_procedure1.correlation_latitude, meta_procedure1.correlation_longitude)
 select sensorTable.meta_procedure as meta_procedure1, gbssprocessedstream.meta_procedure as meta_procedure2
 insert into measuredStream;
</code>```

Thanks in advance!

答:
distance is Function extension (in contrast to Stream Processor extension type).    Please refer Siddhi Extensions doc which shows the usage of each of those types.

As mentioned in the above document, function extensions has to be applied on the select statement. This error is observed because the function extension is applied elsewhere (in the join condition).

Body:
I am using WSO2 CEP 4.2.0 version and I am writing an execution plan for checking when coordinates from different sensors do not vary by more than 4 meters, through Siddhi query. But getting an error:  'distance' is neither a function extension nor an aggregated attribute extension in execution plan "ExecutionPlan".

I have installed the GPL - Siddhi Geo Extension, but I do not know why there is that error. Please help me in solving this error.

My execution plan is below:

/* Enter a unique ExecutionPlan */
@Plan:name('ExecutionPlan')

/* Enter a unique description for ExecutionPlan */
-- @Plan:description('ExecutionPlan')

/* define streams/tables and write queries here ... */

@Import('SR_ProcessedStream:1.0.0')
define stream srprocessedstream (meta_resultTime long, meta_procedure string, correlation_latitude double, correlation_longitude double);

@Import('MPD_ProcessedStream:1.0.0')
define stream mpdprocessedstream (meta_resultTime long, meta_procedure string, correlation_latitude double, correlation_longitude double);

@Import('GBSS_ProcessedStream:1.0.0')
define stream gbssprocessedstream (meta_resultTime long, meta_procedure string, correlation_latitude double, correlation_longitude double);

@Export('measuredStream:1.0.0')
define stream measuredStream (meta_procedure1 string, meta_procedure2 string);

define table sensorTable(meta_procedure string, correlation_latitude double, correlation_longitude double);

from gbssprocessedstream
select meta_procedure, correlation_latitude, correlation_longitude
insert into sensorTable;

from mpdprocessedstream
select meta_procedure, correlation_latitude, correlation_longitude
insert into sensorTable;

from srprocessedstream
select meta_procedure, correlation_latitude, correlation_longitude
insert into sensorTable;

from gbssprocessedstream join sensorTable
 on sensorTable.meta_procedure != gbssprocessedstream.meta_procedure and 4 > geo : distance (sensorTable.correlation_latitude, sensorTable.correlation_longitude, meta_procedure1.correlation_latitude, meta_procedure1.correlation_longitude)
 select sensorTable.meta_procedure as meta_procedure1, gbssprocessedstream.meta_procedure as meta_procedure2
 insert into measuredStream;

Thanks in advance!


问:
MD5/SHA "update" property?
What is the MD5/SHA property that allows you to "update" them? For example, if you have the hash for "test" you can add "case" to get the hash for "testcase". I would like to read up on this property a bit but my searches turn up nothing...</p>

答: It is merely that they are actually calculated incrementally -- you calculate them by operating on the first n bytes of data, (128 in the case of MD5, see http://en.wikipedia.org/wiki/MD5#Algorithm), then on the next n bytes of data, etc.</p>

Title: MD5/SHA "update" property?


问:
ModernUI Footer like control on all pages
I have been working with ModernUI, does the library have a a footer control thats ever present for all pages.

I tried this WPF ModernUI same footer for all pages had no success( am new to wpf)

答:
You can define your page style with header and footer in app.xaml:

```<code><Style x:Key="HeaderFooterPageStyle" TargetType="Page">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Page}">
                <Grid Background="{TemplateBinding Background}">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <!-- Header -->
                    <Border Grid.Row="0" Background="Red">
                        <TextBlock Text="Header"/>
                    </Border>

                    <!-- Body -->
                    <ContentPresenter Grid.Row="1"/>

                    <!-- Footer -->
                    <Border Grid.Row="2" Background="Red">
                        <TextBlock Text="Footer"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Then set style to all pages:

```<code>Style="{StaticResource HeaderFooterPageStyle}"
</code>```

Body:
You can define your page style with header and footer in app.xaml:

<Style x:Key="HeaderFooterPageStyle" TargetType="Page">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Page}">
                <Grid Background="{TemplateBinding Background}">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>

                    <!-- Header -->
                    <Border Grid.Row="0" Background="Red">
                        <TextBlock Text="Header"/>
                    </Border>

                    <!-- Body -->
                    <ContentPresenter Grid.Row="1"/>

                    <!-- Footer -->
                    <Border Grid.Row="2" Background="Red">
                        <TextBlock Text="Footer"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Then set style to all pages:

Style="{StaticResource HeaderFooterPageStyle}"


问:
Issues with Leaflet, map not showing up and wont allow me to zoom out
so I'm trying to complete the chloropleth map tutorial from Leaflet but the only thing showing up is the mapbox and nothing else. Any ideas as to why, ive changed browsers from safari to firefox and that didn't help any other ideas? Thanks a bunch!</p>

```<code> <!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>
            The Map
        </title>
        <!--Leaflet-->
        <link rel="stylesheet" href="lib/Leaflet/leaflet.css"/>
        <script src="lib/Leaflet/leaflet.js"></script>
        <script src="data/states.geojson"></script>
        <style type="text/css">
        #map{height:400px;}
        </style>

    </head>
    <body>
        <h1>Breweries Per Capita in the US</h1>
        <div id="map"></div>
        <script>
            var map = L.map('map');
            var statesLayer = L.geoJson(states).addTo(map).setView([36.688938, -101.340000],13);

             L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', {
        maxZoom: 18,
        attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="http://mapbox.com">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(map);
        </script>

    </body>
</html>
</code>```

答:
As stated by Anton Stepanenkov, your first <meta tag is not properly closed.

As suggested by IvanSanchez, you load a .geojson file which, if compliant with json spec, does not assign any variable but should instead be typically loaded through AJAX. Therefore there is a high chance your states variable is undefined. If your .geojson file does assign states (e.g. it contains a statement like var states = {...};), then you should rather rename your file with .js extension, as it is rather a classic JavaScript file.

setView is an L.Map method, you cannot chain it with L.geoJson.

Your mapbox Tile Layer URL template does not seem to work (maybe an issue with the access key?)

Working demo after closing the meta tag, taking out the states, applying setView on map and using another Tile Layer: http://plnkr.co/edit/G1D05GV68IXUlwlv9Pnw?p=preview

Body:
so I'm trying to complete the chloropleth map tutorial from Leaflet but the only thing showing up is the mapbox and nothing else. Any ideas as to why, ive changed browsers from safari to firefox and that didn't help any other ideas? Thanks a bunch!

 <!DOCTYPE html>

        <meta charset="UTF-8"
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <title>
            The Map
        </title>

        <link rel="stylesheet" href="lib/Leaflet/leaflet.css"/>

Breweries Per Capita in the US


问:
Hide axis tick values
Is there a way to hide axis tick values in c3js (version 0.1.42)? In one of the graphs, I have categorical axis with long tick values. I want to hide them and show only on mouseover. I have tried the tick culling option (by setting max to 0) mentioned at http://c3js.org/samples/axes_x_tick_culling.html but it does not work. </p>

答:
With the next code you can hide all x axis ticks

```<code>   .c3-axis-x .tick line {
      display: none;
    }
</code>```

Example: jsfiddle

Title: Hide axis tick values

Body:
With the next code you can hide all x axis ticks

   .c3-axis-x .tick line {
      display: none;
    }

Example: jsfiddle


问:
How to let user upload multiple images without pre-defining the number of HTML upload input box?
I'm looking for a way to have user upload as many images as they want (perhaps via drag and drop) or dynamically adding more upload box.

I thought statically fixing (say 6) HTML upload input box is slightly limiting and the user have to click "Browse" button (6 times in this example) and navigating to the folder to pick the file.

What is the best practice to achieve this so users find it easy to use? Perhaps with some AJAX magic?

I also wouldn't mind having the user click "Upload more" to reveal (say 6 more) HTML upload input box. Was wondering if there is a better way!

Thank you.

答: You may also want to look at something like Plupload</p>


问:
Initialize form array without empty input at index 0
I am currently constructing an update, add, delete and edit form using angular 2 and reactive forms. I have grouped the controls into a form builder array to dynamically add input controls to the form array. This works fine for an empty form that does not have any items to initialize.

```<code>export class ItemsPage{

   collectionForm: FormGroup;
   get items(): FormArray { return <FormArray>this.collectionForm.get('items'); }

   constructor(public formBuilder: FormBuilder){

        this.pageDetails = this.navParams.data;

        this.collectionForm = this.formBuilder.group({
           items: this.formBuilder.array([this.buildItem()])
        });
   }

   buildItem(item?: string): FormGroup {
       return this.formBuilder.group({ item: [item || '', Validators.required] });
   }

   ionViewDidLoad() {
       // Builds a form with pre populated items
       forEach(this.pageDetails, value => {
           this.items.push(this.buildItem(value));
       })
   }
}
</code>```

The problem is that the list of controls in the view contain an empty input at index 0 when this.pageDetails has a list of values. This can be removed in the constructor with

```<code>this.items.removeAt(0);
</code>```

However that does not seem right. I thought that maybe I could build the array in its formBuilder.array

```<code>let prebuildItems = forEach(this.pageDetails, value => { // lodash forEach
  this.items.push(this.buildItem(value));
});

this.collectionForm = this.formBuilder.group({
  items: this.formBuilder.array([prebuildItems])
});
</code>```

However when I navigate to the page with that code I get the following error:

Error in ./ItemsPage class ItemsPage - caused by: Cannot read property 'get' of undefined

答:
I just had a similar issue and I solved it by doing this (I'm adding headers to a FormArray).

```<code>addHeader(name = '', value = '') {
    // get headers array control from group
    let headers = <FormArray>this.editForm.controls['options'].controls['headers'];

    // create new header control
    let header = this.fb.group({
        name: [name, Validators.required],
        value: [value]
    });

    // set the value on the control
    // header.setValue({ name, value });

    // add the new control to the array
    headers.push(header);
}
</code>```

Then when I initially populate the form I just loop over the data and populate the headers.

```<code>this.data.headers.forEach(h => {
    this.addHeader(h.name, h.value);
});
</code>```

I found the information I needed from here Angular Reactive Forms under the section Initialize the "secretLairs" FormArray

I think what I and maybe you are doing is thinking that

```<code>this.formBuilder.array([this.buildItem()])
</code>```

is setting the "schema" for the array, when its actually added a control with value.

Body:
I am currently constructing an update, add, delete and edit form using angular 2 and reactive forms. I have grouped the controls into a form builder array to dynamically add input controls to the form array. This works fine for an empty form that does not have any items to initialize.

export class ItemsPage{

   collectionForm: FormGroup;
   get items(): FormArray { return <FormArray>this.collectionForm.get('items'); }

   constructor(public formBuilder: FormBuilder){

        this.pageDetails = this.navParams.data;

        this.collectionForm = this.formBuilder.group({
           items: this.formBuilder.array([this.buildItem()])
        });
   }

   buildItem(item?: string): FormGroup {
       return this.formBuilder.group({ item: [item || '', Validators.required] });
   }

   ionViewDidLoad() {
       // Builds a form with pre populated items
       forEach(this.pageDetails, value => {
           this.items.push(this.buildItem(value));
       })
   }
}

The problem is that the list of controls in the view contain an empty input at index 0 when this.pageDetails has a list of values. This can be removed in the constructor with

this.items.removeAt(0);

However that does not seem right. I thought that maybe I could build the array in its formBuilder.array

let prebuildItems = forEach(this.pageDetails, value => { // lodash forEach
  this.items.push(this.buildItem(value));
});

this.collectionForm = this.formBuilder.group({
  items: this.formBuilder.array([prebuildItems])
});

However when I navigate to the page with that code I get the following error:

Error in ./ItemsPage class ItemsPage - caused by: Cannot read property 'get' of undefined

Body:
I just had a similar issue and I solved it by doing this (I'm adding headers to a FormArray).

addHeader(name = '', value = '') {
    // get headers array control from group
    let headers = <FormArray>this.editForm.controls['options'].controls['headers'];

    // create new header control
    let header = this.fb.group({
        name: [name, Validators.required],
        value: [value]
    });

    // set the value on the control
    // header.setValue({ name, value });

    // add the new control to the array
    headers.push(header);
}

Then when I initially populate the form I just loop over the data and populate the headers.

this.data.headers.forEach(h => {
    this.addHeader(h.name, h.value);
});

I found the information I needed from here Angular Reactive Forms under the section Initialize the "secretLairs" FormArray

I think what I and maybe you are doing is thinking that

this.formBuilder.array([this.buildItem()])

is setting the "schema" for the array, when its actually added a control with value.


问:
How to prevent select value to reset on form submit?
In the view,

```<code><select id="gender" ng-model="gender">
     <option value=''>Gender?</option>
     <option value="female" >Female</option>
     <option value="male" >Male</option>
     <option value="other" >Other</option>
</select>
<input type="hidden" name="gender" value="{{gender}}">
</code>```

On submit error, the submitted value is retrived and put as the select value,

```<code>var theValue = "<?php echo set_value('gender');?>";
var e = document.getElementById("gender");
e.value = theValue;
</code>```

On submitting the incomplete form, the select should retain the post value, and momentarily it does, but resets again. How do I prevent the select to reset and keep the value?

答:
Try this, create this PHP function,

```<code>    function __selectedDb($ctrlValue,$dbValue)
{
    if($ctrlValue == $dbValue)
        return "selected='selected'";
    else
        return "";
}
</code>```

and use like this,

```<code><select class="custom-select" id="selImgTiling" name="selImgTiling" value="<?php echo $arrBgSettings['bg_image_tiling']?>">
                                <option value="no-repeat"   <?php echo __selectedDb('no-repeat',$arrBgSettings['bg_image_tiling'])?>>Tiling Off</option>
                                <option value="repeat"      <?php echo __selectedDb('repeat',$arrBgSettings['bg_image_tiling'])?>> Repeat</option>
                                <option value="repeat-x"    <?php echo __selectedDb('repeat-x',$arrBgSettings['bg_image_tiling'])?>>Repeat Horizontal</option>
                                <option value="repeat-y"    <?php echo __selectedDb('repeat-y',$arrBgSettings['bg_image_tiling'])?>>Repeat Vertical</option>
                            </select>
</code>```

Body:
In the view,

<select id="gender" ng-model="gender">
     <option value=''>Gender?</option>
     <option value="female" >Female</option>
     <option value="male" >Male</option>
     <option value="other" >Other</option>
</select>
<input type="hidden" name="gender" value="{{gender}}">

On submit error, the submitted value is retrived and put as the select value,

var theValue = "<?php echo set_value('gender');?>";
var e = document.getElementById("gender");
e.value = theValue;

On submitting the incomplete form, the select should retain the post value, and momentarily it does, but resets again. How do I prevent the select to reset and keep the value?

Body:
Try this, create this PHP function,

    function __selectedDb($ctrlValue,$dbValue)
{
    if($ctrlValue == $dbValue)
        return "selected='selected'";
    else
        return "";
}

and use like this,

<select class="custom-select" id="selImgTiling" name="selImgTiling" value="<?php echo $arrBgSettings['bg_image_tiling']?>">
                                <option value="no-repeat"   <?php echo __selectedDb('no-repeat',$arrBgSettings['bg_image_tiling'])?>>Tiling Off</option>
                                <option value="repeat"      <?php echo __selectedDb('repeat',$arrBgSettings['bg_image_tiling'])?>> Repeat</option>
                                <option value="repeat-x"    <?php echo __selectedDb('repeat-x',$arrBgSettings['bg_image_tiling'])?>>Repeat Horizontal</option>
                                <option value="repeat-y"    <?php echo __selectedDb('repeat-y',$arrBgSettings['bg_image_tiling'])?>>Repeat Vertical</option>
                            </select>


问:
AngularJS expressions not working
I'm not able to display expression in AngularJS. Below is my the HTML code.

```<code><!DOCTYPE html>
<html data-ng-app="appname">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="javascript.js"></script>
</head>
<body>
<div data-ng-controller="appCtrl">
    <p>{{appname.product.name}}</p>
</div>
</body>
</html>
</code>```

This is javascript.js file:

```<code>(function () {
    var appname = angular.module('appname', []);

    var gem = {
        name: "Ring",
        price: 2.9,
        Description: "",
    };

    appname.controller('appCtrl', function () {
        this.product = gem;
    });
});
</code>```

The webpage still displays: {{appname.product.name}}.

答:
Probably undocumented case.

In my case, I had got $window level variables of the same name that I was declaring on $scope level.

After changing the name of the variable it worked.

Strange, as it does recognize $scope level variable in js code but when it comes to putting the value in expressions it gets confused.

```<code>//Global JS variable
var currentLocationName = "Nice Location";
</code>```

I was copying this global variable at $scope level.

```<code>$scope.currentLocationName = $window.currentLocationName;
</code>```

And was having it in the expression in my HTML view.

```<code><b>Your current location is {{ currentLocationName }}</b>
</code>```

And this was not working. I changed the name at $scope level and it worked.

My two cents!

Title: AngularJS expressions not working

Body:
I'm not able to display expression in AngularJS. Below is my the HTML code.

<!DOCTYPE html>

{{appname.product.name}}

This is javascript.js file:

(function () {
    var appname = angular.module('appname', []);

    var gem = {
        name: "Ring",
        price: 2.9,
        Description: "",
    };

    appname.controller('appCtrl', function () {
        this.product = gem;
    });
});

The webpage still displays: {{appname.product.name}}.

Body:
Probably undocumented case.

In my case, I had got $window level variables of the same name that I was declaring on $scope level.

After changing the name of the variable it worked.

Strange, as it does recognize $scope level variable in js code but when it comes to putting the value in expressions it gets confused.

//Global JS variable
var currentLocationName = "Nice Location";

I was copying this global variable at $scope level.

$scope.currentLocationName = $window.currentLocationName;

And was having it in the expression in my HTML view.

<b>Your current location is {{ currentLocationName }}</b>

And this was not working. I changed the name at $scope level and it worked.

My two cents!


问:
Getting Client local timezone in VB.NET
I'm creating a form to be filled and submitted by users using VB.net. This form depends on the client's local timezone and i want this timezone to change with daylight savings.

I tried looking for solutions online and all were in JavaScript. Is there a way to find the client local timezone using VB.NET?

It worked using javascript. The code is:

```<code>function GetDate() {
var offset = new Date().getTimezoneOffset();
console.log(offset);
}
</code>```

答:
Try these:

```<code>System.TimeZone.CurrentTimeZone.GetUtcOffset()
System.TimeZoneInfo.Local.IsDaylightSavingTime(Now)
</code>```

or this:

```<code>DateTimeOffset.Now.Offset
</code>```

Title: Getting Client local timezone in VB.NET

Body:
I'm creating a form to be filled and submitted by users using VB.net. This form depends on the client's local timezone and i want this timezone to change with daylight savings.

I tried looking for solutions online and all were in JavaScript. Is there a way to find the client local timezone using VB.NET?

It worked using javascript. The code is:

function GetDate() {
var offset = new Date().getTimezoneOffset();
console.log(offset);
}

Body:
Try these:

System.TimeZone.CurrentTimeZone.GetUtcOffset()
System.TimeZoneInfo.Local.IsDaylightSavingTime(Now)

or this:

DateTimeOffset.Now.Offset


问:
Syntax Error JSON.parse ajax.responsetext (Spring,jquery,ajax,gson)
I am using Netbeans & spring framework4.0.1,without annotation only normal model&view

When i try to send a JSON to the jsp page & using ajax function call back , i am unable to parse the response text, gives me this error
"SyntaxError: JSON.parse: unexpected character at line 12 column 1 of the JSON data"
This is the controller code

```<code> public ModelAndView contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
            ModelAndView mv = new ModelAndView("createsettings");
           List<Content> contents = new ArrayList<>();
     //       JSONObject obj = new JSONObject();
           try {
             DriverManagerDataSource dataSource;
            dataSource = (DriverManagerDataSource)this.getBean("dataSource",hsr.getServletContext());
            this.cn = dataSource.getConnection();
                 Statement st = this.cn.createStatement();
                 String objectiveid = null;
                    objectiveid = hsr.getParameter("seleccion3");
              ResultSet rs1 = st.executeQuery("SELECT name,id FROM         public.content where public.content.id IN (select public.objective_content.content_id from public.objective_content where public.objective_content.objective_id = "+objectiveid+")");

           while (rs1.next())
            {
     Content eq = new Content();
     contents.add(eq);
//   obj.put("name", rs1.getString("name"));

            }

        } catch (SQLException ex) {
            System.out.println("Error leyendo contents: " + ex);
        }
       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       String json = gson.toJson(contents);
       hsr1.setContentType("application/json");

//      System.out.print(json);
//      json = json.replaceAll("\n", "");
//      json = json.trim();
//      json = json.substring(1,json.length()-1);
//      json = json.replace("\\","");
       mv.addObject(json);
        return mv;
    }
</code>```

When i debug json that i am returning has this value
[
  {
    "name": "newspaper"
  },
  {
    "name": "novel"
  }
]
Below is the JSP code

```<code>function comboSelectionObjective()
            {
                if (window.XMLHttpRequest) //mozilla
                {
                    ajax = new XMLHttpRequest(); //No Internet explorer
                } else
                {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                }

                ajax.onreadystatechange = funcionCallBackContent;
             var seleccion3 = document.getElementById("objective").value;
                ajax.open("GET", "createsetting.htm?select=contentlistObjective&seleccion3=" + seleccion3, true);
                ajax.send("");
}
function funcionCallBackContent()
            {
                if (ajax.readyState === 4) {
                    if (ajax.status===200){
                   var data =JSON.parse(ajax.responseText);
                 console.log(data);
                 }
</code>```

i am using gson library, i used before it Json simple but it gave exactly the same error
also i tried to replace all escape characters and did not work either

Is the problem that i am not using annotations?

Appreciate your help

答:
You need to return the json string instead of a ModelAndView object.

When calling the method addOjbect at the ModelAndView object what you are doing is add or overwrite an attribute to the model.

ModelAndView api

Returning the ModelAndView you are returning basically a string with the view name you want to show back, so you are returning a html page, not a json object.

What you need to do is return a json string. So it should be something like:

```<code>@ResponseBody
public String contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {

  .... your code

  hsr1.setContentType("application/json");

  //You should double check before returning. Just an example.
  return gson.toJson(contents);
}
</code>```

Mapping the response body with the @ResponseBody annotation

The @ResponseBody annotation [...] can be put on a method and
  indicates that the return type should be written straight to the HTTP
  response body (and not placed in a Model, or interpreted as a view
  name).

If you do not want to use any anotation at all and go with the old fashioned way, then you have to put the json content directly in the response output. Something like:

```<code>String json = new Gson().toJson(contents);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
</code>```

I hope you get the idea.

Body:
I am using Netbeans & spring framework4.0.1,without annotation only normal model&view

When i try to send a JSON to the jsp page & using ajax function call back , i am unable to parse the response text, gives me this error
"SyntaxError: JSON.parse: unexpected character at line 12 column 1 of the JSON data"
This is the controller code

 public ModelAndView contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {
            ModelAndView mv = new ModelAndView("createsettings");
           List<Content> contents = new ArrayList<>();
     //       JSONObject obj = new JSONObject();
           try {
             DriverManagerDataSource dataSource;
            dataSource = (DriverManagerDataSource)this.getBean("dataSource",hsr.getServletContext());
            this.cn = dataSource.getConnection();
                 Statement st = this.cn.createStatement();
                 String objectiveid = null;
                    objectiveid = hsr.getParameter("seleccion3");
              ResultSet rs1 = st.executeQuery("SELECT name,id FROM         public.content where public.content.id IN (select public.objective_content.content_id from public.objective_content where public.objective_content.objective_id = "+objectiveid+")");

           while (rs1.next())
            {
     Content eq = new Content();
     contents.add(eq);
//   obj.put("name", rs1.getString("name"));

            }

        } catch (SQLException ex) {
            System.out.println("Error leyendo contents: " + ex);
        }
       Gson gson = new GsonBuilder().setPrettyPrinting().create();
       String json = gson.toJson(contents);
       hsr1.setContentType("application/json");

//      System.out.print(json);
//      json = json.replaceAll("\n", "");
//      json = json.trim();
//      json = json.substring(1,json.length()-1);
//      json = json.replace("\\","");
       mv.addObject(json);
        return mv;
    }

When i debug json that i am returning has this value
[
  {
    "name": "newspaper"
  },
  {
    "name": "novel"
  }
]
Below is the JSP code

function comboSelectionObjective()
            {
                if (window.XMLHttpRequest) //mozilla
                {
                    ajax = new XMLHttpRequest(); //No Internet explorer
                } else
                {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                }

                ajax.onreadystatechange = funcionCallBackContent;
             var seleccion3 = document.getElementById("objective").value;
                ajax.open("GET", "createsetting.htm?select=contentlistObjective&seleccion3=" + seleccion3, true);
                ajax.send("");
}
function funcionCallBackContent()
            {
                if (ajax.readyState === 4) {
                    if (ajax.status===200){
                   var data =JSON.parse(ajax.responseText);
                 console.log(data);
                 }

i am using gson library, i used before it Json simple but it gave exactly the same error
also i tried to replace all escape characters and did not work either

Is the problem that i am not using annotations?

Appreciate your help

Body:
You need to return the json string instead of a ModelAndView object.

When calling the method addOjbect at the ModelAndView object what you are doing is add or overwrite an attribute to the model.

ModelAndView api

Returning the ModelAndView you are returning basically a string with the view name you want to show back, so you are returning a html page, not a json object.

What you need to do is return a json string. So it should be something like:

@ResponseBody
public String contentlistObjective(HttpServletRequest hsr, HttpServletResponse hsr1) throws Exception {

  .... your code

  hsr1.setContentType("application/json");

  //You should double check before returning. Just an example.
  return gson.toJson(contents);
}

Mapping the response body with the @ResponseBody annotation

The @ResponseBody annotation [...] can be put on a method and
  indicates that the return type should be written straight to the HTTP
  response body (and not placed in a Model, or interpreted as a view
  name).

If you do not want to use any anotation at all and go with the old fashioned way, then you have to put the json content directly in the response output. Something like:

String json = new Gson().toJson(contents);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

I hope you get the idea.


问:
Do Bamboo Backup includes deleted plan info(config, scripts)?
I, unfortunately, deletes the plan. How can I get that back. I tried to configure it manually but the documentation is not clear so i need it back for sure. Any suggestions?</p>

答: I you did a backup before plan removal - then start new instance of Bamboo and use that backup file during installation.</p>


问:
How to assign a variable to select and update a field with it
I have two columns in my table, and I am trying to update the second column with the result of first col like this.

```<code>SET @pg = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'x' LIMIT 1)
</code>```

Now the above query works the (SELECT ...) as in it returns an ID from the query, so I am trying to use that ID to update another column like this.

```<code>UPDATE wp_posts SET post_type = 'foo' WHERE ID = @pg;
</code>```

But for some reason the above does not work.

and I get the following error.

```<code>1 queries executed, 0 success, 1 errors, 0 warnings

Query: set @pg = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'x' LIMIT 1) SELECT * ...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM wp_posts WHERE id = @pg' at line 3

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0 sec
</code>```

EDIT/UPDATE:

I am also trying to execute this staetment, which is simpler and does the same thing

```<code>UPDATE wp_posts SET post_type = 'x' WHERE ID = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'z' LIMIT 1)
</code>```

but for some reason, it doesn't work.

答:
You could try to UPDATE using JOIN

```<code>UPDATE wp_posts AS a
       INNER JOIN wp_posts AS b ON a.id = b.id
SET    a.post_type = 'x'
WHERE  b.post_name = 'y'
       AND b.post_status = 'z'
</code>```

Or wrapping the update condition in one more select

```<code>UPDATE wp_posts
SET    post_type = 'x'
WHERE  id IN (SELECT id
              FROM   (SELECT id
                      FROM   wp_posts
                      WHERE  post_name = 'y'
                             AND post_status = 'z') AS SOURCE)
</code>```

Body:
I have two columns in my table, and I am trying to update the second column with the result of first col like this.

SET @pg = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'x' LIMIT 1)

Now the above query works the (SELECT ...) as in it returns an ID from the query, so I am trying to use that ID to update another column like this.

UPDATE wp_posts SET post_type = 'foo' WHERE ID = @pg;

But for some reason the above does not work.

and I get the following error.

1 queries executed, 0 success, 1 errors, 0 warnings

Query: set @pg = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'x' LIMIT 1) SELECT * ...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM wp_posts WHERE id = @pg' at line 3

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0 sec

EDIT/UPDATE:

I am also trying to execute this staetment, which is simpler and does the same thing

UPDATE wp_posts SET post_type = 'x' WHERE ID = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'z' LIMIT 1)

but for some reason, it doesn't work.

Body:
You could try to UPDATE using JOIN

UPDATE wp_posts AS a
       INNER JOIN wp_posts AS b ON a.id = b.id
SET    a.post_type = 'x'
WHERE  b.post_name = 'y'
       AND b.post_status = 'z'

Or wrapping the update condition in one more select

UPDATE wp_posts
SET    post_type = 'x'
WHERE  id IN (SELECT id
              FROM   (SELECT id
                      FROM   wp_posts
                      WHERE  post_name = 'y'
                             AND post_status = 'z') AS SOURCE)


问:
Load YouTube GData feed for a single video by id
I am trying to play a youtube video in a UIWebView instead of leaving my application.

Google thinks is easy peasy- http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html

So I have the GData framework and headers working nicely, and I have no problem doing queries, loading user's video feeds etc.

But what I can't seem to do is load a specific video's feed. I know the ids of the videos that I want the feeds for in advance. How do i load a specific video's feed?

I'm then going to follow google's instruction :

```<code>Grab the video url from the media tag in the API response with the application/x-shockwave-flash type.
</code>```

and then embed it like so:

```<code>// webView is a UIWebView, either initialized programmatically or loaded as part of a xib.

NSString *htmlString = @"<html><head>
<meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/></head>
<body style=\"background:#F00;margin-top:0px;margin-left:0px\">
<div><object width=\"212\" height=\"172\">
<param name=\"movie\" value=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"></param>
<param name=\"wmode\" value=\"transparent\"></param>
<embed src=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"
type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"172\"></embed>
</object></div></body></html>";

[webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];
</code>```

Any help would be much appreciated!

答:
In exactly the same situation just found the answer. Typically of many large APIs, common usage instructions get lost in explanation of the higher level stuff - can be frustrating. Thankfully, the info is there...

http://code.google.com/apis/youtube/2.0/developers_guide_protocol_video_entries.html

So, we should be able to plug the returned ATOM feed into the GData library and have it parse out the proper content URL for use in the 'UIWebView' style player code.

...Grobbins, read the question properly next time!

Body:
I am trying to play a youtube video in a UIWebView instead of leaving my application.

Google thinks is easy peasy- http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html

So I have the GData framework and headers working nicely, and I have no problem doing queries, loading user's video feeds etc.

But what I can't seem to do is load a specific video's feed. I know the ids of the videos that I want the feeds for in advance. How do i load a specific video's feed?

I'm then going to follow google's instruction :

Grab the video url from the media tag in the API response with the application/x-shockwave-flash type.

and then embed it like so:

// webView is a UIWebView, either initialized programmatically or loaded as part of a xib.

NSString *htmlString = @"
<meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/>

<object width=\"212\" height=\"172\">
<param name=\"movie\" value=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"></param>
<param name=\"wmode\" value=\"transparent\"></param>
<embed src=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"
type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"172\"></embed>
</object>
";

[webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];

Any help would be much appreciated!


问:
Auto chart height
The default highstock chart has height = 400px.

How can height chart be set for auto size based on chart axis and its sizes ?

See the example bellow, the navigation bar is over the volume panel.

http://jsfiddle.net/BYNsJ/

I know that I can set the height for the div but I have a solution that insert/remove axis/series dynamically in the chart and would be nice an auto height chart.

The example is the same Candlestick/Volume demo from Highchart site, but without height property in the div container.

```<code>    // split the data set into ohlc and volume
    var ohlc = [],
        volume = [],
        dataLength = data.length;

    for (i = 0; i < dataLength; i++) {
        ohlc.push([
            data[i][0], // the date
            data[i][1], // open
            data[i][2], // high
            data[i][3], // low
            data[i][4] // close
        ]);

        volume.push([
            data[i][0], // the date
            data[i][5] // the volume
        ])
    }

    // set the allowed units for data grouping
    var groupingUnits = [[
        'week',                         // unit name
        [1]                             // allowed multiples
    ], [
        'month',
        [1, 2, 3, 4, 6]
    ]];

    // create the chart
    $('#container').highcharts('StockChart', {

        rangeSelector: {
            selected: 1
        },

        title: {
            text: 'AAPL Historical'
        },

        yAxis: [{
            title: {
                text: 'OHLC'
            },
            height: 200,
            lineWidth: 2
        }, {
            title: {
                text: 'Volume'
            },
            top: 300,
            height: 100,
            offset: 0,
            lineWidth: 2
        }],

        series: [{
            type: 'candlestick',
            name: 'AAPL',
            data: ohlc,
            dataGrouping: {
                units: groupingUnits
            }
        }, {
            type: 'column',
            name: 'Volume',
            data: volume,
            yAxis: 1,
            dataGrouping: {
                units: groupingUnits
            }
        }]
    });
    });
});
</code>```

Regards.

答:
You can set chart.height dynamically with chart.update method.

http://api.highcharts.com/highcharts/Chart.update

```<code>function resizeChartFromValues (chart) {
  const pixelsForValue = 10
  const axis = chart.yAxis[0]
  chart.update({ chart: { height: (axis.max - axis.min) * pixelsForValue } })
}

const options = {
  chart: {
    events: {
      load () {resizeChartFromValues(this)}
    }
  },
  series: [{
    data: [30, 70, 100],
  }]
}

const chart = Highcharts.chart('container', options)

setTimeout(() => {
  chart.series[0].setData([10, 20, 30])
  resizeChartFromValues(chart)
}, 1000)
</code>```

Live example: https://jsfiddle.net/a97fgsmc/

Title: Auto chart height

Body:
The default highstock chart has height = 400px.

How can height chart be set for auto size based on chart axis and its sizes ?

See the example bellow, the navigation bar is over the volume panel.

http://jsfiddle.net/BYNsJ/

I know that I can set the height for the div but I have a solution that insert/remove axis/series dynamically in the chart and would be nice an auto height chart.

The example is the same Candlestick/Volume demo from Highchart site, but without height property in the div container.

    // split the data set into ohlc and volume
    var ohlc = [],
        volume = [],
        dataLength = data.length;

    for (i = 0; i < dataLength; i++) {
        ohlc.push([
            data[i][0], // the date
            data[i][1], // open
            data[i][2], // high
            data[i][3], // low
            data[i][4] // close
        ]);

        volume.push([
            data[i][0], // the date
            data[i][5] // the volume
        ])
    }

    // set the allowed units for data grouping
    var groupingUnits = [[
        'week',                         // unit name
        [1]                             // allowed multiples
    ], [
        'month',
        [1, 2, 3, 4, 6]
    ]];

    // create the chart
    $('#container').highcharts('StockChart', {

        rangeSelector: {
            selected: 1
        },

        title: {
            text: 'AAPL Historical'
        },

        yAxis: [{
            title: {
                text: 'OHLC'
            },
            height: 200,
            lineWidth: 2
        }, {
            title: {
                text: 'Volume'
            },
            top: 300,
            height: 100,
            offset: 0,
            lineWidth: 2
        }],

        series: [{
            type: 'candlestick',
            name: 'AAPL',
            data: ohlc,
            dataGrouping: {
                units: groupingUnits
            }
        }, {
            type: 'column',
            name: 'Volume',
            data: volume,
            yAxis: 1,
            dataGrouping: {
                units: groupingUnits
            }
        }]
    });
    });
});

Regards.

Body:
You can set chart.height dynamically with chart.update method.

http://api.highcharts.com/highcharts/Chart.update

function resizeChartFromValues (chart) {
  const pixelsForValue = 10
  const axis = chart.yAxis[0]
  chart.update({ chart: { height: (axis.max - axis.min) * pixelsForValue } })
}

const options = {
  chart: {
    events: {
      load () {resizeChartFromValues(this)}
    }
  },
  series: [{
    data: [30, 70, 100],
  }]
}

const chart = Highcharts.chart('container', options)

setTimeout(() => {
  chart.series[0].setData([10, 20, 30])
  resizeChartFromValues(chart)
}, 1000)

Live example: https://jsfiddle.net/a97fgsmc/


问:
How to close window in vaadin?
I have got class MyCustomWindow which extends Window (com.vaadin.ui) from vaadin.
When you click some button MyCustomWindow will show.
Now I would like to add button to this window and when you push this buton it will close the window.
I have got problem what to use to remove this window.
I have found:

```<code>Window w = getWindow();
getApplication().removeWindow(w);
</code>```

or

```<code>Window w = this.findAncestor(Window.class);
w.close();
</code>```

But it doesn't work.
I would like to remove window from inside the class, not from outside, using "this"? Something like:

```<code>UI.getCurrent().removeWindow(this);
</code>```

I am using vaadin 7.
Can you help me?

答:
Hello if you want to close the window from inside your click listener you can do one of the following two things:

```<code>yourButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                MyCustomWindow.this.close();
            }
        });
</code>```

Or:

```<code>yourButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                closeMyCustomWindow();
            }
        });

private void closeMyCustomWindow(){
   this.close();
}
</code>```

closeMyCustomWindow() this function is inside the MyCustomWindow class.

Title: How to close window in vaadin?

Body:
I have got class MyCustomWindow which extends Window (com.vaadin.ui) from vaadin.
When you click some button MyCustomWindow will show.
Now I would like to add button to this window and when you push this buton it will close the window.
I have got problem what to use to remove this window.
I have found:

Window w = getWindow();
getApplication().removeWindow(w);

or

Window w = this.findAncestor(Window.class);
w.close();

But it doesn't work.
I would like to remove window from inside the class, not from outside, using "this"? Something like:

UI.getCurrent().removeWindow(this);

I am using vaadin 7.
Can you help me?

Body:
Hello if you want to close the window from inside your click listener you can do one of the following two things:

yourButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                MyCustomWindow.this.close();
            }
        });

Or:

yourButton.addClickListener(new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                closeMyCustomWindow();
            }
        });

private void closeMyCustomWindow(){
   this.close();
}

closeMyCustomWindow() this function is inside the MyCustomWindow class.


问:
remove vectors which are subsets of other vectors in a list
I have a list with vectors of different length, for example:

```<code>a=c(12345,12367,91670,87276,92865)
b=c(12345,87276,89250)
c=c(12367,91670)
d=c(23753,82575,91475,10957,92865,24311)
mylist=list(a,b,c,d)
mylist

# [[1]]
# [1] 12345 12367 91670 87276 92865
#
# [[2]]
# [1] 12345 87276 89250
#
# [[3]]
# [1] 12367 91670
#
# [[4]]
# [1] 23753 82575 91475 10957 92865 24311
</code>```

my question is how can I remove the vectors of this list which are a subset of another vector of the same list. i.e. in this case how can I remove the 3rd object of the list which is a subset of the 1st object??

答:
An alternative (of the "list") format for the elements is a table of "elements-by-values":

```<code>table(values = unlist(mylist),
      elt = rep(seq_along(mylist), lengths(mylist)))
#       elt
#values  1 2 3 4
#  10957 0 0 0 1
#  12345 1 1 0 0
#  12367 1 0 1 0
#  23753 0 0 0 1
#  24311 0 0 0 1
#  82575 0 0 0 1
#  87276 1 1 0 0
#  89250 0 1 0 0
#  91475 0 0 0 1
#  91670 1 0 1 0
#  92865 1 0 0 1
</code>```

This can, very easy, consume much memory so we could chase a sparse alternative:

```<code>l = unlist(mylist)
ul = unique(l)
tab = sparseMatrix(x = TRUE,
                   i = match(l, ul),
                   j = rep(seq_along(mylist), lengths(mylist)),
                   dimnames = list(ul, sprintf("elt_%d", seq_along(mylist))))

tab
#11 x 4 sparse Matrix of class "lgCMatrix"
#      elt_1 elt_2 elt_3 elt_4
#12345     |     |     .     .
#12367     |     .     |     .
#91670     |     .     |     .
#87276     |     |     .     .
#92865     |     .     .     |
#89250     .     |     .     .
#23753     .     .     .     |
#82575     .     .     .     |
#91475     .     .     .     |
#10957     .     .     .     |
#24311     .     .     .     |
</code>```

Then, to find which element is a subset of which:

```<code>subsets = lengths(mylist) == crossprod(tab)

subsets
#4 x 4 sparse Matrix of class "lgCMatrix"
#      elt_1 elt_2 elt_3 elt_4
#elt_1     |     .     .     .
#elt_2     .     |     .     .
#elt_3     |     .     |     .
#elt_4     .     .     .     |
</code>```

where, here, each element is a subset of ...itself and 3 is a subset of 1. To reach the wanted info we could use:

```<code>subset(summary(subsets), i != j)[c("i", "j")]

#
#  i j
#2 3 1
</code>```

Or, to avoid incorporating "diag" indices and subsetting them afterwards, we could manipulate the structure already present:

```<code>dp = diff(subsets@p)
j = rep(0:(length(dp) - 1), dp)
wh = subsets@i != j
cbind(subset = subsets@i[wh], of = j[wh]) + 1L
#     subset of
#[1,]      3  1
</code>```

In both the last cases, the unique of the first column shows which elements are subset of another and can be used to [ "mylist".

Body:
I have a list with vectors of different length, for example:

a=c(12345,12367,91670,87276,92865)
b=c(12345,87276,89250)
c=c(12367,91670)
d=c(23753,82575,91475,10957,92865,24311)
mylist=list(a,b,c,d)
mylist

# [[1]]
# [1] 12345 12367 91670 87276 92865
#
# [[2]]
# [1] 12345 87276 89250
#
# [[3]]
# [1] 12367 91670
#
# [[4]]
# [1] 23753 82575 91475 10957 92865 24311

my question is how can I remove the vectors of this list which are a subset of another vector of the same list. i.e. in this case how can I remove the 3rd object of the list which is a subset of the 1st object??

Body:
An alternative (of the "list") format for the elements is a table of "elements-by-values":

table(values = unlist(mylist),
      elt = rep(seq_along(mylist), lengths(mylist)))
#       elt
#values  1 2 3 4
#  10957 0 0 0 1
#  12345 1 1 0 0
#  12367 1 0 1 0
#  23753 0 0 0 1
#  24311 0 0 0 1
#  82575 0 0 0 1
#  87276 1 1 0 0
#  89250 0 1 0 0
#  91475 0 0 0 1
#  91670 1 0 1 0
#  92865 1 0 0 1

This can, very easy, consume much memory so we could chase a sparse alternative:

l = unlist(mylist)
ul = unique(l)
tab = sparseMatrix(x = TRUE,
                   i = match(l, ul),
                   j = rep(seq_along(mylist), lengths(mylist)),
                   dimnames = list(ul, sprintf("elt_%d", seq_along(mylist))))

tab
#11 x 4 sparse Matrix of class "lgCMatrix"
#      elt_1 elt_2 elt_3 elt_4
#12345     |     |     .     .
#12367     |     .     |     .
#91670     |     .     |     .
#87276     |     |     .     .
#92865     |     .     .     |
#89250     .     |     .     .
#23753     .     .     .     |
#82575     .     .     .     |
#91475     .     .     .     |
#10957     .     .     .     |
#24311     .     .     .     |

Then, to find which element is a subset of which:

subsets = lengths(mylist) == crossprod(tab)

subsets
#4 x 4 sparse Matrix of class "lgCMatrix"
#      elt_1 elt_2 elt_3 elt_4
#elt_1     |     .     .     .
#elt_2     .     |     .     .
#elt_3     |     .     |     .
#elt_4     .     .     .     |

where, here, each element is a subset of ...itself and 3 is a subset of 1. To reach the wanted info we could use:

subset(summary(subsets), i != j)[c("i", "j")]

#
#  i j
#2 3 1

Or, to avoid incorporating "diag" indices and subsetting them afterwards, we could manipulate the structure already present:

dp = diff(subsets@p)
j = rep(0:(length(dp) - 1), dp)
wh = subsets@i != j
cbind(subset = subsets@i[wh], of = j[wh]) + 1L
#     subset of
#[1,]      3  1

In both the last cases, the unique of the first column shows which elements are subset of another and can be used to [ "mylist".


问:
Download a file in Angular Environment
I need to download a file from the server. The file is stored in the database. I have a cs controller that serves a file back to UI. The server GET call looks like this:

```<code>http://server/api/controllername/fileid/data
</code>```

It does work when I run that link in the Browser - the file comes down and goes into the download area (Chrome). But when I send the same command from my Angualar code  I dont see any file. The console reports that my request was successful (code 200), but I just dont see anything. Please let me know what code fragments to post to make it easier to help.

Thanks

答:
The file probably downloads correctly as a byte[] to the calling it but that would be useless to the user - as was my problem.

In my case I needed to download a file with a complex set of parameters. This example JavaScript uses a post request and creates a form (and posts it) with any JavaScript  object that you give it. This code may help if you simplified it:

private open(verb, url, data, target)
    {
        var form = document.createElement("form");
        form.action = url;
        form.method = verb;
        form.target = target || "_self";
        if (data) {
            this.createFormParameters(form, "", data);
        }

        form.style.display = 'none';
        document.body.appendChild(form);
        form.submit();
    }

    private createFormParameters(form, key, value) {
        // recursive algorithm to add parameters (including objects and arrays of objects) to a custom form

        if (typeof value === "object") {
            for (var item in value) {

                if (Array.isArray(value[item])) {
                    for (var arrayItem in value[item]) {
                        this.createFormParameters(form, (item + "[" + arrayItem + "]."), value[item][arrayItem]);
                    }
                    continue;
                }

                var input = document.createElement("textarea");
                input.name = key + item;
                input.value = value[item];
                form.appendChild(input);
            }
        }
        else
        {
            var input = document.createElement("textarea");
            input.name = key;
            input.value = value;
            form.appendChild(input);
        }
    }```

Title: Download a file in Angular Environment

Body:
I need to download a file from the server. The file is stored in the database. I have a cs controller that serves a file back to UI. The server GET call looks like this:

http://server/api/controllername/fileid/data

It does work when I run that link in the Browser - the file comes down and goes into the download area (Chrome). But when I send the same command from my Angualar code  I dont see any file. The console reports that my request was successful (code 200), but I just dont see anything. Please let me know what code fragments to post to make it easier to help.

Thanks


问:
Model Look up table for a JPA Entity Field
I'm trying to find out the appropriate relationship to be used in order to model an JPA Entity Field which needs a Look-up table (Comboxbox equivalent on the UI) to select the value from. An example below:

```<code>@Entity
public class Employee {

    @Id
    private int employeeId;
    private String name;
    private Department department;
}
</code>```

```<code>@Entity
public class Department  {

    @Id
    private int id;
    private String name;
}
</code>```

The instances of Department could be as follows:

```<code>Id    | Name
-----------------------
100   | Human Resources
101   | Sales
102   | Finances
</code>```

For an employee, the department field should get a value from one of the above. What should be the JPA annotations for the corresponding fields in both the entities?

Thanks,

Sandeep Joseph

答:
I think you are looking for a unidirectional ManyToOne relationship from Employee to Department, something like this:

```<code>@Entity
public class Employee {

    @Id
    private int employeeId;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id", nullable = false)
    private Department department;
}
</code>```

This means an employee must be associated to a single department and a department can be associated to many employees.

If you need to know the list of employees associated to a department then you can make the relationship bidirectional by adding this:

```<code>@Entity
public class Department  {

    @Id
    private int id;
    private String name;

    @OneToMany(mappedBy = "department")
    private Collection<Employee> employees;
}
</code>```

Body:
I'm trying to find out the appropriate relationship to be used in order to model an JPA Entity Field which needs a Look-up table (Comboxbox equivalent on the UI) to select the value from. An example below:

@Entity
public class Employee {

    @Id
    private int employeeId;
    private String name;
    private Department department;
}

@Entity
public class Department  {

    @Id
    private int id;
    private String name;
}

The instances of Department could be as follows:

Id    | Name
-----------------------
100   | Human Resources
101   | Sales
102   | Finances

For an employee, the department field should get a value from one of the above. What should be the JPA annotations for the corresponding fields in both the entities?

Thanks,

Sandeep Joseph

Body:
I think you are looking for a unidirectional ManyToOne relationship from Employee to Department, something like this:

@Entity
public class Employee {

    @Id
    private int employeeId;
    private String name;

    @ManyToOne
    @JoinColumn(name = "department_id", nullable = false)
    private Department department;
}

This means an employee must be associated to a single department and a department can be associated to many employees.

If you need to know the list of employees associated to a department then you can make the relationship bidirectional by adding this:

@Entity
public class Department  {

    @Id
    private int id;
    private String name;

    @OneToMany(mappedBy = "department")
    private Collection<Employee> employees;
}


问:
Java's Generic, Inheritance and Inner static classes compilation issue
I have weird compilation issue related to the usage of inherited static inner class as the Generic type.

Just in case: each of individual code snippet is a separate class in the same package.

ParentOuter & ParentInner:

```<code>public class ParentOuter <T extends ParentOuter.ParentInner> {
    T field;

    public static class ParentInner {
    }
}
</code>```

ChildOuter & ChildInner:

```<code>import com.company.ChildOuter.ChildInner;
//import com.company.ParentOuter.ParentInner;

public class ChildOuter extends ParentOuter <ChildInner> {

    public static class ChildInner extends ParentInner {
    }
}
</code>```

TopLevelChild:

```<code>public class TopLevelChild extends ParentOuter.ParentInner {
}
</code>```

Following is the result of compilation:

```<code>$ javac *.java
ChildOuter.java:8: error: cannot find symbol
    public static class ChildInner extends ParentInner {
                                           ^
  symbol:   class ParentInner
  location: class ChildOuter
ChildOuter.java:6: error: type argument ChildInner is not within bounds of type-variable T
public class ChildOuter extends ParentOuter <ChildInner> {
                                             ^
  where T is a type-variable:
    T extends ParentInner declared in class ParentOuter
2 errors
</code>```

Notes:

When I uncomment import com.company.ParentOuter.ParentInner; then
compilation is successful.

When I use <TopLevelChild> instead of <ChildInner> in the ChildOuter then compilation is successful

Questions:

So, from what I see, looks like, javac is not able to determine,
that ChildInner is sub-class of ParentInner, when it used as the
Generic type.

Is it really so? If so - then why? Is expected behaviour or an issue in javac?

Also Android Studio highlight import of ParentInner as "unused import" and removes it when run "Optimize imports", which makes code not compilable.

So, again - is it issue of Android Studio  or javac ?

P.S. I was facing with similar issue for the long time, but finally decided to post this question.

Hope, it's not duplicate as its 1st time I am not able to find an answer neither in single source nor by analysing combination of answers/articles.

答:
Yes, We can resolve this without importing "ParentInner".

The root cause is, the compiler is not able to resolve the "ParentInner". Since "ParentInner" is the static member of "ParentOuter".

So instead of importing "ParentInner" we can simply mention "ParentOuter.ParentInner"

Please find the tweaked ChildOuter.java,

```<code>    package com.company;

import com.company.ChildOuter.ChildInner;
//import com.company.ParentOuter.ParentInner;

public class ChildOuter extends ParentOuter <ChildInner> {

    public static class ChildInner extends ParentOuter.ParentInner {
    }
}
</code>```

Let me know if this helps. Thanks

Body:
I have weird compilation issue related to the usage of inherited static inner class as the Generic type.

Just in case: each of individual code snippet is a separate class in the same package.

ParentOuter & ParentInner:

public class ParentOuter <T extends ParentOuter.ParentInner> {
    T field;

    public static class ParentInner {
    }
}

ChildOuter & ChildInner:

import com.company.ChildOuter.ChildInner;
//import com.company.ParentOuter.ParentInner;

public class ChildOuter extends ParentOuter <ChildInner> {

    public static class ChildInner extends ParentInner {
    }
}

TopLevelChild:

public class TopLevelChild extends ParentOuter.ParentInner {
}

Following is the result of compilation:

$ javac *.java
ChildOuter.java:8: error: cannot find symbol
    public static class ChildInner extends ParentInner {
                                           ^
  symbol:   class ParentInner
  location: class ChildOuter
ChildOuter.java:6: error: type argument ChildInner is not within bounds of type-variable T
public class ChildOuter extends ParentOuter <ChildInner> {
                                             ^
  where T is a type-variable:
    T extends ParentInner declared in class ParentOuter
2 errors

Notes:

When I uncomment import com.company.ParentOuter.ParentInner; then
compilation is successful.

When I use <TopLevelChild> instead of <ChildInner> in the ChildOuter then compilation is successful

Questions:

So, from what I see, looks like, javac is not able to determine,
that ChildInner is sub-class of ParentInner, when it used as the
Generic type.

Is it really so? If so - then why? Is expected behaviour or an issue in javac?

Also Android Studio highlight import of ParentInner as "unused import" and removes it when run "Optimize imports", which makes code not compilable.

So, again - is it issue of Android Studio  or javac ?

P.S. I was facing with similar issue for the long time, but finally decided to post this question.

Hope, it's not duplicate as its 1st time I am not able to find an answer neither in single source nor by analysing combination of answers/articles.

Body:
Yes, We can resolve this without importing "ParentInner".

The root cause is, the compiler is not able to resolve the "ParentInner". Since "ParentInner" is the static member of "ParentOuter".

So instead of importing "ParentInner" we can simply mention "ParentOuter.ParentInner"

Please find the tweaked ChildOuter.java,

    package com.company;

import com.company.ChildOuter.ChildInner;
//import com.company.ParentOuter.ParentInner;

public class ChildOuter extends ParentOuter <ChildInner> {

    public static class ChildInner extends ParentOuter.ParentInner {
    }
}

Let me know if this helps. Thanks