问:
Adyen ERROR: [status] => 403 [errorCode] => 010 [message] => Not allowed [errorType] => security
I'm trying to use JSON API in order to make a (test) payment via ADYEN.

Here's the code (I got this example from Github -> Adyen ->adyen-php-sample-code:

```<code>    <?php
/**
 * Create Payment through the API (HTTP Post)
 *
 *
 * Please note: using our API requires a web service user. Set up your Webservice
 * user: Adyen Test CA >> Settings >> Users >> ws@Company. >> Generate Password >> Submit
 *
 * @author  Created by Adyen - Payments Made Easy
 */

 /**
  * A payment can be submitted by sending a PaymentRequest
  * to the authorise action of the web service, the request should
  * contain the following variables:
  *
  * - merchantAccount: The merchant account the payment was processed with.
  * - amount: The amount of the payment
  *     - currency: the currency of the payment
  *     - amount: the amount of the payment
  * - reference: Your reference
  * - shopperIP: The IP address of the shopper (optional/recommended)
  * - shopperEmail: The e-mail address of the shopper
  * - shopperReference: The shopper reference, i.e. the shopper ID
  * - fraudOffset: Numeric value that will be added to the fraud score (optional)
  * - card
  *     - expiryMonth: The expiration date's month written as a 2-digit string, padded with 0 if required (e.g. 03 or 12).
  *     - expiryYear: The expiration date's year written as in full. e.g. 2016.
  *     - holderName: The card holder's name, aas embossed on the card.
  *     - number: The card number.
  *     - cvc: The card validation code. This is the the CVC2 code (for MasterCard), CVV2 (for Visa) or CID (for American Express).
  * - billingAddress: we advice you to submit billingAddress data if available for risk checks;
  *   - street: The street name
  *   - postalCode: The postal/zip code.
  *   - city: The city
  *   - houseNumberOrName:
  *   - stateOrProvince: The house number
  *   - country: The country
  */

 $request =array(
  "merchantAccount" => "[YourMerchantAccount]",
  "amount" => array(
    "currency" => "EUR",
    "value" => "199"
  ),
  "reference" => "TEST-PAYMENT-" . date("Y-m-d-H:i:s"),
    "shopperIP" => "2.207.255.255",
    "shopperReference" => "YourReference",
  "billingAddress" => array(
    "street" => "Simon Carmiggeltstraat",
        "postalCode" => "1011DJ",
        "city" => "Amsterdam",
        "houseNumberOrName" => "6-60",
        "stateOrProvince" => "NH",
        "country" => "NL"
  ),
    "card" => array(
        "expiryMonth" => "08",
        "expiryYear" => "2018",
        "holderName" => "Test Card Holder",
        "number" => "4111111111111111",
        "cvc" => "737"
    ),
    "browserInfo"=>array(
        "acceptHeader"=>$_SERVER['HTTP_USER_AGENT'],
        "userAgent"=>$_SERVER['HTTP_ACCEPT']
    )
);

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "https://pal-test.adyen.com/pal/servlet/Payment/v25/authorise");
 curl_setopt($ch, CURLOPT_HEADER, false);
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC  );
 curl_setopt($ch, CURLOPT_USERPWD, "YourWSUser:YourWSUserPassword");
 curl_setopt($ch, CURLOPT_POST,count(json_encode($request)));
 curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($request));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-type: application/json"));

 $result = curl_exec($ch);

 if($result === false)
    echo "Error: " . curl_error($ch);
 else{
    /**
     * If the payment passes validation a risk analysis will be done and, depending on the
     * outcome, an authorisation will be attempted. You receive a
     * payment response with the following fields:
     * - pspReference: The reference we assigned to the payment;
     * - resultCode: The result of the payment. One of Authorised, Refused or Error;
     * - authCode: An authorisation code if the payment was successful, or blank otherwise;
     * - refusalReason: If the payment was refused, the refusal reason.
     */

print_r(json_decode($result));
 }

 curl_close($ch);
?>
</code>```

Has anyone faced this problem before? How may I fix this?
I've used almost any example in github, but there are just a few error which are documented, the rest....nothing..

Please help me on this. Thank you

答:
Often this problem occurs when your user doesn't have permission to processes raw card details. Handling the raw card information requires full PCI compliance (SAQ D). If this is you, reach out to support@adyen.com to request that permission to be enabled on your account. </p>

<p>If not, you can use Adyen's CSE solution. Docs here. PHP example here. </p>

Body:
I'm trying to use JSON API in order to make a (test) payment via ADYEN.

Here's the code (I got this example from Github -> Adyen ->adyen-php-sample-code:

    <?php
/**
 * Create Payment through the API (HTTP Post)
 *
 *
 * Please note: using our API requires a web service user. Set up your Webservice
 * user: Adyen Test CA >> Settings >> Users >> ws@Company. >> Generate Password >> Submit
 *
 * @author  Created by Adyen - Payments Made Easy
 */

 /**
  * A payment can be submitted by sending a PaymentRequest
  * to the authorise action of the web service, the request should
  * contain the following variables:
  *
  * - merchantAccount: The merchant account the payment was processed with.
  * - amount: The amount of the payment
  *     - currency: the currency of the payment
  *     - amount: the amount of the payment
  * - reference: Your reference
  * - shopperIP: The IP address of the shopper (optional/recommended)
  * - shopperEmail: The e-mail address of the shopper
  * - shopperReference: The shopper reference, i.e. the shopper ID
  * - fraudOffset: Numeric value that will be added to the fraud score (optional)
  * - card
  *     - expiryMonth: The expiration date's month written as a 2-digit string, padded with 0 if required (e.g. 03 or 12).
  *     - expiryYear: The expiration date's year written as in full. e.g. 2016.
  *     - holderName: The card holder's name, aas embossed on the card.
  *     - number: The card number.
  *     - cvc: The card validation code. This is the the CVC2 code (for MasterCard), CVV2 (for Visa) or CID (for American Express).
  * - billingAddress: we advice you to submit billingAddress data if available for risk checks;
  *   - street: The street name
  *   - postalCode: The postal/zip code.
  *   - city: The city
  *   - houseNumberOrName:
  *   - stateOrProvince: The house number
  *   - country: The country
  */

 $request =array(
  "merchantAccount" => "[YourMerchantAccount]",
  "amount" => array(
    "currency" => "EUR",
    "value" => "199"
  ),
  "reference" => "TEST-PAYMENT-" . date("Y-m-d-H:i:s"),
    "shopperIP" => "2.207.255.255",
    "shopperReference" => "YourReference",
  "billingAddress" => array(
    "street" => "Simon Carmiggeltstraat",
        "postalCode" => "1011DJ",
        "city" => "Amsterdam",
        "houseNumberOrName" => "6-60",
        "stateOrProvince" => "NH",
        "country" => "NL"
  ),
    "card" => array(
        "expiryMonth" => "08",
        "expiryYear" => "2018",
        "holderName" => "Test Card Holder",
        "number" => "4111111111111111",
        "cvc" => "737"
    ),
    "browserInfo"=>array(
        "acceptHeader"=>$_SERVER['HTTP_USER_AGENT'],
        "userAgent"=>$_SERVER['HTTP_ACCEPT']
    )
);

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, "https://pal-test.adyen.com/pal/servlet/Payment/v25/authorise");
 curl_setopt($ch, CURLOPT_HEADER, false);
 curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC  );
 curl_setopt($ch, CURLOPT_USERPWD, "YourWSUser:YourWSUserPassword");
 curl_setopt($ch, CURLOPT_POST,count(json_encode($request)));
 curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($request));
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HTTPHEADER,array("Content-type: application/json"));

 $result = curl_exec($ch);

 if($result === false)
    echo "Error: " . curl_error($ch);
 else{
    /**
     * If the payment passes validation a risk analysis will be done and, depending on the
     * outcome, an authorisation will be attempted. You receive a
     * payment response with the following fields:
     * - pspReference: The reference we assigned to the payment;
     * - resultCode: The result of the payment. One of Authorised, Refused or Error;
     * - authCode: An authorisation code if the payment was successful, or blank otherwise;
     * - refusalReason: If the payment was refused, the refusal reason.
     */

print_r(json_decode($result));
 }

 curl_close($ch);
?>

Has anyone faced this problem before? How may I fix this?
I've used almost any example in github, but there are just a few error which are documented, the rest....nothing..

Please help me on this. Thank you

Body:
Often this problem occurs when your user doesn't have permission to processes raw card details. Handling the raw card information requires full PCI compliance (SAQ D). If this is you, reach out to support@adyen.com to request that permission to be enabled on your account.

If not, you can use Adyen's CSE solution. Docs here. PHP example here.


来源: stackexchange

问:
How can I access a selected option's displayed value from a directive on the select element
My markup looks something like this

```<code><select ng-model="search.parameters.selectedOptionId" ng-options="lookup.id as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
    <option value="" selected>All</option>
</select>
</code>```

From the customAttributeDirective, I need to access the selected option value that is displayed in the dropdown (i.e. lookup.lookupValue). I've tried accessing the $viewValue on the ngModel, but it is set to the lookup.id (which I assume is the fault of the way ng-options is set up). I cannot modify the implementation of the markup due to the circumstances that I am implementing the directive against, so the problem must be solved there.

答:
Bind the lookup.lookupValue for display and lookup.lookupValue for backend Id too. In that case you will get display text with ng-model

```<code><select ng-model="search.parameters.selectedOptionId" ng-options="lookup.lookupValue as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
<option value="" selected>All</option>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My markup looks something like this

<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.id as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
    <option value="" selected>All</option>
</select>

From the customAttributeDirective, I need to access the selected option value that is displayed in the dropdown (i.e. lookup.lookupValue). I've tried accessing the $viewValue on the ngModel, but it is set to the lookup.id (which I assume is the fault of the way ng-options is set up). I cannot modify the implementation of the markup due to the circumstances that I am implementing the directive against, so the problem must be solved there.

Body:
Bind the lookup.lookupValue for display and lookup.lookupValue for backend Id too. In that case you will get display text with ng-model

<select ng-model="search.parameters.selectedOptionId" ng-options="lookup.lookupValue as lookup.lookupValue for lookup in lookups.options" custom-attribute-directive>
<option value="" selected>All</option>


问:
What happens to a running method if its object is deleted?
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

```<code>// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}
</code>```

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)

答:
Technically speaking, this is undefined behavior. What happens in practice, however, is that most compiler implementations will store method instructions in the same place in memory, regardless of whether the methods are static or not, just like static member variables for a class are stored in the same place in memory. This is because method logic does not vary from instance to instance. What is stored in different memory from instance to instance is non-static member variables.

Additionally, when compiled an implicit parameter is added to the functions, which is a pointer to an instance of the class. And this is how the compiled function gets access to the member variables, through the implicit "this" pointer.

Therefore, when you delete the object in the middle of executing the function, it will continue executing until it attempts to use a non-static member variable, which was stored in memory allocated specifically for that object, that was now deallocated. At this point it may continue executing if the memory has not been reclaimed, or if you're lucky the program will crash.

Body:
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)


问:
libgdx disable touch while action is ongoing
I cannot figure out, how to temporary disable the DragListener while there is an ongoing Action on the Actor. When I touch the Actor while there is an ongoing Action it gets interrupted and the new Action is executed, which leads to a "drift" of the Actor. e.g. I shake the Actor, but when it is interrupted, the following Action is based on the interrupted position of the Actor.

Adding Actions inside touchUp method:

```<code>RotateByAction rotL = new RotateByAction();
rotL.setAmount(-3);
rotL.setDuration(0.05f);

RotateByAction rotR = new RotateByAction();
rotR.setAmount(6);
rotR.setDuration(0.05f);

RotateByAction rotBack = new RotateByAction();
rotBack.setAmount(-3);
rotBack.setDuration(0.05f);

SequenceAction seq = new SequenceAction();
seq.addAction(rotL);
seq.addAction(rotR);
seq.addAction(rotBack);

temp.setOrigin(temp.getWidth()/2,temp.getHeight()/2);

temp.addAction(seq);
</code>```

I tried to do something like this inside the Render method of the Actor:

```<code>if (this.getActions().size > 0){//or hasActions()
            this.setTouchable(Touchable.disabled);
        }
        else{
            this.setTouchable(Touchable.enabled);
        }
</code>```

But that leaves the Actor untouchable!

答:
What you should do instead is use Actions.touchable to disable touch at the start of your action and then enable it again at the end. You can also string multiple actions together, using sequence or parallel.

```<code>temp.addAction(Actions.sequence(
    Actions.touchable(Touchable.disabled),
    rotL,
    rotR,
    rotBack,
    Actions.touchable(Touchable.enabled)
));
</code>```

Body:
I cannot figure out, how to temporary disable the DragListener while there is an ongoing Action on the Actor. When I touch the Actor while there is an ongoing Action it gets interrupted and the new Action is executed, which leads to a "drift" of the Actor. e.g. I shake the Actor, but when it is interrupted, the following Action is based on the interrupted position of the Actor.

Adding Actions inside touchUp method:

RotateByAction rotL = new RotateByAction();
rotL.setAmount(-3);
rotL.setDuration(0.05f);

RotateByAction rotR = new RotateByAction();
rotR.setAmount(6);
rotR.setDuration(0.05f);

RotateByAction rotBack = new RotateByAction();
rotBack.setAmount(-3);
rotBack.setDuration(0.05f);

SequenceAction seq = new SequenceAction();
seq.addAction(rotL);
seq.addAction(rotR);
seq.addAction(rotBack);

temp.setOrigin(temp.getWidth()/2,temp.getHeight()/2);

temp.addAction(seq);

I tried to do something like this inside the Render method of the Actor:

if (this.getActions().size > 0){//or hasActions()
            this.setTouchable(Touchable.disabled);
        }
        else{
            this.setTouchable(Touchable.enabled);
        }

But that leaves the Actor untouchable!

Body:
What you should do instead is use Actions.touchable to disable touch at the start of your action and then enable it again at the end. You can also string multiple actions together, using sequence or parallel.

temp.addAction(Actions.sequence(
    Actions.touchable(Touchable.disabled),
    rotL,
    rotR,
    rotBack,
    Actions.touchable(Touchable.enabled)
));


问:
Find, in a list, all arrays whose first element is the same as the ones that match a condition
This is a question that was very hard to title.

In C#, I have a set of int[,] arrays stored in a List<int[,]> paths, each holding a set of coordenates to form a path.
An example would be { {0,0}, {0,1}, {1,1}, {2,1} }.

Now, I want to keep in paths all paths that have the same first index as one of the first indexes of all paths that match a condition.

To better demonstrate what I mean, say I get all the paths that are of an odd length:

```<code>paths.Where(x => x.GetLength(0) % 2 == 1).ToList();
</code>```

Say this returns a list containing some arrays whose first coords are either {0,0} or {0,1}, for example. I want paths to be paths.Where( x=> x's first coords are either {0,0} or {0,1}). How can i achieve this?

Hopefully, what I mean is understandable.

答:
Like this:

```<code>var filteredPaths = paths.Where(x => x[0, 0] == 0 && x[0, 1] == 0  ||  x[0, 0] == 0 && x[0, 1] == 1);
</code>```

Or if you prefer to continue working with the same collection type:

```<code>List<int[,]> filteredPaths = paths.Where(x => x[0, 0] == 0 && x[1, 0] == 0  ||  x[0, 0] == 0 && x[1, 0] == 1).ToList();
</code>```

Body:
This is a question that was very hard to title.

In C#, I have a set of int[,] arrays stored in a List<int[,]> paths, each holding a set of coordenates to form a path.
An example would be { {0,0}, {0,1}, {1,1}, {2,1} }.

Now, I want to keep in paths all paths that have the same first index as one of the first indexes of all paths that match a condition.

To better demonstrate what I mean, say I get all the paths that are of an odd length:

paths.Where(x => x.GetLength(0) % 2 == 1).ToList();

Say this returns a list containing some arrays whose first coords are either {0,0} or {0,1}, for example. I want paths to be paths.Where( x=> x's first coords are either {0,0} or {0,1}). How can i achieve this?

Hopefully, what I mean is understandable.

Body:
Like this:

var filteredPaths = paths.Where(x => x[0, 0] == 0 && x[0, 1] == 0  ||  x[0, 0] == 0 && x[0, 1] == 1);

Or if you prefer to continue working with the same collection type:

List<int[,]> filteredPaths = paths.Where(x => x[0, 0] == 0 && x[1, 0] == 0  ||  x[0, 0] == 0 && x[1, 0] == 1).ToList();


问:
How to get file and read it from internet with Java?
I am trying to make a changelog that gets updated at runtime, now, I would like to download the changelog from my website, and then display it.
How would I do this?

By the way, I just want to read the file (something like when browsers ask you do you want to save or run this file?, not save it.

Thanks.

答:
You can open the input stream from the URI in Java as follows. Replace InputStreamReader with other implementations as per your need. Once you have the reader, you should be able to read the data from the stream.

```<code>InputStream stream = new URI('http://path-to-file').toURL().openStream();
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
String content = "";
while((content = r.readLine()) != null) {
System.out.println(content); // you can put custom logic here.
}
</code>```

Body:
You can open the input stream from the URI in Java as follows. Replace InputStreamReader with other implementations as per your need. Once you have the reader, you should be able to read the data from the stream.

InputStream stream = new URI('http://path-to-file').toURL().openStream();
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
String content = "";
while((content = r.readLine()) != null) {
System.out.println(content); // you can put custom logic here.
}


问:
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"?
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)?

Please explain the rationale, if possible.

I read somewhere that != operator is better than comparison operators. also pre-increment operator is better than post-increment operator, since it doesn't require any temporary variable to store the intermediate value.

Is there any better form of for loop than these two?

p.s: I use the former one as suggested by one of the sources, which i don't remember now.

答:
My teacher in the C++ language told me to use the canonical forms: for(int x=0; x != 5; ++i)

Thou the other works just fine but suppose you want to use the loop on a iterator. Then <= does not has to be properly defined and a postfix inc might make your program spend alot of time copying objects.

So he made us use the forms

for(int i=begin; x != end; ++i) and for(int i=begin; end != i--; )

ContentLicense: CC BY-SA 2.5


问:
Looping for specific values on a df
On one side I have a massive df:

```<code>df1

                A     B    C    ....
2005-11-01     5.3   22    6
2005-11-02     5.4   21    4
2005-11-03     5.2   17    7
   ....
</code>```

On the other hand I have a smaller df with the following structure;

```<code>df2

       date
A    2005-11-02
B    2005-11-01
C    2005-11-03
</code>```

What I am looking forward to is to add an additional column in df2 called price which loops over each index value and column value from df2 and look for the corresponding prices in df .

The desired output would be something like this:

```<code>       date        price
A    2005-11-02     5.4
B    2005-11-01      22
C    2005-11-03      7
</code>```

I tried :

```<code>prices=[]

for index,column in df2:
    prices.append(df.loc[column['date'][i],index.iloc[i]])
    i+=1
return prices
</code>```

However returns this undesired output.

```<code>ValueError: too many values to unpack (expected 2)
</code>```

Could anyone tell me how could I loop through df based on the index and column from df2

答:
lookup is the right way to do it. For reference, you were on the right track, but it would've been better to use iteritems, or zip the index and values:

```<code>df2['Values'] = [df.loc[j, i] for i, j in df2['date'].iteritems()]

df2

         date  Values
A  2005-11-02     5.4
B  2005-11-01    22.0
C  2005-11-03     7.0
</code>```

Title: Looping for specific values on a df

Body:
On one side I have a massive df:

df1

                A     B    C    ....
2005-11-01     5.3   22    6
2005-11-02     5.4   21    4
2005-11-03     5.2   17    7
   ....

On the other hand I have a smaller df with the following structure;

df2

       date
A    2005-11-02
B    2005-11-01
C    2005-11-03

What I am looking forward to is to add an additional column in df2 called price which loops over each index value and column value from df2 and look for the corresponding prices in df .

The desired output would be something like this:

       date        price
A    2005-11-02     5.4
B    2005-11-01      22
C    2005-11-03      7

I tried :

prices=[]

for index,column in df2:
    prices.append(df.loc[column['date'][i],index.iloc[i]])
    i+=1
return prices

However returns this undesired output.

ValueError: too many values to unpack (expected 2)

Could anyone tell me how could I loop through df based on the index and column from df2

Body:
lookup is the right way to do it. For reference, you were on the right track, but it would've been better to use iteritems, or zip the index and values:

df2['Values'] = [df.loc[j, i] for i, j in df2['date'].iteritems()]

df2

         date  Values
A  2005-11-02     5.4
B  2005-11-01    22.0
C  2005-11-03     7.0


答:
Here's one to go about it, assuming the List below is representing your multidimensional elements:

```<code>List<short[,]> paths = new List<short[,]>
                    {
                        new short[3, 2] { { 0, 0 }, { 4, 5 }, { 6, 7 } },
                        new short[3, 2] { { 0, 1 }, { 8, 9 }, { 10, 11 } },
                        new short[3, 2] { { 1, 1 }, { 1, 3 } ,{ 6, 1 } },
                        new short[3, 2] { { 2, 1 }, { 3, 5 }, { 7, 7 } }
                    };
</code>```

define the criteria i.e:

```<code>short[,] firstCriteria = new short[1, 2] { { 0, 0 } };
short[,] secondCriteria = new short[1, 2] { { 0, 1 } };
</code>```

define an extension method which should enable us to truncate the multidimensional array to only the first coordinates for filtering only.

```<code>static class Helper
{
        public static IEnumerable<short> SliceRow(this short[,] array, short row)
        {
            for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++)
            {
                yield return array[row, i];
            }
        }
 }
</code>```

then you can do:

```<code>var resutSet =
             paths.Where(e => e.SliceRow(0).SequenceEqual(firstCriteria.Cast<short>()) ||
                   e.SliceRow(0).SequenceEqual(secondCriteria.Cast<short>())).ToList();
</code>```

resultSet would now contain two multidimentional arrays that meet the given criteria i.e:

```<code>{ { 0, 0 }, { 4, 5 }, { 6, 7 } ,
  { 0, 1 }, { 8, 9 }, { 10, 11 } }
</code>```

Title: Find, in a list, all arrays whose first element is the same as the ones that match a condition

Body:
Here's one to go about it, assuming the List below is representing your multidimensional elements:

List<short[,]> paths = new List<short[,]>
                    {
                        new short[3, 2] { { 0, 0 }, { 4, 5 }, { 6, 7 } },
                        new short[3, 2] { { 0, 1 }, { 8, 9 }, { 10, 11 } },
                        new short[3, 2] { { 1, 1 }, { 1, 3 } ,{ 6, 1 } },
                        new short[3, 2] { { 2, 1 }, { 3, 5 }, { 7, 7 } }
                    };

define the criteria i.e:

short[,] firstCriteria = new short[1, 2] { { 0, 0 } };
short[,] secondCriteria = new short[1, 2] { { 0, 1 } };

define an extension method which should enable us to truncate the multidimensional array to only the first coordinates for filtering only.

static class Helper
{
        public static IEnumerable<short> SliceRow(this short[,] array, short row)
        {
            for (var i = array.GetLowerBound(1); i <= array.GetUpperBound(1); i++)
            {
                yield return array[row, i];
            }
        }
 }

then you can do:

var resutSet =
             paths.Where(e => e.SliceRow(0).SequenceEqual(firstCriteria.Cast<short>()) ||
                   e.SliceRow(0).SequenceEqual(secondCriteria.Cast<short>())).ToList();

resultSet would now contain two multidimentional arrays that meet the given criteria i.e:

{ { 0, 0 }, { 4, 5 }, { 6, 7 } ,
  { 0, 1 }, { 8, 9 }, { 10, 11 } }


问:
python flask with json
I am trying to get user's input and return the details as json.
But I get an error and I can't find why.
Hers is my python code:

```<code>from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')

@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    dictionaryToJson = json.dumps(pythonDictionary)
    return jsonify(dictionaryToJson)
</code>```

and my HTML file:

```<code><html>
   <body>

      <form action = "http://localhost:5000/result" method = "POST">
         <p>Book Name <input type = "text" name = "Book_Name" /></p>
         <p>Page <input type = "text" name = "Page" /></p>
         <p>Text <input type = "text" name = "Text" /></p>
         <p>Topic <input type ="text" name = "Topic" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>

   </body>
</html>
</code>```

How can I return the values properly?

答:
You are dumping the dict twice as jsonify also does json.dumps() (it also sets the correct response headers for you in addition which is why you should use it instead of json.dumps():

```<code>dictionaryToJson = json.dumps(pythonDictionary)
return jsonify(dictionaryToJson)
</code>```

Do this:

```<code>from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')

@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    return jsonify(pythonDictionary )
</code>```

Title: python flask with json

Body:
I am trying to get user's input and return the details as json.
But I get an error and I can't find why.
Hers is my python code:

from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')

@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    dictionaryToJson = json.dumps(pythonDictionary)
    return jsonify(dictionaryToJson)

and my HTML file:

      <form action = "http://localhost:5000/result" method = "POST">

Book Name <input type = "text" name = "Book_Name" />

Page <input type = "text" name = "Page" />

Text <input type = "text" name = "Text" />

Topic <input type ="text" name = "Topic" />

<input type = "submit" value = "submit" />

      </form>

How can I return the values properly?

Body:
You are dumping the dict twice as jsonify also does json.dumps() (it also sets the correct response headers for you in addition which is why you should use it instead of json.dumps():

dictionaryToJson = json.dumps(pythonDictionary)
return jsonify(dictionaryToJson)

Do this:

from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')

@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    return jsonify(pythonDictionary )


问:
Java Interface<?> is equivalent to Interface<any> in typescript
I'm trying "translate" some a java library to typescript.

```<code>public interface Expression<T> {
    <R,C> R accept(Visitor<R,C> v, @Nullable C context);
}
public interface Constant<T> extends Expression<T> {
    T getConstant();
}
public interface Visitor<R,C> {
    R visit(Constant<?> expr, @Nullable C context);
}
</code>```

Up to now, I've been able to code this code:

```<code>interface Expression<T> {
    accept<R, C>(visitor: Visitor<R, C>, context: C) : R;
}
interface Constant<T> extends Expression<T> {
    () : T;
}
public interface Visitor<R,C> {
    (expr: Constant<any>, context: C): R;   //<<<<?>>>>
}
</code>```

I'm not sure how to translate java Constant<?>. Up to now, I've translated it as Constant<any>.

Is this correct?

[EDIT]

What about Interface<? super T> and Interface<? extends T>?

答:
Because generic parameter for Constant, T, does not appear anywhere in the Visitor interface definition, I'd guess nothing is known and nothing is needed - no methods, no properties - from that type. In this case, empty object type {} will suffice - it's assignable from almost any other type.

```<code>interface Expression<T> {
    accept<R, C>(visitor: Visitor<R, C>, context: C) : R;
}
interface Constant<T> extends Expression<T> {
    () : T;
}
interface Visitor<R,C> {
  (expr: Constant<{}>, context: C): R;
}
</code>```

update

Similar to java, TypeScript supports generic type parameter constraints. It's hard to invent a realistic, but simple example where constraints are really necessary, so here is silly made up example:

```<code>interface Writer {
    write(data: string): void;
}

interface WriterProvider<W extends Writer> {
    getWriter(): W;
}

class C<W extends Writer> {

    writer: W;

    constructor(writerProvider: WriterProvider<W>) {
        this.writer = writerProvider.getWriter();
    }

    writeAll(): void {
        this.writer.write('a'); // here we can use its write() method
    }

    // supposedly something here should take advantage
    // of knowing exact W type, as opposed to Writer, at compile time
}
</code>```

However, unlike java, typescript does not have wildcard generic parameters - there is no equivalent for Interface<? super T> and Interface<? extends T>. There is no way to translate such code directly to TypeScript - you have to use TypeScript idioms and figure out what's the best way to express what you need on case by case basis.

Java generic FAQ says that wildcards are necessary in situations where no or only partial knowledge about the type argument of a parameterized type is required.

TypeScript has structural type system. It means that as soon as there is any knowledge about the properties or methods of a type, you can use it right away where this knowledge is sufficient. In practice, there is no need to declare to the compiler that concrete type you are passing as actual generic parameter conforms to some interface or constraint - it comes naturally with structural types and the compiler is able to figure it out by itself.

Body:
I'm trying "translate" some a java library to typescript.

public interface Expression<T> {
    <R,C> R accept(Visitor<R,C> v, @Nullable C context);
}
public interface Constant<T> extends Expression<T> {
    T getConstant();
}
public interface Visitor<R,C> {
    R visit(Constant<?> expr, @Nullable C context);
}

Up to now, I've been able to code this code:

interface Expression<T> {
    accept<R, C>(visitor: Visitor<R, C>, context: C) : R;
}
interface Constant<T> extends Expression<T> {
    () : T;
}
public interface Visitor<R,C> {
    (expr: Constant<any>, context: C): R;   //<<<<?>>>>
}

I'm not sure how to translate java Constant<?>. Up to now, I've translated it as Constant<any>.

Is this correct?

[EDIT]

What about Interface<? super T> and Interface<? extends T>?

Body:
Because generic parameter for Constant, T, does not appear anywhere in the Visitor interface definition, I'd guess nothing is known and nothing is needed - no methods, no properties - from that type. In this case, empty object type {} will suffice - it's assignable from almost any other type.

interface Expression<T> {
    accept<R, C>(visitor: Visitor<R, C>, context: C) : R;
}
interface Constant<T> extends Expression<T> {
    () : T;
}
interface Visitor<R,C> {
  (expr: Constant<{}>, context: C): R;
}

update

Similar to java, TypeScript supports generic type parameter constraints. It's hard to invent a realistic, but simple example where constraints are really necessary, so here is silly made up example:

interface Writer {
    write(data: string): void;
}

interface WriterProvider<W extends Writer> {
    getWriter(): W;
}

class C<W extends Writer> {

    writer: W;

    constructor(writerProvider: WriterProvider<W>) {
        this.writer = writerProvider.getWriter();
    }

    writeAll(): void {
        this.writer.write('a'); // here we can use its write() method
    }

    // supposedly something here should take advantage
    // of knowing exact W type, as opposed to Writer, at compile time
}

However, unlike java, typescript does not have wildcard generic parameters - there is no equivalent for Interface<? super T> and Interface<? extends T>. There is no way to translate such code directly to TypeScript - you have to use TypeScript idioms and figure out what's the best way to express what you need on case by case basis.

Java generic FAQ says that wildcards are necessary in situations where no or only partial knowledge about the type argument of a parameterized type is required.

TypeScript has structural type system. It means that as soon as there is any knowledge about the properties or methods of a type, you can use it right away where this knowledge is sufficient. In practice, there is no need to declare to the compiler that concrete type you are passing as actual generic parameter conforms to some interface or constraint - it comes naturally with structural types and the compiler is able to figure it out by itself.


问:
How to publish react component with style?
I want to publish a ui library using react. But I'm confuse about how to deal with styles.

For example, if I write code in a project.I will using webpack && babel to build my code, and it will create a *.css file.

```<code>import React from 'react';
import './index.less';

export default function() {
  return (
    <div>
      123
    </div>
  )
}
</code>```

But, if I just write react compoents, I will use babel to compile my code.There is not css-loader to deail with *.less file. And after compiling, there is requre('./index.less') in the code, but it can't find file. So if I still want to write my code like above, how can I to publish this comonents with *.css.

答:
Have you looked into available options there are around styling components in React? Because there are a lot of options here and it comes down to what you prefer. Just a quick google search will give you many options.

My personal favorite package to use is the styled-components one.

Body:
I want to publish a ui library using react. But I'm confuse about how to deal with styles.

For example, if I write code in a project.I will using webpack && babel to build my code, and it will create a *.css file.

import React from 'react';
import './index.less';

export default function() {
  return (

      123

  )
}

But, if I just write react compoents, I will use babel to compile my code.There is not css-loader to deail with *.less file. And after compiling, there is requre('./index.less') in the code, but it can't find file. So if I still want to write my code like above, how can I to publish this comonents with *.css.


问:
search for pattern in text using wildcards and automatically export the matches
I've been trying to use Thunderbird with expression search and ImportExportTools Add-on to look for a specific pattern in my emails, which worked to some degree at least. But now I'm unable to create a rule which would export the matches (and not any text before and after the pattern I searched for). I also tried using Libreoffice Calc but it's taking much longer to search and freezes doing so plus it also marks the whole line in which the pattern I searched for is found. I'd be really glad if anyone could help me out by suggesting a way to achieve my goal!</p>

答: Expresso by Ultrapico Editor regex search does the trick</p>


问:
AngularJS: Reload parent controller on state change
I have some nested states as such:

```<code>$stateProvider.state({
    name: 'parent',
    url: '/parent',
    abstract: true,
    template: '<ui-view/>'
})
.state({
    name: 'parent.child1',
    url: '/:id/child1',
    templateUrl: 'path/to/template'
})
.state({
    name: 'parent.child1.child2',
    url: '/child2',
    onEnter: function($state, $stateParams, $rootScope, $uibModal) {
        $uibModal.open({
            templateUrl: 'path/to/template',
            controller: 'Controller',
            controllerAs: 'vm',
            size: 'md',
            backdrop: 'static'
        }).result.then(function(result) {
            if (result) {
                return $state.transitionTo("parent.child");
            }
        });
    }
});
</code>```

The second child state is a modal that, when it's form submission completes, should dismiss the modal, transition back to the first child state, and reload the first child state. To do this, I am using:

```<code>function close() {
    $uibModalInstance.dismiss();
    $state.transitionTo('parent.child1', $stateParams, {reload: true});
}
</code>```

The modal closes properly, and the transition occurs, but the reload is not occurring. I have also tried using $state.go('parent.child1', $stateParams, {reload: true});, but the same thing occurs.

Does anyone know what I'm doing wrong? Thanks!

Update

I was able to achieve the desired results by un-nesting the second child (i.e, changing parent.child1.child2 to parent.child2).

Technically, this is fine for what I'm doing, but I'd still rather nest them if anyone has any thoughts.

答:
The reload property also accepts a string value so you can specify the parent state name explicitly e.g reload: 'parent'

Give that a try and see if it makes a difference

Body:
I have some nested states as such:

$stateProvider.state({
    name: 'parent',
    url: '/parent',
    abstract: true,
    template: '<ui-view/>'
})
.state({
    name: 'parent.child1',
    url: '/:id/child1',
    templateUrl: 'path/to/template'
})
.state({
    name: 'parent.child1.child2',
    url: '/child2',
    onEnter: function($state, $stateParams, $rootScope, $uibModal) {
        $uibModal.open({
            templateUrl: 'path/to/template',
            controller: 'Controller',
            controllerAs: 'vm',
            size: 'md',
            backdrop: 'static'
        }).result.then(function(result) {
            if (result) {
                return $state.transitionTo("parent.child");
            }
        });
    }
});

The second child state is a modal that, when it's form submission completes, should dismiss the modal, transition back to the first child state, and reload the first child state. To do this, I am using:

function close() {
    $uibModalInstance.dismiss();
    $state.transitionTo('parent.child1', $stateParams, {reload: true});
}

The modal closes properly, and the transition occurs, but the reload is not occurring. I have also tried using $state.go('parent.child1', $stateParams, {reload: true});, but the same thing occurs.

Does anyone know what I'm doing wrong? Thanks!

Update

I was able to achieve the desired results by un-nesting the second child (i.e, changing parent.child1.child2 to parent.child2).

Technically, this is fine for what I'm doing, but I'd still rather nest them if anyone has any thoughts.


问:
returning a pointer that points to char array. How do i print out the entire contents of the array?
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

```<code>#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //
</code>```

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.

答: You are returning a char instead of a char*. A char is always just a single character. If you want to get a string back return a string or a char*.</p>

Body:
This program reverses a given string but i can't seem to figure out how to return the entire buffer, all answers welcome.

#include <iostream>
#include <string.h>
using namespace std;

char  ReverseString(char *input);

int main()
{
    string str;
    cout << "Please Enter a String: ";
    getline(cin,str);
    cout << "The string you entered is: " << str << endl;
    str = ReverseString(&str[0]);
    cout << str;
}

char  ReverseString(char* input)
{
    int size = strlen(input);
    char *it;
    char *revBuffer = new char[size];
    it = revBuffer;
    for(int i=0; i<size; i++)
    {
       *it = input[(size-1)-i];
       it++;
    }
    return *revBuffer; //

I can't seem to figure out how to return the entire buffer instead of just one element the pointer is pointing to.


问:
R: Applying a function to every entry in dataframe
I want to make every element in the dataframe (except fot the ID column) become a 0 if it is any number other than 1.

I have:

```<code>ID  A B C D E
abc 5 3 1 4 1
def 4 1 3 2 5
</code>```

I want:

```<code>ID  A B C D E
abc 0 0 1 0 1
def 0 1 0 0 0
</code>```

I am having trouble figuring out how to specify for this to be done to do to every entry in every column and row.

Here is my code:

```<code>apply(dat.lec, 2 , function(y)
  if(!is.na(y)){
      if(y==1){y <- 1}
      else{y <-0}
     }
  else {y<- NA}
)
</code>```

Thank you for your help!

答:
No need for implicit or explicit looping.</p>

```<code># Sample data
set.seed(2016);
df <- as.data.frame(matrix(sample(10, replace = TRUE), nrow = 2));
df <- cbind.data.frame(id = sample(letters, 2), df);
df;
#  id V1 V2 V3 V4 V5
#1  k  2  9  5  7  1
#2  g  2  2  2  9  1

# Replace all entries != 1 with 0's
df[, -1][df[, -1] != 1] <- 0;
df;
#  id V1 V2 V3 V4 V5
#1  k  0  0  0  0  1
#2  g  0  0  0  0  1
</code>```

Body:
I want to make every element in the dataframe (except fot the ID column) become a 0 if it is any number other than 1.

I have:

ID  A B C D E
abc 5 3 1 4 1
def 4 1 3 2 5

I want:

ID  A B C D E
abc 0 0 1 0 1
def 0 1 0 0 0

I am having trouble figuring out how to specify for this to be done to do to every entry in every column and row.

Here is my code:

apply(dat.lec, 2 , function(y)
  if(!is.na(y)){
      if(y==1){y <- 1}
      else{y <-0}
     }
  else {y<- NA}
)

Thank you for your help!

Body:
No need for implicit or explicit looping.

# Sample data
set.seed(2016);
df <- as.data.frame(matrix(sample(10, replace = TRUE), nrow = 2));
df <- cbind.data.frame(id = sample(letters, 2), df);
df;
#  id V1 V2 V3 V4 V5
#1  k  2  9  5  7  1
#2  g  2  2  2  9  1

# Replace all entries != 1 with 0's
df[, -1][df[, -1] != 1] <- 0;
df;
#  id V1 V2 V3 V4 V5
#1  k  0  0  0  0  1
#2  g  0  0  0  0  1


问:
I Can't re-write Java's solution to C# in Selenium
I have some problems with modified FireFox browser on C#.
When the Browser opens and I get an error:

TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"

I think, it's because of browser's name "anotherbrowser" instead of "firefox" in it's binary code.

So I found the solution on Java:

```<code>FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", "anotherbrowser");
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
</code>```

I tested it, and its work fine. But I need on C#, so I tried to rewrite it:

```<code>DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", @"Path to browser binary");
IWebDriver driver = new FirefoxDriver(cap); //here's error
</code>```

But I got an error:

There is already an option for the browserName capability. Please use
  the  instead.

Please, help me to re-write Java solution to C#. I got troubles, because there isn't same method in C#, like in Java: "options.setCapability(" "," ");"

P.s. I can't use original Firefox browser, because it doesn't have same advantages as my modified Firefox.

答:
Who's interested, I found a solution:</p>

```<code>FirefoxOptions options = new FirefoxOptions();
options.UseLegacyImplementation = true;
options.BrowserExecutableLocation = @"Path to Browser";
options.AddAdditionalCapability("browser", "anotherbrowser");
IWebDriver driver = new FirefoxDriver(options);
</code>```

Body:
I have some problems with modified FireFox browser on C#.
When the Browser opens and I get an error:

TypeError: Given browserName [object String] "firefox", but my name is [object String] "anotherbrowser"

I think, it's because of browser's name "anotherbrowser" instead of "firefox" in it's binary code.

So I found the solution on Java:

FirefoxOptions options = new FirefoxOptions();
options.setBinary("Path to browser binary");
options.setCapability("browserName", "anotherbrowser");
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);

I tested it, and its work fine. But I need on C#, so I tried to rewrite it:

DesiredCapabilities cap = DesiredCapabilities.Firefox();
cap.SetCapability("browserName", "anotherbrowser");
cap.SetCapability("firefox_binary", @"Path to browser binary");
IWebDriver driver = new FirefoxDriver(cap); //here's error

But I got an error:

There is already an option for the browserName capability. Please use
  the  instead.

Please, help me to re-write Java solution to C#. I got troubles, because there isn't same method in C#, like in Java: "options.setCapability(" "," ");"

P.s. I can't use original Firefox browser, because it doesn't have same advantages as my modified Firefox.

Body:
Who's interested, I found a solution:

FirefoxOptions options = new FirefoxOptions();
options.UseLegacyImplementation = true;
options.BrowserExecutableLocation = @"Path to Browser";
options.AddAdditionalCapability("browser", "anotherbrowser");
IWebDriver driver = new FirefoxDriver(options);


问:
jQuery and Chrome... Need another set of eyeballs on this please
This is weird but I have some autocomplete code that I've customized to only engage when you type the '@' sign... In FireFox it works great. I type one '@' and the dropdown appears.

BUT... when I try it in Chrome, it requires two '@@' to engage the dropdown.

What could this be?

Another strange behavior is that when ad an alert statment, it then actually works when I type one '@' in Chrome... Any ideas on how to fix this? Thanks!

Here's the onChange function where I am replacing the @ sign with blank "" so it doesn't show or submit the @ when an item is selected from the dropdown

You can see the @ ascii value is set here as 50 (ATSIGN variable)

```<code>    var KEY = {
    UP: 38,
    DOWN: 40,
    DEL: 46,
    TAB: 9,
    RETURN: 13,
    ESC: 27,
    COMMA: 188,
    PAGEUP: 33,
    PAGEDOWN: 34,
    BACKSPACE: 8,
    ATSIGN: 50
};
</code>```

Here is a bit of code right before the switch statement

```<code>    // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
    // a keypress means the input has focus
    // avoids issue where input had focus before the autocomplete was applied
    hasFocus = 1;
    // track last key pressed
    lastKeyPressCode = event.keyCode;
</code>```

Then in the switch statement, the autocomplete gets activated only when the @ sign is pressed:

```<code>        switch(event.keyCode) {

        case KEY.UP:
            event.preventDefault();
            if ( select.visible() ) {
                select.prev();
            } else {
                onChange(0, true);
            }
            break;

        case KEY.DOWN:
            event.preventDefault();
            if ( select.visible() ) {
                select.next();
            } else {
                onChange(0, true);
            }
            break;

        case KEY.PAGEUP:
            event.preventDefault();
            if ( select.visible() ) {
                select.pageUp();
            } else {
                onChange(0, true);
            }
            break;

        case KEY.PAGEDOWN:
            event.preventDefault();
            if ( select.visible() ) {
                select.pageDown();
            } else {
                onChange(0, true);
            }
            break;

        // matches also semicolon
        case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
        case KEY.TAB:
        case KEY.RETURN:
            if( selectCurrent() ) {
                // stop default to prevent a form submit, Opera needs special handling
                event.preventDefault();
                blockSubmit = true;
                return false;
            }
            break;

        case KEY.ESC:
            select.hide();
            break;
        case KEY.ATSIGN:
            clearTimeout(timeout);
            timeout = setTimeout(onChange, options.delay);
            //alert("hi");
            //select.show();
            break;
        default:

            break;
    }
</code>```

And here is the function onChange that gets called in the case statement after @ is pressed

```<code>    function onChange(crap, skipPrevCheck) {
    if( lastKeyPressCode == KEY.DEL ) {
        select.hide();
        return;
    }

    var currentValue = $input.val();

    if ( !skipPrevCheck && currentValue == previousValue )
        return;

    previousValue = currentValue;
    //alert(previousValue);
    currentValue = lastWord(currentValue);
    if ( currentValue.length >= options.minChars) {
        $input.addClass(options.loadingClass);
        if (!options.matchCase)
            currentValue = currentValue.toLowerCase();
            currentValue = currentValue.replace("@","");
            //alert(currentValue);
            request(currentValue, receiveData, hideResultsNow);

    } else {
        stopLoading();
        select.hide();
    }
};
</code>```

As I mentioned, this works great in FF... I press @ once and the autocomplete activates... However in Chrome, I must press @@ (at sign twice)....

Any help is greatly appreciated.

答:
I figured this out... I need to create a new delay variable and make the autocomplete dropdown happen a split second later than the standard time which was 400 ms

So I added the variable delayLong and set it to 500 ms and it works perfectly in Chrome now. Go figure.

Body:
This is weird but I have some autocomplete code that I've customized to only engage when you type the '@' sign... In FireFox it works great. I type one '@' and the dropdown appears.

BUT... when I try it in Chrome, it requires two '@@' to engage the dropdown.

What could this be?

Another strange behavior is that when ad an alert statment, it then actually works when I type one '@' in Chrome... Any ideas on how to fix this? Thanks!

Here's the onChange function where I am replacing the @ sign with blank "" so it doesn't show or submit the @ when an item is selected from the dropdown

You can see the @ ascii value is set here as 50 (ATSIGN variable)

    var KEY = {
    UP: 38,
    DOWN: 40,
    DEL: 46,
    TAB: 9,
    RETURN: 13,
    ESC: 27,
    COMMA: 188,
    PAGEUP: 33,
    PAGEDOWN: 34,
    BACKSPACE: 8,
    ATSIGN: 50
};

Here is a bit of code right before the switch statement

    // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
    // a keypress means the input has focus
    // avoids issue where input had focus before the autocomplete was applied
    hasFocus = 1;
    // track last key pressed
    lastKeyPressCode = event.keyCode;

Then in the switch statement, the autocomplete gets activated only when the @ sign is pressed:

        switch(event.keyCode) {

        case KEY.UP:
            event.preventDefault();
            if ( select.visible() ) {
                select.prev();
            } else {
                onChange(0, true);
            }
            break;

        case KEY.DOWN:
            event.preventDefault();
            if ( select.visible() ) {
                select.next();
            } else {
                onChange(0, true);
            }
            break;

        case KEY.PAGEUP:
            event.preventDefault();
            if ( select.visible() ) {
                select.pageUp();
            } else {
                onChange(0, true);
            }
            break;

        case KEY.PAGEDOWN:
            event.preventDefault();
            if ( select.visible() ) {
                select.pageDown();
            } else {
                onChange(0, true);
            }
            break;

        // matches also semicolon
        case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
        case KEY.TAB:
        case KEY.RETURN:
            if( selectCurrent() ) {
                // stop default to prevent a form submit, Opera needs special handling
                event.preventDefault();
                blockSubmit = true;
                return false;
            }
            break;

        case KEY.ESC:
            select.hide();
            break;
        case KEY.ATSIGN:
            clearTimeout(timeout);
            timeout = setTimeout(onChange, options.delay);
            //alert("hi");
            //select.show();
            break;
        default:

            break;
    }

And here is the function onChange that gets called in the case statement after @ is pressed

    function onChange(crap, skipPrevCheck) {
    if( lastKeyPressCode == KEY.DEL ) {
        select.hide();
        return;
    }

    var currentValue = $input.val();

    if ( !skipPrevCheck && currentValue == previousValue )
        return;

    previousValue = currentValue;
    //alert(previousValue);
    currentValue = lastWord(currentValue);
    if ( currentValue.length >= options.minChars) {
        $input.addClass(options.loadingClass);
        if (!options.matchCase)
            currentValue = currentValue.toLowerCase();
            currentValue = currentValue.replace("@","");
            //alert(currentValue);
            request(currentValue, receiveData, hideResultsNow);

    } else {
        stopLoading();
        select.hide();
    }
};

As I mentioned, this works great in FF... I press @ once and the autocomplete activates... However in Chrome, I must press @@ (at sign twice)....

Any help is greatly appreciated.


问:
cant populate selector, Cannot read property 'name' of undefined,
Im trying to get some fields from BE to map over in to my FE class.
I then want the name on the fields to populate a selector and its options.

Here is the service

```<code>export class FieldsService {

  constructor(private _http: Http) { }

  public getFields(): Observable<Response> {
    return this._http.get('/api/fields');
  }
}
</code>```

Field.class

```<code>export class Field {
    public name: string;
    public id: string;
}
</code>```

Component.js

```<code>export class Component implements OnInit {

  public _fields: Field;

  constructor(private _fieldsService: FieldsService) { }

  ngOnInit() {
    this._fieldsService.getFields()
    .map(response => response.json())
    .subscribe(result => this._fields = result);
  }
}
</code>```

and last but not leaste, Component.html:

```<code>```{{_fields | json}}```
        <div class="form-group" *ngIf="_fields !== undefiend">
          <label for="exampleFormControlSelect1">Fields</label>
          <select class="form-control" id="exampleFormControlSelect1" ng-repeat="let field in _fields">
            <option>{{field.name}}</option>
          </select>
        </div>
</code>```

Im guessing that Im doing something wrong with the mapping.
Been reading tutorials but cant see what im doing wrong.

Br

答:
Let's try replacing your ng-repeat directive with *ngFor directive.

```<code>```{{_fields | json}}```
<div class="form-group" *ngIf="_fields !== undefiend">
   <label for="exampleFormControlSelect1">Fields</label>
   <select class="form-control" id="exampleFormControlSelect1" *ngFor="let field of _fields">
       <option>{{field.name}}</option>
   </select>
</div>
</code>```

I guess you could use .subscribe() method without mapping datas.

You noticed I used "let field of _fields" instead of "in", because in watches for indexes whereas of watches values.

Body:
Im trying to get some fields from BE to map over in to my FE class.
I then want the name on the fields to populate a selector and its options.

Here is the service

export class FieldsService {

  constructor(private _http: Http) { }

  public getFields(): Observable<Response> {
    return this._http.get('/api/fields');
  }
}

Field.class

export class Field {
    public name: string;
    public id: string;
}

Component.js

export class Component implements OnInit {

  public _fields: Field;

  constructor(private _fieldsService: FieldsService) { }

  ngOnInit() {
    this._fieldsService.getFields()
    .map(response => response.json())
    .subscribe(result => this._fields = result);
  }
}

and last but not leaste, Component.html:

{{_fields | json}}

          Fields
          <select class="form-control" id="exampleFormControlSelect1" ng-repeat="let field in _fields">
            <option>{{field.name}}</option>
          </select>

Im guessing that Im doing something wrong with the mapping.
Been reading tutorials but cant see what im doing wrong.

Br

Body:
Let's try replacing your ng-repeat directive with *ngFor directive.

<pre>{{_fields | json}}</pre>
<div class="form-group" *ngIf="_fields !== undefiend">
   <label for="exampleFormControlSelect1">Fields</label>
   <select class="form-control" id="exampleFormControlSelect1" *ngFor="let field of _fields">
       <option>{{field.name}}</option>
   </select>
</div>

I guess you could use .subscribe() method without mapping datas.

You noticed I used "let field of _fields" instead of "in", because in watches for indexes whereas of watches values.


问:
Python XML findall does not work
I am trying to use findall to select on some xml elements, but i can't get any results.

```<code>import xml.etree.ElementTree as ET
import sys

storefront = sys.argv[1]

xmlFileName = 'promotions{0}.xml'

xmlFile = xmlFileName.format(storefront)

csvFileName = 'hrz{0}.csv'
csvFile = csvFileName.format(storefront)
ET.register_namespace('', "http://www.demandware.com/xml/impex/promotion/2008-01-31")
tree = ET.parse(xmlFile)

root = tree.getroot()
print('------------------Generate test-------------\n')

csv = open(csvFile,'w')
n = 0
for child in root.findall('campaign'):
    print(child.attrib['campaign-id'])
    print(n)
    n+=1
</code>```

The XML looks something like this:

```<code>  <?xml version="1.0" encoding="UTF-8"?>
<promotions xmlns="http://www.demandware.com/xml/impex/promotion/2008-01-31">
    <campaign campaign-id="10off-310781">
        <enabled-flag>true</enabled-flag>
        <campaign-scope>
            <applicable-online/>
        </campaign-scope>
        <customer-groups match-mode="any">
            <customer-group group-id="Everyone"/>
        </customer-groups>
    </campaign>

    <campaign campaign-id="MNT-deals">
        <enabled-flag>true</enabled-flag>
        <campaign-scope>
            <applicable-online/>
        </campaign-scope>
        <start-date>2017-07-03T22:00:00.000Z</start-date>
        <end-date>2017-07-31T22:00:00.000Z</end-date>
        <customer-groups match-mode="any">
            <customer-group group-id="Everyone"/>
        </customer-groups>
    </campaign>

    <campaign campaign-id="black-friday">
        <enabled-flag>true</enabled-flag>
        <campaign-scope>
            <applicable-online/>
        </campaign-scope>
        <start-date>2017-11-23T23:00:00.000Z</start-date>
        <end-date>2017-11-24T23:00:00.000Z</end-date>
        <customer-groups match-mode="any">
            <customer-group group-id="Everyone"/>
        </customer-groups>
        <custom-attributes>
            <custom-attribute attribute-id="expires_date">2017-11-29</custom-attribute>
        </custom-attributes>
    </campaign>

    <promotion-campaign-assignment promotion-id="winter17-new-bubble" campaign-id="winter17-new-bubble">
        <qualifiers match-mode="any">
            <customer-groups/>
            <source-codes/>
            <coupons/>
        </qualifiers>
        <rank>100</rank>
    </promotion-campaign-assignment>

    <promotion-campaign-assignment promotion-id="xmas" campaign-id="xmas">
        <qualifiers match-mode="any">
            <customer-groups/>
            <source-codes/>
            <coupons/>
        </qualifiers>
    </promotion-campaign-assignment>

</promotions>
</code>```

Any ideas what i am doing wrong?
 I have tried different solutions that i found on stackoverflow but nothing seems to work for me(from the things i have tried).
 The list is empty.
 Sorry if it is something very obvious i am new to python.

答:
As mentioned here by @MartijnPieters, etree's .findall uses the namespaces argument while the .register_namespace() is used for xml output of the tree. Therefore, consider mapping the default namespace with an explicit prefix. Below uses doc but can even be cosmin.

Additionally, consider with and enumerate() even the csv  module as better handlers for your print and CSV outputs.

```<code>import csv
...

root = tree.getroot()
print('------------------Generate test-------------\n')

with open(csvFile, 'w') as f:
    c = csv.writer(f, lineterminator='\n')

    for n, child in enumerate(root.findall('doc:campaign', namespaces={'doc':'http://www.demandware.com/xml/impex/promotion/2008-01-31'})):
        print(child.attrib['campaign-id'])
        print(n)
        c.writerow([child.attrib['campaign-id']])

# ------------------Generate test-------------

# 10off-310781
# 0
# MNT-deals
# 1
# black-friday
# 2
</code>```

Title: Python XML findall does not work

Body:
I am trying to use findall to select on some xml elements, but i can't get any results.

import xml.etree.ElementTree as ET
import sys

storefront = sys.argv[1]

xmlFileName = 'promotions{0}.xml'

xmlFile = xmlFileName.format(storefront)

csvFileName = 'hrz{0}.csv'
csvFile = csvFileName.format(storefront)
ET.register_namespace('', "http://www.demandware.com/xml/impex/promotion/2008-01-31")
tree = ET.parse(xmlFile)

root = tree.getroot()
print('------------------Generate test-------------\n')

csv = open(csvFile,'w')
n = 0
for child in root.findall('campaign'):
    print(child.attrib['campaign-id'])
    print(n)
    n+=1

The XML looks something like this:

  <?xml version="1.0" encoding="UTF-8"?>
<promotions xmlns="http://www.demandware.com/xml/impex/promotion/2008-01-31">
    <campaign campaign-id="10off-310781">
        <enabled-flag>true</enabled-flag>
        <campaign-scope>
            <applicable-online/>
        </campaign-scope>
        <customer-groups match-mode="any">
            <customer-group group-id="Everyone"/>
        </customer-groups>
    </campaign>

    <campaign campaign-id="MNT-deals">
        <enabled-flag>true</enabled-flag>
        <campaign-scope>
            <applicable-online/>
        </campaign-scope>
        <start-date>2017-07-03T22:00:00.000Z</start-date>
        <end-date>2017-07-31T22:00:00.000Z</end-date>
        <customer-groups match-mode="any">
            <customer-group group-id="Everyone"/>
        </customer-groups>
    </campaign>

    <campaign campaign-id="black-friday">
        <enabled-flag>true</enabled-flag>
        <campaign-scope>
            <applicable-online/>
        </campaign-scope>
        <start-date>2017-11-23T23:00:00.000Z</start-date>
        <end-date>2017-11-24T23:00:00.000Z</end-date>
        <customer-groups match-mode="any">
            <customer-group group-id="Everyone"/>
        </customer-groups>
        <custom-attributes>
            <custom-attribute attribute-id="expires_date">2017-11-29</custom-attribute>
        </custom-attributes>
    </campaign>

    <promotion-campaign-assignment promotion-id="winter17-new-bubble" campaign-id="winter17-new-bubble">
        <qualifiers match-mode="any">
            <customer-groups/>
            <source-codes/>
            <coupons/>
        </qualifiers>
        <rank>100</rank>
    </promotion-campaign-assignment>

    <promotion-campaign-assignment promotion-id="xmas" campaign-id="xmas">
        <qualifiers match-mode="any">
            <customer-groups/>
            <source-codes/>
            <coupons/>
        </qualifiers>
    </promotion-campaign-assignment>

</promotions>

Any ideas what i am doing wrong?
 I have tried different solutions that i found on stackoverflow but nothing seems to work for me(from the things i have tried).
 The list is empty.
 Sorry if it is something very obvious i am new to python.

Body:
As mentioned here by @MartijnPieters, etree's .findall uses the namespaces argument while the .register_namespace() is used for xml output of the tree. Therefore, consider mapping the default namespace with an explicit prefix. Below uses doc but can even be cosmin.

Additionally, consider with and enumerate() even the csv  module as better handlers for your print and CSV outputs.

import csv
...

root = tree.getroot()
print('------------------Generate test-------------\n')

with open(csvFile, 'w') as f:
    c = csv.writer(f, lineterminator='\n')

    for n, child in enumerate(root.findall('doc:campaign', namespaces={'doc':'http://www.demandware.com/xml/impex/promotion/2008-01-31'})):
        print(child.attrib['campaign-id'])
        print(n)
        c.writerow([child.attrib['campaign-id']])

# ------------------Generate test-------------

# 10off-310781
# 0
# MNT-deals
# 1
# black-friday
# 2


问:
Counting records in a SQL subquery
I'm having difficult with a subquery. In plain English I'm trying to pick a random userID from the QCUsers table that has less than 20 records from the QCTier1_Assignments table.  The problem is that my query below is only picking users where it meets the criteria of the inner query when I need it to pick any user from QCUsers table even if the user does not have any records at all in the QCTier1_Assignments table. I need something like this

AND (Sub.QCCount < 20 OR Sub.QCCount = 0 )

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
JOIN (SELECT
  QCA.UserID,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
  AND QCA.ReviewPeriodYear = @ReviewPeriodYear
  GROUP BY QCA.UserID
  ) Sub
 ON E1.UserID = Sub.UserID
 WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
 ORDER BY NEWID()
</code>```

I also tried it this way with no luck

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
RIGHT JOIN (SELECT
  QCA.UserID,
  ReviewPeriodMonth,
  ReviewPeriodYear,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  GROUP BY
    QCA.UserID,
    ReviewPeriodMonth,
    ReviewPeriodYear
  ) Sub
ON E1.UserID = Sub.UserID
WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
  AND Sub.ReviewPeriodMonth = @ReviewPeriodMonth
  AND Sub.ReviewPeriodYear = @ReviewPeriodYear
ORDER BY NEWID()
</code>```

答:
I was able to work it out through a combination of responses here</p>

```<code>DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
  QCUsers.UserID,
  COUNT(QCTier1_Assignments.ReviewID) AS ReviewCount
FROM
QCTier1_Assignments RIGHT OUTER JOIN
QCUsers ON QCTier1_Assignments.UserID = QCUsers.UserID
WHERE
QCUsers.Active = 1
AND QCUsers.Grade = '12'
AND (ReviewPeriodMonth = @ReviewPeriodMonth OR ReviewPeriodMonth IS NULL)
AND (ReviewPeriodYear = @ReviewPeriodYear OR ReviewPeriodYear IS NULL)
GROUP BY
QCUsers.UserID
HAVING
(COALESCE(COUNT(QCTier1_Assignments.ReviewID),0) < 4)
ORDER BY NEWID()
</code>```

Title: Counting records in a SQL subquery

Body:
I'm having difficult with a subquery. In plain English I'm trying to pick a random userID from the QCUsers table that has less than 20 records from the QCTier1_Assignments table.  The problem is that my query below is only picking users where it meets the criteria of the inner query when I need it to pick any user from QCUsers table even if the user does not have any records at all in the QCTier1_Assignments table. I need something like this

AND (Sub.QCCount < 20 OR Sub.QCCount = 0 )

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
JOIN (SELECT
  QCA.UserID,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  WHERE QCA.ReviewPeriodMonth = @ReviewPeriodMonth
  AND QCA.ReviewPeriodYear = @ReviewPeriodYear
  GROUP BY QCA.UserID
  ) Sub
 ON E1.UserID = Sub.UserID
 WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
 ORDER BY NEWID()

I also tried it this way with no luck

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
E1.UserID
,Sub.QCCount --Drawn from the subquery
FROM QCUsers E1
RIGHT JOIN (SELECT
  QCA.UserID,
  ReviewPeriodMonth,
  ReviewPeriodYear,
  COUNT(*) AS QCCount
  FROM QCTier1_Assignments QCA
  GROUP BY
    QCA.UserID,
    ReviewPeriodMonth,
    ReviewPeriodYear
  ) Sub
ON E1.UserID = Sub.UserID
WHERE Active = 1
  AND Grade = 12
  AND Sub.QCCount < 20
  AND Sub.ReviewPeriodMonth = @ReviewPeriodMonth
  AND Sub.ReviewPeriodYear = @ReviewPeriodYear
ORDER BY NEWID()

Body:
I was able to work it out through a combination of responses here

DECLARE @ReviewPeriodMonth varchar(10) = '10'
DECLARE @ReviewPeriodYear varchar(10) = '2015'

SELECT TOP 1
  QCUsers.UserID,
  COUNT(QCTier1_Assignments.ReviewID) AS ReviewCount
FROM
QCTier1_Assignments RIGHT OUTER JOIN
QCUsers ON QCTier1_Assignments.UserID = QCUsers.UserID
WHERE
QCUsers.Active = 1
AND QCUsers.Grade = '12'
AND (ReviewPeriodMonth = @ReviewPeriodMonth OR ReviewPeriodMonth IS NULL)
AND (ReviewPeriodYear = @ReviewPeriodYear OR ReviewPeriodYear IS NULL)
GROUP BY
QCUsers.UserID
HAVING
(COALESCE(COUNT(QCTier1_Assignments.ReviewID),0) < 4)
ORDER BY NEWID()


问:
I need help getting my code to look like this:
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.

Here is my code currently:

```<code>// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.

public class Assignment_6_1
{
    // recursive method factorial (assumes its parameter is >= 0
    static StringBuilder s = new StringBuilder();

    public static long factorial(long number)
{
        if (number == 0) // test for base case
        {
            return 1;
        } else {// recursion step
            if (s.length() == 0) {
                s.append(number).append("*").append(number - 1);
            } else {
                for (int i = 0; i < s.length(); i++) {

                }
                System.out.println(number + " * " + (number - 1) + "!");
                s.append("*").append(number).append("*").append(number - 1);
            }
            return number * factorial(number - 1);
        }
    }

    // output factorials for values 0-21
    public static void main(String[] args) {
        System.out.println("Hannah Coffey - Lab 6");
        // calculate the factorials of 0 through 20
        for (int counter = 0; counter < 25; counter++) {
            s = new StringBuilder();
            System.out.println(counter + "!");
            System.out.printf("%d! = %d%n", counter, factorial(counter));
        }
    }
} // end class FactorialCalculator
</code>```

Here is what I need it to look like and not sure what I am doing wrong:

Any Help would be greatly appreciated.

My program currently looks like this:
enter image description here

答:
```<code> public static long factorial(long number){
         if (number == 0) // test for base case
         {
             return 1;
         } else {// recursion step
             if (s.length() == 0) {
                 s.append(number).append("*").append(number - 1);
             } else {
                 String spaces = "";
                 for (int i = 0; i < number; i++) {
                     spaces = spaces+" ";
                 }
                 if(number==1)
                    System.out.println(" Base Case: 1");
                 else {
                    System.out.println(spaces + "Recursive call:" + number + " * fact(" + (number - 1) + ")");
                    s.append("*").append(number).append("*").append(number - 1);
                 }
             }
        return number * factorial(number - 1);
         }
     }

public static void main(String[] args) {
    System.out.println("Hannah Coffey - Lab 6");
    // calculate the factorials of 0 through 20
    for (int counter = 0; counter < 25; counter++) {
        s = new StringBuilder();
        for (int i = 0; i < counter; i++) {
            spaces = spaces+" ";
        }
        System.out.println(spaces+"Recursive call:"+counter + "!");
        System.out.printf("%d! = %d%n", counter, factorial(counter));
    }
}
</code>```

Body:
I need help getting my code output to look like the image below and I am not sure what I am doing wrong and I need to have my code output indented and cant remember how to indent it.

Here is my code currently:

// Fig. 18.3: FactorialCalculator.java
// Recursive factorial method.

public class Assignment_6_1
{
    // recursive method factorial (assumes its parameter is >= 0
    static StringBuilder s = new StringBuilder();

    public static long factorial(long number)
{
        if (number == 0) // test for base case
        {
            return 1;
        } else {// recursion step
            if (s.length() == 0) {
                s.append(number).append("*").append(number - 1);
            } else {
                for (int i = 0; i < s.length(); i++) {

                }
                System.out.println(number + " * " + (number - 1) + "!");
                s.append("*").append(number).append("*").append(number - 1);
            }
            return number * factorial(number - 1);
        }
    }

    // output factorials for values 0-21
    public static void main(String[] args) {
        System.out.println("Hannah Coffey - Lab 6");
        // calculate the factorials of 0 through 20
        for (int counter = 0; counter < 25; counter++) {
            s = new StringBuilder();
            System.out.println(counter + "!");
            System.out.printf("%d! = %d%n", counter, factorial(counter));
        }
    }
} // end class FactorialCalculator

Here is what I need it to look like and not sure what I am doing wrong:

Any Help would be greatly appreciated.

My program currently looks like this:
enter image description here


问:
Defining custom unmarshalling for non-built in types
Most of us know that a JSON object can be unmarshaled with JSON tags:

```<code>var jsonData = `{"name": "Brown Bear"}`

type Elephant struct {
    Name string `json:"name"`
}
</code>```

This is because string is a built in types. But what if Name were not a built in type, and we wanted to use this type across different structs?

```<code>var jsonData = `{"name": "Brown Bear"}`

type Elephant struct {
    Name Name   `json:"name"`  // Unmarshalling fails here
}

type Feline struct {
    Name Name   `json:"name"`  // Unmarshalling fails here
}

type Bear struct {
    Name Name   `json:"name"`  // Unmarshalling fails here
}

type Name struct {
    CommonName     string
    ScientificName string  // This field should intentionally be blank
}
</code>```

Is there a way we can define the Name type so that the json unmarshaller knows how to unmarshal it?

PS: The solution I want to avoid is creating UnmarshalJSON methods for Elephant, Feline, and Bear above. It would be better to create a method just for the Name type.

答:
See the json.Marshaler and json.Unmarshaler types in the encoding/json package which allow you to define custom JSON en/decoding functions for arbitrary types.

```<code>package main

import (
  "encoding/json"
  "fmt"
)

type Name struct {
  CommonName     string
  ScientificName string
}

func (n *Name) UnmarshalJSON(bytes []byte) error {
  var name string
  err := json.Unmarshal(bytes, &name)
  if err != nil {
    return err
  }
  n.CommonName = name
  n.ScientificName = ""
  return nil
}

type Elephant struct {
  Name Name `json:"name"`
  Age  int  `json:"age"`
}

func main() {
  alice := Elephant{}
  aliceJson := `{"name":"Alice","age":2}`
  err := json.Unmarshal([]byte(aliceJson), &alice)
  if err != nil {
    panic(err)
  }
  fmt.Printf("%#v\n", alice)
}
// main.Elephant{Name:main.Name{CommonName:"Alice", ScientificName:""}, Age:2}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Most of us know that a JSON object can be unmarshaled with JSON tags:

var jsonData = `{"name": "Brown Bear"}`

type Elephant struct {
    Name string `json:"name"`
}

This is because string is a built in types. But what if Name were not a built in type, and we wanted to use this type across different structs?

var jsonData = `{"name": "Brown Bear"}`

type Elephant struct {
    Name Name   `json:"name"`  // Unmarshalling fails here
}

type Feline struct {
    Name Name   `json:"name"`  // Unmarshalling fails here
}

type Bear struct {
    Name Name   `json:"name"`  // Unmarshalling fails here
}

type Name struct {
    CommonName     string
    ScientificName string  // This field should intentionally be blank
}

Is there a way we can define the Name type so that the json unmarshaller knows how to unmarshal it?

PS: The solution I want to avoid is creating UnmarshalJSON methods for Elephant, Feline, and Bear above. It would be better to create a method just for the Name type.

Body:
See the json.Marshaler and json.Unmarshaler types in the encoding/json package which allow you to define custom JSON en/decoding functions for arbitrary types.

package main

import (
  "encoding/json"
  "fmt"
)

type Name struct {
  CommonName     string
  ScientificName string
}

func (n *Name) UnmarshalJSON(bytes []byte) error {
  var name string
  err := json.Unmarshal(bytes, &name)
  if err != nil {
    return err
  }
  n.CommonName = name
  n.ScientificName = ""
  return nil
}

type Elephant struct {
  Name Name `json:"name"`
  Age  int  `json:"age"`
}

func main() {
  alice := Elephant{}
  aliceJson := `{"name":"Alice","age":2}`
  err := json.Unmarshal([]byte(aliceJson), &alice)
  if err != nil {
    panic(err)
  }
  fmt.Printf("%#v\n", alice)
}
// main.Elephant{Name:main.Name{CommonName:"Alice", ScientificName:""}, Age:2}


问:
How to change the position of an array element?
I have a question on how I can change the index of a array element, so that it doesn't come at the 7. position but at position 2 instead...

Is there a function to handle this?

答:
```<code>irb> a = [2,5,4,6]
=> [2, 5, 4, 6]
irb> a.insert(1,a.delete_at(3))
=> [2, 6, 5, 4]
</code>```

UPD: guys, it works fine with the dest>src:

```<code>a = [0,1,2,3,4]
a.insert 1, a.delete_at(3)
p a  #=>  [0, 3, 1, 2, 4]

a = [0,1,2,3,4]
a.insert 3, a.delete_at(1)
p a  #=>  [0, 2, 3, 1, 4]
</code>```

What else would you expect? 0,2,1,3,4? I would not call that dest=3

Body:
irb> a = [2,5,4,6]
=> [2, 5, 4, 6]
irb> a.insert(1,a.delete_at(3))
=> [2, 6, 5, 4]

UPD: guys, it works fine with the dest>src:

a = [0,1,2,3,4]
a.insert 1, a.delete_at(3)
p a  #=>  [0, 3, 1, 2, 4]

a = [0,1,2,3,4]
a.insert 3, a.delete_at(1)
p a  #=>  [0, 2, 3, 1, 4]

What else would you expect? 0,2,1,3,4? I would not call that dest=3


问:
css div not being recognized
I have the following css code:

```<code>#Layer3

{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-color: #f1ffff;
}

#Layer3 h1
{
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}

.tableheader {
    border-width:10px; border-style:solid;
}
.tablecontent {
    height: 95%;
    overflow:auto;
}
</code>```

However, when I use this PHP to generate the html

```<code>echo '<div id="tableheader" class="tableheader">';

echo "<h1>{$query} Auctions</h1>" . "\n";
echo "</div>";
echo '<div id="tablecontent" class="tablecontent">';

echo "<table border='0' width='100%'><tr>" . "\n";

echo "<td width='15%'>Seller ID</td>" . "\n";

echo "<td width='10%'>Start Date</td>" . "\n";

echo "<td width='75%'>Description</td>" . "\n";

echo "</tr>\n";

// printing table rows

    foreach ($rows as $row)

    {

        $pk = $row['ARTICLE_NO'];

        echo '<tr>' . "\n";

table contens generated in here

        echo '</tr>' . "\n";

    }
echo "</table>";
}

echo "</div>";
</code>```

which generates this html:

```<code><div id="tableheader" class="tableheader">
<h1>hardy Auctions</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border='0' width='100%'>
<tr>
<td width='15%'>Seller ID</td>
<td width='10%'>Start Date</td>
<td width='75%'>Description</td>
the rest of table stuff
</div>
</code>```

The stylesheet is correctly referenced so I am unsure what is causing the error. But there is no border around tableheader at all. Both of these layers are in Layer3 which no longer displays properly on the page.

答:
Start by browsing the HTML DOM in the rendered page either using Firebug in Firefox or using the IE Developer Toolbar in IE.

That way, you can see what styles are actually associated with the element in the rendered page.  It's a lot easier to debug the issue from there.

One possibility is that there's a syntax error somewhere in the CSS file causing the styles not to be applied correctly.

Title: css div not being recognized

Body:
I have the following css code:

#Layer3

{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-color: #f1ffff;
}

#Layer3 h1
{
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}

.tableheader {
    border-width:10px; border-style:solid;
}
.tablecontent {
    height: 95%;
    overflow:auto;
}

However, when I use this PHP to generate the html

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";

echo "Start Date	" . "\n";

echo "Description	" . "\n";

echo "
\n";

// printing table rows

    foreach ($rows as $row)

    {

        $pk = $row['ARTICLE_NO'];

        echo '
' . "\n";

table contens generated in here

        echo '
' . "\n";

    }
echo "
";
}

echo "
";

which generates this html:

hardy Auctions

Seller ID
Start Date
Description
the rest of table stuff

The stylesheet is correctly referenced so I am unsure what is causing the error. But there is no border around tableheader at all. Both of these layers are in Layer3 which no longer displays properly on the page.


问:
@monthly cron job is not reliable
Our customer wants us to create a report every month.

In the past, we used a @monthly cron job for this task.

But this is not reliable:

The server could be down in this minute. Cron does not re-run those jobs

If the server is up, the database could be unreachable in this moment.

If the server is up and DB is up, there could be a third party system which is not reachable

There could be a software bug.

What can I do, to be sure that the report gets created monthly?

It is a Django based web application

答:
The easy way is that you can write an helper such that the script checks for the availability of the report first and generates the report only if the report is unavailable.

Then schedule the script to run every hour on that day of the month.

change your script as follows:

```<code>if [[ -f <report_name> ]]
then
    echo "report exists"
    exit 1
else
    echo "run generate report script"
</code>```

crontab entry (To run every hour on 28th of every month):

```<code>0 0-23 28 * * <name_of_helper_script>
</code>```

Title: @monthly cron job is not reliable

Body:
The easy way is that you can write an helper such that the script checks for the availability of the report first and generates the report only if the report is unavailable.

Then schedule the script to run every hour on that day of the month.

change your script as follows:

if [[ -f <report_name> ]]
then
    echo "report exists"
    exit 1
else
    echo "run generate report script"

crontab entry (To run every hour on 28th of every month):

0 0-23 28 * * <name_of_helper_script>


问:
How to access mulesoft application metrics using JMX
I want to expose some custom application metrics like how many records processed to JMX in mulesoft flow.
My application is spring boot application.

Any idea on how to achieve this?

Thanks & Regards,
Vikas Gite

答:
Using the Default JMX Support Agent
You can configure several JMX agents simultaneously using the  element. When set, this element registers the following agents:

List item

JMX agent

RMI registry agent (if necessary) on rmi://localhost:1099

Remote JMX access on service:jmx:rmi:///jndi/rmi://localhost:1099/server

(Optional) Log4J JMX agent, which exposes the configuration of the Log4J instance used by Mule for JMX management

JMX notification agent used to receive server notifications using JMX notifications

(Optional) MX4J adapter, which provides web-based JMX management, statistics, and configuration viewing of a Mule instance

Also you can try below which can directly be configured under the MULE's wrapper.conf (under $MULE_HOME/conf/wrapper.conf) to enable JMX connectivity so that we can use tools like JMC (Java Mission Control), VisualVM, JConsole to pull the JMX attribute values from the Mule Server and the deployed applications -

```<code>wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.port=9999
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.authenticate=false
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.local.only=false
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.ssl=false
wrapper.java.additional.<n>=-Djava.rmi.server.hostname=<localhost ip>
wrapper.java.additional.<n>=-Djava.rmi.activation.port=9998
</code>```

Here  should be removed with the next incremental value of the java wrapper value and  will be the ip of the the Mule runtime host/server

I hope you are looking for this, if not then please post further queries or clarity so that i will help you out.

Body:
Using the Default JMX Support Agent
You can configure several JMX agents simultaneously using the  element. When set, this element registers the following agents:

List item

JMX agent

RMI registry agent (if necessary) on rmi://localhost:1099

Remote JMX access on service:jmx:rmi:///jndi/rmi://localhost:1099/server

(Optional) Log4J JMX agent, which exposes the configuration of the Log4J instance used by Mule for JMX management

JMX notification agent used to receive server notifications using JMX notifications

(Optional) MX4J adapter, which provides web-based JMX management, statistics, and configuration viewing of a Mule instance

Also you can try below which can directly be configured under the MULE's wrapper.conf (under $MULE_HOME/conf/wrapper.conf) to enable JMX connectivity so that we can use tools like JMC (Java Mission Control), VisualVM, JConsole to pull the JMX attribute values from the Mule Server and the deployed applications -

wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.port=9999
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.authenticate=false
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.local.only=false
wrapper.java.additional.<n>=-Dcom.sun.management.jmxremote.ssl=false
wrapper.java.additional.<n>=-Djava.rmi.server.hostname=<localhost ip>
wrapper.java.additional.<n>=-Djava.rmi.activation.port=9998

Here  should be removed with the next incremental value of the java wrapper value and  will be the ip of the the Mule runtime host/server

I hope you are looking for this, if not then please post further queries or clarity so that i will help you out.


问:
Filtering a SelectList based on a User's Role
When assigning a user to a certain project, I'd like to limit the list of available users to people with the role "Project Manager". I could use some help with the syntax because I can't seem to get the LINQ syntax right for the Where method.

Create Action (GET)

```<code>// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");
</code>```

Create View

```<code><div class="form-group">
     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
         <div class="col-md-10">
             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
         </div>
</div>
</code>```

I'm getting an error on the DropDownList saying

cannot compare elements of type 'System.Collections.Generic.ICollection'. Only primitive types, enumeration types and entity types are supported.

答:
The solution to my question is including this code in the Controller Create Action (GET):

```<code>var role = db.Roles.SingleOrDefault(u => u.Name == "Project Manager");
var usersInRole = db.Users.Where(u => u.Roles.Any(r => (r.RoleId == role.Id)));
ViewBag.AssignedId = new SelectList(usersInRole, "Id", "FullName");
</code>```

Instead of :

```<code>ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
</code>```

And then including this in the Create View:

```<code><div class="form-group">
      @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
           @Html.DropDownListFor(Model => Model.AssignedToId, ViewBag.AssignedId as SelectList, null, htmlAttributes: new { @class = "form-control" })
           @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
      </div>
</div>
</code>```

Substituting for this DropDownListFor:

```<code>@Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
</code>```

Body:
When assigning a user to a certain project, I'd like to limit the list of available users to people with the role "Project Manager". I could use some help with the syntax because I can't seem to get the LINQ syntax right for the Where method.

Create Action (GET)

// This is the unfiltered version
ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");
// Attempt to filter
ViewBag.AssignedToId= new SelectList(db.Users.Where(c => c.Roles.Contains("Project Manager")), "Id", "FullName");

Create View

     @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })

             @Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })
             @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })

I'm getting an error on the DropDownList saying

cannot compare elements of type 'System.Collections.Generic.ICollection'. Only primitive types, enumeration types and entity types are supported.

Body:
The solution to my question is including this code in the Controller Create Action (GET):

var role = db.Roles.SingleOrDefault(u => u.Name == "Project Manager");
var usersInRole = db.Users.Where(u => u.Roles.Any(r => (r.RoleId == role.Id)));
ViewBag.AssignedId = new SelectList(usersInRole, "Id", "FullName");

Instead of :

ViewBag.AssignedToId = new SelectList(db.Users, "Id", "FullName");

And then including this in the Create View:

<div class="form-group">
      @Html.LabelFor(model => model.AssignedToId, "Choose a Project Manager", htmlAttributes: new { @class = "control-label col-md-2" })
      <div class="col-md-10">
           @Html.DropDownListFor(Model => Model.AssignedToId, ViewBag.AssignedId as SelectList, null, htmlAttributes: new { @class = "form-control" })
           @Html.ValidationMessageFor(model => model.AssignedToId, "", new { @class = "text-danger" })
      </div>
</div>

Substituting for this DropDownListFor:

@Html.DropDownList("AssignedToId", null, htmlAttributes: new { @class = "form-control" })