问:
Google oauth not returning email passport authentication
I am trying to make a sign in with google button using passport module of node js. I am trying to get person's email id, name, profile pic. I am trying to download pic to local server. Google is not returning email id even after adding 'email' to scope and nor the returned link for profile pic is working. I have looked into various answers to this question but all say to include userinfo.email. It has been deprecated now. As per google documentation new scope parameter is email.

Below is my code. Any help is appreciated.

Passport

```<code>passport.use(new GoogleStrategy({

    clientID        : configAuth.googleAuth.clientID,
    clientSecret    : configAuth.googleAuth.clientSecret,
    callbackURL     : configAuth.googleAuth.callbackURL,
},
function(token, refreshToken, profile, done) {

    // make the code asynchronous
    // User.findOne won't fire until we have all our data back from Google
    process.nextTick(function() {

        // try to find the user based on their google id
        User.findOne({ 'google.id' : profile.id }, function(err, user) {
            if (err)
                return done(err);

            if (user) {

                // if a user is found, log them in
                return done(null, user);
            } else {
                // if the user isnt in our database, create a new user
                var newUser          = new User();
                console.log(profile);
                //JSON.parse(profile);
                // set all of the relevant information
                newUser.google.id    = profile.id;
                newUser.google.token = profile.token;
                newUser.google.name  = profile.displayName;
                newUser.google.uname = profile.emails[0].value; // pull the first email
                newUser.google.dp    = profile._json.picture;
                console.log('url is');
                console.log(newUser.google.name);
                console.log(newUser.google.dp);
                //console.log(profile.picture);
                Download(newUser.google.uname, newUser.google.dp,function(err){
                    if(err)
                        console.log('error in dp');
                    else
                        console.log('Profile Picture downloaded');
                });

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }
        });
    });

}));
};
</code>```

routes.js

```<code>    app.get('/connect/google', passport.authorize('google', { scope : ['profile', 'email'] }));

    // the callback after google has authorized the user
    app.get('/connect/google/callback',
        passport.authorize('google', {
            successRedirect : '/profile',
            failureRedirect : '/'
        }));
</code>```

download.js

```<code>    module.exports = function(username, uri, callback){
var destination;

request(uri).pipe(fs.createWriteStream("./downloads/"+username+".png"))
.on('close', function(){
    console.log("saving process is done!");
});
</code>```

答:
The above answer definitely works, there is also one more way to approach this.

```<code>app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);
</code>```

In your routes.js with the profile add email.

This should resolve your issue.

Body:
I am trying to make a sign in with google button using passport module of node js. I am trying to get person's email id, name, profile pic. I am trying to download pic to local server. Google is not returning email id even after adding 'email' to scope and nor the returned link for profile pic is working. I have looked into various answers to this question but all say to include userinfo.email. It has been deprecated now. As per google documentation new scope parameter is email.

Below is my code. Any help is appreciated.

Passport

passport.use(new GoogleStrategy({

    clientID        : configAuth.googleAuth.clientID,
    clientSecret    : configAuth.googleAuth.clientSecret,
    callbackURL     : configAuth.googleAuth.callbackURL,
},
function(token, refreshToken, profile, done) {

    // make the code asynchronous
    // User.findOne won't fire until we have all our data back from Google
    process.nextTick(function() {

        // try to find the user based on their google id
        User.findOne({ 'google.id' : profile.id }, function(err, user) {
            if (err)
                return done(err);

            if (user) {

                // if a user is found, log them in
                return done(null, user);
            } else {
                // if the user isnt in our database, create a new user
                var newUser          = new User();
                console.log(profile);
                //JSON.parse(profile);
                // set all of the relevant information
                newUser.google.id    = profile.id;
                newUser.google.token = profile.token;
                newUser.google.name  = profile.displayName;
                newUser.google.uname = profile.emails[0].value; // pull the first email
                newUser.google.dp    = profile._json.picture;
                console.log('url is');
                console.log(newUser.google.name);
                console.log(newUser.google.dp);
                //console.log(profile.picture);
                Download(newUser.google.uname, newUser.google.dp,function(err){
                    if(err)
                        console.log('error in dp');
                    else
                        console.log('Profile Picture downloaded');
                });

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }
        });
    });

}));
};

routes.js

    app.get('/connect/google', passport.authorize('google', { scope : ['profile', 'email'] }));

    // the callback after google has authorized the user
    app.get('/connect/google/callback',
        passport.authorize('google', {
            successRedirect : '/profile',
            failureRedirect : '/'
        }));

download.js

    module.exports = function(username, uri, callback){
var destination;

request(uri).pipe(fs.createWriteStream("./downloads/"+username+".png"))
.on('close', function(){
    console.log("saving process is done!");
});

Body:
The above answer definitely works, there is also one more way to approach this.

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] })
);

In your routes.js with the profile add email.

This should resolve your issue.


来源: stackexchange

问:
Apache HTTP 500 but When Refresh Render Properly
I have a website (mobile web) running in 2 server and 1 balancer with haproxy, OS ubuntu 10.10

Apache Configurations:

```<code>Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15

StartServers          5
MinSpareServers       5
MaxSpareServers      10
MaxClients          150
MaxRequestsPerChild   0
</code>```

The site is running well but suddenly now often it return blank page HTTP 500 (20 bytes in 30-50ms) with no error messages, but when i refresh it rendered properly.

does anyone have a clue on where it possibly goes wrong?

Update:

I dont know if this relevance but anytime it could not be loaded browsers push me to download the content, and when i checked the downloaded file (name: Random_Chars.~.part) i found that in the header of the HTML these codes added by browser

```
meta http-equiv="Content-Type" content="text/html; charset=utf-8"
meta name="viewport" content="width = device-width, maximum-scale = 1.0, initial-scale = 1.0"
meta name="apple-mobile-web-app-capable" content="yes"
--- ADDED BY BROWSER --
link href="styles/reset.css" rel="stylesheet" type="text/css"
link href="styles/base.css" rel="stylesheet" type="text/css"
script type="text/javascript" src="scripts/templates.js"
script type="text/javascript"
function init() {
var mySlideshow = new Slideshow ("slideshow", 0, true);
var myToggle = new ToggleSwitch(["toggler1","toggler2","toggler3"]);
var myStyleTweaks = new StyleTweaker();
myStyleTweaks.add("Series60/5.0", "styles/tweaks/S605th.css");
myStyleTweaks.add("Series60/3.2", "styles/tweaks/S603rdFP2.css");
myStyleTweaks.add("AppleWebKit/420+", "styles/tweaks/S406th.css");
myStyleTweaks.add("N900", "styles/tweaks/maemo.css");
myStyleTweaks.add("Firefox/3.0a1 Tablet browser 0.3.7", "styles/tweaks/maemo.css");
myStyleTweaks.add("Opera Mini/4", "styles/tweaks/operamini.css");
myStyleTweaks.tweak();
}
addEvent("onload",init);
/script
```

In Apache Error Logs i found this line:

```
[client ip] File does not exist: /var/www/http:, referer: http://domain.com/search
```

note file filename "http:"

its sometimes not response 500 but 200 OK but the content is blank until i refresh few times
Any help will be appreciated.

答:
Check the error log of your server, it may contain helpful error messages. Don't forget to enable logging (PHP's log_errors=1; phpSettings.log_errors=1 in ZF config).

The script seemingly crashes before having a chance to set the Content-Type header, so the browser don't known what to do with the response, and this is why you see a download dialog.

ContentLicense: CC BY-SA 2.5

Body:
I have a website (mobile web) running in 2 server and 1 balancer with haproxy, OS ubuntu 10.10

Apache Configurations:

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15

StartServers          5
MinSpareServers       5
MaxSpareServers      10
MaxClients          150
MaxRequestsPerChild   0

The site is running well but suddenly now often it return blank page HTTP 500 (20 bytes in 30-50ms) with no error messages, but when i refresh it rendered properly.

does anyone have a clue on where it possibly goes wrong?

Update:

I dont know if this relevance but anytime it could not be loaded browsers push me to download the content, and when i checked the downloaded file (name: Random_Chars.~.part) i found that in the header of the HTML these codes added by browser

meta http-equiv="Content-Type" content="text/html; charset=utf-8"
meta name="viewport" content="width = device-width, maximum-scale = 1.0, initial-scale = 1.0"
meta name="apple-mobile-web-app-capable" content="yes"
--- ADDED BY BROWSER --
link href="styles/reset.css" rel="stylesheet" type="text/css"
link href="styles/base.css" rel="stylesheet" type="text/css"
script type="text/javascript" src="scripts/templates.js"
script type="text/javascript"
function init() {
var mySlideshow = new Slideshow ("slideshow", 0, true);
var myToggle = new ToggleSwitch(["toggler1","toggler2","toggler3"]);
var myStyleTweaks = new StyleTweaker();
myStyleTweaks.add("Series60/5.0", "styles/tweaks/S605th.css");
myStyleTweaks.add("Series60/3.2", "styles/tweaks/S603rdFP2.css");
myStyleTweaks.add("AppleWebKit/420+", "styles/tweaks/S406th.css");
myStyleTweaks.add("N900", "styles/tweaks/maemo.css");
myStyleTweaks.add("Firefox/3.0a1 Tablet browser 0.3.7", "styles/tweaks/maemo.css");
myStyleTweaks.add("Opera Mini/4", "styles/tweaks/operamini.css");
myStyleTweaks.tweak();
}
addEvent("onload",init);
/script

In Apache Error Logs i found this line:

[client ip] File does not exist: /var/www/http:, referer: http://domain.com/search

note file filename "http:"

its sometimes not response 500 but 200 OK but the content is blank until i refresh few times
Any help will be appreciated.


问:
SQLite creating an AFTER UPDATE Trigger
I'm trying to create an SQLite trigger that sets the field FlagPayment to 1 automatically every time a player reaches 10 points, however, apparently, I have a syntax error.

```<code>CREATE TRIGGER aft_update AFTER UPDATE ON Player
FOR EACH ROW WHEN (NEW.ParticipationPoints % 10 = 0) and (NEW.ParticipationPoints > 0)
BEGIN
    UPDATE Player SET FlagPayment = 1 WHERE ID = NEW.ID
END;
</code>```

This is the outcome:

near "END": syntax error: CREATE TRIGGER aft_update AFTER UPDATE ON
  Player FOR EACH ROW WHEN (NEW.ParticipationPoints % 10 = 0) and
  (NEW.ParticipationPoints > 0) BEGIN   UPDATE Player SET FlagPayment = 1
  WHERE ID = NEW.ID END

答:
As shown in the documentation, all statements in the trigger body must be terminated with a semicolon:</p>

```<code>BEGIN
    UPDATE Player SET FlagPayment = 1 WHERE ID = NEW.ID;
END;                                                   ^
</code>```

ContentLicense: CC BY-SA 3.0

Title: SQLite creating an AFTER UPDATE Trigger

Body:
I'm trying to create an SQLite trigger that sets the field FlagPayment to 1 automatically every time a player reaches 10 points, however, apparently, I have a syntax error.

CREATE TRIGGER aft_update AFTER UPDATE ON Player
FOR EACH ROW WHEN (NEW.ParticipationPoints % 10 = 0) and (NEW.ParticipationPoints > 0)
BEGIN
    UPDATE Player SET FlagPayment = 1 WHERE ID = NEW.ID
END;

This is the outcome:

near "END": syntax error: CREATE TRIGGER aft_update AFTER UPDATE ON
  Player FOR EACH ROW WHEN (NEW.ParticipationPoints % 10 = 0) and
  (NEW.ParticipationPoints > 0) BEGIN   UPDATE Player SET FlagPayment = 1
  WHERE ID = NEW.ID END

Body:
As shown in the documentation, all statements in the trigger body must be terminated with a semicolon:

BEGIN
    UPDATE Player SET FlagPayment = 1 WHERE ID = NEW.ID;
END;                                                   ^


问:
PDFBOX : U+000A ('controlLF') is not available in this font Helvetica encoding: WinAnsiEncoding
When trying to print a PDF page using Java and the org.apache.pdfbox library, I get this error:

PDFBOX : U+000A ('controlLF') is not available in this font Helvetica encoding: WinAnsiEncoding

答:
if you are trying to set a new line using "\n" in a string  . you can try         PDPageContentStream.newLineAtOffset(x,y)   to add a new line

```<code>  PDFont font =  PDType1Font.HELVETICA ;

  PDDocument doc    = new PDDocument();
  PDPage page = new PDPage();
  PDPageContentStream content = new PDPageContentStream(doc, page);
  content.beginText();
  content.moveTextPositionByAmount(10, 700);
  content.setFont(font, 12);
  content.drawString("start text   ");
  content.newLineAtOffset(0, -15);
  content.drawString("text in new line  ");
  content.endText();
  content.close();
  doc.addPage(page);
  doc.save("file.pdf");
</code>```

and the pdf

Body:
if you are trying to set a new line using "\n" in a string  . you can try         PDPageContentStream.newLineAtOffset(x,y)   to add a new line

  PDFont font =  PDType1Font.HELVETICA ;

  PDDocument doc    = new PDDocument();
  PDPage page = new PDPage();
  PDPageContentStream content = new PDPageContentStream(doc, page);
  content.beginText();
  content.moveTextPositionByAmount(10, 700);
  content.setFont(font, 12);
  content.drawString("start text   ");
  content.newLineAtOffset(0, -15);
  content.drawString("text in new line  ");
  content.endText();
  content.close();
  doc.addPage(page);
  doc.save("file.pdf");

and the pdf


问:
C# check if variable only contains given string
I am trying to use a variable called game.PlayMode which contains a semicolon-separated list of Play Modes input by the user. The variable can literally contain anything.

An example value:

```<code>Single Player; 2-Player; 3-Player; Co-Op; Versus; Alternate
</code>```

I want to check if game.PlayMode ONLY contains Single Player but I am not sure how to do that.

So far:

```<code>if (game.Playmode.Contains("Single Player"))
        {
           Players = "1";
        }
</code>```

But I know this will also return true with the example value above. How can I make sure my code returns true only if the string is an exact match?

答:
If the variable Playmode only contains "Single Player" it is equal to that string, right?

```<code>if (game.Playmode.Trim().Replace(";", "")  == "Single Player")
{
    Players = "1";
}
</code>```

.. and just in case if there is a semicolon, let's remove it.

Body:
I am trying to use a variable called game.PlayMode which contains a semicolon-separated list of Play Modes input by the user. The variable can literally contain anything.

An example value:

Single Player; 2-Player; 3-Player; Co-Op; Versus; Alternate

I want to check if game.PlayMode ONLY contains Single Player but I am not sure how to do that.

So far:

if (game.Playmode.Contains("Single Player"))
        {
           Players = "1";
        }

But I know this will also return true with the example value above. How can I make sure my code returns true only if the string is an exact match?

Body:
If the variable Playmode only contains "Single Player" it is equal to that string, right?

if (game.Playmode.Trim().Replace(";", "")  == "Single Player")
{
    Players = "1";
}

.. and just in case if there is a semicolon, let's remove it.


问:
Elasticsearch Python API results in "search() missing 1 required positional argument" on a simple query
I am desperately trying to perform a simple search operation on elasticsearch, but fail since hours. This is my code:

```<code>res = es.search(index="people", doc_type="test", body={"query":{"match":{"name": "john"}}})
</code>```

I saw this many times on the internet, but I get always an error and have no clue what is wrong with my code snippet.

```<code>Traceback (most recent call last):
  File "./es_request.py", line 14, in <module>
    res = es.search(index="people", doc_type="test", body={"query":{"match":{"name": "john"}}})
  File "/usr/local/lib/python3.4/dist-packages/pyelasticsearch/client.py", line 93, in decorate
    return func(*args, query_params=query_params, **kwargs)
TypeError: search() missing 1 required positional argument: 'query'
</code>```

Where do I have to write the required 'query'? I am trying to perform the search for name and last name.

答:
The search method from pyelasticsearch library (which you are using) calls the query argument query, not body:

```<code> query = {"query": {"match": {"name": "john"}}}
 es.search(index="people", doc_type="test", query=query)
 es.search(query, index="people", doc_type="test")  # you can also do this
</code>```

I think you meant to use the official elasticsearch library, with which your code works perfectly fine (to add more confusion, its documentation is located at elasticsearch-py.readthedocs.io).

Both libraries export the same module name, so things can sometimes sort of work when you use the wrong one. This is not a coincidence, see this article on their history and differences. Installing the official client is easy as:

```<code>pip uninstall pyelasticsearch
pip install elasticsearch
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am desperately trying to perform a simple search operation on elasticsearch, but fail since hours. This is my code:

res = es.search(index="people", doc_type="test", body={"query":{"match":{"name": "john"}}})

I saw this many times on the internet, but I get always an error and have no clue what is wrong with my code snippet.

Traceback (most recent call last):
  File "./es_request.py", line 14, in <module>
    res = es.search(index="people", doc_type="test", body={"query":{"match":{"name": "john"}}})
  File "/usr/local/lib/python3.4/dist-packages/pyelasticsearch/client.py", line 93, in decorate
    return func(*args, query_params=query_params, **kwargs)
TypeError: search() missing 1 required positional argument: 'query'

Where do I have to write the required 'query'? I am trying to perform the search for name and last name.

Body:
The search method from pyelasticsearch library (which you are using) calls the query argument query, not body:

 query = {"query": {"match": {"name": "john"}}}
 es.search(index="people", doc_type="test", query=query)
 es.search(query, index="people", doc_type="test")  # you can also do this

I think you meant to use the official elasticsearch library, with which your code works perfectly fine (to add more confusion, its documentation is located at elasticsearch-py.readthedocs.io).

Both libraries export the same module name, so things can sometimes sort of work when you use the wrong one. This is not a coincidence, see this article on their history and differences. Installing the official client is easy as:

pip uninstall pyelasticsearch
pip install elasticsearch


问:
Change value for nested dictionary key
I've got following var of which I need to change/update for example the 'dateTime' value of the key 'end' with a value the user has put in.

```<code> var calendarEvent = [
        "subject": "Let's go for lunch",
        "body": [

                "contentType": "HTML",
                "content": "Does late morning work for you?",

        ],
        "start": [

                "dateTime":"2017-12-10T12:55:00",
                "timeZone": "W. Europe Standard Time"

        ],
        "end": [

                "dateTime": "2017-12-10T14:00:00",
                "timeZone": "W. Europe Standard Time"

        ],
        "location": [

                "displayName": "Antwerpen"

        ],
        "attendees": [],
] as [String: AnyObject]
</code>```

Let's say we do not care about the user input - as it is merely a String - and just want to replace the value with the word 'yea boi'.

How can I do this?

答:
The least error-prone, easiest, and most portable way is to define structs and use the Codable protocol along with JsonEncoder and JsonDecoder to read and write the JSON string for your endpoint. Then if you need to change a certain key you can simply treat it as any other struct and change it directly.

```<code>import Foundation

// structures for encoding/decoding

struct Body: Codable {
  let contentType: String
  let content: String
}

struct Time: Codable {
  let dateTime: String
  let timeZone: String
}

struct Location: Codable {
  let displayName: String
}

struct CalendarEvent: Codable {
  var subject: String // mutable
  let body: Body
  let start: Time
  let end: Time
  let location: Location
  let attendees: [String]
}

// set up structure

var event = CalendarEvent(subject: "Let's go for lunch",
                body: Body(contentType: "HTML",
                            content: "Does late morning work for you?"),
                start: Time(dateTime:"2017-12-10T12:55:00",
                             timeZone: "W. Europe Standard Time"),
                end: Time(dateTime:"2017-12-10T14:00:00",
                           timeZone: "W. Europe Standard Time"),
                location: Location(displayName: "Antwerpen"),
                attendees: [])

// change the subject
event.subject = "yea boi"

// create encoder

let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = [.prettyPrinted, .sortedKeys]

// encode, convert to a String, and print it

if let jsonData = try? jsonEncoder.encode(event),
  let jsonString = String(data: jsonData, encoding: .utf8) {
  print(jsonString)
}

// output

/* {
     "attendees" : [],
     "body" : {
       "content" : "Does late morning work for you?",
       "contentType" : "HTML"
     },
     "end" : {
       "dateTime" : "2017-12-10T14:00:00",
       "timeZone" : "W. Europe Standard Time"
     },
     "location" : {
       "displayName" : "Antwerpen"
     },
     "start" : {
       "dateTime" : "2017-12-10T12:55:00",
       "timeZone" : "W. Europe Standard Time"
     },
     "subject" : "yea boi"
   }
*/
</code>```

Note the mutated subject, changed from "Let's go for lunch" to "yea boi".

Title: Change value for nested dictionary key

Body:
I've got following var of which I need to change/update for example the 'dateTime' value of the key 'end' with a value the user has put in.

 var calendarEvent = [
        "subject": "Let's go for lunch",
        "body": [

                "contentType": "HTML",
                "content": "Does late morning work for you?",

        ],
        "start": [

                "dateTime":"2017-12-10T12:55:00",
                "timeZone": "W. Europe Standard Time"

        ],
        "end": [

                "dateTime": "2017-12-10T14:00:00",
                "timeZone": "W. Europe Standard Time"

        ],
        "location": [

                "displayName": "Antwerpen"

        ],
        "attendees": [],
] as [String: AnyObject]

Let's say we do not care about the user input - as it is merely a String - and just want to replace the value with the word 'yea boi'.

How can I do this?

Body:
The least error-prone, easiest, and most portable way is to define structs and use the Codable protocol along with JsonEncoder and JsonDecoder to read and write the JSON string for your endpoint. Then if you need to change a certain key you can simply treat it as any other struct and change it directly.

import Foundation

// structures for encoding/decoding

struct Body: Codable {
  let contentType: String
  let content: String
}

struct Time: Codable {
  let dateTime: String
  let timeZone: String
}

struct Location: Codable {
  let displayName: String
}

struct CalendarEvent: Codable {
  var subject: String // mutable
  let body: Body
  let start: Time
  let end: Time
  let location: Location
  let attendees: [String]
}

// set up structure

var event = CalendarEvent(subject: "Let's go for lunch",
                body: Body(contentType: "HTML",
                            content: "Does late morning work for you?"),
                start: Time(dateTime:"2017-12-10T12:55:00",
                             timeZone: "W. Europe Standard Time"),
                end: Time(dateTime:"2017-12-10T14:00:00",
                           timeZone: "W. Europe Standard Time"),
                location: Location(displayName: "Antwerpen"),
                attendees: [])

// change the subject
event.subject = "yea boi"

// create encoder

let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = [.prettyPrinted, .sortedKeys]

// encode, convert to a String, and print it

if let jsonData = try? jsonEncoder.encode(event),
  let jsonString = String(data: jsonData, encoding: .utf8) {
  print(jsonString)
}

// output

/* {
     "attendees" : [],
     "body" : {
       "content" : "Does late morning work for you?",
       "contentType" : "HTML"
     },
     "end" : {
       "dateTime" : "2017-12-10T14:00:00",
       "timeZone" : "W. Europe Standard Time"
     },
     "location" : {
       "displayName" : "Antwerpen"
     },
     "start" : {
       "dateTime" : "2017-12-10T12:55:00",
       "timeZone" : "W. Europe Standard Time"
     },
     "subject" : "yea boi"
   }
*/

Note the mutated subject, changed from "Let's go for lunch" to "yea boi".


问:
How to run sql scripts from a pl sql procedure
I have a procedure like :

```<code>CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
END;
</code>```

I want to run some sql scripts stored in the current directory.
I could run them from sqlplus with '@scriptname.sql' but how can i do it from inside the procedure ?  For ex:

```<code>CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
  @scriptname.sql

END;
</code>```

This doesn't seem to work ! Is there a specific to run sql scripts from pl/sql procedures ?

答:
You could execute an OS command to start SQLPlus and have that execute the scripts.  You can pass a filename into SQLplus at start up and it will execute it.

Google External Procedures and extproc or this article.  Or something like call OS command with Java

Body:
I have a procedure like :

CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
END;

I want to run some sql scripts stored in the current directory.
I could run them from sqlplus with '@scriptname.sql' but how can i do it from inside the procedure ?  For ex:

CREATE OR REPLACE PROCEDURE test is
BEGIN

  DBMS_OUTPUT.PUT_LINE('This is a Test');
  @scriptname.sql

END;

This doesn't seem to work ! Is there a specific to run sql scripts from pl/sql procedures ?


问:
When pressed 'Enter', sum the input and clear it
I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared

The amounts entered must be added together and their total must be shown in a second text box.

my HTML:

```<code><input type="text" id="input">
<p>Uw totaal:</p>
<input type="text" id="output">
</code>```

My JS:

```<code>input = document.getElementById("input");
        input.onkeypress = function(event) {
            ceckKey(event);
        };

        function ceckKey(e) {
            // check for enter: e.key is for Firefox
            // if true, make input empty
            if (e.keyCode == 13 || e.key == 13) {
                input.value = "";
            }
            var number = +input.value;
            return number;
        }

        var total = 0
        total += checkKey();
        document.getElementById("output").value = total;
</code>```

The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.

I hope you guys can help!

答:
You are clearing the value of input before calculating the total. I have updated your code little bit to work as you intended.</p>

```<code>input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(event) {
    checkKey(event);
};
function checkKey(e) {
  // check for enter: e.key is for Firefox
  // if true, make input empty
  if (e.keyCode == 13 || e.key == 13) {
    // Note : in the begining the output text box is empty, so while output is empty i have assign 0 as its value.
    outputValue = (output.value == '') ? 0 : output.value;
    total = parseInt(outputValue) + parseInt(input.value);
    input.value = "";

    // To update the total in output text box
    document.getElementById("output").value = total;

  }
}
</code>```

Body:
I'm in the begin fase of learning JS. I'm trying to make a page were the user can put numbers in a text field. The user can press enter to add another number. When the user pressed enter the input field need to be cleared

The amounts entered must be added together and their total must be shown in a second text box.

my HTML:

<input type="text" id="input">

Uw totaal:

<input type="text" id="output">

My JS:

input = document.getElementById("input");
        input.onkeypress = function(event) {
            ceckKey(event);
        };

        function ceckKey(e) {
            // check for enter: e.key is for Firefox
            // if true, make input empty
            if (e.keyCode == 13 || e.key == 13) {
                input.value = "";
            }
            var number = +input.value;
            return number;
        }

        var total = 0
        total += checkKey();
        document.getElementById("output").value = total;

The keypress works in every browser. The problem is that i cannot sum the numbers. If i put it in the keypress function, the number will be cleared everytime you hit enter again.

I hope you guys can help!

Body:
You are clearing the value of input before calculating the total. I have updated your code little bit to work as you intended.

input = document.getElementById("input");
output = document.getElementById("output");
input.onkeypress = function(event) {
    checkKey(event);
};
function checkKey(e) {
  // check for enter: e.key is for Firefox
  // if true, make input empty
  if (e.keyCode == 13 || e.key == 13) {
    // Note : in the begining the output text box is empty, so while output is empty i have assign 0 as its value.
    outputValue = (output.value == '') ? 0 : output.value;
    total = parseInt(outputValue) + parseInt(input.value);
    input.value = "";

    // To update the total in output text box
    document.getElementById("output").value = total;

  }
}


问:
Django Model Form does not display Image field properly and does not Post it
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates.

Here is how it looks

enter image description here

Here is the definition in the Model.

```<code>picture = models.ImageField(upload_to=user_directory_path)
</code>```

So when Django creates the Form it does it in that weird way for the File filed

How should I then define the Field for File in the Model? Or where is the error lying?

The Form had this instruction>

```<code>{% load widget_tweaks %}
<form method="post" action="{% url 'book_create' %}" class="js-book-create-form" enctype="multipart/form-data">

  {% csrf_token %}

  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      <span aria-hidden="true">×</span>
    </button>
    <h4 class="modal-title">Create a new book</h4>
  </div>
  <div class="modal-body">
    {% for field in form %}
      <div class="form-group{% if field.errors %} has-error{% endif %}">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {% render_field field class="form-control" %}
        {% for error in field.errors %}
          <p class="help-block">{{ error }}</p>
        {% endfor %}
      </div>
    {% endfor %}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create book</button>
  </div>
</form>
</code>```

The handling of the form was like this:

```<code>data = dict()

    if request.method == 'POST':
        form = NewStockOfBookssForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False
</code>```

答:
The look of the File Upload for the picture in the Form is not OK as
  the button is inside the field.

As for this problem, the solution I found is to add a custom css class to the button, an then tweak as neccesary. The whole field span acts as a button, but it doesn't look awful.

Body:
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates.

Here is how it looks

enter image description here

Here is the definition in the Model.

picture = models.ImageField(upload_to=user_directory_path)

So when Django creates the Form it does it in that weird way for the File filed

How should I then define the Field for File in the Model? Or where is the error lying?

The Form had this instruction>

{% load widget_tweaks %}
<form method="post" action="{% url 'book_create' %}" class="js-book-create-form" enctype="multipart/form-data">

  {% csrf_token %}

    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
      ×
    </button>

Create a new book

    {% for field in form %}

        {{ field.label }}
        {% render_field field class="form-control" %}
        {% for error in field.errors %}

{{ error }}

        {% endfor %}

    {% endfor %}

    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary">Create book</button>

</form>

The handling of the form was like this:

data = dict()

    if request.method == 'POST':
        form = NewStockOfBookssForm(request.POST, request.FILES)
        if form.is_valid():

            form.save()
            data['form_is_valid'] = True
        else:
            data['form_is_valid'] = False


问:
Change element width dynamically on Angular 5
I have two tables.

I want to set the width of the column of one table to equal the width of the column of another table.

Like this :

```<code>    <table class="table-header table">
        <thead class="table-bordered">
          <tr>
              <th>Name</th>
              <th>Last Name</th>
              <th>Gender</th>
              <th>Education</th>
            </tr>
        </thead>
      </table>
</code>```

And the other table:

```<code>          <table class="table-header table">
         <thead class="table-bordered">
          <tr>
              <th>Name</th>
              <th>Last Name</th>
              <th>Gender</th>
              <th>Education</th>
            </tr>
        </thead>
      <tbody>
         <tr>
            <td> Ross </td>
             <td> Ross </td>
            <td> M</td>
            <td> BsC </td>
        ..
      </tbody>
</code>```

What I want to do is have all the headers of the first table to always equal the headers width of the second table.
Because on the second table they get resized based on the content.

So I know I can add a HostListener('window:resize')
But how do I assign these values in Angular ?
So that they're always the same. As if it's a duplicate of one another.
Any guidance?

答:
First you need to get a reference of your source table columns and your target table columns, you can do this with a template variables and the @ViewChildren decorator.

In your template:

```<code><!-- Source table -->
<table class="table-header table">
  <thead class="table-bordered">
    <tr>
        <th #sourceTh>Name</th>
        <th #sourceTh>Last Name</th>
        <th #sourceTh>Gender</th>
        <th #sourceTh>Education</th>
      </tr>
  </thead>
</table>

<!-- Target table -->
<table class="table-header table">
  <thead class="table-bordered">
    <tr>
      <th #targetTh>Name</th>
      <th #targetTh>Last Name</th>
      <th #targetTh>Gender</th>
      <th #targetTh>Education</th>
    </tr>
  </thead>
  <tbody>
    <!-- table body content -->
  </tbody>
</table>
</code>```

And then inside you component class

```<code>@Component({ ... })
export class MyClass {
  @ViewChildren('sourceTh')
  sourceTh: QueryList<ElementRef>;

  @ViewChildren('targetTh')
  targetTh: QueryList<ElementRef>;

  // ...
}
</code>```

This way you can get a QueryList of elements references, so you can access the nativeElement of each table heading (the actual DOM Nodes) and get each individual offsetWidth. Notice @ViewChild and @ViewChildren decorated properties are only available after the AfterViewInit lifecycle hook. A QueryList is an array-like data structure and it has some array methods like forEach, map, etc...

Inside ngAfterViewInit you want to iterate over the list of source table header cells, get each one width and then iterate over target header cell list and set the width. For this, you can use the setStyle method from Renderer2. Then you can call this method also on window.resize event or whatever

```<code>@Component({ ... })
export class MyClass implements AfterViewInit {
  @ViewChildren('sourceTh')
  sourceTh: QueryList<ElementRef>;

  @ViewChildren('targetTh')
  targetTh: QueryList<ElementRef>;

  constructor( private renderer: Renderer2 ) {}

  ngAfterViewInit() {
    this.resizeColumns();
  }

  resizeColumns() {
    let widths = this.sourceTh.map(th => th.nativeElement.offsetWidth);

    this.targetTh.forEach((th, index) => {
      this.renderer.setStyle(
        th.nativeElement,
        'width',
        `${widths[index]}px`
      );
    });
  }
}
</code>```

Body:
I have two tables.

I want to set the width of the column of one table to equal the width of the column of another table.

Like this :

              Name
              Last Name
              Gender
              Education

And the other table:

              Name
              Last Name
              Gender
              Education

             Ross
              Ross
             M
             BsC
        ..

What I want to do is have all the headers of the first table to always equal the headers width of the second table.
Because on the second table they get resized based on the content.

So I know I can add a HostListener('window:resize')
But how do I assign these values in Angular ?
So that they're always the same. As if it's a duplicate of one another.
Any guidance?

Body:
First you need to get a reference of your source table columns and your target table columns, you can do this with a template variables and the @ViewChildren decorator.

In your template:

<!-- Source table -->
<table class="table-header table">
  <thead class="table-bordered">
    <tr>
        <th #sourceTh>Name</th>
        <th #sourceTh>Last Name</th>
        <th #sourceTh>Gender</th>
        <th #sourceTh>Education</th>
      </tr>
  </thead>
</table>

<!-- Target table -->
<table class="table-header table">
  <thead class="table-bordered">
    <tr>
      <th #targetTh>Name</th>
      <th #targetTh>Last Name</th>
      <th #targetTh>Gender</th>
      <th #targetTh>Education</th>
    </tr>
  </thead>
  <tbody>
    <!-- table body content -->
  </tbody>
</table>

And then inside you component class

@Component({ ... })
export class MyClass {
  @ViewChildren('sourceTh')
  sourceTh: QueryList<ElementRef>;

  @ViewChildren('targetTh')
  targetTh: QueryList<ElementRef>;

  // ...
}

This way you can get a QueryList of elements references, so you can access the nativeElement of each table heading (the actual DOM Nodes) and get each individual offsetWidth. Notice @ViewChild and @ViewChildren decorated properties are only available after the AfterViewInit lifecycle hook. A QueryList is an array-like data structure and it has some array methods like forEach, map, etc...

Inside ngAfterViewInit you want to iterate over the list of source table header cells, get each one width and then iterate over target header cell list and set the width. For this, you can use the setStyle method from Renderer2. Then you can call this method also on window.resize event or whatever

@Component({ ... })
export class MyClass implements AfterViewInit {
  @ViewChildren('sourceTh')
  sourceTh: QueryList<ElementRef>;

  @ViewChildren('targetTh')
  targetTh: QueryList<ElementRef>;

  constructor( private renderer: Renderer2 ) {}

  ngAfterViewInit() {
    this.resizeColumns();
  }

  resizeColumns() {
    let widths = this.sourceTh.map(th => th.nativeElement.offsetWidth);

    this.targetTh.forEach((th, index) => {
      this.renderer.setStyle(
        th.nativeElement,
        'width',
        `${widths[index]}px`
      );
    });
  }
}


问:
why SSIS File System Task is not moving the file where I want it
I am trying to archive a file.  included in the image is the settings of my system file task.  I'm trying to send a file whose name is stored in a variable within the loop, and send that file into the requisite folder.

The file is supposed to land in F:\DATA\ARCHIVE\WELLBORE\ using the filename it was given.  However, it keeps landing in F:\DATA\ARCHIVE with the NAME WELLBORE, which is not what I am looking for.

What do I have missing?
Thanks

答:
Problem

The issue is when you select Move File so you have to select the source full file path and the destination full file path, so the destination variable should contains the destination full path (with file name) and if the variable contains a folder path, the folder name will be considered as a filename and it will throw an exception.

Solution

Create a new variable @[User::DestinationFile] and assign the following expression to it:

```<code>@[User::ArchiveFolder] + RIGHT( @[User::WellBoreFile] , FINDSTRING(REVERSE( @[User::WellBoreFile] ) , "\\", 1) - 1)
</code>```

This expression will add the filename to the destination path. And use this new variable as a Destination

References

SSIS EXPRESSION TO GET FILE NAME FROM FULL PATH

SSIS Expression to get filename from FilePath

Microsoft Docs article*

Body:
Problem

The issue is when you select Move File so you have to select the source full file path and the destination full file path, so the destination variable should contains the destination full path (with file name) and if the variable contains a folder path, the folder name will be considered as a filename and it will throw an exception.

Solution

Create a new variable @[User::DestinationFile] and assign the following expression to it:

@[User::ArchiveFolder] + RIGHT( @[User::WellBoreFile] , FINDSTRING(REVERSE( @[User::WellBoreFile] ) , "\\", 1) - 1)

This expression will add the filename to the destination path. And use this new variable as a Destination

References

SSIS EXPRESSION TO GET FILE NAME FROM FULL PATH

SSIS Expression to get filename from FilePath

Microsoft Docs article*


问:
MaterializeCss changes all input field IDs
Something really peculiar is happening and I can't figure out why.
I'm using materializecss framework for my UI. But for some reason when I'm including any input fields in my HTML like

```<code><div class="col s5">
    <input id="teacher_id" runat="server" type="number" placeholder="Your ID"/>
</div>
</code>```

the id and the names are getting changed to some jibberish like

```<code><div class="col s5">
    <input name="**ctl00$ContentPlaceHolder1$teacher_id**" type="number" id="ContentPlaceHolder1_teacher_id" placeholder="Your ID">
</div>
</code>```

Can someone please help? What am I doing wrong?

(I'm using Asp.net with a master page)

答:
Okay I figured it out.
It wasn't materializecss but insteas asp.net itself.
To refer to the fields from jquery or js i used the following:

```<code>$('#<%= teacher_id.ClientID %>').val('123');
</code>```

Didn't exactly solve the issue, but the workaround calmed some of the concerns ..for now.

Body:
Something really peculiar is happening and I can't figure out why.
I'm using materializecss framework for my UI. But for some reason when I'm including any input fields in my HTML like

    <input id="teacher_id" runat="server" type="number" placeholder="Your ID"/>

the id and the names are getting changed to some jibberish like

    <input name="**ctl00$ContentPlaceHolder1$teacher_id**" type="number" id="ContentPlaceHolder1_teacher_id" placeholder="Your ID">

Can someone please help? What am I doing wrong?

(I'm using Asp.net with a master page)

Body:
Okay I figured it out.
It wasn't materializecss but insteas asp.net itself.
To refer to the fields from jquery or js i used the following:

$('#<%= teacher_id.ClientID %>').val('123');

Didn't exactly solve the issue, but the workaround calmed some of the concerns ..for now.


问:
Cannot log in Neo4j server
On a fresh install of neo4j-community-2.2.4 I get the message "Invalid username or password." when submitting the login form at localhost:7474/browser with the default username neo4j and password neo4j.

I did enable org.neo4j.server.webserver.address=0.0.0.0 and dbms.security.auth_enabled=true with a server stop and start and a browser shift-reload.

I then changed the property org.neo4j.server.webserver.address=127.0.0.1 to match my /etc/hosts and tried on 127.0.0.1:7474/browser but got the same message.

Here is the browser console output:

```<code>Remote Address:127.0.0.1:7474
Request URL:http://localhost:7474/db/data/
Request Method:GET
Status Code:401 Unauthorized
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6,ru;q=0.4,es;q=0.2,sv;q=0.2,nb;q=0.2,et;q=0.2
Authorization:Basic bmVvNGo6bmVvNGo=
Cache-Control:no-cache
Connection:keep-alive
Cookie:languageCodeAdmin=en; PHPSESSID=vcbvfkvj3shajhlh5u2pue9i70; admin_template_phone_client=0; admin_template_touch_client=0; admin_template_model=1
Host:localhost:7474
If-Modified-Since:Wed, 11 Dec 2013 08:00:00 GMT
Pragma:no-cache
Referer:http://localhost:7474/browser/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36
X-stream:true
Response Headersview source
Content-Length:135
Content-Type:application/json; charset=UTF-8
Date:Sat, 19 Sep 2015 09:14:03 GMT
Server:Jetty(9.2.4.v20141103)
WWW-Authenticate:None
{
  "errors" : [ {
    "message" : "Invalid username or password.",
    "code" : "Neo.ClientError.Security.AuthorizationFailed"
  } ]
}
</code>```

So I then tried to change the default password.

To do that, I first disabled the authentication with a dbms.security.auth_enabled=false and a server stop and start.

And I then tried the following curl request:

```<code>curl -H "Accept:application/json; charset=UTF-8" -H "Content-Type: application/json" "http://localhost:7474/user/neo4j/password" -X POST -d "{ \"password\" : \"neo4j\" }" -i
</code>```

But it gives me the response:

```<code>HTTP/1.1 404 Not Found
Date: Sat, 19 Sep 2015 09:25:38 GMT
Access-Control-Allow-Origin: *
Content-Length: 0
Server: Jetty(9.2.4.v20141103)
</code>```

答:
In my case Neo4J windows services was not installed just followed below steps

neo4j.bat install-service

neo4j.bat status

neo4j.bat start

it worked, cheers

Title: Cannot log in Neo4j server

Body:
On a fresh install of neo4j-community-2.2.4 I get the message "Invalid username or password." when submitting the login form at localhost:7474/browser with the default username neo4j and password neo4j.

I did enable org.neo4j.server.webserver.address=0.0.0.0 and dbms.security.auth_enabled=true with a server stop and start and a browser shift-reload.

I then changed the property org.neo4j.server.webserver.address=127.0.0.1 to match my /etc/hosts and tried on 127.0.0.1:7474/browser but got the same message.

Here is the browser console output:

Remote Address:127.0.0.1:7474
Request URL:http://localhost:7474/db/data/
Request Method:GET
Status Code:401 Unauthorized
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,fr;q=0.6,ru;q=0.4,es;q=0.2,sv;q=0.2,nb;q=0.2,et;q=0.2
Authorization:Basic bmVvNGo6bmVvNGo=
Cache-Control:no-cache
Connection:keep-alive
Cookie:languageCodeAdmin=en; PHPSESSID=vcbvfkvj3shajhlh5u2pue9i70; admin_template_phone_client=0; admin_template_touch_client=0; admin_template_model=1
Host:localhost:7474
If-Modified-Since:Wed, 11 Dec 2013 08:00:00 GMT
Pragma:no-cache
Referer:http://localhost:7474/browser/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/37.0.2062.120 Chrome/37.0.2062.120 Safari/537.36
X-stream:true
Response Headersview source
Content-Length:135
Content-Type:application/json; charset=UTF-8
Date:Sat, 19 Sep 2015 09:14:03 GMT
Server:Jetty(9.2.4.v20141103)
WWW-Authenticate:None
{
  "errors" : [ {
    "message" : "Invalid username or password.",
    "code" : "Neo.ClientError.Security.AuthorizationFailed"
  } ]
}

So I then tried to change the default password.

To do that, I first disabled the authentication with a dbms.security.auth_enabled=false and a server stop and start.

And I then tried the following curl request:

curl -H "Accept:application/json; charset=UTF-8" -H "Content-Type: application/json" "http://localhost:7474/user/neo4j/password" -X POST -d "{ \"password\" : \"neo4j\" }" -i

But it gives me the response:

HTTP/1.1 404 Not Found
Date: Sat, 19 Sep 2015 09:25:38 GMT
Access-Control-Allow-Origin: *
Content-Length: 0
Server: Jetty(9.2.4.v20141103)


问:
C++ CreateNamedPipe ERROR_PATH_NOT_FOUND (3)
I am trying to create a named pipe in vc++.
I am used to C and I hope that the error is not just related to me not being familiar with c++.
The code I am using is the following:

```<code>#ifdef DEBUG
printf("%s\n%s\n", this->pipe_name, this->pipe_path);
#endif
this->pipe = CreateNamedPipe(
    this->pipe_path,
    PIPE_ACCESS_DUPLEX,
    PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_NOWAIT,
    1,
    this->pipe_buffer_size_kb * 1024,
    this->pipe_buffer_size_kb * 1024,
    NMPWAIT_USE_DEFAULT_WAIT,
    NULL);

if (this->pipe != INVALID_HANDLE_VALUE) // Setup successful
    return true;

if (GetLastError() != ERROR_PIPE_BUSY)  // Some unexpected error occured
{
#ifdef DEBUG
    printf("Failed to create named pipe: %d\n", GetLastError());
#endif
    return false;
}
</code>```

pipe_buffer_size_kb is 8

The output I am getting is the following:

```<code>>.\run.exe
p0
\\.\rftb\p0
Failed to create named pipe: 3
</code>```

As an IDE I use Microsoft Visual Studio Community 2017 (Product details: Microsoft Visual Basic 2017)
I've used an empty project template and added DEBUG and _CRT_SECURE_NO_WARNINGS as preprocessor definitions.

Any help is appreciated.

答:
The MSDN docs state:

The unique pipe name. This string must have the following form:

\\.\pipe\pipename

The pipename part of the name can include any character other than a backslash, including numbers and special characters. The entire pipe name string can be up to 256 characters long. Pipe names are not case sensitive.

Your pipe name is invalid because it does not match that pattern.

Body:
I am trying to create a named pipe in vc++.
I am used to C and I hope that the error is not just related to me not being familiar with c++.
The code I am using is the following:

#ifdef DEBUG
printf("%s\n%s\n", this->pipe_name, this->pipe_path);
#endif
this->pipe = CreateNamedPipe(
    this->pipe_path,
    PIPE_ACCESS_DUPLEX,
    PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_NOWAIT,
    1,
    this->pipe_buffer_size_kb * 1024,
    this->pipe_buffer_size_kb * 1024,
    NMPWAIT_USE_DEFAULT_WAIT,
    NULL);

if (this->pipe != INVALID_HANDLE_VALUE) // Setup successful
    return true;

if (GetLastError() != ERROR_PIPE_BUSY)  // Some unexpected error occured
{
#ifdef DEBUG
    printf("Failed to create named pipe: %d\n", GetLastError());
#endif
    return false;
}

pipe_buffer_size_kb is 8

The output I am getting is the following:

>.\run.exe
p0
\\.\rftb\p0
Failed to create named pipe: 3

As an IDE I use Microsoft Visual Studio Community 2017 (Product details: Microsoft Visual Basic 2017)
I've used an empty project template and added DEBUG and _CRT_SECURE_NO_WARNINGS as preprocessor definitions.

Any help is appreciated.


问:
How do I access a priority_queue from another class?
My code looks roughly like this:

```<code>#include <queue>
#include <iostream>

using namespace std;

int main() {

priority_queue <String> pq;

otherClass.qPusher();
pq.pop();

}
</code>```

How does qPusher method access priority_queue pq?
I have tried to pass a reference of pq to qPusher, but I can't seem to get the syntax right. Does anyone know how to do this?

答: You would need to pass the queue to the class (probably as a constructor argument, likely as a reference, at the very least as a pointer).</p>

Body:
My code looks roughly like this:

#include <queue>
#include <iostream>

using namespace std;

int main() {

priority_queue <String> pq;

otherClass.qPusher();
pq.pop();

}

How does qPusher method access priority_queue pq?
I have tried to pass a reference of pq to qPusher, but I can't seem to get the syntax right. Does anyone know how to do this?


答:
The commented batch file code below modifies upload2.log from

```<code>-------------------------------------------------------------------------------

 Started : Sat Dec 09 20:40:18 2017

  Source : D:\shareME\test\
     Dest : \\remoteServer\delME\

    Files : test.zip

  Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

------------------------------------------------------------------------------
                       1    D:\shareME\test\
        Newer            181.8 m    test.zip
 56.0%
 56.1%
 56.1%
 56.1%
 56.2%
 56.2%
 56.2%
 56.3%
 56.3%
 56.3%
 56.4%
 56.4%
 56.4%
 56.5%
 56.5%
 56.5%
 68.3%
</code>```

to

```<code>-------------------------------------------------------------------------------

 Started : Sat Dec 09 20:40:18 2017

  Source : D:\shareME\test\
     Dest : \\remoteServer\delME\

    Files : test.zip

  Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

------------------------------------------------------------------------------
                       1    D:\shareME\test\
        Newer            181.8 m    test.zip
  68.3%
</code>```

I hope this is the output you expect.

```<code>@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Define name of log file.
set "LogFile=upload2.log"

rem Does this file exist at all?
if not exist "%LogFile%" goto :EOF

rem Define name of a temporary file created with name of batch
rem file with file extension TMP in folder for temporary files.
set "TmpFile=%TEMP%\%~n0.tmp"

rem Search in log file for lines starting with 0 or more leading spaces,
rem having next at least one digit, followed by 0 or more digits or a point
rem (floating point number), then a percent sign, and 0 or more trailing
rem spaces at end of line using a regular expression. But wanted for output
rem are only those lines NOT matching this expression (inVerted output).
rem The output lines not matching the expression are redirected into the
rem temporary file which is created new or overwritten if existing already.

%SystemRoot%\System32\findstr.exe /V /R /C:"^ *[01234567689][0123456789.]*%% *" "%LogFile%" >"%TmpFile%"

rem Then run again the regular expression search, but this time in a command
rem process in background started by command FOR and with printing to handle
rem STDOUT the lines matching the regular expression captured by FOR.
rem Each captured line is assigned to loop variable I being next assigned
rem to environment variable LastPercentLine. Just the last line found in
rem the log file is of interest for further processing of this batch file.

set "LastPercentLine="
for /F "delims=" %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"^ *[01234567689][0123456789.]*%% *" "%LogFile%" 2^>nul') do set "LastPercentLine=%%I"

rem If a line with a percent value could be found at all in the log file,
rem append this line to the temporary file and replace the log file with
rem the temporary file with just the last percent value line. Otherwise
rem delete the temporary file and keep the log file unmodified.

if defined LastPercentLine (
    echo %LastPercentLine%>>"%TmpFile%"
    move /Y "%TmpFile%" "%LogFile%"
) else del "%TmpFile%"

endlocal
</code>```

Redirecting output of a command or console application written to handle STDOUT to a file results in getting written to file everything output to STDOUT even when the command or application uses special code to move text cursor in console window after output of a line back to beginning of this line to overwrite in console window the just output text with another text.

The output with the percent indication is finally readable in console window as expected because of the special text cursor moving code used by the command/application. But the output redirected into a file contains all output text as the special code to move text cursor to a specific position in console window has no effect on the file.

To get from log file upload2.log just the percent value without leading and trailing spaces the batch file can be reduced for example to:

```<code>@echo off
set "LastPercentValue=0%%"
for /F %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"^ *[01234567689][0123456789.]*%% *" "upload2.log" 2^>nul') do set "LastPercentValue=%%I"
echo %LastPercentValue% copied.
set "LastPercentValue="
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

endlocal /?

findstr /?

for /?

goto /?

if /?

move /?

rem /?

set /?

setlocal /?

Title: What is the reason for different TYPE command behavior in FOR loop?

Body:
I have the following file generated from robocopy:

-------------------------------------------------------------------------------

   ROBOCOPY     ::     Robust File Copy for Windows

-------------------------------------------------------------------------------

 Started : Sat Dec 09 20:40:18 2017

  Source : D:\shareME\test\
     Dest : \\remoteServer\delME\

    Files : test.zip

  Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

------------------------------------------------------------------------------
                       1    D:\shareME\test\
        Newer            181.8 m    test.zip
 56.0%
 56.1%
 56.1%
 56.1%
 56.2%
 56.2%
 56.2%
 56.3%
 56.3%
 56.3%
 56.4%
 56.4%
 56.4%
 56.5%
 56.5%
 56.5%
 .
 .
 .
 *up to
 68.3%

When I use the type command on this log file, I get the following (fully desirable as the unnecessary older % are not displayed):

 -------------------------------------------------------------------------------

 ROBOCOPY     ::     Robust File Copy for Windows

 -------------------------------------------------------------------------------

   Started : Sat Dec 09 20:40:18 2017

    Source : D:\shareME\test\
      Dest : \\remoteServer\delME\

     Files : test.zip

   Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

 ------------------------------------------------------------------------------

                            1    D:\shareME\test\
  68.6%      Newer                181.8 m        test.zip

However, if I put this same command in for loop inside a batch file it displays the older % of file copy progress.

for /f "tokens=1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 delims= " %%a in ('type upload2.log') do ( echo %%a %%b %%c .... %%z )

as seen here

 -------------------------------------------------------------------------------

 ROBOCOPY     ::     Robust File Copy for Windows

 -------------------------------------------------------------------------------

   Started : Sat Dec 09 20:40:18 2017

  Source : D:\shareME\test\
     Dest : \\remoteServer\delME\

    Files : test.zip

   Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

 ------------------------------------------------------------------------------

                            1    D:\shareME\test\
  56.3%      Newer                181.8 m        test.zip

What is the reason for this?

It's mandatory that I use the type command as the file is in use as long as I need to read it.

Body:
The commented batch file code below modifies upload2.log from

-------------------------------------------------------------------------------

 Started : Sat Dec 09 20:40:18 2017

  Source : D:\shareME\test\
     Dest : \\remoteServer\delME\

    Files : test.zip

  Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

------------------------------------------------------------------------------
                       1    D:\shareME\test\
        Newer            181.8 m    test.zip
 56.0%
 56.1%
 56.1%
 56.1%
 56.2%
 56.2%
 56.2%
 56.3%
 56.3%
 56.3%
 56.4%
 56.4%
 56.4%
 56.5%
 56.5%
 56.5%
 68.3%

to

-------------------------------------------------------------------------------

 Started : Sat Dec 09 20:40:18 2017

  Source : D:\shareME\test\
     Dest : \\remoteServer\delME\

    Files : test.zip

  Options : /TEE /COPY:DAT /Z /IS /R:1000000 /W:30

------------------------------------------------------------------------------
                       1    D:\shareME\test\
        Newer            181.8 m    test.zip
  68.3%

I hope this is the output you expect.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem Define name of log file.
set "LogFile=upload2.log"

rem Does this file exist at all?
if not exist "%LogFile%" goto :EOF

rem Define name of a temporary file created with name of batch
rem file with file extension TMP in folder for temporary files.
set "TmpFile=%TEMP%\%~n0.tmp"

rem Search in log file for lines starting with 0 or more leading spaces,
rem having next at least one digit, followed by 0 or more digits or a point
rem (floating point number), then a percent sign, and 0 or more trailing
rem spaces at end of line using a regular expression. But wanted for output
rem are only those lines NOT matching this expression (inVerted output).
rem The output lines not matching the expression are redirected into the
rem temporary file which is created new or overwritten if existing already.

%SystemRoot%\System32\findstr.exe /V /R /C:"^ *[01234567689][0123456789.]*%% *" "%LogFile%" >"%TmpFile%"

rem Then run again the regular expression search, but this time in a command
rem process in background started by command FOR and with printing to handle
rem STDOUT the lines matching the regular expression captured by FOR.
rem Each captured line is assigned to loop variable I being next assigned
rem to environment variable LastPercentLine. Just the last line found in
rem the log file is of interest for further processing of this batch file.

set "LastPercentLine="
for /F "delims=" %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"^ *[01234567689][0123456789.]*%% *" "%LogFile%" 2^>nul') do set "LastPercentLine=%%I"

rem If a line with a percent value could be found at all in the log file,
rem append this line to the temporary file and replace the log file with
rem the temporary file with just the last percent value line. Otherwise
rem delete the temporary file and keep the log file unmodified.

if defined LastPercentLine (
    echo %LastPercentLine%>>"%TmpFile%"
    move /Y "%TmpFile%" "%LogFile%"
) else del "%TmpFile%"

endlocal

Redirecting output of a command or console application written to handle STDOUT to a file results in getting written to file everything output to STDOUT even when the command or application uses special code to move text cursor in console window after output of a line back to beginning of this line to overwrite in console window the just output text with another text.

The output with the percent indication is finally readable in console window as expected because of the special text cursor moving code used by the command/application. But the output redirected into a file contains all output text as the special code to move text cursor to a specific position in console window has no effect on the file.

To get from log file upload2.log just the percent value without leading and trailing spaces the batch file can be reduced for example to:

@echo off
set "LastPercentValue=0%%"
for /F %%I in ('%SystemRoot%\System32\findstr.exe /R /C:"^ *[01234567689][0123456789.]*%% *" "upload2.log" 2^>nul') do set "LastPercentValue=%%I"
echo %LastPercentValue% copied.
set "LastPercentValue="

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

del /?

echo /?

endlocal /?

findstr /?

for /?

goto /?

if /?

move /?

rem /?

set /?

setlocal /?


问:
Re-position div on mobile with CSS Grid
I have a grid layout that is several blocks of copy with an accompanying image (link to jsfiddle).

```<code><div class="story-body">

    <div class="body-copy">
         <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
    </div>

    <div class="regular-photo">
         <img src="http://placehold.it/500x500">
    </div>

    <div class="body-copy">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
    </div>

    <div class="regular-photo">
         <img src="http://placehold.it/500x500">
    </div>

</div>
</code>```

It displays perfectly on desktop — the image lines up next to the top of the accompanying copy block. The problem is, on mobile, the images show up after the body copy sections which, makes sense, considering I organized the HTML that way.

```<code>.story-body {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-auto-flow: row;
}

.body-copy {
    justify-self: center;
    max-width: 80%;
}

.regular-photo {
justify-self: left;
}

@media screen and (max-width: 500px) {
    .story-body {
    grid-template-columns: 100%;
    }
    .regular-photo {
    justify-self: center;
    }
}
</code>```

Is there a way to position the .regular-photo divs before the .body-copy divs on mobile without having to reorganize the HTML?

答:
I did some little refactoring with your code. Excuse me. But here is the solution. You can use order property with the children of the class containing display: grid

.story-body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: row;
  justify-self: center;
}

.story-body p {
  justify-self: center;
  max-width: 80%;
}

.regular-photo {
  justify-self: left;
  display: inline-block;
  width: 100%;
  height: auto;
}

@media screen and (max-width: 500px) {
  .story-body {
    grid-template-columns: 1fr;
  }
  .photo1 {
    order: 1;
  }
  .p1 {
    order: 2;
  }
  .photo2 {
    order: 3;
  }
  .p2 {
    order: 4;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="story-body">
  <p class="p1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
    elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  <div class="regular-photo photo1">
    <img src="http://placehold.it/500x500">
  </div>

  <p class="p2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
    elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  <div class="regular-photo photo2">
    <img src="http://placehold.it/500x500">
  </div>
</div></code>```

Title: Re-position div on mobile with CSS Grid

Body:
I have a grid layout that is several blocks of copy with an accompanying image (link to jsfiddle).

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar, elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus.

It displays perfectly on desktop — the image lines up next to the top of the accompanying copy block. The problem is, on mobile, the images show up after the body copy sections which, makes sense, considering I organized the HTML that way.

.story-body {
    display: grid;
    grid-template-columns: 50% 50%;
    grid-auto-flow: row;
}

.body-copy {
    justify-self: center;
    max-width: 80%;
}

.regular-photo {
justify-self: left;
}

@media screen and (max-width: 500px) {
    .story-body {
    grid-template-columns: 100%;
    }
    .regular-photo {
    justify-self: center;
    }
}

Is there a way to position the .regular-photo divs before the .body-copy divs on mobile without having to reorganize the HTML?

Body:
I did some little refactoring with your code. Excuse me. But here is the solution. You can use order property with the children of the class containing display: grid

.story-body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-auto-flow: row;
  justify-self: center;
}

.story-body p {
  justify-self: center;
  max-width: 80%;
}

.regular-photo {
  justify-self: left;
  display: inline-block;
  width: 100%;
  height: auto;
}

@media screen and (max-width: 500px) {
  .story-body {
    grid-template-columns: 1fr;
  }
  .photo1 {
    order: 1;
  }
  .p1 {
    order: 2;
  }
  .photo2 {
    order: 3;
  }
  .p2 {
    order: 4;
  }
}

<div class="story-body">
  <p class="p1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
    elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  <div class="regular-photo photo1">
    <img src="http://placehold.it/500x500">
  </div>

  <p class="p2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec dapibus iaculis felis, molestie tincidunt est hendrerit vel. Aenean mattis convallis malesuada. Donec nec risus sem. Mauris mi urna, dictum in pulvinar vehicula, rutrum in elit. Sed pulvinar,
    elit sit amet sollicitudin imperdiet, mauris velit sollicitudin velit, nec lacinia dui massa vitae tellus. </p>
  <div class="regular-photo photo2">
    <img src="http://placehold.it/500x500">
  </div>
</div>


问:
Pycharm 2017.3 and input function
I am getting input value and save it in the variable. and the error message occurs as this. Here is my code:

```<code>    input_id = input("your id please")

    members = ['egoing', 'k8805']
    for member in members:
        if member == input_id:
            print("hellop"+member)
</code>```

and here is the error message

```<code>/Python_Workspace/PycharmProjects/Practice/venv/bin/python /Python_Workspace/PycharmProjects/Practice/Container_Loop/4.py
your id pleaseegoing
Traceback (most recent call last):
  File "/Python_Workspace/PycharmProjects/Practice/Container_Loop/4.py", line 1, in <module>
    input_id = input("your id please")
  File "<string>", line 1, in <module>
NameError: name 'egoing' is not defined

Process finished with exit code 1
</code>```

Many others asked similar questions and many answers highlighted raw_input and input function and its role after version change.
I just started python and currently using pycharm 2017.3 and didnot individually install python in my mac. Any advice why this error is happening?

答:
You're using Python 2, because the call to input() is trying to evaluate what you've entered, and that's why you're seeing that error message. It's looking for a variable with that name and not finding one.  You can change your call to raw_input() instead, which does not try to evaluate your input.
 This will solve your problem.

In the future, if you want to see what version of python you're running, just type python inside a Terminal shell, and it will pop up some info at the top. For instance, when I run Py2 on my Mac, I see:

```<code>g$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

so I know I'm running Py 2.7.

Also, there is a change between Py2 and Py3. In Py2, there is both raw_input() and input(). Both read in a string, but input() evaluates the string, expecting the string to be the name of some global item, like a function or variable.
In Py3, things changed, and Py3's input() works just Py2's raw_input(). So, because your call to input() was trying to evaluate the entered string, I could tell you were running Py2.

Title: Pycharm 2017.3 and input function

Body:
I am getting input value and save it in the variable. and the error message occurs as this. Here is my code:

    input_id = input("your id please")

    members = ['egoing', 'k8805']
    for member in members:
        if member == input_id:
            print("hellop"+member)

and here is the error message

/Python_Workspace/PycharmProjects/Practice/venv/bin/python /Python_Workspace/PycharmProjects/Practice/Container_Loop/4.py
your id pleaseegoing
Traceback (most recent call last):
  File "/Python_Workspace/PycharmProjects/Practice/Container_Loop/4.py", line 1, in <module>
    input_id = input("your id please")
  File "<string>", line 1, in <module>
NameError: name 'egoing' is not defined

Process finished with exit code 1

Many others asked similar questions and many answers highlighted raw_input and input function and its role after version change.
I just started python and currently using pycharm 2017.3 and didnot individually install python in my mac. Any advice why this error is happening?

Body:
You're using Python 2, because the call to input() is trying to evaluate what you've entered, and that's why you're seeing that error message. It's looking for a variable with that name and not finding one.  You can change your call to raw_input() instead, which does not try to evaluate your input.
 This will solve your problem.

In the future, if you want to see what version of python you're running, just type python inside a Terminal shell, and it will pop up some info at the top. For instance, when I run Py2 on my Mac, I see:

g$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

so I know I'm running Py 2.7.

Also, there is a change between Py2 and Py3. In Py2, there is both raw_input() and input(). Both read in a string, but input() evaluates the string, expecting the string to be the name of some global item, like a function or variable.
In Py3, things changed, and Py3's input() works just Py2's raw_input(). So, because your call to input() was trying to evaluate the entered string, I could tell you were running Py2.


问:
Objective-C equivalent of Java function
How could I write an Objective-C equivalent of this Java code?

```<code>public static @Nullable byte[] getUnknownData(Sample s){
    int length = s.data.length-index;
    byte data[] = new byte[length];
    for(int i=0;i<length;i++){
        data[i]=s.data[UNKNOWN_STATUS_INDEX+i].byteValue();
    }
    return data;
}
</code>```

Objective-C code:

```<code>- (NSData *)getUnknownData:(Sample s) {
    int length = s.data.count-index;
    NSData * data = [NSData alloc]init;
    . . . ????
}
</code>```

答:
You should use NSMutableData which is a modifiable subclass of NSData:

```<code>-(NSData *)getUnknownData:(Sample s){
   int length = s.data.count-index;
   NSMutableData *theData = [NSMutableData dataWithCapacity:length];

   theData.length = length;
   char *theBytes = (char *)theData.mutableBytes;
   for(int i = 0; i < length; ++i) {
       theBytes[i] = (char)[s.data[UNKNOWN_STATUS_INDEX + i] intValue]
   }
   return [theData copy];
}
</code>```

After reserving the needed amount of bytes you have to convert each value from the array into the data object.

Title: Objective-C equivalent of Java function

Body:
How could I write an Objective-C equivalent of this Java code?

public static @Nullable byte[] getUnknownData(Sample s){
    int length = s.data.length-index;
    byte data[] = new byte[length];
    for(int i=0;i<length;i++){
        data[i]=s.data[UNKNOWN_STATUS_INDEX+i].byteValue();
    }
    return data;
}

Objective-C code:

- (NSData *)getUnknownData:(Sample s) {
    int length = s.data.count-index;
    NSData * data = [NSData alloc]init;
    . . . ????
}

Body:
You should use NSMutableData which is a modifiable subclass of NSData:

-(NSData *)getUnknownData:(Sample s){
   int length = s.data.count-index;
   NSMutableData *theData = [NSMutableData dataWithCapacity:length];

   theData.length = length;
   char *theBytes = (char *)theData.mutableBytes;
   for(int i = 0; i < length; ++i) {
       theBytes[i] = (char)[s.data[UNKNOWN_STATUS_INDEX + i] intValue]
   }
   return [theData copy];
}

After reserving the needed amount of bytes you have to convert each value from the array into the data object.


答: Your path is \\.\rftb\p0 but afaik all named pipes in Windows reside under \\.\pipe\. Change yout path to e.g. \\.\pipe\p0 and it will likely work.

Title: C++ CreateNamedPipe ERROR_PATH_NOT_FOUND (3)


问:
ajax request does not send POST vars (or PHP script does not receive them)
I have an AJAX request that sends out the following information (via POST). All is well except in the requested PHP file the $_POST superglobal is empty.

I am providing Firebug's Headers and Post tabs:

Headers tab:

```Response Headers view source
Date Sun, 23 Jan 2011 08:41:03 GMT
Server Apache
X-Powered-By PHP/5.2.13
Expires Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma no-cache
Content-Length 127
Connection close
Content-Type text/html

Request Headers view source
Host xx
User-Agent Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Referer http://xx/florin2/cautare
Content-Length 2325
Content-Type text/plain; charset=UTF-8
Cookie PHPSESSID=8367d170xx```

Post tab:

```Parts multipart/form-data
titluPublic PDG Archivarius
nr_versiune
nume_developer Astonsoft
site_developer
site_produs
pret_vechi
pret_actual 9.95
link_pret /nph-softsell.cgi?item=2304-3&affiliate=441937
size 20.00
zilePromo 0
startPromo 0000-00-00
date_added 2009-02-01
dataupdate 0000-00-00
rating 0
nr_download 191
id_pad 0
featured 0
license Shareware
os Windows
id_subcat_f 102
subtitlu An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanni...
description An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanning.
features
review
pro
contra
requirements
limitations

Source
Content-Type: multipart/form-data; boundary=gRNHZ7wzOS
--gRNHZ7wzOS
Content-Disposition: form-data; name="titluPublic"

PDG Archivarius
--gRNHZ7wzOS
Content-Disposition: form-data; name="nr_versiune"

--gRNHZ7wzOS
Content-Disposition: form-data; name="nume_developer"

Astonsoft
--gRNHZ7wzOS
Content-Disposition: form-data; name="site_developer"
--gRNHZ7wzOS
Content-Disposition: form-data; name="site_produs"

--gRNHZ7wzOS
Content-Disposition: form-data; name="pret_vechi"

--gRNHZ7wzOS Content-Disposition: form-data; name="pret_actual"

9.95
--gRNHZ7wzOS
Content-Disposition: form-data; name="link_pret"

/nph-softsell.cgi?item=2304-3&affiliate=441937
--gRNHZ7wzOS
Content-Disposition: form-data; name="size"

20.00
--gRNHZ7wzOS
Content-Disposition: form-data; name="zilePromo"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="startPromo"

0000-00-00
--gRNHZ7wzOS
Content-Disposition: form-data; name="date_added"

2009-02-01
--gRNHZ7wzOS
Content-Disposition: form-data; name="dataupdate"

0000-00-00
--gRNHZ7wzOS
Content-Disposition: form-data; name="rating"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="nr_download"

191
--gRNHZ7wzOS
Content-Disposition: form-data; name="id_pad"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="featured"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="license"

Shareware
--gRNHZ7wzOS
Content-Disposition: form-data; name="os"

Windows
--gRNHZ7wzOS Content-Disposition: form-data; name="id_subcat_f"

102
--gRNHZ7wzOS
Content-Disposition: form-data; name="subtitlu"

An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanni...
--gRNHZ7wzOS
Content-Disposition: form-data; name="description"

An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanning.
--gRNHZ7wzOS
Content-Disposition: form-data; name="features"

--gRNHZ7wzOS
Content-Disposition: form-data; name="review"

--gRNHZ7wzOS
Content-Disposition: form-data; name="pro"

--gRNHZ7wzOS
Content-Disposition: form-data; name="contra"

--gRNHZ7wzOS
Content-Disposition: form-data; name="requirements"

--gRNHZ7wzOS
Content-Disposition: form-data; name="limitations"

--gRNHZ7wzOS--```

Sorry for the very long post and thanks!

UPDATE

as polarblau suggested I tried `echo file_get_contents('php://input');' which outputs the following:

```Content-Type: multipart/form-data; boundary=zMgU0RnQIk

--zMgU0RnQIk
Content-Disposition: form-data; name="titluPublic"

Feldenkrais Pelvic Clock Variations
--zMgU0RnQIk
Content-Disposition: form-data; name="nr_versiune"

--zMgU0RnQIk
Content-Disposition: form-data; name="nume_developer"

Integrated-Learning
--zMgU0RnQIk
Content-Disposition: form-data; name="site_developer"

--zMgU0RnQIk
Content-Disposition: form-data; name="site_produs"

--zMgU0RnQIk
Content-Disposition: form-data; name="pret_vechi"

--zMgU0RnQIk
Content-Disposition: form-data; name="pret_actual"

7
--zMgU0RnQIk
Content-Disposition: form-data; name="link_pret"

/nph-softsell.cgi?item=14294-5&affiliate=441937
--zMgU0RnQIk
Content-Disposition: form-data; name="size"

20.00
--zMgU0RnQIk
Content-Disposition: form-data; name="zilePromo"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="startPromo"

0000-00-00
--zMgU0RnQIk
Content-Disposition: form-data; name="date_added"

2009-02-01
--zMgU0RnQIk
Content-Disposition: form-data; name="dataupdate"

0000-00-00
--zMgU0RnQIk
Content-Disposition: form-data; name="rating"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="nr_download"

261
--zMgU0RnQIk
Content-Disposition: form-data; name="id_pad"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="featured"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="license"

Shareware
--zMgU0RnQIk
Content-Disposition: form-data; name="os"

Windows
--zMgU0RnQIk
Content-Disposition: form-data; name="id_subcat_f"

7
--zMgU0RnQIk
Content-Disposition: form-data; name="subtitlu"

Feldenkrais Lesson Pelvic Clock Variations This Feldenkrais lesson takes the theme of the ...
--zMgU0RnQIk
Content-Disposition: form-data; name="description"

Feldenkrais Lesson Pelvic Clock Variations This Feldenkrais lesson takes the theme of the Pelvic Clock in other directions. Its value lies in the slightly different demands it places on your nervous system. This is how you can develop with variation of a Feldenkrais Lesson. It is very useful to do this. It helps in developing the subtle and intricate qualities of awareness that a Feldenkrais lesson and Feldenkrais Practitioners are renowned for. Develop a greater mobility with your pelvis.
--zMgU0RnQIk
Content-Disposition: form-data; name="features"

--zMgU0RnQIk
Content-Disposition: form-data; name="review"

--zMgU0RnQIk
Content-Disposition: form-data; name="pro"

--zMgU0RnQIk
Content-Disposition: form-data; name="contra"

--zMgU0RnQIk
Content-Disposition: form-data; name="requirements"

--zMgU0RnQIk
Content-Disposition: form-data; name="limitations"

--zMgU0RnQIk--```

This is very good, but I still don't know why my $_POST is not populated. I even tried forcing $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; but with no result.

答:
This guy here at bradino.com seems to suggest a nice debugging method for this case:

```<code>$data = file_get_contents('php://input');
</code>```

This should give you the 'raw incoming message'. If this shows, that you in fact have incoming data, he suggests to force a content type in case that has been messed–up when making the request:

```<code>if(empty($_SERVER['CONTENT_TYPE'])){
     $type = "application/x-www-form-urlencoded";
     $_SERVER['CONTENT_TYPE'] = $type;
}
</code>```

Body:
I have an AJAX request that sends out the following information (via POST). All is well except in the requested PHP file the $_POST superglobal is empty.

I am providing Firebug's Headers and Post tabs:

Headers tab:

Response Headers view source
Date Sun, 23 Jan 2011 08:41:03 GMT
Server Apache
X-Powered-By PHP/5.2.13
Expires Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma no-cache
Content-Length 127
Connection close
Content-Type text/html

Request Headers view source
Host xx
User-Agent Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 115
Connection keep-alive
Referer http://xx/florin2/cautare
Content-Length 2325
Content-Type text/plain; charset=UTF-8
Cookie PHPSESSID=8367d170xx

Post tab:

Parts multipart/form-data
titluPublic PDG Archivarius
nr_versiune
nume_developer Astonsoft
site_developer
site_produs
pret_vechi
pret_actual 9.95
link_pret /nph-softsell.cgi?item=2304-3&affiliate=441937
size 20.00
zilePromo 0
startPromo 0000-00-00
date_added 2009-02-01
dataupdate 0000-00-00
rating 0
nr_download 191
id_pad 0
featured 0
license Shareware
os Windows
id_subcat_f 102
subtitlu An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanni...
description An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanning.
features
review
pro
contra
requirements
limitations

Source
Content-Type: multipart/form-data; boundary=gRNHZ7wzOS
--gRNHZ7wzOS
Content-Disposition: form-data; name="titluPublic"

PDG Archivarius
--gRNHZ7wzOS
Content-Disposition: form-data; name="nr_versiune"

--gRNHZ7wzOS
Content-Disposition: form-data; name="nume_developer"

Astonsoft
--gRNHZ7wzOS
Content-Disposition: form-data; name="site_developer"
--gRNHZ7wzOS
Content-Disposition: form-data; name="site_produs"

--gRNHZ7wzOS
Content-Disposition: form-data; name="pret_vechi"

--gRNHZ7wzOS Content-Disposition: form-data; name="pret_actual"

9.95
--gRNHZ7wzOS
Content-Disposition: form-data; name="link_pret"

/nph-softsell.cgi?item=2304-3&affiliate=441937
--gRNHZ7wzOS
Content-Disposition: form-data; name="size"

20.00
--gRNHZ7wzOS
Content-Disposition: form-data; name="zilePromo"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="startPromo"

0000-00-00
--gRNHZ7wzOS
Content-Disposition: form-data; name="date_added"

2009-02-01
--gRNHZ7wzOS
Content-Disposition: form-data; name="dataupdate"

0000-00-00
--gRNHZ7wzOS
Content-Disposition: form-data; name="rating"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="nr_download"

191
--gRNHZ7wzOS
Content-Disposition: form-data; name="id_pad"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="featured"

0
--gRNHZ7wzOS
Content-Disposition: form-data; name="license"

Shareware
--gRNHZ7wzOS
Content-Disposition: form-data; name="os"

Windows
--gRNHZ7wzOS Content-Disposition: form-data; name="id_subcat_f"

102
--gRNHZ7wzOS
Content-Disposition: form-data; name="subtitlu"

An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanni...
--gRNHZ7wzOS
Content-Disposition: form-data; name="description"

An advanced zipping utility wich allows to recover .zip passwords and do anti-virus scanning.
--gRNHZ7wzOS
Content-Disposition: form-data; name="features"

--gRNHZ7wzOS
Content-Disposition: form-data; name="review"

--gRNHZ7wzOS
Content-Disposition: form-data; name="pro"

--gRNHZ7wzOS
Content-Disposition: form-data; name="contra"

--gRNHZ7wzOS
Content-Disposition: form-data; name="requirements"

--gRNHZ7wzOS
Content-Disposition: form-data; name="limitations"

--gRNHZ7wzOS--

Sorry for the very long post and thanks!

UPDATE

as polarblau suggested I tried `echo file_get_contents('php://input');' which outputs the following:

Content-Type: multipart/form-data; boundary=zMgU0RnQIk

--zMgU0RnQIk
Content-Disposition: form-data; name="titluPublic"

Feldenkrais Pelvic Clock Variations
--zMgU0RnQIk
Content-Disposition: form-data; name="nr_versiune"

--zMgU0RnQIk
Content-Disposition: form-data; name="nume_developer"

Integrated-Learning
--zMgU0RnQIk
Content-Disposition: form-data; name="site_developer"

--zMgU0RnQIk
Content-Disposition: form-data; name="site_produs"

--zMgU0RnQIk
Content-Disposition: form-data; name="pret_vechi"

--zMgU0RnQIk
Content-Disposition: form-data; name="pret_actual"

7
--zMgU0RnQIk
Content-Disposition: form-data; name="link_pret"

/nph-softsell.cgi?item=14294-5&affiliate=441937
--zMgU0RnQIk
Content-Disposition: form-data; name="size"

20.00
--zMgU0RnQIk
Content-Disposition: form-data; name="zilePromo"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="startPromo"

0000-00-00
--zMgU0RnQIk
Content-Disposition: form-data; name="date_added"

2009-02-01
--zMgU0RnQIk
Content-Disposition: form-data; name="dataupdate"

0000-00-00
--zMgU0RnQIk
Content-Disposition: form-data; name="rating"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="nr_download"

261
--zMgU0RnQIk
Content-Disposition: form-data; name="id_pad"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="featured"

0
--zMgU0RnQIk
Content-Disposition: form-data; name="license"

Shareware
--zMgU0RnQIk
Content-Disposition: form-data; name="os"

Windows
--zMgU0RnQIk
Content-Disposition: form-data; name="id_subcat_f"

7
--zMgU0RnQIk
Content-Disposition: form-data; name="subtitlu"

Feldenkrais Lesson Pelvic Clock Variations This Feldenkrais lesson takes the theme of the ...
--zMgU0RnQIk
Content-Disposition: form-data; name="description"

Feldenkrais Lesson Pelvic Clock Variations This Feldenkrais lesson takes the theme of the Pelvic Clock in other directions. Its value lies in the slightly different demands it places on your nervous system. This is how you can develop with variation of a Feldenkrais Lesson. It is very useful to do this. It helps in developing the subtle and intricate qualities of awareness that a Feldenkrais lesson and Feldenkrais Practitioners are renowned for. Develop a greater mobility with your pelvis.
--zMgU0RnQIk
Content-Disposition: form-data; name="features"

--zMgU0RnQIk
Content-Disposition: form-data; name="review"

--zMgU0RnQIk
Content-Disposition: form-data; name="pro"

--zMgU0RnQIk
Content-Disposition: form-data; name="contra"

--zMgU0RnQIk
Content-Disposition: form-data; name="requirements"

--zMgU0RnQIk
Content-Disposition: form-data; name="limitations"

--zMgU0RnQIk--

This is very good, but I still don't know why my $_POST is not populated. I even tried forcing $_SERVER['CONTENT_TYPE'] = 'multipart/form-data'; but with no result.

Body:
This guy here at bradino.com seems to suggest a nice debugging method for this case:

$data = file_get_contents('php://input');

This should give you the 'raw incoming message'. If this shows, that you in fact have incoming data, he suggests to force a content type in case that has been messed–up when making the request:

if(empty($_SERVER['CONTENT_TYPE'])){
     $type = "application/x-www-form-urlencoded";
     $_SERVER['CONTENT_TYPE'] = $type;
}


问:
cordapp-template-java "Cannot resolve symbol 'docs'"
I have been working my way through the Hello, World! Tutorial from V2.0 and cannot import the following variable.

```<code>import static net.corda.docs.java.tutorial.helloworld.TemplateContract.TEMPLATE_CONTRACT_ID;
</code>```

Intellij informs me that it "Cannot resolve symbol 'docs'".

Is this a known issue or have I incorrectly setup the cordapp-template-java project?

答:
Resolved this issue by using:

```<code>import static com.template.TemplateContract.TEMPLATE_CONTRACT_ID;
</code>```

The definition for this variable can be found here.

Body:
I have been working my way through the Hello, World! Tutorial from V2.0 and cannot import the following variable.

import static net.corda.docs.java.tutorial.helloworld.TemplateContract.TEMPLATE_CONTRACT_ID;

Intellij informs me that it "Cannot resolve symbol 'docs'".

Is this a known issue or have I incorrectly setup the cordapp-template-java project?

Body:
Resolved this issue by using:

import static com.template.TemplateContract.TEMPLATE_CONTRACT_ID;

The definition for this variable can be found here.


问:
Redirecting All Subdirectories to Single Location
I am using .htaccess to rewrite my subdirectories or additional URL information in links to a single location. I'm not quite sure how to phrase this, so I'll include examples below.

OLD URL                                                  NEW URL

oldsite.com/shop                                newsite.com/shop

oldsite.com/shop/something                      newsite.com/shop

oldsite.com/shop/category/product/123.html      newsite.com/shop

oldsite.com/shop/landingpage                    newsite.com/shop

There are still a number of additional functions that oldsite is performing, so I only want the /shop (and anything after that) to redirect to the newsite.

If it would be easier to do this somewhere besides .htaccess that would be great too.

答:
That can easily be done with mod_rewrite:

```<code>RewriteEngine On
RewriteRule ^shop https://newsite.com/shop [R=301,L]
</code>```

This will look at the URL and, if it begins with "shop" (the leading / is ignored automatically), redirect to the new URL.
Note that it will also redirect /shopping. If that is not what you want, you'd have to modifiy the pattern.

It will use a 301 Moved Permanently HTTP status code, but you could change that to another 3XX code by modifying the R flag.

Body:
That can easily be done with mod_rewrite:

RewriteEngine On
RewriteRule ^shop https://newsite.com/shop [R=301,L]

This will look at the URL and, if it begins with "shop" (the leading / is ignored automatically), redirect to the new URL.
Note that it will also redirect /shopping. If that is not what you want, you'd have to modifiy the pattern.

It will use a 301 Moved Permanently HTTP status code, but you could change that to another 3XX code by modifying the R flag.