问:
Replace HTML Comment along with string variable
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.

I am having trouble getting the regex to work.

Here is an html line I am working on:

```<code><td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
</code>```

Now, here is the javascript/jquery that I have at the moment:

```<code>var thisval = $(this).val();  //gets replacement text from a text box
var thistoken = "firstname";

currentTemplate = $("#gentextCodeArea").text();  //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate);   //put the new text back
</code>```

I think I'm pretty close, but I don't have the regex right yet.

The regex ought to replace the firstname with whatever is entered in the textbox for $thisval  (method is attached to keyup procedure on textbox).

答:
here is a function which will generate an appropriate Regular expression:

```<code>function templatePattern(key) {
  return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}
</code>```

the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:

```<code>'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
    .replace(templatePattern('firstname'), 'Bob')
    .replace(templatePattern('lastname'), 'Johnson')    // "Bob Johnson"
</code>```

Body:
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.

I am having trouble getting the regex to work.

Here is an html line I am working on:

Harrison Ford

Now, here is the javascript/jquery that I have at the moment:

var thisval = $(this).val();  //gets replacement text from a text box
var thistoken = "firstname";

currentTemplate = $("#gentextCodeArea").text();  //fetch the text
var tokenstring = ""
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate);   //put the new text back

I think I'm pretty close, but I don't have the regex right yet.

The regex ought to replace the firstname with whatever is entered in the textbox for $thisval  (method is attached to keyup procedure on textbox).

Body:
here is a function which will generate an appropriate Regular expression:

function templatePattern(key) {
  return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}

the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:

'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
    .replace(templatePattern('firstname'), 'Bob')
    .replace(templatePattern('lastname'), 'Johnson')    // "Bob Johnson"


来源: stackexchange

问:
How to make console program to disappear and work in background?
How can I make console program disappear and work in the background?
I mean, I don't want to see the program, but I want to see it running in the task manager.

Thanks.

答:
If you are using Windows try

```<code>start command.exe
</code>```

If you are using *nix

```<code>nohup command
</code>```

OwnerDisplayName: Tal

ContentLicense: CC BY-SA 3.0

Body:
If you are using Windows try

start command.exe

If you are using *nix

nohup command

OwnerDisplayName: ng

ContentLicense: CC BY-SA 2.5


问:
Sorttable How does it work?
I have an HTML table with less than 50 rows.
I am using Sorttable to allow the users to sort the table accordingly.

I would like to stripe my tables with something like: Zebra Tables

I have implemented both scripts on the table. The only problem is that I need to call the stripe method after the table is sorted.

I am unsure how the Sorttable script is called, as there isn't a onclick method added to the header of my table.

So my question is, how can javascript be called without an event?

答:
Take a look at line 92 of sorttables.js. Its adding a click event:

```<code>dean_addEvent(headrow[i],"click", function(e) {```

Title: Sorttable How does it work?

Body:
Take a look at line 92 of sorttables.js. Its adding a click event:

dean_addEvent(headrow[i],"click", function(e) {


问:
What exactly is stdin?
I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?

Here is a sample:

```<code>#include<stdio.h>
#include<stdlib.h>

int main(){

    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);

    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}
</code>```

When I input

foobar1234567890

I get the result:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

And when I input

foobar

I get the output

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?

答:
stdin (short for standard input) is a pointer to a FILE type that can only be manipulated with these functions:

https://en.wikipedia.org/wiki/C_file_input/output

On most (if not all) implementations, the FILE type is a structure with a integer file descriptor and a character buffer, allowing for buffered I/O operations. This file descriptor is opened in read-only mode and is normally connected to either the terminal, a pipe or a file.

There's also stdout (standard output) and stderr (standard error), opened in writing mode.

Title: What exactly is stdin?

Body:
I am a bit confused regarding the implementation of stdin. What exactly is it? Is it a pointer? I tried to print the size of stdin using sizeof on a 64 bit machine and got 8. I even de-referenced it using *stdin in the %s specifier and got the not used characters in the input stream( all of them). But if I compare its de referenced value inside if I get an error. I know its an input stream. But how is it implemented?

Here is a sample:

#include<stdio.h>
#include<stdlib.h>

int main(){

    char a[10];

    fgets(a,10,stdin);

    printf("a: %s",a);

    printf("\nstdin: %s",*stdin);

//if(*stdin=="foo"){
//    printf("True");
//}//Error: invalid operands to binary == (have 'FILE' and 'char *')//and casting to char * doesn't help

    printf("\nSize of stdin: %d\n",sizeof(stdin));

    if(stdin!=NULL){
        printf("This statement is always reached");//always printed even in when input is bigger than 10 chars and otherwise
    }

if(!feof(stdin)){
    printf("\nThis statement is also always reached");
}
}

When I input

foobar1234567890

I get the result:

a: foobar123

stdin: 4567890

Size of stdin: 8

This statement is always reached

This statement is also always reached

And when I input

foobar

I get the output

a: foobar

stdin:

Size of stdin: 4

This statement is always reached

This statement is also always reached

I understand that stdin is kind of a FILE pointer, but I don't clearly get it. Could anyone explain the above outputs?


问:
How to get the result of difference between two date using php?
I have this php code

```<code>$today_date = date('d/m/Y H:i:s');
$Expierdate = '09/06/2017 21:45:03';
$remaindate = date_diff($today_date,$Expierdate);
echo $remaindate;
</code>```

and i need result from difference between two date.

答:
date_diff() needs a DateTimeInterface as an argument. In other words, you need to create a DateTime object first, using new DateTime() as shown below.

```<code>$today_date = new DateTime();
$Expierdate = new DateTime('09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
</code>```

Live demo

The above would output

90 days

Because today is June 8th, and the format 09/06/2017 is September 6th - because you're using American format (MM/DD/YYYY).

If you ment June 9th (tomorrow), you need to use European format (MM-DD-YYYY, note the dash instead of slash). You can alternatively use DateTime::createFromFormat() to create from a set format, so your current format, 09/06/2017, is interpreted as June 9th. The code would then be

```<code>$today_date = new DateTime();
$Expierdate = DateTime::createFromFormat('d/m/Y H:i:s', '09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');
</code>```

Output (live demo)

1 days

In any case, $remaindate holds some properties which can be used (see the manual), or you can format it to your liking by supplying the desired formation into the format() method.

new DateTime()

DateTime::diff()

DateTime::format()

DateTime::create_from_format()

ContentLicense: CC BY-SA 4.0

Body:
I have this php code

$today_date = date('d/m/Y H:i:s');
$Expierdate = '09/06/2017 21:45:03';
$remaindate = date_diff($today_date,$Expierdate);
echo $remaindate;

and i need result from difference between two date.

Body:
date_diff() needs a DateTimeInterface as an argument. In other words, you need to create a DateTime object first, using new DateTime() as shown below.

$today_date = new DateTime();
$Expierdate = new DateTime('09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');

Live demo

The above would output

90 days

Because today is June 8th, and the format 09/06/2017 is September 6th - because you're using American format (MM/DD/YYYY).

If you ment June 9th (tomorrow), you need to use European format (MM-DD-YYYY, note the dash instead of slash). You can alternatively use DateTime::createFromFormat() to create from a set format, so your current format, 09/06/2017, is interpreted as June 9th. The code would then be

$today_date = new DateTime();
$Expierdate = DateTime::createFromFormat('d/m/Y H:i:s', '09/06/2017 21:45:03');
$remaindate = $today_date->diff($Expierdate);
echo $remaindate->format('%a days');

Output (live demo)

1 days

In any case, $remaindate holds some properties which can be used (see the manual), or you can format it to your liking by supplying the desired formation into the format() method.

new DateTime()

DateTime::diff()

DateTime::format()

DateTime::create_from_format()


问:
Shorthand way to remove last forward slash and trailing characters from string
If I have the following string:

/lorem/ipsum/dolor

and I want this to become:

/lorem/ipsum

What is the short-hand way of removing the last forward slash, and all characters following it?

I know how I can do this by spliting the string into a List<> and removing the last item, and then joining, but is there a shorter way of writing this?

My question is not URL specific.

答:
Thank you @Curt for your question.
I slightly improved @newfurniturey's code, and here is my version.</p>

```<code> if(str.Contains('/')){
      str = str.Substring(0, str.LastIndexOf('/'));
 }
</code>```

Body:
Thank you @Curt for your question.
I slightly improved @newfurniturey's code, and here is my version.

 if(str.Contains('/')){
      str = str.Substring(0, str.LastIndexOf('/'));
 }


答: It's an abstraction of the Standard Input service the OS supports. It is modeled as a stream. Check GNU LibC definitions.</p>

Title: What exactly is stdin?


答:
stdin is a pointer of type FILE *.  The standard does not restrict the implementation beyond this,  the details of what FILE is is entirely up to your compiler. It could even be an incomplete type (opaque).

Of course, trying to print a FILE with %s causes undefined behaviour (unless FILE is a typedef for char * or similar, which it almost certainly is not).

Title: What exactly is stdin?


问:
How do I document an object created with Object.create that also has prototypal methods
I am trying to work out the best way to jsdoc what I have using jsdoc3 with the closure dictionary. The code below documents to almost what I want but the @class tag adds a new keyword in the documentation and I am also uneasy about using the class definition as it is not really a class.

/**
 * myObject constructor.  Do not use with new.
 * @class myObject
 * @param {string} someText The text to store
 */
function myObject (someText) {
  var instance = Object.create(myObject.prototype);
  instance.someText = someText;

  return instance;
}

/**
 * Outputs to the console
 */
myObject.prototype.doSomething = function () {
  console.log(this.someText);
};

var test = myObject('foobar');
test.doSomething();
```

@namespace seemed like a better pick originally but it does not allow for documenting @param or similar on the pseudo constructor. Any help is appreciated.

答:
Here demonstrates a possible implementation of your constructor/factory, and how to document members of the constructed object:

```<code>/**
 * Constructs my object.
 *
 * <p>
 * It is not necessary to call this with <i>new</i> keyword.
 *
 * @name myObject
 * @namespace
 * @constructor
 * @param {string} someText The text to store
 */
function myObject ( someText ) {
    var instance = Object.create( myObject.prototype, {
        /**
         * A member, could be a value of any type.
         *
         * @type {string}
         * @memberof myObject#
         */
        anyMember: {
            value: "whatever"
        },
        /**
         * A <strong>method</strong> member.
         *
         * @param {string|number|object|function} anArgument A parameter.
         *
         * @method
         * @memberof myObject#
         */
        aMethodSpecially: {
            value: function ( anArgument ) {
                throw "Not yet implemented";
            }
        }
    } );

    /**
     * Some text.
     *
     * @property {string}
     */
    instance.someText = someText;

    return instance;
}

/**
 * Outputs to the console.
 *
 * @param {number|string|function|object} someArgument Some method argument.
 * @function doSomething
 * @memberof myObject#
 */
myObject.prototype.doSomething = function ( someArgument ) {
    // @ts-ignore
    console.log( this.someText );
};

var test = myObject( 'foobar' );
test.doSomething();
</code>```

The generated doc using JSDoc 3 looks as follows:

--- screenshot continues...

Body:
I am trying to work out the best way to jsdoc what I have using jsdoc3 with the closure dictionary. The code below documents to almost what I want but the @class tag adds a new keyword in the documentation and I am also uneasy about using the class definition as it is not really a class.

/**
 * myObject constructor.  Do not use with new.
 * @class myObject
 * @param {string} someText The text to store
 */
function myObject (someText) {
  var instance = Object.create(myObject.prototype);
  instance.someText = someText;

  return instance;
}

/**
 * Outputs to the console
 */
myObject.prototype.doSomething = function () {
  console.log(this.someText);
};

var test = myObject('foobar');
test.doSomething();

@namespace seemed like a better pick originally but it does not allow for documenting @param or similar on the pseudo constructor. Any help is appreciated.

Body:
Here demonstrates a possible implementation of your constructor/factory, and how to document members of the constructed object:

/**
 * Constructs my object.
 *
 * <p>
 * It is not necessary to call this with <i>new</i> keyword.
 *
 * @name myObject
 * @namespace
 * @constructor
 * @param {string} someText The text to store
 */
function myObject ( someText ) {
    var instance = Object.create( myObject.prototype, {
        /**
         * A member, could be a value of any type.
         *
         * @type {string}
         * @memberof myObject#
         */
        anyMember: {
            value: "whatever"
        },
        /**
         * A <strong>method</strong> member.
         *
         * @param {string|number|object|function} anArgument A parameter.
         *
         * @method
         * @memberof myObject#
         */
        aMethodSpecially: {
            value: function ( anArgument ) {
                throw "Not yet implemented";
            }
        }
    } );

    /**
     * Some text.
     *
     * @property {string}
     */
    instance.someText = someText;

    return instance;
}

/**
 * Outputs to the console.
 *
 * @param {number|string|function|object} someArgument Some method argument.
 * @function doSomething
 * @memberof myObject#
 */
myObject.prototype.doSomething = function ( someArgument ) {
    // @ts-ignore
    console.log( this.someText );
};

var test = myObject( 'foobar' );
test.doSomething();

The generated doc using JSDoc 3 looks as follows:

--- screenshot continues...


问:
How can I join these two select statements?
First statement

```<code>SELECT * FROM `file` WHERE Region = 'x' AND level > 2 ORDER by id DESC LIMIT 0,6
</code>```

Second statement

```<code>SELECT * FROM `file` WHERE Region = 'x' AND level < 3 ORDER by id DESC LIMIT 0,6
</code>```

答:
Wouldnt the "obvious" solution be to do this:

```<code>SELECT * FROM `file` WHERE Region = 'x' AND (level > 2 OR level < 3) ORDER by id DESC LIMIT 0,6
</code>```

or alternative like Remco mentioned with between:

```<code>SELECT * FROM `file` WHERE Region = 'x' AND NOT (level BETWEEN 2 AND 3) ORDER by id DESC LIMIT 0,6
</code>```

Body:
First statement

SELECT * FROM `file` WHERE Region = 'x' AND level > 2 ORDER by id DESC LIMIT 0,6

Second statement

SELECT * FROM `file` WHERE Region = 'x' AND level < 3 ORDER by id DESC LIMIT 0,6

Body:
Wouldnt the "obvious" solution be to do this:

SELECT * FROM `file` WHERE Region = 'x' AND (level > 2 OR level < 3) ORDER by id DESC LIMIT 0,6

or alternative like Remco mentioned with between:

SELECT * FROM `file` WHERE Region = 'x' AND NOT (level BETWEEN 2 AND 3) ORDER by id DESC LIMIT 0,6


问:
how do i connect to oracle with the info i have?
i have the info below from the oracle DBA and want to connect to oracle from a .net application. i just got done installing the oracle tools/ drivers for windows/ .net and now want to get a console app to connect tot he oracle DB and extract data from oracle into SQL server.

another solution would be to have SQL server pull from oracle all the records in the bugs table. i have no clue what the oracle connection string is and have tried to create a system DSN but failed at that prior to turning to the SO gurus...

ORACLE SQL user name is ‘USER_dev’,
  password is ‘welcome’.

Connection string is
  ‘jdbc:mercury:oracle://qct-ds2-p.apps.com:1139;sid=QCTRP1’

答:
now that you have the tnsnames created from @erbsock, you will need to get the .net side of
things working.  Oracle has several tutorials available to help you in this matter.

When you install the Oracle ODP (in the link you will see samples as well as the downloads) drivers you will get a directory created in the
%oracle_home%\odp.net\samples\4\DataSet\DSPopulate\src
(this appears to be the same example as located @ http://www.oracle.com/technology/sample_code/tech/windows/odpnet/DSPopulate/ViewProducts.cs.html)

as an initial test I would recommend just changing around the id/passwrd/sql/etc and trying it out.

it is not that fundamentally different than using System.Data; but there are a few gotchas and remember that each computer will need to have ODP/Oracle client installed to have them work with the ora connection.

if you have any problems post the exact error msg that is displayed as well as a snippet of your .net code that establishes the connection, does the query, and where it is breaking


问:
Python: printing strings from another file
I want to call a file, erase its data, write new lines and print it.
Below is my program and its output.

```<code>from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()
</code>```

Output:

[]
[]

答:
So, your error (by your comments is that it isn't letting you read).

This is because your trying to read using a file pointer which was used to open the file in write mode.

```<code>from sys import argv
string, filename = argv
with open(filename, 'w') as text:
    line1 = "hey"
    line2 = "I was doing just fine before I met you"
    line3 = "I drink too much and that's an issue but I'm okay"
    text.write('%s\n%s\n%s\n' %(line1, line2, line3))

with open(filename, 'r') as text:
    ...
</code>```

Body:
I want to call a file, erase its data, write new lines and print it.
Below is my program and its output.

from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()

Output:

[]
[]

Body:
So, your error (by your comments is that it isn't letting you read).

This is because your trying to read using a file pointer which was used to open the file in write mode.

from sys import argv
string, filename = argv
with open(filename, 'w') as text:
    line1 = "hey"
    line2 = "I was doing just fine before I met you"
    line3 = "I drink too much and that's an issue but I'm okay"
    text.write('%s\n%s\n%s\n' %(line1, line2, line3))

with open(filename, 'r') as text:
    ...


问:
Curly braces in string {0}
I often see curly braces in a string usually containing a number, such as:

```<code>string something = "I have {0} cats";
</code>```

Whilst I can work out what this means, I can say I've never read any documentation relating to its useage.  The c# string documentation seems to be void of any information relating to these.  Can anyone point me in the right direction?

答:
*With C# 6.0 & friends, curly braces aren't just for string.Format any more! Now they can denote interpolated strings, where you can mix in C# objects and code without all the string.Format & {0} {1} {2} overhead.

NOTE: Interpolated strings start with a dollar sign: $

From the language reference page linked above:

Used to construct strings. An interpolated string looks like a
  template string that contains interpolated expressions. An
  interpolated string returns a string that replaces the interpolated
  expressions that it contains with their string representations.

The arguments of an interpolated string are easier to understand than
  a composite format string. For example, the interpolated string

Console.WriteLine($"Name = {name}, hours = {hours:hh}");

contains two interpolated expressions, '{name}' and '{hours:hh}'. The
  equivalent composite format string is:

Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours);

Note: If you didn't know, Console.WriteLine has a sort of built-in string.Format, which might not be obvious in the above example if you didn't realize that going in.

If you wanted to get the same string out without relying on Console.WriteLine magic, it might be easier to read that this...

```<code>string message = $"Name = {name}, hours = {hours:hh}"; // interpolated
</code>```

... is equivalent to...

```<code>string message = string.Format("Name = {0}, hours = {1:hh}", name, hours); // old school
</code>```

The structure of an interpolated string is:

$"<text> {<interpolated-expression> [,<field-width>] [<:format-string>] } <text> ..."

  where:

field-width is a signed integer that indicates the number of characters in the field. If it is positive, the field is right-aligned; if negative, left-aligned.

format-string is a format string appropriate for the type of object being formatted. For example, for a DateTime value, it could be a standard date and time format string such as "D" or "d".

You can use an interpolated string anywhere you can use a string
  literal. The interpolated string is evaluated each time the code with
  the interpolated string executes. This allows you to separate the
  definition and evaluation of an interpolated string.

To include a curly brace ("{" or "}") in an interpolated string, use
  two curly braces, "{{" or "}}".

* As @Ben points out in a comment, above. (Sorry, missed that on the way in.)

Title: Curly braces in string {0}

Body:
I often see curly braces in a string usually containing a number, such as:

string something = "I have {0} cats";

Whilst I can work out what this means, I can say I've never read any documentation relating to its useage.  The c# string documentation seems to be void of any information relating to these.  Can anyone point me in the right direction?

Body:
*With C# 6.0 & friends, curly braces aren't just for string.Format any more! Now they can denote interpolated strings, where you can mix in C# objects and code without all the string.Format & {0} {1} {2} overhead.

NOTE: Interpolated strings start with a dollar sign: $

From the language reference page linked above:

Used to construct strings. An interpolated string looks like a
  template string that contains interpolated expressions. An
  interpolated string returns a string that replaces the interpolated
  expressions that it contains with their string representations.

The arguments of an interpolated string are easier to understand than
  a composite format string. For example, the interpolated string

Console.WriteLine($"Name = {name}, hours = {hours:hh}");

contains two interpolated expressions, '{name}' and '{hours:hh}'. The
  equivalent composite format string is:

Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours);

Note: If you didn't know, Console.WriteLine has a sort of built-in string.Format, which might not be obvious in the above example if you didn't realize that going in.

If you wanted to get the same string out without relying on Console.WriteLine magic, it might be easier to read that this...

string message = $"Name = {name}, hours = {hours:hh}"; // interpolated

... is equivalent to...

string message = string.Format("Name = {0}, hours = {1:hh}", name, hours); // old school

The structure of an interpolated string is:

$"<text> {<interpolated-expression> [,<field-width>] [<:format-string>] } <text> ..."

  where:

field-width is a signed integer that indicates the number of characters in the field. If it is positive, the field is right-aligned; if negative, left-aligned.

format-string is a format string appropriate for the type of object being formatted. For example, for a DateTime value, it could be a standard date and time format string such as "D" or "d".

You can use an interpolated string anywhere you can use a string
  literal. The interpolated string is evaluated each time the code with
  the interpolated string executes. This allows you to separate the
  definition and evaluation of an interpolated string.

To include a curly brace ("{" or "}") in an interpolated string, use
  two curly braces, "{{" or "}}".

* As @Ben points out in a comment, above. (Sorry, missed that on the way in.)


问:
How to improve method structure to reduce params?
In many methods in the service classes I am repeating the code like this:

```<code>$model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event');

$this->worker->uploadFile($provider->id, 'root', $file);
</code>```

Many different $model will have addEvent() which is done via trait.

How can I refactor those two lines into a method with readable/memorable parameters?

I have tried the following:

```<code>public function deploy($model, $providerId, $status, $user, $action, $file, $description = null)
{
   $model->addEvent($providerId, $status, $user, $action, $description);

   $this->serverWorker->uploadFile($providerId, $user, $file);
}
</code>```

What I don't like about this method that there is too many params.

Usage:

Eg 1. deploy($site, 1, 'In Queue', 'root', 'create', $file, 'Installing Site domain.com')

Eg 2. deploy($rule, 1, 'In Queue', 'root', 'update', $file, 'Updating Rule')

Eg 2. deploy($something, 1, 'In Queue', 'root', 'delete', $file)

答:
You could try wrapping the common configurations into small reusable classes like so:

```<code>public function deploy($model, FileDeployTarget $target, $description = null)
{
   $model->addEvent($target->providerId, $target->status, $target->user, $target->action, $description);

   $this->serverWorker->uploadFile($target->providerId, $target->user, $target->file);
}
</code>```

And somewhere else:

```<code>class UpdateInQueue extends FileDeployTarget {
    public $status = 'In Queue';
    public $action = 'update';
}
</code>```

FileDeployTarget and descendants would handle all extra parameters in their constructors.

Body:
In many methods in the service classes I am repeating the code like this:

$model->addEvent($provider->id, 'installing', 'username', 'add', 'Description of event');

$this->worker->uploadFile($provider->id, 'root', $file);

Many different $model will have addEvent() which is done via trait.

How can I refactor those two lines into a method with readable/memorable parameters?

I have tried the following:

public function deploy($model, $providerId, $status, $user, $action, $file, $description = null)
{
   $model->addEvent($providerId, $status, $user, $action, $description);

   $this->serverWorker->uploadFile($providerId, $user, $file);
}

What I don't like about this method that there is too many params.

Usage:

Eg 1. deploy($site, 1, 'In Queue', 'root', 'create', $file, 'Installing Site domain.com')

Eg 2. deploy($rule, 1, 'In Queue', 'root', 'update', $file, 'Updating Rule')

Eg 2. deploy($something, 1, 'In Queue', 'root', 'delete', $file)

Body:
You could try wrapping the common configurations into small reusable classes like so:

public function deploy($model, FileDeployTarget $target, $description = null)
{
   $model->addEvent($target->providerId, $target->status, $target->user, $target->action, $description);

   $this->serverWorker->uploadFile($target->providerId, $target->user, $target->file);
}

And somewhere else:

class UpdateInQueue extends FileDeployTarget {
    public $status = 'In Queue';
    public $action = 'update';
}

FileDeployTarget and descendants would handle all extra parameters in their constructors.


问:
FizzBuzz using JDK8 Lambda
Just want to see by JDK8 lambda how small the program can be, my approach is using a result builder:

```<code>IntStream.rangeClosed(0 , 100).forEach(i ->{
        StringBuffer bfr= new StringBuffer();
        if(i % 3 == 0 )
            bfr.append("Fizz");
        if(i % 5 == 0 )
            bfr.append("Buzz");
        if(i % 3 != 0 && i % 5 != 0 )
            bfr.append(i);

        System.out.println(bfr.toString());
});
</code>```

Can anyone try to use predicate instead ? I could not think of a way to do this.

答:
My version using format.</p>

```<code>IntStream.rangeClosed(1, 100).forEach(
    i -> System.out.format("%s%s%n",
                           (i % 3 == 0 ? "Fizz": ""),
                           (i % 5 == 0 ? "Buzz": (i % 3 == 0 ? "" : i))
         )
);
</code>```

Title: FizzBuzz using JDK8 Lambda

Body:
Just want to see by JDK8 lambda how small the program can be, my approach is using a result builder:

IntStream.rangeClosed(0 , 100).forEach(i ->{
        StringBuffer bfr= new StringBuffer();
        if(i % 3 == 0 )
            bfr.append("Fizz");
        if(i % 5 == 0 )
            bfr.append("Buzz");
        if(i % 3 != 0 && i % 5 != 0 )
            bfr.append(i);

        System.out.println(bfr.toString());
});

Can anyone try to use predicate instead ? I could not think of a way to do this.

Body:
My version using format.

IntStream.rangeClosed(1, 100).forEach(
    i -> System.out.format("%s%s%n",
                           (i % 3 == 0 ? "Fizz": ""),
                           (i % 5 == 0 ? "Buzz": (i % 3 == 0 ? "" : i))
         )
);


问:
How to add a "back to top of page" button in R Shiny?
This is a very common feature among other webapps, but in R Shiny, how do you add a button that brings the user back to the top of the page when clicked?

In addition to that, is it possible to set how far up or down the user's view moves to?

Many thanks, I searched for a while but can't find any posts about this.

答:
Using the shinyjs package, you can define a simple jump to top function along the lines of

```<code>jscode <- "shinyjs.toTop = function() {document.body.scrollTop = 0;}"
</code>```

And you can then assign the code to a button in the ui

```<code>  useShinyjs(),
  extendShinyjs(text = jscode),
  actionButton("toTop", "jump to top")
</code>```

And the have an observer in the server that executes the javascript when the button is clicked, something like

```<code>observeEvent(input$toTop, {
    js$toTop();
 })
</code>```

Note that I have not tested this answer, but it should be enough to point you in the right direction (for example, the javascript might not work with different browsers)

Body:
Using the shinyjs package, you can define a simple jump to top function along the lines of

jscode <- "shinyjs.toTop = function() {document.body.scrollTop = 0;}"

And you can then assign the code to a button in the ui

  useShinyjs(),
  extendShinyjs(text = jscode),
  actionButton("toTop", "jump to top")

And the have an observer in the server that executes the javascript when the button is clicked, something like

observeEvent(input$toTop, {
    js$toTop();
 })

Note that I have not tested this answer, but it should be enough to point you in the right direction (for example, the javascript might not work with different browsers)


答:
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.

If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:

$("#fname").on("input", function () {
    var thisval = $(this).val();  //gets replacement text from a text box
    var thistoken = "firstname";

    var between = false;
    $("#gentextCodeArea").contents().each(function () {
        if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
            if (between) return false;
            between = true;
        } else if (between) {
            this.nodeValue = thisval;
            thisval = '';
        }
    });
});    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
    <!--firstname-->Harrison<!--firstname-->
    <!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div></code>```

What went wrong in your code

By using text() you don't get the comment tags. To get those, you need to use html() instead

replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate

It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.

Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:

$("#fname").on("input", function () {
    var thisval = $(this).val();  //gets replacement text from a text box
    var thistoken = "firstname";

    currentTemplate = $("#gentextCodeArea").html();  //fetch the html
    var tokenstring = ""
    var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
    currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
    $("#gentextCodeArea").html(currentTemplate);   //put the new text back
});    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
    <!--firstname-->Harrison<!--firstname-->
    <!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div></code>```

Title: Replace HTML Comment along with string variable

Body:
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.

I am having trouble getting the regex to work.

Here is an html line I am working on:

Harrison Ford

Now, here is the javascript/jquery that I have at the moment:

var thisval = $(this).val();  //gets replacement text from a text box
var thistoken = "firstname";

currentTemplate = $("#gentextCodeArea").text();  //fetch the text
var tokenstring = ""
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate);   //put the new text back

I think I'm pretty close, but I don't have the regex right yet.

The regex ought to replace the firstname with whatever is entered in the textbox for $thisval  (method is attached to keyup procedure on textbox).

Body:
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.

If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:

$("#fname").on("input", function () {
    var thisval = $(this).val();  //gets replacement text from a text box
    var thistoken = "firstname";

    var between = false;
    $("#gentextCodeArea").contents().each(function () {
        if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
            if (between) return false;
            between = true;
        } else if (between) {
            this.nodeValue = thisval;
            thisval = '';
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
    <!--firstname-->Harrison<!--firstname-->
    <!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>

What went wrong in your code

By using text() you don't get the comment tags. To get those, you need to use html() instead

replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate

It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.

Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:

$("#fname").on("input", function () {
    var thisval = $(this).val();  //gets replacement text from a text box
    var thistoken = "firstname";

    currentTemplate = $("#gentextCodeArea").html();  //fetch the html
    var tokenstring = "<!--" + thistoken + "-->"
    var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
    currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
    $("#gentextCodeArea").html(currentTemplate);   //put the new text back
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
    <!--firstname-->Harrison<!--firstname-->
    <!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>


问:
Severe: org.hibernate.TransactionException: nested transactions not supported
I am doing this tutorial on Hibernate: https://netbeans.org/kb/docs/web/hibernate-webapp.html

My issue:
After I am done with the instructions and run the project, I get Hibernate Error: "Severe:   org.hibernate.TransactionException: nested transactions not supported"

I tried "tx.commit();" to close the transaction but that didn't change anything.

question: why did it work when the tutorial people wrote the instructions but not working now? and how to get it to work?

答:
change

```<code>    public FilmHelper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }
</code>```

to

```<code>    public FilmHelper() {
        this.session = HibernateUtil.getSessionFactory().openSession();
    }
</code>```

Reason:
Tutorial uses Hibernate 3 and now I am using Hibernate 4.
In Hibernate3, once transaction is complete it is closed and the same session is allowed to open a new transaction w/ NoProblem.
In Hibernate4, once transaction is complete it is still open. if a developer close it then the session close with it. developer has to manually open a new session.

If anyone knows more about Hibernate and like to add to this, please comment below me.

Body:
change

    public FilmHelper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

to

    public FilmHelper() {
        this.session = HibernateUtil.getSessionFactory().openSession();
    }

Reason:
Tutorial uses Hibernate 3 and now I am using Hibernate 4.
In Hibernate3, once transaction is complete it is closed and the same session is allowed to open a new transaction w/ NoProblem.
In Hibernate4, once transaction is complete it is still open. if a developer close it then the session close with it. developer has to manually open a new session.

If anyone knows more about Hibernate and like to add to this, please comment below me.


问:
Conditionally Applying class with ternary operator
I've got a Button component that I'd like to assign an active class to if the state is 'true'. </p>

```<code><Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>
</code>```

答:
To work with conditional classes is better if you use classnames</p>

```<code>var btnClass = classNames({
  'col-sm-12': true,
  'text-center': true,
  'active': this.state.straight
});
<Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={btnClass}
    viewStyle="primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>
</code>```

Body:
I've got a Button component that I'd like to assign an active class to if the state is 'true'.

<Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={"col-sm-12 text-center " + (this.state.straight ? "active") }
    viewStyle=  "primary"
>

Straight

</Button>

Body:
To work with conditional classes is better if you use classnames

var btnClass = classNames({
  'col-sm-12': true,
  'text-center': true,
  'active': this.state.straight
});
<Button
    onClick={this.preferenceHandler.bind(this, "straight")}
    className={btnClass}
    viewStyle="primary"
>
    <h4>Straight</h4>
    <i className="icon icon-ok-6"></i>
</Button>


问:
Doctrine flush changes and free up memory
I'm experiencing problems working on a Symfony project with low memory limit. I need to create several entities, add them to another entity (entities are associated) and then flush changes to database. This happens in a while loop.

The problem is that sometimes the loop can't finish the whole cycle because the process crashes for memory exhausting. Of course I can't raise the memory limit.

I try to explain you better with some code...

Entities structure

```<code>class Device
{
    /**
     * @ORM\ManyToMany(targetEntity="Resource", inversedBy="devices",cascade={"persist", "refresh"}, fetch="EXTRA_LAZY")
     */
    protected $resources;

    public function addResource(Resource $resource)
    {
        if ($this->resources->contains($resource)) return;
        $this->resources->add($resource);
        $resource->addDevice($this);
    }
}

class Resource
{
    /**
     * @ORM\ManyToMany(targetEntity="Device", mappedBy="resources")
     */
    protected $devices;

    public function addDevice(Device $device)
    {
        if ($this->devices->contains($device)) return;
        $this->devices->add($device);
        $device->addResource($this);
    }
}
</code>```

The loop

```<code>function doIt(Device $device) {
    while(...) {
        $res = new Resource(...);
        $device->addResource($res); // store $res in memory until end
    }
    $em->persist($device);
    $em->flush();
}
</code>```

So the problem is that until the loop finishes, $device keeps in memory Resource objects and sometimes memory limit is reached.

What I tried so far

```<code>function doIt(Device $device) {
   $i = 0;
   while(...) {
       $res = new Resource(...);
       $device->addResource($res);
       $i++;
       if ($i % 100 == 0) {
              $em->persist($device);
              $em->flush($device);
              $device->setResources(null); // free up Resources in memory
              $em->refresh($device); // Resources are not stored in memory
       }
   }
   $em->persist($device);
   $em->flush();
}
</code>```

This works not that good even because I see memory raising anyway (probably caused then by Doctrine). Moreover there are a lot of entities and several associations between them, and checking results in database gives me something wrong (e.g. an Entity not persisted).

What would you do?

答: I never persist more then 50 entity after flush. Try to decrease $i to 50 or less. Maybe that help.</p>

Body:
I'm experiencing problems working on a Symfony project with low memory limit. I need to create several entities, add them to another entity (entities are associated) and then flush changes to database. This happens in a while loop.

The problem is that sometimes the loop can't finish the whole cycle because the process crashes for memory exhausting. Of course I can't raise the memory limit.

I try to explain you better with some code...

Entities structure

class Device
{
    /**
     * @ORM\ManyToMany(targetEntity="Resource", inversedBy="devices",cascade={"persist", "refresh"}, fetch="EXTRA_LAZY")
     */
    protected $resources;

    public function addResource(Resource $resource)
    {
        if ($this->resources->contains($resource)) return;
        $this->resources->add($resource);
        $resource->addDevice($this);
    }
}

class Resource
{
    /**
     * @ORM\ManyToMany(targetEntity="Device", mappedBy="resources")
     */
    protected $devices;

    public function addDevice(Device $device)
    {
        if ($this->devices->contains($device)) return;
        $this->devices->add($device);
        $device->addResource($this);
    }
}

The loop

function doIt(Device $device) {
    while(...) {
        $res = new Resource(...);
        $device->addResource($res); // store $res in memory until end
    }
    $em->persist($device);
    $em->flush();
}

So the problem is that until the loop finishes, $device keeps in memory Resource objects and sometimes memory limit is reached.

What I tried so far

function doIt(Device $device) {
   $i = 0;
   while(...) {
       $res = new Resource(...);
       $device->addResource($res);
       $i++;
       if ($i % 100 == 0) {
              $em->persist($device);
              $em->flush($device);
              $device->setResources(null); // free up Resources in memory
              $em->refresh($device); // Resources are not stored in memory
       }
   }
   $em->persist($device);
   $em->flush();
}

This works not that good even because I see memory raising anyway (probably caused then by Doctrine). Moreover there are a lot of entities and several associations between them, and checking results in database gives me something wrong (e.g. an Entity not persisted).

What would you do?


问:
Ember.js testing: follow  link
I'm testing an Ember app and I've got a link inside a table.

I can get to the link by the selector:

```<code>$('tr:nth-child(1) td:nth-child(3) a')
</code>```

In my test I have:

```<code>click($('tr:nth-child(1) td:nth-child(3) a'));
</code>```

But after doing console.log(currentURL()); I am not on the link that the above click should have taken me to.

Do I need to be more specific with the link to click? Or am I using click wrong? Or is there a different test helper I should be using?

答:
I am having this exact problem.  In the Ember app, I can click on the  tag and a modal dialog pops up, as expected.  In the test I'm writing for this modal, nothing seems to work.  I can type

```<code>Ember.$('#id-of-tag').click();
</code>```

on the JS console, and the modal appears.  I paste that into the test and nothing happens.
I've tried click(find('#id-of-tag')[0]) too.

We're using Ember 2.7.3 but will switch to 2.12 very soon.

Title: Ember.js testing: follow <a> link

Body:
I'm testing an Ember app and I've got a link inside a table.

I can get to the link by the selector:

$('tr:nth-child(1) td:nth-child(3) a')

In my test I have:

click($('tr:nth-child(1) td:nth-child(3) a'));

But after doing console.log(currentURL()); I am not on the link that the above click should have taken me to.

Do I need to be more specific with the link to click? Or am I using click wrong? Or is there a different test helper I should be using?

Body:
I am having this exact problem.  In the Ember app, I can click on the  tag and a modal dialog pops up, as expected.  In the test I'm writing for this modal, nothing seems to work.  I can type

Ember.$('#id-of-tag').click();

on the JS console, and the modal appears.  I paste that into the test and nothing happens.
I've tried click(find('#id-of-tag')[0]) too.

We're using Ember 2.7.3 but will switch to 2.12 very soon.


问:
Mysql password expired and my mysql.user table is corrupted
Okay, I have a little problem.

My password is expired and my users table is corrupted. I can login via

```<code>mysql -u root -p
</code>```

but on every action I perform I get the folowing error:

Column count of mysql.user is wrong. Expected 45, found 46. The table is probably corrupted.

I have read that you can fix the mysql.user table with the folowing command:

```<code>mysql_upgrade -u root -p
</code>```

But when I do that I get the folowing error:

mysql_upgrade: Got error: 1862: Your password has expired. To log in you
  must change it using a client that supports expired passwords. while
  connecting to the MySQL server
  Upgrade process encountered error and will not continue.
  So, How do I fix this?

I have backups of all my tables so I won't be a problem if I have to reset all my databases.

(why the weird format? Stackoverflow thinks it's all code and wants me to put it in code blocks, otherwise I can not save it)

EDIT:

I know my password. That's not the problem at all.

My problem is that the password is expired and I am not able to do anything becuase my mysql.user is corrupted!

答:
Try to disable the password expiration option: edit the my.cnf and put

```<code>[mysqld]
default_password_lifetime=0
</code>```

and try to restart mysql server and try again login again.
the source is here https://dev.mysql.com/doc/refman/5.7/en/password-expiration-policy.html

For repairing the database you run mysqlcheck --repair --databases db_name or mysqlcheck --repair --all-databases for repairing all databases
The source is here https://dev.mysql.com/doc/refman/5.7/en/rebuilding-tables.html
You could first try to repair the database then you could try to disable password lifetime.

Body:
Okay, I have a little problem.

My password is expired and my users table is corrupted. I can login via

mysql -u root -p

but on every action I perform I get the folowing error:

Column count of mysql.user is wrong. Expected 45, found 46. The table is probably corrupted.

I have read that you can fix the mysql.user table with the folowing command:

mysql_upgrade -u root -p

But when I do that I get the folowing error:

mysql_upgrade: Got error: 1862: Your password has expired. To log in you
  must change it using a client that supports expired passwords. while
  connecting to the MySQL server
  Upgrade process encountered error and will not continue.
  So, How do I fix this?

I have backups of all my tables so I won't be a problem if I have to reset all my databases.

(why the weird format? Stackoverflow thinks it's all code and wants me to put it in code blocks, otherwise I can not save it)

EDIT:

I know my password. That's not the problem at all.

My problem is that the password is expired and I am not able to do anything becuase my mysql.user is corrupted!

Body:
Try to disable the password expiration option: edit the my.cnf and put

[mysqld]
default_password_lifetime=0

and try to restart mysql server and try again login again.
the source is here https://dev.mysql.com/doc/refman/5.7/en/password-expiration-policy.html

For repairing the database you run mysqlcheck --repair --databases db_name or mysqlcheck --repair --all-databases for repairing all databases
The source is here https://dev.mysql.com/doc/refman/5.7/en/rebuilding-tables.html
You could first try to repair the database then you could try to disable password lifetime.


问:
Running multiple Kivy apps at same time that communicate with each other
I would like my Kivy application to be able to spawn multiple apps (i.e. new windows) on a Windows machine that can communicate with each other.

ScreenManager and Popup options will not cut it because they live in the same window..I need to be able to drag new screens across multiple monitors and therefore need multiple windows.

Kivy docs explicitly state that "Kivy supports only one window
per application: please don't try to create more than one."

A google search produces this simple approach of simple spawning a new app from within another app, like so:

```<code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label

class ChildApp(App):
    def build(self):
        return Label(text='Child')

class MainApp(App):

    def build(self):
        b = Button(text='Launch Child App')
        b.bind(on_press=self.launchChild)
        return b

    def launchChild(self, button):
        ChildApp().run()

if __name__ == '__main__':
    MainApp().run()
</code>```

However, when I do this, it launches the app within the same window and crashes, and my terminal spits out like crazy:

```<code>Original exception was:
Error in sys.exceptionhook:
</code>```

I get the same result if instead of ChildApp().run() I do multiprocessing.Process(target=ChildApp().run()).start()

Using the subprocess library gets me closer to what I want:

```<code># filename: test2.py

from kivy.app import App
from kivy.uix.label import Label

class ChildApp(App):
    def build(self):
        return Label(text='Child')

if __name__ == '__main__':
    ChildApp().run()
</code>```

```<code># filename: test.py

from kivy.app import App
from kivy.uix.button import Button

import subprocess

class MainApp(App):

    def build(self):
        b = Button(text='Launch Child App')
        b.bind(on_press=self.launchChild)
        return b

    def launchChild(self, button):
        subprocess.call('ipython test2.py', shell=True)

if __name__ == '__main__':
    MainApp().run()
</code>```

This spawns the child window without error, however now the main window is locked (white canvas) and if I close the child window, it just gets reopened.

They need to be able pass data between one another. Any ideas on how to do this correctly in Windows? This post seems to suggest that this is possible but I'm not sure where to start.

答:
I tried baconwichsand's code and can confirm with Python 3.6 and Windows 10 it does not work. Apparently only top level object classes can be pickled, and since both apps inherit from the App class python throws an error. However a top level definition that simply executes the ChildApp().run() command can be pickled and works. Here is my working code.

```<code>import multiprocessing
from kivy.app import App
from kivy.uix.label import Label

class MainApp(App):
    def build(self):
        return Label(text='Main App Window')

class OtherApp(App):
    def build(self):
        return Label(text='Other App Window')

def open_parent():
    MainApp().run()

def open_child():
    OtherApp().run()

if __name__ == '__main__':
    a = multiprocessing.Process(target=open_parent)
    b = multiprocessing.Process(target=open_child)
    a.start()
    b.start()
</code>```

And here is the code I am using, including the Builder to use a shared .kv file for both windows.

```<code>import multiprocessing
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.widget import Widget

class MainRoot(Widget):
    pass

class OtherRoot(Widget):
    pass

class MainApp(App):
    def build(self):
        Builder.load_file('B:\Python_Codes\Testing Grounds\shared.kv')
        main = MainRoot()
        return main

class OtherApp(App):
    def build(self):
        Builder.load_file('B:\Python_Codes\Testing Grounds\shared.kv')
        other = OtherRoot()
        return other

def open_parent():
    MainApp().run()

def open_child():
    OtherApp().run()

if __name__ == '__main__':
    a = multiprocessing.Process(target=open_parent)
    b = multiprocessing.Process(target=open_child)
    a.start()
    b.start()
</code>```

Body:
I would like my Kivy application to be able to spawn multiple apps (i.e. new windows) on a Windows machine that can communicate with each other.

ScreenManager and Popup options will not cut it because they live in the same window..I need to be able to drag new screens across multiple monitors and therefore need multiple windows.

Kivy docs explicitly state that "Kivy supports only one window
per application: please don't try to create more than one."

A google search produces this simple approach of simple spawning a new app from within another app, like so:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label

class ChildApp(App):
    def build(self):
        return Label(text='Child')

class MainApp(App):

    def build(self):
        b = Button(text='Launch Child App')
        b.bind(on_press=self.launchChild)
        return b

    def launchChild(self, button):
        ChildApp().run()

if __name__ == '__main__':
    MainApp().run()

However, when I do this, it launches the app within the same window and crashes, and my terminal spits out like crazy:

Original exception was:
Error in sys.exceptionhook:

I get the same result if instead of ChildApp().run() I do multiprocessing.Process(target=ChildApp().run()).start()

Using the subprocess library gets me closer to what I want:

# filename: test2.py

from kivy.app import App
from kivy.uix.label import Label

class ChildApp(App):
    def build(self):
        return Label(text='Child')

if __name__ == '__main__':
    ChildApp().run()

# filename: test.py

from kivy.app import App
from kivy.uix.button import Button

import subprocess

class MainApp(App):

    def build(self):
        b = Button(text='Launch Child App')
        b.bind(on_press=self.launchChild)
        return b

    def launchChild(self, button):
        subprocess.call('ipython test2.py', shell=True)

if __name__ == '__main__':
    MainApp().run()

This spawns the child window without error, however now the main window is locked (white canvas) and if I close the child window, it just gets reopened.

They need to be able pass data between one another. Any ideas on how to do this correctly in Windows? This post seems to suggest that this is possible but I'm not sure where to start.

Body:
I tried baconwichsand's code and can confirm with Python 3.6 and Windows 10 it does not work. Apparently only top level object classes can be pickled, and since both apps inherit from the App class python throws an error. However a top level definition that simply executes the ChildApp().run() command can be pickled and works. Here is my working code.

import multiprocessing
from kivy.app import App
from kivy.uix.label import Label

class MainApp(App):
    def build(self):
        return Label(text='Main App Window')

class OtherApp(App):
    def build(self):
        return Label(text='Other App Window')

def open_parent():
    MainApp().run()

def open_child():
    OtherApp().run()

if __name__ == '__main__':
    a = multiprocessing.Process(target=open_parent)
    b = multiprocessing.Process(target=open_child)
    a.start()
    b.start()

And here is the code I am using, including the Builder to use a shared .kv file for both windows.

import multiprocessing
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.widget import Widget

class MainRoot(Widget):
    pass

class OtherRoot(Widget):
    pass

class MainApp(App):
    def build(self):
        Builder.load_file('B:\Python_Codes\Testing Grounds\shared.kv')
        main = MainRoot()
        return main

class OtherApp(App):
    def build(self):
        Builder.load_file('B:\Python_Codes\Testing Grounds\shared.kv')
        other = OtherRoot()
        return other

def open_parent():
    MainApp().run()

def open_child():
    OtherApp().run()

if __name__ == '__main__':
    a = multiprocessing.Process(target=open_parent)
    b = multiprocessing.Process(target=open_child)
    a.start()
    b.start()


问:
AJAX HTTP GET request must be fired twice to work
I'm writing an ajax chat program, and I'm having a weird bug. I have to call a GET request twice for it to handle it properly. The first time it's fired it seems to respond fine to the server, however it will not activate the the function assigned to onreadystatechange [ getChatText() ] until the second time it's called. Not sure what's causing it, and I figured you guys could help.

Code posted below.

Javascript:

```<code>var recieveReq = getXmlHttpRequestObject();
var sendReq = getXmlHttpRequestObject();
var lastMessage = "NULL";
var mTimer;

//Create XMLHTTP Object
function getXmlHttpRequestObject() {
    return new XMLHttpRequest();
};

//GET & POST creation
function getChatText() {
    if (recieveReq.readyState == 4 || recieveReq.readyState == 0) {
        recieveReq.onreadystatechange = handleRecieveChat();
        recieveReq.open("GET", 'chat.php?chat=1', true);
        recieveReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        recieveReq.send(null);
    };
};
function sendChatText() {
    if(document.getElementById('text_message').value == '') {
        alert("You have not entered a message");
        return;
    };
    if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        sendReq.onreadystatechange = handleSendChat();
        sendReq.open("POST", 'chat.php?send=1', true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        var param = '&message=' + document.getElementById('text_message').value;
        sendReq.send(param);
        document.getElementById('text_message').value = '';
    };
};

//Handle Send & Receive
function handleRecieveChat() {
    if (recieveReq.readyState == 4 && recieveReq.status == 200) {
        var chatDiv = document.getElementById('div_chat');
        var tempResponse = recieveReq.responseText;
        var response = tempResponse.replace(/\\\//g,"/");
        if (response != lastMessage) {
            chatDiv.innerHTML = response;
        };
        chatDiv.scrollTop = chatDiv.scrollHeight;
        lastMessage = response;
        mTimer = setTimeout('getChatText();', 5000);
    };
};
function handleSendChat() {
    clearInterval(mTimer);
    if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        getChatText();
    }
};

function resetChat() {}; //Empty for now

document.onload = getChatText();
</code>```

PHP:

```<code><?php
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
    header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
    header("Cache-Control: no-cache, must-revalidate" );
    header("Pragma: no-cache" );
    header("Content-Type: text/plain; charset=utf-8");

    $connect = mysqli_connect("localhost", "user", "password", "database");

    if (!$connect) {
        die('Could not connect: ' . mysqli_connect_errno($connect));
    }

    if(isset($_GET["chat"])) {
        $sql = "SELECT * FROM message ORDER BY message_id;";
        $result = mysqli_query($connect, $sql);
        $row = mysqli_fetch_array($result);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $time = substr($row['post_time'], 0, 5);
                echo "<span style=color:".$row['user_color'].">".$row['user_name']."</span> (".$time."): ".$row['message']."<br>";
            }
        }
        $connect->close();
    }

    if(isset($_POST['message']) && $_POST['message'] != '') {
        $sql = "INSERT INTO message (chat_id, user_id, user_name, message, post_time, user_color) VALUES (1, 3, 'Riley', '".$_POST['message']."', NOW(), '#29D410');";    //Couple are default for testing purposes
        $result = mysqli_query($connect, $sql);
        echo $sql;
        $connect->close();
    }
?>
</code>```

PS:
Please don't bother with pointing out sql input sanitation or other things I haven't gotten to yet. Just answers for this http request handling bug please. Thanks.

答:
onreadystatechange is an event handler and as such should be referencing a function. In your code, you're referencing the result of handleReceiveChat and handleSendChat which are both returning nothing, soundefined. Try changing to the following:

receiveReq.onreadystatechange = handleReceiveChat

sendReq.onreadystatechange = handleSendChat;

It will appear as though the call is working the second time, however, the code will be using the response from the first call (as the second response won't have completed yet).

Body:
I'm writing an ajax chat program, and I'm having a weird bug. I have to call a GET request twice for it to handle it properly. The first time it's fired it seems to respond fine to the server, however it will not activate the the function assigned to onreadystatechange [ getChatText() ] until the second time it's called. Not sure what's causing it, and I figured you guys could help.

Code posted below.

Javascript:

var recieveReq = getXmlHttpRequestObject();
var sendReq = getXmlHttpRequestObject();
var lastMessage = "NULL";
var mTimer;

//Create XMLHTTP Object
function getXmlHttpRequestObject() {
    return new XMLHttpRequest();
};

//GET & POST creation
function getChatText() {
    if (recieveReq.readyState == 4 || recieveReq.readyState == 0) {
        recieveReq.onreadystatechange = handleRecieveChat();
        recieveReq.open("GET", 'chat.php?chat=1', true);
        recieveReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        recieveReq.send(null);
    };
};
function sendChatText() {
    if(document.getElementById('text_message').value == '') {
        alert("You have not entered a message");
        return;
    };
    if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        sendReq.onreadystatechange = handleSendChat();
        sendReq.open("POST", 'chat.php?send=1', true);
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        var param = '&message=' + document.getElementById('text_message').value;
        sendReq.send(param);
        document.getElementById('text_message').value = '';
    };
};

//Handle Send & Receive
function handleRecieveChat() {
    if (recieveReq.readyState == 4 && recieveReq.status == 200) {
        var chatDiv = document.getElementById('div_chat');
        var tempResponse = recieveReq.responseText;
        var response = tempResponse.replace(/\\\//g,"/");
        if (response != lastMessage) {
            chatDiv.innerHTML = response;
        };
        chatDiv.scrollTop = chatDiv.scrollHeight;
        lastMessage = response;
        mTimer = setTimeout('getChatText();', 5000);
    };
};
function handleSendChat() {
    clearInterval(mTimer);
    if (sendReq.readyState == 4 || sendReq.readyState == 0) {
        getChatText();
    }
};

function resetChat() {}; //Empty for now

document.onload = getChatText();

PHP:

<?php
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
    header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
    header("Cache-Control: no-cache, must-revalidate" );
    header("Pragma: no-cache" );
    header("Content-Type: text/plain; charset=utf-8");

    $connect = mysqli_connect("localhost", "user", "password", "database");

    if (!$connect) {
        die('Could not connect: ' . mysqli_connect_errno($connect));
    }

    if(isset($_GET["chat"])) {
        $sql = "SELECT * FROM message ORDER BY message_id;";
        $result = mysqli_query($connect, $sql);
        $row = mysqli_fetch_array($result);
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $time = substr($row['post_time'], 0, 5);
                echo "".$row['user_name']." (".$time."): ".$row['message']."
";
            }
        }
        $connect->close();
    }

    if(isset($_POST['message']) && $_POST['message'] != '') {
        $sql = "INSERT INTO message (chat_id, user_id, user_name, message, post_time, user_color) VALUES (1, 3, 'Riley', '".$_POST['message']."', NOW(), '#29D410');";    //Couple are default for testing purposes
        $result = mysqli_query($connect, $sql);
        echo $sql;
        $connect->close();
    }
?>

PS:
Please don't bother with pointing out sql input sanitation or other things I haven't gotten to yet. Just answers for this http request handling bug please. Thanks.


问:
keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error
Good day, I keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error.

Can someone please assist with why and where?

Any help will be greatly appriciated

Below is the code

```<code>Try
        conec.Open()

        Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName =  '" & TxtName.Text & "', LastName =  '" & txtSurname.Text & "', Access =  '" & cmbAccess.SelectedItem & "', CreatedBY =  '" & Label9.Text & "', DateCreated =  '" & Label10.Text & "', ChangedBY =  '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd  hh:mm tt") & "' WHERE UserName = " & txtUserName.Text & ";")

        cmd.CommandType = CommandType.Text
        cmd.Connection = conec
        cmd.ExecuteNonQuery()
        MessageBox.Show("Data Updated" & vbCrLf & "Done")
        conec.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
</code>```

答:
Looks like you're missing apostrophes in your where clause, try:

```<code>   Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName =  '" & TxtName.Text & "', LastName =  '" & txtSurname.Text & "', Access =  '" & cmbAccess.SelectedItem & "', CreatedBY =  '" & Label9.Text & "', DateCreated =  '" & Label10.Text & "', ChangedBY =  '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd  hh:mm tt") & "' WHERE UserName = '" & txtUserName.Text & "';")
</code>```

I recommend using SQL Parameters however, they're a lot easier to maintain.

Body:
Good day, I keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error.

Can someone please assist with why and where?

Any help will be greatly appriciated

Below is the code

Try
        conec.Open()

        Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName =  '" & TxtName.Text & "', LastName =  '" & txtSurname.Text & "', Access =  '" & cmbAccess.SelectedItem & "', CreatedBY =  '" & Label9.Text & "', DateCreated =  '" & Label10.Text & "', ChangedBY =  '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd  hh:mm tt") & "' WHERE UserName = " & txtUserName.Text & ";")

        cmd.CommandType = CommandType.Text
        cmd.Connection = conec
        cmd.ExecuteNonQuery()
        MessageBox.Show("Data Updated" & vbCrLf & "Done")
        conec.Close()

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

Body:
Looks like you're missing apostrophes in your where clause, try:

   Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName =  '" & TxtName.Text & "', LastName =  '" & txtSurname.Text & "', Access =  '" & cmbAccess.SelectedItem & "', CreatedBY =  '" & Label9.Text & "', DateCreated =  '" & Label10.Text & "', ChangedBY =  '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd  hh:mm tt") & "' WHERE UserName = '" & txtUserName.Text & "';")

I recommend using SQL Parameters however, they're a lot easier to maintain.


问:
VBA to copy sheets from all files in folder and copy it to master
I have a folder full of multiple excel files and all of the files have a specific sheet that i need to copy into my master.

I need macro to open all files in that folder one by one and copy the specific sheet to the master file using the source file name as sheet name in the master workbook. Excel 2013.

I tried searching online and have the following code:

```<code>Option Explicit

Sub test()

Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xls")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    'Your copy/paste code here (((((need help here please))))))))
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation

End Sub
</code>```

EDIT:

So i manage to get to the below however its still not working properly. It doesn't rename the sheet to the source filename. Can someone please help?

Option Explicit

Sub test()

```<code>Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xlsx")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation
</code>```

End Sub

答:
so the part you need help with is how to copy/paste a range from a worksheet in one file to a common worksheet in a destination file?

set up a variable to track the last empty row in the destination sheet

look up how to determine what the last row is in each source sheet, select that source range, copy it into the clipboard, and then paste it at the last empty row in the destination sheet, and reset the destination variable to the new first blank row in the destination sheet

an alternative way of doing it would be to open an output CSV file, and parse each row and build up a string and write it to the file without closing the output CSV file until the loop is over

if the files are large tho, it would be much better to use VB.NET instead as it is much faster at dealing with large files

you could also read each file/row into an in-memory datatable and then output the datatable to a CSV file, or to the destination Excel file

which method would you prefer?

Body:
I have a folder full of multiple excel files and all of the files have a specific sheet that i need to copy into my master.

I need macro to open all files in that folder one by one and copy the specific sheet to the master file using the source file name as sheet name in the master workbook. Excel 2013.

I tried searching online and have the following code:

Option Explicit

Sub test()

Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xls")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    'Your copy/paste code here (((((need help here please))))))))
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation

End Sub

EDIT:

So i manage to get to the below however its still not working properly. It doesn't rename the sheet to the source filename. Can someone please help?

Option Explicit

Sub test()

Dim wkbDest As Workbook
Dim wksDest As Worksheet
Dim wkbSource As Workbook
Dim wksSource As Worksheet
Dim MyPath As String
Dim MyFile As String

Application.ScreenUpdating = False

Set wkbDest = ThisWorkbook
Set wksDest = wkbDest.Worksheets("Sheet1") 'change the destination sheet name accordingly

MyPath = "H:\Cutover\"

If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"

MyFile = Dir(MyPath & "*.xlsx")

Do While Len(MyFile) > 0
    Set wkbSource = Workbooks.Open(MyPath & MyFile)
    Set wksSource = wkbSource.Worksheets("Sheet1") 'change the source sheet name accordingly
    Sheets("SheetToCopy").Copy Before:=Workbooks("WorkbookToPasteIn").Sheets(SheetIndex)
    wkbSource.Close savechanges:=False
    MyFile = Dir
Loop

Application.ScreenUpdating = True

MsgBox "Completed...", vbInformation

End Sub


问:
Bayer Ordered Dithering
I'm updating a plugin for Paint.net which i made some months ago, it's called Simulate Color Depth and it reduces the number of colors in the image to the chosen BPP and for a long time it have had dithering included but NEVER ordered dithering and i thought it would be a nice addition to have that in so i started to search on the internet for something useful, i ended up on this wiki page here http://en.wikipedia.org/wiki/Ordered_dithering, and tried to do as written in the pseudo code

```<code>for (int y = 0; x < image.Height; y++)
{
    for (int x = 0; x < image.Width; x++)
    {
        Color color = image.GetPixel(x, y);
        color.R = color.R + bayer8x8[x % 8, y % 8];
        color.G = color.G + bayer8x8[x % 8, y % 8];
        color.B = color.B + bayer8x8[x % 8, y % 8];
        image.SetPixel(x, y, GetClosestColor(color, bitdepth);
    }
}
</code>```

but the result is way too bright so i decided to check the wiki page again and then i see that there's a "1/65" to the right of the threshold map which got me thinking of both error diffusing (yes i know, weird huh?) and dividing the value i get from bayer8x8[x % 8, y % 8] with 65 and then multiply the value with the color channels, but either the results were messy or else still too bright (as i remember it) but the results were nothing like i have seen elsewhere, either too bright, too high contrast or too messy and i haven't found anything really useful searching through the internet, so do anyone know how i can get this bayer dithering working properly?

Thanks in advance, Cookies

答:
Try this:

```<code>color.R = color.R + bayer8x8[x % 8, y % 8] * GAP / 65;
</code>```

Here GAP should be the distance between the two nearest color thresholds. This depends on the bits per pixel.

For example, if you are converting the image to use 4 bits for the red component of each pixel, there are 16 levels of red total. They are: R=0, R=17, R=34, ... R=255.  So GAP would be 17.

Title: Bayer Ordered Dithering

Body:
I'm updating a plugin for Paint.net which i made some months ago, it's called Simulate Color Depth and it reduces the number of colors in the image to the chosen BPP and for a long time it have had dithering included but NEVER ordered dithering and i thought it would be a nice addition to have that in so i started to search on the internet for something useful, i ended up on this wiki page here http://en.wikipedia.org/wiki/Ordered_dithering, and tried to do as written in the pseudo code

for (int y = 0; x < image.Height; y++)
{
    for (int x = 0; x < image.Width; x++)
    {
        Color color = image.GetPixel(x, y);
        color.R = color.R + bayer8x8[x % 8, y % 8];
        color.G = color.G + bayer8x8[x % 8, y % 8];
        color.B = color.B + bayer8x8[x % 8, y % 8];
        image.SetPixel(x, y, GetClosestColor(color, bitdepth);
    }
}

but the result is way too bright so i decided to check the wiki page again and then i see that there's a "1/65" to the right of the threshold map which got me thinking of both error diffusing (yes i know, weird huh?) and dividing the value i get from bayer8x8[x % 8, y % 8] with 65 and then multiply the value with the color channels, but either the results were messy or else still too bright (as i remember it) but the results were nothing like i have seen elsewhere, either too bright, too high contrast or too messy and i haven't found anything really useful searching through the internet, so do anyone know how i can get this bayer dithering working properly?

Thanks in advance, Cookies

Body:
Try this:

color.R = color.R + bayer8x8[x % 8, y % 8] * GAP / 65;

Here GAP should be the distance between the two nearest color thresholds. This depends on the bits per pixel.

For example, if you are converting the image to use 4 bits for the red component of each pixel, there are 16 levels of red total. They are: R=0, R=17, R=34, ... R=255.  So GAP would be 17.


问:
Different bit mappings with anonymous structs
I would like to implement different mappings for some number of bits.
I came up with this solution that works reasonably well for me:

```<code>union myBits{
 // constructors

 struct{ // Mapping 1
   uint16_t a : 8, b : 8;
 };
 struct{ // Mapping 2
   uint16_t c : 10, d : 6;
 };
};
</code>```

I can then access the different bit mappings simply by

```<code>myBits mb(/**/);
mb.c = 10;
mb.a = 2;
</code>```

I think this functionality is very elegant, although it is not considered standard C++.
g++ and clang produce warnings (Telling me that anonymous structs are not explicity allowed in the standard), Visual Studio compiles the code without producing any warnings.

My question is: Is there a modern C++1x way of writing the same code with the same functionality that does not include just naming the structs ?

答:
Due to the constraints C++ has in comparison to C, I don't see any efficient, legal and elegant way to do this in standard C++. You can choose only two of the three attributes :)

Efficient and legal, but not elegant

```<code>struct myBits
{
    void set_bits(size_t start_bit, size_t end_bit, uint16_t value)
    {
        size_t len = end_bit - start_bit + 1;
        uint16_t mask = ((1 << len) - 1) << (start_bit - 1);
        word = (word & ~mask) | ((value << (start_bit - 1)) & mask);
    }
    uint16_t get_bits(size_t start_bit, size_t end_bit)
    {
        size_t len = end_bit - start_bit + 1;
        return (word >> (start_bit - 1)) & ((1 << len) - 1);
    }
    uint16_t word;
};
</code>```

To use it like in your scenario:

```<code>myBits mb;
mb.set_bits(1, 10, 10);
mb.set_bits(1, 8, 2);
</code>```

This is possibly not really as efficient as the code in the question, it really depends on how the compiler generates the code for accessing bit fields vs the code above. The upside of this compared to the initial solution is that you can access any subset of bits without defining new structs and bit-fields for it.

Legal and elegant, but not efficient

```<code>template<size_t start_bit, size_t end_bit>
struct bit_field
{
    bit_field(uint16_t& w) : word(w) {}

    operator uint16_t() const
    {
        return (word >> (start_bit - 1)) & ((1 << len) - 1);
    }

    bit_field& operator=(uint16_t value)
    {
        uint16_t mask = ((1 << len) - 1) << (start_bit - 1);
        word = (word & ~mask) | ((value << (start_bit - 1)) & mask);
        return *this;
    }

    const size_t len = end_bit - start_bit + 1;
    uint16_t &word;
};

struct Word
{
    Word(uint16_t w) : word(w), a(word), b(word), c(word), d(word) {}

    uint16_t word;
    bit_field<1, 8> a;
    bit_field<9, 16> b;
    bit_field<1, 10> c;
    bit_field<11, 16> d;
};
</code>```

The usage in this case is as elegant as in your example:

```<code>Word w(0);
w.c = 10;
w.a = 2;
</code>```

The problem with this approach is that it's really space inefficient. You must have a struct declared for every bit field, compared to the initial approach of just storing bits.

Efficient and elegant, but not legal

This would basically be the way you described in the question.

Body:
I would like to implement different mappings for some number of bits.
I came up with this solution that works reasonably well for me:

union myBits{
 // constructors

 struct{ // Mapping 1
   uint16_t a : 8, b : 8;
 };
 struct{ // Mapping 2
   uint16_t c : 10, d : 6;
 };
};

I can then access the different bit mappings simply by

myBits mb(/**/);
mb.c = 10;
mb.a = 2;

I think this functionality is very elegant, although it is not considered standard C++.
g++ and clang produce warnings (Telling me that anonymous structs are not explicity allowed in the standard), Visual Studio compiles the code without producing any warnings.

My question is: Is there a modern C++1x way of writing the same code with the same functionality that does not include just naming the structs ?

Body:
Due to the constraints C++ has in comparison to C, I don't see any efficient, legal and elegant way to do this in standard C++. You can choose only two of the three attributes :)

Efficient and legal, but not elegant

struct myBits
{
    void set_bits(size_t start_bit, size_t end_bit, uint16_t value)
    {
        size_t len = end_bit - start_bit + 1;
        uint16_t mask = ((1 << len) - 1) << (start_bit - 1);
        word = (word & ~mask) | ((value << (start_bit - 1)) & mask);
    }
    uint16_t get_bits(size_t start_bit, size_t end_bit)
    {
        size_t len = end_bit - start_bit + 1;
        return (word >> (start_bit - 1)) & ((1 << len) - 1);
    }
    uint16_t word;
};

To use it like in your scenario:

myBits mb;
mb.set_bits(1, 10, 10);
mb.set_bits(1, 8, 2);

This is possibly not really as efficient as the code in the question, it really depends on how the compiler generates the code for accessing bit fields vs the code above. The upside of this compared to the initial solution is that you can access any subset of bits without defining new structs and bit-fields for it.

Legal and elegant, but not efficient

template<size_t start_bit, size_t end_bit>
struct bit_field
{
    bit_field(uint16_t& w) : word(w) {}

    operator uint16_t() const
    {
        return (word >> (start_bit - 1)) & ((1 << len) - 1);
    }

    bit_field& operator=(uint16_t value)
    {
        uint16_t mask = ((1 << len) - 1) << (start_bit - 1);
        word = (word & ~mask) | ((value << (start_bit - 1)) & mask);
        return *this;
    }

    const size_t len = end_bit - start_bit + 1;
    uint16_t &word;
};

struct Word
{
    Word(uint16_t w) : word(w), a(word), b(word), c(word), d(word) {}

    uint16_t word;
    bit_field<1, 8> a;
    bit_field<9, 16> b;
    bit_field<1, 10> c;
    bit_field<11, 16> d;
};

The usage in this case is as elegant as in your example:

Word w(0);
w.c = 10;
w.a = 2;

The problem with this approach is that it's really space inefficient. You must have a struct declared for every bit field, compared to the initial approach of just storing bits.

Efficient and elegant, but not legal

This would basically be the way you described in the question.


问:
Out-of-process Classic COM EXE using Windows Runtime Template Library (WRL)
I have followed the example here: http://msdn.microsoft.com/en-us/library/vstudio/jj822931.aspx to create an In-proc Classic COM DLL using Windows Runtime Template Library (WRL). I am also able to modify to code to run the DLL as COM surrogate (wrapped inside DllHost.exe).

However, I couldn't find the way to create an out-of-process COM EXE using the WRL. There is a simple example using barebone COM API here: http://www.codeproject.com/Articles/3173/A-simple-yet-debuggable-COM-skeleton-code, but I'd like to know how I can utilize WRL to simplify that.

Thanks.

答:
Yes it is possible.  I just got one working.  Here's the basics that are required, as compared to implementing an in-proc coclass.

Implement your coclass using WRL::RuntimeClass the same way you would for an in-proc class. (https://msdn.microsoft.com/en-us/library/jj822931.aspx)

In your main function, create a module object using WRL::Module<OutOfProc>::Create(), and call module.RegisterObjects() on startup, and module.UnregisterObjects() and module.Terminate() on shutdown.

You need to build a DLL to host the proxies: https://msdn.microsoft.com/en-us/library/windows/desktop/ms688707(v=vs.85).aspx

Static Registrations: DO register the Interface and the CLSID of your proxy stub. DO NOT statically register your coclass.

In the Client, when you call CoCreateInstance, be sure to use the appropriate CLSCTX. (I use CLSCTX_ALL when the hosting model is not important to the client.)

(I know it's been almost 4 years, but I had the same question this week.)


问:
Application Insights, convert time difference to milliseconds
How can I convert time difference into milliseconds in Azure Application Insights

```<code>let startTime = todatetime('2017-05-15T17:02:23.7148691Z');
let endTime = todatetime('2017-05-15T17:02:25.5430172Z');
let timeDifference = endTime-startTime;
requests
| project timeDifference
| limit 1
</code>```

The above query outputs

```<code>00:00:01.8281481
</code>```

I would like to display it in milliseconds

For ex: 1828

答:
You can divide your timespan by another timespan. So, to get number of milliseconds you can do the following:

```<code>let startTime = todatetime('2017-05-15T17:02:23.7148691Z');
let endTime = todatetime('2017-05-15T17:02:25.5430172Z');
let timeDifference = endTime-startTime;
// get total milliseconds
requests
| extend timeDifferenceMilliseconds = timeDifference / time(1ms)
| project timeDifferenceMilliseconds
| limit 1
</code>```

More about date and time expressions can be found here: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-analytics-reference#date-and-time-expressions

Body:
How can I convert time difference into milliseconds in Azure Application Insights

let startTime = todatetime('2017-05-15T17:02:23.7148691Z');
let endTime = todatetime('2017-05-15T17:02:25.5430172Z');
let timeDifference = endTime-startTime;
requests
| project timeDifference
| limit 1

The above query outputs

00:00:01.8281481

I would like to display it in milliseconds

For ex: 1828

Body:
You can divide your timespan by another timespan. So, to get number of milliseconds you can do the following:

let startTime = todatetime('2017-05-15T17:02:23.7148691Z');
let endTime = todatetime('2017-05-15T17:02:25.5430172Z');
let timeDifference = endTime-startTime;
// get total milliseconds
requests
| extend timeDifferenceMilliseconds = timeDifference / time(1ms)
| project timeDifferenceMilliseconds
| limit 1

More about date and time expressions can be found here: https://learn.microsoft.com/en-us/azure/application-insights/app-insights-analytics-reference#date-and-time-expressions


问:
setAnchorPoint for UIImage?
All,

This is probably very basic, but I cannot find an answer that works for me.

Simple enough -- I want to rotate an image around an endpoint, not the center.  I know that all I really need is to be able to set the anchor point of the image and then apply the transform.

I cannot, however, figure out how to set the anchor point of the image (or should it be an UIImageView?)

```<code>UIImageView * imgv = nil;
UIImage * image;

imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"greenbar.png"]];
image = [imgv image];
image.layer.anchorPoint =  CGPointMake(0.5, 1.0);***-- Request for member 'layer' in something not a structure or union.***
imgv.image.layer.anchorPoint = CGPointMake(0.5, 1.0); ***-- Request for member 'layer' in something not a structure or union.***
imgv.layer.anchorPoint = CGPointMake(0.5, 1.0);  ***-- Accessing unknown 'anchorPoint' component of a property.***
</code>```

This is driving me crazy, so please help! :)

Thank you!

:bp:

答:
layer is imageView property so the following line should be correct:

```<code>imgv.layer.anchorPoint = CGPointMake(0.5, 1.0);
</code>```

The reason you get this error may be that you need to import quartzcore header:

```<code>#import <QuartzCore/QuartzCore.h>
</code>```

Title: setAnchorPoint for UIImage?

Body:
All,

This is probably very basic, but I cannot find an answer that works for me.

Simple enough -- I want to rotate an image around an endpoint, not the center.  I know that all I really need is to be able to set the anchor point of the image and then apply the transform.

I cannot, however, figure out how to set the anchor point of the image (or should it be an UIImageView?)

UIImageView * imgv = nil;
UIImage * image;

imgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"greenbar.png"]];
image = [imgv image];
image.layer.anchorPoint =  CGPointMake(0.5, 1.0);***-- Request for member 'layer' in something not a structure or union.***
imgv.image.layer.anchorPoint = CGPointMake(0.5, 1.0); ***-- Request for member 'layer' in something not a structure or union.***
imgv.layer.anchorPoint = CGPointMake(0.5, 1.0);  ***-- Accessing unknown 'anchorPoint' component of a property.***

This is driving me crazy, so please help! :)

Thank you!

:bp:

Body:
layer is imageView property so the following line should be correct:

imgv.layer.anchorPoint = CGPointMake(0.5, 1.0);

The reason you get this error may be that you need to import quartzcore header:

#import <QuartzCore/QuartzCore.h>


问:
Check if Timer is running
I have been trying to refill in game lives with a timer, but whenever I leave a view and return, the timer duplicates and becomes faster. I have tried to address this with the Timer?.isValid function to only run the timer when it is invalid so it never duplicates, but it cannot seem to check is the timer is invalid in an if statement.

This is the if statement that I have been using so far:

```<code>if (myTimer?.isValid){
} else{
//start timer
}
</code>```

Any help would be appreciated, thanks.

答: You need to check if your Timer instance isValid (not the Timer class), let's say: if myTimer.isValid? {}.

Title: Check if Timer is running

Body:
I have been trying to refill in game lives with a timer, but whenever I leave a view and return, the timer duplicates and becomes faster. I have tried to address this with the Timer?.isValid function to only run the timer when it is invalid so it never duplicates, but it cannot seem to check is the timer is invalid in an if statement.

This is the if statement that I have been using so far:

if (myTimer?.isValid){
} else{
//start timer
}

Any help would be appreciated, thanks.