问:
how can delete/remove values from list/set/dict in Python?
I created a list, a set and a dict and now I want to remove certain items from them

```<code>N = [10**i for i in range(0,3)] #range(3,7) for 1000 to 1M
    for i in N:
        con_list = []
        con_set = set()
        con_dict = {}
        for x in range (i): #this is the list
            con_list.append(x)
            print(con_list)
        for x in range(i): #this is the set
            con_set.add(x)
            print(con_set)
        for x in range(i): #this is the dict
            con_dict = dict(zip(range(x), range(x)))
            print(con_dict)
</code>```

items to remove

```<code>n = min(10000, int(0.1 * len(con_list)))
indeces_to_delete = sorted(random.sample(range(i),n), reverse=True)
</code>```

now if I add this:

```<code>for a in indeces_to_delete:
     del con_list[a]
     print(con_list)
</code>```

it doesn't work

Need to do the same for a set and a dict

Thanks!

答:
You can use pop
On a dict:

```<code>d = {'a': 'test', 'b': 'test2'}
</code>```

calling d.pop('b') will remove the key/value pair for key b

on list:

```<code>l = ['a', 'b', 'c']
</code>```

calling l.pop(2) will remove the third element (as list index start at 0)

Beware on set:

```<code>s = {'a', 'b', 'c'}
</code>```

calling s.pop() will remove a random element as discussed here: In python, is set.pop() deterministic?

you should use s.discard('a') to remove element 'a'

More infos here: https://docs.python.org/2/tutorial/datastructures.html

Body:
I created a list, a set and a dict and now I want to remove certain items from them

N = [10**i for i in range(0,3)] #range(3,7) for 1000 to 1M
    for i in N:
        con_list = []
        con_set = set()
        con_dict = {}
        for x in range (i): #this is the list
            con_list.append(x)
            print(con_list)
        for x in range(i): #this is the set
            con_set.add(x)
            print(con_set)
        for x in range(i): #this is the dict
            con_dict = dict(zip(range(x), range(x)))
            print(con_dict)

items to remove

n = min(10000, int(0.1 * len(con_list)))
indeces_to_delete = sorted(random.sample(range(i),n), reverse=True)

now if I add this:

for a in indeces_to_delete:
     del con_list[a]
     print(con_list)

it doesn't work

Need to do the same for a set and a dict

Thanks!

Body:
You can use pop
On a dict:

d = {'a': 'test', 'b': 'test2'}

calling d.pop('b') will remove the key/value pair for key b

on list:

l = ['a', 'b', 'c']

calling l.pop(2) will remove the third element (as list index start at 0)

Beware on set:

s = {'a', 'b', 'c'}

calling s.pop() will remove a random element as discussed here: In python, is set.pop() deterministic?

you should use s.discard('a') to remove element 'a'

More infos here: https://docs.python.org/2/tutorial/datastructures.html


来源: stackexchange

问:
using a static library featuring <mutex> in a CLR library
I have a utility library written in c++ that I use in many of my projects.

I wanted to create a partial wrapper for it in c++/CLI to bring some of its features to a vb.net project of mine but immediately ran into a problem -

```<code><mutex> is not supported when compiling with /clr or /clr:pure.
</code>```

And I can't cut out the things using mutex either since the ria logging utility I have there is the main thing I want this wrapper for and it relies heavily on mutex.

So.. is there any way around this problem?

答:
If you cannot "hide" the C++ headers that are illegal in CLR (mutex, atomic, ...) by mean of a wrapper C++ class/code or simple forward declarations,

the only other way I succeeded in something very similar is by creating an Interop assembly with:

 - an unmanaged C++ "layer" whose only purpose is to insulate the "real" C++ code (containing mutex, atomic and anything illegal in CLR)

 - a managed C++ "layer" that uses the unmanaged layer, and exposed its API/services to the .NET world.

Ugly, heavy to maintain and error-prone as it can be, unfortunately.

ContentLicense: CC BY-SA 3.0

Body:
I have a utility library written in c++ that I use in many of my projects.

I wanted to create a partial wrapper for it in c++/CLI to bring some of its features to a vb.net project of mine but immediately ran into a problem -

<mutex> is not supported when compiling with /clr or /clr:pure.

And I can't cut out the things using mutex either since the ria logging utility I have there is the main thing I want this wrapper for and it relies heavily on mutex.

So.. is there any way around this problem?


问:
"Hello world" Android app with as few files as possible, no IDE, and text editor only
In nearly all languages that I've used (Python, C, C++, etc.), it's possible to write a "hello world" application with a text editor only and run it from command-line (interpreted languages) or compile/build it from command-line (compiled languages), e.g. cl.exe helloworld1.cpp.

On the other hand, every time I'm doing an Android App, I need to use Android Studio (which is slow on my machine), create a new project with the IDE, etc.

Question: What is the smallest number of minimalist Java source code files/project files to produce an .apk Android app? How to build it from command-line? (and never have to open the IDE)

NB: I've read many hello world for Android but all of them involve using the IDE.

NB2: I'm looking for standard apps written in Java, not solutions like Kivy, etc.

NB3: even if an IDE is probably more convenient to program an Android app, I don't see any technical reason for which compiling/building a number of files would absolutely require an IDE / programming with a GUI. Some people (like me) prefer command-line and text editor only, and such an IDE-free solution would be helpful.

NB4: I'm working on Windows platform, I have started a "Hello World without IDE" github repo here based on this answer, but I have a few problems such as this one. On the other hand, the method used there seems to be deprecated...

答:
What is the smallest number of minimalist Java source code
  files/project files to produce an .apk Android app?

Only these 2 files are required to build android Apk file classes.dex and  AndroidManifest.xml , check out
 this blog post for complete info .

The smallest apk size made till now is 678 bytes.check out this repo


问:
flask request args parser error The browser (or proxy) sent a request that this server could not understand
using test_client and sending a request like so:

```<code>app = Flask(__name__)
client = app.test_client()

headers = {'content-type': 'application/json', 'Authorization': u'Bearer fake_token_123'}
params = {'dont_care': True}
client.get(ֿֿ'/my_route/123', query_string=params, headers=headers)
</code>```

my route is

```<code>class MyController(Resource):

    def get(self, id):
        parser = reqparse.RequestParser()
        parser.add_argument('currency', type=str, default='USD', help="help text")

        args = parser.parse_args()
        currency_from_params = args.currency
</code>```

parser.parse_args() failing for

```<code>The browser (or proxy) sent a request that this server could not understand
</code>```

when removing 'content-type': 'application/json' from header it works.

I don't understand this behaviour, and how do I protect against it without the un elegant try, expect.

Thanks for your help

答: You already discovered how to fix it: don't send content-type: application/json if you're not posting JSON. You can't send JSON with GET, and even if you could (or were using POST) you would have to encode the JSON with json.dumps(data) first.

Body:
using test_client and sending a request like so:

app = Flask(__name__)
client = app.test_client()

headers = {'content-type': 'application/json', 'Authorization': u'Bearer fake_token_123'}
params = {'dont_care': True}
client.get(ֿֿ'/my_route/123', query_string=params, headers=headers)

my route is

class MyController(Resource):

    def get(self, id):
        parser = reqparse.RequestParser()
        parser.add_argument('currency', type=str, default='USD', help="help text")

        args = parser.parse_args()
        currency_from_params = args.currency

parser.parse_args() failing for

The browser (or proxy) sent a request that this server could not understand

when removing 'content-type': 'application/json' from header it works.

I don't understand this behaviour, and how do I protect against it without the un elegant try, expect.

Thanks for your help


问:
Is jquery or animated png/gif better for image animation on a webpage?
Would it be better to use an animated gif/png or jquery for very fast image animation? Flash is not an option because of lack of iPhone/iPad support.

I have to add a row of flickering candles to a homepage (I know its a bad idea, but they wanted a 5-second animated splash screen so its a compromise). The image is approx 600 x 200px, and needs to be quick for the flame "flicker".

I have only used jquery for fading images so I don't know if it is suitable for this?

Any advise welcome, thanks!

答: If speed is the issue, go with an animated gif. Use jQuery to swap out the animation with a static image after 5 seconds (preload the image while the gif animation is running so there is no delay during the swapping).</p>

ContentLicense: CC BY-SA 2.5


问:
Cloud Functions for Firebase HelloWorld "Error: An unexpected error has occurred."
When trying to run the simple HelloWorld Example found on firebase youtube video.

Im further confused as it does not provide an detailed error message and log files found with command firebase functions:log is empty.

I am also using Webstorm as my IDE

Here is a screenshot of the terminal

index.js file

```<code>const functions = require('firebase-functions');

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});
</code>```

package.json

```<code>{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "firebase-admin": "~4.2.1",
    "firebase-functions": "^0.5.7"
  },
  "private": true
}
</code>```

答:
You are probably using the Node with version 8.0.0.
Just downgrade it.

I've tried with 6.10.3 and got success :)

Body:
When trying to run the simple HelloWorld Example found on firebase youtube video.

Im further confused as it does not provide an detailed error message and log files found with command firebase functions:log is empty.

I am also using Webstorm as my IDE

Here is a screenshot of the terminal

index.js file

const functions = require('firebase-functions');

// Create and Deploy Your First Cloud Functions
// https://firebase.google.com/docs/functions/write-firebase-functions

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

package.json

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {
    "firebase-admin": "~4.2.1",
    "firebase-functions": "^0.5.7"
  },
  "private": true
}


问:
Clicking a button in Internet Explorer using VBA (getElementsByClassName)
I'm trying to click a button within an Internet Explorer window using VBA and HTML. The button has no "id" so I have to locate it by "classname."

The button's HTML code is as follows:

```<code><button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only`"
</code>```

VBA Code:

```<code>Private Sub CommandButton21_Click()

Const cURL = "xxxxxx.com"
Const cUsername = "xxxxxx"
Const cPassword = "xxxxxx"

Dim IE As InternetExplorer
Dim doc As HTMLDocument
Dim LoginForm As HTMLFormElement
Dim UserNameInputBox As HTMLInputElement
Dim PasswordInputBox As HTMLInputElement
Dim SignInButton As HTMLInputButtonElement
Dim CVBATButton As HTMLInputButtonElement
Set IE = New InternetExplorer

IE.Visible = True
IE.navigate cURL

Do While IE.readyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop

Set doc = IE.document

'A previous login window that leads me into a new window, where I need to click a button.

Set LoginForm = doc.forms(0)
Set UserNameInputBox = doc.getElementById("BIA_Login")
UserNameInputBox.Value = cUsername
Set PasswordInputBox = doc.getElementById("BIA_Pass")
PasswordInputBox.Value = cPassword
Set SignInButton = doc.getElementById("login")
SignInButton.Click

'It's this portion of the code below that I'm struggling with

Set doc = IE.document
Set LoginForm = doc.forms(0)
Application.Wait Now + TimeValue("00:00:03")
Set CVBATButton = doc.getElementsByClassName("ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only")
CVBATButton.Click
</code>```

答:
I had the same Error,
try this (it worked for me):</p>

```<code>Set CVBATButton = doc.getElementsByClassName("ui-button ui-widget ui-state-
default ui-corner-all ui-button-text-only")
  For Each btn In CVBATButton
     btn.Click
     Exit For
  Next
</code>```

Body:
I'm trying to click a button within an Internet Explorer window using VBA and HTML. The button has no "id" so I have to locate it by "classname."

The button's HTML code is as follows:

<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only`"

VBA Code:

Private Sub CommandButton21_Click()

Const cURL = "xxxxxx.com"
Const cUsername = "xxxxxx"
Const cPassword = "xxxxxx"

Dim IE As InternetExplorer
Dim doc As HTMLDocument
Dim LoginForm As HTMLFormElement
Dim UserNameInputBox As HTMLInputElement
Dim PasswordInputBox As HTMLInputElement
Dim SignInButton As HTMLInputButtonElement
Dim CVBATButton As HTMLInputButtonElement
Set IE = New InternetExplorer

IE.Visible = True
IE.navigate cURL

Do While IE.readyState <> READYSTATE_COMPLETE Or IE.Busy: DoEvents: Loop

Set doc = IE.document

'A previous login window that leads me into a new window, where I need to click a button.

Set LoginForm = doc.forms(0)
Set UserNameInputBox = doc.getElementById("BIA_Login")
UserNameInputBox.Value = cUsername
Set PasswordInputBox = doc.getElementById("BIA_Pass")
PasswordInputBox.Value = cPassword
Set SignInButton = doc.getElementById("login")
SignInButton.Click

'It's this portion of the code below that I'm struggling with

Set doc = IE.document
Set LoginForm = doc.forms(0)
Application.Wait Now + TimeValue("00:00:03")
Set CVBATButton = doc.getElementsByClassName("ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only")
CVBATButton.Click

Body:
I had the same Error,
try this (it worked for me):

Set CVBATButton = doc.getElementsByClassName("ui-button ui-widget ui-state-
default ui-corner-all ui-button-text-only")
  For Each btn In CVBATButton
     btn.Click
     Exit For
  Next


问:
Search product data not working in codeigniter
I tried to make a search bar so users will be able to search products by searching on the product name but its not working and I'm not able to search a product.

This is my controller function:

```<code><?php
class SearchController extends CI_Controller {
  function __construct(){
     parent::__construct();
     $this->load->model('Search_model');
  }

  public function index(){
     $data = array();
  }

  function search_keyword(){
    $keyword = $this->input->post('keyword');
    $data['results'] = $this->Search_model->search($keyword);
    //laad de view
    $this->load->view('result_view',$data);
  }
}
?>
</code>```

This is my model function:

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search_model extends CI_Model  {
    function __construct(){
        parent::__construct();
    }

    function search($keyword) {
        $this->db->select('product_naam');
        $this->db->like('product_naam',$keyword);
        $query  =   $this->db->get('products');
        return $query->result_array();
    }
}
?>
</code>```

And this is my view file with searchbar:

```<code><?php include_once('templates/header.php');  ?>
  <center>
    <h2>Zoek een cadeau</h2><br>
      <form class="navbar-form" role="search" action="<?php echo base_url(); ?>SearchController/search_keyword" method="POST">
          <div class="input-group">
              <input type="text" class="form-control" placeholder="Search" name="keyword" size="30px; ">
              <div class="input-group-btn">
                  <button class="btn btn-default " type="submit" value = "Search"><i class="glyphicon glyphicon-search"></i></button>
              </div>
          </div>
      </form>
  </center>
    <div class="clearfix"></div>
  <table>
    <?php foreach($results as $row){ ?>
      <tr>
        <td><?php echo $row->product_naam?></td>
      </tr>
    <?php } ?>
  </table>
<?php include_once('templates/footer.php'); ?>
</code>```

I hope someone can help me with this problem!,
thanks

答:
I don't think like() will help you much with your particular needs. Your best bet, I guess, would be to bypass the problem and use a where function containing your LIKE clause:

```<code>$this->db->select('product_naam')->from('products')
$this->db->where("product_naam LIKE '%$keyword%'")->get();
</code>```

Or if you want pure ci you have to change your 'like' line :

```<code>$this->db->like('product_naam',$keyword);
</code>```

For %$query you can use

```<code>$this->db->like('product_naam',$keyword,'before');
</code>```

and for $query% you can use

```<code>$this->db->like('product_naam',$keyword,'after');
</code>```

Body:
I tried to make a search bar so users will be able to search products by searching on the product name but its not working and I'm not able to search a product.

This is my controller function:

<?php
class SearchController extends CI_Controller {
  function __construct(){
     parent::__construct();
     $this->load->model('Search_model');
  }

  public function index(){
     $data = array();
  }

  function search_keyword(){
    $keyword = $this->input->post('keyword');
    $data['results'] = $this->Search_model->search($keyword);
    //laad de view
    $this->load->view('result_view',$data);
  }
}
?>

This is my model function:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search_model extends CI_Model  {
    function __construct(){
        parent::__construct();
    }

    function search($keyword) {
        $this->db->select('product_naam');
        $this->db->like('product_naam',$keyword);
        $query  =   $this->db->get('products');
        return $query->result_array();
    }
}
?>

And this is my view file with searchbar:

<?php include_once('templates/header.php');  ?>

Zoek een cadeau

      <form class="navbar-form" role="search" action="<?php echo base_url(); ?>SearchController/search_keyword" method="POST">

              <input type="text" class="form-control" placeholder="Search" name="keyword" size="30px; ">

                  <button class="btn btn-default " type="submit" value = "Search"></button>

      </form>

    <?php foreach($results as $row){ ?>

        <?php echo $row->product_naam?>

    <?php } ?>

<?php include_once('templates/footer.php'); ?>

I hope someone can help me with this problem!,
thanks

Body:
I don't think like() will help you much with your particular needs. Your best bet, I guess, would be to bypass the problem and use a where function containing your LIKE clause:

$this->db->select('product_naam')->from('products')
$this->db->where("product_naam LIKE '%$keyword%'")->get();

Or if you want pure ci you have to change your 'like' line :

$this->db->like('product_naam',$keyword);

For %$query you can use

$this->db->like('product_naam',$keyword,'before');

and for $query% you can use

$this->db->like('product_naam',$keyword,'after');


问:
How to do number keypad with done button in Swift 2.0?
I've tried lots of numeric keyboard with done button, it's not found a correct answer in SWIFT 2.0.</p>

答:
Without toolbar, I'd added the done button in the Return key place itself by the following steps,

Create a custom Return button as below

```<code>let mobilePadNextButton = UIButton(type: UIButtonType.custom)
</code>```

In viewdidload, design it. Here I'm designing Next button as I need Next instead of Done.

```<code>mobilePadNextButton.setTitle("Next", for: UIControlState())//Set Done here
mobilePadNextButton.setTitleColor(UIColor.black, for: UIControlState())
mobilePadNextButton.frame = CGRect(x: 0, y: 163, width: 106, height: 53)
mobilePadNextButton.adjustsImageWhenHighlighted = false
mobilePadNextButton.addTarget(self, action: #selector(self.mobilePadNextAction(_:)), for: UIControlEvents.touchUpInside)
</code>```

Add Keyboad notification

```<code>func textFieldDidBeginEditing(_ textField: UITextField) {
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

func keyboardWillShow(notification:NSNotification){

    if mobileNoTxtFld.isFirstResponder
    {
        DispatchQueue.main.async { () -> Void in
            self.mobilePadNextButton.isHidden = false
            let keyBoardWindow = UIApplication.shared.windows.last
            self.mobilePadNextButton.frame = CGRect(x: 0, y: (keyBoardWindow?.frame.size.height)!-53, width: 106, height: 53)
            keyBoardWindow?.addSubview(self.mobilePadNextButton)
            keyBoardWindow?.bringSubview(toFront: self.mobilePadNextButton)

            UIView.animate(withDuration: (((notification.userInfo! as NSDictionary).object(forKey: UIKeyboardAnimationCurveUserInfoKey) as AnyObject).doubleValue)!, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
                self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 0)
            }, completion: { (complete) -> Void in
                print("Complete")
            })
        }
    }
    else
    {
        self.mobilePadNextButton.isHidden = true
    }

}
</code>```

Here, you can do the done actions

```<code>func mobilePadNextAction(_ sender : UIButton){

    //Click action

}
</code>```

The UI will looks like below,

I referred this Git Code

Body:
Without toolbar, I'd added the done button in the Return key place itself by the following steps,

Create a custom Return button as below

let mobilePadNextButton = UIButton(type: UIButtonType.custom)

In viewdidload, design it. Here I'm designing Next button as I need Next instead of Done.

mobilePadNextButton.setTitle("Next", for: UIControlState())//Set Done here
mobilePadNextButton.setTitleColor(UIColor.black, for: UIControlState())
mobilePadNextButton.frame = CGRect(x: 0, y: 163, width: 106, height: 53)
mobilePadNextButton.adjustsImageWhenHighlighted = false
mobilePadNextButton.addTarget(self, action: #selector(self.mobilePadNextAction(_:)), for: UIControlEvents.touchUpInside)

Add Keyboad notification

func textFieldDidBeginEditing(_ textField: UITextField) {
    NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}

func keyboardWillShow(notification:NSNotification){

    if mobileNoTxtFld.isFirstResponder
    {
        DispatchQueue.main.async { () -> Void in
            self.mobilePadNextButton.isHidden = false
            let keyBoardWindow = UIApplication.shared.windows.last
            self.mobilePadNextButton.frame = CGRect(x: 0, y: (keyBoardWindow?.frame.size.height)!-53, width: 106, height: 53)
            keyBoardWindow?.addSubview(self.mobilePadNextButton)
            keyBoardWindow?.bringSubview(toFront: self.mobilePadNextButton)

            UIView.animate(withDuration: (((notification.userInfo! as NSDictionary).object(forKey: UIKeyboardAnimationCurveUserInfoKey) as AnyObject).doubleValue)!, delay: 0, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
                self.view.frame = self.view.frame.offsetBy(dx: 0, dy: 0)
            }, completion: { (complete) -> Void in
                print("Complete")
            })
        }
    }
    else
    {
        self.mobilePadNextButton.isHidden = true
    }

}

Here, you can do the done actions

func mobilePadNextAction(_ sender : UIButton){

    //Click action

}

The UI will looks like below,

I referred this Git Code


问:
environmentVariables() not working for Jenkins Job DSL and Pipeline Jobs
We use Jenkins Job DSL for our CI setup. Since we are using a special command only available in the traditional Jenkinsfile syntax, we need to use a pipeline job.

Inside of the pipeline job we check out our project from Git. We are using the pipeline job for multiple projects, so we want to inject the git url into the pipeline script.

This is a short version of our script generating the pipeline job:

```<code>def createPipelineJob(def jobName, def gitUrl) {
    pipelineJob(jobName) {
        environmentVariables(GIT_URL: gitUrl)
        definition {
            cps {
                script('''
                    node {
                        sh 'env | sort'
                    }
                ''')
                sandbox(true)
            }
        }
    }
}
</code>```

This creates the following XML config:

```<code><flow-definition>
    <actions/>
    <description/>
    <keepDependencies>false</keepDependencies>
    <properties>
        <EnvInjectJobProperty>
            <info>
                <propertiesContent>GIT_URL=my-git.url</propertiesContent>
                <loadFilesFromMaster>false</loadFilesFromMaster>
            </info>
            <on>true</on>
            <keepJenkinsSystemVariables>true</keepJenkinsSystemVariables>
            <keepBuildVariables>true</keepBuildVariables>
            <overrideBuildParameters>false</overrideBuildParameters>
            <contributors/>
        </EnvInjectJobProperty>
    </properties>
    <triggers/>
    <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition">
        <script>
            node { sh 'env | sort' }
        </script>
        <sandbox>true</sandbox>
    </definition>
</flow-definition>
</code>```

But if i run this, the GIT_URL environment variable is not listed (other environment variables are). But if i instead create the pipeline job manually with this setup, the GIT_URL environment variable is printed just fine. Creating the job manually pretty much creates the same xml configuration:

```<code><flow-definition plugin="workflow-job@2.15">
    <actions>
        <io.jenkins.blueocean.service.embedded.BlueOceanUrlAction plugin="blueocean-rest-impl@1.3.1">
            <blueOceanUrlObject class="io.jenkins.blueocean.service.embedded.BlueOceanUrlObjectImpl">
                <mappedUrl>blue/organizations/jenkins/test-jobname</mappedUrl>
                <modelObject class="flow-definition" reference="../../../.."/>
            </blueOceanUrlObject>
        </io.jenkins.blueocean.service.embedded.BlueOceanUrlAction>
    </actions>
    <description/>
    <keepDependencies>false</keepDependencies>
    <properties>
        <com.sonyericsson.rebuild.RebuildSettings plugin="rebuild@1.27">
            <autoRebuild>false</autoRebuild>
            <rebuildDisabled>false</rebuildDisabled>
        </com.sonyericsson.rebuild.RebuildSettings>
        <EnvInjectJobProperty plugin="envinject@2.1.5">
            <info>
                <propertiesContent>GIT_URL=my-git.url</propertiesContent>
                <secureGroovyScript plugin="script-security@1.35">
                <script/>
                <sandbox>false</sandbox>
            </secureGroovyScript>
            <loadFilesFromMaster>false</loadFilesFromMaster>
        </info>
        <on>true</on>
        <keepJenkinsSystemVariables>true</keepJenkinsSystemVariables>
        <keepBuildVariables>true</keepBuildVariables>
        <overrideBuildParameters>false</overrideBuildParameters>
    </EnvInjectJobProperty>
        <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
            <triggers/>
        </org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
    </properties>
    <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps@2.41">
        <script>
            node { sh 'env | sort' }
        </script>
        <sandbox>true</sandbox>
    </definition>
    <triggers/>
    <disabled>false</disabled>
</flow-definition>
</code>```

We are pretty lost because we are new to jenkins and this problem is holding us for days now.

Edit:

The job is generated on the jenkins master node but executed on a slave node

Jenkins 2.37.3

Environment Injector Plugin 2.1.5

Pipeline 2.5

答: As it turns out the Environment Injector Plugin was not installed successfully, therefore the script did not run properly. So all i had to do was to restart Jenkins and everything worked just fine. Special thanks to Javier Garcés ensuring me that my script was indeed correct.</p>

Body:
We use Jenkins Job DSL for our CI setup. Since we are using a special command only available in the traditional Jenkinsfile syntax, we need to use a pipeline job.

Inside of the pipeline job we check out our project from Git. We are using the pipeline job for multiple projects, so we want to inject the git url into the pipeline script.

This is a short version of our script generating the pipeline job:

def createPipelineJob(def jobName, def gitUrl) {
    pipelineJob(jobName) {
        environmentVariables(GIT_URL: gitUrl)
        definition {
            cps {
                script('''
                    node {
                        sh 'env | sort'
                    }
                ''')
                sandbox(true)
            }
        }
    }
}

This creates the following XML config:

<flow-definition>
    <actions/>
    <description/>
    <keepDependencies>false</keepDependencies>
    <properties>
        <EnvInjectJobProperty>
            <info>
                <propertiesContent>GIT_URL=my-git.url</propertiesContent>
                <loadFilesFromMaster>false</loadFilesFromMaster>
            </info>
            <on>true</on>
            <keepJenkinsSystemVariables>true</keepJenkinsSystemVariables>
            <keepBuildVariables>true</keepBuildVariables>
            <overrideBuildParameters>false</overrideBuildParameters>
            <contributors/>
        </EnvInjectJobProperty>
    </properties>
    <triggers/>
    <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition">

        <sandbox>true</sandbox>
    </definition>
</flow-definition>

But if i run this, the GIT_URL environment variable is not listed (other environment variables are). But if i instead create the pipeline job manually with this setup, the GIT_URL environment variable is printed just fine. Creating the job manually pretty much creates the same xml configuration:

<flow-definition plugin="workflow-job@2.15">
    <actions>
        <io.jenkins.blueocean.service.embedded.BlueOceanUrlAction plugin="blueocean-rest-impl@1.3.1">
            <blueOceanUrlObject class="io.jenkins.blueocean.service.embedded.BlueOceanUrlObjectImpl">
                <mappedUrl>blue/organizations/jenkins/test-jobname</mappedUrl>
                <modelObject class="flow-definition" reference="../../../.."/>
            </blueOceanUrlObject>
        </io.jenkins.blueocean.service.embedded.BlueOceanUrlAction>
    </actions>
    <description/>
    <keepDependencies>false</keepDependencies>
    <properties>
        <com.sonyericsson.rebuild.RebuildSettings plugin="rebuild@1.27">
            <autoRebuild>false</autoRebuild>
            <rebuildDisabled>false</rebuildDisabled>
        </com.sonyericsson.rebuild.RebuildSettings>
        <EnvInjectJobProperty plugin="envinject@2.1.5">
            <info>
                <propertiesContent>GIT_URL=my-git.url</propertiesContent>
                <secureGroovyScript plugin="script-security@1.35">

        <sandbox>true</sandbox>
    </definition>
    <triggers/>
    <disabled>false</disabled>
</flow-definition>

We are pretty lost because we are new to jenkins and this problem is holding us for days now.

Edit:

The job is generated on the jenkins master node but executed on a slave node

Jenkins 2.37.3

Environment Injector Plugin 2.1.5

Pipeline 2.5


问:
HTTP 401 Error while posting XML to REST
I am trying to post a XML to REST Service. Here's the code I am using:

I am getting following error, while calling the service.

The remote server returned an error: (401) Unauthorized.

I have also tried setting NetworkCredentials directly i.e.

```<code>NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;
</code>```

Thanks for your help.

```<code>Uri address = new Uri("https://localhost:30000/restservice/");

// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";

string data = @"<Sample XML Here>";

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

// Set the content length in the request headers
request.ContentLength = byteData.Length;

// Write data
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}

string usernamePassword = username + ":" + password;

CredentialCache mycache = new CredentialCache();

mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;

// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Console application output
    Response.Write(reader.ReadToEnd());
}
</code>```

答:
Couple of things to try:

Change the content type as you're not posting json to it

Not encode the data as its expecting xml, not a binary stream

Hope this helps.

Body:
I am trying to post a XML to REST Service. Here's the code I am using:

I am getting following error, while calling the service.

The remote server returned an error: (401) Unauthorized.

I have also tried setting NetworkCredentials directly i.e.

NetworkCredential nc = new NetworkCredential(username, password);
serviceRequest.Credentials = nc;

Thanks for your help.

Uri address = new Uri("https://localhost:30000/restservice/");

// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";

string data = @"<Sample XML Here>";

// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

// Set the content length in the request headers
request.ContentLength = byteData.Length;

// Write data
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}

string usernamePassword = username + ":" + password;

CredentialCache mycache = new CredentialCache();

mycache.Add(address, "Basic", new NetworkCredential(username, password));
request.Credentials = mycache;

// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Console application output
    Response.Write(reader.ReadToEnd());
}


问:
tkinter: callback not returning the value?
My function is not returning any value which i entered into entry-box on button click:</p>

```<code>from tkinter import *
import os

def onclick2():
    val = box.get()
    return(val)
root = Tk()
box = Entry(root)
box.pack()
buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black', 9), bd=10, width=20,command=onclick2)
buttonfortxtbox.pack(anchor = S)
print(onclick2())
root.mainloop()
</code>```

答:
You are trying to print the content of your entry widget but you are using the variable for your entry to receive the content which is wrong. Also call print the content in your entry widget  to the your terminal . </p>

```<code> from tkinter import *

def onclick2():
    val = boss.get()
    print(val)

root = Tk()

boss = StringVar() # to receive the content in the entry

box = Entry(root , textvariable=boss)
box.pack()

buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black',
9), bd=10, width=20,command=onclick2)
buttonfortxtbox.pack(anchor = S)

    #print(onclick2()) # don't need to call this

root.mainloop()
</code>```

Body:
My function is not returning any value which i entered into entry-box on button click:

from tkinter import *
import os

def onclick2():
    val = box.get()
    return(val)
root = Tk()
box = Entry(root)
box.pack()
buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black', 9), bd=10, width=20,command=onclick2)
buttonfortxtbox.pack(anchor = S)
print(onclick2())
root.mainloop()

Body:
You are trying to print the content of your entry widget but you are using the variable for your entry to receive the content which is wrong. Also call print the content in your entry widget  to the your terminal .

 from tkinter import *

def onclick2():
    val = boss.get()
    print(val)

root = Tk()

boss = StringVar() # to receive the content in the entry

box = Entry(root , textvariable=boss)
box.pack()

buttonfortxtbox = Button(root, text="Check Result", font=('Cooper Black',
9), bd=10, width=20,command=onclick2)
buttonfortxtbox.pack(anchor = S)

    #print(onclick2()) # don't need to call this

root.mainloop()


问:
Angular data communication to and from components
I have a parent component (P1) and two child components(C1 and C2).
Both the child components have a primeng data-table which are editable.
I have two buttons on P1 : fetch() and save().
fetch() calls the database to get the data.
I'm using a shared service to fetch data and pass it down to the components using BehaviorSubject.
My data object looks like:

```<code>export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]}
export interface Child1 { weight: number;}
export interface Child2 { code: string;}
</code>```

Child components subscribe to the data from the shared service.
Now the issue is that the Child components also modify the data which they have.
So on click of save() on the P1, I am unable to get the latest modified values from the child components as I do not have any way of notifying P1 that C1 and/or C2 has changed the data.

Is there a way to accomplish the same so that I could notify the child components when the save() is called and it reflects in the ParentObj?.

答:
I was able to solve it using the ViewChild from '@angular/core' as there was no event trigger on the child components.
The parent can read the child attributes using the @ViewChild(ChildComponent) child;
Reference: Here

Body:
I have a parent component (P1) and two child components(C1 and C2).
Both the child components have a primeng data-table which are editable.
I have two buttons on P1 : fetch() and save().
fetch() calls the database to get the data.
I'm using a shared service to fetch data and pass it down to the components using BehaviorSubject.
My data object looks like:

export interface ParentObj { name: string; child1 : Child1[]; child2: Child2[]}
export interface Child1 { weight: number;}
export interface Child2 { code: string;}

Child components subscribe to the data from the shared service.
Now the issue is that the Child components also modify the data which they have.
So on click of save() on the P1, I am unable to get the latest modified values from the child components as I do not have any way of notifying P1 that C1 and/or C2 has changed the data.

Is there a way to accomplish the same so that I could notify the child components when the save() is called and it reflects in the ParentObj?.


问:
fopen fails invisibly when creating files in system drive (C:\)
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file.  My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not?  The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

```<code>FILE *FileHandle;
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else
{
    //write to file
    //close file
}
</code>```

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization.  Does anyone know how to disable this feature?

答: This might have to do with the virtual store.  Take a look here for some info.</p>

Body:
Whenever I try to create a file using fopen, fopen acts as if the file has been opened properly and that it has full access to it, but it doesn't actually create the file.  My program doesn't have write access to the system root folder because it needs admin access to write there, but why isn't fopen() giving any errors?

Any idea how to tell if there's an error or not?  The file handle that gets returned when I'm trying to open the file in a protected directory is exactly the same as when I open a file in a directory where I have write access.

I've tried this with the various different versions of fopen (fopen, _wfopen, _wfopen_s) but they all have the same output.

Interestingly enough, GetLastError() returns ERROR_ALREADY_EXISTS.

Here's the code that I'm using:

FILE *FileHandle;
DWORD error = _wfopen_s(&FileHandle, L"\\filename.txt", L"a");
Win32Error = GetLastError();

if (error != 0 || FileHandle == NULL)
{
    //Throw error
}
else
{
    //write to file
    //close file
}

EDIT: As rerun pointed out, the file is getting created in %APPDATA% because of virtualization.  Does anyone know how to disable this feature?


问:
setheader gives error: "throw new Error('Can\'t set headers after they are sent.');"
Getting this error while checking whether the user already voted or not. I suggest setheader thing is responsible.

CODE

```<code>index : function(req, res, next){
    if(req.method == "POST"){
        var aa =  Users.findOneByEmail(req.param('email'), function(err, data, next){
            if(err) res.serverError(err);
            console.log(data);
            if(data){
                res.redirect('/users');
                return;
            }
        });

        var data = {
            remoteip:  req.ip,
            challenge: req.body.recaptcha_challenge_field,
            response:  req.body.recaptcha_response_field
        };

        // console.log(data);
        var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY,  data);
        recaptcha.verify(function(success, error_code) {
            if(!success){
                return res.serverError(error_code)
            } else {
                var username =  req.param('username');
                var vote =  req.param('vote');
                var email = req.param('email');
                var reason =  req.param('reason');
                console.log('I am here 2');
                Users.create({
                    username: req.param('username'),
                    email: email,
                    candidate_id : vote,
                    reason : reason
                }).done(function(err, data){
                    if(err){
                        return res.serverError(JSON.stringify(err));
                    } else {
                        return res.send('You sucessfully voted');
                    }
                });
            }

            res.redirect('/candidates/');
        });
    } else {
        var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY);
        Candidates.find().done(function(err, data){
            res.view({candidates : data, recaptcha_form: recaptcha.toHTML()});
        });
    }
},
</code>```

The error:

```<code>http.js:691
    throw new Error('Can\'t set headers after they are sent.');
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
    at ServerResponse.res.setHeader (/usr/local/lib/node_modules/sails/node_modules/express/node_modules/connect/lib/patch.js:59:22)
    at ServerResponse.res.set.res.header (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:522:10)
    at ServerResponse.res.location (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:656:8)
    at ServerResponse.res.redirect (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:698:8)
    at /Users/korotane/Documents/node_projects/the_next_indian_pm/api/controllers/UsersController.js:75:14
    at IncomingMessage.<anonymous> (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/recaptcha/lib/recaptcha.js:160:20)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickDomainCallback (node.js:459:13)
</code>```

答:
In a complex code whenever you want to send a response at many occasion
you can put a check res.headersSent is false.

IE:if(res.headersSent){res.send()}

if you used "return" before wile sending response then the  code will not execute further.

Body:
Getting this error while checking whether the user already voted or not. I suggest setheader thing is responsible.

CODE

index : function(req, res, next){
    if(req.method == "POST"){
        var aa =  Users.findOneByEmail(req.param('email'), function(err, data, next){
            if(err) res.serverError(err);
            console.log(data);
            if(data){
                res.redirect('/users');
                return;
            }
        });

        var data = {
            remoteip:  req.ip,
            challenge: req.body.recaptcha_challenge_field,
            response:  req.body.recaptcha_response_field
        };

        // console.log(data);
        var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY,  data);
        recaptcha.verify(function(success, error_code) {
            if(!success){
                return res.serverError(error_code)
            } else {
                var username =  req.param('username');
                var vote =  req.param('vote');
                var email = req.param('email');
                var reason =  req.param('reason');
                console.log('I am here 2');
                Users.create({
                    username: req.param('username'),
                    email: email,
                    candidate_id : vote,
                    reason : reason
                }).done(function(err, data){
                    if(err){
                        return res.serverError(JSON.stringify(err));
                    } else {
                        return res.send('You sucessfully voted');
                    }
                });
            }

            res.redirect('/candidates/');
        });
    } else {
        var recaptcha = new Recaptcha(PUBLIC_KEY, PRIVATE_KEY);
        Candidates.find().done(function(err, data){
            res.view({candidates : data, recaptcha_form: recaptcha.toHTML()});
        });
    }
},

The error:

http.js:691
    throw new Error('Can\'t set headers after they are sent.');
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:691:11)
    at ServerResponse.res.setHeader (/usr/local/lib/node_modules/sails/node_modules/express/node_modules/connect/lib/patch.js:59:22)
    at ServerResponse.res.set.res.header (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:522:10)
    at ServerResponse.res.location (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:656:8)
    at ServerResponse.res.redirect (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/sails/node_modules/express/lib/response.js:698:8)
    at /Users/korotane/Documents/node_projects/the_next_indian_pm/api/controllers/UsersController.js:75:14
    at IncomingMessage.<anonymous> (/Users/korotane/Documents/node_projects/the_next_indian_pm/node_modules/recaptcha/lib/recaptcha.js:160:20)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickDomainCallback (node.js:459:13)


问:
Where to place the BackgroundWorker
I have a class that gathers information about a machine (this is an example - in total GetInfo() may take minutes to run):

```<code>public class Scanner
{
    public void GetInfo()
    {
        this.Name = GetName();
        this.OS = GetOS();
    }

    public string Name { get; set; }
    public string OS { get; set; }
    public string Status { get; set; }

    private string GetName() { this.Status = "Getting computer name"; /*More operations*/ }
    private string GetOS() { this.Status = "Getting OS"; /*More operations*/ }
}
</code>```

This is called by a form that needs to provide status feedback to the user.

```<code>TextBox1.Text = scanner.Status;
</code>```

My question is, to achieve this, what is the best way to implement threading so that the application remains responsive?

I have got a BackgroundWorker running in the form and calling GetName(), GetOS() etc itself and that works fine, but the code isn't very repeatable - to keep maintenance low I want to keep a GetInfo() method in the class so if I need to run a scan from elsewhere theres only one piece of code that knows about how to.

I could move the BackgroundWorker in to GetInfo(), but then how would the form be able to check the Status property without doing a loop and locking up the UI?

Maybe have a BackgroundWorker in the form run GetInfo() and then run another Worker that would check Status and update the form if a change is detected?

This is my first proper go at Threading and can't get my head around what, I think, is a fairly common task so any help would be appreciated.

Note: I'm also well open to suggestions for other ways to implement the Status property - hopefully you get what I'm trying to achieve.

/edit: Some clarification.

Scanner.GetInfo() would be called manually, for example on a form button click. GetInfo() would then start populating the objects properties as it goes gathering information, and might take 5 minutes to complete.

I need to be able to keep the user up to date on its status, and the only way I can think of that happening (with my current knowledge) is for GetInfo() to update a 'Scanner.Status' property, which the form can then check at interval/within a loop and update the UI when it changes.

答:
How about using INotifyPropertyChanged with a thread in the class as follows:

```<code>public class Scanner : INotifyPropertyChanged
{
  private string _Name, _OS;
  public event PropertyChangedEventHandler PropertyChanged;

  public string Name
  {
    get
    {
      return _Name;
    }
    set
    {
      if (value != _Name)
      {
        _Name = value;
        NotifyPropertyChanged("Name");
      }
    }
  }

  public string OS
  {
    get
    {
      return _OS;
    }
    set
    {
      if (value != _OS)
      {
        _OS = value;
        NotifyPropertyChanged("OS");
      }
    }
  }

  public void GetInfo()
  {
    _Name = string.Empty;
    _OS = string.Empty;

    new Thread(() => this.Name = GetName()).Start();
    new Thread(() => this.OS = GetOS()).Start();
  }

  private void NotifyPropertyChanged(string pName)
  {
    if (PropertyChanged != null)
    {
      PropertyChanged(this, new PropertyChangedEventArgs(pName));
    }
  }

  private string GetName()
  {
    return "long name operation here";
  }

  private string GetOS()
  {
    return "long OS operation here";
  }
}
</code>```

Then in your form you could use the following:

```<code>Scanner m_Scanner = new Scanner();

public void Main()
{
  m_Scanner.PropertyChanged += UpdateGUI;
  m_Scanner.GetInfo();
}

private void UpdateGUI(object sender, PropertyChangedEventArgs e)
{
  if (e.PropertyName == "OS")
    txtOs.Text = m_Scanner.OS;
  else if (e.PropertyName == "Name")
    txtName.Text = m_Scanner.Name;
}
</code>```

Title: Where to place the BackgroundWorker

Body:
I have a class that gathers information about a machine (this is an example - in total GetInfo() may take minutes to run):

public class Scanner
{
    public void GetInfo()
    {
        this.Name = GetName();
        this.OS = GetOS();
    }

    public string Name { get; set; }
    public string OS { get; set; }
    public string Status { get; set; }

    private string GetName() { this.Status = "Getting computer name"; /*More operations*/ }
    private string GetOS() { this.Status = "Getting OS"; /*More operations*/ }
}

This is called by a form that needs to provide status feedback to the user.

TextBox1.Text = scanner.Status;

My question is, to achieve this, what is the best way to implement threading so that the application remains responsive?

I have got a BackgroundWorker running in the form and calling GetName(), GetOS() etc itself and that works fine, but the code isn't very repeatable - to keep maintenance low I want to keep a GetInfo() method in the class so if I need to run a scan from elsewhere theres only one piece of code that knows about how to.

I could move the BackgroundWorker in to GetInfo(), but then how would the form be able to check the Status property without doing a loop and locking up the UI?

Maybe have a BackgroundWorker in the form run GetInfo() and then run another Worker that would check Status and update the form if a change is detected?

This is my first proper go at Threading and can't get my head around what, I think, is a fairly common task so any help would be appreciated.

Note: I'm also well open to suggestions for other ways to implement the Status property - hopefully you get what I'm trying to achieve.

/edit: Some clarification.

Scanner.GetInfo() would be called manually, for example on a form button click. GetInfo() would then start populating the objects properties as it goes gathering information, and might take 5 minutes to complete.

I need to be able to keep the user up to date on its status, and the only way I can think of that happening (with my current knowledge) is for GetInfo() to update a 'Scanner.Status' property, which the form can then check at interval/within a loop and update the UI when it changes.

Body:
How about using INotifyPropertyChanged with a thread in the class as follows:

public class Scanner : INotifyPropertyChanged
{
  private string _Name, _OS;
  public event PropertyChangedEventHandler PropertyChanged;

  public string Name
  {
    get
    {
      return _Name;
    }
    set
    {
      if (value != _Name)
      {
        _Name = value;
        NotifyPropertyChanged("Name");
      }
    }
  }

  public string OS
  {
    get
    {
      return _OS;
    }
    set
    {
      if (value != _OS)
      {
        _OS = value;
        NotifyPropertyChanged("OS");
      }
    }
  }

  public void GetInfo()
  {
    _Name = string.Empty;
    _OS = string.Empty;

    new Thread(() => this.Name = GetName()).Start();
    new Thread(() => this.OS = GetOS()).Start();
  }

  private void NotifyPropertyChanged(string pName)
  {
    if (PropertyChanged != null)
    {
      PropertyChanged(this, new PropertyChangedEventArgs(pName));
    }
  }

  private string GetName()
  {
    return "long name operation here";
  }

  private string GetOS()
  {
    return "long OS operation here";
  }
}

Then in your form you could use the following:

Scanner m_Scanner = new Scanner();

public void Main()
{
  m_Scanner.PropertyChanged += UpdateGUI;
  m_Scanner.GetInfo();
}

private void UpdateGUI(object sender, PropertyChangedEventArgs e)
{
  if (e.PropertyName == "OS")
    txtOs.Text = m_Scanner.OS;
  else if (e.PropertyName == "Name")
    txtName.Text = m_Scanner.Name;
}


问:
Invalid Token. while verifying email verification code using UserManager.ConfirmEmailAsync(user.Id, code)
I have recently migrated Asp.net identity 1.0 to 2.0 . I am trying to verify email verification code using below method. But i am getting "Invalid Token" error message.

```<code>public async Task<HttpResponseMessage> ConfirmEmail(string userName, string code)
        {
            ApplicationUser user = UserManager.FindByName(userName);
            var result = await UserManager.ConfirmEmailAsync(user.Id, code);
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }
</code>```

Generating Email verification token using below code (And if i call ConfirmEmailAsyc immediate after generating token, which is working fine). But when i am calling using different method which is giving error

```<code>public async Task<HttpResponseMessage> GetEmailConfirmationCode(string userName)
        {
            ApplicationUser user = UserManager.FindByName(userName);
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            //var result = await UserManager.ConfirmEmailAsync(user.Id, code);
            return Request.CreateResponse(HttpStatusCode.OK, code);
        }
</code>```

Please help

答:
We had the same issue, Load balancing was causing this problem. Adding a <machineKey validationKey="XXX" decryptionKey="XXX" validation="SHA1" decryption="AES"/> in web.config file solved the problem. All your servers need to have the same machine key to verify previously generated code.

Hope this helps.

Body:
I have recently migrated Asp.net identity 1.0 to 2.0 . I am trying to verify email verification code using below method. But i am getting "Invalid Token" error message.

public async Task<HttpResponseMessage> ConfirmEmail(string userName, string code)
        {
            ApplicationUser user = UserManager.FindByName(userName);
            var result = await UserManager.ConfirmEmailAsync(user.Id, code);
            return Request.CreateResponse(HttpStatusCode.OK, result);
        }

Generating Email verification token using below code (And if i call ConfirmEmailAsyc immediate after generating token, which is working fine). But when i am calling using different method which is giving error

public async Task<HttpResponseMessage> GetEmailConfirmationCode(string userName)
        {
            ApplicationUser user = UserManager.FindByName(userName);
            var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            //var result = await UserManager.ConfirmEmailAsync(user.Id, code);
            return Request.CreateResponse(HttpStatusCode.OK, code);
        }

Please help


问:
Targeting older macOS versions using Swift 4
What is the earliest macOS version that an app developed using Swift 4 (Xcode 9) will work on?</p>

答:
Depends what you're asking. You might be able to run Swift 4 itself (that is, the toolchain) on older macOS versions for non-Xcode development.

If you're asking what's the oldest deployment target, the oldest macOS that Swift-compiled apps will run on, the answer is here:

```<code> https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/index.html
</code>```

That is, Swift can deploy back to macOS 10.9.

If you're asking what's the oldest macOS to run Swift 4 within Xcode, you need Xcode 9, which needs to run on 10.12.4+, which forces you to SDK 10.13+.

Body:
Depends what you're asking. You might be able to run Swift 4 itself (that is, the toolchain) on older macOS versions for non-Xcode development.

If you're asking what's the oldest deployment target, the oldest macOS that Swift-compiled apps will run on, the answer is here:

 https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/index.html

That is, Swift can deploy back to macOS 10.9.

If you're asking what's the oldest macOS to run Swift 4 within Xcode, you need Xcode 9, which needs to run on 10.12.4+, which forces you to SDK 10.13+.


问:
How to routes to a specific controller with a variable value ahead of it in rails 5?
Normally its like:
resources :users
To keep a value ahead we can do like

```<code>scope :url do
   resources :users
end
</code>```

but, issue is that I have the just variable in front of the routes not a fixed value with few conditions for it.
Example in rails 2. and want to convert the routing accoding to rails5

```<code>map.with_options :controller => 'users' do |user|
  user.forgot_user ':url/users/forgot',   :action => 'forgot',  :url => /([a-zA-Z0-9\-]*)/
  user.user ':url/users/retrieve',   :action => 'retrieve',  :url => /([a-zA-Z0-9\-]*)/
  user.login       ':url/users/login',    :action => 'login',                                          :url => /([a-zA-Z0-9\-]*)/
  user.logout      ':url/users/logout',   :action => 'logout',                                         :url => /([a-zA-Z0-9\-]*)/
  user.new_user    ':url/users/new',      :action => 'new',     :conditions => { :method => :get },    :url => /([a-zA-Z0-9\-]*)/
  user.users       ':url/users/:id',      :action => 'show',   :conditions => { :method => :get },    :url => /([a-zA-Z0-9\-]*)/
end
</code>```

Thanks in advance.

答:
```<code>scope "/(:subdomain)", :defaults => {:subdomain => "default"} do
  ...
end
</code>```

use subdomain as a variable.

Body:
Normally its like:
resources :users
To keep a value ahead we can do like

scope :url do
   resources :users
end

but, issue is that I have the just variable in front of the routes not a fixed value with few conditions for it.
Example in rails 2. and want to convert the routing accoding to rails5

map.with_options :controller => 'users' do |user|
  user.forgot_user ':url/users/forgot',   :action => 'forgot',  :url => /([a-zA-Z0-9\-]*)/
  user.user ':url/users/retrieve',   :action => 'retrieve',  :url => /([a-zA-Z0-9\-]*)/
  user.login       ':url/users/login',    :action => 'login',                                          :url => /([a-zA-Z0-9\-]*)/
  user.logout      ':url/users/logout',   :action => 'logout',                                         :url => /([a-zA-Z0-9\-]*)/
  user.new_user    ':url/users/new',      :action => 'new',     :conditions => { :method => :get },    :url => /([a-zA-Z0-9\-]*)/
  user.users       ':url/users/:id',      :action => 'show',   :conditions => { :method => :get },    :url => /([a-zA-Z0-9\-]*)/
end

Thanks in advance.

Body:
scope "/(:subdomain)", :defaults => {:subdomain => "default"} do
  ...
end

use subdomain as a variable.


问:
Select current element from getElementsbyClassName
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
  <button onclick="myFunction()">Click</button>
</div>
<div class="myClass">
  <button onclick="myFunction()">Click</button>
</div></code>```

答:
In javascript you can simply do it using this and parentElement. Just pass the reference in button click and then use parentElement to hide it like this

function myFunction(obj) {
    obj.parentElement.style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
    <button onclick="myFunction(this)">Click</button>
</div>
<div class="myClass">
    <button onclick="myFunction(this)">Click</button>
</div></code>```

P.S You have to use style before using display for any element

Body:
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}

  <button onclick="myFunction()">Click</button>

  <button onclick="myFunction()">Click</button>

Body:
In javascript you can simply do it using this and parentElement. Just pass the reference in button click and then use parentElement to hide it like this

function myFunction(obj) {
    obj.parentElement.style.display = "none";
}

<div class="myClass">
    <button onclick="myFunction(this)">Click</button>
</div>
<div class="myClass">
    <button onclick="myFunction(this)">Click</button>
</div>

P.S You have to use style before using display for any element


问:
How to produce XML signature with no whitespaces and line-breaks in Java?
I work with the brazilian "Nota Fiscal Eletronica" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there are absolutely no whitespaces between tags, including signature tags (*).

We happen to use apache's XMLSignature and I can't seem to produce an unindented signature.

If I remove the whitespaces after signing, the signature gets broken.

I cannot change the canonicalizer / transformers set either, since they're predefined.

I couldn't find an option or parameter in the XMLSignature API to control indentation or whitespaces.

Below is the code:

```<code>    // the element where to insert the signature
    Element element = ...;
    X509Certificate cert = ...;
    PrivateKey privateKey = ...;

    XMLSignature signer =
            new XMLSignature(doc, "http://xml-security",
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    element.appendChild(signer.getElement());

    Transforms transforms = new Transforms(doc);

    // Define as regras de transformação e canonicalização do documento
    // XML, necessário para fazer a verificação do parsing e da
    // assinatura pelos destinatários
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //, xpath.getElementPlusReturns());

    transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); //,xpath.getElementPlusReturns());

    String id = "";

    id = ((Element) element.getElementsByTagName("infNFe").item(0)).getAttributeNode("Id").getNodeValue();

    signer.addDocument("#" + id, transforms,
                       Constants.ALGO_ID_DIGEST_SHA1);
    signer.addKeyInfo(cert);
    signer.sign(privateKey);
</code>```

And below is the resulting signature (snippet):

```<code><Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#NFe43110189716583000165550010000076011492273645">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>fas0ra5uRskQgRHSrIYhEjFEjKQ=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
2RGltUZy0HfNoiKtVanAeN+JUPyglWDuQNnMudSgA7kESoHBZ/q/GMbc+xMSN1eV8u7+2PxSKl1T
Zl592FWmCSAkL8pwMujDxJ4iTLU20Hf0dNF7oGcyB+g9GgbipW2udq0kwJLz6HzXUD/Evf/0y+3T
NtsXeIaA6A29ttD/UEs=
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
MIIFqTCCBJGgAwIBAgIEQeNSuzANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJicjETMBEGA1UE
ChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNhIEZlZGVyYWwxFDASBgNVBAMT
C0FDIENBSVhBIFBKMB4XDTEwMDYwODE5MjQwNVoXDTExMDYwODE5NTQwNVowgYQxCzAJBgNVBAYT
AmJyMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSAwHgYDVQQLExdDYWl4YSBFY29ub21pY2EgRmVkZXJh
bDEUMBIGA1UECxMLQUMgQ0FJWEEgUEoxKDAmBgNVBAMTH0EgQlVITEVSIFNBIENVUlRVTUU6NDA5
NDI0OTAwMTAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOFxgvG35RQWgXec4zVrzoUHolnJ
fP76rpO2Vo40593W9Gf0WwHt36gVmli0ZeQitFmzFSoE5KhgXQGZg6RpV3WJUFcIrPBHPdqOSfiB
988kf962P+j8fZ38BNmo7TV9H9hMBkV9bD/QOe73wFDc+rT6/9io++Z+7/wup/3glKntAgMBAAGj
ggLOMIICyjAOBgNVHQ8BAf8EBAMCBeAwVwYDVR0gBFAwTjBMBgZgTAECAQkwQjBABggrBgEFBQcC
ARY0aHR0cDovL2ljcC5jYWl4YS5nb3YuYnIvcmVwb3NpdG9yaW8vZHBjYWNjYWl4YXBqLnBkZjAp
BgNVHSUEIjAgBggrBgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcUAgIwgbYGA1UdEQSBrjCBq4EV
YnVobGVyQGFidWhsZXIuY29tLmJyoD4GBWBMAQMEoDUEMzE0MDkxOTQ2NDA5NDI0OTAwMTAxMDg0
NDcwODE3NTAwMDAwODAzMjkyMjM1NlNTUCBSU6AeBgVgTAEDAqAVBBNOQUlSIEJVSExFUiBTQ0hO
RUNLoBkGBWBMAQMDoBAEDjg5NzE2NTgzMDAwMTY1oBcGBWBMAQMHoA4EDDAwMDAwMDAwMDAwMDCC
ATIGA1UdHwSCASkwggElMIGuoIGroIGohjJodHRwOi8vaWNwLmNhaXhhLmdvdi5ici9yZXBvc2l0
b3Jpby9BQ0NBSVhBUEoxLmNybIY0aHR0cDovL2ljcDIuY2FpeGEuZ292LmJyL3JlcG9zaXRvcmlv
Mi9BQ0NBSVhBUEoxLmNybIY8aHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNy
L2NhaXhhL0FDQ0FJWEFQSjEuY3JsMHKgcKBupGwwajELMAkGA1UEBhMCYnIxEzARBgNVBAoTCklD
UC1CcmFzaWwxIDAeBgNVBAsTF0NhaXhhIEVjb25vbWljYSBGZWRlcmFsMRQwEgYDVQQDEwtBQyBD
QUlYQSBQSjEOMAwGA1UEAxMFQ1JMNDEwHwYDVR0jBBgwFoAUjkAvCv4T1ao5oHZ0htO8fcfx5c8w
CQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDqDANBgkqhkiG9w0BAQUFAAOCAQEA
nZHUvdnZsiCIDjKm1zHehbtuDtDJha4O4FZ03J74Y+AxyAFs/4JED+xUvZ5jFuEsdqgA0V/dxUFy
Uz/ca10Ievd578GQdGwYl1GFhRtO/SlxeaOEf7eDdGOWXO3VmUA3NmNo0X8RRTIoifnhpDXu7RbN
5sijyH/uXyRFWX9XH2N0U/r3oJtNKXsvoUlbDrkalgkuLzLKsaEj0TkwisXO3cmMoWGuBpAZC+46
e4x/2vTqOvYkzZO+O9NLi0YWSYY7OJKiKBjMC6MzdlPM9VTkIwO9WvWEMdbU0/jhO2cMcVMzNZc1
r6ZmdTDrwqV3elSTkQtJ0RIZNgMJUn+Y8c7Aog==
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>
</code>```

Notice the (unwanted) line-breaks.

Any help would be greatly appreciated.

Thanks a lot in advance.

(*) Clarification: the new rule forbids whitespaces (or any other text) between element-only tags. As an example, this would be allowed:

```<code><a><b>
  text
  inside
  tag
</b></a>
</code>```

while this would be forbidden:

```<code><a>
<b>text</b>
</a>
</code>```

because on the latter case, the whitespaces (line-breaks) are between two tags, or, in other words, placed inside an element-only tag.

答:
Fortunately XMLSignature is opensource, so I guess you'll have to get the source code and hack it your self.

Probably your solution will help others in the future so, create a patch and send it back to the project.

Good luck!

:) :)

Body:
I work with the brazilian "Nota Fiscal Eletronica" project, in which they define a standart way to sign XML documents.

Recently, they started to require that there are absolutely no whitespaces between tags, including signature tags (*).

We happen to use apache's XMLSignature and I can't seem to produce an unindented signature.

If I remove the whitespaces after signing, the signature gets broken.

I cannot change the canonicalizer / transformers set either, since they're predefined.

I couldn't find an option or parameter in the XMLSignature API to control indentation or whitespaces.

Below is the code:

    // the element where to insert the signature
    Element element = ...;
    X509Certificate cert = ...;
    PrivateKey privateKey = ...;

    XMLSignature signer =
            new XMLSignature(doc, "http://xml-security",
            XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1);

    element.appendChild(signer.getElement());

    Transforms transforms = new Transforms(doc);

    // Define as regras de transformação e canonicalização do documento
    // XML, necessário para fazer a verificação do parsing e da
    // assinatura pelos destinatários
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); //, xpath.getElementPlusReturns());

    transforms.addTransform(Transforms.TRANSFORM_C14N_OMIT_COMMENTS); //,xpath.getElementPlusReturns());

    String id = "";

    id = ((Element) element.getElementsByTagName("infNFe").item(0)).getAttributeNode("Id").getNodeValue();

    signer.addDocument("#" + id, transforms,
                       Constants.ALGO_ID_DIGEST_SHA1);
    signer.addKeyInfo(cert);
    signer.sign(privateKey);

And below is the resulting signature (snippet):

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#NFe43110189716583000165550010000076011492273645">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>fas0ra5uRskQgRHSrIYhEjFEjKQ=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>
2RGltUZy0HfNoiKtVanAeN+JUPyglWDuQNnMudSgA7kESoHBZ/q/GMbc+xMSN1eV8u7+2PxSKl1T
Zl592FWmCSAkL8pwMujDxJ4iTLU20Hf0dNF7oGcyB+g9GgbipW2udq0kwJLz6HzXUD/Evf/0y+3T
NtsXeIaA6A29ttD/UEs=
</SignatureValue>
<KeyInfo>
<X509Data>
<X509Certificate>
MIIFqTCCBJGgAwIBAgIEQeNSuzANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJicjETMBEGA1UE
ChMKSUNQLUJyYXNpbDEgMB4GA1UECxMXQ2FpeGEgRWNvbm9taWNhIEZlZGVyYWwxFDASBgNVBAMT
C0FDIENBSVhBIFBKMB4XDTEwMDYwODE5MjQwNVoXDTExMDYwODE5NTQwNVowgYQxCzAJBgNVBAYT
AmJyMRMwEQYDVQQKEwpJQ1AtQnJhc2lsMSAwHgYDVQQLExdDYWl4YSBFY29ub21pY2EgRmVkZXJh
bDEUMBIGA1UECxMLQUMgQ0FJWEEgUEoxKDAmBgNVBAMTH0EgQlVITEVSIFNBIENVUlRVTUU6NDA5
NDI0OTAwMTAwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAOFxgvG35RQWgXec4zVrzoUHolnJ
fP76rpO2Vo40593W9Gf0WwHt36gVmli0ZeQitFmzFSoE5KhgXQGZg6RpV3WJUFcIrPBHPdqOSfiB
988kf962P+j8fZ38BNmo7TV9H9hMBkV9bD/QOe73wFDc+rT6/9io++Z+7/wup/3glKntAgMBAAGj
ggLOMIICyjAOBgNVHQ8BAf8EBAMCBeAwVwYDVR0gBFAwTjBMBgZgTAECAQkwQjBABggrBgEFBQcC
ARY0aHR0cDovL2ljcC5jYWl4YS5nb3YuYnIvcmVwb3NpdG9yaW8vZHBjYWNjYWl4YXBqLnBkZjAp
BgNVHSUEIjAgBggrBgEFBQcDAgYIKwYBBQUHAwQGCisGAQQBgjcUAgIwgbYGA1UdEQSBrjCBq4EV
YnVobGVyQGFidWhsZXIuY29tLmJyoD4GBWBMAQMEoDUEMzE0MDkxOTQ2NDA5NDI0OTAwMTAxMDg0
NDcwODE3NTAwMDAwODAzMjkyMjM1NlNTUCBSU6AeBgVgTAEDAqAVBBNOQUlSIEJVSExFUiBTQ0hO
RUNLoBkGBWBMAQMDoBAEDjg5NzE2NTgzMDAwMTY1oBcGBWBMAQMHoA4EDDAwMDAwMDAwMDAwMDCC
ATIGA1UdHwSCASkwggElMIGuoIGroIGohjJodHRwOi8vaWNwLmNhaXhhLmdvdi5ici9yZXBvc2l0
b3Jpby9BQ0NBSVhBUEoxLmNybIY0aHR0cDovL2ljcDIuY2FpeGEuZ292LmJyL3JlcG9zaXRvcmlv
Mi9BQ0NBSVhBUEoxLmNybIY8aHR0cDovL3JlcG9zaXRvcmlvLmljcGJyYXNpbC5nb3YuYnIvbGNy
L2NhaXhhL0FDQ0FJWEFQSjEuY3JsMHKgcKBupGwwajELMAkGA1UEBhMCYnIxEzARBgNVBAoTCklD
UC1CcmFzaWwxIDAeBgNVBAsTF0NhaXhhIEVjb25vbWljYSBGZWRlcmFsMRQwEgYDVQQDEwtBQyBD
QUlYQSBQSjEOMAwGA1UEAxMFQ1JMNDEwHwYDVR0jBBgwFoAUjkAvCv4T1ao5oHZ0htO8fcfx5c8w
CQYDVR0TBAIwADAZBgkqhkiG9n0HQQAEDDAKGwRWNy4xAwIDqDANBgkqhkiG9w0BAQUFAAOCAQEA
nZHUvdnZsiCIDjKm1zHehbtuDtDJha4O4FZ03J74Y+AxyAFs/4JED+xUvZ5jFuEsdqgA0V/dxUFy
Uz/ca10Ievd578GQdGwYl1GFhRtO/SlxeaOEf7eDdGOWXO3VmUA3NmNo0X8RRTIoifnhpDXu7RbN
5sijyH/uXyRFWX9XH2N0U/r3oJtNKXsvoUlbDrkalgkuLzLKsaEj0TkwisXO3cmMoWGuBpAZC+46
e4x/2vTqOvYkzZO+O9NLi0YWSYY7OJKiKBjMC6MzdlPM9VTkIwO9WvWEMdbU0/jhO2cMcVMzNZc1
r6ZmdTDrwqV3elSTkQtJ0RIZNgMJUn+Y8c7Aog==
</X509Certificate>
</X509Data>
</KeyInfo>
</Signature>

Notice the (unwanted) line-breaks.

Any help would be greatly appreciated.

Thanks a lot in advance.

(*) Clarification: the new rule forbids whitespaces (or any other text) between element-only tags. As an example, this would be allowed:

  text
  inside
  tag

while this would be forbidden:

text

because on the latter case, the whitespaces (line-breaks) are between two tags, or, in other words, placed inside an element-only tag.


问:
Waiting for a javascript promise to complete (when I have no other options...)
Before you all start screaming about refactoring and callbacks, read the question fully, please :)

I have the following situation in javascript (code simplified for convenience):

```<code>    function myFunc(){
        var myItems = getItemsAsync(); //this returns a promise

        return {
            settings: {
                type: "items",
                component: "accordion",
                items: myItems //WRONG! This is a promise, not the data itself!
            }
        }
    }
</code>```

Here's the situation: I have an external framework that calls myFunc and expects the returned object {settings: etc...} to have all values already filled in, including the items sub-object. I have no control over how this framework calls myFunc, so I cannot change it to accept a promise or partial result, the returned object must be "ready" when myFunc returns.

Now, as you can see, here's the problem: to obtain the items I need to call an API that is asynchronous by design, and returns a promise. Unfortunately, this API is also out of my control, so I cannot modify it to work synchronously.

So basically I am at a stalemate: I have to synchronously return a complete object, but one of the pieces of that object can only be obtained asynchronously!!

Is there a way out of this? All the similar questions I've seen here on SO suggest that waiting for a promise to be complete cannot be done... is it true?

I know what you're all dying to say: "CHANGE EITHER THE CALLER OR THE API", but unfortunately they are both components that are totally out of my control, as they're part of existing systems that i CANNOT modify (due to bureaucratic, rather than technical, reasons)

Any ideas to get out of this?

答:
You know the answer already :-) If you have no other options, you have no options at all. It's fundamentally impossible to immediately return a value that will be obtained in the future.

That said, there exist some solutions that can halt the world of your caller, if you are able to wrap the entire framework in a Fiber or something similar. Of course that requires a fundamental change to the entire system, but can be done without changing the framework's code. This might cause some bugs due to unexpected timing, though.

Body:
Before you all start screaming about refactoring and callbacks, read the question fully, please :)

I have the following situation in javascript (code simplified for convenience):

    function myFunc(){
        var myItems = getItemsAsync(); //this returns a promise

        return {
            settings: {
                type: "items",
                component: "accordion",
                items: myItems //WRONG! This is a promise, not the data itself!
            }
        }
    }

Here's the situation: I have an external framework that calls myFunc and expects the returned object {settings: etc...} to have all values already filled in, including the items sub-object. I have no control over how this framework calls myFunc, so I cannot change it to accept a promise or partial result, the returned object must be "ready" when myFunc returns.

Now, as you can see, here's the problem: to obtain the items I need to call an API that is asynchronous by design, and returns a promise. Unfortunately, this API is also out of my control, so I cannot modify it to work synchronously.

So basically I am at a stalemate: I have to synchronously return a complete object, but one of the pieces of that object can only be obtained asynchronously!!

Is there a way out of this? All the similar questions I've seen here on SO suggest that waiting for a promise to be complete cannot be done... is it true?

I know what you're all dying to say: "CHANGE EITHER THE CALLER OR THE API", but unfortunately they are both components that are totally out of my control, as they're part of existing systems that i CANNOT modify (due to bureaucratic, rather than technical, reasons)

Any ideas to get out of this?


问:
How would i group an array in php
I want to group this array. please help me..

```<code>Array
(
    [0] => dghfdih@hjuh.cvh
    [1] => dghfdih@hjuh.cvh
    [2] => dghfdih@hjuh.cvh
)
</code>```

And my expected output is

```<code> Array
    (
        [0] => dghfdih@hjuh.cvh

    )
</code>```

答:
Look at array_unique which will remove duplicates from the array.

```<code><?php
// Assuming your array is stored as $arr
$arr = array(
    'dghfdih@hjuh.cvh',
    'dghfdih@hjuh.cvh',
    'dghfdih@hjuh.cvh'
);
// Remove the duplicates
$arr = array_unique($arr);
// Print to test
echo '```'.var_export($arr, TRUE).'```';
</code>```

Title: How would i group an array in php

Body:
I want to group this array. please help me..

Array
(
    [0] => dghfdih@hjuh.cvh
    [1] => dghfdih@hjuh.cvh
    [2] => dghfdih@hjuh.cvh
)

And my expected output is

 Array
    (
        [0] => dghfdih@hjuh.cvh

    )

Body:
Look at array_unique which will remove duplicates from the array.

<?php
// Assuming your array is stored as $arr
$arr = array(
    'dghfdih@hjuh.cvh',
    'dghfdih@hjuh.cvh',
    'dghfdih@hjuh.cvh'
);
// Remove the duplicates
$arr = array_unique($arr);
// Print to test
echo '<pre>'.var_export($arr, TRUE).'</pre>';


问:
How can I populate the following objects in multiple input fields?
Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!

<!DOCTYPE html>

    <meta charset="UTF-8">

How to get the console result in the input fields below?

1st
<input value="" id="1">

2nd
<input value="" id="2">

3rd
<input value="" id="3">

4th
<input value="" id="4">

5th
<input value="" id="5">

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

<p>My console perfectly returns </p>

``` * Vibrant #7a4426
 * Muted #7b9eae
 * DarkVibrant #348945
 * DarkMuted #141414
 * LightVibrant #f3ccb4
```

The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.

答:
Take a look at this example I made. Hopefully it helps!

var url = 'https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D';
var img = document.createElement('img');
img.setAttribute('src', url + '&' + new Date().getTime());
img.setAttribute('crossOrigin', '');

img.addEventListener('load', function() {
    var vibrant = new Vibrant(img);
    var swatches = vibrant.swatches()
    var i = 0;
    for (var swatch in swatches)
        if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
          document.getElementById(""+(i+1)).value = swatches[swatch].getHex();
          i = i + 1;
        }
});
      ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://jariz.github.io/vibrant.js/dist/Vibrant.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <label>Vibrant</label>
      <input value="" class="form-control" id="1">
      <label>Muted</label>
      <input value="" class="form-control" id="2">
      <label>DarkVibrant</label>
      <input value="" class="form-control" id="3">
      <label>DarkMuted</label>
      <input value="" class="form-control" id="4">
      <label>LightVibrant</label>
      <input value="" class="form-control" id="5">
    </div>
    <div class="col-sm-6">
      <div class="panel panel-default">
        <div class="panel-body">
          <img class="img-responsive" src="https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D">
        </div>
      </div>
    </div>
  </div>
</div></code>```

Also you can find it here:
https://jsfiddle.net/bgmpow5q/

Body:
Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!

<!DOCTYPE html>

    <meta charset="UTF-8">

How to get the console result in the input fields below?

1st
<input value="" id="1">

2nd
<input value="" id="2">

3rd
<input value="" id="3">

4th
<input value="" id="4">

5th
<input value="" id="5">

My console perfectly returns

 * Vibrant #7a4426
 * Muted #7b9eae
 * DarkVibrant #348945
 * DarkMuted #141414
 * LightVibrant #f3ccb4

The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.

Body:
Take a look at this example I made. Hopefully it helps!

var url = 'https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D';
var img = document.createElement('img');
img.setAttribute('src', url + '&' + new Date().getTime());
img.setAttribute('crossOrigin', '');

img.addEventListener('load', function() {
    var vibrant = new Vibrant(img);
    var swatches = vibrant.swatches()
    var i = 0;
    for (var swatch in swatches)
        if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
          document.getElementById(""+(i+1)).value = swatches[swatch].getHex();
          i = i + 1;
        }
});

<script src="https://jariz.github.io/vibrant.js/dist/Vibrant.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
  <div class="row">
    <div class="col-sm-6">
      <label>Vibrant</label>
      <input value="" class="form-control" id="1">
      <label>Muted</label>
      <input value="" class="form-control" id="2">
      <label>DarkVibrant</label>
      <input value="" class="form-control" id="3">
      <label>DarkMuted</label>
      <input value="" class="form-control" id="4">
      <label>LightVibrant</label>
      <input value="" class="form-control" id="5">
    </div>
    <div class="col-sm-6">
      <div class="panel panel-default">
        <div class="panel-body">
          <img class="img-responsive" src="https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D">
        </div>
      </div>
    </div>
  </div>
</div>

Also you can find it here:
https://jsfiddle.net/bgmpow5q/


答:
I assume you wish to remove duplicates, luckily PHP has a function called array_unique

Use it like so:

```<code>$array = array( "dghfdih@hjuh.cvh", "dghfdih@hjuh.cvh", "dghfdih@hjuh.cvh" );

$array = array_unique( $array );
</code>```

Title: How would i group an array in php

Body:
I assume you wish to remove duplicates, luckily PHP has a function called array_unique

Use it like so:

$array = array( "dghfdih@hjuh.cvh", "dghfdih@hjuh.cvh", "dghfdih@hjuh.cvh" );

$array = array_unique( $array );


问:
MYSQL: find duplicates in a relational field
I have a main table, related to another table through another_table_id field.

```<code>id  another_table_id
1   1
2   2
3   2
</code>```

I need to select all rows, that have duplicates (id 2 and 3 of main table)

I tried the following query

```<code>select * from main_table
group by another_table_id
having count(*) > 1
</code>```

But the query gives me

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'main_table.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Also, this query

```<code>select * from main_table
group by id, another_table_id
having count(*) > 1
</code>```

Give me an empty dataset, any suggestions, please?

答:
You could use a JOIN.

```<code>SELECT * FROM main_table
JOIN another_table ON another_table.id = main_table.
</code>```

This would join the data eliminating the need for the HAVING clause

However if you wanted both sets of data use a UNION as this will not join the data

```<code>SELECT * FROM main_table
UNION
SELECT * FROM another_table
HAVING COUNT(*) > 1
</code>```

Hope this helps!

Body:
I have a main table, related to another table through another_table_id field.

id  another_table_id
1   1
2   2
3   2

I need to select all rows, that have duplicates (id 2 and 3 of main table)

I tried the following query

select * from main_table
group by another_table_id
having count(*) > 1

But the query gives me

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'main_table.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Also, this query

select * from main_table
group by id, another_table_id
having count(*) > 1

Give me an empty dataset, any suggestions, please?

Body:
You could use a JOIN.

SELECT * FROM main_table
JOIN another_table ON another_table.id = main_table.

This would join the data eliminating the need for the HAVING clause

However if you wanted both sets of data use a UNION as this will not join the data

SELECT * FROM main_table
UNION
SELECT * FROM another_table
HAVING COUNT(*) > 1

Hope this helps!


问:
Set a flag for duplicates in a sql table
I have a table with some field of duplicate value. I can't delete those duplicates beacause I don't know which ones are correct, so i want to identify all records that have possible duplicates for same values and  set in a column the id of the possible duplicates.
This is an example test table:

```<code>id col1 col2
----------------
1  aaa  aaa
2  baa  bbb
3  abc  ccc
4  cde  aaa
5  baa  bbb
6  aaa  aaa
</code>```

and want to achieve the following result finding duplicates in col2:

```<code>id col1 col2 dup
----------------
1  aaa  aaa  4,6
2  baa  bbb  5
3  abc  ccc
4  cde  aaa  6,1
5  baa  bbb  2
6  aaa  aaa  1,4
</code>```

So for more than one duplicate it must report a comma separated list of duplicate found.
I have an sql statement to identify those duplicates but no idea how to set an update query:

```<code> select distinct l.* from table l
 inner join table r on l.id != r.id and l.col2 = r.col2
</code>```

Any ideas?

答:
This seems to work:

```<code>mysql> select id, col1, col2, (select group_concat(id) from bubu q where q.col2=a.col2 and q.id <> a.id group by q.col2) as dup from bubu a;
+----+------+------+------+
| id | col1 | col2 | dup  |
+----+------+------+------+
|  1 | aaa  | aaa  | 4,6  |
|  2 | baa  | bbb  | 5    |
|  3 | abc  | ccc  | NULL |
|  4 | cde  | aaa  | 1,6  |
|  5 | baa  | bbb  | 2    |
|  6 | aaa  | aaa  | 1,4  |
+----+------+------+------+
</code>```

To update the original table, it looks like you need to create a temporary table first:

```<code>create table tmp as select id, (select group_concat(id) from bubu q where q.col2=a.col2
and q.id <> a.id group by q.col2) as dup from bubu a;

update bubu a set dup = (select dup from tmp where tmp.id=a.id);
</code>```

If your table is large, it's probably helpful to create an index on tmp.id before updating (but haven't tested).

Body:
I have a table with some field of duplicate value. I can't delete those duplicates beacause I don't know which ones are correct, so i want to identify all records that have possible duplicates for same values and  set in a column the id of the possible duplicates.
This is an example test table:

id col1 col2
----------------
1  aaa  aaa
2  baa  bbb
3  abc  ccc
4  cde  aaa
5  baa  bbb
6  aaa  aaa

and want to achieve the following result finding duplicates in col2:

id col1 col2 dup
----------------
1  aaa  aaa  4,6
2  baa  bbb  5
3  abc  ccc
4  cde  aaa  6,1
5  baa  bbb  2
6  aaa  aaa  1,4

So for more than one duplicate it must report a comma separated list of duplicate found.
I have an sql statement to identify those duplicates but no idea how to set an update query:

 select distinct l.* from table l
 inner join table r on l.id != r.id and l.col2 = r.col2

Any ideas?

Body:
This seems to work:

mysql> select id, col1, col2, (select group_concat(id) from bubu q where q.col2=a.col2 and q.id <> a.id group by q.col2) as dup from bubu a;
+----+------+------+------+
| id | col1 | col2 | dup  |
+----+------+------+------+
|  1 | aaa  | aaa  | 4,6  |
|  2 | baa  | bbb  | 5    |
|  3 | abc  | ccc  | NULL |
|  4 | cde  | aaa  | 1,6  |
|  5 | baa  | bbb  | 2    |
|  6 | aaa  | aaa  | 1,4  |
+----+------+------+------+

To update the original table, it looks like you need to create a temporary table first:

create table tmp as select id, (select group_concat(id) from bubu q where q.col2=a.col2
and q.id <> a.id group by q.col2) as dup from bubu a;

update bubu a set dup = (select dup from tmp where tmp.id=a.id);

If your table is large, it's probably helpful to create an index on tmp.id before updating (but haven't tested).


问:
Python, specific count of chars in string
I am trying to count the number of occurrences in a string in python. I would like to take a binary input, say '001101'. Then count the number of 1s, 0s, 11s, 00s etc.

I have tried to implement this by using count, but this will output that there are 3 1s, when i only want it to output 1 1, and 1 11s and for it to not count them individually, unless they are on their own.

I have also tried to implement this with find, but i am having the same problem.

Any help would be appreciated, thanks.

答:
You can do the following, using itertools.groupby and collections.Counter:

```<code>from itertools import groupby
from collections import Counter

s = '001101011'
c = Counter(''.join(g) for _, g in groupby(s))

c.get('11')
# 2
c.get('1')
# 1
c.get('111', 0)  # use default value to capture count 0 properly
# 0
</code>```

This groups the string into substrings consisting only of equal chars and performs the counting on those substrings.

Body:
You can do the following, using itertools.groupby and collections.Counter:

from itertools import groupby
from collections import Counter

s = '001101011'
c = Counter(''.join(g) for _, g in groupby(s))

c.get('11')
# 2
c.get('1')
# 1
c.get('111', 0)  # use default value to capture count 0 properly
# 0

This groups the string into substrings consisting only of equal chars and performs the counting on those substrings.


问:
Weekly Group by not including Sunday
I am grouping the data by week in the following queries

```<code> select id,sum(quantity) ,dateadd(wk, datediff(wk,0, [createddate]), 0) from table1 where
 createddate >= '2017-10-02' and createddate <= '2017-11-12'
 and [id] = 111
 group by [id] , dateadd(wk, datediff(wk,0, [createddate]), 0)
</code>```

Its grouping the data upto Sat i.e. Mon - Sat, not Mon to Sun. Can someone explain what I am missing.

I cannot change the database start day

Sample data is :

02/10/2017 9.00

03/10/2017 10.50

04/10/2017 10.00

08/10/2017 1.00

答:
You could group by week number instead:

```<code> group by [id] , datepart(ISO_WEEK, [createddate])
</code>```

ISO weeks start on Monday.

Title: Weekly Group by not including Sunday

Body:
I am grouping the data by week in the following queries

 select id,sum(quantity) ,dateadd(wk, datediff(wk,0, [createddate]), 0) from table1 where
 createddate >= '2017-10-02' and createddate <= '2017-11-12'
 and [id] = 111
 group by [id] , dateadd(wk, datediff(wk,0, [createddate]), 0)

Its grouping the data upto Sat i.e. Mon - Sat, not Mon to Sun. Can someone explain what I am missing.

I cannot change the database start day

Sample data is :

02/10/2017 9.00

03/10/2017 10.50

04/10/2017 10.00

08/10/2017 1.00

Body:
You could group by week number instead:

 group by [id] , datepart(ISO_WEEK, [createddate])

ISO weeks start on Monday.


答:
Here's one way:</p>

```<code>SELECT DISTINCT x.*
           FROM my_table x
           JOIN my_table y
             ON y.another_table_id = x.another_table_id
            AND y.id <> x.id;
</code>```

Title: MYSQL: find duplicates in a relational field

Body:
Here's one way:

SELECT DISTINCT x.*
           FROM my_table x
           JOIN my_table y
             ON y.another_table_id = x.another_table_id
            AND y.id <> x.id;