问:
Why 'args cannot be read at compile time'
I am trying to use mixin in following code:

```<code>import std.stdio;
import std.file;

void main(string[] args){
    if (args.length != 2)   {
        writeln("usage: ./app < number expression >");
        return;
    }
    else    {
        // following statements work ok:
        writeln(args);
        writeln(args.length);
        writeln(args[1]);

        // following 2 statements do not work; same error:
        //mixin("writeln("~args[1]~");"); //    Error: variable args cannot be read at compile time
        writeln(mixin(args[1]));  //        Error: variable args cannot be read at compile time
    }
}
</code>```

But I am getting following error:

```<code>$ rdmd soq_mycalc.d
soq_mycalc.d(17): Error: variable args cannot be read at compile time
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_mycalc.d", "-I."]
</code>```

Where is the problem and how can it be corrected?

Edit: I want to call this program with argument: "2+2" and want the program to calculate it.

Following also does not work:

```<code>char[] mainarg = args[1].dup;
writeln(mixin(mainarg));  // Error: variable args cannot be read at compile time
</code>```

答:
If I understand well, what you are trying to achieve is some form of expression evaluation (which involves parsing an expression grammar). BASH for an example has eval() that can take arbitrary expression as string, and return a value (if the expression is valid).

D standard library does not have such function as far as I know.

For a simple solution I would use Pegged (Reference). DLang Tour's Pegged page is a good starting point so I recommend you start from there.

Body:
I am trying to use mixin in following code:

import std.stdio;
import std.file;

void main(string[] args){
    if (args.length != 2)   {
        writeln("usage: ./app < number expression >");
        return;
    }
    else    {
        // following statements work ok:
        writeln(args);
        writeln(args.length);
        writeln(args[1]);

        // following 2 statements do not work; same error:
        //mixin("writeln("~args[1]~");"); //    Error: variable args cannot be read at compile time
        writeln(mixin(args[1]));  //        Error: variable args cannot be read at compile time
    }
}

But I am getting following error:

$ rdmd soq_mycalc.d
soq_mycalc.d(17): Error: variable args cannot be read at compile time
Failed: ["/usr/bin/dmd", "-v", "-o-", "soq_mycalc.d", "-I."]

Where is the problem and how can it be corrected?

Edit: I want to call this program with argument: "2+2" and want the program to calculate it.

Following also does not work:

char[] mainarg = args[1].dup;
writeln(mixin(mainarg));  // Error: variable args cannot be read at compile time


来源: stackexchange

问:
Service: v1.Service.Spec: v1.ServiceSpec.Selector: ReadString: expects " or n, but found t
```<code>kubectl create -f redis.yaml
Error from server (BadRequest): error when creating "redis.yaml": Service in version "v1" cannot be handled as a Service: v1.Service.Spec: v1.ServiceSpec.Selector: ReadString: expects " or n, but found t, error found in #10 byte of ...|service":true}}}
|..., bigger context ...|79,"protocol":"TCP"}],"selector":{"redisservice":true}}}
|...
</code>```

What does this error mean?

```<code>apiVersion: v1
kind: Service
metadata:
  name: redis
spec:
  selector:
    redis-service: yes
  ports:
  - protocol: TCP
    port: 6379
  - protocol: TCP
    port: 26379
  - protocol: TCP
    port: 16379
</code>```

答:
Yaml yes values evaluate to a boolean. So should  be quoted...

```<code>redis-service: "yes"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
kubectl create -f redis.yaml
Error from server (BadRequest): error when creating "redis.yaml": Service in version "v1" cannot be handled as a Service: v1.Service.Spec: v1.ServiceSpec.Selector: ReadString: expects " or n, but found t, error found in #10 byte of ...|service":true}}}
|..., bigger context ...|79,"protocol":"TCP"}],"selector":{"redisservice":true}}}
|...

What does this error mean?

apiVersion: v1
kind: Service
metadata:
  name: redis
spec:
  selector:
    redis-service: yes
  ports:
  - protocol: TCP
    port: 6379
  - protocol: TCP
    port: 26379
  - protocol: TCP
    port: 16379

Body:
Yaml yes values evaluate to a boolean. So should  be quoted...

redis-service: "yes"


问:
How to undo setting Elasticsearch Index to readonly?
So I just set one of my indices to readonly, and now want to delete it.

To set it to readonly:

```<code>PUT my_index/_settings
{ "index": { "index.blocks.read_only" : true } }
</code>```

When I tried to delete it I got this response:

```<code>ClusterBlockException[blocked by: [FORBIDDEN/5/index read-only (api)];]
</code>```

Then I tried to set the index to readonly false:

```<code>PUT my_index/_settings
{ "index": { "index.blocks.read_only" : false } }
</code>```

But that gives the same error message as above. So how to set readonly back to false?

答:
If you have Kibana installed, you can go to your kibana url:

```<code>Management (Left pane) -> Elasticseach Index Management -> Select your Index -> Edit Settings
</code>```

then update:

```<code>"index.blocks.read_only_allow_delete": "false"
</code>```

Also, to set it globally on kibana you can go to dev tools (left pane) and make the following request:

```<code>PUT _settings
{
  "index": {
    "blocks": {
      "read_only_allow_delete": "false"
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I just set one of my indices to readonly, and now want to delete it.

To set it to readonly:

PUT my_index/_settings
{ "index": { "index.blocks.read_only" : true } }

When I tried to delete it I got this response:

ClusterBlockException[blocked by: [FORBIDDEN/5/index read-only (api)];]

Then I tried to set the index to readonly false:

PUT my_index/_settings
{ "index": { "index.blocks.read_only" : false } }

But that gives the same error message as above. So how to set readonly back to false?

Body:
If you have Kibana installed, you can go to your kibana url:

Management (Left pane) -> Elasticseach Index Management -> Select your Index -> Edit Settings

then update:

"index.blocks.read_only_allow_delete": "false"

Also, to set it globally on kibana you can go to dev tools (left pane) and make the following request:

PUT _settings
{
  "index": {
    "blocks": {
      "read_only_allow_delete": "false"
    }
  }
}


问:
Websphere Migration from was7 to was9
Planning to Migrate the Websphere from 7.0 to 9 and 8.5 to 9.
Can anyone help me getting the detailed Process

Migration here is "In place". (Migration will be done on the same servers, where the old Installation are in)

if at all any migration tools need to be used, please provide the clear info on them.
any documental references, or any video references for the questioner is appreciated.

OS used : RHEL
CUrrent version: WAS 7x and 8.5
Migrating to : WAS 9.0

答:
It sounds like you're in the very beginning stages of doing this migration. Therefore, I highly recommend you take some time to plan this out, especially to figure out the exact steps you'll be taking and how you'll handle something going wrong. For WebSphere, there is a collection of documents from IBM that discuss planning and executing the upgrade. Look around there for documentation on the tools and step by step guides for different kinds of topologies. The step by step guide for an in place migration of a cell is here.

You should make sure to take good backups before you start the process so you can restore back to before the migration if you need to.

In addition to doing the upgrade, an important part is to also make sure your applications are going to work on the new version if you haven't already. IBM provides this tool to scan applications and identify potential issues that developers will have to fix. There is documentation for the tool at that link as well.

Title: Websphere Migration from was7 to was9


问:
Adding a custom VS Code setting for a file type (.pug)
How can I set a VS code setting active only an a certain file extension?

In my case it's
"editor.renderWhitespace": "boundary" on all .pug and .jade files.

Thanks!

答:
Place your settings within an object that has the keyword [jade] (Source):

```<code>{
    "[jade]": {
        "editor.renderWhitespace": "boundary",
    }
}
</code>```

The above will support both jade and pug files, you don't need to define it for both.

Body:
Place your settings within an object that has the keyword [jade] (Source):

{
    "[jade]": {
        "editor.renderWhitespace": "boundary",
    }
}

The above will support both jade and pug files, you don't need to define it for both.


问:
Swift Conditional String Interpolation
I often trap myself writing code like this when I need to construct a string depending on some condition (in this case isFavorite):

let me = Contact(name: "Stefan", isFavorite: true)

var message = "Contact \(me.name)"
if me.isFavorite {
    message.append(" is a favorite contact")
}
```

These are 4 lines or alternatively a complex ternary operator (if ? then : else) for such a simple task. I always have a bad conscience with this...

Is there a way to do this more elegantly with Swift?

答:
Swift 5

Indeed there is - I found the answer at the UIKonf 2019 where I heard from Erica Sadun that there is a way by using Swift 5 String Interpolation to achieve this in one single line. All you need is this reusable extension:

extension String.StringInterpolation {
    mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
        guard condition() else { return }
        appendLiteral(literal)
    }
}
```

<p>It enables you to transform your 4 lines into just one:</p>

<pre class="lang-swift prettyprint-override"><code>"Contact: \(me.name)\(if: me.isFavorite, " is a favorite contact")"
</code>```

You can read about the different possibilities of Swift's string interpolation in in Erica's article: https://ericasadun.com/2018/12/12/the-beauty-of-swift-5-string-interpolation/

Playground

Start getting your hands dirty with this:

import Foundation

// *****************************************************************************
// Many thanks to Erica Sadun for describing the new possibilities of string
// interpolation in Swift 5
// *****************************************************************************

// *****************************************************************************
// Conditional Interpolation

struct Contact {
    let name: String
    let isFavorite: Bool
}
let me = Contact(name: "Stefan", isFavorite: true)

// ***************************************************************** Swift 4

var message = "Contact \(me.name)"
if me.isFavorite {
    message.append(" is favorite")
}
message // we need 4 lines to construct this message!!!
"Contact: \(me.name)\(me.isFavorite ? " is favorite" : "")" // or a complex ternary operator

// ***************************************************************** Swift 5

extension String.StringInterpolation {

    mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
        guard condition() else { return }
        appendLiteral(literal)
    }
}
"Contact: \(me.name)\(if: me.isFavorite, " is favorite")" // simple and clean - no extras

// *****************************************************************************
// Optional Interpolation

let optionalMe: Contact? = Contact(name: "Stefan", isFavorite: true)

// ***************************************************************** Swift 4

"Contact: \(optionalMe?.name)" // shows warning

// ***************************************************************** Swift 5

// Interpolate nil value
extension String.StringInterpolation {
    /// Provides `Optional` string interpolation without forcing the
    /// use of `String(describing:)`.
    public mutating func appendInterpolation<T>(_ value: T?, default defaultValue: String) {
        if let value = value {
            appendInterpolation(value)
        } else {
            appendLiteral(defaultValue)
        }
    }
}
let nilContact: Contact? = nil
"Contact: \(nilContact?.name, default: "nil")"

// Strip `Optional`
extension String.StringInterpolation {
    /// Interpolates an optional using "stripped" interpolation, omitting
    /// the word "Optional" from both `.some` and `.none` cases
    public mutating func appendInterpolation<T>(describing value: T?) {
        if let value = value {
            appendInterpolation(value)
        } else {
            appendLiteral("nil")
        }
    }

}
"Contact: \(describing: optionalMe?.name)"
```

Title: Swift Conditional String Interpolation

Body:
I often trap myself writing code like this when I need to construct a string depending on some condition (in this case isFavorite):

let me = Contact(name: "Stefan", isFavorite: true)

var message = "Contact \(me.name)"
if me.isFavorite {
    message.append(" is a favorite contact")
}

These are 4 lines or alternatively a complex ternary operator (if ? then : else) for such a simple task. I always have a bad conscience with this...

Is there a way to do this more elegantly with Swift?

Body:
Swift 5

Indeed there is - I found the answer at the UIKonf 2019 where I heard from Erica Sadun that there is a way by using Swift 5 String Interpolation to achieve this in one single line. All you need is this reusable extension:

extension String.StringInterpolation {
    mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
        guard condition() else { return }
        appendLiteral(literal)
    }
}

It enables you to transform your 4 lines into just one:

"Contact: \(me.name)\(if: me.isFavorite, " is a favorite contact")"

You can read about the different possibilities of Swift's string interpolation in in Erica's article: https://ericasadun.com/2018/12/12/the-beauty-of-swift-5-string-interpolation/

Playground

Start getting your hands dirty with this:

import Foundation

// *****************************************************************************
// Many thanks to Erica Sadun for describing the new possibilities of string
// interpolation in Swift 5
// *****************************************************************************

// *****************************************************************************
// Conditional Interpolation

struct Contact {
    let name: String
    let isFavorite: Bool
}
let me = Contact(name: "Stefan", isFavorite: true)

// ***************************************************************** Swift 4

var message = "Contact \(me.name)"
if me.isFavorite {
    message.append(" is favorite")
}
message // we need 4 lines to construct this message!!!
"Contact: \(me.name)\(me.isFavorite ? " is favorite" : "")" // or a complex ternary operator

// ***************************************************************** Swift 5

extension String.StringInterpolation {

    mutating func appendInterpolation(if condition: @autoclosure () -> Bool, _ literal: StringLiteralType) {
        guard condition() else { return }
        appendLiteral(literal)
    }
}
"Contact: \(me.name)\(if: me.isFavorite, " is favorite")" // simple and clean - no extras

// *****************************************************************************
// Optional Interpolation

let optionalMe: Contact? = Contact(name: "Stefan", isFavorite: true)

// ***************************************************************** Swift 4

"Contact: \(optionalMe?.name)" // shows warning

// ***************************************************************** Swift 5

// Interpolate nil value
extension String.StringInterpolation {
    /// Provides `Optional` string interpolation without forcing the
    /// use of `String(describing:)`.
    public mutating func appendInterpolation<T>(_ value: T?, default defaultValue: String) {
        if let value = value {
            appendInterpolation(value)
        } else {
            appendLiteral(defaultValue)
        }
    }
}
let nilContact: Contact? = nil
"Contact: \(nilContact?.name, default: "nil")"

// Strip `Optional`
extension String.StringInterpolation {
    /// Interpolates an optional using "stripped" interpolation, omitting
    /// the word "Optional" from both `.some` and `.none` cases
    public mutating func appendInterpolation<T>(describing value: T?) {
        if let value = value {
            appendInterpolation(value)
        } else {
            appendLiteral("nil")
        }
    }

}
"Contact: \(describing: optionalMe?.name)"


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答: We initially wrote an app using JPA ever since the day it went into production we have regretted it.  The amount of database calls being made by the ORM were astronomical, so we have now started the process of piece-meal rewriting the application using good ol' fashioned JDBC utilizing Spring's JDBC helper classes.  The pitfalls of starting with an ORM is that we spent a good deal of time learning JPA and at the end of the day we have to replace it with JDBC so our application can be more scalable without adding 3 other nodes to our Oracle RAC.  So if you balance it out, the control and precision of JDBC was worth the extra lines of code you have to write.  Also, most people do not understand that SQL is not something that can be generated and expected to perform.  It is something that has to be written and tweaked to gain maximium performance.</p>

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments

OwnerDisplayName: Nick


问:
Pandas create a dataframe whose entries are relationships between rows of another dataframe?
Suppose I have the following table in a csv.

```<code> elementID | groupID | sequence
     abc   |    A    |    0
     dcv   |    A    |    1
     asd   |    B    |    1
     ccc   |    B    |    0
     abc   |    B    |    2
</code>```

I imported this table in Pandas as a DataFrame.

From this DataFrame I need to create another one where each entry represents two two sequential elements of elementID.

For example something like the following

```<code> elementID_1 | elementID_2 | groupID
     abc     |    dcv      |    A
     asd     |    abc      |    B
     ccc     |    asd      |    B
</code>```

At first I thought of a multi-row selection but could not find out how to do that.

So I decided to do step by step creating one column per time.
I created first the column elementID_2 as follows

```<code>new_df = pd.DataFrame()
new_df[["elementID_2", "sequence", "groupID"]] = old_df.loc[old_df.loc.sequence>1][["elementID", "sequence", "groupID"]]
</code>```

Now to create the elementID_1 column I would like to match the entries of the old dataframe having assequence value, the sequence value of the new DataFrame minus 1 and the same groupdID between the two DataFrame.

How can I do that?

答:
Here is one way using groupby + itertools

```<code>s=df.groupby('groupID').elementID.apply(lambda x : set(itertools.combinations(x.values.tolist(), 2)))
df1=pd.DataFrame(s.index.repeat(s.str.len()))
df2=pd.DataFrame(list(itertools.chain(*s.tolist())))
pd.concat([df1,df2],axis=1)
Out[286]:
  groupID    0    1
0       A  abc  dcv
1       B  asd  abc
2       B  asd  ccc
3       B  ccc  abc
</code>```

Body:
Suppose I have the following table in a csv.

 elementID | groupID | sequence
     abc   |    A    |    0
     dcv   |    A    |    1
     asd   |    B    |    1
     ccc   |    B    |    0
     abc   |    B    |    2

I imported this table in Pandas as a DataFrame.

From this DataFrame I need to create another one where each entry represents two two sequential elements of elementID.

For example something like the following

 elementID_1 | elementID_2 | groupID
     abc     |    dcv      |    A
     asd     |    abc      |    B
     ccc     |    asd      |    B

At first I thought of a multi-row selection but could not find out how to do that.

So I decided to do step by step creating one column per time.
I created first the column elementID_2 as follows

new_df = pd.DataFrame()
new_df[["elementID_2", "sequence", "groupID"]] = old_df.loc[old_df.loc.sequence>1][["elementID", "sequence", "groupID"]]

Now to create the elementID_1 column I would like to match the entries of the old dataframe having assequence value, the sequence value of the new DataFrame minus 1 and the same groupdID between the two DataFrame.

How can I do that?

Body:
Here is one way using groupby + itertools

s=df.groupby('groupID').elementID.apply(lambda x : set(itertools.combinations(x.values.tolist(), 2)))
df1=pd.DataFrame(s.index.repeat(s.str.len()))
df2=pd.DataFrame(list(itertools.chain(*s.tolist())))
pd.concat([df1,df2],axis=1)
Out[286]:
  groupID    0    1
0       A  abc  dcv
1       B  asd  abc
2       B  asd  ccc
3       B  ccc  abc


问:
How to check for double entries in my sql table?
i'm a newbie in programming and still learning.
I've created a database in mySQL to store a fictional restaurant's reservations. I got my site's form up and running, when you enter your info (email/seats needed/date/hour) it registers and is entered into the database successfully. But now i'm trying to check and see if i have double entries in my database to then send a message to my customer saying "sorry, that table is already booked, please choose another time or date"

just to make it simple, all i want to check for now is if the "seating table" in question is already in the database more than 2 times, if a third attempt is made i want to error message to appear, but i can't seem to figure out how to check my sql for that, here is the code i have for now...  the column i'm checking is the seating table "5-8" people,   my selections are 1-2, 3-4 and 5-8.
5-8 is what is written in the sql table column as "text"

```<code>require_once("config.php.inc");

$idConnexion = new mysqli($serveur, $utilisateur, $motDePasse, $bd, $port);

if ($idConnexion->connect_error) {
    die('Erreur de connexion (' . $idConnexion->connect_errno . ') ' .$idConnexion->connect_error);
}

$requete = $idConnexion->query("SELECT * FROM tables") or die("La requete a echouee!");
$tableau = $requete->fetch_array();
$heure_res = $tableau["heure"];
$date_res = $tableau["date_res"];
$nombre_res = $tableau["nombre_personnes"];

if (($tableau = $requete->fetch_array()) !=FALSE) {
    $nombre_table = $nombre_res == "5-8";
    if (count($nombre_table) >= 2) {
        echo "Il n'y a plus de place, choisissez une autre heure ou date.";
    } else {
        $resultats = $idConnexion->query("INSERT INTO `tables` SET email = '$_GET[email]', nombre_personnes ='$_GET[nombre_personne]', date_res = '$_GET[date_res]', heure = '$_GET[heure_preference]'") or die("La requête a échouée! : (" . $idConnexion->errno . ") " . $idConnexion->error);
        $message = "L'ajout de la réservation a été fait avec succès!";
        include("succes_interface.php");
    }
}
</code>```

once i fetch the array, i'm trying to see if the "5-8" is in the database more than twice, to return an error, and if it is less than 2, then PHP can continue and add the reservation into the database.

I really hope i'm asking the right questions, I have searched StackOverflow for an answer, but didn't have any luck.

Thank you in advance.

答:
you must put an ID (ID int NOT NULL AUTO_INCREMENT,) in your table so your tables have an id which will guarantee that every table are unique.
When somebody try to make a reservation you will have the id of the table and compare it with the reservation so you can't have two same table.</p>

Body:
i'm a newbie in programming and still learning.
I've created a database in mySQL to store a fictional restaurant's reservations. I got my site's form up and running, when you enter your info (email/seats needed/date/hour) it registers and is entered into the database successfully. But now i'm trying to check and see if i have double entries in my database to then send a message to my customer saying "sorry, that table is already booked, please choose another time or date"

just to make it simple, all i want to check for now is if the "seating table" in question is already in the database more than 2 times, if a third attempt is made i want to error message to appear, but i can't seem to figure out how to check my sql for that, here is the code i have for now...  the column i'm checking is the seating table "5-8" people,   my selections are 1-2, 3-4 and 5-8.
5-8 is what is written in the sql table column as "text"

require_once("config.php.inc");

$idConnexion = new mysqli($serveur, $utilisateur, $motDePasse, $bd, $port);

if ($idConnexion->connect_error) {
    die('Erreur de connexion (' . $idConnexion->connect_errno . ') ' .$idConnexion->connect_error);
}

$requete = $idConnexion->query("SELECT * FROM tables") or die("La requete a echouee!");
$tableau = $requete->fetch_array();
$heure_res = $tableau["heure"];
$date_res = $tableau["date_res"];
$nombre_res = $tableau["nombre_personnes"];

if (($tableau = $requete->fetch_array()) !=FALSE) {
    $nombre_table = $nombre_res == "5-8";
    if (count($nombre_table) >= 2) {
        echo "Il n'y a plus de place, choisissez une autre heure ou date.";
    } else {
        $resultats = $idConnexion->query("INSERT INTO `tables` SET email = '$_GET[email]', nombre_personnes ='$_GET[nombre_personne]', date_res = '$_GET[date_res]', heure = '$_GET[heure_preference]'") or die("La requête a échouée! : (" . $idConnexion->errno . ") " . $idConnexion->error);
        $message = "L'ajout de la réservation a été fait avec succès!";
        include("succes_interface.php");
    }
}

once i fetch the array, i'm trying to see if the "5-8" is in the database more than twice, to return an error, and if it is less than 2, then PHP can continue and add the reservation into the database.

I really hope i'm asking the right questions, I have searched StackOverflow for an answer, but didn't have any luck.

Thank you in advance.


问:
How to validate type 'java.lang.Boolean' in Spring boot
I have a boolean field which I want to validate to have only "true" or "false" as value(without quotes). But this field is also allowing "true" or "false" as value(with quotes) which I want to restrict.

I tried to use @Pattern annotation to match these values.
But I have the following error:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Boolean'. Check configuration for 'restartable'

My code is:

```<code>@Pattern(regexp = "^(true|false)$", message = "restartable field allowed input: true or false")
private Boolean restartable;
</code>```

What should i do? Is there some other way to overcome this issue? Thanks in advance.

答:
you can use @NotNull and @AssertTrue or @AssertFalse assertions present in javax.validation if the goal is to enforce non null and truthy value.

https://docs.oracle.com/javaee/7/tutorial/bean-validation001.htm

```<code>@NotNull
@AssertTrue
private Boolean restartable;
</code>```

Not Null annotation would suffice if the value can be either true or false  as booleans in Java can only have two values.

Body:
I have a boolean field which I want to validate to have only "true" or "false" as value(without quotes). But this field is also allowing "true" or "false" as value(with quotes) which I want to restrict.

I tried to use @Pattern annotation to match these values.
But I have the following error:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Boolean'. Check configuration for 'restartable'

My code is:

@Pattern(regexp = "^(true|false)$", message = "restartable field allowed input: true or false")
private Boolean restartable;

What should i do? Is there some other way to overcome this issue? Thanks in advance.

Body:
you can use @NotNull and @AssertTrue or @AssertFalse assertions present in javax.validation if the goal is to enforce non null and truthy value.

https://docs.oracle.com/javaee/7/tutorial/bean-validation001.htm

@NotNull
@AssertTrue
private Boolean restartable;

Not Null annotation would suffice if the value can be either true or false  as booleans in Java can only have two values.


问:
C++ std::unique is not showing what I am expecting from it
I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)

```<code>    vector<int> nums2 = {1,2,3,4};
    vector<int> nums = {1,2,3,1};
    cout << "nums1" << endl;
    vector<int> a(nums.begin(), nums.end());
    auto ip = unique(nums.begin(), nums.begin()+nums.size());
    nums.resize( std::distance(nums.begin(),ip) );
    cout << a.size() <<  " " << nums.size() << endl;

    cout << "Nums2" << endl;
    vector<int> a2(nums2.begin(), nums2.end());
    auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
    nums.resize( std::distance(nums2.begin(),ip2) );
    cout << a2.size() <<  " " << nums2.size();
</code>```

The actual output is

```<code>nums1
4 4
Nums2
4 4
</code>```

but it  should have been

```<code>nums1
4 3
Nums2
4 4
</code>```

答:
std::unique only removes consecutive duplicates. From cppreference.com on std::unique :

Eliminates all but the first element from every consecutive group of equivalent elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

Your 1s are not consecutive so they aren't removed. This is the expected behavior. A quick solution is to first std::sort your range.

Body:
I was trying to find if the vector contains duplicates (please don't provide an algorithm to check duplicates.) I came up with this weird behavior. std::unique on vector 1,2,3,1 should make it 1,2,3,1 returning an iterator to 1 but on erasing the iterator returned till the vector.end() I got the same size vector as that of I original vector. Here is the snippet of code depicting the said behavior (available at ideone)

    vector<int> nums2 = {1,2,3,4};
    vector<int> nums = {1,2,3,1};
    cout << "nums1" << endl;
    vector<int> a(nums.begin(), nums.end());
    auto ip = unique(nums.begin(), nums.begin()+nums.size());
    nums.resize( std::distance(nums.begin(),ip) );
    cout << a.size() <<  " " << nums.size() << endl;

    cout << "Nums2" << endl;
    vector<int> a2(nums2.begin(), nums2.end());
    auto ip2 = unique(nums2.begin(), nums2.begin()+nums2.size());
    nums.resize( std::distance(nums2.begin(),ip2) );
    cout << a2.size() <<  " " << nums2.size();

The actual output is

nums1
4 4
Nums2
4 4

but it  should have been

nums1
4 3
Nums2
4 4


问:
Player sticks in a wall while moving on slope up
I made a simple slope movement in my GameMaker game.

Everything works fine except if player goes up slope and its speed is high enough not to have time to react to the collision code it gets stuck in the wall.

This is how it looks: GIF.

So my code looks like this:

Create Event:

```<code>hspd = 0;
vspd = 0;

grav = 2;
</code>```

Step Event:

```<code>// Movement
if (keyboard_check(vk_right) && !keyboard_check(vk_left)) {
    hspd = 9;
} else
if (keyboard_check(vk_left) && !keyboard_check(vk_right)) {
    hspd = -9;
}

// Check not moving
if ((!keyboard_check(vk_right) && !keyboard_check(vk_left)) || (keyboard_check(vk_right) && keyboard_check(vk_left))) {
    hspd = 0;
}

// Gravity
if (!place_meeting(x, y+1, parent_ground)) {
    vspd += grav;
}

// Jumping
if (place_meeting(x, y+1, parent_ground)) {
    if (keyboard_check_pressed(vk_up)) {
        vspd = -20;
    }
}

// Variables
var hspd_final = hspd;

// Horizontal collision
horizontal_collision = instance_place(x+hspd_final, y, parent_ground);
if (horizontal_collision != noone) {
    if (horizontal_collision.object_index == object_ground) {
        while (!place_meeting(x+sign(hspd_final), y, horizontal_collision)) {
            x += sign(hspd_final);
        }
        hspd_final = 0;
    } else {
        // Declare yplus
        yplus = 0;

        // Loop
        while (place_meeting(x+hspd_final, y-yplus, parent_ground) && yplus <= abs(1*hspd_final)) {
            yplus += 1;
        }
        y -= yplus;
        while (place_meeting(x, y+1, parent_ground)) {
            y -= 1;
        }
    }
}

// Down slope
down_slope = instance_place(x, y+1, parent_ground);
if (down_slope != noone && down_slope.object_index != object_ground) {
    if (place_meeting(x, y+1, parent_ground)) {
        yminus = abs(hspd_final);

        while (place_meeting(x+hspd_final, y+yminus, parent_ground) && yminus != 0) {
            yminus --;
        }

        y += yminus;
    }
}

// Initialize horizontal speed
x += hspd_final;

// Vertical collision
if (place_meeting(x, y+vspd, parent_ground)) {
    while (!place_meeting(x, y+sign(vspd), parent_ground)) {
        y += sign(vspd);
    }
    vspd = 0;
}

// Initialize vertical speed
y += vspd;
</code>```

I have 3 wall objects: object_ground (basic block), object_slope (percise slope object) and parent_ground (object which child objects are object_ground and object_slope).

Thank you.

答:
This is quite a common problem with game-maker, and it only have 2 real solutions.

Changing your room speed so it can keep up

Reducing your player(white cube) speed

Body:
I made a simple slope movement in my GameMaker game.

Everything works fine except if player goes up slope and its speed is high enough not to have time to react to the collision code it gets stuck in the wall.

This is how it looks: GIF.

So my code looks like this:

Create Event:

hspd = 0;
vspd = 0;

grav = 2;

Step Event:

// Movement
if (keyboard_check(vk_right) && !keyboard_check(vk_left)) {
    hspd = 9;
} else
if (keyboard_check(vk_left) && !keyboard_check(vk_right)) {
    hspd = -9;
}

// Check not moving
if ((!keyboard_check(vk_right) && !keyboard_check(vk_left)) || (keyboard_check(vk_right) && keyboard_check(vk_left))) {
    hspd = 0;
}

// Gravity
if (!place_meeting(x, y+1, parent_ground)) {
    vspd += grav;
}

// Jumping
if (place_meeting(x, y+1, parent_ground)) {
    if (keyboard_check_pressed(vk_up)) {
        vspd = -20;
    }
}

// Variables
var hspd_final = hspd;

// Horizontal collision
horizontal_collision = instance_place(x+hspd_final, y, parent_ground);
if (horizontal_collision != noone) {
    if (horizontal_collision.object_index == object_ground) {
        while (!place_meeting(x+sign(hspd_final), y, horizontal_collision)) {
            x += sign(hspd_final);
        }
        hspd_final = 0;
    } else {
        // Declare yplus
        yplus = 0;

        // Loop
        while (place_meeting(x+hspd_final, y-yplus, parent_ground) && yplus <= abs(1*hspd_final)) {
            yplus += 1;
        }
        y -= yplus;
        while (place_meeting(x, y+1, parent_ground)) {
            y -= 1;
        }
    }
}

// Down slope
down_slope = instance_place(x, y+1, parent_ground);
if (down_slope != noone && down_slope.object_index != object_ground) {
    if (place_meeting(x, y+1, parent_ground)) {
        yminus = abs(hspd_final);

        while (place_meeting(x+hspd_final, y+yminus, parent_ground) && yminus != 0) {
            yminus --;
        }

        y += yminus;
    }
}

// Initialize horizontal speed
x += hspd_final;

// Vertical collision
if (place_meeting(x, y+vspd, parent_ground)) {
    while (!place_meeting(x, y+sign(vspd), parent_ground)) {
        y += sign(vspd);
    }
    vspd = 0;
}

// Initialize vertical speed
y += vspd;

I have 3 wall objects: object_ground (basic block), object_slope (percise slope object) and parent_ground (object which child objects are object_ground and object_slope).

Thank you.


问:
What is GET/ error in node.js application?
I am trying to run my node.js application with npm start

The output I am getting is:

```<code>$ npm start

> alaka@1.0.0 start C:\Users\Alaka\Downloads\A4\API assignment 4
> nodemon app.js

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
</code>```

When I try to connect via localhost, I get error Cannot GET /

I tried running nodemon nodemon ./app.js and nodemon start 9000
  but the error is still the same.

Here's my app.js

```<code>const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

var uploadRouter = require('./Upload/upload');
const app = express();
app.use(express.json());

app.use('/uploads',express.static('./public/uploads'));
app.use(express.urlencoded({ extended: false }));

require('./DB/dbmongoose');
const User = require('./model/user');
const Product= require('./model/product');

app.use(bodyParser.urlencoded({ extended: false }));
app.use('/upload', uploadRouter);
module.exports = app;
app.post('/Register', (req, res) => {

    var user = new User(req.body);
    console.log(req.body);
    user.save();
});

app.get('/Login', function (req, res) {
    User.find().then(function (user) {
        res.send(user);
    }).catch(function (e) {
        res.send(e)
    });

});

app.post('/addproduct', (req, res) => {

    var product = new Product(req.body);
    console.log(req.body);
    product.save().then(function(product){
            res.send(product);
    }).catch(function (e){
        res.send(e);
    });
    });

app.get('/allproduct',(req, res, next) => {
    console.log('ok');
    Product.find({})
        .then((product) => {
            res.json(product);
        }, (err) => next(err))
        .catch((err) => next(err));
});

app.listen(9000);
</code>```

答:
Try using the following middleware for connection

```<code>//set port for connection
app.set('port', (process.env.PORT || 9000));

app.listen(app.get('port'), function(){
    console.log('Server started on port '+app.get('port'));
});
</code>```

Also as mentioned in the other comment.
Please have a route for home/*

```<code>app.get('/', (req, res) => {
  throw new Error('BROKEN');
})
</code>```

Body:
I am trying to run my node.js application with npm start

The output I am getting is:

$ npm start

> alaka@1.0.0 start C:\Users\Alaka\Downloads\A4\API assignment 4
> nodemon app.js

[nodemon] 1.19.1
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`

When I try to connect via localhost, I get error Cannot GET /

I tried running nodemon nodemon ./app.js and nodemon start 9000
  but the error is still the same.

Here's my app.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');

var uploadRouter = require('./Upload/upload');
const app = express();
app.use(express.json());

app.use('/uploads',express.static('./public/uploads'));
app.use(express.urlencoded({ extended: false }));

require('./DB/dbmongoose');
const User = require('./model/user');
const Product= require('./model/product');

app.use(bodyParser.urlencoded({ extended: false }));
app.use('/upload', uploadRouter);
module.exports = app;
app.post('/Register', (req, res) => {

    var user = new User(req.body);
    console.log(req.body);
    user.save();
});

app.get('/Login', function (req, res) {
    User.find().then(function (user) {
        res.send(user);
    }).catch(function (e) {
        res.send(e)
    });

});

app.post('/addproduct', (req, res) => {

    var product = new Product(req.body);
    console.log(req.body);
    product.save().then(function(product){
            res.send(product);
    }).catch(function (e){
        res.send(e);
    });
    });

app.get('/allproduct',(req, res, next) => {
    console.log('ok');
    Product.find({})
        .then((product) => {
            res.json(product);
        }, (err) => next(err))
        .catch((err) => next(err));
});

app.listen(9000);

Body:
Try using the following middleware for connection

//set port for connection
app.set('port', (process.env.PORT || 9000));

app.listen(app.get('port'), function(){
    console.log('Server started on port '+app.get('port'));
});

Also as mentioned in the other comment.
Please have a route for home/*

app.get('/', (req, res) => {
  throw new Error('BROKEN');
})


问:
How to disable localization warnings for some ui elements in Xcode?
I develops multilingual iOS project that has translations for UI elements in %LANG%.lproj/%STORYBOARD_NAME%.strings:

```<code>/* Class = "UINavigationItem"; title = "User information"; ObjectID = "yXU-vS-01l"; */
"yXU-vS-01l.title" = "User information";
</code>```

When UI element has no translation, Xcode writes warning in console:

```
Localizable string "yXU-vS-01l.title" not found in strings table "Main" of bundle CFBundle  (executable, loaded).
```

But some elements get its values at runtime only and doesn't need storyboard translations.

How can I disable warnings for such elements?
Now I see two ways:

Set localizable value as empty string

It helps with navigation items or other elements with visible bounds, but elements as labels and buttons will be invisible in design-time and also can be resize to zero-width

Add dummy translations to *.strings files

Will be too timespently when number of supporting languages will increase

May be another way exists? Eg set some property for UI element?

答: It's Xcode 10.2 now and I think in order to get rid of those warnings You should disable "Localization Debugging" in "Edit Scheme" -> "Options" for this target. </p>

Body:
I develops multilingual iOS project that has translations for UI elements in %LANG%.lproj/%STORYBOARD_NAME%.strings:

/* Class = "UINavigationItem"; title = "User information"; ObjectID = "yXU-vS-01l"; */
"yXU-vS-01l.title" = "User information";

When UI element has no translation, Xcode writes warning in console:

Localizable string "yXU-vS-01l.title" not found in strings table "Main" of bundle CFBundle  (executable, loaded).

But some elements get its values at runtime only and doesn't need storyboard translations.

How can I disable warnings for such elements?
Now I see two ways:

Set localizable value as empty string

It helps with navigation items or other elements with visible bounds, but elements as labels and buttons will be invisible in design-time and also can be resize to zero-width

Add dummy translations to *.strings files

Will be too timespently when number of supporting languages will increase

May be another way exists? Eg set some property for UI element?


问:
Using indices with a pointer without dereferencing
I am looking at a function that makes an identity matrix, but I am confused on some of the syntax that is being used.

```<code>/* make an identity matrix of ints */
real      **id_mat(int dim) {
    int         row, col;
    real      **mat;

    mat = (real **) alloc2d(dim, dim, sizeof(real));
    if(mat == NULL)
        return (mat);

    for(row = 0; row < dim; row++)
        for(col = 0; col < dim; col++)
            mat[row][col] = (row == col ? 1.0 : 0.0); /* here */

    return (mat);
}
</code>```

I am confused why mat is not being dereferenced to assign the row/column values. mat stores an address to a pointer, which I presume the goal is to keep the value changed outside of the function, so how does one build an array from an address? Should it not be **mat[row][col] = (row == col ? 1.0 : 0.0);? If not, why does this not work?

答:
I am confused why mat is not being dereferenced to assign the row/column values.

mat is indeed being dereferenced with the line:

```<code>mat[row][col] = (row == col ? 1.0 : 0.0); /* here */
</code>```

In C, the syntax a[i] is equivalent to *((a) + (i)), so what you have there is:

```<code>*(*((mat) + (row)) + (col)) = ...;
</code>```

In fact, since addition is commutative (even for addresses), you could just as easily have row[mat][col]. For example, observe the array access syntax as well as the output for the following code:

```<code>int a[10][10];
int i = 0;

memset(a, 0, 10 * 10 * sizeof(int));

i[a][5] = 100;

printf("%d\n", 0[a][5]);
</code>```

Body:
I am looking at a function that makes an identity matrix, but I am confused on some of the syntax that is being used.

/* make an identity matrix of ints */
real      **id_mat(int dim) {
    int         row, col;
    real      **mat;

    mat = (real **) alloc2d(dim, dim, sizeof(real));
    if(mat == NULL)
        return (mat);

    for(row = 0; row < dim; row++)
        for(col = 0; col < dim; col++)
            mat[row][col] = (row == col ? 1.0 : 0.0); /* here */

    return (mat);
}

I am confused why mat is not being dereferenced to assign the row/column values. mat stores an address to a pointer, which I presume the goal is to keep the value changed outside of the function, so how does one build an array from an address? Should it not be **mat[row][col] = (row == col ? 1.0 : 0.0);? If not, why does this not work?

Body:
I am confused why mat is not being dereferenced to assign the row/column values.

mat is indeed being dereferenced with the line:

mat[row][col] = (row == col ? 1.0 : 0.0); /* here */

In C, the syntax a[i] is equivalent to *((a) + (i)), so what you have there is:

*(*((mat) + (row)) + (col)) = ...;

In fact, since addition is commutative (even for addresses), you could just as easily have row[mat][col]. For example, observe the array access syntax as well as the output for the following code:

int a[10][10];
int i = 0;

memset(a, 0, 10 * 10 * sizeof(int));

i[a][5] = 100;

printf("%d\n", 0[a][5]);


问:
RegEx for replacing a string if it contains more than 2 decimals
I have this user price input that I want to allow 0, 1 or 2 decimal digits.

I'm using comma for decimals.

I'm not using nor allowing thousand separators.

QUESTION:

I want to replace the input if the user enters a third decimal digit.

Somethin like:

5 this is ok

5, this is ok, because it's waiting for the decimals

5,5 this is ok

5,55 this is ok

5,555 this is NOT OK, and I want to delete the last digit and go back to 5,55

5,555555555555 this is also NOT OK, the user might paste something with extra decimal digits and I want to trim them down to 2 decimals maximum, going back again to 5,55

How can I do this?

I know how I can match the end of the string: /[,\d+]$/

But how can I replace with the first two digits after the comma?

答:
Your pattern [,\d+]$ will match a comma a digit or a plus sign and assert the end of the string.

You could capture in a group 1+ digits,  an optional comma and 0-2 digits. then match 0+ digits afterwards and replace with group 1.

```<code>^(\d+,?\d{0,2})\d*$
</code>```

Explanation

^ Start of strig

( Capture group 1

\d+ 1+ digits

,? optional comma

\d{0,2} 0 - 2 digits

) Close group

\d* Match 0+ digits

$ Assert end of string

Regex demo

If you want to keep the part before the decimal, you could use a capturing group^(\d+),?\d{0,2}$ and replace with the first capturing group:

[
  "5",
  "5",
  "5,0",
  "5,00",
  "5,000"
].forEach(s => console.log(s.replace(/^(\d+,?\d{0,2})\d*$/, "$1")));```

Body:
Your pattern [,\d+]$ will match a comma a digit or a plus sign and assert the end of the string.

You could capture in a group 1+ digits,  an optional comma and 0-2 digits. then match 0+ digits afterwards and replace with group 1.

^(\d+,?\d{0,2})\d*$

Explanation

^ Start of strig

( Capture group 1

\d+ 1+ digits

,? optional comma

\d{0,2} 0 - 2 digits

) Close group

\d* Match 0+ digits

$ Assert end of string

Regex demo

If you want to keep the part before the decimal, you could use a capturing group^(\d+),?\d{0,2}$ and replace with the first capturing group:

[
  "5",
  "5",
  "5,0",
  "5,00",
  "5,000"
].forEach(s => console.log(s.replace(/^(\d+,?\d{0,2})\d*$/, "$1")));


答:
You are misunderstanding what std::unique does; it eliminates all but the first of any consecutive runs of elements. That is, it will not remove duplicates that are t adjacent.
Thus, to remove duplicates, you need to make sure all duplicates are located next to each other; the simplest way to do this with a std::vector is to first apply std::sort, and then std::unique.

Title: C++ std::unique is not showing what I am expecting from it


问:
Simplest way to detect a pinch
This is a WEB APP not a native app. Please no Objective-C NS commands.

So I need to detect 'pinch' events on iOS. Problem is every plugin or method I see for doing gestures or multi-touch events, is (usually) with jQuery and is a whole additional pluggin for every gesture under the sun. My application is huge, and I am very sensitive to deadwood in my code. All I need is to detect a pinch, and using something like jGesture is just way to bloated for my simple needs.

Additionally, I have a limited understanding of how to detect a pinch manually. I can get the position of both fingers, can't seem to get the mix right to detect this. Does anyone have a simple snippet that JUST detects pinch?

答:
detect two fingers pinch zoom on any element, easy and w/o hassle with 3rd party libs like Hammer.js (beware, hammer has issues with scrolling!)</p>

```<code>function onScale(el, callback) {
    let hypo = undefined;

    el.addEventListener('touchmove', function(event) {
        if (event.targetTouches.length === 2) {
            let hypo1 = Math.hypot((event.targetTouches[0].pageX - event.targetTouches[1].pageX),
                (event.targetTouches[0].pageY - event.targetTouches[1].pageY));
            if (hypo === undefined) {
                hypo = hypo1;
            }
            callback(hypo1/hypo);
        }
    }, false);

    el.addEventListener('touchend', function(event) {
        hypo = undefined;
    }, false);
}
</code>```

Title: Simplest way to detect a pinch

Body:
detect two fingers pinch zoom on any element, easy and w/o hassle with 3rd party libs like Hammer.js (beware, hammer has issues with scrolling!)

function onScale(el, callback) {
    let hypo = undefined;

    el.addEventListener('touchmove', function(event) {
        if (event.targetTouches.length === 2) {
            let hypo1 = Math.hypot((event.targetTouches[0].pageX - event.targetTouches[1].pageX),
                (event.targetTouches[0].pageY - event.targetTouches[1].pageY));
            if (hypo === undefined) {
                hypo = hypo1;
            }
            callback(hypo1/hypo);
        }
    }, false);

    el.addEventListener('touchend', function(event) {
        hypo = undefined;
    }, false);
}


问:
Git strategy for when you need to work on several features at a time
Let's say I am working on a few front-end features concurrently that all are in different branches (e.g. login branch, reset password branch, update settings branch, etc.). In our current workflow, it's up to me in which order or manner I finish all these features as long as I do them within the set deadline (e.g. 2 weeks time).

To pace myself better, I'd create a branch for each of these features and work on them concurrently, integrating the functionalities first (the hard parts so to speak) and work on the styles and nitty-gritty details towards the end. (Analogy would be like building a house; you don't really complete each part of the house one by one. You build all the foundation first, scaffolding and all, before you do all the decorative stuff towards the end.)

Now this is fine if all of these features are totally isolated from one another. However, there are functionalities or even general styles that I've done on e.g. login branch that I can actually use in reset password branch. (Example, both are forms hence should have the same general form styling and will make use of the same validation functions).

However, since all of them are WIP all at once, I cannot do a PR for login before I continue working on reset pw (e.g. login is at 90% and reset pw at 80% but I need something from login to get reset pw to 90% completion also). Even if I complete login, PR reviews may take time.

I also cannot also e.g. merge/rebase to login from reset pw because 1. that would mix the 2 different features and 2. login feature is not even approved yet.

What is the best strategy for this kind of scenario? I am in a dilemma because the best way to actually avoid this is to finish one feature after another. But at the same time, I work better if I do it in the manner I just mentioned (in parallel).

答:
Actually you can have one feature after another, that's not a technical impossibility, it only requires a little more work on your part in terms of knowing how you have things laid out so that you can move stuff around.

Let's do a little excercise. You have feature1 branch with 2 commits and then your start feature2 on top of feature1. You develop a couple of commits on top of feature2. At this point you realize you need to do something on feature 1:

```<code>git checkout feature1
# edit files
git add blah blah
git commit -m "feature 1"
</code>```

Now, how do you pull this into feature2? Simple enough:

```<code>git checkout feature2
git rebase feature1
</code>```

That was simple.... At this point you realize that you also need something from feature3.. feature 3 has 10 commits and you only need feature3~2. Do not put it on top of feature2, because then you are mixing stuff up in history. You would:

```<code>git checkout HEAD~2 (go back in history 2 revisions... do not use a branch)
git cherry-pick feature3~2 # get the revision you need
# how do we move feature2 onto this?
git rebase --onto HEAD HEAD feature2 # rebase only the last 2 revisions of feature2. No need to rebase any of the revisions up to where you are standing right now
</code>```

Now feature 3 is completely merged into master, and you are asked to move everything on top of current position of master. Well... you are not in charge of feature3 so no point in moving that revision with you, right?

```<code>git checkout feature1
git rebase master
git rebase --onto feature1 feature2~2 feature2
</code>```

And feature 3 is gone from history. At this point you want to separate feature2 from feature1:

```<code>git checkout feature2
git rebase --onto master feature2~2 feature2
</code>```

And now feature2 is on top of master and not feature1... and you can see how you were able to move stuff around without too much work.... it's only a matter of knowing how the "branches are laid down", much like a traffic controller with planes.

Body:
Actually you can have one feature after another, that's not a technical impossibility, it only requires a little more work on your part in terms of knowing how you have things laid out so that you can move stuff around.

Let's do a little excercise. You have feature1 branch with 2 commits and then your start feature2 on top of feature1. You develop a couple of commits on top of feature2. At this point you realize you need to do something on feature 1:

git checkout feature1
# edit files
git add blah blah
git commit -m "feature 1"

Now, how do you pull this into feature2? Simple enough:

git checkout feature2
git rebase feature1

That was simple.... At this point you realize that you also need something from feature3.. feature 3 has 10 commits and you only need feature3~2. Do not put it on top of feature2, because then you are mixing stuff up in history. You would:

git checkout HEAD~2 (go back in history 2 revisions... do not use a branch)
git cherry-pick feature3~2 # get the revision you need
# how do we move feature2 onto this?
git rebase --onto HEAD HEAD feature2 # rebase only the last 2 revisions of feature2. No need to rebase any of the revisions up to where you are standing right now

Now feature 3 is completely merged into master, and you are asked to move everything on top of current position of master. Well... you are not in charge of feature3 so no point in moving that revision with you, right?

git checkout feature1
git rebase master
git rebase --onto feature1 feature2~2 feature2

And feature 3 is gone from history. At this point you want to separate feature2 from feature1:

git checkout feature2
git rebase --onto master feature2~2 feature2

And now feature2 is on top of master and not feature1... and you can see how you were able to move stuff around without too much work.... it's only a matter of knowing how the "branches are laid down", much like a traffic controller with planes.


问:
When I put object into the body I get different field names
The object "info" when go into body method it should have another fields name. e.g. brandName->BrandName, id-> Id etc.

```<code>@JsonRootName(value = "Laptop")
@XmlRootElement(name = "Laptop")
public class ComputerInfo {

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("BrandName")
    private String brandName;

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("Id")
    private String id;

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("LaptopName")
    private String laptopName;

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("Features")
    private Feature features;

    @XmlElement(name = "BrandName")
    public String getBrandName() {
        return brandName;
    }

    @XmlElement(name = "Id")
    public String getId() {
        return id;
    }

    @XmlElement(name = "LaptopName")
    public String getLaptopName() {
        return laptopName;
    }

    @XmlElement(name = "Features")
    public Feature getFeatures() {
        return features;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setLaptopName(String laptopName) {
        this.laptopName = laptopName;
    }

    public void setFeatures(Feature features) {
        this.features = features;
    }

    @Override
    public String toString() {
        return "ComputerInfo{" +
                "brandName='" + brandName + '\'' +
                ", id='" + id + '\'' +
                ", laptopName='" + laptopName + '\'' +
                ", features=" + features +
                '}';
    }
}

public class Feature {

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("Feature")
    private ArrayList<String> feature;

    public ArrayList<String> getFeature() {
        return feature;
    }

    public void setFeature(ArrayList<String> feature) {
        this.feature = feature;
    }

}
</code>```

My Test

```<code>  @Test
  public void testPostWithObjectMapping() throws URISyntaxException {

    URI uri = new URI("http://localhost:8080/laptop-bag/webapi/api/add");
    String id = new Random().nextInt(500) + "";

    ComputerInfo info = new ComputerInfo();
    info.setBrandName("Microsoft");
    info.setId(id);
    info.setLaptopName("Surface");

    Feature feature = new Feature();

    feature.setFeature(new ArrayList<>(Arrays.asList("8GB RAM", "1 TB Hard Drive")));
    info.setFeatures(feature);

    Response response = given().accept(ContentType.JSON)
            .log()
            .body()
            .with()
            .contentType(ContentType.JSON)
            .body(info)
            .post(uri);

    response
            .thenReturn()
            .then()
            .assertThat()
            .statusCode(HttpStatus.SC_OK)
            .body("Laptop.Id", equalTo( info.getId( )));
}
</code>```

Result:

ComputerInfo{brandName='Microsoft', id='421', laptopName='Surface',
  features=http_client.models.Feature@cb51256}

But it should be

```<code>Laptop{BrandName='Microsoft', Id='421', LaptopName='Surface', Features=""}
</code>```

答:
SerializedName is Gson's annotation, not Jackson's

You should use @JsonProperty("BrandName") instead of @SerializedName("BrandName")

Body:
The object "info" when go into body method it should have another fields name. e.g. brandName->BrandName, id-> Id etc.

@JsonRootName(value = "Laptop")
@XmlRootElement(name = "Laptop")
public class ComputerInfo {

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("BrandName")
    private String brandName;

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("Id")
    private String id;

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("LaptopName")
    private String laptopName;

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("Features")
    private Feature features;

    @XmlElement(name = "BrandName")
    public String getBrandName() {
        return brandName;
    }

    @XmlElement(name = "Id")
    public String getId() {
        return id;
    }

    @XmlElement(name = "LaptopName")
    public String getLaptopName() {
        return laptopName;
    }

    @XmlElement(name = "Features")
    public Feature getFeatures() {
        return features;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setLaptopName(String laptopName) {
        this.laptopName = laptopName;
    }

    public void setFeatures(Feature features) {
        this.features = features;
    }

    @Override
    public String toString() {
        return "ComputerInfo{" +
                "brandName='" + brandName + '\'' +
                ", id='" + id + '\'' +
                ", laptopName='" + laptopName + '\'' +
                ", features=" + features +
                '}';
    }
}

public class Feature {

    @JacksonXmlProperty(isAttribute = true)
    @SerializedName("Feature")
    private ArrayList<String> feature;

    public ArrayList<String> getFeature() {
        return feature;
    }

    public void setFeature(ArrayList<String> feature) {
        this.feature = feature;
    }

}

My Test

  @Test
  public void testPostWithObjectMapping() throws URISyntaxException {

    URI uri = new URI("http://localhost:8080/laptop-bag/webapi/api/add");
    String id = new Random().nextInt(500) + "";

    ComputerInfo info = new ComputerInfo();
    info.setBrandName("Microsoft");
    info.setId(id);
    info.setLaptopName("Surface");

    Feature feature = new Feature();

    feature.setFeature(new ArrayList<>(Arrays.asList("8GB RAM", "1 TB Hard Drive")));
    info.setFeatures(feature);

    Response response = given().accept(ContentType.JSON)
            .log()
            .body()
            .with()
            .contentType(ContentType.JSON)
            .body(info)
            .post(uri);

    response
            .thenReturn()
            .then()
            .assertThat()
            .statusCode(HttpStatus.SC_OK)
            .body("Laptop.Id", equalTo( info.getId( )));
}

Result:

ComputerInfo{brandName='Microsoft', id='421', laptopName='Surface',
  features=http_client.models.Feature@cb51256}

But it should be

Laptop{BrandName='Microsoft', Id='421', LaptopName='Surface', Features=""}


问:
Limit the number of selection of child nodes in jstree
I am using jsTree. I want to restrict the child node selection to 4 (either don't allow user to select more than 4 nodes or disable all the checkboxes). I am using select limit which is not working. How can I achieve this?</p>

```<code>$("#mytree").jstree({
    "plugins" : [ "themes","html_data", "ui", "crrm","checkbox" ],
    "html_data" : {
        // ...
    },
    "checkbox": {
        "keep_selected_style": false
    },
    "ui": {
        "select_limit": 4,
    },
    // ...
});
</code>```

答:
I had the same need, and i was able to find a solution with a few java script.
    I wanted to have a limit of 3 nodes checked, so i did this :</p>

```<code>$('#jstree')
    // listen for event
    .on('changed.jstree', function (e, data) {
            var i, j, r = [];
            var lenght = data.selected.length;

            for(i = 0, j = data.selected.length; i < j; i++) {
                 if(data.instance.get_node(data.selected[i]).type.localeCompare("child") != 0) {
                    lenght -= 1;
                }
            }

            if(lenght > 3) {

                if(data.instance.get_node(data.selected[data.selected.length-1]).type.localeCompare("child") == 0) {
                    $("#jstree").jstree("uncheck_node", data.instance.get_node(data.selected[data.selected.length-1]).id);
                } else {
                    $("#jstree").jstree("uncheck_node", data.instance.get_node(data.selected[data.selected.length-2]).id);
                }
            }
    })
    // create the instance
    .jstree({
          'core' :
           ...
</code>```

Body:
I am using jsTree. I want to restrict the child node selection to 4 (either don't allow user to select more than 4 nodes or disable all the checkboxes). I am using select limit which is not working. How can I achieve this?

$("#mytree").jstree({
    "plugins" : [ "themes","html_data", "ui", "crrm","checkbox" ],
    "html_data" : {
        // ...
    },
    "checkbox": {
        "keep_selected_style": false
    },
    "ui": {
        "select_limit": 4,
    },
    // ...
});

Body:
I had the same need, and i was able to find a solution with a few java script.
    I wanted to have a limit of 3 nodes checked, so i did this :

$('#jstree')
    // listen for event
    .on('changed.jstree', function (e, data) {
            var i, j, r = [];
            var lenght = data.selected.length;

            for(i = 0, j = data.selected.length; i < j; i++) {
                 if(data.instance.get_node(data.selected[i]).type.localeCompare("child") != 0) {
                    lenght -= 1;
                }
            }

            if(lenght > 3) {

                if(data.instance.get_node(data.selected[data.selected.length-1]).type.localeCompare("child") == 0) {
                    $("#jstree").jstree("uncheck_node", data.instance.get_node(data.selected[data.selected.length-1]).id);
                } else {
                    $("#jstree").jstree("uncheck_node", data.instance.get_node(data.selected[data.selected.length-2]).id);
                }
            }
    })
    // create the instance
    .jstree({
          'core' :
           ...


问:
how to implement two different animations on same sprite in cocos2d
I'm confused on using animations in cocos2d... I've a sprite which has 3 types of animations, like a smiley which laughs, cries and winks eyes... And I have separate sprite sheets for each of these animations... how will I be able to use these animations on the same sprite... Can anybody help me please???

Regards,

Suraj

答:
It would be much easier to have all your animations on the same sprite sheet, as, if your sprite is using a CCBatchnode to do it's draw method, you'd have remove it as a child from 1 sheet, and readd it to another.

In your CCSprite subclass, set some CCAction's as instance variables.

In an initialization method, write those actions and store them to the instance variables.

Then when you want to use an animation, tell your sprite to run it.

E.g.

```<code>NSMutableArray *smileFrames = [NSMutableArray array];
[smileFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"character_smile.png"]];
[smileFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"character_smile2.png"]];
[smileFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"character_smile3.png"]];

CCAnimation *smileAnim = [CCAnimation
                         animationWithFrames:smileFrames delay:0.2f];

self.smileAction = [CCSequence actions:
                   [CCAnimate actionWithAnimation:smileAnim restoreOriginalFrame:NO],
                   [CCCallFunc actionWithTarget:self selector:@selector(smileFinished)],
                   nil];
</code>```

Then you would simply use..

```<code>[sprite runAction:smileAction];
</code>```

I have added a CCCallFunc to the end of the animation, as you may want to revert back to an idle animation after it is finished.

Don't forget to release any retained actions when the sprite is deallocated.

Body:
It would be much easier to have all your animations on the same sprite sheet, as, if your sprite is using a CCBatchnode to do it's draw method, you'd have remove it as a child from 1 sheet, and readd it to another.

In your CCSprite subclass, set some CCAction's as instance variables.

In an initialization method, write those actions and store them to the instance variables.

Then when you want to use an animation, tell your sprite to run it.

E.g.

NSMutableArray *smileFrames = [NSMutableArray array];
[smileFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"character_smile.png"]];
[smileFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"character_smile2.png"]];
[smileFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:@"character_smile3.png"]];

CCAnimation *smileAnim = [CCAnimation
                         animationWithFrames:smileFrames delay:0.2f];

self.smileAction = [CCSequence actions:
                   [CCAnimate actionWithAnimation:smileAnim restoreOriginalFrame:NO],
                   [CCCallFunc actionWithTarget:self selector:@selector(smileFinished)],
                   nil];

Then you would simply use..

[sprite runAction:smileAction];

I have added a CCCallFunc to the end of the animation, as you may want to revert back to an idle animation after it is finished.

Don't forget to release any retained actions when the sprite is deallocated.


问:
Excel VBA code to scrape URLs, two different error codes
Again, very new to coding, any insight appreciated. See code below, am happy to provide more if that helps solve the issue. I've marked [issue] next to the lines that are generating the error messages.

```<code>
Set xRng = Application.InputBox("Please select the keyword range", "Google Search Macro", Selection.Address, , , , , 8)
If xRng Is Nothing Then Exit Sub

Application.ScreenUpdating = False
xLastRow = xRng.Rows.Count

Set xRng = xRng(1)

For i = 0 [issue] To xLastRow - 1
tempStr = xRng.Offset(i).Value
tempStr = Replace(tempStr, " ", "+")
url = "https://www.google.com/search?q=" & tempStr

Set nameCell = xRng.Offset(i, 1)
Set linkCell = xRng.Offset(i, 2)

Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", url, False
request.setRequestHeader "Content-Type", "text/xml"
request.send

returnStr = StrConv(request.responseBody, vbUnicode)
returnPage.body.innerHTML = returnStr [issue]
</code>```

The first error message that comes up is "Compile error: For control variable already in use" and it highlights "For i = 0."

The second error message that comes up is "Compile error: Expected End Sub" and it highlights "returnStr."

答:
Here, your code sorted.

You were missing a declaration, to avoid this I recommend using Option Explicit on the top of your module which will forece you to declare all your variables.

You were missing the Next i to close the loop and the End Sub to close the procedure:

```<code>Option Explicit
Sub URLPull()

    Dim searchRange As Range
'    Dim nameCell As Range 'not used
'    Dim linkCell As Range 'not used
    Dim url As String
    Dim returnStr As String
    Dim tempStr As String
    'Dim i As Long, xLastRow As Long 'no need for them using For Each loop
    Dim request As Object
    Dim returnPage As New HTMLDocument
    Dim returnSiteName As Variant
    Dim returnLink As Variant
    Dim xRng As Range 'this was missing
    Dim C As Range 'to loop through the xRng

    'On Error Resume Next delete this, this is for error handle

    Set xRng = Application.InputBox("Please select the keyword range", "Google Search Macro", Selection.Address, , , , , 8)
    If xRng Is Nothing Then Exit Sub

    Application.ScreenUpdating = False
'    xLastRow = xRng.Rows.Count
'
'    Set xRng = xRng(1)

    Set request = CreateObject("MSXML2.XMLHTTP") 'QHarr comment

    For Each C In xRng 'this way you loop through all the cells in your range
        tempStr = C 'this is the cell value
        tempStr = Replace(tempStr, " ", "+")
        url = "https://www.google.com/search?q=" & tempStr 'if you get no results, check here the tempStr value
        'You are not using these:
'        Set nameCell = xRng.Offset(i, 1)
'        Set linkCell = xRng.Offset(i, 2)
        request.Open "GET", url, False
        request.setRequestHeader "Content-Type", "text/xml"
        request.send
        returnStr = StrConv(request.responseBody, vbUnicode)
        returnPage.body.innerHTML = returnStr
    Next C 'this was missing

End Sub 'this was missing
</code>```

Body:
Again, very new to coding, any insight appreciated. See code below, am happy to provide more if that helps solve the issue. I've marked [issue] next to the lines that are generating the error messages.

Set xRng = Application.InputBox("Please select the keyword range", "Google Search Macro", Selection.Address, , , , , 8)
If xRng Is Nothing Then Exit Sub

Application.ScreenUpdating = False
xLastRow = xRng.Rows.Count

Set xRng = xRng(1)

For i = 0 [issue] To xLastRow - 1
tempStr = xRng.Offset(i).Value
tempStr = Replace(tempStr, " ", "+")
url = "https://www.google.com/search?q=" & tempStr

Set nameCell = xRng.Offset(i, 1)
Set linkCell = xRng.Offset(i, 2)

Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", url, False
request.setRequestHeader "Content-Type", "text/xml"
request.send

returnStr = StrConv(request.responseBody, vbUnicode)
returnPage.body.innerHTML = returnStr [issue]

The first error message that comes up is "Compile error: For control variable already in use" and it highlights "For i = 0."

The second error message that comes up is "Compile error: Expected End Sub" and it highlights "returnStr."

Body:
Here, your code sorted.

You were missing a declaration, to avoid this I recommend using Option Explicit on the top of your module which will forece you to declare all your variables.

You were missing the Next i to close the loop and the End Sub to close the procedure:

Option Explicit
Sub URLPull()

    Dim searchRange As Range
'    Dim nameCell As Range 'not used
'    Dim linkCell As Range 'not used
    Dim url As String
    Dim returnStr As String
    Dim tempStr As String
    'Dim i As Long, xLastRow As Long 'no need for them using For Each loop
    Dim request As Object
    Dim returnPage As New HTMLDocument
    Dim returnSiteName As Variant
    Dim returnLink As Variant
    Dim xRng As Range 'this was missing
    Dim C As Range 'to loop through the xRng

    'On Error Resume Next delete this, this is for error handle

    Set xRng = Application.InputBox("Please select the keyword range", "Google Search Macro", Selection.Address, , , , , 8)
    If xRng Is Nothing Then Exit Sub

    Application.ScreenUpdating = False
'    xLastRow = xRng.Rows.Count
'
'    Set xRng = xRng(1)

    Set request = CreateObject("MSXML2.XMLHTTP") 'QHarr comment

    For Each C In xRng 'this way you loop through all the cells in your range
        tempStr = C 'this is the cell value
        tempStr = Replace(tempStr, " ", "+")
        url = "https://www.google.com/search?q=" & tempStr 'if you get no results, check here the tempStr value
        'You are not using these:
'        Set nameCell = xRng.Offset(i, 1)
'        Set linkCell = xRng.Offset(i, 2)
        request.Open "GET", url, False
        request.setRequestHeader "Content-Type", "text/xml"
        request.send
        returnStr = StrConv(request.responseBody, vbUnicode)
        returnPage.body.innerHTML = returnStr
    Next C 'this was missing

End Sub 'this was missing


问:
4 simple toggle switches! What am I doing wrong?
I got this code from a youtube video but, it doesn't work. So, I put it into jsfiddle and fixed everything it said was wrong but, EEERRRRRR.... it still doesn't work. There should be four sliding on/off switches. Yet I only have this one giant blob that doesn't do anything but, sit there and laugh at me. Any help out there?

http://jsfiddle.net/p2bxkyv8/

```<code>    <html>
    <head>
     <title>Toggle Switch</title>
     <link href="style.css" rel="stylesheet" type="text/css">
    </head>

    <body>
    <div class="container">
     <h1>Toggle Switch</h1>
     <lable class="switch">
     <input type="checkbox">
     <span class="slider"></span>
     </lable>

     <lable class="switch">
     <input type="checkbox" checked>
     <span class="slider"></span>
     </lable>

     <lable class="switch">
     <input type="checkbox">
     <span class="slider"></span>
     </lable>

     <lable class="switch">
     <input type="checkbox" checked>
     <span class="slider"></span>
     </lable>
    </div>
    </body>
    </html>
</code>```

css

```<code>  * {
    margin: 0;
    padding: 0;
    }

  .container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    }

  h1 {
    margin-bottom: 40px;
    font-family: sans-serif;
    }

  .switch {
    position: relitive;
    display: inline-block;
    width: 110px;
    height: 60px;
    margin: 0 10px;
    }

  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 34px;
    }

  .switch input { display: none; }

  .slider::before {
    position: absolute;
    content: "";
    height: 50px;
    width: 50px;
    left: 5px;
    bottom: 5px;
    background-color: white;
    transition: 0.4s;
    border-radius: 50px;
    }

  input:checked + .slider {
    background-color: #ff278c;
    }

  input:checked + .slider::before {
    transform: translateX(50px);
    }
</code>```

答:
This works. Fix lable to label and relitive to relative

* {
  margin: 0;
  padding: 0;
}

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  }

h1 {
  margin-bottom: 40px;
  font-family: sans-serif;
  }

.switch {
  position: relative;
  display: inline-block;
  width: 110px;
  height: 60px;
  margin: 0 10px;
  }

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.4s;
  border-radius: 34px;
  }

.switch input { display: none; }

.slider::before {
  position: absolute;
  content: "";
  height: 50px;
  width: 50px;
  left: 5px;
  bottom: 5px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50px;
  }

input:checked + .slider {
  background-color: #ff278c;
  }

input:checked + .slider::before {
  transform: translateX(50px);
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Toggle Switch</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">
<h1>Toggle Switch</h1>
 <label class="switch">
  <input type="checkbox">
   <span class="slider"></span>
 </label>

 <label class="switch">
  <input type="checkbox" checked>
   <span class="slider"></span>
 </label>

 <label class="switch">
  <input type="checkbox">
   <span class="slider"></span>
 </label>

 <label class="switch">
  <input type="checkbox" checked>
   <span class="slider"></span>
 </label>
</div>
</body>
</html>
 </code>```

Body:
I got this code from a youtube video but, it doesn't work. So, I put it into jsfiddle and fixed everything it said was wrong but, EEERRRRRR.... it still doesn't work. There should be four sliding on/off switches. Yet I only have this one giant blob that doesn't do anything but, sit there and laugh at me. Any help out there?

http://jsfiddle.net/p2bxkyv8/

     <title>Toggle Switch</title>
     <link href="style.css" rel="stylesheet" type="text/css">

Toggle Switch

     <lable class="switch">
     <input type="checkbox">

     </lable>

     <lable class="switch">
     <input type="checkbox" checked>

     </lable>

     <lable class="switch">
     <input type="checkbox">

     </lable>

     <lable class="switch">
     <input type="checkbox" checked>

     </lable>

css

  * {
    margin: 0;
    padding: 0;
    }

  .container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    }

  h1 {
    margin-bottom: 40px;
    font-family: sans-serif;
    }

  .switch {
    position: relitive;
    display: inline-block;
    width: 110px;
    height: 60px;
    margin: 0 10px;
    }

  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 34px;
    }

  .switch input { display: none; }

  .slider::before {
    position: absolute;
    content: "";
    height: 50px;
    width: 50px;
    left: 5px;
    bottom: 5px;
    background-color: white;
    transition: 0.4s;
    border-radius: 50px;
    }

  input:checked + .slider {
    background-color: #ff278c;
    }

  input:checked + .slider::before {
    transform: translateX(50px);
    }

Body:
This works. Fix lable to label and relitive to relative

* {
  margin: 0;
  padding: 0;
}

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  }

h1 {
  margin-bottom: 40px;
  font-family: sans-serif;
  }

.switch {
  position: relative;
  display: inline-block;
  width: 110px;
  height: 60px;
  margin: 0 10px;
  }

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: 0.4s;
  border-radius: 34px;
  }

.switch input { display: none; }

.slider::before {
  position: absolute;
  content: "";
  height: 50px;
  width: 50px;
  left: 5px;
  bottom: 5px;
  background-color: white;
  transition: 0.4s;
  border-radius: 50px;
  }

input:checked + .slider {
  background-color: #ff278c;
  }

input:checked + .slider::before {
  transform: translateX(50px);
  }

<html>
<head>
<title>Toggle Switch</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">
<h1>Toggle Switch</h1>
 <label class="switch">
  <input type="checkbox">
   <span class="slider"></span>
 </label>

 <label class="switch">
  <input type="checkbox" checked>
   <span class="slider"></span>
 </label>

 <label class="switch">
  <input type="checkbox">
   <span class="slider"></span>
 </label>

 <label class="switch">
  <input type="checkbox" checked>
   <span class="slider"></span>
 </label>
</div>
</body>
</html>


问:
Why Does Reassigning Function Pointer Slow Down Function Call
I have been using a function pointer, p, to call different functions. My problem is, the performance of calling p decreases dramatically if I point it to a different function after it has already been assigned a function. The performance is fine if I switch p between undefined and the same function over and over again, and fine when I only point it to one function, but switching between functions kills performance.

Below is the code I am using to test this scenario and here is the fiddle. I loop 500 times recursively and call p 1,000,000 times on each loop. p can be undefined or pointing to func1 or func2.

```<code>function func1() {} // two identical empty functions
function func2() {} // different in name only

var p = func1; // default to func1

var count  = 0; // current loop
var elapse = 0; // elapsed time for 1,000,000 calls on each loop
var start  = 0; // start time for 1,000,000 calls on each loop
var total  = 0; // total elapsed time for all loops

function loop() {

  start = performance.now(); // get start time

  for (let i = 0; i < 1000000; i ++) if (p !== undefined) p(); // do 1,000,000 calls or early out 1,000,000 times if undefined

    elapse = performance.now() - start;

  total += elapse; // used for getting average

  count ++;

  console.log(p + "\nelapsed " + elapse + "\naverage " + total / count);

  // Switch between the lines below to see the performance difference.
  p = (p === func1) ? p = undefined : p = func1; // best performance
  //p = (p === func1) ? p = func1 : p = func1; // good performance
  //p = (p === func1) ? p = func2 : p = func1; // bad performance

  // pattern: func1 -> undefined -> func2 -> undefined -> repeat
  /*if (p === undefined) p = (count % 4 === 0) ? p = func1 : p = func2;
  else p = undefined;*/ // also bad performance

  if (count < 500) loop(); // start the next loop

}

console.clear();

loop(); // start the loop
</code>```

Why does the performance of calling p drop significantly when it is assigned a different function? Also, why does setting p to undefined and back to the original function not change performance when setting p to undefined and then to a different function does?

答:
You are stopping the engine from creating an optimized hotpath because it can't rely on the value of the function pointer.

See the section titled "Interpreter/compiler pipelines in JavaScript engines" in this article: https://mathiasbynens.be/notes/shapes-ics

The pictures show TurboFan optimizing the bytecode based on profiling data from execution, and the text after it explains:

To make it run faster, the bytecode can be sent to the optimizing compiler along with profiling data. The optimizing compiler makes certain assumptions based on the profiling data it has, and then produces highly-optimized machine code.

If at some point one of the assumptions turns out to be incorrect, the optimizing compiler deoptimizes and goes back to the interpreter.

When you reassign the function pointer, you send conflicting profiling data from the interpreter to the compiler. This doesn't happen when you assign undefined, because that code path doesn't get executed in that case: if (p !== undefined) p();

Body:
I have been using a function pointer, p, to call different functions. My problem is, the performance of calling p decreases dramatically if I point it to a different function after it has already been assigned a function. The performance is fine if I switch p between undefined and the same function over and over again, and fine when I only point it to one function, but switching between functions kills performance.

Below is the code I am using to test this scenario and here is the fiddle. I loop 500 times recursively and call p 1,000,000 times on each loop. p can be undefined or pointing to func1 or func2.

function func1() {} // two identical empty functions
function func2() {} // different in name only

var p = func1; // default to func1

var count  = 0; // current loop
var elapse = 0; // elapsed time for 1,000,000 calls on each loop
var start  = 0; // start time for 1,000,000 calls on each loop
var total  = 0; // total elapsed time for all loops

function loop() {

  start = performance.now(); // get start time

  for (let i = 0; i < 1000000; i ++) if (p !== undefined) p(); // do 1,000,000 calls or early out 1,000,000 times if undefined

    elapse = performance.now() - start;

  total += elapse; // used for getting average

  count ++;

  console.log(p + "\nelapsed " + elapse + "\naverage " + total / count);

  // Switch between the lines below to see the performance difference.
  p = (p === func1) ? p = undefined : p = func1; // best performance
  //p = (p === func1) ? p = func1 : p = func1; // good performance
  //p = (p === func1) ? p = func2 : p = func1; // bad performance

  // pattern: func1 -> undefined -> func2 -> undefined -> repeat
  /*if (p === undefined) p = (count % 4 === 0) ? p = func1 : p = func2;
  else p = undefined;*/ // also bad performance

  if (count < 500) loop(); // start the next loop

}

console.clear();

loop(); // start the loop

Why does the performance of calling p drop significantly when it is assigned a different function? Also, why does setting p to undefined and back to the original function not change performance when setting p to undefined and then to a different function does?


问:
Rails: how do I validate that something is a boolean?
Does rails have a validator like validates_numericality_of for boolean or do I need to roll my own?

答:
Answer according to Rails Docs 5.2.3

This helper (presence) validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.

Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:

```<code>validates :boolean_field_name, inclusion: { in: [true, false] }
</code>```

Body:
Answer according to Rails Docs 5.2.3

This helper (presence) validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.

Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:

validates :boolean_field_name, inclusion: { in: [true, false] }


问:
Increasing timeout on channel originate
Using ARI (C#, AsterNET), I'm creating a channel via the Originate command:

```<code>   var channel = client.Channels.Originate($"SIP/{number}@{destination}", app: appName, callerId: CLI, timeout: timeout);
</code>```

This works fine; however,timeout starts from when the channel is created, and in reality I'd like to timeout to only be enforced once the channel starts ringing.

Is there any way (via ARI) to manipulate the timeout setting once the channel is created - so I could, for example, create the channel with an arbitrary timeout, and then (re)set the timeout once the channel state has changed to RINGING?

答:
There is no way do timeout based on ringing in asterisk.

Not in dialplan, not in ARI or AMI or AGI. No at all.

Only complex things like listen for event and manualy hangup channels.

Title: Increasing timeout on channel originate

Body:
Using ARI (C#, AsterNET), I'm creating a channel via the Originate command:

   var channel = client.Channels.Originate($"SIP/{number}@{destination}", app: appName, callerId: CLI, timeout: timeout);

This works fine; however,timeout starts from when the channel is created, and in reality I'd like to timeout to only be enforced once the channel starts ringing.

Is there any way (via ARI) to manipulate the timeout setting once the channel is created - so I could, for example, create the channel with an arbitrary timeout, and then (re)set the timeout once the channel state has changed to RINGING?


问:
How to move my border-top to the very top of the page?
I'm trying to make an hover effects on my nav bar, I want to have a line on top of the li where your cursor is.

I've given the li a border-top property but i need the line to be at the very top of the page not directly on top of the li.

#liste li:hover{
    border-top: 3px solid;
    color: #5CABD1;
}
```

I already know the problem is the border top property but i dont know others way to put a line on top of my li. Here is a photo of my nav bar and the current border-top effect.

答: Seems like the issue is that you're assigning the hover behavior to the list item and not the link itself. If the container link extends all the way to the top line, it should overlap and display properly.</p>

Body:
I'm trying to make an hover effects on my nav bar, I want to have a line on top of the li where your cursor is.

I've given the li a border-top property but i need the line to be at the very top of the page not directly on top of the li.

#liste li:hover{
    border-top: 3px solid;
    color: #5CABD1;
}

I already know the problem is the border top property but i dont know others way to put a line on top of my li. Here is a photo of my nav bar and the current border-top effect.


问:
Swift Conditional String Interpolation
I often trap myself writing code like this when I need to construct a string depending on some condition (in this case isFavorite):

let me = Contact(name: "Stefan", isFavorite: true)

var message = "Contact \(me.name)"
if me.isFavorite {
    message.append(" is a favorite contact")
}
```

These are 4 lines or alternatively a complex ternary operator (if ? then : else) for such a simple task. I always have a bad conscience with this...

Is there a way to do this more elegantly with Swift?

答:
You can use Ternary operator</p>

```<code>let msg = "Contact \(me.name)" + (me.isFavorite ? " is a favorite contact" : "")
</code>```

Title: Swift Conditional String Interpolation

Body:
I often trap myself writing code like this when I need to construct a string depending on some condition (in this case isFavorite):

let me = Contact(name: "Stefan", isFavorite: true)

var message = "Contact \(me.name)"
if me.isFavorite {
    message.append(" is a favorite contact")
}

These are 4 lines or alternatively a complex ternary operator (if ? then : else) for such a simple task. I always have a bad conscience with this...

Is there a way to do this more elegantly with Swift?

Body:
You can use Ternary operator

let msg = "Contact \(me.name)" + (me.isFavorite ? " is a favorite contact" : "")