问:
When onCreateView is called after setArguments?
There is one question.

So in my adpater class, I excute codes below.

```<code>DrinkFragment fragment3 = new DrinkFragment();
Bundle bundle3 = new Bundle();
bundle3.putInt("type",2);
fragment3.setArguments(bundle3);
return fragment3;
</code>```

So I make an instance of DrinkFragment.

To excute getArguments() in DrinkFragment.java at onCreateView(~~~), onCreateView(~~~) must be excuted after fragment3.setArgument(bundle3) right?

So I don't think onCreateView(~~) is excuted the moment i create DrinkFragment instance. Then when does it excuted?

Thanks in advance. ;)

this is my PagerAdapter.java where I create Fragment instance.

```<code>package com.junga.project1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int numOfFragment;
    private static final String TAG = "PagerAdapter";

    public PagerAdapter(FragmentManager fm,int numOfFragment) {
        super(fm);
        this.numOfFragment = numOfFragment;
    }

    @Override
    public Fragment getItem(int i) {

        switch(i){
            case 0:
                DrinkFragment fragment1 = new DrinkFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("type",0);
                fragment1.setArguments(bundle);
                Log.d(TAG, "getItem: 0 ");
                Log.d(TAG, "Set the argument fragment1");
                return fragment1;
            case 1:
                DrinkFragment fragment2 = new DrinkFragment();
                Bundle bundle2 = new Bundle();
                bundle2.putInt("type",1);
                fragment2.setArguments(bundle2);
                Log.d(TAG, "Set the argument fragment2");
                Log.d(TAG, "getItem: 1");
                return fragment2;

            case 2:
                DrinkFragment fragment3 = new DrinkFragment();
                Bundle bundle3 = new Bundle();
                bundle3.putInt("type",2);
                fragment3.setArguments(bundle3);
                Log.d(TAG, "getItem: 2");
                Log.d(TAG, "getItem: Set the argument fragment3");
                return fragment3;

            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return numOfFragment;
    }
}
</code>```

This is fragment.java where onCreateView() exists.

```<code>
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class DrinkFragment extends Fragment {

    private static final String TAG = "DrinkFragment";
    int fragmentType;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: Created");
        Bundle bundle = this.getArguments();

        fragmentType = bundle.getInt("type",0);
        Log.d(TAG, "Got the bundle type : "+fragmentType);
        View view =  inflater.inflate(R.layout.fragment_drink,container,false);
        ImageView image = (ImageView) view.findViewById(R.id.image);

        switch(fragmentType){
            case 0 :
                image.setImageResource(R.drawable.fragment_soju);
                return view;
            case 1:
                image.setImageResource(R.drawable.fragment_makgeoli);
                return view;
            case 2:
                image.setImageResource(R.drawable.fragment_cheongju);
                return view;
            default:
                return view;

        }
    }
}```
```

答:
Sorry if my code is not in Java but what I did to pass arguments in kotlin was to make oncreateview to return the view first then call the function to onviewcreated so it will execute once the view has been created. Here is the code in Kotlin:</p>

```<code> override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                    val menufragment: Fragment = YourFragment()
                    val args = Bundle()
                    args.putString("str1", text) //text and text1 are strings
                    args.putString("str2", text1)
                menufragment.arguments = args
                    val fr = fragmentManager?.beginTransaction()
                    fr?.replace(R.id.content_frame, menufragment)
                    fr?.addToBackStack(null)
                    fr?.commit()
}
</code>```

Body:
There is one question.

So in my adpater class, I excute codes below.

DrinkFragment fragment3 = new DrinkFragment();
Bundle bundle3 = new Bundle();
bundle3.putInt("type",2);
fragment3.setArguments(bundle3);
return fragment3;

So I make an instance of DrinkFragment.

To excute getArguments() in DrinkFragment.java at onCreateView(~~~), onCreateView(~~~) must be excuted after fragment3.setArgument(bundle3) right?

So I don't think onCreateView(~~) is excuted the moment i create DrinkFragment instance. Then when does it excuted?

Thanks in advance. ;)

this is my PagerAdapter.java where I create Fragment instance.

package com.junga.project1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int numOfFragment;
    private static final String TAG = "PagerAdapter";

    public PagerAdapter(FragmentManager fm,int numOfFragment) {
        super(fm);
        this.numOfFragment = numOfFragment;
    }

    @Override
    public Fragment getItem(int i) {

        switch(i){
            case 0:
                DrinkFragment fragment1 = new DrinkFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("type",0);
                fragment1.setArguments(bundle);
                Log.d(TAG, "getItem: 0 ");
                Log.d(TAG, "Set the argument fragment1");
                return fragment1;
            case 1:
                DrinkFragment fragment2 = new DrinkFragment();
                Bundle bundle2 = new Bundle();
                bundle2.putInt("type",1);
                fragment2.setArguments(bundle2);
                Log.d(TAG, "Set the argument fragment2");
                Log.d(TAG, "getItem: 1");
                return fragment2;

            case 2:
                DrinkFragment fragment3 = new DrinkFragment();
                Bundle bundle3 = new Bundle();
                bundle3.putInt("type",2);
                fragment3.setArguments(bundle3);
                Log.d(TAG, "getItem: 2");
                Log.d(TAG, "getItem: Set the argument fragment3");
                return fragment3;

            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return numOfFragment;
    }
}

This is fragment.java where onCreateView() exists.

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class DrinkFragment extends Fragment {

    private static final String TAG = "DrinkFragment";
    int fragmentType;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: Created");
        Bundle bundle = this.getArguments();

        fragmentType = bundle.getInt("type",0);
        Log.d(TAG, "Got the bundle type : "+fragmentType);
        View view =  inflater.inflate(R.layout.fragment_drink,container,false);
        ImageView image = (ImageView) view.findViewById(R.id.image);

        switch(fragmentType){
            case 0 :
                image.setImageResource(R.drawable.fragment_soju);
                return view;
            case 1:
                image.setImageResource(R.drawable.fragment_makgeoli);
                return view;
            case 2:
                image.setImageResource(R.drawable.fragment_cheongju);
                return view;
            default:
                return view;

        }
    }
}```

Body:
Sorry if my code is not in Java but what I did to pass arguments in kotlin was to make oncreateview to return the view first then call the function to onviewcreated so it will execute once the view has been created. Here is the code in Kotlin:

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                    val menufragment: Fragment = YourFragment()
                    val args = Bundle()
                    args.putString("str1", text) //text and text1 are strings
                    args.putString("str2", text1)
                menufragment.arguments = args
                    val fr = fragmentManager?.beginTransaction()
                    fr?.replace(R.id.content_frame, menufragment)
                    fr?.addToBackStack(null)
                    fr?.commit()
}


来源: stackexchange

问:
Filter data using group by
I have this data

I want to filter this table to get another table contain quantity of each item which driver have.
I tried to use group by driver_id but it count all items with the driver. I don't need that I need quantity of each item with the driver.
I need a result table like this

答:
It looks like you need to group by both the item_id and the driver_id:</p>

```<code>group by driver_id, item_id
</code>```

ContentLicense: CC BY-SA 4.0

Title: Filter data using group by

Body:
It looks like you need to group by both the item_id and the driver_id:

group by driver_id, item_id


问:
Wildcard have same class then take first child of the css
If some elements have a class with prefix and if the class is similar then I need to hide all classes except for the first one.

```<code><span class="prefix-one">A</span>
<span class="prefix-two">B</span>
<span class="prefix-one">C</span>
<span class="prefix-three">D</span>
<span class="prefix-four">E</span>
<span class="prefix-one">F</span>
<span class="prefix-five">G</span>
</code>```

Here prefix-one is repeated thrice. So I need to display only the first one.

And the result needs to be like

```<code>ABDEG
</code>```

That is, I need to hide the repeated span.
I tried using some wildcard CSS selector like

```<code><style>
  [class*="prefix-"]{
    display: none;
  }
  [class*="prefix-"]:first-child{
    display:block;
  }
</style>
</code>```

nothing works.
Is there is any possibility to select an element like this?

If there is nothing jQuery also acceptable. But I would like to have a solution with CSS or SCSS.

NB: This one is only an example. The word after prefix- is dynamic. So hardcoding the class name is not possible. I can't add any specific class to them. The HTML is generated from some other way.

答:
Try like this.

I provided solution with jquery.

var text = "";

$('[class^="prefix-"]').each(function(){
  text += $(this).text()
});
var i=0;
$('[class^="prefix-"]').each(function(){
  if(i==0)
    $(this).css('display','block')

  $(this).html(text);
  i++;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[class*="prefix-"]{
    display: none;
}</code>```

A
B
C
D
E
F
G```

Body:
If some elements have a class with prefix and if the class is similar then I need to hide all classes except for the first one.

A
B
C
D
E
F
G

Here prefix-one is repeated thrice. So I need to display only the first one.

And the result needs to be like

ABDEG

That is, I need to hide the repeated span.
I tried using some wildcard CSS selector like

nothing works.
Is there is any possibility to select an element like this?

If there is nothing jQuery also acceptable. But I would like to have a solution with CSS or SCSS.

NB: This one is only an example. The word after prefix- is dynamic. So hardcoding the class name is not possible. I can't add any specific class to them. The HTML is generated from some other way.

Body:
Try like this.

I provided solution with jquery.

var text = "";

$('[class^="prefix-"]').each(function(){
  text += $(this).text()
});
var i=0;
$('[class^="prefix-"]').each(function(){
  if(i==0)
    $(this).css('display','block')

  $(this).html(text);
  i++;
});

[class*="prefix-"]{
    display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="prefix-one">A</span>
<span class="prefix-two">B</span>
<span class="prefix-one">C</span>
<span class="prefix-three">D</span>
<span class="prefix-four">E</span>
<span class="prefix-one">F</span>
<span class="prefix-five">G</span>


问:
SonarLint doesn't show custom rules from local SonarQube server
I've added some XML custom rules for my project. Then I added these rules to my local SonarQube server. When I analyze my project all of the custom rules appear. When I opened my project in Eclipse and connected to my local sonarqube via sonarlint, everything works fine. The problem with intellij. It doesn't show any of rules except the rules that have been there before.

in my pom.xml I flagged this one

```<code><sonarLintSupported>true</sonarLintSupported>
</code>```

Also I'm informed that sonarlint doesn't support 3rd party plugins, but I don't use any of them. Maybe there is some exceptions for intellij? cause for eclipse those rules appear.

My sonarqube version is 7.7.0.23042
and sonarlint Version for Intellij : 3.4.0.2532
Sonarlint for eclipse 4.1

答:
SonarLint for Eclipse and IntelliJ don't provide the same features. There are many differences. One of them is a list of supported languages:

```<code>+------------+----------------+-----------------+
|  Language  | SL Eclipse 4.1 | SL IntelliJ 4.0 |
|------------|----------------|-----------------|
|    Java    |       Yes      |       Yes       |
| JavaScript |       Yes      |       Yes       |
|   Python   |       Yes      |       Yes       |
|   Kotlin   |       No       |       Yes       |
|    Ruby    |       No       |       Yes       |
|    PHP     |       Yes      |       Yes       |
+------------+----------------+-----------------+
</code>```

And another is a different level of support of the above languages. In SonarSource Jira you can find this issue: SLCORE-221 Whitelist SonarSource XML analyzer 2.0, and tickets depend on it:

SLE-295 Enable XML Analyzer in connected mode ← done in Eclipse 4.1

SLI-320 Enable XML Analyzer in connected mode ← open, should be done in IntelliJ 4.1

I think this could be a reason why you see issues in Eclipse, and don't see them in IntelliJ.

Body:
I've added some XML custom rules for my project. Then I added these rules to my local SonarQube server. When I analyze my project all of the custom rules appear. When I opened my project in Eclipse and connected to my local sonarqube via sonarlint, everything works fine. The problem with intellij. It doesn't show any of rules except the rules that have been there before.

in my pom.xml I flagged this one

<sonarLintSupported>true</sonarLintSupported>

Also I'm informed that sonarlint doesn't support 3rd party plugins, but I don't use any of them. Maybe there is some exceptions for intellij? cause for eclipse those rules appear.

My sonarqube version is 7.7.0.23042
and sonarlint Version for Intellij : 3.4.0.2532
Sonarlint for eclipse 4.1

Body:
SonarLint for Eclipse and IntelliJ don't provide the same features. There are many differences. One of them is a list of supported languages:

+------------+----------------+-----------------+
|  Language  | SL Eclipse 4.1 | SL IntelliJ 4.0 |
|------------|----------------|-----------------|
|    Java    |       Yes      |       Yes       |
| JavaScript |       Yes      |       Yes       |
|   Python   |       Yes      |       Yes       |
|   Kotlin   |       No       |       Yes       |
|    Ruby    |       No       |       Yes       |
|    PHP     |       Yes      |       Yes       |
+------------+----------------+-----------------+

And another is a different level of support of the above languages. In SonarSource Jira you can find this issue: SLCORE-221 Whitelist SonarSource XML analyzer 2.0, and tickets depend on it:

SLE-295 Enable XML Analyzer in connected mode ← done in Eclipse 4.1

SLI-320 Enable XML Analyzer in connected mode ← open, should be done in IntelliJ 4.1

I think this could be a reason why you see issues in Eclipse, and don't see them in IntelliJ.


问:
Is there anyway to disable a bootstrap button permanently after one click on server side using PHP?
I'm trying to disable a bootstrap button permanently after one click. I know how to do this on client side using JavaScript but after refreshing page, it becomes enabled. So, I want to do it on the server side. But don't know how to do it. Can anyone help??</p>

答:
There would need to be informed in a database in order for the button to know if it needs to be pressed.

I would suggest either using an Ajax request to do an insert statement into a database once the selected button is pressed or you can use it through a  tag submits into an insert statement in order to get the data to see if it should be permanently selected.

Then you would need a select statement to read the database data into an IF statement such as this;

```<code>($row['Button_Pressed'] == '1' ? 'Selected' : '')
</code>```

The Button_Pressed is just the column in the table that would store the data and the 1 is the boolean value

Body:
There would need to be informed in a database in order for the button to know if it needs to be pressed.

I would suggest either using an Ajax request to do an insert statement into a database once the selected button is pressed or you can use it through a  tag submits into an insert statement in order to get the data to see if it should be permanently selected.

Then you would need a select statement to read the database data into an IF statement such as this;

($row['Button_Pressed'] == '1' ? 'Selected' : '')

The Button_Pressed is just the column in the table that would store the data and the 1 is the boolean value


问:
how to override django save method to update some field dynamically?
Here i have two models.In these models i want to make the value of amount_to_pay dynamic in Ledger model.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field  then if only ledger.id and expense.payment_option_id are same then the value of amount_to_pay in ledger model should be replaced with that value.how can i do it ?

models.py

```<code>     class Expense(models.Model):
        pay_from = models.CharField(max_length=200)
        payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE)
        amount_to_pay = models.IntegerField(default=0)
        expense_date = models.DateField(default=datetime.date.today)
        expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE)
        note = models.TextField()
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='expense_type')

        def get_amount_to_pay(self):
            return self.amount_to_pay

    class Ledger(models.Model):
        name = models.CharField(max_length=200)
        account_number = models.CharField(max_length=250, unique=True)
        account_type = models.CharField(max_length=200)
        opening_balance = models.IntegerField(default=0)
        amount_to_pay = models.IntegerField(default=0, blank=True, null=True)
        current_balance = models.IntegerField(default=0, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='name')

        def save(self, *args, **kwargs):
             self.amount_to_pay = Expense.get_amount_to_pay(self)

# here how can i save the amount_to_pay from expense form if the ledger.id and expense.payment_option.id matches??
#i got stuck here.
 self.current_balance = self.opening_balance - self.amount_to_pay

            super(Ledger, self).save(*args, **kwargs)
</code>```

答:
check if Ledger have child and then update it:</p>

```<code>class Expense(models.Model):
        def save(self, *args, **kwargs):
                self.payment_option.amount_to_pay = self.payment_option.amount_to_pay + self.amount_to_pay
                self.payment_option.save()
            super(Expense, self).save(*args, **kwargs)
</code>```

Body:
Here i have two models.In these models i want to make the value of amount_to_pay dynamic in Ledger model.For Example i have two different forms for these two models and while saving expense form if the user select the payment_option which comes from ledger model and gives some value for the amount_to_pay field  then if only ledger.id and expense.payment_option_id are same then the value of amount_to_pay in ledger model should be replaced with that value.how can i do it ?

models.py

     class Expense(models.Model):
        pay_from = models.CharField(max_length=200)
        payment_option = models.ForeignKey('Ledger', on_delete=models.CASCADE)
        amount_to_pay = models.IntegerField(default=0)
        expense_date = models.DateField(default=datetime.date.today)
        expense_type = models.ForeignKey(ExpenseType, on_delete=models.CASCADE)
        note = models.TextField()
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='expense_type')

        def get_amount_to_pay(self):
            return self.amount_to_pay

    class Ledger(models.Model):
        name = models.CharField(max_length=200)
        account_number = models.CharField(max_length=250, unique=True)
        account_type = models.CharField(max_length=200)
        opening_balance = models.IntegerField(default=0)
        amount_to_pay = models.IntegerField(default=0, blank=True, null=True)
        current_balance = models.IntegerField(default=0, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)
        slug = AutoSlugField(unique_with='id', populate_from='name')

        def save(self, *args, **kwargs):
             self.amount_to_pay = Expense.get_amount_to_pay(self)

# here how can i save the amount_to_pay from expense form if the ledger.id and expense.payment_option.id matches??
#i got stuck here.
 self.current_balance = self.opening_balance - self.amount_to_pay

            super(Ledger, self).save(*args, **kwargs)

Body:
check if Ledger have child and then update it:

class Expense(models.Model):
        def save(self, *args, **kwargs):
                self.payment_option.amount_to_pay = self.payment_option.amount_to_pay + self.amount_to_pay
                self.payment_option.save()
            super(Expense, self).save(*args, **kwargs)


问:
Generate a Dataframe that follow a mathematical function for each column / row
Is there a way to create/generate a Pandas DataFrame from scratch, such that each record follows a specific mathematical function?

Background: In Financial Mathematics, very basic financial-derivatives (e.g. calls and puts) have closed-form pricing formulas (e.g. Black Scholes). These pricing formulas can be called stochastic functions (because they involve a random term)

I'm trying to create a Monte Carlo simulation of a stock price (and subseuqently an option payoff and price based on the stock price). I need, say, 1000 paths (rows) and 100 time-steps (columns). I want to "initiate" a dataframe that is 1000 by 100 and follows a stochastic equation.

```<code># Psuedo-code
MonteCarloDF = DataFrame(rows=1000, columns=100, customFunc=TRUE,
        appliedBy='by column',
        FUNC={s0=321;
              s_i=prev*exp(r-q*sqrt(sigma))*T +
                 (etc)*NormDist(rnd())*sqr(deltaT)}
        )
</code>```

Column 0 in every row would be 321, and each subsequent column would be figured out based on the FUNC above.

This is an example of something similar done in VBA

```<code>Function MonteCarlo_Vanilla_call(S, K, r, q, vol, T, N)

sum = 0
payoff = 0

For i = 1 To N
 S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd()))
 payoff = Application.Max(S_T - K, 0)
 sum = sum + payoff
Next i

MonteCarlo_Vanilla_call = Exp(-r * T) * sum / N

End Function
</code>```

Every passed in variable is a constant.
In my case, I want each next column in the same row to be just like S_T in the VBA code. That's really the only like that matters. I want to apply a function like S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd())) . Each S_T is the next column in the same row. There's N columns making one simulation. I will have, for example, 1000 simulations.

```<code>321     | 322.125 | 323.277 | ... | column 100 value
321     | 320.704 | 319.839 | ... | column 100 value
321     | 321.471 | 318.456 | ... | column 100 value
...
row 1000| etc     | etc     | ... | value (1000,100)
</code>```

答:
IIUC, you could create your own function to generate a DataFrame.
Within the function iterate using .iloc[:, -1] to use the last created column.

We'll also use numpy.random.randn to generate an array of normally distributed random values.

You may need to adjust the default values of your variables, but the idea would be something like:

Function

```<code>import pandas as pd
import numpy as np
from math import exp, sqrt

def monte_carlo_df(nrows,
                   ncols,
                   col_1_val,
                   r=0.03,
                   q=0.5,
                   sigma=0.002,
                   T=1.0002,
                   deltaT=0.002):
    """Returns stochastic monte carlo DataFrame"""

    # Create first column
    df = pd.DataFrame({'s0': [col_1_val] * nrows})

    # Create subsequent columns
    for i in range(1, ncols):
        df[f's{i}'] = (df.iloc[:, -1] * exp(r - q * sqrt(sigma)) * T
                       + (np.random.randn(nrows) * sqrt(deltaT)))
    return df
</code>```

Usage example

```<code>df = monte_carlo_df(nrows=1000, ncols=100, col_1_val=321)
</code>```

Body:
Is there a way to create/generate a Pandas DataFrame from scratch, such that each record follows a specific mathematical function?

Background: In Financial Mathematics, very basic financial-derivatives (e.g. calls and puts) have closed-form pricing formulas (e.g. Black Scholes). These pricing formulas can be called stochastic functions (because they involve a random term)

I'm trying to create a Monte Carlo simulation of a stock price (and subseuqently an option payoff and price based on the stock price). I need, say, 1000 paths (rows) and 100 time-steps (columns). I want to "initiate" a dataframe that is 1000 by 100 and follows a stochastic equation.

# Psuedo-code
MonteCarloDF = DataFrame(rows=1000, columns=100, customFunc=TRUE,
        appliedBy='by column',
        FUNC={s0=321;
              s_i=prev*exp(r-q*sqrt(sigma))*T +
                 (etc)*NormDist(rnd())*sqr(deltaT)}
        )

Column 0 in every row would be 321, and each subsequent column would be figured out based on the FUNC above.

This is an example of something similar done in VBA

Function MonteCarlo_Vanilla_call(S, K, r, q, vol, T, N)

sum = 0
payoff = 0

For i = 1 To N
 S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd()))
 payoff = Application.Max(S_T - K, 0)
 sum = sum + payoff
Next i

MonteCarlo_Vanilla_call = Exp(-r * T) * sum / N

End Function

Every passed in variable is a constant.
In my case, I want each next column in the same row to be just like S_T in the VBA code. That's really the only like that matters. I want to apply a function like S_T = S * Exp((r - q - 0.5 * vol ^ 2) * T + vol * Sqr(T) * Application.NormSInv(Rnd())) . Each S_T is the next column in the same row. There's N columns making one simulation. I will have, for example, 1000 simulations.

321     | 322.125 | 323.277 | ... | column 100 value
321     | 320.704 | 319.839 | ... | column 100 value
321     | 321.471 | 318.456 | ... | column 100 value
...
row 1000| etc     | etc     | ... | value (1000,100)

Body:
IIUC, you could create your own function to generate a DataFrame.
Within the function iterate using .iloc[:, -1] to use the last created column.

We'll also use numpy.random.randn to generate an array of normally distributed random values.

You may need to adjust the default values of your variables, but the idea would be something like:

Function

import pandas as pd
import numpy as np
from math import exp, sqrt

def monte_carlo_df(nrows,
                   ncols,
                   col_1_val,
                   r=0.03,
                   q=0.5,
                   sigma=0.002,
                   T=1.0002,
                   deltaT=0.002):
    """Returns stochastic monte carlo DataFrame"""

    # Create first column
    df = pd.DataFrame({'s0': [col_1_val] * nrows})

    # Create subsequent columns
    for i in range(1, ncols):
        df[f's{i}'] = (df.iloc[:, -1] * exp(r - q * sqrt(sigma)) * T
                       + (np.random.randn(nrows) * sqrt(deltaT)))
    return df

Usage example

df = monte_carlo_df(nrows=1000, ncols=100, col_1_val=321)


问:
How to run 1 complete loop-circle than refresh page than check with if(), if the condition are met, run 1 loop circle again
What i want is after user click specific button on my webpage, I will check with if(isset()) than run the follow commend for loop.

This is what i have done so far. If $balance is 10 than for loop should run 10 times. For loop run instantly 10 times without refreshing the page but sleep() function help delay it. I need to refresh the page every 1 loop complete than continue the rest 9 loops. Every loop need to refresh page every time its run.

```<code>$balance = '10';
$wallet = $_SESSION['wallet'];

if(isset($_POST['click'])){
    if($balance != 0){
        for($x = 0; $x < $balance; $x++){
            $sql = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' " );
            //some code to complete this
            ....
            //this is where the page to refresh
            header("location: click.php?e=2");
        }
        sleep(5);
    }
    else{
        header("location: click.php?e=1");
    }
}
</code>```

What i expected is ....
1 loop complete refresh page 1 time than continue another 1 loop than refresh page 1 more time than continue....

答:
You don't need any loop its just decrement values will work.</p>

```<code>$balance = ($_SESSION['balance'] ?? 0);
$wallet  = $_SESSION['wallet'];
if (isset($_POST['click'])) {
    if ($balance > 0) {
        // for ($x = 0; $x < $balance; $x++) {
        $sql                = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' ");
        $_SESSION['wallet'] = intval($_SESSION['wallet']) - 1;
        $_SESSION['balance'] = $_SESSION['balance']-1;
        //some code to complete this
        //....
        //this is where the page to refresh
        header("location: click.php?e=2");
        // }
        sleep(5);
    } else {
        header("location: click.php?e=1");
    }
}
</code>```

Body:
What i want is after user click specific button on my webpage, I will check with if(isset()) than run the follow commend for loop.

This is what i have done so far. If $balance is 10 than for loop should run 10 times. For loop run instantly 10 times without refreshing the page but sleep() function help delay it. I need to refresh the page every 1 loop complete than continue the rest 9 loops. Every loop need to refresh page every time its run.

$balance = '10';
$wallet = $_SESSION['wallet'];

if(isset($_POST['click'])){
    if($balance != 0){
        for($x = 0; $x < $balance; $x++){
            $sql = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' " );
            //some code to complete this
            ....
            //this is where the page to refresh
            header("location: click.php?e=2");
        }
        sleep(5);
    }
    else{
        header("location: click.php?e=1");
    }
}

What i expected is ....
1 loop complete refresh page 1 time than continue another 1 loop than refresh page 1 more time than continue....

Body:
You don't need any loop its just decrement values will work.

$balance = ($_SESSION['balance'] ?? 0);
$wallet  = $_SESSION['wallet'];
if (isset($_POST['click'])) {
    if ($balance > 0) {
        // for ($x = 0; $x < $balance; $x++) {
        $sql                = $conn->query("UPDATE wallets SET balance = balance - 1 WHERE wallet = '$wallet' ");
        $_SESSION['wallet'] = intval($_SESSION['wallet']) - 1;
        $_SESSION['balance'] = $_SESSION['balance']-1;
        //some code to complete this
        //....
        //this is where the page to refresh
        header("location: click.php?e=2");
        // }
        sleep(5);
    } else {
        header("location: click.php?e=1");
    }
}


问:
How to insert a row in Javascript with a loop?
I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?

Json file:

```<code>{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
 }
</code>```

My code:

```<code>    var jdata = {};
    jdata.cols = [
        {
            "id": "1",
            "label": "name",
            "type": "string"
        },
        {
            "id": "2",
            "label": "country",
            "type":"string"
        }
    ];

    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.insertRow(row);
    }
</code>```

Edit: Add expected output: change the json file to the following structure.

```<code>[
    ['lily', 'china'],
    ['mike', 'japan'],
    ['lucy', 'korea'],
  ]
</code>```

答:
There are a few errors in your code

The JSON needs to be an array so you can loop through each object to display.

insertRow() is a method from the Table object, jdata.rows is not a Table object but an array.

Since, you have used insertRow(), I have rewritten your code to display the table data using the Table Object methods. Here is a code snippet

Edit: You can use the push() method to create your required JSON structure. I have edited the code snippet to create your required JSON.

var jdata = {
  cols: [{
      "id": "1",
      "label": "name",
      "type": "string"
    },
    {
      "id": "2",
      "label": "country",
      "type": "string"
    }
  ],
  rows: []
};

var persons = [{
    "name": "lily",
    "country": "china",
    "age": 23
  },
  {
    "name": "mike",
    "country": "japan",
    "age": 22
  }, {
    "name": "lucy",
    "country": "korea",
    "age": 25
  }
];

var table = document.getElementById("table");
var header = table.createTHead();
var footer = table.createTFoot();
var rowHeader = header.insertRow(0);

jdata.cols.forEach((col, index) => {
  var cell = rowHeader.insertCell(index);
  cell.innerHTML = col.label;
});

persons.forEach((person, index) => {
  var rowFooter = footer.insertRow(index);
  rowFooter.insertCell(0).innerHTML = person.name;
  rowFooter.insertCell(1).innerHTML = person.country;

  jdata.rows.push([person.name, person.country]);
});

console.log(jdata.rows);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table">

</table></code>```

Body:
I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?

Json file:

{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
 }

My code:

    var jdata = {};
    jdata.cols = [
        {
            "id": "1",
            "label": "name",
            "type": "string"
        },
        {
            "id": "2",
            "label": "country",
            "type":"string"
        }
    ];

    for(var i = 1; i < 3; i++){
        row = [
            {
                "c": [
                    {
                      "v": json["hits"]["hits"][i]["_source"]["name"]
                    },
                    {
                       "v": json["hits"]["hits"][i]["_source"]["country"]
                    }
                ]
            }
        ];
        jdata.rows.insertRow(row);
    }

Edit: Add expected output: change the json file to the following structure.

[
    ['lily', 'china'],
    ['mike', 'japan'],
    ['lucy', 'korea'],
  ]

Body:
There are a few errors in your code

The JSON needs to be an array so you can loop through each object to display.

insertRow() is a method from the Table object, jdata.rows is not a Table object but an array.

Since, you have used insertRow(), I have rewritten your code to display the table data using the Table Object methods. Here is a code snippet

Edit: You can use the push() method to create your required JSON structure. I have edited the code snippet to create your required JSON.

var jdata = {
  cols: [{
      "id": "1",
      "label": "name",
      "type": "string"
    },
    {
      "id": "2",
      "label": "country",
      "type": "string"
    }
  ],
  rows: []
};

var persons = [{
    "name": "lily",
    "country": "china",
    "age": 23
  },
  {
    "name": "mike",
    "country": "japan",
    "age": 22
  }, {
    "name": "lucy",
    "country": "korea",
    "age": 25
  }
];

var table = document.getElementById("table");
var header = table.createTHead();
var footer = table.createTFoot();
var rowHeader = header.insertRow(0);

jdata.cols.forEach((col, index) => {
  var cell = rowHeader.insertCell(index);
  cell.innerHTML = col.label;
});

persons.forEach((person, index) => {
  var rowFooter = footer.insertRow(index);
  rowFooter.insertCell(0).innerHTML = person.name;
  rowFooter.insertCell(1).innerHTML = person.country;

  jdata.rows.push([person.name, person.country]);
});

console.log(jdata.rows);

<table id="table">

</table>


问:
how to know which c++ version is uesd when use -lstdc++ to build cpp file
I need to use gcc to build c++ files and gcc command is like "gcc -g test.cpp -lstdc++ -o out". How can i know which c++ version is used to build test.cpp?</p>

答: First of all don't use gcc -lstdc++, use g++ instead. The used C++ version can be seen in the output of g++ --version. gcc --version shows the same output


问:
Spring boot MongoDB configuration
I'm working in a spring boot application & use both MySQL & mongodb as databases.Below you can see spring boot main application for MySQL.

```<code>@EnableFeignClients(basePackages = {"com.saman.kamal.nimalservice"})
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = {"com.saman.kamal.nimalservice"})
@EnableOAuth2Client
@EnableJpaRepositories(basePackages = {"com.saman.kamal.nimalservice.repository"})
@EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
public class HuththaApplication {
    public static void main(String[] args) {
        SpringApplication.run(HuththaApplication.class, args);
    }
}
</code>```

if I use mongodb instead of mysql

```<code>@EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
</code>```

should be change. How should be change?

Below you can see my entity class.

```<code>import java.io.Serializable;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document
public class EbankLog implements Serializable {

    private static final Long serialVersionUID = 1L;

    @Id
    private String bothala;
    private String sapaththu;
    private String sereppu;
    private String kanda;
    private String bag;
}
</code>```

答:
You have not let Spring know where your MongoDb repositories are. In order to do that use @EnableMongoRepositories. See below codes:

@EnableMongoRepositories(basePackages = "your.mongodb.repositories.package")
@EnableFeignClients(basePackages = {"com.saman.kamal.nimalservice"})
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = {"com.saman.kamal.nimalservice"})
@EnableOAuth2Client
@EnableJpaRepositories(basePackages = {"com.saman.kamal.nimalservice.repository"})
@EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
public class HuththaApplication {
    public static void main(String[] args) {
        SpringApplication.run(HuththaApplication.class, args);
    }
}
```

Title: Spring boot MongoDB configuration

Body:
I'm working in a spring boot application & use both MySQL & mongodb as databases.Below you can see spring boot main application for MySQL.

@EnableFeignClients(basePackages = {"com.saman.kamal.nimalservice"})
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = {"com.saman.kamal.nimalservice"})
@EnableOAuth2Client
@EnableJpaRepositories(basePackages = {"com.saman.kamal.nimalservice.repository"})
@EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})
public class HuththaApplication {
    public static void main(String[] args) {
        SpringApplication.run(HuththaApplication.class, args);
    }
}

if I use mongodb instead of mysql

@EntityScan(basePackages = {"com.saman.kamal.nimalservice.domain"})

should be change. How should be change?

Below you can see my entity class.

import java.io.Serializable;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document
public class EbankLog implements Serializable {

    private static final Long serialVersionUID = 1L;

    @Id
    private String bothala;
    private String sapaththu;
    private String sereppu;
    private String kanda;
    private String bag;
}


问:
Flex font rendering differences from 4.1 to 4.5
I'm currently upgrading an app from Flex 4.1 to 4.5

We've noticed that the Arial font is rendered differently between the two versions when used at small sizes.

Here's a simple app example:

```<code><?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <fx:Style>
        @namespace s "library://ns.adobe.com/flex/spark";
        @namespace mx "library://ns.adobe.com/flex/mx";
        @font-face {
            src: url("/assets/fonts/ARIAL.ttf");
            fontFamily: arial;
            embedAsCFF: true;
        }
        @font-face {
            src: url("/assets/fonts/ARIALBD.ttf");
            fontFamily: arial;
            embedAsCFF: true;
            font-weight: bold;
        }
        global
        {
            font-family: arial;
        }
    </fx:Style>
    <s:Label text="Hello world" fontWeight="bold" x="20" y="20"  />
</s:Application>
</code>```

When run against the 2 different sdks, here's an image of the font rendering we get:

Note that in 4.5 the font looks slightly squashed.

What's the cause of this, and how do we resolve it?

答:
My best guess is that it's related to the changes that were made to support fonts on handheld devices. To fix it you may have to play around with your style sheet settings a bit.

CSS Media Queries

  You can now use @media rules in your style sheets to
  filter CSS rules based on the device’s
  DPI classification. There are two
  properties you can filter on
  currently, os-platform and
  application-dpi. Here’s an example of
  filtering on them to set a button font
  for instance (from Adobe’s prerelease
  docs):

```<code>@media (os-platform: "Android") and (application-dpi: 240) {
s|Button {
     fontSize: 10;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently upgrading an app from Flex 4.1 to 4.5

We've noticed that the Arial font is rendered differently between the two versions when used at small sizes.

Here's a simple app example:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <fx:Style>
        @namespace s "library://ns.adobe.com/flex/spark";
        @namespace mx "library://ns.adobe.com/flex/mx";
        @font-face {
            src: url("/assets/fonts/ARIAL.ttf");
            fontFamily: arial;
            embedAsCFF: true;
        }
        @font-face {
            src: url("/assets/fonts/ARIALBD.ttf");
            fontFamily: arial;
            embedAsCFF: true;
            font-weight: bold;
        }
        global
        {
            font-family: arial;
        }
    </fx:Style>
    <s:Label text="Hello world" fontWeight="bold" x="20" y="20"  />
</s:Application>

When run against the 2 different sdks, here's an image of the font rendering we get:

Note that in 4.5 the font looks slightly squashed.

What's the cause of this, and how do we resolve it?

Body:
My best guess is that it's related to the changes that were made to support fonts on handheld devices. To fix it you may have to play around with your style sheet settings a bit.

CSS Media Queries

  You can now use @media rules in your style sheets to
  filter CSS rules based on the device’s
  DPI classification. There are two
  properties you can filter on
  currently, os-platform and
  application-dpi. Here’s an example of
  filtering on them to set a button font
  for instance (from Adobe’s prerelease
  docs):

@media (os-platform: "Android") and (application-dpi: 240) {
s|Button {
     fontSize: 10;
}


问:
Python: Add contents of a csv file to a list
have a new issue with this that I could do with some help on.
Like before i am passing a csv (with comma as separator) into a list.
the first element in the list will always be an integer but the next two will be strings.
I'm trying to add a new line to the csv which will have an incremented number in the first element but I will also add hash strings in the other two elements.
It works on the first run as the file is empty but when it tries a second run I get an error

chain_list = [int(i) for i in lineList[-1].split(',')]

ValueError: invalid literal for int() with base 10: '9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794'

The first line of the file that i'm passing in contains:

1,0,9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794

My code looks like this at the minute. Not sure how to get around this?

#Check if chain_info.txt exists
CHAIN_FILE_exists = os.path.isfile(CHAIN_FILE)
#If chainfile is empty set element 0 in list to 1
if CHAIN_FILE_exists:
    if os.stat(CHAIN_FILE).st_size == 0:
        print('empty')
        fileHandle = open (CHAIN_FILE, 'a')
        fileHandle.write('1,0,0')
        fileHandle.close()
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        increment_value = 1
        print('1 chain list now is: ' + str(chain_list))
    else:
        #Read the last line of a file
        fileHandle = open (CHAIN_FILE)
        lineList = fileHandle.readlines()
        fileHandle.close()
        #Take last line of file and add to a list called chain_list
        chain_list = lineList[-1].split(',')
        chain_list = [int(i) for i in lineList[-1].split(',')]
        #increment the first value in the list by 1, this will be used to determine the block number
        increment_value = (chain_list[0])
        increment_value = increment_value +1
        chain_list.remove (chain_list[0])
        chain_list.insert (0,increment_value)
        print('chain list now is: ' + str(chain_list))
        #Open file
        fileHandle = open (CHAIN_FILE, 'a')
        #Write the contents of the list to the chain file on a new line and separate with a comma
        fileHandle.write('\n' + str(chain_list[0]) + ',' + str(chain_list[1]))
        fileHandle.close()
else:
    print ('file does not exist')
```

答:
Thanks to everyone for the help. Eventually got this little piece working. The first line of the file which is always 1,0,0 is being passed into a list called lineList as integers.
Then the first element of this list which has a value of 1 is incremented and printed to the screen.

import os
import io
import sys
import zipfile
import shutil
import csv
from os import path
from zipfile import ZipFile
from shutil import make_archive

#input file
chain_file = 'c:\\securelog_workfiles\\chain_info.txt'

#Check if chain_info.txt exists
chain_file_exists = os.path.isfile(chain_file)
if chain_file_exists:
    if os.stat(chain_file).st_size == 0:
        print('empty')
        fileHandle = open (chain_file, 'a')
        fileHandle.write('1,0,0')
        fileHandle.close()
    else:
        #Read the last line of a file
        fileHandle = open (chain_file)
        lineList = fileHandle.readlines()
        fileHandle.close()
        print (lineList)
        print ("The last line is:")
        print (lineList[-1])

        #split the line into separate values using the comma as the delimeter
        chain_list = lineList[-1].split(',')

        #convert the string characters from the file into integers before adding
        #to the list
        chain_list = [int(i) for i in lineList[-1].split(',')]
        print (chain_list)

        #increment 1 to 2
        increment_value = (chain_list[0])
        increment_value = increment_value +1

        #remove the first element from the list
        chain_list.remove (chain_list[0])
        #verifying that the 1st element was removd
        print (chain_list)

        #insert the incremented value into the list
        chain_list.insert (0,increment_value)
        print('chain list now is: ' + str(chain_list))

else:
    print ('file does not exist')
```


问:
upgrade to angular 8 from 7 errors with incompatible peer dependency
ng update @angular/cli @angular/core . -  Getting the below error when upgrading from 7 to 8, following the guide from https://update.angular.io/#7.0:8.0</p>

```<code>> "@angular/core" (requires "^6.0.0" (extended), would install "8.0.0").```

Incompatible peer dependencies found. See above.

package.json has the below versions

"dependencies": {
    "@angular/animations": "^7.0.4",
    "@angular/common": "^7.0.3",
    "@angular/compiler": "^7.0.3",
    "@angular/core": "^7.0.3",
    "@angular/forms": "^7.0.3",
    "@angular/http": "^7.0.3",
    .....
    ````

</code>```

答: Looks like @ngrx/store does not yet have a released version that supports angular 8. You would have to use their latest beta version, 8.0.0-beta.2 (2019-05-15), if you wanted to upgrade or wait until they release version 8.

Body:
ng update @angular/cli @angular/core . -  Getting the below error when upgrading from 7 to 8, following the guide from https://update.angular.io/#7.0:8.0

> "@angular/core" (requires "^6.0.0" (extended), would install "8.0.0").```

Incompatible peer dependencies found. See above.

package.json has the below versions

"dependencies": {
    "@angular/animations": "^7.0.4",
    "@angular/common": "^7.0.3",
    "@angular/compiler": "^7.0.3",
    "@angular/core": "^7.0.3",
    "@angular/forms": "^7.0.3",
    "@angular/http": "^7.0.3",
    .....
    ````


问:
"Trying to get property of non-object" error in calling a library function
I am writing a test function to read the number of pages in a PDF file. I have tried various methods, but the one I am working on now is giving me an error (Trying to get property of non-object) and I can't figure out why.

```<code>function testPageCount()
{
    $this->CI->load->library('Awss3', null, 'S3'); <-- this is where I get the error
    $this->CI->load->library('pdflib');
    $data = $this->CI->S3->readFile('uploads/171465/name.pdf', false, self::BUCKET);
    echo $data;

}
</code>```

I have looked through all the code and everywhere else this library call is used, it's called exactly the same way. Any help or insight would be much appreciated.

EDIT: This is all the code in the function. I have not left anything out.

答:
I added the following and that solved this problem:</p>

```<code>$CI = &get_instance();
$CI->load->library('Awss3', null, 'S3');
$CI->load->library('Pdflib');
$data = $CI->S3->readFile('uploads/171465/name.pdf', false, self::BUCKET);
</code>```

Body:
I am writing a test function to read the number of pages in a PDF file. I have tried various methods, but the one I am working on now is giving me an error (Trying to get property of non-object) and I can't figure out why.

function testPageCount()
{
    $this->CI->load->library('Awss3', null, 'S3'); <-- this is where I get the error
    $this->CI->load->library('pdflib');
    $data = $this->CI->S3->readFile('uploads/171465/name.pdf', false, self::BUCKET);
    echo $data;

}

I have looked through all the code and everywhere else this library call is used, it's called exactly the same way. Any help or insight would be much appreciated.

EDIT: This is all the code in the function. I have not left anything out.

Body:
I added the following and that solved this problem:

$CI = &get_instance();
$CI->load->library('Awss3', null, 'S3');
$CI->load->library('Pdflib');
$data = $CI->S3->readFile('uploads/171465/name.pdf', false, self::BUCKET);


问:
Parsing JSON and displaying in a RecyclerView
Feedback App

```<code>    String url = "http://www.dohagarage.com/api/v1/sample";

    JsonObjectRequest request = new
   JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("data");

                        for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject hit = jsonArray.getJSONObject(i);

        String naame = hit.getString("question");

        mExampleList.add(new ExampleItem(naame));
                        } mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);mRecyclerView.setAdapter(mExampleAdapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mRequestQueue.add(request);
}
</code>```

This is the code I used to show the questions using json in a RecyclerView. I want show the options in a radio button.

答: Please provide more code to better understand but i think you didn't set Layout Manager to RecyclerView</p>

Body:
Feedback App

    String url = "http://www.dohagarage.com/api/v1/sample";

    JsonObjectRequest request = new
   JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("data");

                        for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject hit = jsonArray.getJSONObject(i);

        String naame = hit.getString("question");

        mExampleList.add(new ExampleItem(naame));
                        } mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);mRecyclerView.setAdapter(mExampleAdapter);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });
    mRequestQueue.add(request);
}

This is the code I used to show the questions using json in a RecyclerView. I want show the options in a radio button.


问:
Get key value from string using Powershell
I am trying to get key value using Regex in powershell.

```<code>$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name
</code>```

I want output like this :

```<code>$key1 = "value1"
$key2 = "value2"
$key3 = "value3"
</code>```

Output i am getting :

```<code>Name : :value1,key2:value2,
</code>```

答:
Pretty sure that sysg0blin's helpful answer can do the job, but if you really want to set specific variables this can be done with such script:

```<code>$string = "key1:value1,key2:value2,key3:value3"
$splitted = $string -split ','
$splitted | ForEach-Object {
  $i = $_ -split ":"
  Set-Variable -Name $i[0] -Value $i[1]
}
</code>```

What you do here is to split string into array of key:value pair and then split each pair into array with 2 elements, first being variable name and second being value of the variable.

Body:
I am trying to get key value using Regex in powershell.

$string = "key1:value1,key2:value2,key3:value3"
$name = [Regex]::Matches($string, ':([^/]+),') | Select -ExpandProperty Value
Write-Host "Name :" $name

I want output like this :

$key1 = "value1"
$key2 = "value2"
$key3 = "value3"

Output i am getting :

Name : :value1,key2:value2,

Body:
Pretty sure that sysg0blin's helpful answer can do the job, but if you really want to set specific variables this can be done with such script:

$string = "key1:value1,key2:value2,key3:value3"
$splitted = $string -split ','
$splitted | ForEach-Object {
  $i = $_ -split ":"
  Set-Variable -Name $i[0] -Value $i[1]
}

What you do here is to split string into array of key:value pair and then split each pair into array with 2 elements, first being variable name and second being value of the variable.


问:
Angular 8 with Ivy how to verify it is used
Today I installed Angular 8 final version.

npm install -g @angular/cli

Generated a simple app with:

```<code>ng new sampleApp
</code>```

On https://angular.io/guide/ivy site I found that I have to modify tsconfig.app.json file to enable Ivy. Like this:

```<code>"angularCompilerOptions": {
    "enableIvy": true
}
</code>```

My question is after I perform build how can I verify that Ivy is in place and used as a rendering engine?

答:
When you set enableIvy to true

```<code>...
"angularCompilerOptions": {
  "enableIvy": true
}
...
</code>```

then ngcc command is executed by running ng serve or ng build. You can recognize it in the console easily because it will start printing out something like this

```<code>Compiling @angular/core : es2015 as esm2015

Compiling @angular/common : es2015 as esm2015

Compiling @angular/platform-browser : es2015 as esm2015

...
</code>```

The seconds possible way is by checking bundle size as it was mentioned in comments.

Also there is a short paragraph about Ivy and Bazel on Angular blog that we will get more info about Ivy next week.

We know there’s lots of excitement for our forthcoming opt-in
  previews. We’ll be providing individual updates on these next week on
  this blog, so stay tuned!

Body:
Today I installed Angular 8 final version.

npm install -g @angular/cli

Generated a simple app with:

ng new sampleApp

On https://angular.io/guide/ivy site I found that I have to modify tsconfig.app.json file to enable Ivy. Like this:

"angularCompilerOptions": {
    "enableIvy": true
}

My question is after I perform build how can I verify that Ivy is in place and used as a rendering engine?

Body:
When you set enableIvy to true

...
"angularCompilerOptions": {
  "enableIvy": true
}
...

then ngcc command is executed by running ng serve or ng build. You can recognize it in the console easily because it will start printing out something like this

Compiling @angular/core : es2015 as esm2015

Compiling @angular/common : es2015 as esm2015

Compiling @angular/platform-browser : es2015 as esm2015

...

The seconds possible way is by checking bundle size as it was mentioned in comments.

Also there is a short paragraph about Ivy and Bazel on Angular blog that we will get more info about Ivy next week.

We know there’s lots of excitement for our forthcoming opt-in
  previews. We’ll be providing individual updates on these next week on
  this blog, so stay tuned!


问:
Why does POST Request return 404
I have this code snippet in PHP:

```<code>if (strcasecmp($_POST['method'], 'assignId') == 0) {
$username = $_POST['username'];

$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$sql = "CALL new_person('$username')";

if (($result = $conn->query($sql)) === TRUE) {
    $row = $result->fetch_assoc();
    $response['data'] = $row;
}
deliver_response($response);
</code>```

new_person is a stored procedure which returns an id, it has been tested and works fine and deliver_response returns JSON format of the input. It has also been tested and works fine.

Why do POST Requests return 404 error?

The stored procedure is being executed, but it doesn't return the result. Finally, when I change the POST method to GET and make a get request instead it works fine!

答:
Prefix everything, especially your variables. The names you are using are used by WordPress internally (see the comment form), so WordPress might try to do something with your form values. If that fails you get an error.

While $_GET problems are usually rather easy to debug, $_POST and $_REQUEST names are not so simple.

The following list is probably not complete. But its bare length tells us a lesson:

Avoid any name you can find in a dictionary. Prefix your form names.

List of reserved names in $_POST and $_REQUEST used by WordPress 3.5

These names might have side effects when used in themes or plugins. Some are used on specific pages only (removeheader), others on multiple pages or requests. Avoid them all if you can.

_ajax_nonce
_page
_per_page
_signup_form
_total
_url
_wp_http_referer
_wp_original_http_referer
_wp_unfiltered_html_comment
_wpnonce
_wpnonce-custom-header-upload

aa
action
action2
active_post_lock
add_new
add_new_users
addmeta
admin_bar_front
admin_color
admin_email
admin_password
admin_password2
ajax
align
allblogs
allusers
alt
approve_parent
approved
attachment
attachment_id
attachments
auth_cookie
author
author_name
autocomplete_type
auto_draft
auto-add-pages
autosave

background-attachment
background-color
background-position-x
background-repeat
banned_email_domains
blog
blog_name
blog_public
blog_upload_space
blogname
bulk_edit

c
calendar
cat
category_base
category_name
catslist
changeit
changes
charset
checkbox
checked
clear-recent-list
closed
comment
comment_approved
comment_author
comment_author_email
comment_author_url
comment_content
comment_date
comment_ID
comment_parent
comment_post_ID
comment_shortcuts
comment_status
comments_listing
comments_popup
confirmdelete
connection_type
content
context
cpage
create-new-attachment
createuser
customize_messenger_channel
customized
customlink-tab

date
date_format
date_format_custom
day
default-header
delete
delete_all
delete_all2
delete_comments
delete_option
delete_tags
delete_widget
deletebookmarks
deletecomment
deleted
deletemeta
deletepost
description
detached
dismiss
display_name
do

edit_date
email
error
exact
excerpt

features
feed
fetch
fheight
file
fileupload_maxk
filter
find_detached
first_comment
first_comment_author
first_comment_url
first_name
first_page
first_post
found_post_id
fwidth

global_terms_enabled
GLOBALS
gmt_offset
guid

height
hh
hidden
hidden_aa
hidden_jj
hidden_mm
hidden_mn
hidden_hh
history
hostname
hour
html-upload

id
ID
ids
id_base
illegal_names
insert-gallery
insertonlybutton
interim-login
item-object
item-type

jj
json
json_data

key

last_name
limited_email_domains
link_id
link_image
link_name
link_rss
link_url
link_visible
linkcheck
locale
locked
log
logged_in_cookie

m
media
media_type
menu
menu_items
menu-item
menu-item-attr-title
menu-item-classes
menu-item-db-id
menu-item-description
menu-item-object
menu-item-object-id
menu-item-parent-id
menu-item-position
menu-item-target
menu-item-title
menu-item-type
menu-item-url
menu-item-xfn
menu-locations
menu-name
message
meta
metakeyinput
metakeyselect
metavalue
minute
mm
mn
mode
monthnum
more
move
multi_number

name
nav-menu-locations
new
new_role
new_slug
new_title
newcat
newcomment_author
newcomment_author_email
newcomment_author_url
newcontent
newuser
nickname
no_placeholder
noapi
noconfirmation
noredir
number

offset
oitar
option
option_page
order
orderby

p
pb
page
page_columns
page_id
page_options
paged
pagegen_timestamp
pagename
parent_id
pass1
pass2
password
permalink_structure
photo_description
photo_src
phperror
ping_status
plugin
plugin_status
pointer
position
post
post_category
post_data
post_format
post_ID
post_id
post_mime_type
post_password
post_status
post_title
post_type
post_view
postid
posts
preview
primary_blog
private_key
ps
public_key
publish
pwd

query

reassign_user
reauth
redirect
redirect_to
ref
referredby
registration
registrationnotification
rememberme
remove-background
removeheader
removewidget
reset-background
resetheader
review
rich_editing
robots
role

s
same
save
savewidget
savewidgets
screen
scrollto
search
second
section
selectall
selection
send
send_password
sentence
short
show_sticky
sidebar
sidebars
signup_for
signup_form_id
site_id
site_name
sitename
size
skip-cropping
spam
spammed
src
ss
stage
start
static
status
sticky
subdomain_install
submit
subpost
subpost_id
super_admin

tab
tag
tag_ID
tag-name
tag_base
tags_input
tax
tax_input
tag-name
target
taxonomy
tb
term
text-color
the-widget-id
theme
theme_status
thumb
timezone_string
time_format
time_format_custom
title
thumbnail_id
trash
trashed
type

undismiss
unspam
unspammed
untrash
untrashed
url
update_home_url
updated
upgrade
upload_filetypes
upload_space_check_disabled
use_ssl
user
user_id
user_login
user_name
username
users

verify-delete
version
visibility
visible

w
weblog_title
welcome_email
welcome_user_email
widget_id
widget_number
widget-id
widget-recent-comments
widget-rss
width
withcomments
withoutcomments
wp_customize
wp_http_referer
wp_screen_options
wp-preview
WPLANG

x1

y1
year
```

<h2>Variable names</h2>

<pre class="lang-none prettyprint-override"><code>$method // Filter: 'user_contactmethods'
$post_type_name . -tab
$sidebar_id . _position
$taxonomy_name . -tab
$whitelist_options // Filter: 'whitelist_options'

__i__ . $something // used in widgets
new . $taxonomy->name
new . $taxonomy->name . _parent
quick-search-posttype- . $post_type_name
quick-search-taxonomy- . $taxonomy_name
widget- . $id_base
</code>```

Credit : fuxia

Title: Why does POST Request return 404

Body:
I have this code snippet in PHP:

if (strcasecmp($_POST['method'], 'assignId') == 0) {
$username = $_POST['username'];

$response['code'] = 1;
$response['status'] = $api_response_code[$response['code']]['HTTP Response'];
$sql = "CALL new_person('$username')";

if (($result = $conn->query($sql)) === TRUE) {
    $row = $result->fetch_assoc();
    $response['data'] = $row;
}
deliver_response($response);

new_person is a stored procedure which returns an id, it has been tested and works fine and deliver_response returns JSON format of the input. It has also been tested and works fine.

Why do POST Requests return 404 error?

The stored procedure is being executed, but it doesn't return the result. Finally, when I change the POST method to GET and make a get request instead it works fine!

Body:
Prefix everything, especially your variables. The names you are using are used by WordPress internally (see the comment form), so WordPress might try to do something with your form values. If that fails you get an error.

While $_GET problems are usually rather easy to debug, $_POST and $_REQUEST names are not so simple.

The following list is probably not complete. But its bare length tells us a lesson:

Avoid any name you can find in a dictionary. Prefix your form names.

List of reserved names in $_POST and $_REQUEST used by WordPress 3.5

These names might have side effects when used in themes or plugins. Some are used on specific pages only (removeheader), others on multiple pages or requests. Avoid them all if you can.

_ajax_nonce
_page
_per_page
_signup_form
_total
_url
_wp_http_referer
_wp_original_http_referer
_wp_unfiltered_html_comment
_wpnonce
_wpnonce-custom-header-upload

aa
action
action2
active_post_lock
add_new
add_new_users
addmeta
admin_bar_front
admin_color
admin_email
admin_password
admin_password2
ajax
align
allblogs
allusers
alt
approve_parent
approved
attachment
attachment_id
attachments
auth_cookie
author
author_name
autocomplete_type
auto_draft
auto-add-pages
autosave

background-attachment
background-color
background-position-x
background-repeat
banned_email_domains
blog
blog_name
blog_public
blog_upload_space
blogname
bulk_edit

c
calendar
cat
category_base
category_name
catslist
changeit
changes
charset
checkbox
checked
clear-recent-list
closed
comment
comment_approved
comment_author
comment_author_email
comment_author_url
comment_content
comment_date
comment_ID
comment_parent
comment_post_ID
comment_shortcuts
comment_status
comments_listing
comments_popup
confirmdelete
connection_type
content
context
cpage
create-new-attachment
createuser
customize_messenger_channel
customized
customlink-tab

date
date_format
date_format_custom
day
default-header
delete
delete_all
delete_all2
delete_comments
delete_option
delete_tags
delete_widget
deletebookmarks
deletecomment
deleted
deletemeta
deletepost
description
detached
dismiss
display_name
do

edit_date
email
error
exact
excerpt

features
feed
fetch
fheight
file
fileupload_maxk
filter
find_detached
first_comment
first_comment_author
first_comment_url
first_name
first_page
first_post
found_post_id
fwidth

global_terms_enabled
GLOBALS
gmt_offset
guid

height
hh
hidden
hidden_aa
hidden_jj
hidden_mm
hidden_mn
hidden_hh
history
hostname
hour
html-upload

id
ID
ids
id_base
illegal_names
insert-gallery
insertonlybutton
interim-login
item-object
item-type

jj
json
json_data

key

last_name
limited_email_domains
link_id
link_image
link_name
link_rss
link_url
link_visible
linkcheck
locale
locked
log
logged_in_cookie

m
media
media_type
menu
menu_items
menu-item
menu-item-attr-title
menu-item-classes
menu-item-db-id
menu-item-description
menu-item-object
menu-item-object-id
menu-item-parent-id
menu-item-position
menu-item-target
menu-item-title
menu-item-type
menu-item-url
menu-item-xfn
menu-locations
menu-name
message
meta
metakeyinput
metakeyselect
metavalue
minute
mm
mn
mode
monthnum
more
move
multi_number

name
nav-menu-locations
new
new_role
new_slug
new_title
newcat
newcomment_author
newcomment_author_email
newcomment_author_url
newcontent
newuser
nickname
no_placeholder
noapi
noconfirmation
noredir
number

offset
oitar
option
option_page
order
orderby

p
pb
page
page_columns
page_id
page_options
paged
pagegen_timestamp
pagename
parent_id
pass1
pass2
password
permalink_structure
photo_description
photo_src
phperror
ping_status
plugin
plugin_status
pointer
position
post
post_category
post_data
post_format
post_ID
post_id
post_mime_type
post_password
post_status
post_title
post_type
post_view
postid
posts
preview
primary_blog
private_key
ps
public_key
publish
pwd

query

reassign_user
reauth
redirect
redirect_to
ref
referredby
registration
registrationnotification
rememberme
remove-background
removeheader
removewidget
reset-background
resetheader
review
rich_editing
robots
role

s
same
save
savewidget
savewidgets
screen
scrollto
search
second
section
selectall
selection
send
send_password
sentence
short
show_sticky
sidebar
sidebars
signup_for
signup_form_id
site_id
site_name
sitename
size
skip-cropping
spam
spammed
src
ss
stage
start
static
status
sticky
subdomain_install
submit
subpost
subpost_id
super_admin

tab
tag
tag_ID
tag-name
tag_base
tags_input
tax
tax_input
tag-name
target
taxonomy
tb
term
text-color
the-widget-id
theme
theme_status
thumb
timezone_string
time_format
time_format_custom
title
thumbnail_id
trash
trashed
type

undismiss
unspam
unspammed
untrash
untrashed
url
update_home_url
updated
upgrade
upload_filetypes
upload_space_check_disabled
use_ssl
user
user_id
user_login
user_name
username
users

verify-delete
version
visibility
visible

w
weblog_title
welcome_email
welcome_user_email
widget_id
widget_number
widget-id
widget-recent-comments
widget-rss
width
withcomments
withoutcomments
wp_customize
wp_http_referer
wp_screen_options
wp-preview
WPLANG

x1

y1
year

Variable names

$method // Filter: 'user_contactmethods'
$post_type_name . -tab
$sidebar_id . _position
$taxonomy_name . -tab
$whitelist_options // Filter: 'whitelist_options'

__i__ . $something // used in widgets
new . $taxonomy->name
new . $taxonomy->name . _parent
quick-search-posttype- . $post_type_name
quick-search-taxonomy- . $taxonomy_name
widget- . $id_base

Credit : fuxia


问:
Why Firefox and other browsers freeze while I'm trying to initialize multiple components but not on Chrome?
On Firefox (version 67.0), I have a grid table to display data. I use a forEach() to create columns and rows from JSON data for the grid table. It's about 100 rows, 10 columns. During the creating row & column iteration, the browser is freezing, I can't do anything on the webpage. After the iteration, everything back to normal.

I have tried to do the same on different browsers: IE, Edge, Chrome (newest version). The freezing problem exists on IE, Edge excepts Chrome. During the iteration on Chrome, I can do other tasks on the webpage e.g click on a button, hover on columns, etc.

Why doesn't it happen on Chrome? Is it because Chrome uses a different engine?
How can I overcome this issue?

```<code>function initGridComponents() {
  let records = data.items;
  records.forEach((record) => {
    createColumnsType1(record);
    createColumnsType2(record);
    createColumnsType3(record);
  });
}
</code>```

I expect it will work normally among browsers with freezing.

答:
You can utilise the event queue to space out the operations and thus make your page more responsive while loading:

function initGridComponents() {
  let records = data.items;
  records.forEach((record) => {

    setTimeout(createColumnsType1, 0, record);
//             ^^^^^^^^^^^^^^^^^^     ^^^^^^
//               function handle     parameter
    setTimeout(createColumnsType2, 0, record);
    setTimeout(createColumnsType3, 0, record);
  });
}
```

Body:
On Firefox (version 67.0), I have a grid table to display data. I use a forEach() to create columns and rows from JSON data for the grid table. It's about 100 rows, 10 columns. During the creating row & column iteration, the browser is freezing, I can't do anything on the webpage. After the iteration, everything back to normal.

I have tried to do the same on different browsers: IE, Edge, Chrome (newest version). The freezing problem exists on IE, Edge excepts Chrome. During the iteration on Chrome, I can do other tasks on the webpage e.g click on a button, hover on columns, etc.

Why doesn't it happen on Chrome? Is it because Chrome uses a different engine?
How can I overcome this issue?

function initGridComponents() {
  let records = data.items;
  records.forEach((record) => {
    createColumnsType1(record);
    createColumnsType2(record);
    createColumnsType3(record);
  });
}

I expect it will work normally among browsers with freezing.


问:
What apiGroups and resources exist for RBAC rules in kubernetes?
```<code>apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: xi-{{instanceId}}
  name: deployment-creation
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["batch", "extensions"]
  resources: ["jobs"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
</code>```

In the above example, I permit various operations on pods and jobs.
For pods, the apiGroup is blank. For jobs, the apiGroup may be batch or extensions.
Where can I find all the possible resources, and which apiGroup I should use with each resource?

答: kubectl api-resources will list all the supported resource types and api-group. Here is the table of resource-types

Body:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: xi-{{instanceId}}
  name: deployment-creation
rules:
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["batch", "extensions"]
  resources: ["jobs"]
  verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]

In the above example, I permit various operations on pods and jobs.
For pods, the apiGroup is blank. For jobs, the apiGroup may be batch or extensions.
Where can I find all the possible resources, and which apiGroup I should use with each resource?


问:
Unable to parse array of dictionary inside string
Currently I am working on bus booking module. After user set his departure and arrival city and date of journey, user will be shown a list of available buses. I have done that part successfully. But the problem which I am facing is that, each bus has it's own cancellation policy which is array of dictionary inside string. I am unable to parse it. Inside every dictionary of "apiAvailableBuses" there is "cancellationPolicy" key which has string as value which contains array of dictionary. I have removed other key value pairs from "apiAvailableBuses".

List of available Buses JSON response:

```<code>"apiAvailableBuses":[
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"9-12\",\"refundInPercentage\":\"25\"},{\"cutoffTime\":\"12-24\",\"refundInPercentage\":\"35\"},{\"cutoffTime\":\"24-48\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"48-60\",\"refundInPercentage\":\"75\"},{\"cutoffTime\":\"60\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"6-24\",\"refundInPercentage\":\"70\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"85\"}]"
   }
]
</code>```

Can anyone help me with a solution for this? If anyone can't understand my question please let me know.

Note: I am not using Codable in my project.

Thanks in advance.

答:
Use Codable to parse the above JSON response.

If your JSON response have the below format:

```<code>{
  "apiAvailableBuses": [
    {
      "cancellationPolicy": [
        {
          "cutoffTime": "5",
          "refundInPercentage": "90"
        }
      ]
    }
  ]
}
</code>```

Create Codable types to parse the above response.

```<code>struct AvailableBuses: Codable {
    var apiAvailableBuses: [Bus]
}

struct Bus: Codable {
    var cancellationPolicy: [CancellationPolicy]
}

struct CancellationPolicy: Codable {
    var cutoffTime: String
    var refundInPercentage: String
}
</code>```

In the above code, I've created 3 struct conforming to Codable protocol - AvailableBuses, Bus, CancellationPolicy

Usage:

After getting data from your API response, you can parse the it using the above created structs like,

```<code>if let data = jsonStr.data(using: .utf8) {
    do {
        let availableBuses = try JSONDecoder().decode(AvailableBuses.self, from: data)
        print(availableBuses)
    } catch {
        print(error)
    }
}
</code>```

Body:
Currently I am working on bus booking module. After user set his departure and arrival city and date of journey, user will be shown a list of available buses. I have done that part successfully. But the problem which I am facing is that, each bus has it's own cancellation policy which is array of dictionary inside string. I am unable to parse it. Inside every dictionary of "apiAvailableBuses" there is "cancellationPolicy" key which has string as value which contains array of dictionary. I have removed other key value pairs from "apiAvailableBuses".

List of available Buses JSON response:

"apiAvailableBuses":[
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"9-12\",\"refundInPercentage\":\"25\"},{\"cutoffTime\":\"12-24\",\"refundInPercentage\":\"35\"},{\"cutoffTime\":\"24-48\",\"refundInPercentage\":\"50\"},{\"cutoffTime\":\"48-60\",\"refundInPercentage\":\"75\"},{\"cutoffTime\":\"60\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"5\",\"refundInPercentage\":\"90\"}]"
   },
   {
      "cancellationPolicy":"[{\"cutoffTime\":\"6-24\",\"refundInPercentage\":\"70\"},{\"cutoffTime\":\"24\",\"refundInPercentage\":\"85\"}]"
   }
]

Can anyone help me with a solution for this? If anyone can't understand my question please let me know.

Note: I am not using Codable in my project.

Thanks in advance.

Body:
Use Codable to parse the above JSON response.

If your JSON response have the below format:

{
  "apiAvailableBuses": [
    {
      "cancellationPolicy": [
        {
          "cutoffTime": "5",
          "refundInPercentage": "90"
        }
      ]
    }
  ]
}

Create Codable types to parse the above response.

struct AvailableBuses: Codable {
    var apiAvailableBuses: [Bus]
}

struct Bus: Codable {
    var cancellationPolicy: [CancellationPolicy]
}

struct CancellationPolicy: Codable {
    var cutoffTime: String
    var refundInPercentage: String
}

In the above code, I've created 3 struct conforming to Codable protocol - AvailableBuses, Bus, CancellationPolicy

Usage:

After getting data from your API response, you can parse the it using the above created structs like,

if let data = jsonStr.data(using: .utf8) {
    do {
        let availableBuses = try JSONDecoder().decode(AvailableBuses.self, from: data)
        print(availableBuses)
    } catch {
        print(error)
    }
}


问:
Can I pass custom data in the HTTP header?
I have a whole bunch of web services each with several web methods. The consumers of these services are varied and many. I want to augment each of these web methods with an extra optional parameter (Int64 or Int32) but adding new methods with this extra (optional parameter) is a lot of work and getting the clients to use the new methods will be even more time consuming.

So I was wondering if I could allow the clients that wanted to take advantage of the new feature that this param provides could pass this Int in the HTTP header or some other way.

So the first question is can I pass an int in the HTTP header? If so, how would one do that in C#/ASP.NET?

Otherwise, what other suggestions do you have for tackling this problem?

答:
I've used this concept once to handle logout redirect for ajax calls in an intranet web application (nothing related to webservice).

it was my best solution at hand, but as some other have said it depends if you can push the constraint to clients to treat theses headers for your purpose.

Definitely not a thing you would want to do by default.

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: smoothdeveloper


问:
The output from calling New-AzureRmVm is inaccessible until it is returned to caller
When calling New-AzureRMVM, the Output includes an object that represents the VM that is created, but the object is inaccessible until I'm outside the function.

In the code snippet below, while inside the function Create-VM, the output ($newVM.Name)  is $null. But if I return $newVM to the caller, then $V.Name contains a value.

# PSVersion                      5.1.17763.503

Function Create-VM
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$vmName

        # and some others ...
    )

    # Snipped
    try
    {
        $newVM =  New-AzureRMVM -ResourceGroupName $vmResourceGroup # ...
        Write-Host "newVM.IsSuccessStatusCode = $($newVM.IsSuccessStatusCode)"
        Write-Host "newVM.Name  = $($newVM.Name)"
        return $newVM
    }
    catch
    {
        # Snipped
    }

}

$vmName ="testvm1"
$V = Create-VM  -vmName $vmName # ....
if ($V)
{
    Write-Host $V.GetType() # why does this return System.Object[]?
    Write-Host "V.IsSuccessStatusCode = $($V.IsSuccessStatusCode)"
    Write-Host "V.Name  = $($V.Name)"  # why does this return a value???
}
```

<p>The output looks like this: </p>

```WARNING: New-AzureRmVM: A property of the output of this cmdlet will change in an upcoming breaking change release. The StorageAccountType property
for a DataDisk will return Standard_LRS and Premium_LRS
newVM.IsSuccessStatusCode = True
newVM.Name  =
System.Object[]
V.IsSuccessStatusCode = True
V.Name  = testvm1
```

Stepping through this code in a debugger, we can see that $newVM is a single object of type  "PSAzureOperationResponse" object when inside the Create-VM function, but when it is returned to the caller, it becomes an System.Object[] array of two objects :

$V[0] is type "PSAzureOperationResponse"

$V[1] is type "PSVirtualMachine"

That is why $newVM.Name returns $null but $V.Name returns the name property of the VM object ("testvm1")

Can someone explain how this works? There must be some weird output binding going on.

PS. A new VM is indeed correctly created!

答:
I tried to execute the script provided above (with minor changes) on my machine running the same version of Powershell 5.1.17763.503 and AzureRM version 6.13.1, and was able to access the newVM object fine within the Create-VM function and post return as well. Here is the script and the output:

```<code># PSVersion                      5.1.17763.503
# AzureRM                        6.13.1

Function Create-VM
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$vmName

        # and some others ...
    )

    # Snipped
    try
    {
        $newVM =  New-AzureRMVM -ResourceGroupName $ResourceGroupName # ...
        Write-Host "`nnewVM.StatusCode = $($newVM.StatusCode)" # StatusCode is the property
        Write-Host "newVM.Name = $($newVM.Name)"
        Write-Host $newVM.GetType()
        return $newVM
    }
    catch
    {
        Write-Host "in the catch block"
    }

}

$vmName ="testvm1"
$V = Create-VM -vmName $vmName # ....
if ($V)
{
    Write-Host "`nOut of Create-VM"
    Write-Host $V.GetType()
    Write-Host "V.StatusCode = $($V.StatusCode)"
    Write-Host "V.Name  = $($V.Name)"
}
</code>```

Output:

```<code>Supply values for the following parameters:
Name: testvm0

newVM.StatusCode = 0
newVM.Name = testvm0
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine

Out of Create-VM
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine
V.StatusCode = 0
V.Name  = testvm0
</code>```

Can you try upgrading to the latest version of AzureRM and check if it helps? If not, you might add wait/sleep period for a few seconds.

Body:
When calling New-AzureRMVM, the Output includes an object that represents the VM that is created, but the object is inaccessible until I'm outside the function.

In the code snippet below, while inside the function Create-VM, the output ($newVM.Name)  is $null. But if I return $newVM to the caller, then $V.Name contains a value.

# PSVersion                      5.1.17763.503

Function Create-VM
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$vmName

        # and some others ...
    )

    # Snipped
    try
    {
        $newVM =  New-AzureRMVM -ResourceGroupName $vmResourceGroup # ...
        Write-Host "newVM.IsSuccessStatusCode = $($newVM.IsSuccessStatusCode)"
        Write-Host "newVM.Name  = $($newVM.Name)"
        return $newVM
    }
    catch
    {
        # Snipped
    }

}

$vmName ="testvm1"
$V = Create-VM  -vmName $vmName # ....
if ($V)
{
    Write-Host $V.GetType() # why does this return System.Object[]?
    Write-Host "V.IsSuccessStatusCode = $($V.IsSuccessStatusCode)"
    Write-Host "V.Name  = $($V.Name)"  # why does this return a value???
}

The output looks like this:

WARNING: New-AzureRmVM: A property of the output of this cmdlet will change in an upcoming breaking change release. The StorageAccountType property
for a DataDisk will return Standard_LRS and Premium_LRS
newVM.IsSuccessStatusCode = True
newVM.Name  =
System.Object[]
V.IsSuccessStatusCode = True
V.Name  = testvm1

Stepping through this code in a debugger, we can see that $newVM is a single object of type  "PSAzureOperationResponse" object when inside the Create-VM function, but when it is returned to the caller, it becomes an System.Object[] array of two objects :

$V[0] is type "PSAzureOperationResponse"

$V[1] is type "PSVirtualMachine"

That is why $newVM.Name returns $null but $V.Name returns the name property of the VM object ("testvm1")

Can someone explain how this works? There must be some weird output binding going on.

PS. A new VM is indeed correctly created!

Body:
I tried to execute the script provided above (with minor changes) on my machine running the same version of Powershell 5.1.17763.503 and AzureRM version 6.13.1, and was able to access the newVM object fine within the Create-VM function and post return as well. Here is the script and the output:

# PSVersion                      5.1.17763.503
# AzureRM                        6.13.1

Function Create-VM
{
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$vmName

        # and some others ...
    )

    # Snipped
    try
    {
        $newVM =  New-AzureRMVM -ResourceGroupName $ResourceGroupName # ...
        Write-Host "`nnewVM.StatusCode = $($newVM.StatusCode)" # StatusCode is the property
        Write-Host "newVM.Name = $($newVM.Name)"
        Write-Host $newVM.GetType()
        return $newVM
    }
    catch
    {
        Write-Host "in the catch block"
    }

}

$vmName ="testvm1"
$V = Create-VM -vmName $vmName # ....
if ($V)
{
    Write-Host "`nOut of Create-VM"
    Write-Host $V.GetType()
    Write-Host "V.StatusCode = $($V.StatusCode)"
    Write-Host "V.Name  = $($V.Name)"
}

Output:

Supply values for the following parameters:
Name: testvm0

newVM.StatusCode = 0
newVM.Name = testvm0
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine

Out of Create-VM
Microsoft.Azure.Commands.Compute.Models.PSVirtualMachine
V.StatusCode = 0
V.Name  = testvm0

Can you try upgrading to the latest version of AzureRM and check if it helps? If not, you might add wait/sleep period for a few seconds.