问:
Access Scope of elements in page object model
I am working on to automate a form to create a profile. While doing that I observed a something i need to understand. Please look at the code below and if it would be great if anyone can explain the reason behind this.

I am using page object for my project.
I have selectors defined under elements and i am accessing the elements/selectors in the functions down below.

I am not able to access the elements inside the function for the below code

For the this.api.perform function when I try to access the element(subjectGenderFemale) to click on it, it errors out with the error "ERROR: Unable to locate element: "@subjectGenderFemale" using: css selector". So i had to access it with the actual selector 'input[value="F"]'. Please refer to the code below @ .api.perform.

```<code>'use strict';
var assert = require('assert');

var subjectJSON = require('../../../e2e/data/subjectData.json');

module.exports = {
   elements: {
    newSubjectButton: {
      selector: '.btn.btn--primary'
},
subjectFirstName: {
  selector: 'input[name^="first_name"]'
},
subjectLastName: {
  selector: 'input[name^="last_name"]'
},
subjectDateOfBirth: {
  selector: 'input[name^="date_of_birth"]'
},
subjectGenderFemale: {
  selector: 'input[value="F"]'
},
subjectGenderMale: {
  selector: 'input[value="M"]'
},
submitButton: {
  selector: '.col.col-sm-offset-2.col-sm-8>div>form>button'
}
  },
  commands: [{
openCreateSubjectForm: function() {
  return this
    .waitForElementPresent('@newSubjectButton', 1000)
    //the below href needs to change to proper element
    .click('a[href="/subject/create"]')
},
populateSubjectForm: function() {
  return this
  .setValue('@subjectFirstName', subjectJSON["createSubject"]["firstName"])
  .setValue('@subjectLastName', subjectJSON["createSubject"]["lastName"])
  .setValue('@subjectDateOfBirth', subjectJSON["createSubject"]["dateOfBirth"])
  .api.perform(function() {
    if (subjectJSON["createSubject"]["gender"]=="F") {
      this.api.click('input[value="F"]')
    }else if (subjectJSON["createSubject"]["gender"]=="M") {
      this.api.click('input[value="M"]')
    }else if (subjectJSON["createSubject"]["gender"]=="Both") {
      this.api.click('input[value="Both"]')
    }else {
      this.api.click('input[value="No preference"]')
    }
  })
},
submitCreateSubjectForm: function() {
  return this.click('@submitButton');
 }
}]
};
</code>```

答: i got around this problem by accessing it via this.elements.subjectGenderFemale.selector

Body:
I am working on to automate a form to create a profile. While doing that I observed a something i need to understand. Please look at the code below and if it would be great if anyone can explain the reason behind this.

I am using page object for my project.
I have selectors defined under elements and i am accessing the elements/selectors in the functions down below.

I am not able to access the elements inside the function for the below code

For the this.api.perform function when I try to access the element(subjectGenderFemale) to click on it, it errors out with the error "ERROR: Unable to locate element: "@subjectGenderFemale" using: css selector". So i had to access it with the actual selector 'input[value="F"]'. Please refer to the code below @ .api.perform.

'use strict';
var assert = require('assert');

var subjectJSON = require('../../../e2e/data/subjectData.json');

module.exports = {
   elements: {
    newSubjectButton: {
      selector: '.btn.btn--primary'
},
subjectFirstName: {
  selector: 'input[name^="first_name"]'
},
subjectLastName: {
  selector: 'input[name^="last_name"]'
},
subjectDateOfBirth: {
  selector: 'input[name^="date_of_birth"]'
},
subjectGenderFemale: {
  selector: 'input[value="F"]'
},
subjectGenderMale: {
  selector: 'input[value="M"]'
},
submitButton: {
  selector: '.col.col-sm-offset-2.col-sm-8>div>form>button'
}
  },
  commands: [{
openCreateSubjectForm: function() {
  return this
    .waitForElementPresent('@newSubjectButton', 1000)
    //the below href needs to change to proper element
    .click('a[href="/subject/create"]')
},
populateSubjectForm: function() {
  return this
  .setValue('@subjectFirstName', subjectJSON["createSubject"]["firstName"])
  .setValue('@subjectLastName', subjectJSON["createSubject"]["lastName"])
  .setValue('@subjectDateOfBirth', subjectJSON["createSubject"]["dateOfBirth"])
  .api.perform(function() {
    if (subjectJSON["createSubject"]["gender"]=="F") {
      this.api.click('input[value="F"]')
    }else if (subjectJSON["createSubject"]["gender"]=="M") {
      this.api.click('input[value="M"]')
    }else if (subjectJSON["createSubject"]["gender"]=="Both") {
      this.api.click('input[value="Both"]')
    }else {
      this.api.click('input[value="No preference"]')
    }
  })
},
submitCreateSubjectForm: function() {
  return this.click('@submitButton');
 }
}]
};


来源: stackexchange

问:
Replace mongodb document without appending attributes
I think I have a weird one here.

I'm using mongoose in express to update a document in a collection. The model looks like this:

```<code>var customers = new Schema({
companyName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
contacts: [{
    firstName: String,
    lastName: String,
    title: String,
    phone: String,
    email: String
}],
custCode: Number,
rep: String
});
</code>```

Above is a new model, as the old model looked like this:

```<code>var customers = new Schema({
companyName: String,
firstName: String,
lastName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
email: String
custCode: Number,
rep: String
});
</code>```

The difference is that I broke out a "contacts" array so I can add more contacts in the future. Existing documents in the collection have the old style of model and the update object has the new model.

When I run the following code, the document ends up getting appended with the contacts array, but also keeps the firstName and lastName, email etc instead of losing it as per the rules of the new model.

```<code>var conditions = {custCode:req.body.customer.custCode}
, update = req.body.customer
, options = {upsert: false, new: true};

mongoose.model('customers').findOneAndUpdate(conditions, update, options, callback);
function callback (err, doc) {
    if(err) {
      console.log("Errors: " + err);
      res.sendStatus(500);
    } else {
      console.log("Customer Saved! Rows affected: ", doc);
      res.sendStatus(200);
    };
  };
</code>```

Is there a different mongoose function that I should be using? Should I be using $unset?

I'd rather not do two calls to the database (one to remove the matching collection and another to save a new model.

Thanks so much in advance!

答:
You can use $unset to remove the contacts array and $set to add the new model.

mongoose.model('customers').findOneAndUpdate(conditions, { $set:update, $unset: {'contacts': ''}}, options, callback);

ContentLicense: CC BY-SA 3.0

Body:
I think I have a weird one here.

I'm using mongoose in express to update a document in a collection. The model looks like this:

var customers = new Schema({
companyName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
contacts: [{
    firstName: String,
    lastName: String,
    title: String,
    phone: String,
    email: String
}],
custCode: Number,
rep: String
});

Above is a new model, as the old model looked like this:

var customers = new Schema({
companyName: String,
firstName: String,
lastName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
email: String
custCode: Number,
rep: String
});

The difference is that I broke out a "contacts" array so I can add more contacts in the future. Existing documents in the collection have the old style of model and the update object has the new model.

When I run the following code, the document ends up getting appended with the contacts array, but also keeps the firstName and lastName, email etc instead of losing it as per the rules of the new model.

var conditions = {custCode:req.body.customer.custCode}
, update = req.body.customer
, options = {upsert: false, new: true};

mongoose.model('customers').findOneAndUpdate(conditions, update, options, callback);
function callback (err, doc) {
    if(err) {
      console.log("Errors: " + err);
      res.sendStatus(500);
    } else {
      console.log("Customer Saved! Rows affected: ", doc);
      res.sendStatus(200);
    };
  };

Is there a different mongoose function that I should be using? Should I be using $unset?

I'd rather not do two calls to the database (one to remove the matching collection and another to save a new model.

Thanks so much in advance!


问:
Disable Cloudflare error pages and show the actual error page
I want to know what the actual error is. I was able to hide it temporary, and it gave me a database connection error, so I tweaked the username and password. Now it's back to an error page.

How do I disable this error page entirely? I tried development mode, but it is still showing the actual error.

Besides, the error isn't entirely true:

```<code># systemctl status nginx
nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
Active: active (running) since Tue 2017-03-28 20:44:47 UTC; 11min ago
</code>```

答: Users on the Enterprise plan may be able to accomplish something like that.  However, you should be able use your own error logs to get that type of information.</p>

Body:
I want to know what the actual error is. I was able to hide it temporary, and it gave me a database connection error, so I tweaked the username and password. Now it's back to an error page.

How do I disable this error page entirely? I tried development mode, but it is still showing the actual error.

Besides, the error isn't entirely true:

# systemctl status nginx
nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
Active: active (running) since Tue 2017-03-28 20:44:47 UTC; 11min ago


问:
What are all of the generic collections/types in the 4.0 .NET Framework?
Is there an exhaustive list of all of the "base" (not used in an object-oriented sense but more in a common sense) generic types in the 4.0 .NET Framework? I have found this list that I often send newer/mid-level devs to so they can understand how non-generic types map to generic types, but this is by no means exhaustive. I'm looking for something that also includes things such as KeyValuePair<>, Tuple<>, and other basic generics that may not be very-well known. Interfaces such as IObservable<> would be nice but not necessarily required.

答:
You can find this in the System.Collections.Generic namespace
http://msdn.microsoft.com/en-us/library/system.collections.generic.aspx</p>

ContentLicense: CC BY-SA 2.5


问:
Emacs equivalent of Xcode's "Open Quickly"
I'm trying to get a Cocoa development environment working in Emacs, and I'm 80% of the way there.  The one feature I miss is Xcode's "Open Quickly", which basically performs a fuzzy match of the string you type against the filenames referenced in the Xcode workspace and the symbols defined in those files.

My problem is that our project is huge: if I generate a TAGS file using etags for the .h and .m files in our project's sub-directories, the result is over a gig in size and Emacs complains "TAGS file is large. Really open?", and if I say yes, then Emacs hangs and becomes essentially unusable. Of course, this is before I've even considered indexing tags for system libraries.  I've also tried projectile, but unfortunately it's similarly unusable on a project of my size (on the order of a full minute to find a match).

It occurs to me that all the indexing information I really want is in the Xcode projects themselves, so if I had an Emacs package that could parse them and traverse their dependencies, that might be a start, but I'm not aware of any such package.

Any suggestions/solutions in this respect?

答:
I've never found a single function quite as convenient as Xcode's "Open Quickly", but these days I use

helm-projectile-git-grep when I want to match on strings I know to be in the filenames, and

helm-git-grep for quick searches through the contents of the files themselves.

I've found that this gets me really close to what I wanted in my original question.


问:
Active link with React-Router?
I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

```<code>const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)
</code>```

答:
This is an old, outdated answer for React Router v4

<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

```<code>const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <NavLink exact activeClassName='is-active' to='/'>Home</NavLink>
        <NavLink activeClassName='is-active' to='/about'>About</NavLink>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)
</code>```

I added an exact property to the home <NavLink>, I'm fairly sure that without it, the home link would always be active since / would match /about and any other pages you have.

Title: Active link with React-Router?

Body:
I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

const Router = () => (
  <BrowserRouter>

        <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}
        <Link activeClassName='is-active' to='/about'>About</Link>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />

  </BrowserRouter>
)

Body:
This is an old, outdated answer for React Router v4

<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

const Router = () => (
  <BrowserRouter>
    <div>
      <Nav>
        <NavLink exact activeClassName='is-active' to='/'>Home</NavLink>
        <NavLink activeClassName='is-active' to='/about'>About</NavLink>
      </Nav>

      <Match pattern='/' exactly component={Home} />
      <Match pattern='/about' exactly component={About} />
      <Miss component={NoMatch} />
    </div>
  </BrowserRouter>
)

I added an exact property to the home <NavLink>, I'm fairly sure that without it, the home link would always be active since / would match /about and any other pages you have.

ContentLicense: CC BY-SA 4.0


问:
How to call back the same window!? PYQT5
I spent all day debugging and stripping my project to fix this issue.

I have a help window(Help_ui class) which should open if the text.txt is not found and the main window(Main class)which has a QTextEdit box which should print "Hello".
The problem is that when I call the Main window from the Help_ui class it doesn't print "Hello", but it does if I call it from the logic.

Why is doing this, does it open another instance of that windows and not the proper window?

```<code>from PyQt5 import QtWidgets
import sys
from pathlib import Path
from ui_files import mainWindow
from ui_files import help_ui

text = "Hello"

class Main(QtWidgets.QMainWindow, mainWindow.Ui_mainWindow):
    def __init__(self, text):
        super().__init__()
        self.setupUi(self)

        self.mainTextEdit.setText(text)

class Help_ui(QtWidgets.QDialog, help_ui.Ui_help):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.close_btn.clicked.connect(self.close)

        self.form = Main(None)
        self.form.show()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    form = Main(text)

    my_file = Path("file.txt")
    if my_file.is_file():
        form.show()
    else:
        help_window = Help_ui()
        help_window.show()

    app.exec_()
</code>```

答:
What happens is that the instance form is different from the instance self.form, in the first you pass as a parameter text, instead in the second None.

Must be change self.form = Main(None) to self.form = Main(text)

Body:
I spent all day debugging and stripping my project to fix this issue.

I have a help window(Help_ui class) which should open if the text.txt is not found and the main window(Main class)which has a QTextEdit box which should print "Hello".
The problem is that when I call the Main window from the Help_ui class it doesn't print "Hello", but it does if I call it from the logic.

Why is doing this, does it open another instance of that windows and not the proper window?

from PyQt5 import QtWidgets
import sys
from pathlib import Path
from ui_files import mainWindow
from ui_files import help_ui

text = "Hello"

class Main(QtWidgets.QMainWindow, mainWindow.Ui_mainWindow):
    def __init__(self, text):
        super().__init__()
        self.setupUi(self)

        self.mainTextEdit.setText(text)

class Help_ui(QtWidgets.QDialog, help_ui.Ui_help):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        self.close_btn.clicked.connect(self.close)

        self.form = Main(None)
        self.form.show()

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    form = Main(text)

    my_file = Path("file.txt")
    if my_file.is_file():
        form.show()
    else:
        help_window = Help_ui()
        help_window.show()

    app.exec_()


问:
asp.net mvc: why is Html.CheckBox generating an additional hidden input
I just noticed that Html.CheckBox("foo") generates 2 inputs instead of one, anybody knows why is this so ?

```<code><input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" />
</code>```

答:
I found this really caused issues when I had a WebGrid. The sorting links on the WebGrid would turn by the doubled up querystring or x=true&x=false into x=true,false and cause a parse error in checkbox for.

I ended up using jQuery to delete the hidden fields on the client side:

```<code>    <script type="text/javascript">
    $(function () {
        // delete extra hidden fields created by checkboxes as the grid links mess this up by doubling the querystring parameters
        $("input[type='hidden'][name='x']").remove();
    });
    </script>
</code>```

Body:
I just noticed that Html.CheckBox("foo") generates 2 inputs instead of one, anybody knows why is this so ?

<input id="foo" name="foo" type="checkbox" value="true" />
<input name="foo" type="hidden" value="false" />

Body:
I found this really caused issues when I had a WebGrid. The sorting links on the WebGrid would turn by the doubled up querystring or x=true&x=false into x=true,false and cause a parse error in checkbox for.

I ended up using jQuery to delete the hidden fields on the client side:

    <script type="text/javascript">
    $(function () {
        // delete extra hidden fields created by checkboxes as the grid links mess this up by doubling the querystring parameters
        $("input[type='hidden'][name='x']").remove();
    });
    </script>


问:
Why won't my my mad lib compile?
So I have to use javascript and html to make a mad lib. I am asking the user to enter values and then hit the button and it is supposed to generate a story using the values they entered.

Here is my HTML:

```<code><ul>
  <li>Your Name: <input type="text" id="name"></li>
  <li>Adjective: <input type="text" id="adjective"></li>
  <li>State: <input type="text" id="state"></li>
  <li>Animal: <input type="text" id="animal"></li>
  <li>Month: <input type="text" id="month"></li>
  <li>Adjective: <input type="text" id="adjective2"></li>
  <li>Animal: <input type="text" id="animal2"></li>
  <li>Object: <input type="text" id="object"></li>
</ul>
<button id="ready-button">Ready</button>
<div id="story"></div>
<script>
    function madLib() {
      var storyDiv = document.getElementById("story");
      var adjective = document.getElementById("adjective").value;
      var noun = document.getElementById("noun").value;
      var state = document.getElementById("state").value;
      var animal = document.getElementById("animal").value;
      var month = document.getElementById("month").value;
      var adjective2 = document.getElementById("adjective2").value;
      var animal2 = document.getElementById("animal2").value;
      var object = document.getElementById("object").value;
      storyDiv.innerHTML ="One day, " + name + " was in the backwoods of " + state + " riding their pet " + animal + " it wasn't often that " + name + " got the chance to do this so they always made the most of their adventure. Usually, it was a fun experience until that one day in " + month + " they were minding their own business when all of the sudden the " + adjective2 + " " + animal2 + " jumped out from behind a small " + object + ". " + name + " could not beieve what they were seeing.";
    }
    var readyButton = document.getElementById('ready-button');
    readyButton.addEventListener('click', madLib);
</script>
</code>```

答:
It seems that you got "noun" mixed up with "name" when grabbing the values for your story.
You have <input type="text" id="name">
 and you use the name variable in your story a few times, but in the madLib function you have

```<code>var noun = document.getElementById("noun").value;
//document.getElementById("noun") will be undefined because there is no "noun element"
</code>```

which should probably be

```<code>var name = document.getElementById("name").value;
</code>```

Title: Why won't my my mad lib compile?

Body:
So I have to use javascript and html to make a mad lib. I am asking the user to enter values and then hit the button and it is supposed to generate a story using the values they entered.

Here is my HTML:

Your Name: <input type="text" id="name">

Adjective: <input type="text" id="adjective">

State: <input type="text" id="state">

Animal: <input type="text" id="animal">

Month: <input type="text" id="month">

Adjective: <input type="text" id="adjective2">

Animal: <input type="text" id="animal2">

Object: <input type="text" id="object">

<button id="ready-button">Ready</button>

Body:
It seems that you got "noun" mixed up with "name" when grabbing the values for your story.
You have <input type="text" id="name"></li> and you use the name variable in your story a few times, but in the madLib function you have

var noun = document.getElementById("noun").value;
//document.getElementById("noun") will be undefined because there is no "noun element"

which should probably be

var name = document.getElementById("name").value;


问:
Linking CSS to HTML background color
I am using node.js to run a local website and am having trouble linking the css to html.

The html is:

```<code><!DOCTYPE html>
<html>

<head>
    <title> Name </title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css" />

</head>

<body id="background">
    <h1> My Website </h1>
    <span style="float:right">
    <a href = "https://google.com/"> Google </a>
    </span>
</body>
</code>```

and css is:

```<code>#background {
  background-color: #0099FF;
}
</code>```

I have not been able to view the effects of the css on the website and am not able to change the background color.

I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.

update: i am adding the app.js file

```<code>var http = require('http'),
    fs = require('fs');

fs.readFile('./header.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});
</code>```

答: Your syntax looks correct. Definitely check the browser console to see if there is error with finding the css file. I would check to make sure that the css file is indeed named "style.css".</p>

Title: Linking CSS to HTML background color

Body:
I am using node.js to run a local website and am having trouble linking the css to html.

The html is:

<!DOCTYPE html>

    <title> Name </title>
    <meta charset="utf-8"/>
    <link rel="stylesheet" type="text/css" href="style.css" />

 My Website

     Google

and css is:

#background {
  background-color: #0099FF;
}

I have not been able to view the effects of the css on the website and am not able to change the background color.

I have checked online resources and it seems as if the syntax is correct. The css file style.css is in the same directory as the html. The html is working on the local website but not the css.

update: i am adding the app.js file

var http = require('http'),
    fs = require('fs');

fs.readFile('./header.html', function (err, html) {
    if (err) {
        throw err;
    }
    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});


问:
php, simple preg_match_all example not working
It seems like the preg_match is working until it finds the first match and then stops:

```<code>$bgStr="<><><><><><><>";

$regStr='/</';

preg_match_all($regStr,$bgStr,$matches);

echo count($matches);
</code>```

gives me the result of:  "1".  What am I missing?

答:
There are at least 3 logical ways to achieve your count on the less than symbol.
The last one listed being the best / most efficient / recommended one...

preg_match_all() is overkill.  It creates an array in an array containing elements which must be counted.

```<code>$bgStr="<><><><><><><>";
if(preg_match_all('/</',$bgStr,$matches)){
    echo sizeof($matches[0]);  // counts the fullstring elements that preg_match_all creates
}
</code>```

count_chars() is overkill.  It creates an array of elements like CodeNumber=>Count for each character found in the string.

```<code>$bgStr="<><><><><><><>";
echo count_chars($bgStr,1)[60];
</code>```

substr_count() is the leanest method and was specifically
  designed for this purpose.  This is a single-function, one-liner that
  does not generate excess data nor requires additional variables.

```<code>$bgStr="<><><><><><><>";
echo substr_count($bgStr,'<');
</code>```

All methods above will output: 7

Body:
It seems like the preg_match is working until it finds the first match and then stops:

$bgStr="<><><><><><><>";

$regStr='/</';

preg_match_all($regStr,$bgStr,$matches);

echo count($matches);

gives me the result of:  "1".  What am I missing?

Body:
There are at least 3 logical ways to achieve your count on the less than symbol.
The last one listed being the best / most efficient / recommended one...

preg_match_all() is overkill.  It creates an array in an array containing elements which must be counted.

$bgStr="<><><><><><><>";
if(preg_match_all('/</',$bgStr,$matches)){
    echo sizeof($matches[0]);  // counts the fullstring elements that preg_match_all creates
}

count_chars() is overkill.  It creates an array of elements like CodeNumber=>Count for each character found in the string.

$bgStr="<><><><><><><>";
echo count_chars($bgStr,1)[60];

substr_count() is the leanest method and was specifically
  designed for this purpose.  This is a single-function, one-liner that
  does not generate excess data nor requires additional variables.

$bgStr="<><><><><><><>";
echo substr_count($bgStr,'<');

All methods above will output: 7


问:
Is the Broker able to Block unwanted topic spammers?
I have a MQTT environment like this:

there is One (gray) sensor and one Observer that are related by the topic room/temp, so far so good, sensor can publish and the Observer can get the info as it should.

the Issue I have is now: I need to block IN THE BROKER that a 2nd undesired client comes(the orange one),and start to publish into the same topic, as far as I know, MQTT is loose coupled so that observer doesn't care who is pushing the temp values, but I find a security flawless when someone hack my environment and publish non sense triggering my alarms...

any suggestion?

am using eMQTTd by the way and according to this there is nothing in the etc/emqttd.config file I can do to avoid that...

Thanks!

答:
I only have experience with Mosquitto but, from a quick read of the document linked, it looks like there are several ways you could achieve this.

I am unclear if you are talking about an incidental problem here--i.e. bad information is being accidentally sent--or if you are protecting against an active threat.

If you are concerned with incidental overwriting of a value, then the simple clientid solution on (pg. 38) would work.

But my impression is that it would still be transmitted in the clear and thus be of little use to you if you are facing an actual adversary (hacker etc.). If that is your concern simply setup SSL and remove all non-SSL listeners. (See pg. 24). That should limit all traffic to an encrypted channel. Then if you wish add password / user authentication (pg. 38) to complete the security.

Alternatively, depending on your configuration, you could block unapproved ip addresses at the firewall level (i.e. block access to the port that your broker is listening on to all addresses except for the temperature sensor) or using eMQTTd's built in ACL facility (pg. 25). That would be less secure than a full SSL setup but depending upon your needs it might be enough.


问:
Best practice to do nested TRY / FINALLY statement
Hi What is the best way to do nested try & finally statements in delphi?

```<code>var cds1  : TClientDataSet;
    cds2  : TClientDataSet;
    cds3  : TClientDataSet;
    cds4  : TClientDataSet;
begin
  cds1      := TClientDataSet.Create(application );
  try
    cds2      := TClientDataSet.Create(application );
    try
      cds3      := TClientDataSet.Create(application );
      try
        cds4      := TClientDataSet.Create(application );
        try
        ///////////////////////////////////////////////////////////////////////
        ///      DO WHAT NEEDS TO BE DONE
        ///////////////////////////////////////////////////////////////////////
        finally
          cds4.free;
        end;

      finally
        cds3.free;
      end;
    finally
      cds2.free;
    end;
  finally
    cds1.free;
  end;
end;
</code>```

Can you Suggest a better way of doing this?

答:
There is a good video on exceptions in constructors & destructors

It shows some nice examples such as:

```<code>var cds1  : TClientDataSet;
    cds2  : TClientDataSet;
begin
  cds1      := Nil;
  cds2      := Nil;
 try
    cds1      := TClientDataSet.Create(nil);
    cds2      := TClientDataSet.Create(nil);
    ///////////////////////////////////////////////////////////////////////
    ///      DO WHAT NEEDS TO BE DONE
    ///////////////////////////////////////////////////////////////////////
  finally
    freeandnil(cds2);    //// what has if there in an error in the destructor of cds2
    freeandnil(Cds1);
  end;
end;
</code>```

What has if there in an error in the destructor of cds2

Cds1 will not be Destroyed

EDIT

Another good resource is :

Jim McKeeth excellent  video on Delayed Exception Handling in code range III were he talks about problems in handling exceptions in the finally block.

OwnerDisplayName: CharlesF

Body:
Hi What is the best way to do nested try & finally statements in delphi?

var cds1  : TClientDataSet;
    cds2  : TClientDataSet;
    cds3  : TClientDataSet;
    cds4  : TClientDataSet;
begin
  cds1      := TClientDataSet.Create(application );
  try
    cds2      := TClientDataSet.Create(application );
    try
      cds3      := TClientDataSet.Create(application );
      try
        cds4      := TClientDataSet.Create(application );
        try
        ///////////////////////////////////////////////////////////////////////
        ///      DO WHAT NEEDS TO BE DONE
        ///////////////////////////////////////////////////////////////////////
        finally
          cds4.free;
        end;

      finally
        cds3.free;
      end;
    finally
      cds2.free;
    end;
  finally
    cds1.free;
  end;
end;

Can you Suggest a better way of doing this?

LastEditorDisplayName: Oliver Giesen

Body:
There is a good video on exceptions in constructors & destructors

It shows some nice examples such as:

var cds1  : TClientDataSet;
    cds2  : TClientDataSet;
begin
  cds1      := Nil;
  cds2      := Nil;
 try
    cds1      := TClientDataSet.Create(nil);
    cds2      := TClientDataSet.Create(nil);
    ///////////////////////////////////////////////////////////////////////
    ///      DO WHAT NEEDS TO BE DONE
    ///////////////////////////////////////////////////////////////////////
  finally
    freeandnil(cds2);    //// what has if there in an error in the destructor of cds2
    freeandnil(Cds1);
  end;
end;

What has if there in an error in the destructor of cds2

Cds1 will not be Destroyed

EDIT

Another good resource is :

Jim McKeeth excellent  video on Delayed Exception Handling in code range III were he talks about problems in handling exceptions in the finally block.

OwnerDisplayName: Charles Faiga

LastEditorDisplayName: Charles Faiga


问:
Programmatically determine best foreground color to be placed onto an image
I'm working on a node module that will return the color that will look best onto a background image which of course will have multiple colors.

Here's what I have so far:

```<code>'use strict';

var randomcolor = require('randomcolor');
var tinycolor = require('tinycolor2');

module.exports = function(colors, tries) {
  var topColor, data = {};

  if (typeof colors == 'string') { colors = [colors]; }
  if (!tries) { tries = 10000; }

  for (var t = 0; t < tries; t++) {
    var score = 0, color = randomcolor(); //tinycolor.random();

    for (var i = 0; i < colors.length; i++) {
      score += tinycolor.readability(colors[i], color);
    }

    data[color] = (score / colors.length);

    if (!topColor || data[color] > data[topColor]) {
      topColor = color;
    }
  }

  return tinycolor(topColor);
};
</code>```

So the way it works is first I provide this script with the 6 most dominant colors in an image like this:

```<code>[ { r: 44, g: 65, b: 54 },
  { r: 187, g: 196, b: 182 },
  { r: 68, g: 106, b: 124 },
  { r: 126, g: 145, b: 137 },
  { r: 147, g: 176, b: 169 },
  { r: 73, g: 138, b: 176 } ]
</code>```

and then it will generate 10,000 different random colors and then pick the one that has the best average contrast ratio with the 6 given colors.

The problem is that depending on which script I use to generate the random colors, I'll basically get the same results regardless of the image given.

With tinycolor2 I'll always end up with either a very dark gray (almost black) or a very light gray (almost white). And with randomcolor I'll either end up with a dark blue or a light peach color.

My script might not be the best way of going about this but does anybody have any ideas?

Thank you

答: It depends on where the text is that is overlayed on the background image.  If the background has some large feature on part of it, the text will likely be placed away from that, so must contrast with that part of the image, but you may also want to pick up a certain color or complement the other colors in the image.  I think practically speaking you will need to create a widget for people to easily slide/adjust the foreground color interactively.  Or you will need to create a deep learning system in order to do this really effectively.</p>

Body:
I'm working on a node module that will return the color that will look best onto a background image which of course will have multiple colors.

Here's what I have so far:

'use strict';

var randomcolor = require('randomcolor');
var tinycolor = require('tinycolor2');

module.exports = function(colors, tries) {
  var topColor, data = {};

  if (typeof colors == 'string') { colors = [colors]; }
  if (!tries) { tries = 10000; }

  for (var t = 0; t < tries; t++) {
    var score = 0, color = randomcolor(); //tinycolor.random();

    for (var i = 0; i < colors.length; i++) {
      score += tinycolor.readability(colors[i], color);
    }

    data[color] = (score / colors.length);

    if (!topColor || data[color] > data[topColor]) {
      topColor = color;
    }
  }

  return tinycolor(topColor);
};

So the way it works is first I provide this script with the 6 most dominant colors in an image like this:

[ { r: 44, g: 65, b: 54 },
  { r: 187, g: 196, b: 182 },
  { r: 68, g: 106, b: 124 },
  { r: 126, g: 145, b: 137 },
  { r: 147, g: 176, b: 169 },
  { r: 73, g: 138, b: 176 } ]

and then it will generate 10,000 different random colors and then pick the one that has the best average contrast ratio with the 6 given colors.

The problem is that depending on which script I use to generate the random colors, I'll basically get the same results regardless of the image given.

With tinycolor2 I'll always end up with either a very dark gray (almost black) or a very light gray (almost white). And with randomcolor I'll either end up with a dark blue or a light peach color.

My script might not be the best way of going about this but does anybody have any ideas?

Thank you


问:
Java Apache http library file upload issue
I Have a webservice that uploads a file. (details in the first link)

To communicate with this webservice I use org.apache.http library (Apache HttpComponents). I have found most of this code if not all of it here.

Sadly the solution only works with images and despite the efforts when trying to upload a video is shows the error of Content Length too long. To try and fix this I decided to replace it with what's in current use. At first using HttpClientBuilder

```<code>HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();
</code>```

My try failed as it still gives the same error and after research I found out that I need to use the CloseableHttpClient as follow to disable the automatic headers

```<code>CloseableHttpClient httpclient = HttpClients.custom()
        .setHttpProcessor(HttpProcessorBuilder.create().build())
        .build();
</code>```

That worked but when setting the headers something doesn't pass I can't figure it out. I did it as follow

```<code>httppost.addHeader("Keep-Alive", "timeout=5, max=100");
httppost.addHeader("Connection", "Keep-Alive");
httppost.addHeader("Content-Type", "text/html; charset=UTF-8");
</code>```

But when tracing the response this is what I have

```<code>Http Client Builder Trace
    Date,Tue, 28 Mar 2017 18:30:50 GMT
    Server,Apache/2.4.23 (Win64) PHP/7.0.10
    X-Powered-By,PHP/7.0.10
    Content-Length,43
    Keep-Alive,timeout=5, max=100
    Connection,Keep-Alive
    Content-Type,text/html; charset=UTF-8

Closable Response Trace
    Date,Tue, 28 Mar 2017 18:31:27 GMT
    Server,Apache/2.4.23 (Win64) PHP/7.0.10
    Content-Length,311
    Connection,close
    Content-Type,text/html; charset=iso-8859-1
</code>```

I tried to set the headers to the response but I am haven't figured how to instantiate it properly to set the headers. And also I am trying to understand why the httppost is not being taken in consideration. Did I miss something?

One last thing when I use Closable The way I did it doesn't upload anymore due to missing headers I guess.

EDIT

Error when uploading video

```<code>Exception in thread "main" org.apache.http.ContentTooLongException: Content length is too long: 16363535
at org.apache.http.entity.mime.MultipartFormEntity.getContent(MultipartFormEntity.java:103)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:199)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:306)
at testfileupload.PostFile.main(PostFile.java:100)
C:\Users\User\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
</code>```

EDIT

I changed the max file size for php following this but it still shows the same error

Update

This is how I handle the multipart (I use multipartform)

```<code>HttpEntity resEntity = MultipartEntityBuilder.create()
    .addBinaryBody("userfile", file, ContentType.create("video/mp4"), file.getName())
    .build();
</code>```

I rememeber reading something about it (not sure) And as for the php.ini params that need to be of higher value upload_max_filesize = 40M and post_max_size = 40M and memory_limit = 128M which I am kinda sure its enough (using wamp64).

I kept trying to udnerstand the content length issue since ..

I found out that the HttpEntity sets calculates the length and I checked the value its 2 bits off I believe but no matter the conenction type it just doesn't work and sticks to content length error.

I also tried

```<code>HttpClient httpclient = HttpClients.custom().setDefaultHeaders(Arrays.asList(CustomHeader)).build();
</code>```

But still nothing. At this point I highly doubt its about setting the header and more related to HttpEntity with the Multipart or the HttpPost but It could be else.

Upload

I tried with a 9s Video of a size ~350Kb but it still gives the content length error which means there might be a default content set or none at all

答:
So I dont know what I did / changed but now its working with the error.

I would really want to know why this cause an error it doesn't make sense so far unless its calling something that can't take too high of a value (method of param type given value more than it can)

To be clear the error is generated when I use this (verifcation area)

```<code>System.out.println(response.getStatusLine());
if (resEntity != null) {
// error from below, kinda forgot about it
      System.out.println(EntityUtils.toString(resEntity));
}

    if (resEntity != null) {
//      resEntity.consumeContent();
    }
</code>```

The webservice is the same as in the first link.

Below is my code (dont mind the comments I didn't clear the decrepated / changed / replaced / test / different approaches)

```<code>import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.util.EntityUtils;

public class PostFile {
  public static void main(String[] args) throws Exception {
//    HttpClient httpclient = new DefaultHttpClient();

//    CloseableHttpClient httpclient = HttpClients.custom()
//        .setHttpProcessor(HttpProcessorBuilder.create().build())
//        .build();

//    Header headerCustom = new BasicHeader(HttpHeaders.CONTENT_LENGTH, "15");

//    HttpClient httpclient = HttpClients.custom().build();

//        HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();
   HttpClient httpclient = HttpClientBuilder.create().build();
//    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost/userVids/upload.php");

    httppost.setProtocolVersion(new ProtocolVersion("HTTP", 1, 1));
    File file = new File("C:/Users/User/Desktop/test_video.mp4");

//    httppost.addHeader("Content-Length", String.valueOf(file.length()));

//    MultipartEntity mpEntity = new MultipartEntity();
//    ContentBody cbFile = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
//    mpEntity.addPart("userfile", cbFile);
//      System.out.println(mpEntity.getContentLength());
//
//    httppost.setEntity(mpEntity);

    /*
        Date,Tue, 28 Mar 2017 18:30:50 GMT
        Server,Apache/2.4.23 (Win64) PHP/7.0.10
        X-Powered-By,PHP/7.0.10
        Content-Length,43
        Keep-Alive,timeout=5, max=100
        Connection,Keep-Alive
        Content-Type,text/html; charset=UTF-8
    */

    /*
        Date,Tue, 28 Mar 2017 18:31:27 GMT
        Server,Apache/2.4.23 (Win64) PHP/7.0.10
        Content-Length,311
        Connection,close
        Content-Type,text/html; charset=iso-8859-1
    */

    HttpEntity resEntity = MultipartEntityBuilder.create()
        .addBinaryBody("userfile", file, ContentType.create("video/mp4"), file.getName())
        .build();

      System.out.println("Entity Length " + resEntity.getContentLength());
//    httppost.addHeader("Keep-Alive", "timeout=5, max=100");
//    httppost.addHeader("Connection", "Keep-Alive");
//    httppost.addHeader("Content-Type", "text/html; charset=UTF-8");

//    httppost.addHeader("Content-Disposition", "form-data; name=\"userfile\"; filename=\"star_empty.png\"");
//    httppost.addHeader("Content-Type", "image/png");
//    httppost.addHeader("Content-Transfer-Encoding", "binary");
//    httppost.addHeader("Content-Length", "99999");

    httppost.setEntity(resEntity);

    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
//    HttpEntity resEntity = response.getEntity();

    System.out.println("Headers (name,value)");
    List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
    httpHeaders.forEach((header) -> {
        System.out.println(header.getName() + "," + header.getValue());
    });

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
//      resEntity.consumeContent();
    }

//    httpclient.getConnectionManager().shutdown();
  }
}
</code>```

BUT A HUGE NOTICE I had my php.ini (changed all of them in wamp didn't know if it would consider only the running version or reads all (didn't test) ) and changed the values as Lucas Holt (he fixed it i.e, I am just providing for who needs or maybe explanation) said and he deserves credit for it. (I am sure it didn't work before that I just tested a lot and dont remember really.)

Body:
I Have a webservice that uploads a file. (details in the first link)

To communicate with this webservice I use org.apache.http library (Apache HttpComponents). I have found most of this code if not all of it here.

Sadly the solution only works with images and despite the efforts when trying to upload a video is shows the error of Content Length too long. To try and fix this I decided to replace it with what's in current use. At first using HttpClientBuilder

HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();

My try failed as it still gives the same error and after research I found out that I need to use the CloseableHttpClient as follow to disable the automatic headers

CloseableHttpClient httpclient = HttpClients.custom()
        .setHttpProcessor(HttpProcessorBuilder.create().build())
        .build();

That worked but when setting the headers something doesn't pass I can't figure it out. I did it as follow

httppost.addHeader("Keep-Alive", "timeout=5, max=100");
httppost.addHeader("Connection", "Keep-Alive");
httppost.addHeader("Content-Type", "text/html; charset=UTF-8");

But when tracing the response this is what I have

Http Client Builder Trace
    Date,Tue, 28 Mar 2017 18:30:50 GMT
    Server,Apache/2.4.23 (Win64) PHP/7.0.10
    X-Powered-By,PHP/7.0.10
    Content-Length,43
    Keep-Alive,timeout=5, max=100
    Connection,Keep-Alive
    Content-Type,text/html; charset=UTF-8

Closable Response Trace
    Date,Tue, 28 Mar 2017 18:31:27 GMT
    Server,Apache/2.4.23 (Win64) PHP/7.0.10
    Content-Length,311
    Connection,close
    Content-Type,text/html; charset=iso-8859-1

I tried to set the headers to the response but I am haven't figured how to instantiate it properly to set the headers. And also I am trying to understand why the httppost is not being taken in consideration. Did I miss something?

One last thing when I use Closable The way I did it doesn't upload anymore due to missing headers I guess.

EDIT

Error when uploading video

Exception in thread "main" org.apache.http.ContentTooLongException: Content length is too long: 16363535
at org.apache.http.entity.mime.MultipartFormEntity.getContent(MultipartFormEntity.java:103)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:199)
at org.apache.http.util.EntityUtils.toString(EntityUtils.java:306)
at testfileupload.PostFile.main(PostFile.java:100)
C:\Users\User\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

EDIT

I changed the max file size for php following this but it still shows the same error

Update

This is how I handle the multipart (I use multipartform)

HttpEntity resEntity = MultipartEntityBuilder.create()
    .addBinaryBody("userfile", file, ContentType.create("video/mp4"), file.getName())
    .build();

I rememeber reading something about it (not sure) And as for the php.ini params that need to be of higher value upload_max_filesize = 40M and post_max_size = 40M and memory_limit = 128M which I am kinda sure its enough (using wamp64).

I kept trying to udnerstand the content length issue since ..

I found out that the HttpEntity sets calculates the length and I checked the value its 2 bits off I believe but no matter the conenction type it just doesn't work and sticks to content length error.

I also tried

HttpClient httpclient = HttpClients.custom().setDefaultHeaders(Arrays.asList(CustomHeader)).build();

But still nothing. At this point I highly doubt its about setting the header and more related to HttpEntity with the Multipart or the HttpPost but It could be else.

Upload

I tried with a 9s Video of a size ~350Kb but it still gives the content length error which means there might be a default content set or none at all

Body:
So I dont know what I did / changed but now its working with the error.

I would really want to know why this cause an error it doesn't make sense so far unless its calling something that can't take too high of a value (method of param type given value more than it can)

To be clear the error is generated when I use this (verifcation area)

System.out.println(response.getStatusLine());
if (resEntity != null) {
// error from below, kinda forgot about it
      System.out.println(EntityUtils.toString(resEntity));
}

    if (resEntity != null) {
//      resEntity.consumeContent();
    }

The webservice is the same as in the first link.

Below is my code (dont mind the comments I didn't clear the decrepated / changed / replaced / test / different approaches)

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.util.EntityUtils;

public class PostFile {
  public static void main(String[] args) throws Exception {
//    HttpClient httpclient = new DefaultHttpClient();

//    CloseableHttpClient httpclient = HttpClients.custom()
//        .setHttpProcessor(HttpProcessorBuilder.create().build())
//        .build();

//    Header headerCustom = new BasicHeader(HttpHeaders.CONTENT_LENGTH, "15");

//    HttpClient httpclient = HttpClients.custom().build();

//        HttpClient httpclient = HttpClientBuilder.create().disableContentCompression().build();
   HttpClient httpclient = HttpClientBuilder.create().build();
//    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost/userVids/upload.php");

    httppost.setProtocolVersion(new ProtocolVersion("HTTP", 1, 1));
    File file = new File("C:/Users/User/Desktop/test_video.mp4");

//    httppost.addHeader("Content-Length", String.valueOf(file.length()));

//    MultipartEntity mpEntity = new MultipartEntity();
//    ContentBody cbFile = new FileBody(file, ContentType.MULTIPART_FORM_DATA);
//    mpEntity.addPart("userfile", cbFile);
//      System.out.println(mpEntity.getContentLength());
//
//    httppost.setEntity(mpEntity);

    /*
        Date,Tue, 28 Mar 2017 18:30:50 GMT
        Server,Apache/2.4.23 (Win64) PHP/7.0.10
        X-Powered-By,PHP/7.0.10
        Content-Length,43
        Keep-Alive,timeout=5, max=100
        Connection,Keep-Alive
        Content-Type,text/html; charset=UTF-8
    */

    /*
        Date,Tue, 28 Mar 2017 18:31:27 GMT
        Server,Apache/2.4.23 (Win64) PHP/7.0.10
        Content-Length,311
        Connection,close
        Content-Type,text/html; charset=iso-8859-1
    */

    HttpEntity resEntity = MultipartEntityBuilder.create()
        .addBinaryBody("userfile", file, ContentType.create("video/mp4"), file.getName())
        .build();

      System.out.println("Entity Length " + resEntity.getContentLength());
//    httppost.addHeader("Keep-Alive", "timeout=5, max=100");
//    httppost.addHeader("Connection", "Keep-Alive");
//    httppost.addHeader("Content-Type", "text/html; charset=UTF-8");

//    httppost.addHeader("Content-Disposition", "form-data; name=\"userfile\"; filename=\"star_empty.png\"");
//    httppost.addHeader("Content-Type", "image/png");
//    httppost.addHeader("Content-Transfer-Encoding", "binary");
//    httppost.addHeader("Content-Length", "99999");

    httppost.setEntity(resEntity);

    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
//    HttpEntity resEntity = response.getEntity();

    System.out.println("Headers (name,value)");
    List<Header> httpHeaders = Arrays.asList(response.getAllHeaders());
    httpHeaders.forEach((header) -> {
        System.out.println(header.getName() + "," + header.getValue());
    });

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
//      resEntity.consumeContent();
    }

//    httpclient.getConnectionManager().shutdown();
  }
}

BUT A HUGE NOTICE I had my php.ini (changed all of them in wamp didn't know if it would consider only the running version or reads all (didn't test) ) and changed the values as Lucas Holt (he fixed it i.e, I am just providing for who needs or maybe explanation) said and he deserves credit for it. (I am sure it didn't work before that I just tested a lot and dont remember really.)


问:
Using Google Play Store to push out updates to a "device owner" app
We have an Android app that we'd like to run on thousands of identical tablets that we will own and rent to our customers. The app runs in a sort of "kiosk mode" (we use app pinning, in the parlance of this page: https://developer.android.com/work/cosu.html). We're also, at present, configuring our app as the device owner using adb shell dpm set-device-owner ....

We have two goals here:

Be able to push updates to the app out to all our devices without any user interaction on each device.

Reduce the manual configuration of each new device when we unbox it and set it up as much as possible.

Can we use Google Play Store to push app updates out? I had in mind that we'd use the Alpha or Beta release for this and never actually publish the app for others to install. Using Google Play Store of course requires a Google Account to be added to the device, and once we do that, I fear our options for using a device owner app are limited, not to mention the fact that adding that Google Account may not be able to be scripted using adb or similar. We'd like to avoid manually adding the Google Account if possible.

答:
Unfortunately the Google Play sandbox is still very consumer app oriented. However, the Play EMM API and Managed Google Play have some capabilities around distributing apps: https://developers.google.com/android/work/distribute

Their EMM documentation covers provisioning as well via either a device-driven flow (using nfc) or a user driven flow (using a google account): https://developers.google.com/android/work/prov-devices

Alternatively you could look at 3rd party MDM solutions or use a platform built for enterprise mobile deployment like Mason: http://bymason.com

Mason allows you to create a custom Android OS in a just a few minutes (kiosk mode app, disable camera/sms, remove apps and settings, etc). Applications can be bundled and versioned along with the operating system or deployed independently. Mason supports background app and os updates 100% controlled and configured by you.

You can order large volumes devices from Mason with your OS and apps preloaded on them as well.

Feel free to ping me directly: dylan @ bymason.com

Big Disclaimer: I work for Mason


问:
PHP asynchronous reading (shell scripting)
I have a PHP TCP daemon which provides data to clients. One of the features is to get info from "tail -f messages" command. So I have to run this command asynchronously and in case of new data, send it to the clients.

I have a problem how to create this asynchronous reader - when new data is added, run the method, otherwise do the other things you have to.

Mejmo

EDIT: My problem could be resolved by using some kinds of threads and IPC (does php support threads?).

答: Try stream_set_blocking(), it should do the trick.


问:
Is it possible to display as "block" if content "line breaks" but display "inline" otherwise?
I have  code that looks a little bit like this:

```<code><div class="some-class">
    <span>NameOfThing</span>
    <div class="block-or-inline">
        <span style="white-space: nowrap">ValueOfThing1</span>
        <span style="white-space: nowrap">ValueOfThing2</span>
    </div>
</div>
</code>```

If the content inside div.block-or-inline is shorter than the width of its container (no line break) I would like all the content to render on a single line. But if the content is wider - causing a line break - I would like BOTH spans inside to break to the new line.

Is this possible?

答:
I just left my keyboard for a few minutes and realized a simple way to solve this would be to to place the two pieces of content that I want to break to the new line under the same "white-space: nowrap" span: </p>

```<code><div class="some-class">
    <span>NameOfThing</span>
    <span style="white-space: nowrap">ValueOfThing1 ValueOfThing2</span>
</div>
</code>```

Body:
I have  code that looks a little bit like this:

    NameOfThing

        ValueOfThing1
        ValueOfThing2

If the content inside div.block-or-inline is shorter than the width of its container (no line break) I would like all the content to render on a single line. But if the content is wider - causing a line break - I would like BOTH spans inside to break to the new line.

Is this possible?

Body:
I just left my keyboard for a few minutes and realized a simple way to solve this would be to to place the two pieces of content that I want to break to the new line under the same "white-space: nowrap" span:

<div class="some-class">
    <span>NameOfThing</span>
    <span style="white-space: nowrap">ValueOfThing1 ValueOfThing2</span>
</div>


问:
Updating table with business day and calendar day
I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in.  The date rule already has values but the expected date column is what is updated manually.  If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month.  If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth.  Is it possible to write an update query where it would loop through the values and update automatically?  I'm having trouble figuring out to update to the correct business day.

```
date rule  | March expected date | April expected date |
--------------------------------------------------------
| BD1      | 3/1/2017            | 4/3/2017            |
| BD2      | 3/2/2017            |                     |
| BD3      | 3/3/2017            |                     |
| BD4      | 3/6/2017            |                     |
| BD5      |                     |                     |
| BD6      |                     |                     |
| CD1      | 3/1/2017            |                     |
| CD2      | 3/2/2017            |                     |
| CD3      | 3/3/2017            |                     |
| CD4      | 3/4/2017            |                     |
| CD5      | 3/5/2017            |                     |
| CD6      | 3/6/2017            |                     |

```

I was using the following code to calculate the first business day

```<code>SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
</code>```

)

but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday.  i'm getting stumped in how to tackle this.  I'm thinking a loop update query would be best

Body:
I have a table in SQL Server 2012 that is updated manually every month to reflect what date is a file expected to come in.  The date rule already has values but the expected date column is what is updated manually.  If its expected on BD1(Business Day 1) I will update to the first non-weekend day of the month.  If its expected on CD1(Calenday Day 1) I will update to the 1st regardless if it falls on a weekday or a weekend and so forth.  Is it possible to write an update query where it would loop through the values and update automatically?  I'm having trouble figuring out to update to the correct business day.

date rule  | March expected date | April expected date |
--------------------------------------------------------
| BD1      | 3/1/2017            | 4/3/2017            |
| BD2      | 3/2/2017            |                     |
| BD3      | 3/3/2017            |                     |
| BD4      | 3/6/2017            |                     |
| BD5      |                     |                     |
| BD6      |                     |                     |
| CD1      | 3/1/2017            |                     |
| CD2      | 3/2/2017            |                     |
| CD3      | 3/3/2017            |                     |
| CD4      | 3/4/2017            |                     |
| CD5      | 3/5/2017            |                     |
| CD6      | 3/6/2017            |                     |

I was using the following code to calculate the first business day

SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)

)

but then when it would come to business day 4, it would give me 3/4/2017 which is a saturday instead of 3/6/2017 which is the following monday.  i'm getting stumped in how to tackle this.  I'm thinking a loop update query would be best

Body:
here you go. This recursive CTE will give you the BDs for the whole month:

declare @forwhichdate datetime
set @forwhichdate ='20170401'
;with bd as(
select
DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, DATEADD(MONTH, DATEDIFF(MONTH, 0, @forwhichdate), 0)) + @@DATEFIRST - 1) % 7
    WHEN 6 THEN 2
    WHEN 7 THEN 1
    ELSE 0
END,
DATEADD(MONTH, DATEDIFF(MONTH, 0, @forwhichdate), 0)
) as bd, 1 as n
UNION ALL
SELECT DATEADD(DAY,
CASE
    (DATEPART(WEEKDAY, bd.bd) + @@DATEFIRST - 1) % 7
    WHEN 5 THEN 3
    WHEN 6 THEN 2
    ELSE 1
END,
bd.bd
) as db,
bd.n+1
from bd where month(bd.bd) = month(@forwhichdate)
)
select * from bd

Result:

bd                      n
----------------------- -----------
2017-04-03 00:00:00.000 1
2017-04-04 00:00:00.000 2
2017-04-05 00:00:00.000 3
2017-04-06 00:00:00.000 4
2017-04-07 00:00:00.000 5
2017-04-10 00:00:00.000 6
2017-04-11 00:00:00.000 7
2017-04-12 00:00:00.000 8
2017-04-13 00:00:00.000 9
2017-04-14 00:00:00.000 10
2017-04-17 00:00:00.000 11
2017-04-18 00:00:00.000 12
2017-04-19 00:00:00.000 13
2017-04-20 00:00:00.000 14
2017-04-21 00:00:00.000 15
2017-04-24 00:00:00.000 16
2017-04-25 00:00:00.000 17
2017-04-26 00:00:00.000 18
2017-04-27 00:00:00.000 19
2017-04-28 00:00:00.000 20
2017-05-01 00:00:00.000 21

(21 row(s) affected)

However, in reality your query should also check for the holidays.


问:
How to select a specific  with the same class names?
I am attempting to extract some data from this block of HTML.

```<code><div class="group-capitalization-content field-group-html-element">
    <h2><span>Capitalization</span></h2>
    <div  class="item">
        <div class="label-inline">Issued & Outstanding: </div>
        <span class="number">242906121</span>
    </div >
    <div class="item">
        <div class="label-inline">Reserved for Issuance: </div>
        <span  class="number">51423534</span >
    </div>
</div>
</code>```

I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".

```<code> var data = $('.group-capitalization-content .item .number').text();
</code>```

Running this code results in: 24290612151423534, which is both results appended together.

How do I select the individual numbers here / separate them?

答:
If the above example is all you need, use .eq().

First items's text() is

```<code>$('.group-capitalization-content .item .number').eq(0).text();
</code>```

...and second is

```<code>$('.group-capitalization-content .item .number').eq(1).text();
</code>```

If you have a more complex case and you need to store the data in an array, for later, I'd use $.map() (@Sushanth's answer) - probably a bit more specific, to rule out the possibility of other .numbers in the page:

```<code>let data = $.map(
  $('.group-capitalization-content .item .number'),
  function(e){ return $(e).text() }
);
</code>```

Title: How to select a specific <span> with the same class names?

Body:
I am attempting to extract some data from this block of HTML.

Capitalization

Issued & Outstanding:

        242906121

Reserved for Issuance:

        51423534

I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".

 var data = $('.group-capitalization-content .item .number').text();

Running this code results in: 24290612151423534, which is both results appended together.

How do I select the individual numbers here / separate them?

Body:
If the above example is all you need, use .eq().

First items's text() is

$('.group-capitalization-content .item .number').eq(0).text();

...and second is

$('.group-capitalization-content .item .number').eq(1).text();

If you have a more complex case and you need to store the data in an array, for later, I'd use $.map() (@Sushanth's answer) - probably a bit more specific, to rule out the possibility of other .numbers in the page:

let data = $.map(
  $('.group-capitalization-content .item .number'),
  function(e){ return $(e).text() }
);


问:
In Javascript, what is a sure way to loop through an array of 3 strings?
Something like this works, but looks a bit clumsy:

```<code>for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome
}
</code>```

if using an array, I don't want to create any global temporary variable for the array...  Also, this has to work in any modern browser IE7 / FF / Chrome / Safari.  thanks.

答:
How about

```<code>javascript:
Array.prototype.enum = function (fn) {
  for( var i=0; i < this.length; i++ )
    fn( this[i] )
};

["one","two","tri"].enum( function(item){
  alert(item)
})
</code>```

reformatted

Body:
Something like this works, but looks a bit clumsy:

for (i in {foo: 1, bar: 1, wah: 1}) {  // loops through foo, bar, wah
  console.log(i + " haha");            // can view using Firebug or Chrome
}

if using an array, I don't want to create any global temporary variable for the array...  Also, this has to work in any modern browser IE7 / FF / Chrome / Safari.  thanks.

Body:
How about

javascript:
Array.prototype.enum = function (fn) {
  for( var i=0; i < this.length; i++ )
    fn( this[i] )
};

["one","two","tri"].enum( function(item){
  alert(item)
})

reformatted


问:
Is there a bug in Series.hasNot?
The help for function Series.hasNot in Deedle says:

Returns true when the series does not contains value for the specified key

The function does not seem to be working this way in the following example:

```<code>let election =
             [ "Party A", 304
               "Party B", 25
               "Party C", 570
               "Party Y", 2
               "Party Z", 258 ]
             |> series
let bhnt =
    election
    |> Series.hasNot "Party A"
printfn "%A" <| bhnt
// true
// val bhnt : bool = true
// val it : unit = ()
</code>```

Am I missing something?

答:
I just looked at the Deedle source and saw the following:

```<code>let has key (series:Series<'K, 'T>) = series.TryGet(key).HasValue
let hasNot key (series:Series<'K, 'T>) = series.TryGet(key).HasValue
</code>```

Yes, you've found a bug. The hasNot function should have looked like not (series.TryGet(key).HasValue).

Workaround: Until this bug is fixed, you can work around it by replacing all occurrences of Series.hasNot key in your code by Series.has key and then piping through the not function. E.g.,

```<code>let bhnt =
    election
    |> Series.has "Party A"
    |> not
</code>```

Or, if you think it looks better, you could also write that as:

```<code>let bhnt =
    election
    |> (not << Series.has "Party A")
</code>```

These two ways of writing it are equivalent; which one you prefer to use will depend on how comfortable you are with functional programming. Some people find the << syntax more natural to read, while others find it completely weird and want to stick to using only |>. It all depends on how experienced you are with functional programming; pick whichever of these two feels the most natural to you.

Title: Is there a bug in Series.hasNot?

Body:
The help for function Series.hasNot in Deedle says:

Returns true when the series does not contains value for the specified key

The function does not seem to be working this way in the following example:

let election =
             [ "Party A", 304
               "Party B", 25
               "Party C", 570
               "Party Y", 2
               "Party Z", 258 ]
             |> series
let bhnt =
    election
    |> Series.hasNot "Party A"
printfn "%A" <| bhnt
// true
// val bhnt : bool = true
// val it : unit = ()

Am I missing something?

Body:
I just looked at the Deedle source and saw the following:

let has key (series:Series<'K, 'T>) = series.TryGet(key).HasValue
let hasNot key (series:Series<'K, 'T>) = series.TryGet(key).HasValue

Yes, you've found a bug. The hasNot function should have looked like not (series.TryGet(key).HasValue).

Workaround: Until this bug is fixed, you can work around it by replacing all occurrences of Series.hasNot key in your code by Series.has key and then piping through the not function. E.g.,

let bhnt =
    election
    |> Series.has "Party A"
    |> not

Or, if you think it looks better, you could also write that as:

let bhnt =
    election
    |> (not << Series.has "Party A")

These two ways of writing it are equivalent; which one you prefer to use will depend on how comfortable you are with functional programming. Some people find the << syntax more natural to read, while others find it completely weird and want to stick to using only |>. It all depends on how experienced you are with functional programming; pick whichever of these two feels the most natural to you.


问:
IBM Object Storage with Python
I have some issue trying to save a file to IBM object storage via python. I copied the following credentials from the bluemix account (with details omitted below).

```<code>credentials = {
  "auth_url": "https://identity.open.softlayer.com",
  "project": <my project>,
  "projectId": <my project id>,
  "region": "dallas",
  "userId": <user id>,
  "username": <user name>,
  "password": <password>,
  "domainId": <domain Id>,
  "domainName": <domain Name>,
  "role": <role>
  }
</code>```

And below is the python script that I have used trying to save a file to the container
    from io import StringIO
    import requests
    import json

```<code>url1 = ''.join(['https://identity.open.softlayer.com', '/v3/auth/tokens'])
data = {'auth': {'identity': {'methods': ['password'],
        'password': {'user': {'name': credentials['username'],'domain': {'id': credentials['domainId']},
        'password': credentials['password']}}}}}
headers1 = {'Content-Type': 'application/json'}
resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
resp1_body = resp1.json()
for e1 in resp1_body['token']['catalog']:
    if(e1['type']=='object-store'):
        for e2 in e1['endpoints']:
                    if(e2['interface']=='public'and e2['region']=='dallas'):
                        url2 = ''.join([e2['url'],'/', container, '/', filename])
s_subject_token = resp1.headers['x-subject-token']
headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
print(url2)
resp2 = requests.post(url=url2, data=filename, headers=headers2)
print(resp2.text)
return StringIO(resp2.text)

filename = "sample.png"<br>
post_object_storage_file("democontainer", filename)
</code>```

I seems to get a token via resp1 and obtained url2. However, I get a 'Forbidden' response when i print resp2.text. I am the admin for that storage container so I don't see why I can't have access with this.

I am new to the IBM object storage so any advice will be helpful.

Thanks.

答:
The code you have is for reading objects from storage.

I would recommend you to use the "insert credentials" option in the Data Science Experience Data Import Panel and then use the swift client to save and read files from object storage. With Data Science Experience you can't reference files from your local hard disk, therefore I have given example of an image retrieved from the web.

Swift Client has the put_object function for saving objects.

```<code>import swiftclient
import keystoneclient.v3 as keystoneclient
from PIL import Image   ## To get image
import requests         ## To get image
from io import BytesIO

credentials = {
   ## Credentials HERE
}

conn = swiftclient.Connection(
key=credentials['password'],
authurl=credentials['auth_url']+"/v3",
auth_version='3',
os_options={
    "project_id": credentials['project_id'],
    "user_id": credentials['user_id'],
    "region_name": credentials['region']})

response = requests.get("URL to image file") ## Change to link to image file
img = Image.open(BytesIO(response.content))

conn.put_object(credentials['container'],"test.jpg",response,content_type='image/jpeg')
</code>```

Title: IBM Object Storage with Python

Body:
I have some issue trying to save a file to IBM object storage via python. I copied the following credentials from the bluemix account (with details omitted below).

credentials = {
  "auth_url": "https://identity.open.softlayer.com",
  "project": <my project>,
  "projectId": <my project id>,
  "region": "dallas",
  "userId": <user id>,
  "username": <user name>,
  "password": <password>,
  "domainId": <domain Id>,
  "domainName": <domain Name>,
  "role": <role>
  }

And below is the python script that I have used trying to save a file to the container
    from io import StringIO
    import requests
    import json

url1 = ''.join(['https://identity.open.softlayer.com', '/v3/auth/tokens'])
data = {'auth': {'identity': {'methods': ['password'],
        'password': {'user': {'name': credentials['username'],'domain': {'id': credentials['domainId']},
        'password': credentials['password']}}}}}
headers1 = {'Content-Type': 'application/json'}
resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
resp1_body = resp1.json()
for e1 in resp1_body['token']['catalog']:
    if(e1['type']=='object-store'):
        for e2 in e1['endpoints']:
                    if(e2['interface']=='public'and e2['region']=='dallas'):
                        url2 = ''.join([e2['url'],'/', container, '/', filename])
s_subject_token = resp1.headers['x-subject-token']
headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
print(url2)
resp2 = requests.post(url=url2, data=filename, headers=headers2)
print(resp2.text)
return StringIO(resp2.text)

filename = "sample.png"

post_object_storage_file("democontainer", filename)

I seems to get a token via resp1 and obtained url2. However, I get a 'Forbidden' response when i print resp2.text. I am the admin for that storage container so I don't see why I can't have access with this.

I am new to the IBM object storage so any advice will be helpful.

Thanks.

Body:
The code you have is for reading objects from storage.

I would recommend you to use the "insert credentials" option in the Data Science Experience Data Import Panel and then use the swift client to save and read files from object storage. With Data Science Experience you can't reference files from your local hard disk, therefore I have given example of an image retrieved from the web.

Swift Client has the put_object function for saving objects.

import swiftclient
import keystoneclient.v3 as keystoneclient
from PIL import Image   ## To get image
import requests         ## To get image
from io import BytesIO

credentials = {
   ## Credentials HERE
}

conn = swiftclient.Connection(
key=credentials['password'],
authurl=credentials['auth_url']+"/v3",
auth_version='3',
os_options={
    "project_id": credentials['project_id'],
    "user_id": credentials['user_id'],
    "region_name": credentials['region']})

response = requests.get("URL to image file") ## Change to link to image file
img = Image.open(BytesIO(response.content))

conn.put_object(credentials['container'],"test.jpg",response,content_type='image/jpeg')


答:
How about each function to go through each of your results, like:

```<code>$('.group-capitalization-content .item .number').each(function(index, element) {
    //your individual item code goes here
    console.log( index + ": " + $( this ).text() );
});
</code>```

Body:
How about each function to go through each of your results, like:

$('.group-capitalization-content .item .number').each(function(index, element) {
    //your individual item code goes here
    console.log( index + ": " + $( this ).text() );
});


问:
Does LOGON32_LOGON_INTERACTIVE give restricted token?
What I'm trying to understand is whether LogonUser with LOGON32_LOGON_INTERACTIVE produces restricted token or not? Here is my code:

```<code>int davai()
{
FILE * fp;

fp = fopen ("C:\\tmp\\davai.txt", "a");
fprintf(fp, "shevedi davai");
fflush(fp);

HANDLE token = NULL;
HANDLE dupToken = NULL;

if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &token))
{
  fprintf(fp, "davai: OpenProcessToken cheijva. %d\n", (int)GetLastError());
  fflush(fp);
}

if (DuplicateTokenEx(token, MAXIMUM_ALLOWED, NULL, SecurityDelegation,
                          TokenPrimary, &dupToken) == 0)
{
  fprintf(fp, "davai: OpenProcessToken DuplicateTokenEx. %d\n", (int)GetLastError());
  fflush(fp);
}

PTOKEN_GROUPS pPrivilegesToken = NULL;
DWORD cbSize = 0;

GetTokenInformation(dupToken, TokenGroups, NULL, 0, &cbSize);

pPrivilegesToken = (PTOKEN_GROUPS) LocalAlloc(LPTR, cbSize);

if (GetTokenInformation(dupToken, TokenGroups,
                             pPrivilegesToken, cbSize, &cbSize) == FALSE)
{
  fprintf(fp, "davai: GetTokenInformation cheijva. %d\n", (int)GetLastError());
  fflush(fp);
}

char * gio;

for (ULONG i = 0; i < pPrivilegesToken->GroupCount; i++)
{
  if (ConvertSidToStringSid(pPrivilegesToken->Groups[i].Sid, &gio) == 0)
  {
    fprintf(fp, "davai: ConvertSidToStringSid cheijva. %d\n", (int)GetLastError());
    fflush(fp);
  }

  fprintf(fp, "Value: %s attribute -> %ld \n",gio, pPrivilegesToken->Groups[i].Attributes);
  fflush(fp);
}

LocalFree (gio);

return 1;
}
</code>```

which is run by a token which was obtained by LOGON32_LOGON_INTERACTIVE. And my output is this:

```<code>Value: S-1-5-21-1018819917-2920201817-244685803-513 attribute -> 7
Value: S-1-1-0 attribute -> 7
Value: S-1-5-21-1018819917-2920201817-244685803-1000 attribute -> 7
Value: S-1-5-32-544 attribute -> 16
Value: S-1-5-32-545 attribute -> 7
Value: S-1-5-4 attribute -> 7
Value: S-1-2-1 attribute -> 7
Value: S-1-5-11 attribute -> 7
Value: S-1-5-15 attribute -> 7
Value: S-1-5-5-0-19732224 attribute -> -1073741817
Value: S-1-5-64-10 attribute -> 7
Value: S-1-16-8192 attribute -> 96
</code>```

Notice the 16 with Administrators Group. If I use LOGON32_LOGON_BATCH I get this:

```<code>S-1-5-21-1018819917-2920201817-244685803-513 attribute -> 7
Value: S-1-1-0 attribute -> 7
Value: S-1-5-21-1018819917-2920201817-244685803-1000 attribute -> 7
Value: S-1-5-32-544 attribute -> 15
Value: S-1-5-32-545 attribute -> 7
Value: S-1-5-3 attribute -> 7
Value: S-1-2-1 attribute -> 7
Value: S-1-5-11 attribute -> 7
Value: S-1-5-15 attribute -> 7
Value: S-1-2-0 attribute -> 7
Value: S-1-5-5-0-20537541 attribute -> -1073741817
Value: S-1-5-64-10 attribute -> 7
Value: S-1-16-12288 attribute -> 96
</code>```

I also found that some people have same problem as I do.

IsAdminUser returns incorrect value

In Windows: How do you programatically launch a process in administrator mode under another user context?

How to call LogonUser() to get a non-restricted full token inside a Windows Service with UAC enabled?

It seems to me that LOGON32_LOGON_INTERACTIVE produces restricted token (or is it that just different types of logons produce different kind of token?), Is there any documentation that would verify that I'm right?

答:
Does LOGON32_LOGON_INTERACTIVE give restricted token?

Yes, for all interactive logon types : { Interactive, RemoteInteractive, CachedInteractive, CachedRemoteInteractive }

let debug lsass.exe and look what happen during call to LsaApLogonUserEx2 (this function is called in context of lsass when client process called LsaLogonUser or it shell LogonUser)

if login is ok, the lsass must create new token for logged user. this done in function LsaBuildAndCreateToken (of course this is internal implementation and name of this function can changed from version to version, but general how it worked - unchanged). so i trace this function under debugger - look at call tree at the right (this is for interactive logon)

look for red squire - here in ESI - LogonType - SECURITY_LOGON_TYPE enumeration value

so code in general is next:

```<code>    SECURITY_LOGON_TYPE LogonType;
    switch (LogonType)
    {
    case Interactive://2
    case RemoteInteractive://10
    case CachedInteractive://11
    case CachedRemoteInteractive://12
        // optimization (LogonType == 2) || (LogonType - 10) <= 2
        BOOLEAN b, c;
        if (0 <= LsapShouldSplitToken(Sid, &b,&c) && b)
        {
            LsaSplitElevatedToken(..)
        }
        break;
    }
</code>```

this mean that lsass try restrict ONLY INTERACTIVE logon types, if will be another logon type, say Batch - token will never be filtered.

next interesting point - let look for LsapShouldSplitToken function

who know x64 - can understand code :) in general if LUA not enabled - dont filter token. if global variable LsapGlobalFilterAdministratorToken is false - check are user is built-in admin - check RID of Sid - are it 0x1f4 - DOMAIN_USER_RID_ADMIN (in other words built-in admin restricted only when LsapGlobalFilterAdministratorToken true - based on global comp politics (gpedit.msc) ) - and returned result of query 10+4=0x14=TokenElevation and returned value of TokenIsElevated

so if TokenIsElevated is true lsass call (not forget only for Interactive logon type) LsaSplitElevatedToken - what this function is doing visible in image:

created additional logon session (elevated and not elevated process for same user run in different logon sessions), created else one token (LsapCreateTokenObject) and it filtered by call NtFilterToken(hToken, LUA_TOKEN, 0, 0, 0, &hNewToken) (the win32 api CreateRestrictedToken is shell over NtFilterToken)

Body:
What I'm trying to understand is whether LogonUser with LOGON32_LOGON_INTERACTIVE produces restricted token or not? Here is my code:

int davai()
{
FILE * fp;

fp = fopen ("C:\\tmp\\davai.txt", "a");
fprintf(fp, "shevedi davai");
fflush(fp);

HANDLE token = NULL;
HANDLE dupToken = NULL;

if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &token))
{
  fprintf(fp, "davai: OpenProcessToken cheijva. %d\n", (int)GetLastError());
  fflush(fp);
}

if (DuplicateTokenEx(token, MAXIMUM_ALLOWED, NULL, SecurityDelegation,
                          TokenPrimary, &dupToken) == 0)
{
  fprintf(fp, "davai: OpenProcessToken DuplicateTokenEx. %d\n", (int)GetLastError());
  fflush(fp);
}

PTOKEN_GROUPS pPrivilegesToken = NULL;
DWORD cbSize = 0;

GetTokenInformation(dupToken, TokenGroups, NULL, 0, &cbSize);

pPrivilegesToken = (PTOKEN_GROUPS) LocalAlloc(LPTR, cbSize);

if (GetTokenInformation(dupToken, TokenGroups,
                             pPrivilegesToken, cbSize, &cbSize) == FALSE)
{
  fprintf(fp, "davai: GetTokenInformation cheijva. %d\n", (int)GetLastError());
  fflush(fp);
}

char * gio;

for (ULONG i = 0; i < pPrivilegesToken->GroupCount; i++)
{
  if (ConvertSidToStringSid(pPrivilegesToken->Groups[i].Sid, &gio) == 0)
  {
    fprintf(fp, "davai: ConvertSidToStringSid cheijva. %d\n", (int)GetLastError());
    fflush(fp);
  }

  fprintf(fp, "Value: %s attribute -> %ld \n",gio, pPrivilegesToken->Groups[i].Attributes);
  fflush(fp);
}

LocalFree (gio);

return 1;
}

which is run by a token which was obtained by LOGON32_LOGON_INTERACTIVE. And my output is this:

Value: S-1-5-21-1018819917-2920201817-244685803-513 attribute -> 7
Value: S-1-1-0 attribute -> 7
Value: S-1-5-21-1018819917-2920201817-244685803-1000 attribute -> 7
Value: S-1-5-32-544 attribute -> 16
Value: S-1-5-32-545 attribute -> 7
Value: S-1-5-4 attribute -> 7
Value: S-1-2-1 attribute -> 7
Value: S-1-5-11 attribute -> 7
Value: S-1-5-15 attribute -> 7
Value: S-1-5-5-0-19732224 attribute -> -1073741817
Value: S-1-5-64-10 attribute -> 7
Value: S-1-16-8192 attribute -> 96

Notice the 16 with Administrators Group. If I use LOGON32_LOGON_BATCH I get this:

S-1-5-21-1018819917-2920201817-244685803-513 attribute -> 7
Value: S-1-1-0 attribute -> 7
Value: S-1-5-21-1018819917-2920201817-244685803-1000 attribute -> 7
Value: S-1-5-32-544 attribute -> 15
Value: S-1-5-32-545 attribute -> 7
Value: S-1-5-3 attribute -> 7
Value: S-1-2-1 attribute -> 7
Value: S-1-5-11 attribute -> 7
Value: S-1-5-15 attribute -> 7
Value: S-1-2-0 attribute -> 7
Value: S-1-5-5-0-20537541 attribute -> -1073741817
Value: S-1-5-64-10 attribute -> 7
Value: S-1-16-12288 attribute -> 96

I also found that some people have same problem as I do.

IsAdminUser returns incorrect value

In Windows: How do you programatically launch a process in administrator mode under another user context?

How to call LogonUser() to get a non-restricted full token inside a Windows Service with UAC enabled?

It seems to me that LOGON32_LOGON_INTERACTIVE produces restricted token (or is it that just different types of logons produce different kind of token?), Is there any documentation that would verify that I'm right?

Body:
Does LOGON32_LOGON_INTERACTIVE give restricted token?

Yes, for all interactive logon types : { Interactive, RemoteInteractive, CachedInteractive, CachedRemoteInteractive }

let debug lsass.exe and look what happen during call to LsaApLogonUserEx2 (this function is called in context of lsass when client process called LsaLogonUser or it shell LogonUser)

if login is ok, the lsass must create new token for logged user. this done in function LsaBuildAndCreateToken (of course this is internal implementation and name of this function can changed from version to version, but general how it worked - unchanged). so i trace this function under debugger - look at call tree at the right (this is for interactive logon)

look for red squire - here in ESI - LogonType - SECURITY_LOGON_TYPE enumeration value

so code in general is next:

    SECURITY_LOGON_TYPE LogonType;
    switch (LogonType)
    {
    case Interactive://2
    case RemoteInteractive://10
    case CachedInteractive://11
    case CachedRemoteInteractive://12
        // optimization (LogonType == 2) || (LogonType - 10) <= 2
        BOOLEAN b, c;
        if (0 <= LsapShouldSplitToken(Sid, &b,&c) && b)
        {
            LsaSplitElevatedToken(..)
        }
        break;
    }

this mean that lsass try restrict ONLY INTERACTIVE logon types, if will be another logon type, say Batch - token will never be filtered.

next interesting point - let look for LsapShouldSplitToken function

who know x64 - can understand code :) in general if LUA not enabled - dont filter token. if global variable LsapGlobalFilterAdministratorToken is false - check are user is built-in admin - check RID of Sid - are it 0x1f4 - DOMAIN_USER_RID_ADMIN (in other words built-in admin restricted only when LsapGlobalFilterAdministratorToken true - based on global comp politics (gpedit.msc) ) - and returned result of query 10+4=0x14=TokenElevation and returned value of TokenIsElevated

so if TokenIsElevated is true lsass call (not forget only for Interactive logon type) LsaSplitElevatedToken - what this function is doing visible in image:

created additional logon session (elevated and not elevated process for same user run in different logon sessions), created else one token (LsapCreateTokenObject) and it filtered by call NtFilterToken(hToken, LUA_TOKEN, 0, 0, 0, &hNewToken) (the win32 api CreateRestrictedToken is shell over NtFilterToken)


问:
Best Continuous Integration system for Clojure
I'm currently using Jenkins and Building in Clojure. I was wondering if there was a better CI system for Clojure projects. I know CircleCI is built in Clojure but is CircleCI the Best CI tool for Clojure? I read this blog post about CircleCI's Clojure Library but wondering what my other options are. </p>

答:
I use CircleCI for a couple of GitHub/Clojure projects and I have found it to be superb.

Can't tell you if it is the best, but I can tell you it was easy to configure, and has worked seamlessly for nearly a year over hundreds of builds.

Easy to integrate with Slack, etc.


问:
How to create an enum variable using ApolloStack/GraphQL with a special character?
I'm trying to create a GraphQL enum type using ApolloStack. But nothing seems to work. For reference, please see the example code.

```<code>enum Test {
    ABC
    Dog
    Dog/Cat
}
</code>```

In the example above, Dog/Cat will cause the server to not work.

答:
You cannot have a special character in an enum in GraphQL. But you can handle them with a resolver - except there is a gotcha that you cannot resolve a Type in GraphQL, you can only resolve a field of a Type.

For example,

```<code>type Foo {
  test: Test
}
enum Test {
  ABC
  Dog
  DogCat
}
</code>```

and in your resolver for Foo,

```<code>{
  Foo: {
    test({ test }) {
      // handle special characters and return enum supported string
      if (test === "Cat/Dog") return "CatDog";
      return test;
    }
  }
}
</code>```

Body:
I'm trying to create a GraphQL enum type using ApolloStack. But nothing seems to work. For reference, please see the example code.

enum Test {
    ABC
    Dog
    Dog/Cat
}

In the example above, Dog/Cat will cause the server to not work.

Body:
You cannot have a special character in an enum in GraphQL. But you can handle them with a resolver - except there is a gotcha that you cannot resolve a Type in GraphQL, you can only resolve a field of a Type.

For example,

type Foo {
  test: Test
}
enum Test {
  ABC
  Dog
  DogCat
}

and in your resolver for Foo,

{
  Foo: {
    test({ test }) {
      // handle special characters and return enum supported string
      if (test === "Cat/Dog") return "CatDog";
      return test;
    }
  }
}


问:
Getting the exception value in Python
If I have that code:

```<code>try:
    some_method()
except Exception, e:
</code>```

How can I get this Exception value (string
representation I mean)?

答:
use str

```<code>try:
    some_method()
except Exception as e:
    s = str(e)
</code>```

Also, most exception classes will have an args attribute. Often, args[0] will be an error message.

It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.

It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?

Title: Getting the exception value in Python

Body:
If I have that code:

try:
    some_method()
except Exception, e:

How can I get this Exception value (string
representation I mean)?

Body:
use str

try:
    some_method()
except Exception as e:
    s = str(e)

Also, most exception classes will have an args attribute. Often, args[0] will be an error message.

It should be noted that just using str will return an empty string if there's no error message whereas using repr as pyfunc recommends will at least display the class of the exception. My take is that if you're printing it out, it's for an end user that doesn't care what the class is and just wants an error message.

It really depends on the class of exception that you are dealing with and how it is instantiated. Did you have something in particular in mind?


问:
Same table or different table?
My application tracks purchases and sales of inventory. I can't decide if I should use separate tables with auto-increment or the same table with a distinguishing type field with a manual auto-increment id. The tables would store close to identical data. I'm worried that combining the two tables would make it harder to visualize inventory movement in the future. I understand that this is purely for human comfort but I'm not sure if there are other performance related issues as well. I would like to hear opinions from both ends.

Suppose I decide to combine my sales invoice and purchase order tables into the same table, there is a single difference in the columns required - purchase orders store the tax paid while sales invoices use a bool on whether the order is taxed. I have two options:

Use two fields - one bool and one decimal

Use the same field and type cast the values on the application level

Does anyone know if the second would cause more problems?

Thanks

答:
If you're using a single-table design you probably need two columns, one for each purpose, where some records may use column A, and some column B, but the rest are shared.

The real question is if a purchase order and an invoice are really the same thing or not when speaking in terms of data and relationships. Normally a purchase order is related to an invoice, but an invoice may not have an associated purchase order. In some systems you will have a complex arrangement between multiple purchase orders and multiple invoices, it depends on the nature of what's being sold and how it's packaged.

If you're dealing with fairly granular things, like large, expensive items that can be tracked indidually, then your system can get into a lot of detail. If it's tracking inexpensive items sold in large quantities it gets pretty hard to manage that. Things get even more complicated if you're dealing with things that are made-to-order.

I'd do a lot more research about the types of situations you're likely to encounter, order those by probability, and then test your schema against the ugliest cases you're likely to encounter.

Title: Same table or different table?


答:
You could you map method and target the .number class, which will spit out the contents into an array.

```<code>let data = $.map($('.number'), function(elem) {
    return $(elem).text();
});

console.log(data);
</code>```

Body:
You could you map method and target the .number class, which will spit out the contents into an array.

let data = $.map($('.number'), function(elem) {
    return $(elem).text();
});

console.log(data);