问:
What purpose is served by having an async keyword for a callback inside an awaited function?
I have the following code:

```<code>async createApiCall(apiCalls: IApiCallsTable):Promise<IApiCallsTable> {
  try {
    const instance: any = this.db.getEntities().dbo__api_calls.build(apiCalls);
    instance.isNewRecord = true;
    let result = await this.db.getSequelize().transaction( async (transaction) => {
      return instance.save();
    });
    return Promise.resolve(result.dataValues);
  }
  catch (error) {
    console.log(error);
    let message: ILogMessage = {
      code: ResponseErrorCode.unknownError,
      message: ResponseErrorCode.unknownError.toString(),
      meta: error,
      sourceFunction : 'ApiCallsQueries: createApiCall()'
    };
    log.error(message);
    return Promise.reject(error);
  }
}
</code>```

I would to understand if is it necessary to have an async labelling an anonymous function, i.e. this.db.getSequelize().transaction( async (transaction) => { ...? The code is working flawlessly, but I cannot seem to understand the reason to label a callback async if nothing is being awaited inside it? Is this a recommended pattern and/or best practice?

PS: Any further suggestions/recommendations on how this code could be improved are more than welcome :)

答:
Sequelize.transaction() expects a callback function that returns a Promise. async transforms any function into a Promise-returning function.
 However, Model.save() already returns a Promise, so you should be able to use just:

```<code>await this.db.getSequelize().transaction((tx) => instance.save());
</code>```

async instructs the runtime to translate a function into continuation-passing style; that is, turn it into function that returns a Promise that eventually resolves with the function's return value. This is independent of whether or not you use await in the body of the function.

The TypeScript definition for Sequelize.transaction() has this as the signature of the method you're using:

```<code>transaction(autoCallback: (t: Transaction) => PromiseLike<any>): Promise<any>;
</code>```

In TypeScript, it's invalid to pass a "regular" function to a callback parameter that expects a promise-returning function:

```<code>let foo: (() => PromiseLike<string>);

foo = async () => "aaa";            // this compiles
foo = () => Promise.resolve("aaa"); // this does as well
foo = () => "aaa";                  // this does *not*
</code>```

(You can see it in the TS playground here.) After all, a Promise<string> is very different from a string!

Your code however uses async on a method that already returns a Promise<Model>, meaning that your callback actually returns a Promise<Promise<Model>>. This doesn't seem right, and your code should actually cause TypeScript to complain about result.dataValues, since result will be of type Promise<Model>, not Model. I'm guessing it came about by starting with code with the following basic shape:

```<code>transaction(async (tx) => {
    let foo = await Foo.find();
    // use foo
    return await foo.save();
});
</code>```

where they keywords are used appropriately, since it doesn't just pass through a promise.

Body:
I have the following code:

async createApiCall(apiCalls: IApiCallsTable):Promise<IApiCallsTable> {
  try {
    const instance: any = this.db.getEntities().dbo__api_calls.build(apiCalls);
    instance.isNewRecord = true;
    let result = await this.db.getSequelize().transaction( async (transaction) => {
      return instance.save();
    });
    return Promise.resolve(result.dataValues);
  }
  catch (error) {
    console.log(error);
    let message: ILogMessage = {
      code: ResponseErrorCode.unknownError,
      message: ResponseErrorCode.unknownError.toString(),
      meta: error,
      sourceFunction : 'ApiCallsQueries: createApiCall()'
    };
    log.error(message);
    return Promise.reject(error);
  }
}

I would to understand if is it necessary to have an async labelling an anonymous function, i.e. this.db.getSequelize().transaction( async (transaction) => { ...? The code is working flawlessly, but I cannot seem to understand the reason to label a callback async if nothing is being awaited inside it? Is this a recommended pattern and/or best practice?

PS: Any further suggestions/recommendations on how this code could be improved are more than welcome :)

Body:
Sequelize.transaction() expects a callback function that returns a Promise. async transforms any function into a Promise-returning function.
 However, Model.save() already returns a Promise, so you should be able to use just:

await this.db.getSequelize().transaction((tx) => instance.save());

async instructs the runtime to translate a function into continuation-passing style; that is, turn it into function that returns a Promise that eventually resolves with the function's return value. This is independent of whether or not you use await in the body of the function.

The TypeScript definition for Sequelize.transaction() has this as the signature of the method you're using:

transaction(autoCallback: (t: Transaction) => PromiseLike<any>): Promise<any>;

In TypeScript, it's invalid to pass a "regular" function to a callback parameter that expects a promise-returning function:

let foo: (() => PromiseLike<string>);

foo = async () => "aaa";            // this compiles
foo = () => Promise.resolve("aaa"); // this does as well
foo = () => "aaa";                  // this does *not*

(You can see it in the TS playground here.) After all, a Promise<string> is very different from a string!

Your code however uses async on a method that already returns a Promise<Model>, meaning that your callback actually returns a Promise<Promise<Model>>. This doesn't seem right, and your code should actually cause TypeScript to complain about result.dataValues, since result will be of type Promise<Model>, not Model. I'm guessing it came about by starting with code with the following basic shape:

transaction(async (tx) => {
    let foo = await Foo.find();
    // use foo
    return await foo.save();
});

where they keywords are used appropriately, since it doesn't just pass through a promise.


来源: stackexchange

问:
Does the Either type constructor contain a phantom type each for the left/right case?
AFAIK, only types are inhabited by values in Haskell, not type constructors. Either is a binary type constructor of kind * -> * -> *. Left and Right both apply this type constructor to a single type, which is provided by the passed value. Doesn't that mean that in both cases Either is merely partially applied and thus still a type constructor awaiting the missing type argument?

```<code>let x = Right 'x' -- Either a Char
</code>```

x has the type Either a Char. I would assume that this type would have the kind * -> *. This is clearly a polymorphic type, not a ground one. Yet Either a Char can be inhabited by values like 'x'.

My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left. I know phantom types in connection with  Const, where the respective type variable isn't used at all. Am I on the right tack?

答:
AFAIK, only types are inhabited by values in Haskell, not type constructors.

Spot on.

Left and Right both apply this type constructor to a single type

You can't say that. Left and Right don't live in the type language at all, so they don't apply anything to any types, they only apply themselves to values.

x has the type Either a Char. I would assume that this type would have the kind * -> *

You need to distinguish between function/constructor arguments, and type variables. It's basically the distinction between free and bound variables. Either a Char still has kind *, not * -> *, because it is already applied to a. Yes, that's a type variable, but it still is an argument that's already applied.

Yet Either a Char can be inhabited by values like 'x'.

Not quite – it can be inhabited by values like Right 'x'.

My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left

kind of, but I wouldn't call it “phantom” because you can't just count out Left or Right. At least not unless you choose Either Void b, but in that case you don't have the a variable.

ContentLicense: CC BY-SA 3.0

Body:
AFAIK, only types are inhabited by values in Haskell, not type constructors. Either is a binary type constructor of kind * -> * -> *. Left and Right both apply this type constructor to a single type, which is provided by the passed value. Doesn't that mean that in both cases Either is merely partially applied and thus still a type constructor awaiting the missing type argument?

let x = Right 'x' -- Either a Char

x has the type Either a Char. I would assume that this type would have the kind * -> *. This is clearly a polymorphic type, not a ground one. Yet Either a Char can be inhabited by values like 'x'.

My suspicion is that the type variable a is a phantom type for the Right case resp. b for Left. I know phantom types in connection with  Const, where the respective type variable isn't used at all. Am I on the right tack?


问:
Is there a shortcut for git branch name?
I tend to have long branch names for git (e.g., step110_create_search_engine_to_replace_google).

How should I refer to it simply as step110 in checkout/commit statements?

答:
git symbolic-ref may help if you are too lazy to even press a TAB. You can create an alias to the branch.

$ # Define short name 's1'
$ git symbolic-ref refs/heads/s1 refs/heads/step110_create_search_engine_to_replace_google
$
$ # You can use short name 's1' afterwards
$ git reset --hard s1
$ git checkout -b s1-experiment s1
$
$ # Remove the short name (don't use branch -d here or the original branch gets deleted!)
$ git symbolic-ref -d refs/heads/s1
```

<p>Remote branches can be referred in the same manner to save typing <code>remote/</code><kbd>TAB</kbd>. (In this case, I recommend to prefix with <code>refs/tags/</code> instead of <code>refs/heads/</code> to prevent moving the remote ref accidentally)</p>

<pre class="lang-sh prettyprint-override"><code>$ git symbolic-ref refs/tags/base refs/remotes/github/a-very-long-named-remote-branch
$ git rebase -i base
</code>```

Body:
git symbolic-ref may help if you are too lazy to even press a TAB. You can create an alias to the branch.

$ # Define short name 's1'
$ git symbolic-ref refs/heads/s1 refs/heads/step110_create_search_engine_to_replace_google
$
$ # You can use short name 's1' afterwards
$ git reset --hard s1
$ git checkout -b s1-experiment s1
$
$ # Remove the short name (don't use branch -d here or the original branch gets deleted!)
$ git symbolic-ref -d refs/heads/s1

Remote branches can be referred in the same manner to save typing remote/TAB. (In this case, I recommend to prefix with refs/tags/ instead of refs/heads/ to prevent moving the remote ref accidentally)

$ git symbolic-ref refs/tags/base refs/remotes/github/a-very-long-named-remote-branch
$ git rebase -i base

ContentLicense: CC BY-SA 4.0


问:
Convert from lowercase to uppercase all values in all character variables in dataframe
I have a mixed dataframe of character and numeric variables.

```<code>city,hs_cd,sl_no,col_01,col_02,col_03
Austin,1,2,,46,Female
Austin,1,3,,32,Male
Austin,1,4,,27,Male
Austin,1,5,,20,Female
Austin,2,2,,42,Female
Austin,2,1,,52,Male
Austin,2,3,,25,Male
Austin,2,4,,22,Female
Austin,3,3,,30,Female
Austin,3,1,,65,Female
</code>```

I want to convert all the lower-case characters in the dataframe to uppercase. Is there any way to do this in one shot without doing it repeatedly over each character-variable?

答:
It simple with apply function in R

```<code>f <- apply(f,2,toupper)
</code>```

No need to check if the column is character or any other type.

Body:
I have a mixed dataframe of character and numeric variables.

city,hs_cd,sl_no,col_01,col_02,col_03
Austin,1,2,,46,Female
Austin,1,3,,32,Male
Austin,1,4,,27,Male
Austin,1,5,,20,Female
Austin,2,2,,42,Female
Austin,2,1,,52,Male
Austin,2,3,,25,Male
Austin,2,4,,22,Female
Austin,3,3,,30,Female
Austin,3,1,,65,Female

I want to convert all the lower-case characters in the dataframe to uppercase. Is there any way to do this in one shot without doing it repeatedly over each character-variable?

Body:
It simple with apply function in R

f <- apply(f,2,toupper)

No need to check if the column is character or any other type.


问:
Declaring variables and select statement in a procedure
I'm writing a SQL procedure which should use calculated date stored as a local variable in a select statement. I'm using Oracle SQL developer. My code is:

```<code>create or replace PROCEDURE
                                   my_procedure
AS
BEGIN
DECLARE
  l_max_dt  DATE;
BEGIN
 SELECT MAX(TRX_DT)
 INTO   l_max_dt
 FROM   TABLE
 WHERE 1=1;
end;
 select * from TABLE where trx_dt = l_max_dt;
end;
</code>```

This code gives me an error : " Error(14,48): PL/SQL: ORA-00904: "L_MAX_DT": invalid identifier" when select statement is present.
How can I store variables to use them in statements?

答:
This is how you write a Procedure. Syntax is incorrect. Read about syntax Here

```<code>CREATE OR REPLACE PROCEDURE my_procedure
AS
   l_max_dt   DATE;
   v_var      TABLE2%ROWTYPE;
BEGIN
   SELECT MAX (TRX_DT)
     INTO l_max_dt
     FROM TABLE1
    WHERE 1 = 1;

   -- Assuming the query will retrun only 1 row.
   SELECT *
     INTO v_var
     FROM TABLE2
    WHERE trx_dt = l_max_dt;
END;
</code>```

Body:
I'm writing a SQL procedure which should use calculated date stored as a local variable in a select statement. I'm using Oracle SQL developer. My code is:

create or replace PROCEDURE
                                   my_procedure
AS
BEGIN
DECLARE
  l_max_dt  DATE;
BEGIN
 SELECT MAX(TRX_DT)
 INTO   l_max_dt
 FROM   TABLE
 WHERE 1=1;
end;
 select * from TABLE where trx_dt = l_max_dt;
end;

This code gives me an error : " Error(14,48): PL/SQL: ORA-00904: "L_MAX_DT": invalid identifier" when select statement is present.
How can I store variables to use them in statements?

Body:
This is how you write a Procedure. Syntax is incorrect. Read about syntax Here

CREATE OR REPLACE PROCEDURE my_procedure
AS
   l_max_dt   DATE;
   v_var      TABLE2%ROWTYPE;
BEGIN
   SELECT MAX (TRX_DT)
     INTO l_max_dt
     FROM TABLE1
    WHERE 1 = 1;

   -- Assuming the query will retrun only 1 row.
   SELECT *
     INTO v_var
     FROM TABLE2
    WHERE trx_dt = l_max_dt;
END;


问:
How to handle the value I get from a HashMap
I want my getv() function return the value from a HashMap. I get errors no matter how I modify my code:

```<code>enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    Env: HashMap<char, Type>,
}
impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.Env.insert(name, ty);
    }

    fn getv(self, name: char) -> Type {
        match self.Env.get(&name) {
            Some(Type) => Type, // <------- Always error here
            None => Type::TyInt,
        }
    }
}
</code>```

答:
HashMap::get returns an Option<&Type>, not an Option<Type>, which is why just returning the matched value fails to compile.

get provides a reference because in Rust you cannot simply return the actual value that is in the hash table - you need to either clone it (make a copy, potentially expensive), remove it from the container and transfer it to the caller, or return a reference to the value inside. HashMap::get chooses the last option because it is cheap while providing the greatest flexibility to the caller, which can choose to either inspect the value or clone it.

For your enum that consists of a single machine word, copying the value would be the optimal approach. (For more complex enums, a better approach is to return a reference as shown in Simon's answer.) Copying requires:

making Type copyable, by marking it with the Copy trait using the #[derive(Copy, Clone)] directive at the type definition.

returning the copy from getv by dereferencing the matched value using *matched_value, or by using & in the pattern.

Finally, your getv method consumes the object, which means that you can call it only once. This is almost certainly not what was intended - it should accept &self instead. With those changes, the resulting code looks like this:

```<code>use std::collections::HashMap;

#[derive(Copy, Clone)]
enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    env: HashMap<char, Type>,
}

impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.env.insert(name, ty);
    }

    fn getv(&self, name: char) -> Type {
        match self.env.get(&name) {
            Some(&v) => v,
            None => Type::TyInt,
        }
    }
}
</code>```

If the type needs to contain non-Copy data, then you can make it only Clone instead, and return v.clone().

Body:
I want my getv() function return the value from a HashMap. I get errors no matter how I modify my code:

enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    Env: HashMap<char, Type>,
}
impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.Env.insert(name, ty);
    }

    fn getv(self, name: char) -> Type {
        match self.Env.get(&name) {
            Some(Type) => Type, // <------- Always error here
            None => Type::TyInt,
        }
    }
}

Body:
HashMap::get returns an Option<&Type>, not an Option<Type>, which is why just returning the matched value fails to compile.

get provides a reference because in Rust you cannot simply return the actual value that is in the hash table - you need to either clone it (make a copy, potentially expensive), remove it from the container and transfer it to the caller, or return a reference to the value inside. HashMap::get chooses the last option because it is cheap while providing the greatest flexibility to the caller, which can choose to either inspect the value or clone it.

For your enum that consists of a single machine word, copying the value would be the optimal approach. (For more complex enums, a better approach is to return a reference as shown in Simon's answer.) Copying requires:

making Type copyable, by marking it with the Copy trait using the #[derive(Copy, Clone)] directive at the type definition.

returning the copy from getv by dereferencing the matched value using *matched_value, or by using & in the pattern.

Finally, your getv method consumes the object, which means that you can call it only once. This is almost certainly not what was intended - it should accept &self instead. With those changes, the resulting code looks like this:

use std::collections::HashMap;

#[derive(Copy, Clone)]
enum Type {
    TyInt,
    TyBool,
}

struct TypeEnv {
    env: HashMap<char, Type>,
}

impl TypeEnv {
    fn set(&mut self, name: char, ty: Type) {
        self.env.insert(name, ty);
    }

    fn getv(&self, name: char) -> Type {
        match self.env.get(&name) {
            Some(&v) => v,
            None => Type::TyInt,
        }
    }
}

If the type needs to contain non-Copy data, then you can make it only Clone instead, and return v.clone().


问:
How to evaluate multiple expression in if--elif statement in python?
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

```<code>n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"
</code>```

答:
if you have multiple branch in an if/elif statement that does the same thing you could use the or operator.
Something like this might work:

```<code>n = 5

if n % 2 != 0 or (not n % 2 and 6 < n < 20):
    print("weird")
else:
    print("Not Weird")
</code>```

Body:
How to evaluate multiple expression in if--elif in below code snipet.

I am sure its basic syntax issue

n=5
if n%2 != 0:
    print ("weird")
elif n%2 == 0 && 2 < n && n <5:
    print "Not Weird"
elif n%2 == 0 && 6 < n && n < 20:
    print "Weird"
elif n%2 == 0 && n >20:
    print "NOt Weird"

Body:
if you have multiple branch in an if/elif statement that does the same thing you could use the or operator.
Something like this might work:

n = 5

if n % 2 != 0 or (not n % 2 and 6 < n < 20):
    print("weird")
else:
    print("Not Weird")


问:
get country code from http header and add it to url parameters in apache
I'm using cloudflare to provide the server with the country code in http header HTTP_CF_IPCOUNTRY.

I need to get country code from http header and add it to url parameters in apache server using .conf file (virtual host). is that possible?

Server version: Apache/2.4.7 (Ubuntu)

I have an angular dist folder and I'm serving the files using apache server and need the country in the url parameter.

my config file for both php service and angular app(/consultation/*)

```<code><VirtualHost *:80>
    ServerName hero.azure
    ServerAlias hero.com
    ErrorLog /var/log/apache2/error.log
    DocumentRoot /var/www/hero/public
    SetEnv APPLICATION_ENV "testing"
    AliasMatch ^/consultation(.*) "/var/www/ng2/dist/index.html"
    Alias "/ng2" "/var/www/ng2/dist/ng2/"
    <Directory /var/www/hero/public>
     <LimitExcept OPTIONS>
            AuthType Basic
            AuthName "user"
            AuthUserFile /etc/apache2/htpass
            Require user user
    </LimitExcept>
            DirectoryIndex index.php
            AllowOverride All
            Order allow,deny
            Allow from all
    </Directory>
</VirtualHost>
</code>```

and here is some tries to add the query

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} country
RewriteRule ^/consultation(.*)$ ^/consultation/(.*)?country="%{CF-IPCOUNTRY}i"&%{QUERY_STRING} [QSA]
</code>```

答:
solved by adding this rule to the virtual host:</p>

```<code>SetEnvIf CF-IPCountry "(.*)" COUNTRY=$1
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{ENV:COUNTRY} [A-Z]{2}
    RewriteCond %{QUERY_STRING} !country [NC]
    RewriteRule ^/consultation(.*) %{REQUEST_URI}?country=%{ENV:COUNTRY} [L,QSA,R]
</IfModule>
</code>```

Body:
I'm using cloudflare to provide the server with the country code in http header HTTP_CF_IPCOUNTRY.

I need to get country code from http header and add it to url parameters in apache server using .conf file (virtual host). is that possible?

Server version: Apache/2.4.7 (Ubuntu)

I have an angular dist folder and I'm serving the files using apache server and need the country in the url parameter.

my config file for both php service and angular app(/consultation/*)

<VirtualHost *:80>
    ServerName hero.azure
    ServerAlias hero.com
    ErrorLog /var/log/apache2/error.log
    DocumentRoot /var/www/hero/public
    SetEnv APPLICATION_ENV "testing"
    AliasMatch ^/consultation(.*) "/var/www/ng2/dist/index.html"
    Alias "/ng2" "/var/www/ng2/dist/ng2/"
    <Directory /var/www/hero/public>
     <LimitExcept OPTIONS>
            AuthType Basic
            AuthName "user"
            AuthUserFile /etc/apache2/htpass
            Require user user
    </LimitExcept>
            DirectoryIndex index.php
            AllowOverride All
            Order allow,deny
            Allow from all
    </Directory>
</VirtualHost>

and here is some tries to add the query

RewriteEngine on
RewriteCond %{QUERY_STRING} country
RewriteRule ^/consultation(.*)$ ^/consultation/(.*)?country="%{CF-IPCOUNTRY}i"&%{QUERY_STRING} [QSA]

Body:
solved by adding this rule to the virtual host:

SetEnvIf CF-IPCountry "(.*)" COUNTRY=$1
<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{ENV:COUNTRY} [A-Z]{2}
    RewriteCond %{QUERY_STRING} !country [NC]
    RewriteRule ^/consultation(.*) %{REQUEST_URI}?country=%{ENV:COUNTRY} [L,QSA,R]
</IfModule>


问:
Fire AJAX jQuery if scroll reach to each div
I want make ajax fire if scroll reach to each div element.

Item div 1

Item div 2 (fire ajax if scroll to this element)

Item div 3 (fire ajax again if scroll to this element)

Item .....N

I use this code, but only fire if scroll to end.

$( window ).scroll( function() {
     if( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
      alert('Fire!');
     }
    });```

Please help.

答:
```<code>$(window).scroll( function() {
    var scrolled = $( window ).scrollTop();

    $('div:not(.fired)').each(function () {
        var position_of_div = $(this).offset();
        if (scrolled > position_of_div.top) {
            $(this).addClass('fired');
            alert('fire');
        }
    });
});
</code>```

Save the scrolled pixels in an variable. On scroll get the position of each div. If the amount of pixels scrolled is greater than the offset of the div (related to the document) fire a AJAX call.

Body:
I want make ajax fire if scroll reach to each div element.

Item div 1

Item div 2 (fire ajax if scroll to this element)

Item div 3 (fire ajax again if scroll to this element)

Item .....N

I use this code, but only fire if scroll to end.

$( window ).scroll( function() {
     if( $( window ).scrollTop() == $( document ).height() - $( window ).height() ) {
      alert('Fire!');
     }
    });

Please help.

Body:
$(window).scroll( function() {
    var scrolled = $( window ).scrollTop();

    $('div:not(.fired)').each(function () {
        var position_of_div = $(this).offset();
        if (scrolled > position_of_div.top) {
            $(this).addClass('fired');
            alert('fire');
        }
    });
});

Save the scrolled pixels in an variable. On scroll get the position of each div. If the amount of pixels scrolled is greater than the offset of the div (related to the document) fire a AJAX call.


问:
Error upon form submission in php
It appears my information is not being placed into the POST array correctly. I'm new to php so I'm not too sure why. I don't know what other information y'all need on this, so I'll just place the code and the error message. Any help/advice you could offer would be greatly appreciated.

This is the form after being rendered.

This is the error I'm getting after submission.

Here's the code snippets. I haven't included all of the html. I may be that I need to ditch the php and write stuff in java. Opinions welcomed.

```<code>        <h2 class="tgminix-padding-large" style="margin:auto;max-width:1000px">Calculating Total Percent Impedance Upstream of the Motor</h2>
    <hr class="tgminix-border-grey" style="margin:auto;width:80%">
    <p><span class="error">* Required Field</span></p>
    <form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>
          High Side Busbar Impedance (Real): <input type="float" name="SubstationHighsideEqivImpedanceR">
          <span class="error"> <?php echo $subImpedanceError;?></span>
          <br><br>
           High Side Busbar Impedance (Imaginary): <input type="float" name="SubstationHighsideEqivImpedanceI">
          <span class="error"> <?php echo $subImpedanceError;?></span>
          <br><br>
           Low Side Busbar Impedance (Real): <input type="float" name="SubstationLowsideEquivImpedanceR">
          <span class="error"><?php echo $subImpedanceError;?></span>
          <br><br>
          Low Side Busbar Impedance (Imaginary): <input type="float" name="SubstationLowsideEquivImpedanceI">
          <span class="error"><?php echo $subImpedanceError;?></span>
          <br><br>
          Motor Starting Power Factor: <input type="float" name="MotorStartingPowerFactor_num">
          <span class="error"><?php echo $subImpedanceError;?></span>
          <br><br>
          <input type="submit" value="Submit">
    </form>
  <?php
    /* Locked Rotor Constants Array
    $MotorLockedRotorConstants = array(
            array("NEMA Code Letter","Mid-Value Constant")
            array("A",1.6)
            array("B",3.3)
            array("C",3.8)
            array("D",4.3)
            array("E",4.7)
            array("F",5.3)
            array("G",5.9)
             array("H",6.7)
            array("J",7.5)
            array("K",8.5)
            array("L",9.5)
            array("M",10.6)
            array("N",11.8)
            array("P",13.2)
            array("R",15.0)
            array("S",17.1)
            array("T",19.0)
            array("U",21.5)
            array("V",25));*/
        if ($_POST){
            $SubstationHighsideEqivImpedance_real = $_POST["SubstationHighsideEqivImpedanceR"];
            $SubstationHighsideEquivImpedance_imaginary = $_POST["SubstationHighsideEqivImpedanceI"];
            $SubstationLowsideEquivImpedance_real = $_POST["SubstationLowsideEquivImpedanceR"];
            $SubstationLowsideEquivImpedance_imaginary = $_POST["SubstationLowsideEquivImpedanceI"];

            $MotorStartingPowerFactor = $_POST["MotorStartingPowerFactor_num"];

            $SubstationPercentImpedance = "";
            $TEMP_X_perc = $TEMP_R_perc = "";
            $TEMP_X_perc = $SubstationLowsideEquivImpedance_imaginary + 0.333333 * $SubstationHighsideEquivImpedance_imaginary;
            $TEMP_R_perc = $SubstationLowsideEquivImpedance_real + 0.33333 * $SubstationHighsideEqivImpedance_real;
            $RAD_ANGLE_TEMP = $MotorStartingPowerFactor*(pi()/180);
            $DEG_ANGLE_TEMP_cos = (180/pi()) * cos($RAD_ANGLE_TEMP);
            $DEG_ANGLE_TEMP_sin = (180/pi()) * sin($RAD_ANGLE_TEMP);
            $SubstationHisideImpedancePercent = ($TEMP_R_perc * $DEG_ANGLE_TEMP_cos) + ($TEMP_X_perc * DEG_ANGLE_TEMP_sin);
        } else {
            echo "There's nothing in POST. srry"
        }
       ?>
    <p class="tgminix-padding-large" style="margin:auto;max-width:1000px">
        The Substation Impedance is: <?php echo $SubstationHisideImpedancePercent; ?>
        <br>
        The Substation Impedance is: <?php echo $TEMP_R_perc; ?> $ + \mathbf{i}$ <?php echo $TEMP_X_perc; ?>
    </p>
</code>```

Let me know if this is too ambiguous.

答:
```<code>    REPLACE
    <form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>
    WITH
    <form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>">
</code>```

Title: Error upon form submission in php

Body:
It appears my information is not being placed into the POST array correctly. I'm new to php so I'm not too sure why. I don't know what other information y'all need on this, so I'll just place the code and the error message. Any help/advice you could offer would be greatly appreciated.

This is the form after being rendered.

This is the error I'm getting after submission.

Here's the code snippets. I haven't included all of the html. I may be that I need to ditch the php and write stuff in java. Opinions welcomed.

Calculating Total Percent Impedance Upstream of the Motor

* Required Field

    <form method="post" action="<?php echo htmlspecialcharachars($_SERVER["PHP_SELF"]);?>
          High Side Busbar Impedance (Real): <input type="float" name="SubstationHighsideEqivImpedanceR">
           <?php echo $subImpedanceError;?>

           High Side Busbar Impedance (Imaginary): <input type="float" name="SubstationHighsideEqivImpedanceI">
           <?php echo $subImpedanceError;?>

           Low Side Busbar Impedance (Real): <input type="float" name="SubstationLowsideEquivImpedanceR">
          <?php echo $subImpedanceError;?>

          Low Side Busbar Impedance (Imaginary): <input type="float" name="SubstationLowsideEquivImpedanceI">
          <?php echo $subImpedanceError;?>

          Motor Starting Power Factor: <input type="float" name="MotorStartingPowerFactor_num">
          <?php echo $subImpedanceError;?>

          <input type="submit" value="Submit">
    </form>
  <?php
    /* Locked Rotor Constants Array
    $MotorLockedRotorConstants = array(
            array("NEMA Code Letter","Mid-Value Constant")
            array("A",1.6)
            array("B",3.3)
            array("C",3.8)
            array("D",4.3)
            array("E",4.7)
            array("F",5.3)
            array("G",5.9)
             array("H",6.7)
            array("J",7.5)
            array("K",8.5)
            array("L",9.5)
            array("M",10.6)
            array("N",11.8)
            array("P",13.2)
            array("R",15.0)
            array("S",17.1)
            array("T",19.0)
            array("U",21.5)
            array("V",25));*/
        if ($_POST){
            $SubstationHighsideEqivImpedance_real = $_POST["SubstationHighsideEqivImpedanceR"];
            $SubstationHighsideEquivImpedance_imaginary = $_POST["SubstationHighsideEqivImpedanceI"];
            $SubstationLowsideEquivImpedance_real = $_POST["SubstationLowsideEquivImpedanceR"];
            $SubstationLowsideEquivImpedance_imaginary = $_POST["SubstationLowsideEquivImpedanceI"];

            $MotorStartingPowerFactor = $_POST["MotorStartingPowerFactor_num"];

            $SubstationPercentImpedance = "";
            $TEMP_X_perc = $TEMP_R_perc = "";
            $TEMP_X_perc = $SubstationLowsideEquivImpedance_imaginary + 0.333333 * $SubstationHighsideEquivImpedance_imaginary;
            $TEMP_R_perc = $SubstationLowsideEquivImpedance_real + 0.33333 * $SubstationHighsideEqivImpedance_real;
            $RAD_ANGLE_TEMP = $MotorStartingPowerFactor*(pi()/180);
            $DEG_ANGLE_TEMP_cos = (180/pi()) * cos($RAD_ANGLE_TEMP);
            $DEG_ANGLE_TEMP_sin = (180/pi()) * sin($RAD_ANGLE_TEMP);
            $SubstationHisideImpedancePercent = ($TEMP_R_perc * $DEG_ANGLE_TEMP_cos) + ($TEMP_X_perc * DEG_ANGLE_TEMP_sin);
        } else {
            echo "There's nothing in POST. srry"
        }
       ?>

        The Substation Impedance is: <?php echo $SubstationHisideImpedancePercent; ?>

        The Substation Impedance is: <?php echo $TEMP_R_perc; ?> $ + \mathbf{i}$ <?php echo $TEMP_X_perc; ?>

Let me know if this is too ambiguous.


问:
Selenium firefox fails to load only when run through windows task scheduler
I have a web scraping script in Python, using Selenium and (tor) Firefox. This runs completely fine when I start the script manually, in my IDE or from cmd. However, this script needs to be run when I am not in the office, so I run it via a batch script (along with some other scraping scripts) which is started by the windows task scheduler. Again, when I run this batch file manually, the script runs perfectly. When the scheduled task runs, on the other hand, it fails as soon as the webdriver is set with the following unhelpful error message:

```<code>Traceback (most recent call last):
  ...
  #private library traceback
  ...
  File "redacted.py", line 322, in redacted_func
    driver = webdriver.Firefox()
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 152, in __init__
    keep_alive=True)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 188, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 0
</code>```

Does anyone have any idea why this error occurs only when run from the task scheduler?

答:
After further investigation, I found that the error happens when the task is processed in the background. This happens when the task is set to 'Run whether user is logged on or not'. Changing this setting to 'Run only when user is logged on' allows the task to run without issue, in the foreground.

For some reason, running in the background causes firefox to crash, but chromedriver (which is used in some other scraping scripts I run) is unaffected by this. This seems slightly bizarre, but this workaround is sufficient to get this running on windows.

Body:
I have a web scraping script in Python, using Selenium and (tor) Firefox. This runs completely fine when I start the script manually, in my IDE or from cmd. However, this script needs to be run when I am not in the office, so I run it via a batch script (along with some other scraping scripts) which is started by the windows task scheduler. Again, when I run this batch file manually, the script runs perfectly. When the scheduled task runs, on the other hand, it fails as soon as the webdriver is set with the following unhelpful error message:

Traceback (most recent call last):
  ...
  #private library traceback
  ...
  File "redacted.py", line 322, in redacted_func
    driver = webdriver.Firefox()
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 152, in __init__
    keep_alive=True)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 98, in __init__
    self.start_session(desired_capabilities, browser_profile)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 188, in start_session
    response = self.execute(Command.NEW_SESSION, parameters)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 256, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files\Python 3.5\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: Process unexpectedly closed with status: 0

Does anyone have any idea why this error occurs only when run from the task scheduler?


问:
Passing a complex object to a page while navigating in a WP7 Silverlight application
I have been using the NavigationService's Navigate method to navigate to other pages in my WP7 Silverlight app:

```<code>NavigationService.Navigate(new Uri("/Somepage.xaml?val=dreas", UriKind.Relative));
</code>```

From Somepage.xaml, I then retrieve the query string parameters as follows:

```<code>string val;
NavigationContext.QueryString.TryGetValue("val", out val);
</code>```

I now need a way to pass a complex object using a similar manner.  How can I do this without having to serialize the object every time I need to pass it to a new page?

答:
This is an extremely complex problem, and there is no simple solution here. There is no magic API that would just work for any app to solve this problem.

The core problem with passing navigation data is Tombstoning. The only piece of data that is tombstoned by default is the Navigation URI. so if you're using a QueryString parameter, it'll get picked up automatically by tombstoning and your code. Any time you'll manually pass a instance of an object though, you'll have to manually do tombstoning for that instance yourself.

So, if you navigate to "/CowDetails.xaml?ID=1" your page will probably have perfect tombstoning just by picking up on the ID Querystring Parameter. However, if you somehow provide CowDetails page with a "new Cow() { ID = 1}" you'll have to make sure to tombstone and zombificate this value yourself.

Also, there's the issue of timing. While calling NavigationService.Navigate, the page you're navigating too doesn't have an actual instance yet. So even though you're navigating to FooPage and have the FooData ready, there's no way to immediately connect FooPage to FooData. You'll have to wait until the PhoneApplicationFrame.Navigated event has fired in order to provide FooPage with FooData.

The way I normally deal with this is problem:

Have a BasePage with an Object type Data property

Have a NavigationHelper get the page URI and Data: NavigationHelper.Navigate("foo.xaml", fooData)

Have NavigationHelper register to PhoneApplicationFrame.Navigated event and if it's "foo.xaml" set the BasePage.Data to FooData.

Have BasePage use JSON.Net to tombstone and zombificate BasePage.Data.

On BasePage, I've got a OnDataSet virtual method that is invoked once the Data property is populated either by Zombification or Navigation. In this method, everything that has to do with business data happens.

ContentLicense: CC BY-SA 2.5

Body:
I have been using the NavigationService's Navigate method to navigate to other pages in my WP7 Silverlight app:

NavigationService.Navigate(new Uri("/Somepage.xaml?val=dreas", UriKind.Relative));

From Somepage.xaml, I then retrieve the query string parameters as follows:

string val;
NavigationContext.QueryString.TryGetValue("val", out val);

I now need a way to pass a complex object using a similar manner.  How can I do this without having to serialize the object every time I need to pass it to a new page?


问:
How can I exit a ruby program on strg-c if a SystemExit exception is being catched
The code which I can not interrupt by using strg-c (Ctrl-C) :

```<code>orig_std_out = STDOUT.clone
orig_std_err = STDERR.clone
STDOUT.reopen('/dev/null', 'w')
STDERR.reopen('/dev/null', 'w')

name = cookbook_name(File.join(path, 'Metadata.rb'))
error = 0

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit
  error = 1
end
.
.
.
</code>```

In my understanding this behaviour would be reasonable if I would rescue Exception, but in this case I am basically catching siblings which only share their parent exception Exception.

I have already tried to rescue the exception Interrupt and SignalException explicitly.

EDIT1: In the hope of clarifying my question I added the following code which i tried:

```<code>begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit => e
  msg1 = e.message
  error = 1
rescue Interrupt
  msg2 = "interrupted"
end
</code>```

In both cases - SystemExit thrown by Knife.run and thrown by Ctrl-C - e.message returns "exit". This does not only mean, that Ctrl-C throws a SystemExit whereas I am expecting it to throw an Interrupt, but also that the error message is the same.
I guess that I have got a major misunderstanding in how ruby works there, since I am not very familiar with ruby.

EDIT2: Further testing revealed that some Ctrl-C interrupts are rescued by rescue Interrupt. Is it possible that the command ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"]), which takes about 3-5 seconds to run, creates some kind of subprocess which responds to a Ctrl-C, but always closes with a SystemExit and that rescue Interruptonly works when it is interrupted just the moment this subprocess is not running? If this is the case, how am I going to be able to Interrupt the whole program?

EDIT3: I initially wanted to attach all the methods which get called on calling Knife.run, however, this would have been too many LoC, although I think my guess that a subcommand is executed was right. The chef gem code can be found here. Thus, the following excerpt is only the part which is the problematic one in my opinion:

```<code> rescue Exception => e
  raise if raise_exception || Chef::Config[:verbosity] == 2
  humanize_exception(e)
  exit 100
end
</code>```

Which leads to the question: How can I catch a Ctrl-C which is already rescued by a subcommand?

答:
The following code shows how I am able to interrupt after all:

```<code>interrupted = false
trap("INT") { interrupted = true} #sent INT to force exit in Knife.run and then exit

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"]) #exits on error and on interrupt with 100
  if interrupted
    exit
  end
rescue SystemExit => e
  if interrupted
    exit
  end
  error = 1
end
</code>```

The drawback still is, that I am not exactly able to interrupt the Knife.run, but only able to trap the interrupt and check after that command whether an interrupt was triggered. I found no way to trap the interrupt and "reraise" it at the same time, so that I am at least able to force an exit out of Knife.run which I can then exit manually.

Body:
The code which I can not interrupt by using strg-c (Ctrl-C) :

orig_std_out = STDOUT.clone
orig_std_err = STDERR.clone
STDOUT.reopen('/dev/null', 'w')
STDERR.reopen('/dev/null', 'w')

name = cookbook_name(File.join(path, 'Metadata.rb'))
error = 0

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit
  error = 1
end
.
.
.

In my understanding this behaviour would be reasonable if I would rescue Exception, but in this case I am basically catching siblings which only share their parent exception Exception.

I have already tried to rescue the exception Interrupt and SignalException explicitly.

EDIT1: In the hope of clarifying my question I added the following code which i tried:

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit => e
  msg1 = e.message
  error = 1
rescue Interrupt
  msg2 = "interrupted"
end

In both cases - SystemExit thrown by Knife.run and thrown by Ctrl-C - e.message returns "exit". This does not only mean, that Ctrl-C throws a SystemExit whereas I am expecting it to throw an Interrupt, but also that the error message is the same.
I guess that I have got a major misunderstanding in how ruby works there, since I am not very familiar with ruby.

EDIT2: Further testing revealed that some Ctrl-C interrupts are rescued by rescue Interrupt. Is it possible that the command ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"]), which takes about 3-5 seconds to run, creates some kind of subprocess which responds to a Ctrl-C, but always closes with a SystemExit and that rescue Interruptonly works when it is interrupted just the moment this subprocess is not running? If this is the case, how am I going to be able to Interrupt the whole program?

EDIT3: I initially wanted to attach all the methods which get called on calling Knife.run, however, this would have been too many LoC, although I think my guess that a subcommand is executed was right. The chef gem code can be found here. Thus, the following excerpt is only the part which is the problematic one in my opinion:

 rescue Exception => e
  raise if raise_exception || Chef::Config[:verbosity] == 2
  humanize_exception(e)
  exit 100
end

Which leads to the question: How can I catch a Ctrl-C which is already rescued by a subcommand?

Body:
The following code shows how I am able to interrupt after all:

interrupted = false
trap("INT") { interrupted = true} #sent INT to force exit in Knife.run and then exit

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"]) #exits on error and on interrupt with 100
  if interrupted
    exit
  end
rescue SystemExit => e
  if interrupted
    exit
  end
  error = 1
end

The drawback still is, that I am not exactly able to interrupt the Knife.run, but only able to trap the interrupt and check after that command whether an interrupt was triggered. I found no way to trap the interrupt and "reraise" it at the same time, so that I am at least able to force an exit out of Knife.run which I can then exit manually.


问:
How to center a div (CSS loader)
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="loader"></div></code>```

How do I centre it horizontally & vertically?

I tried:

```<code>position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
</code>```

But transform:translate(-50%,-50%); do not work

答:
Please add body {height: 100vh;} and update the css of loader div as the following:

```<code>.loader {
            border: 16px solid #f3f3f3;
            border-radius: 50%;
            border-top: 16px solid #3498db;
            width: 120px;
            height: 120px;
            -webkit-animation: spin 2s linear infinite;
            animation: spin 2s linear infinite;
            margin: auto;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }
</code>```

https://jsfiddle.net/7baw2rmp/

Title: How to center a div (CSS loader)

Body:
JS Fiddle: fiddle and here is the code:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite;
  animation: spin 2s linear infinite;
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

How do I centre it horizontally & vertically?

I tried:

position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);

But transform:translate(-50%,-50%); do not work

Body:
Please add body {height: 100vh;} and update the css of loader div as the following:

.loader {
            border: 16px solid #f3f3f3;
            border-radius: 50%;
            border-top: 16px solid #3498db;
            width: 120px;
            height: 120px;
            -webkit-animation: spin 2s linear infinite;
            animation: spin 2s linear infinite;
            margin: auto;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }

https://jsfiddle.net/7baw2rmp/


问:
Angular2: ngClass is not working on page load
This is my code:

```<code>constructor(private service: MyService) {
    this.customer = service.getData();
    console.log(this.customer.address.postalAddress.streetAddress.length);
  }

<input required [(ngModel)]="customer.address.postalAddress.streetAddress"
       [ngClass]="{'ng-dirty': customer.address.postalAddress.streetAddress.length > 0}">
</code>```

Inside console browser logs 15 which is number of counted address length yet css class is not applied.

Css is applied only when on purpose reset customer object and again
  set data, on page load is not working.

答:
You most probably need a resolver or change detection. Or preferably both.

What happens is the page gets initialized before your data is loaded in and not checked again until you reset the customer object. Resolve would allow you to grab data before you activate a route and component thus eliminating that problem.

https://angular.io/guide/router#resolve-pre-fetching-component-data - here's angular official guide on how to use resolvers.

https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html - I also would suggest reading up and using change detection. Helps identify and eliminate problems like this.

Body:
This is my code:

constructor(private service: MyService) {
    this.customer = service.getData();
    console.log(this.customer.address.postalAddress.streetAddress.length);
  }

<input required [(ngModel)]="customer.address.postalAddress.streetAddress"
       [ngClass]="{'ng-dirty': customer.address.postalAddress.streetAddress.length > 0}">

Inside console browser logs 15 which is number of counted address length yet css class is not applied.

Css is applied only when on purpose reset customer object and again
  set data, on page load is not working.


问:
npm: Add a platform specific dependency
In NPM documentation, there is an os option for platform specific dependency.

My package.json contains fsevents, which is a must on MacOS for performance reasons. On the other hand, it causes error on Windows.

```<code>"dependencies": {
        "axios": "^0.17.0",
        "electron": "^1.6.11",
        "electron-packager": "^8.7.2",
        "electron-reload": "^1.2.2",
        "electron-store": "^1.3.0",
        "flatpickr": "^4.0.7",
        "fsevents": "^1.1.2",
</code>```

So how exactly do I use the os option?

答:
Its work around i tried

Add to your package.json:

```<code>"scripts": {
  "install": "node install_dependencies.js"
}
</code>```

And then add a install_dependencies.js file that checks the OS - which run npm install.

Title: npm: Add a platform specific dependency

Body:
In NPM documentation, there is an os option for platform specific dependency.

My package.json contains fsevents, which is a must on MacOS for performance reasons. On the other hand, it causes error on Windows.

"dependencies": {
        "axios": "^0.17.0",
        "electron": "^1.6.11",
        "electron-packager": "^8.7.2",
        "electron-reload": "^1.2.2",
        "electron-store": "^1.3.0",
        "flatpickr": "^4.0.7",
        "fsevents": "^1.1.2",

So how exactly do I use the os option?

Body:
Its work around i tried

Add to your package.json:

"scripts": {
  "install": "node install_dependencies.js"
}

And then add a install_dependencies.js file that checks the OS - which run npm install.


问:
Cloud Firestore: Missing or insufficient permissions
I am getting (on Android):

com.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions

using these security rules:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}
</code>```

My app seems to be properly authenticated using FirebaseAuth, as the mFirebaseAuth.getCurrentUser().getUid() returns the proper user ID.

Is there something I am doing wrong?

答:
I asked the Firebase support team directly since this issue was kind of critical for our service and I received the email below. It seems they fixed the bug now.

Please let me know if the issue happens again.

Hi there,

We have just confirmed with our engineers that this sporadic issue
  with our Security Rules for Firestore was a known bug but was already
  fixed today. Kindly test your security rules again and let us know if
  you are still encountering the issue.

Regards, Kevin

Body:
I am getting (on Android):

com.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions

using these security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

My app seems to be properly authenticated using FirebaseAuth, as the mFirebaseAuth.getCurrentUser().getUid() returns the proper user ID.

Is there something I am doing wrong?


问:
Angular2 + Jasmine test: "Illegal state: Could not load the summary for directive Foo."
When I try to run the following test with ng test it gives me the error shown below.

```<code>import { TestBed, inject } from '@angular/core/testing';

export class Foo {

}

describe('Foo', () => {

    let foo: Foo;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                Foo
            ]
        }).compileComponents();
        foo = TestBed.createComponent(Foo).componentInstance;
    });

    it('should be created', () => {
        expect(foo).toBeTruthy();
    });
});
</code>```

Error: Illegal state: Could not load the summary for directive Foo.

Why does this happen and how can I make it run?

答:
like @lex82 mentioned, you need to add @Component, and like @marco birchler mentioned, you need to add Foo to declarations list.

You can compile it, but that's not really needed

and you can remove the providers list, because Foo is a Component

import { TestBed, inject } from '@angular/core/testing';
import { Component } from '@angular/core';

@Component({template: '

'})
export class Foo { }

describe('Foo', () => {
  let foo: Foo;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [Foo]
    });
    foo = TestBed.createComponent(Foo).componentInstance;
  });

  it('should be created', () => {
    expect(foo).toBeTruthy();
  });
});```

Body:
When I try to run the following test with ng test it gives me the error shown below.

import { TestBed, inject } from '@angular/core/testing';

export class Foo {

}

describe('Foo', () => {

    let foo: Foo;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                Foo
            ]
        }).compileComponents();
        foo = TestBed.createComponent(Foo).componentInstance;
    });

    it('should be created', () => {
        expect(foo).toBeTruthy();
    });
});

Error: Illegal state: Could not load the summary for directive Foo.

Why does this happen and how can I make it run?

Body:
like @lex82 mentioned, you need to add @Component, and like @marco birchler mentioned, you need to add Foo to declarations list.

You can compile it, but that's not really needed

and you can remove the providers list, because Foo is a Component

import { TestBed, inject } from '@angular/core/testing';
import { Component } from '@angular/core';

@Component({template: '<div></div>'})
export class Foo { }

describe('Foo', () => {
  let foo: Foo;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [Foo]
    });
    foo = TestBed.createComponent(Foo).componentInstance;
  });

  it('should be created', () => {
    expect(foo).toBeTruthy();
  });
});


问:
Asynchronous returning of values to parent process
I'm involved in the resolution of an exercise using fork. The statement is this: 1 parent creates 3 children, those have random and different execution times and they have to return their respective values to the parent. So, till now I'm capable to create and execute the child processes and capture SOME of their values, but the execution becames nuts after that. The code I got till now is this:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAXCAPOS 3
#define MAXCOMERCIOS 3

/* Funcion que calcula aleatorios */
int calculaAleatorios(int min, int max) {
    return rand() % (max-min+1) + min;
}

/* Funcion para dar más tiempo a que los negocios paguen */
void darPlazo() {
    printf("\nDON: ¡Chicos! Decidle a los comerciantes que me deben dinero, que como no paguen lo que me deben, la semana que viene quemare sus tiendas.");
}

/* Funcion para dar una leccion a los negocios */
void darLeccion() {
    printf("\nDON: ¡Chicos! Quemad los comercios que no han pagado esta semana.");
}

/* Funcion para generar un consejo */
void generaConsejo() {
    sleep(10);
    if(calculaAleatorios(0,1)==0) {
        printf("\nConsigliere: Ya he deliberado SIGUSR1");
        kill(getppid(), SIGUSR1);
    } else {
        printf("\nConsigliere: Ya he deliberado SIGUSR2");
        kill(getppid(), SIGUSR2);
    }
}

int main(void){
  pid_t pidDon;
  pid_t pidCapo[MAXCAPOS];
  pid_t pidConsigliere;
  int i = 1, j = 1;
  int totalImpagos = 0;
  for (i; i <= MAXCAPOS; i++){
    /* Forkeando pidDon para obtener los capos */
    switch (pidDon = fork()){
      case -1:
        perror("Error en la llamada a la funcion fork()");
        exit(EXIT_FAILURE);
        break;
      case 0:
      {
        int noPagan = 0, tiempo = 0;
        pidCapo[i] = getpid();
        srand(pidCapo[i]); /*Generamos una semilla por el pid, dentro del proceso hijo para obtener semillas diferentes*/
        printf("\nDON: Contrato al capo%d (pid: %d)", i, pidCapo[i]);
        /* VISITAR LOS COMERCIOS Y RECIBIR CUANTOS HAN PAGADO (int) */
        for (j; j <= MAXCOMERCIOS; j++){
          tiempo = calculaAleatorios(5, 10); /* Genera un tiempo aleatorio entre 5 y 10 */
          printf("\n Capo%d: %d Segundos para despertar (pid: %d)", i, tiempo, pidCapo[i]);
          sleep(tiempo);
          printf("\n Capo%d: Visita el comercio %d (pid: %d)", i, j, pidCapo[i]);
          if (calculaAleatorios(0, 1) == 0){
            printf("\n Capo%d: El comercio %d no me ha pagado, malditas ratas!! (pid: %d)", i, j, pidCapo[i]);
            noPagan++;
          } else {
            printf("\n Capo%d: El comercio %d ha pagado (pid:%d)", i, j, pidCapo[i]);
          }
        }
        printf("\nCapo%d: tengo %d morosos", i, noPagan);
        exit(noPagan);
        break;
      }
      default:
        break;
    }
  }
  /*Proceso DON*/
  // Crear señales
  printf("\nDON: Voy a esperar noticias de mis capos... (pid: %d)", getpid());
  signal(SIGUSR1, darPlazo); // Unimos la señal SIGUSR1 a su procedimiento
  signal(SIGUSR2, darLeccion); //Unimos la señal SIGUSR2 a su procedimiento
  if (pidDon != 0 && pidDon != -1){
    for (i = 1; i <= MAXCAPOS; i++){
      int retorno;
      waitpid(pidCapo[i], &retorno, 0);
      retorno = WEXITSTATUS(retorno);
      printf("\nDON: Al capo %d no le han pagado %d comercios", i, retorno);
      totalImpagos += retorno;
    }
    sleep(30);
    if (totalImpagos == 0){
      printf("\nDON: Que bien, esta vez han pagado todos :D");
      printf("\nDON: He terminado mi dia\n");
      return (0);
    } else {
      if (totalImpagos == 1){
        printf("\nDON: No me ha pagado 1 comercio, grrrrrrrr!!!!");
      }
      if (totalImpagos > 1){
        printf("\nDON: No me han pagado %d comercios, estoy muy encabronado!", totalImpagos);
      }
      printf("\nDON: Consultare con mi consigliere");
      /*Proceso Consigliere*/
      pidConsigliere = fork();
      if (pidConsigliere == -1){
        perror("\nFallo al crear el proceso Consigliere");
        exit(EXIT_FAILURE);
      }
      else if (pidConsigliere == 0){
        signal(SIGUSR1, generaConsejo); // Unimos la señal SIGUSR1 a su procedimiento
        printf("\nConsigliere: Hola Don! Espero tu señal");
        pause();
        exit(0);
      }
      /*Vuelta al DON*/
      // Consulta al consigliere
      sleep(5);
      printf("\DON: Le mando una señal a mi consigliere");
      if (kill(pidConsigliere, SIGUSR1) == -1){ // Lanzamos kill contra pidConsigliere y evaluamos el error
        perror("\nFallo al enviar la señal al Consigliere");
        exit(EXIT_FAILURE);
      }
      printf("\nDON: Esperare mientras mi consigliere delibera");
      pause();
    }
  }
  printf("\nDON: He terminado mi dia\n");
  return (0);
}
</code>```

So, I need to know how to retreive correctly all the 3 returned values. Thanks in advance.

答:
So, till now I'm capable to create and execute the child processes and
  capture SOME of their values, but the execution becames nuts after
  that.

You are indexing pidCapo[i] with values for i from 1 to MAXCAPOS, which is wrong because arrays are indexed from 0 on.

Body:
I'm involved in the resolution of an exercise using fork. The statement is this: 1 parent creates 3 children, those have random and different execution times and they have to return their respective values to the parent. So, till now I'm capable to create and execute the child processes and capture SOME of their values, but the execution becames nuts after that. The code I got till now is this:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAXCAPOS 3
#define MAXCOMERCIOS 3

/* Funcion que calcula aleatorios */
int calculaAleatorios(int min, int max) {
    return rand() % (max-min+1) + min;
}

/* Funcion para dar más tiempo a que los negocios paguen */
void darPlazo() {
    printf("\nDON: ¡Chicos! Decidle a los comerciantes que me deben dinero, que como no paguen lo que me deben, la semana que viene quemare sus tiendas.");
}

/* Funcion para dar una leccion a los negocios */
void darLeccion() {
    printf("\nDON: ¡Chicos! Quemad los comercios que no han pagado esta semana.");
}

/* Funcion para generar un consejo */
void generaConsejo() {
    sleep(10);
    if(calculaAleatorios(0,1)==0) {
        printf("\nConsigliere: Ya he deliberado SIGUSR1");
        kill(getppid(), SIGUSR1);
    } else {
        printf("\nConsigliere: Ya he deliberado SIGUSR2");
        kill(getppid(), SIGUSR2);
    }
}

int main(void){
  pid_t pidDon;
  pid_t pidCapo[MAXCAPOS];
  pid_t pidConsigliere;
  int i = 1, j = 1;
  int totalImpagos = 0;
  for (i; i <= MAXCAPOS; i++){
    /* Forkeando pidDon para obtener los capos */
    switch (pidDon = fork()){
      case -1:
        perror("Error en la llamada a la funcion fork()");
        exit(EXIT_FAILURE);
        break;
      case 0:
      {
        int noPagan = 0, tiempo = 0;
        pidCapo[i] = getpid();
        srand(pidCapo[i]); /*Generamos una semilla por el pid, dentro del proceso hijo para obtener semillas diferentes*/
        printf("\nDON: Contrato al capo%d (pid: %d)", i, pidCapo[i]);
        /* VISITAR LOS COMERCIOS Y RECIBIR CUANTOS HAN PAGADO (int) */
        for (j; j <= MAXCOMERCIOS; j++){
          tiempo = calculaAleatorios(5, 10); /* Genera un tiempo aleatorio entre 5 y 10 */
          printf("\n Capo%d: %d Segundos para despertar (pid: %d)", i, tiempo, pidCapo[i]);
          sleep(tiempo);
          printf("\n Capo%d: Visita el comercio %d (pid: %d)", i, j, pidCapo[i]);
          if (calculaAleatorios(0, 1) == 0){
            printf("\n Capo%d: El comercio %d no me ha pagado, malditas ratas!! (pid: %d)", i, j, pidCapo[i]);
            noPagan++;
          } else {
            printf("\n Capo%d: El comercio %d ha pagado (pid:%d)", i, j, pidCapo[i]);
          }
        }
        printf("\nCapo%d: tengo %d morosos", i, noPagan);
        exit(noPagan);
        break;
      }
      default:
        break;
    }
  }
  /*Proceso DON*/
  // Crear señales
  printf("\nDON: Voy a esperar noticias de mis capos... (pid: %d)", getpid());
  signal(SIGUSR1, darPlazo); // Unimos la señal SIGUSR1 a su procedimiento
  signal(SIGUSR2, darLeccion); //Unimos la señal SIGUSR2 a su procedimiento
  if (pidDon != 0 && pidDon != -1){
    for (i = 1; i <= MAXCAPOS; i++){
      int retorno;
      waitpid(pidCapo[i], &retorno, 0);
      retorno = WEXITSTATUS(retorno);
      printf("\nDON: Al capo %d no le han pagado %d comercios", i, retorno);
      totalImpagos += retorno;
    }
    sleep(30);
    if (totalImpagos == 0){
      printf("\nDON: Que bien, esta vez han pagado todos :D");
      printf("\nDON: He terminado mi dia\n");
      return (0);
    } else {
      if (totalImpagos == 1){
        printf("\nDON: No me ha pagado 1 comercio, grrrrrrrr!!!!");
      }
      if (totalImpagos > 1){
        printf("\nDON: No me han pagado %d comercios, estoy muy encabronado!", totalImpagos);
      }
      printf("\nDON: Consultare con mi consigliere");
      /*Proceso Consigliere*/
      pidConsigliere = fork();
      if (pidConsigliere == -1){
        perror("\nFallo al crear el proceso Consigliere");
        exit(EXIT_FAILURE);
      }
      else if (pidConsigliere == 0){
        signal(SIGUSR1, generaConsejo); // Unimos la señal SIGUSR1 a su procedimiento
        printf("\nConsigliere: Hola Don! Espero tu señal");
        pause();
        exit(0);
      }
      /*Vuelta al DON*/
      // Consulta al consigliere
      sleep(5);
      printf("\DON: Le mando una señal a mi consigliere");
      if (kill(pidConsigliere, SIGUSR1) == -1){ // Lanzamos kill contra pidConsigliere y evaluamos el error
        perror("\nFallo al enviar la señal al Consigliere");
        exit(EXIT_FAILURE);
      }
      printf("\nDON: Esperare mientras mi consigliere delibera");
      pause();
    }
  }
  printf("\nDON: He terminado mi dia\n");
  return (0);
}

So, I need to know how to retreive correctly all the 3 returned values. Thanks in advance.


问:
Overriding id on create in ActiveRecord
Is there any way of overriding a model's id value on create? Something like:

```<code>Post.create(:id => 10, :title => 'Test')
</code>```

would be ideal, but obviously won't work.

答:
you can insert id by sql:</p>

```<code>  arr = record_line.strip.split(",")
  sql = "insert into records(id, created_at, updated_at, count, type_id, cycle, date) values(#{arr[0]},#{arr[1]},#{arr[2]},#{arr[3]},#{arr[4]},#{arr[5]},#{arr[6]})"
  ActiveRecord::Base.connection.execute sql
</code>```

OwnerDisplayName: Mr. Matt

Title: Overriding id on create in ActiveRecord

Body:
Is there any way of overriding a model's id value on create? Something like:

Post.create(:id => 10, :title => 'Test')

would be ideal, but obviously won't work.

Body:
you can insert id by sql:

  arr = record_line.strip.split(",")
  sql = "insert into records(id, created_at, updated_at, count, type_id, cycle, date) values(#{arr[0]},#{arr[1]},#{arr[2]},#{arr[3]},#{arr[4]},#{arr[5]},#{arr[6]})"
  ActiveRecord::Base.connection.execute sql


问:
Remove trailing whitespace recursively only at end of file using grep/sed?
Basically, I've got about 1,500 files and the last character of any of these files should not be any type of white space.

How do I check a bunch of files to make sure that they don't end in some form of whitespace?(newline, space, carriage return, tab, etc.)?

答:
Version 2. Linux syntax. Proper command.

```<code>find /directory/you/want -type f | \
xargs --verbose -L 1 sed -n --in-place -r \
':loop;/[^[:space:]\t]/ {p;b;}; N;b loop;'
</code>```

Version 1. Remove whitespace at the end of each line. FreeBSD syntax.

```<code>find /directory/that/holds/your/files -type f | xargs -L 1  sed  -i '' -E 's/[:         :]+$//'
</code>```

where the white space in [:         :] actually consists of one space and one tab characters.
With space it's easy. You just hit the space button. In order to get tab character inserted press Ctrl-V and then Tab in the shell.

Body:
Version 2. Linux syntax. Proper command.

find /directory/you/want -type f | \
xargs --verbose -L 1 sed -n --in-place -r \
':loop;/[^[:space:]\t]/ {p;b;}; N;b loop;'

Version 1. Remove whitespace at the end of each line. FreeBSD syntax.

find /directory/that/holds/your/files -type f | xargs -L 1  sed  -i '' -E 's/[:         :]+$//'

where the white space in [:         :] actually consists of one space and one tab characters.
With space it's easy. You just hit the space button. In order to get tab character inserted press Ctrl-V and then Tab in the shell.


问:
Generate String Permutations from multiple Set values (Java 8 Streams)
I have two Sets - country and state. I want to create all possible permutations from both.

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");

    Set<String> countryPermutations = new HashSet<>(
        Arrays.asList("United States of america", "USA"));
    Set<String> statePermutations = new HashSet<>(
        Arrays.asList("Texas", "TX"));

    Set<String> stateCountryPermutations = countryPermutations.stream()
        .flatMap(country -> statePermutations.stream()
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());

    Set<String> finalAliases = Optional.ofNullable(stateCountryPermutations)
        .map(Collection::stream).orElse(Stream.empty())
        .map(sc -> "houston " + sc)
        .collect(Collectors.toSet());
    System.out.println(stateCountryPermutationAliases);
  }
}
```
<p>The state or country or both permutations can be null. I still want my code to function.</p>
<p>Requirements</p>
<ol>
<li><p>If state permutation is null, final output should be [Houston USA, Houston United States of America]</p>
</li>
<li><p>If country permutations is null, final output should be [Houston TX, Houston Texas]</p>
</li>
<li><p>If both are null, then no output</p>
</li>
</ol>
<p>I'm changed my code to below</p>
<pre class="lang-java prettyprint-override"><code>Set<String> stateCountryPermutations =
    Optional.ofNullable(countryPermutations)
        .map(Collection::stream)
        .orElse(Stream.empty())
        .flatMap(country -> Optional.ofNullable(statePermutations)
            .map(Collection::stream)
            .orElse(Stream.empty())
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());
</code>```

This satisfies 3. When either permutation is null, 1 & 2 are not satisfied. I get no aliases as response. How do I modify my code?

答:
The following code creates all combinations from any number of input sets, ignoring null/empty sets:

Stream<Collection<String>> inputs = Stream.of(
        Arrays.asList("United States of america", "USA"),
        Arrays.asList("Texas", "TX"),
        Arrays.asList("Hello", "World"),
        null,
        new ArrayList<>());

Stream<Collection<List<String>>> listified = inputs
        .filter(Objects::nonNull)
        .filter(input -> !input.isEmpty())
        .map(l -> l.stream()
                .map(o -> new ArrayList<>(Arrays.asList(o)))
                .collect(Collectors.toList()));

Collection<List<String>> combinations = listified
        .reduce((input1, input2) -> {
            Collection<List<String>> merged = new ArrayList<>();
            input1.forEach(permutation1 -> input2.forEach(permutation2 -> {
                List<String> combination = new ArrayList<>();
                combination.addAll(permutation1);
                combination.addAll(permutation2);
                merged.add(combination);
            }));
            return merged;
        }).orElse(new HashSet<>());

combinations.forEach(System.out::println);
```
<p>Output:</p>
```[United States of america, Texas, Hello]
[United States of america, Texas, World]
[United States of america, TX, Hello]
[United States of america, TX, World]
[USA, Texas, Hello]
[USA, Texas, World]
[USA, TX, Hello]
[USA, TX, World]
```

Now you can use your mentioned helper method to create the permutations of each combination. This question shows how to generate all permutations of a list.

Body:
I have two Sets - country and state. I want to create all possible permutations from both.

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");

    Set<String> countryPermutations = new HashSet<>(
        Arrays.asList("United States of america", "USA"));
    Set<String> statePermutations = new HashSet<>(
        Arrays.asList("Texas", "TX"));

    Set<String> stateCountryPermutations = countryPermutations.stream()
        .flatMap(country -> statePermutations.stream()
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());

    Set<String> finalAliases = Optional.ofNullable(stateCountryPermutations)
        .map(Collection::stream).orElse(Stream.empty())
        .map(sc -> "houston " + sc)
        .collect(Collectors.toSet());
    System.out.println(stateCountryPermutationAliases);
  }
}

The state or country or both permutations can be null. I still want my code to function.

Requirements

If state permutation is null, final output should be [Houston USA, Houston United States of America]

If country permutations is null, final output should be [Houston TX, Houston Texas]

If both are null, then no output

I'm changed my code to below

Set<String> stateCountryPermutations =
    Optional.ofNullable(countryPermutations)
        .map(Collection::stream)
        .orElse(Stream.empty())
        .flatMap(country -> Optional.ofNullable(statePermutations)
            .map(Collection::stream)
            .orElse(Stream.empty())
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());

This satisfies 3. When either permutation is null, 1 & 2 are not satisfied. I get no aliases as response. How do I modify my code?

Body:
The following code creates all combinations from any number of input sets, ignoring null/empty sets:

Stream<Collection<String>> inputs = Stream.of(
        Arrays.asList("United States of america", "USA"),
        Arrays.asList("Texas", "TX"),
        Arrays.asList("Hello", "World"),
        null,
        new ArrayList<>());

Stream<Collection<List<String>>> listified = inputs
        .filter(Objects::nonNull)
        .filter(input -> !input.isEmpty())
        .map(l -> l.stream()
                .map(o -> new ArrayList<>(Arrays.asList(o)))
                .collect(Collectors.toList()));

Collection<List<String>> combinations = listified
        .reduce((input1, input2) -> {
            Collection<List<String>> merged = new ArrayList<>();
            input1.forEach(permutation1 -> input2.forEach(permutation2 -> {
                List<String> combination = new ArrayList<>();
                combination.addAll(permutation1);
                combination.addAll(permutation2);
                merged.add(combination);
            }));
            return merged;
        }).orElse(new HashSet<>());

combinations.forEach(System.out::println);

Output:

[United States of america, Texas, Hello]
[United States of america, Texas, World]
[United States of america, TX, Hello]
[United States of america, TX, World]
[USA, Texas, Hello]
[USA, Texas, World]
[USA, TX, Hello]
[USA, TX, World]

Now you can use your mentioned helper method to create the permutations of each combination. This question shows how to generate all permutations of a list.


问:
How to set Recyclerview to show only 4 tiles
So, ive implemented a RecyclerView which has 15 items, now what I want to do is to restrict the RecyclerView to 4 items when I click a button and vice versa, i'm not sure how to do that, this is what I have done, any inputs would be helpful

```<code>floatingButton.Click += delegate {
            if (clicked)
            {
                Toast.MakeText(this, "Has been clicked before", ToastLength.Short).Show();
                recyclerview_layoutmanger = new GridLayoutManager(this,, 2);
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = false;
            }
            else {
                recyclerview_layoutmanger = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
                Toast.MakeText(this, "Has not been clicked before", ToastLength.Short).Show();
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = true;
            }
        };
</code>```

Adapter Class

```<code>  public class RecyclerAdapter : RecyclerView.Adapter
    {
        public event EventHandler<int> ItemClick;

        private readonly List<MessageList> messages;

        public RecyclerAdapter(List<MessageList> messages)
        {
            this.messages = messages;
            NotifyDataSetChanged();
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var movieViewHolder = (MessageViewHolder)holder;
            movieViewHolder.messageView.Text = messages[position].Message;
            movieViewHolder.dateView.Text = messages[position].messageDate;
            // movieViewHolder.MovieImageView.SetImageResource(Resource.Drawable.starwarslogo);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var layout = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.messages_list_layout, parent, false);

            return new MessageViewHolder(layout, OnItemClick);

        }

        public override int ItemCount
        {
            get { return messages.Count; }
        }

        void OnItemClick(int position)
        {
            if (ItemClick != null)
                ItemClick(this, position);
        }
    }

        /// <summary>
        /// Called after <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>, <c><see cref="M:Android.App.Activity.OnRestart" /></c>, or
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, for your activity to start interacting with the user.
        /// </summary>
        protected override void OnResume()
    {
        var toggle = new ActionBarDrawerToggle(this, this.DrawerLayout, this.AppToolbar, 0, 0);
        this.DrawerLayout.AddDrawerListener(toggle);
        toggle.SyncState();

        base.OnResume();
    }
</code>```

But this just changes the layout to a side by side kinda thing

答:
You can change it in getItemsCount()

Solution:

```<code>class Adapter<ViewHolder> extends ...{
boolean userClicked=false;
//your other method

 @Override
public int getItemCount() {
    if(userClicked)
    return yourlist.size();
    else
    return yourlist.size()>4?4:yourlist.size();
}

public void setUserClicked( boolean userClicked){
        this.userClicked=userClicked;
        notifyDatasetChanged();
 }
}
</code>```

Body:
So, ive implemented a RecyclerView which has 15 items, now what I want to do is to restrict the RecyclerView to 4 items when I click a button and vice versa, i'm not sure how to do that, this is what I have done, any inputs would be helpful

floatingButton.Click += delegate {
            if (clicked)
            {
                Toast.MakeText(this, "Has been clicked before", ToastLength.Short).Show();
                recyclerview_layoutmanger = new GridLayoutManager(this,, 2);
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = false;
            }
            else {
                recyclerview_layoutmanger = new LinearLayoutManager(this, LinearLayoutManager.Vertical, false);
                Toast.MakeText(this, "Has not been clicked before", ToastLength.Short).Show();
                myRecyclerview.SetLayoutManager(recyclerview_layoutmanger);
                recyclerview_adapter.NotifyDataSetChanged();
                clicked = true;
            }
        };

Adapter Class

  public class RecyclerAdapter : RecyclerView.Adapter
    {
        public event EventHandler<int> ItemClick;

        private readonly List<MessageList> messages;

        public RecyclerAdapter(List<MessageList> messages)
        {
            this.messages = messages;
            NotifyDataSetChanged();
        }

        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            var movieViewHolder = (MessageViewHolder)holder;
            movieViewHolder.messageView.Text = messages[position].Message;
            movieViewHolder.dateView.Text = messages[position].messageDate;
            // movieViewHolder.MovieImageView.SetImageResource(Resource.Drawable.starwarslogo);
        }

        public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
        {
            var layout = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.messages_list_layout, parent, false);

            return new MessageViewHolder(layout, OnItemClick);

        }

        public override int ItemCount
        {
            get { return messages.Count; }
        }

        void OnItemClick(int position)
        {
            if (ItemClick != null)
                ItemClick(this, position);
        }
    }

        ///
        /// Called after <c><see cref="M:Android.App.Activity.OnRestoreInstanceState(Android.OS.Bundle)" /></c>, <c><see cref="M:Android.App.Activity.OnRestart" /></c>, or
        /// <c><see cref="M:Android.App.Activity.OnPause" /></c>, for your activity to start interacting with the user.
        ///
        protected override void OnResume()
    {
        var toggle = new ActionBarDrawerToggle(this, this.DrawerLayout, this.AppToolbar, 0, 0);
        this.DrawerLayout.AddDrawerListener(toggle);
        toggle.SyncState();

        base.OnResume();
    }

But this just changes the layout to a side by side kinda thing

Body:
You can change it in getItemsCount()

Solution:

class Adapter<ViewHolder> extends ...{
boolean userClicked=false;
//your other method

 @Override
public int getItemCount() {
    if(userClicked)
    return yourlist.size();
    else
    return yourlist.size()>4?4:yourlist.size();
}

public void setUserClicked( boolean userClicked){
        this.userClicked=userClicked;
        notifyDatasetChanged();
 }
}


问:
TypoScript to add a class only for "li" elements belonging to an "ol" list
the next TS code works great for my TYPO3 7.6 installation:

```<code>tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,li,ul
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks {
    ul {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser.tags.ul.fixAttrib.class.default = row
    }
    li {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
        callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default = col-4 col-sm-2 col-md-2
    }
    ol {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
    }
}
</code>```

Now I would like the class col-4 col-sm-2 col-md-2 is not present for li items only belonging to ol elements. For ul, they should be kept.

Trying the next line (or other variants) just breaks the markup:

```<code>tt_content.highlight_list.20.text.20.parseFunc.externalBlocks.ol.callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default =
</code>```

Any hints?

答:
I'm afraid this is not possible, since the tags are handled equal in
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,li,ul

To get similar results,
target ol>li and ul>li directly via css,

or
unset ol>li.col-4.col-sm-2.col-md-2 styles.

Should be quicker to do than to hassle with typoscript, IMHO.

Body:
the next TS code works great for my TYPO3 7.6 installation:

tt_content.highlight_list.20.text.20.parseFunc.externalBlocks = table,blockquote,ol,li,ul
tt_content.highlight_list.20.text.20.parseFunc.externalBlocks {
    ul {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser.tags.ul.fixAttrib.class.default = row
    }
    li {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
        callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default = col-4 col-sm-2 col-md-2
    }
    ol {
        stripNL = 1
        callRecursive = 1
        callRecursive.tagStdWrap.HTMLparser = 1
    }
}

Now I would like the class col-4 col-sm-2 col-md-2 is not present for li items only belonging to ol elements. For ul, they should be kept.

Trying the next line (or other variants) just breaks the markup:

tt_content.highlight_list.20.text.20.parseFunc.externalBlocks.ol.callRecursive.tagStdWrap.HTMLparser.tags.li.fixAttrib.class.default =

Any hints?


问:
sponsored messages on facebook with bot framework
How can I send a message to the user without the user sending me a message? Like for example CNN bot is sending messages every day in the morning by itself. How can I do that in the bot framework?</p>

答:
Yes you can do that. We called it Greeting from Bot. I have done it and sharing a sample code with you.

Write this code in your messageController or first dialog used in bot.

```<code>if (activity.Text == null)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                Activity isActivityTyping = activity.CreateReply();
                isActivityTyping.Type = ActivityTypes.Typing;
                await connector.Conversations.ReplyToActivityAsync(isActivityTyping);
                await Conversation.SendAsync(activity, () => new Dialogs.GreetDialog());

            }
</code>```

after this code you need to create a dialog GreetDialog. Below is the cs file code for your reference.

```<code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

namespace GPP.Bot.Dialogs
{
    [Serializable]
    internal class GreetDialog : IDialog<object>
    {
        public async Task StartAsync(IDialogContext context)
        {
           context.Wait(Greeting);
        }
        private async Task Greeting(IDialogContext context, IAwaitable<IMessageActivity> argument)
        {
            var message = await argument;
            if (string.IsNullOrEmpty(message.Text))
            {

                // Hero Card
                var cardMsg = context.MakeMessage();
                var attachment = BotWelcomeCard("Hello, I am a bot. Right now I am on training and in a prototype state", "");
                cardMsg.Attachments.Add(attachment);
                await context.PostAsync(cardMsg);
                context.Call<object>(new ActionDialog(), AfterGreetingDialogCompleted);
            }
            else
            {
               context.Call<object>(new ActionDialog(), AfterGreetingDialogCompleted);
            }
        }
        private static Attachment BotWelcomeCard(string responseFromQNAMaker, string userQuery)
        {
            var heroCard = new HeroCard
            {
                Title = userQuery,
                Subtitle = "",
                Text = responseFromQNAMaker,
                Images = new List<CardImage> { new CardImage("https://i2.wp.com/lawyerist.com/lawyerist/wp-content/uploads/2016/08/docubot.gif?fit=322%2C294&ssl=1") },
                Buttons = new List<CardAction> { new CardAction(ActionTypes.ImBack, "Show Menu", value: "Show Bot Menu") }
            };

            return heroCard.ToAttachment();
        }
        private async Task AfterGreetingDialogCompleted(IDialogContext context, IAwaitable<object> result)
        {
            context.Done<object>(new object());
        }
    }
}
</code>```

this is a working code. Do let me know in case you face ant issue.
~cheers :)

Body:
Yes you can do that. We called it Greeting from Bot. I have done it and sharing a sample code with you.

Write this code in your messageController or first dialog used in bot.

if (activity.Text == null)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                Activity isActivityTyping = activity.CreateReply();
                isActivityTyping.Type = ActivityTypes.Typing;
                await connector.Conversations.ReplyToActivityAsync(isActivityTyping);
                await Conversation.SendAsync(activity, () => new Dialogs.GreetDialog());

            }

after this code you need to create a dialog GreetDialog. Below is the cs file code for your reference.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Connector;

namespace GPP.Bot.Dialogs
{
    [Serializable]
    internal class GreetDialog : IDialog<object>
    {
        public async Task StartAsync(IDialogContext context)
        {
           context.Wait(Greeting);
        }
        private async Task Greeting(IDialogContext context, IAwaitable<IMessageActivity> argument)
        {
            var message = await argument;
            if (string.IsNullOrEmpty(message.Text))
            {

                // Hero Card
                var cardMsg = context.MakeMessage();
                var attachment = BotWelcomeCard("Hello, I am a bot. Right now I am on training and in a prototype state", "");
                cardMsg.Attachments.Add(attachment);
                await context.PostAsync(cardMsg);
                context.Call<object>(new ActionDialog(), AfterGreetingDialogCompleted);
            }
            else
            {
               context.Call<object>(new ActionDialog(), AfterGreetingDialogCompleted);
            }
        }
        private static Attachment BotWelcomeCard(string responseFromQNAMaker, string userQuery)
        {
            var heroCard = new HeroCard
            {
                Title = userQuery,
                Subtitle = "",
                Text = responseFromQNAMaker,
                Images = new List<CardImage> { new CardImage("https://i2.wp.com/lawyerist.com/lawyerist/wp-content/uploads/2016/08/docubot.gif?fit=322%2C294&ssl=1") },
                Buttons = new List<CardAction> { new CardAction(ActionTypes.ImBack, "Show Menu", value: "Show Bot Menu") }
            };

            return heroCard.ToAttachment();
        }
        private async Task AfterGreetingDialogCompleted(IDialogContext context, IAwaitable<object> result)
        {
            context.Done<object>(new object());
        }
    }
}

this is a working code. Do let me know in case you face ant issue.
~cheers :)


问:
How to get value of escape characters in c#?

I want to know the ASCII value of an escape sequence in runtime. for example:

string x = "\\b";
char res = someFunctionCall(x);
//res = '\b' = 0x08
```

The difference here that I only know x at runtime.

I know that this can be made with simple switch (already doing that), but I was wondering if it can be made using some existing c# call. I tried Char.Parse(x), but it didn't work.

Edit: I'm not talking here about converting '\b' to its corresponding ASCII value, rather, I'd like to parse "\\b" as what you write in c# to get '\b'.

答:
There is slow but rather easy way to do this. compile your code at runtime and let c# compiler take care of that! I know its overkill for what you want. but it works.

Anyway as @JonSkeet noted you can use a dictionary for simple escape sequences. take your list from here https://msdn.microsoft.com/en-us/library/h21280bw.aspx

Here is solution by compiling code at runtime, Note that its VERY SLOW, so I suggest you to replace and map multiple characters at once so compiler only runs and evaluate all of that for you only once.

```<code>using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

//...

private static void Main()
{
    string x = "\\b";
    string res = Evaluate(x);
    Console.WriteLine(res);
}

public static string Evaluate(string input)
{
    // code to compile.
    const string format = "namespace EscapeSequenceMapper {{public class Program{{public static string Main(){{ return \"{0}\";}}}}}}";

    // compile code.
    var cr = new CSharpCodeProvider().CompileAssemblyFromSource(
        new CompilerParameters { GenerateInMemory = true }, string.Format(format, input));

    if (cr.Errors.HasErrors) return null;

    // get main method and invoke.
    var method = cr.CompiledAssembly.GetType("EscapeSequenceMapper.Program").GetMethod("Main");
    return (string)method.Invoke(null, null);
}
</code>```

Body:
I want to know the ASCII value of an escape sequence in runtime. for example:

string x = "\\b";
char res = someFunctionCall(x);
//res = '\b' = 0x08

The difference here that I only know x at runtime.

I know that this can be made with simple switch (already doing that), but I was wondering if it can be made using some existing c# call. I tried Char.Parse(x), but it didn't work.

Edit: I'm not talking here about converting '\b' to its corresponding ASCII value, rather, I'd like to parse "\\b" as what you write in c# to get '\b'.

Body:
There is slow but rather easy way to do this. compile your code at runtime and let c# compiler take care of that! I know its overkill for what you want. but it works.

Anyway as @JonSkeet noted you can use a dictionary for simple escape sequences. take your list from here https://msdn.microsoft.com/en-us/library/h21280bw.aspx

Here is solution by compiling code at runtime, Note that its VERY SLOW, so I suggest you to replace and map multiple characters at once so compiler only runs and evaluate all of that for you only once.

using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

//...

private static void Main()
{
    string x = "\\b";
    string res = Evaluate(x);
    Console.WriteLine(res);
}

public static string Evaluate(string input)
{
    // code to compile.
    const string format = "namespace EscapeSequenceMapper {{public class Program{{public static string Main(){{ return \"{0}\";}}}}}}";

    // compile code.
    var cr = new CSharpCodeProvider().CompileAssemblyFromSource(
        new CompilerParameters { GenerateInMemory = true }, string.Format(format, input));

    if (cr.Errors.HasErrors) return null;

    // get main method and invoke.
    var method = cr.CompiledAssembly.GetType("EscapeSequenceMapper.Program").GetMethod("Main");
    return (string)method.Invoke(null, null);
}


问:
DDD - How handle transactions in the "returning domain events" pattern?
In the DDD litterature, the returning domain event pattern is described as a way to manage domain events. Conceptually, the aggregate root keeps a list of domain events, populated when you do some operations on it.

When the operation on the aggregate root is done, the DB transaction is completed, at the application service layer, and then, the application service iterates on the domain events, calling an Event Dispatcher to handle those messages.

My question is concerning the way we should handle transaction at this moment. Should the Event Dispatcher be responsible of managing a new transaction for each event it process? Or should the application service manages the transaction inside the domain event iteration where it calls the domain Event Dispatcher? When the dispatcher uses infrastructure mecanism like RabbitMQ, the question is irrelevent, but when the domain events are handled in-process, it is.

Sub-question related to my question. What is your opinion about using ORM hooks (i.e.: IPostInsertEventListener, IPostDeleteEventListener, IPostUpdateEventListener of NHibernate) to kick in the Domain Events iteration on the aggregate root instead of manually doing it in the application service? Does it add too much coupling? Is it better because it does not require the same code being written at each use case (the domain event looping on the aggregate and potentially the new transaction creation if it is not inside the dispatcher)?

答:
Just because event handling happens in-process doesn't mean the originating application service has to orchestrate all transactions happening as a consequence of the events.

If we take in-process event handling via the Observable pattern for instance, each Observer will be responsible for creating its own transaction if it needs one.

What is your opinion about using ORM hooks (i.e.:
  IPostInsertEventListener, IPostDeleteEventListener,
  IPostUpdateEventListener of NHibernate) to kick in the Domain Events
  iteration on the aggregate root instead of manually doing it in the
  application service?

Wouldn't this have to happen during the original DB transaction, effectively turning everything into immediate consistency (if events are handled in process)?