问:
How do I know which groups each product is in?
```<code>class Product(models.Model):
    name = models.CharField(max_length=256)

class Group(models.Model):
    name = models.CharField(max_length=32, unique=False)
    products = models.ManyToManyField(Product, blank=True)
</code>```

Products in group.pk == 1:

```<code>products = Group.objects.get(pk=1).products.all().values('name')
</code>```

Result:

```<code><QuerySet [
    {"name": "product1"},
    {"name": "product2"},
    {"name": "product3"},
]
</code>```

How do I know which groups each product is in? Like this:

```<code><QuerySet [
    {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]},
    {"name": "product2", "groups": []"},
    {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}},
]
</code>```

Thanks!

UPD1.

If we have data:

```<code>group1 | product 1
group1 | product 2
group2 | product 2
group2 | product 3
</code>```

The idea of creating a table (html) is as follows:

/group/1:

```<code>product 1 | dropdown (group1)
product 2 | dropdown (group1, group2)
</code>```

/group/2:

```<code>product 2 | dropdown (group1, group2)
product 3 | dropdown (group2)
</code>```

答:
model.py:

```<code>context['products'] = Group.objects.get(pk=1).products.all()
return render(request, 'template.html', context)
</code>```

template.html:

```<code>{% for product in products %}
    {{ product.name }}

    COUNT: {{ product.group_set.count }}
    <ul>
        {% for group in product.group_set.all %}
            <li>{{ group.name }}</li>
        {% endfor %}
    </ul>
{% endfor %}
</code>```

The solution was not difficult, it got confused because of:

```<code>{% for group in slave_product.group_set.all() %} # ()
</code>```

Thanks to all!

Body:
class Product(models.Model):
    name = models.CharField(max_length=256)

class Group(models.Model):
    name = models.CharField(max_length=32, unique=False)
    products = models.ManyToManyField(Product, blank=True)

Products in group.pk == 1:

products = Group.objects.get(pk=1).products.all().values('name')

Result:

<QuerySet [
    {"name": "product1"},
    {"name": "product2"},
    {"name": "product3"},
]

How do I know which groups each product is in? Like this:

<QuerySet [
    {"name": "product1", "groups": [{"pk": 1, "name": "group1"}]},
    {"name": "product2", "groups": []"},
    {"name": "product3", "groups": [{"pk": 1, "name": "group1"}, {"pk": 2, "name": "group2"}},
]

Thanks!

UPD1.

If we have data:

group1 | product 1
group1 | product 2
group2 | product 2
group2 | product 3

The idea of creating a table (html) is as follows:

/group/1:

product 1 | dropdown (group1)
product 2 | dropdown (group1, group2)

/group/2:

product 2 | dropdown (group1, group2)
product 3 | dropdown (group2)

Body:
model.py:

context['products'] = Group.objects.get(pk=1).products.all()
return render(request, 'template.html', context)

template.html:

{% for product in products %}
    {{ product.name }}

    COUNT: {{ product.group_set.count }}
    <ul>
        {% for group in product.group_set.all %}
            <li>{{ group.name }}</li>
        {% endfor %}
    </ul>
{% endfor %}

The solution was not difficult, it got confused because of:

{% for group in slave_product.group_set.all() %} # ()

Thanks to all!


来源: stackexchange

问:
How to throw compile time exception, if certain value is not set.
I have created an Android library, there is a method setContext()in it. Client need to pass context other wise app will crash at runtime. I need to throw an error on compile time, if user does not set context. I can't pass it throw constructor as its a singleton class.

Client

```<code>SampleLibrary sl= SampleLibrary.getInstance();
sl.setContext(this);
</code>```

Class

```<code>public void setContext(Context context){
  this.context= context;
}
</code>```

Kindly guide me How to throw compile time exception, if certain value is not set or null.

答:
doing this

```<code>sl.setContext(this);
</code>```

is giving the option to developers to dont set the context, or forget to set it...

but if you define the class as

public SampleLibrary(Context ctx) then they are done! there is no other chance for them to create an object of SampleLibrary without giving a context

ContentLicense: CC BY-SA 3.0

Body:
I have created an Android library, there is a method setContext()in it. Client need to pass context other wise app will crash at runtime. I need to throw an error on compile time, if user does not set context. I can't pass it throw constructor as its a singleton class.

Client

SampleLibrary sl= SampleLibrary.getInstance();
sl.setContext(this);

Class

public void setContext(Context context){
  this.context= context;
}

Kindly guide me How to throw compile time exception, if certain value is not set or null.

Body:
doing this

sl.setContext(this);

is giving the option to developers to dont set the context, or forget to set it...

but if you define the class as

public SampleLibrary(Context ctx) then they are done! there is no other chance for them to create an object of SampleLibrary without giving a context


问:
Load index.html every time from the server and NOT from cache
I have a webpage index.html hosted on a particular server. I have pointed example.com to example.com/index.html. So when I make changes in index.html and save it, and then try to open example.com, the changes are not reflected. Reason that the webpages are being cached.

Then I manually refresh the page and since it loads the fresh copies and not from cache, it works fine. But I cannot ask my client to do so, and they want everything to be perfect. So my question is that is there a trick or technique as to how I can make the file load every time from the server and not from cache?

P.S: I know the trick for CSS, JS and images files, i.e. appending ?v=1 but don't know how to do it for index.html.

Any help would be appreciated. Thanks!

答:
i ever meet this problem with my website. in your URL add the q=''

```<code>http://yoururl.com/somelinks?q=fill_with_random_number
</code>```

for me, it works

Body:
i ever meet this problem with my website. in your URL add the q=''

http://yoururl.com/somelinks?q=fill_with_random_number

for me, it works


问:
C# Split Date and Time format into Datatable
I have a CSV with a server log. I need to split the date/time format as attached image into my datatable.

Sample of CSV txt file

10.115.10.74 - - [20/Mar/2016:03:38:14 +0800] "GET /portal/images/banners/iot.jpg HTTP/1.1" 404 918 "http://www.utem.edu.my/portal/" "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"

172.16.75.219 - - [20/Mar/2016:03:38:17 +0800] "GET / HTTP/1.1" 200 98 "http://192.168.0.1:8090/httpclient.html" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36"

Is there any way I can do to achieve something like this?

What I have tried so far

```<code>string[] raw_text = System.IO.File.ReadAllLines("C:\\log4.csv");

string[] data_col = null;

int x = 0;
foreach (string text_line in raw_text)
{
    //MessageBox.Show(text_line);
    data_col = text_line.Split(' ', '<', '>', '[', ']', '-', '"', ';', '(', ')', '+', ':');

    if (x == 1)
    {
        for (int i = 0; i <= data_col.Count() - 1; i++)
        {
            my_datatable.Columns.Add(data_col[i]);
        }

        x++;
    }
    else
    {

        my_datatable.Rows.Add(data_col);
    }
</code>```

答:
Check the below code. I hope it helps</p>

```<code>        string[] raw_text = System.IO.File.ReadAllLines("C:\\log4.csv");
        string[] data_col = null;

        int x = 0;

        foreach (string text_line in raw_text)
        {
            //MessageBox.Show(text_line);
            data_col = text_line.Split(' ', '<', '>', '[', ']', '-', '"', ';', '(', ')', '+', ':');

            if (x == 1)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {
                        my_datatable.Columns.Add(data_col[i]);
                        my_datatable.Columns.Add(Convert.ToDateTime(data_col[i]).ToString("ddMMMyyyy"));

                        my_datatable.Columns.Add(Convert.ToDateTime(data_col[i]).ToString("HH:mm tt"));

                         my_datatable.Columns.Add(Convert.ToDateTime(data_col[i]).ToString("zzz"));

                        my_datatable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {

                my_datatable.Rows.Add(data_col);
            }
</code>```

Body:
I have a CSV with a server log. I need to split the date/time format as attached image into my datatable.

Sample of CSV txt file

10.115.10.74 - - [20/Mar/2016:03:38:14 +0800] "GET /portal/images/banners/iot.jpg HTTP/1.1" 404 918 "http://www.utem.edu.my/portal/" "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"

172.16.75.219 - - [20/Mar/2016:03:38:17 +0800] "GET / HTTP/1.1" 200 98 "http://192.168.0.1:8090/httpclient.html" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36"

Is there any way I can do to achieve something like this?

What I have tried so far

string[] raw_text = System.IO.File.ReadAllLines("C:\\log4.csv");

string[] data_col = null;

int x = 0;
foreach (string text_line in raw_text)
{
    //MessageBox.Show(text_line);
    data_col = text_line.Split(' ', '<', '>', '[', ']', '-', '"', ';', '(', ')', '+', ':');

    if (x == 1)
    {
        for (int i = 0; i <= data_col.Count() - 1; i++)
        {
            my_datatable.Columns.Add(data_col[i]);
        }

        x++;
    }
    else
    {

        my_datatable.Rows.Add(data_col);
    }

Body:
Check the below code. I hope it helps

        string[] raw_text = System.IO.File.ReadAllLines("C:\\log4.csv");
        string[] data_col = null;

        int x = 0;

        foreach (string text_line in raw_text)
        {
            //MessageBox.Show(text_line);
            data_col = text_line.Split(' ', '<', '>', '[', ']', '-', '"', ';', '(', ')', '+', ':');

            if (x == 1)
            {
                for (int i = 0; i <= data_col.Count() - 1; i++)
                {
                        my_datatable.Columns.Add(data_col[i]);
                        my_datatable.Columns.Add(Convert.ToDateTime(data_col[i]).ToString("ddMMMyyyy"));

                        my_datatable.Columns.Add(Convert.ToDateTime(data_col[i]).ToString("HH:mm tt"));

                         my_datatable.Columns.Add(Convert.ToDateTime(data_col[i]).ToString("zzz"));

                        my_datatable.Columns.Add(data_col[i]);
                }

                x++;
            }
            else
            {

                my_datatable.Rows.Add(data_col);
            }


问:
how to use lambda expression for jdk 7 or older versions
what are the changes that I need to make if I am using jdk 7 and want to use lambda expression?
I am comparing 2 xml files and want to ignore specific nodes hence using this expression

```<code>final Diff documentDiff = DiffBuilder
            .compare(expectedSource)
            .withTest(actualSource)
            .withNodeFilter(node -> !node.getNodeName().equals(someName))
            .build();
</code>```

error: Syntax error on token '-',-- expected

答:
Try this.

```<code>    final Diff documentDiff = DiffBuilder
        .compare(expectedSource)
        .withTest(actualSource)
        .withNodeFilter(new Predicate<Node>() {
            @Override
            public boolean test(Node node) {
                return !node.getNodeName().equals(someName);
            }
        })
        .build();
</code>```

This is redundant, but JDK7 will accept it.
I don't know if you can realize what you want to do with this.

Body:
what are the changes that I need to make if I am using jdk 7 and want to use lambda expression?
I am comparing 2 xml files and want to ignore specific nodes hence using this expression

final Diff documentDiff = DiffBuilder
            .compare(expectedSource)
            .withTest(actualSource)
            .withNodeFilter(node -> !node.getNodeName().equals(someName))
            .build();

error: Syntax error on token '-',-- expected

Body:
Try this.

    final Diff documentDiff = DiffBuilder
        .compare(expectedSource)
        .withTest(actualSource)
        .withNodeFilter(new Predicate<Node>() {
            @Override
            public boolean test(Node node) {
                return !node.getNodeName().equals(someName);
            }
        })
        .build();

This is redundant, but JDK7 will accept it.
I don't know if you can realize what you want to do with this.


问:
Passing values to other components using props in reactjs
I'm binding some text values when a certain div is clicked in my react application. Now i'm facing a problem on passing these text values to another component using props.

My code looks like this

```<code>class PostOptionBar extends Component {

    constructor() {
        super();

        this.state = {

            postType: 'text',

        }

    }

    textType(postType) {

        this.setState({postType});

    }

    render() {

        return (

            <div className="post_type_selection_div">

                <div className="post_type_btn">

                    <div className="horiz_center" onClick={this.textType.bind(this,'text')}>
                        <img src={StarIcon} className="post_type_icon"/>
                        <a className="post_type_text">Text</a>
                    </div>

                </div>

                <div className="post_type_btn" onClick={this.textType.bind(this,'imageVote')}>

                    <div className="horiz_center">
                        <img src={StarIcon} className="post_type_icon"/>
                        <a className="post_type_text">Image poll</a>
                    </div>

                </div>

                <div className="post_type_btn" onClick={this.textType.bind(this,'poll')}>

                    <div className="horiz_center">
                        <img src={StarIcon} className="post_type_icon"/>
                        <a className="post_type_text">Text poll</a>
                    </div>

                </div>

            </div>

        );
    }
}

export default PostOptionBar;
</code>```

I can bind the values successfully within this class. If i log the postType i can clearly see that. But i want to pass postType to another component. I'm loading PostOptionBar in my other component like this.

```<code> <div className="polaroid">
   <PostOptionBar/>
 <div>
</code>```

I'm trying to do something like this in my 2nd component.But because i cannot pass postType from my 1st component to 2nd one i cannot do this.

```<code>    renderTab() {

        switch (this.state.postType) {
            case 'text':
                return <TextPost/>
            case 'imageVote':
                return <ImageVote/>
            case 'poll':
                return <TextVotePost/>

        }
    }
</code>```

答:
To solve that issue, you need to manage the state by the parent component of PostOptionBar then pass the value to PostOptionBar and other components also. Also pass a function to PostOptionBar component to update the state of parent component.

Parent Component of PostOptionBar:

```<code><div className="polaroid">
    <PostOptionBar postType = {this.state.postType} changeType = {this.changeType}/>
<div>

changeType = (postType) => {
   this.setState({postType})
}
</code>```

Inside PostOptionBar use the props value this.props.postType:

```<code>class PostOptionBar extends Component {

    textType(postType) {
        this.props.changeType(postType);  // call the parent component to update the state
    }

    render() {
        return (
            ...
        );
    }
}
</code>```

Body:
I'm binding some text values when a certain div is clicked in my react application. Now i'm facing a problem on passing these text values to another component using props.

My code looks like this

class PostOptionBar extends Component {

    constructor() {
        super();

        this.state = {

            postType: 'text',

        }

    }

    textType(postType) {

        this.setState({postType});

    }

    render() {

        return (

                        Text

                        Image poll

                        Text poll

        );
    }
}

export default PostOptionBar;

I can bind the values successfully within this class. If i log the postType i can clearly see that. But i want to pass postType to another component. I'm loading PostOptionBar in my other component like this.

   <PostOptionBar/>

I'm trying to do something like this in my 2nd component.But because i cannot pass postType from my 1st component to 2nd one i cannot do this.

    renderTab() {

        switch (this.state.postType) {
            case 'text':
                return <TextPost/>
            case 'imageVote':
                return <ImageVote/>
            case 'poll':
                return <TextVotePost/>

        }
    }

Body:
To solve that issue, you need to manage the state by the parent component of PostOptionBar then pass the value to PostOptionBar and other components also. Also pass a function to PostOptionBar component to update the state of parent component.

Parent Component of PostOptionBar:

<div className="polaroid">
    <PostOptionBar postType = {this.state.postType} changeType = {this.changeType}/>
<div>

changeType = (postType) => {
   this.setState({postType})
}

Inside PostOptionBar use the props value this.props.postType:

class PostOptionBar extends Component {

    textType(postType) {
        this.props.changeType(postType);  // call the parent component to update the state
    }

    render() {
        return (
            ...
        );
    }
}


问:
action create not working Yii2 frontend
i want to execute action create in my view frontend, the code of actionCreate in site controller is correct , but it redirect me to index.php with this url "http://localhost/advanced/frontend/web/index.php?Subsidize%5Bname%5D..........."
knowing that i want to redirect to view.php after creating a new item in table "subsidize"

action create in siteController.php

```<code>public function actionView($id) {
    $model = Subsidize::findOne($id);
    if ($model === null) {
        throw new NotFoundHttpException;
    }

    return $this->render('view', [
                'model' => $model,
    ]);
}

public function actionCreate() {
    $model = new Subsidize();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

         return $this->redirect(['view', 'id' => $model->subsidize_id]);

    } else {

        return $this->render('create', [
                    'model' => $model,
        ]);
    }
}
</code>```

code of  submitButton in view "create.php"

```<code>        <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</code>```

also , function behaviors in  siteController

```<code> public function behaviors() {
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create'],
            'rules' => [
                [
                    'actions' => ['login', 'error'],
                    'allow' => true,
                ],
                [
                    'actions' => ['create', 'view'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    //see captcha and error added here, this fixes the issue
                    'actions' => ['support', 'test', 'delete', 'update', 'create', 'view'],
                    'allow' => true,
                    'roles' => ['?', '@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index' => ['get'],
                'view' => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
            ],
        ],
    ];
}
</code>```

code of my view : create.php

```<code><?php use yii\helpers\Html; use yii\widgets\ActiveForm; $model = new app\models\Subsidize; ?> <section class="support">
<div class="container">
    <form class="dialog-form row">
        <?php $form = ActiveForm::begin() ?>
        <div class="col-md-12">
            <div class="form-group">

                <?php echo $form->field($model, 'name', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('name', ['placeholder' => "الإسم الكريم"])->label(false); ?>

            </div><!--End Form-group-->
        </div><!-- col -->
        <div class="col-md-12">
            <div class="form-group">
                 <?php echo $form->field($model, 'montant', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('montant', ['placeholder' => "المبلغ "])->label(false); ?>
            </div><!--End Form-group-->
        </div><!-- col -->

         <div class="col-md-12">
            <div class="form-group">
                 <?php echo $form->field($model, 'date', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('date', ['placeholder' => "تاريخ التذكير "])->label(false); ?>
            </div><!--End Form-group-->
        </div><!-- col -->

        <div class="col-md-12">
            <div class="form-group">
                 <?php echo $form->field($model, 'phone', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('phone', ['placeholder' => "رقم الجوال"])->label(false); ?>
            </div><!--End Form-group-->
        </div><!-- col -->

        <div class="col-md-12">
            <div class="form-group">

                    <?php echo $form->field($model, 'remarks', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput(['rows' =>6])->input('remarks', ['placeholder' => "ملاحظات"])->label(false); ?>
            </div><!-- form-group -->
        </div><!-- col -->
        <div class="col-md-12">
            <div class="form-group" style="text-align:center ">

    <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

            </div><!-- form-group -->
        </div><!-- col -->
         <?php ActiveForm::end(); ?>
    </form><!--End-->
</div><!-- container -->
</code>```

答:
Sorry for my english before. Can you edit your post and add your complete ActiveForm::begin() code. for alternate fix, you can try to remove the create action on your verb behavior like this :

```<code>'verbs' => [
        'class' => VerbFilter::className(),
        'actions' => [
            'index' => ['get'],
            'view' => ['get'],
            'update' => ['get', 'put', 'post'],
            'delete' => ['post', 'delete'],
        ],
    ],
</code>```

Title: action create not working Yii2 frontend

Body:
i want to execute action create in my view frontend, the code of actionCreate in site controller is correct , but it redirect me to index.php with this url "http://localhost/advanced/frontend/web/index.php?Subsidize%5Bname%5D..........."
knowing that i want to redirect to view.php after creating a new item in table "subsidize"

action create in siteController.php

public function actionView($id) {
    $model = Subsidize::findOne($id);
    if ($model === null) {
        throw new NotFoundHttpException;
    }

    return $this->render('view', [
                'model' => $model,
    ]);
}

public function actionCreate() {
    $model = new Subsidize();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

         return $this->redirect(['view', 'id' => $model->subsidize_id]);

    } else {

        return $this->render('create', [
                    'model' => $model,
        ]);
    }
}

code of  submitButton in view "create.php"

        <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

also , function behaviors in  siteController

 public function behaviors() {
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create'],
            'rules' => [
                [
                    'actions' => ['login', 'error'],
                    'allow' => true,
                ],
                [
                    'actions' => ['create', 'view'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
                [
                    //see captcha and error added here, this fixes the issue
                    'actions' => ['support', 'test', 'delete', 'update', 'create', 'view'],
                    'allow' => true,
                    'roles' => ['?', '@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'index' => ['get'],
                'view' => ['get'],
                'create' => ['get', 'post'],
                'update' => ['get', 'put', 'post'],
                'delete' => ['post', 'delete'],
            ],
        ],
    ];
}

code of my view : create.php

<?php use yii\helpers\Html; use yii\widgets\ActiveForm; $model = new app\models\Subsidize; ?>

    <form class="dialog-form row">
        <?php $form = ActiveForm::begin() ?>

                <?php echo $form->field($model, 'name', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('name', ['placeholder' => "الإسم الكريم"])->label(false); ?>

                 <?php echo $form->field($model, 'montant', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('montant', ['placeholder' => "المبلغ "])->label(false); ?>

                 <?php echo $form->field($model, 'date', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('date', ['placeholder' => "تاريخ التذكير "])->label(false); ?>

                 <?php echo $form->field($model, 'phone', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput()->input('phone', ['placeholder' => "رقم الجوال"])->label(false); ?>

                    <?php echo $form->field($model, 'remarks', [
       'inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control transparent']
 ])->textInput(['rows' =>6])->input('remarks', ['placeholder' => "ملاحظات"])->label(false); ?>

    <?= Html::submitButton($model->isNewRecord ? 'إرسال ' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

         <?php ActiveForm::end(); ?>
    </form>

Body:
Sorry for my english before. Can you edit your post and add your complete ActiveForm::begin() code. for alternate fix, you can try to remove the create action on your verb behavior like this :

'verbs' => [
        'class' => VerbFilter::className(),
        'actions' => [
            'index' => ['get'],
            'view' => ['get'],
            'update' => ['get', 'put', 'post'],
            'delete' => ['post', 'delete'],
        ],
    ],


问:
APNS Firebase Notification failed to fetch token
For Swift3 / iOS10 see this link:

ios10, Swift 3 and Firebase Push Notifications (FCM)

I'm trying to use the Firebase for Notifications and I integrated it exactly as described in the docs.
But I don't understand why is doesn't work. When I build my project I see this line:

```<code>2016-05-25 16:09:34.987: <FIRInstanceID/WARNING> Failed to fetch default token Error Domain=com.firebase.iid Code=0 "(null)"
</code>```

This my AppDelegate:

```<code> func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
     var service: DataService = DataService()
    service.start()
    registerForPushNotifications(application)
    application.registerForRemoteNotifications()
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
    print("Device Token:", tokenString)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)  {
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
}
</code>```

答:
The answers above cover most of the issue, but I had the same issue and I found the following info useful:

Firebase can 'rotate' (change) a user's FCM token at any time. This is the 128 character ID that your server will use to send the push notification to the device.

Firebase docs say best practice is to use a delegate to monitor for changes with the delegate callback method:

```<code>- (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken
</code>```

[Obj - C]

```<code>func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String)
</code>```

[Swift]

The delegate method should be called on every change, at which point you can update the record in your server.

Unfortunately that wasn't working for me, I had a delegate but the callback wasn't being invoked. So I had to resort to manually updating the token on each app launch (as suggested by @micheal chein above) as follows:

```<code>NSString *deviceToken = [FIRInstanceID instanceID].token; // Send this to your server
</code>```

[Obj-C]

```<code>let token = FIRInstanceID.instanceID().token() // Send this to your server
</code>```

[Swift]

** Important: update the token after a delay (20-25s), as the rotation can sometimes only reflect after some time. You can use a timer for this.

After this I still get the APNS warning/error message:

```<code>2017-06-06 09:21:49.520: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"
</code>```

BUT, push notifications work every time without fail. So I think that log message is a bit off (possibly mistimed).  If you can get option 2 to work for you, definitely do that!

Body:
For Swift3 / iOS10 see this link:

ios10, Swift 3 and Firebase Push Notifications (FCM)

I'm trying to use the Firebase for Notifications and I integrated it exactly as described in the docs.
But I don't understand why is doesn't work. When I build my project I see this line:

2016-05-25 16:09:34.987: <FIRInstanceID/WARNING> Failed to fetch default token Error Domain=com.firebase.iid Code=0 "(null)"

This my AppDelegate:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    FIRApp.configure()
    FIRDatabase.database().persistenceEnabled = true
     var service: DataService = DataService()
    service.start()
    registerForPushNotifications(application)
    application.registerForRemoteNotifications()
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.Unknown)
    print("Device Token:", tokenString)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void)  {
    // Print message ID.
    print("Message ID: \(userInfo["gcm.message_id"]!)")

    // Print full message.
    print("%@", userInfo)
}

Body:
The answers above cover most of the issue, but I had the same issue and I found the following info useful:

Firebase can 'rotate' (change) a user's FCM token at any time. This is the 128 character ID that your server will use to send the push notification to the device.

Firebase docs say best practice is to use a delegate to monitor for changes with the delegate callback method:

- (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken

[Obj - C]

func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String)

[Swift]

The delegate method should be called on every change, at which point you can update the record in your server.

Unfortunately that wasn't working for me, I had a delegate but the callback wasn't being invoked. So I had to resort to manually updating the token on each app launch (as suggested by @micheal chein above) as follows:

NSString *deviceToken = [FIRInstanceID instanceID].token; // Send this to your server

[Obj-C]

let token = FIRInstanceID.instanceID().token() // Send this to your server

[Swift]

** Important: update the token after a delay (20-25s), as the rotation can sometimes only reflect after some time. You can use a timer for this.

After this I still get the APNS warning/error message:

2017-06-06 09:21:49.520: <FIRInstanceID/WARNING> Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)"

BUT, push notifications work every time without fail. So I think that log message is a bit off (possibly mistimed).  If you can get option 2 to work for you, definitely do that!


问:
How to Split row into multiple columns in MySQL

Hi can somebody help me, i have some question on how to separate this row into columns with the same id number. I have tried some SQL function like GROUP_CONCAT() or SUBSTRING_INDEX() function but i dont know how it works

I want the output to look something like this

答:
You might try a pivot table query:</p>

```<code>SELECT
    t1.`Unit_Cost` as `Unit_Cost1`,
    ifnull(t2.`Unit_Cost`,'') as `Unit_Cost2`
FROM table t1
LEFT JOIN table t2
ON t1.`ID` = t2.`ID`
GROUP BY `ID`
ORDER BY `ID`
</code>```

Body:
You might try a pivot table query:

SELECT
    t1.`Unit_Cost` as `Unit_Cost1`,
    ifnull(t2.`Unit_Cost`,'') as `Unit_Cost2`
FROM table t1
LEFT JOIN table t2
ON t1.`ID` = t2.`ID`
GROUP BY `ID`
ORDER BY `ID`


问:
Submit button not inputting
I wanted to try and create a bigger input and submit button box for a simple JS function for my course. However, when I changed the height and font size of my input my submit button no longer functions. I know it has to do with the height because when I remove it, it works. How can I work around this?

I will provide the URL for my website my CSS code that starts the input and the button is on line 273.

http://web.gccaz.edu/~pet2153867/test/

Thanks!

答:
Add position: relative;  and z-index:9999; to your button style.

```<code>button {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    padding: 10px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 20px;
    height: 50px;
    position: relative;
    z-index: 99999;
}
</code>```

this problem caused by H1 Tag. h1 tag crosspvered with your button. removing bottom:70px will also fix your problem.

```<code>#projects h1 {
position: relative;
bottom: 70px;
}
</code>```

Title: Submit button not inputting

Body:
Add position: relative;  and z-index:9999; to your button style.

button {
    width: 100%;
    background-color: #4CAF50;
    color: white;
    padding: 10px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 20px;
    height: 50px;
    position: relative;
    z-index: 99999;
}

this problem caused by H1 Tag. h1 tag crosspvered with your button. removing bottom:70px will also fix your problem.

#projects h1 {
position: relative;
bottom: 70px;
}


问:
How to retrieve all contacts details from Content provider with single query?
I need to read the contacts from device. The fields I required are ID , Display Name, Phone Number (All types) Email id (All types) and 'photo'. For this right now I am doing like this.

1 :    First I am reading all the ids from ContactsContract.Contacts.CONTENT_URI; as shown below

```<code>        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
        // Querying the table ContactsContract.Contacts to retrieve all the contacts
        String[] projection = {ID};
        Cursor contactsCursor = mContentResolver.query(contactsUri, projection, null, null,
                "upper(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
</code>```

2 : Then iterating through this cursor to read requred fields of all contacts.

```<code>if (contactsCursor.moveToFirst()) {
            do {
                 long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex(ID));
                   Uri dataUri = ContactsContract.Data.CONTENT_URI;
                // Querying the table ContactsContract.Data to retrieve individual items like
                // home phone, mobile phone, work email etc corresponding to each contact
                   String[] columns = {CONTACT_ID, PHOTO_URI, DISPLAY_NAME, MIME_TYPE, DATA_1, DATA_2, DATA_4};
                   String selection = ContactsContract.Data.CONTACT_ID + "=" + contactId;
                   Cursor dataCursor = mContentResolver.query(dataUri, columns,
                        selection,
                        null, null);
                                 if (dataCursor.moveToFirst()) {
                                 // Getting Display Name
                                 displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                                 do {
                                    // Getting Phone numbers
                                    String mimeType = dataCursor.getString(dataCursor.getColumnIndex(MIME_TYPE));
                                    switch (mimeType) {
                                             case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
                                             String phoneNumber = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                             switch (dataCursor.getInt(dataCursor.getColumnIndex(DATA_2))) {
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                        homePhone = phoneNumber;
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                        mobilePhone = phoneNumber;
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                        workPhone = phoneNumber;
                                        break;
                                    default:
                                        otherPhone = phoneNumber;
                                }
                                break;
                              // Getting emails
                              case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
                                switch (dataCursor.getInt(dataCursor.getColumnIndex(DATA_2))) {
                                    case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
                                        homeEmail = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                        break;
                                    case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
                                        workEmail = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                        break;
                                    default:
                                        otherEmail = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                }
                                break;
                               // getting photo Uri
                               case ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE:
                                if (dataCursor.getString(dataCursor.getColumnIndex(PHOTO_URI)) != null) {
                                    photoUri = Uri.parse(dataCursor.getString(dataCursor.getColumnIndex(PHOTO_URI)));
                                }
                                break;
                        }

                    } while (dataCursor.moveToNext());

               } while (contactsCursor.moveToNext());
</code>```

The queries work fine but the problem is it is taking too much time to iterate and get details of each contact. First query is returning quickly , but the whole delay is now in the second part,  that is iterating through each row of the first query and querying for each fields. Can this be done in a single join query so that I can optimize the performance?

答:
Yes, you can do that in a single query - all the data about contacts is actually stored in a single table Data, which contains everything you need on a contact including CONTACT_ID and DISPLAY_NAME which are also hosted on the Contacts table.

So you need to basically query everything from the Data table in a single query, and sort it out into contacts using a HashMap from CONTACT_ID to some contact object (or if you prefer a list of details).

(Note: make sure you import the following classes from ContactsContract package only)

```<code>Map<Long, List<String>> contacts = new HashMap<Long, List<String>>();

String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.PHOTO_ID};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);

while (cur != null && cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1);
    String mime = cur.getString(2); // email / phone / company
    String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
    int type = cur.getInt(4); // a numeric value representing type: e.g. home / office / personal
    String label = cur.getString(5); // a custom label in case type is "TYPE_CUSTOM"
    long photoId = cur.getLong(6);

    String kind = "unknown";
    String labelStr = "";

    switch (mime) {
        case Phone.CONTENT_ITEM_TYPE:
            kind = "phone";
            labelStr = Phone.getTypeLabel(getResources(), type, label);
            break;
        case Email.CONTENT_ITEM_TYPE:
            kind = "email";
            labelStr = Email.getTypeLabel(getResources(), type, label);
            break;
    }
    Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data + " (" + labelStr + ")");

    // add info to existing list if this contact-id was already found, or create a new list in case it's new
    List<String> infos;
    if (contacts.containsKey(id)) {
        infos = contacts.get(id);
    } else {
        infos = new ArrayList<String>();
        infos.add("name = " + name);
        infos.add("photo = " + photoId);
        contacts.put(id, infos);
    }
    infos.add(kind + " = " + data + " (" + labelStr + ")");
}
</code>```

Body:
I need to read the contacts from device. The fields I required are ID , Display Name, Phone Number (All types) Email id (All types) and 'photo'. For this right now I am doing like this.

1 :    First I am reading all the ids from ContactsContract.Contacts.CONTENT_URI; as shown below

        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
        // Querying the table ContactsContract.Contacts to retrieve all the contacts
        String[] projection = {ID};
        Cursor contactsCursor = mContentResolver.query(contactsUri, projection, null, null,
                "upper(" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");

2 : Then iterating through this cursor to read requred fields of all contacts.

if (contactsCursor.moveToFirst()) {
            do {
                 long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex(ID));
                   Uri dataUri = ContactsContract.Data.CONTENT_URI;
                // Querying the table ContactsContract.Data to retrieve individual items like
                // home phone, mobile phone, work email etc corresponding to each contact
                   String[] columns = {CONTACT_ID, PHOTO_URI, DISPLAY_NAME, MIME_TYPE, DATA_1, DATA_2, DATA_4};
                   String selection = ContactsContract.Data.CONTACT_ID + "=" + contactId;
                   Cursor dataCursor = mContentResolver.query(dataUri, columns,
                        selection,
                        null, null);
                                 if (dataCursor.moveToFirst()) {
                                 // Getting Display Name
                                 displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
                                 do {
                                    // Getting Phone numbers
                                    String mimeType = dataCursor.getString(dataCursor.getColumnIndex(MIME_TYPE));
                                    switch (mimeType) {
                                             case ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE:
                                             String phoneNumber = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                             switch (dataCursor.getInt(dataCursor.getColumnIndex(DATA_2))) {
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
                                        homePhone = phoneNumber;
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
                                        mobilePhone = phoneNumber;
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
                                        workPhone = phoneNumber;
                                        break;
                                    default:
                                        otherPhone = phoneNumber;
                                }
                                break;
                              // Getting emails
                              case ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE:
                                switch (dataCursor.getInt(dataCursor.getColumnIndex(DATA_2))) {
                                    case ContactsContract.CommonDataKinds.Email.TYPE_HOME:
                                        homeEmail = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                        break;
                                    case ContactsContract.CommonDataKinds.Email.TYPE_WORK:
                                        workEmail = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                        break;
                                    default:
                                        otherEmail = dataCursor.getString(dataCursor.getColumnIndex(DATA_1));
                                }
                                break;
                               // getting photo Uri
                               case ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE:
                                if (dataCursor.getString(dataCursor.getColumnIndex(PHOTO_URI)) != null) {
                                    photoUri = Uri.parse(dataCursor.getString(dataCursor.getColumnIndex(PHOTO_URI)));
                                }
                                break;
                        }

                    } while (dataCursor.moveToNext());

               } while (contactsCursor.moveToNext());

The queries work fine but the problem is it is taking too much time to iterate and get details of each contact. First query is returning quickly , but the whole delay is now in the second part,  that is iterating through each row of the first query and querying for each fields. Can this be done in a single join query so that I can optimize the performance?

Body:
Yes, you can do that in a single query - all the data about contacts is actually stored in a single table Data, which contains everything you need on a contact including CONTACT_ID and DISPLAY_NAME which are also hosted on the Contacts table.

So you need to basically query everything from the Data table in a single query, and sort it out into contacts using a HashMap from CONTACT_ID to some contact object (or if you prefer a list of details).

(Note: make sure you import the following classes from ContactsContract package only)

Map<Long, List<String>> contacts = new HashMap<Long, List<String>>();

String[] projection = {Data.CONTACT_ID, Data.DISPLAY_NAME, Data.MIMETYPE, Data.DATA1, Data.DATA2, Data.DATA3, Data.PHOTO_ID};
String selection = Data.MIMETYPE + " IN ('" + Phone.CONTENT_ITEM_TYPE + "', '" + Email.CONTENT_ITEM_TYPE + "')";
Cursor cur = cr.query(Data.CONTENT_URI, projection, selection, null, null);

while (cur != null && cur.moveToNext()) {
    long id = cur.getLong(0);
    String name = cur.getString(1);
    String mime = cur.getString(2); // email / phone / company
    String data = cur.getString(3); // the actual info, e.g. +1-212-555-1234
    int type = cur.getInt(4); // a numeric value representing type: e.g. home / office / personal
    String label = cur.getString(5); // a custom label in case type is "TYPE_CUSTOM"
    long photoId = cur.getLong(6);

    String kind = "unknown";
    String labelStr = "";

    switch (mime) {
        case Phone.CONTENT_ITEM_TYPE:
            kind = "phone";
            labelStr = Phone.getTypeLabel(getResources(), type, label);
            break;
        case Email.CONTENT_ITEM_TYPE:
            kind = "email";
            labelStr = Email.getTypeLabel(getResources(), type, label);
            break;
    }
    Log.d(TAG, "got " + id + ", " + name + ", " + kind + " - " + data + " (" + labelStr + ")");

    // add info to existing list if this contact-id was already found, or create a new list in case it's new
    List<String> infos;
    if (contacts.containsKey(id)) {
        infos = contacts.get(id);
    } else {
        infos = new ArrayList<String>();
        infos.add("name = " + name);
        infos.add("photo = " + photoId);
        contacts.put(id, infos);
    }
    infos.add(kind + " = " + data + " (" + labelStr + ")");
}


问:
How to ajax request to custom page in prestashop 1.7
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop

```<code>//My js file
     $.ajax({
     url : baseUrl + "modules/<myModule>/ajaxfunc.php",
     type: "POST",
     cache: false,
     data : {form_data: 1 , action:'imageuploadAction'},

     beforeSend: function() {
     $('body').append('<div class="loading_popup">Loading...</div>');},

    success: function(data){
    console.log(data);
       }
      });

// php file
// modules/<myModule>/ajaxfanc.php

   <?php
   include_once('../../config/config.inc.php');
   include_once('../../init.php');
   class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
    {
    public function  imageuploadAction() {
     die('here');
    }
   }
   ?>
</code>```

I didn't know its be correct or not. please guide me.

答:
I have found the solution to get the proper Ajax request in prestashop 1.7

//In tpl file

```<code><script>
  var url= {url entity='module' name='<myModuleName>' controller='<MyControllerName>' params = ['var1' => 1,'var2' => 2,action => 'MyControllerAction']}
</script>
</code>```

//In Js file

```<code>$.ajax({
url : url,
type: "POST",
data : 'var3='3,
success : function(response){
  console.log(response);
</code>```

}
  });

//In Controller Php file

```<code><?php
  require_once(dirname(__FILE__).'../../../../config/config.inc.php');
  require_once(dirname(__FILE__).'../../../../init.php');
  class <MyModule><MyController>ModuleFrontController extends ModuleFrontController
    {
      public function initContent()
      {
       $this->ajax = true;
        parent::initContent();
      }
      // displayAjax for FrontEnd Invoke the ajax action
      // ajaxProcess for BackEnd Invoke the ajax action

       public function displayAjaxMyControllerAction()
        {
         $var1 = Tools::getValue('var1');
         $var2 = Tools::getValue('var2');
         $var3 = Tools::getValue('var3');

         header('Content-Type: application/json');
         die(Tools::jsonEncode(['var1'=> $var3]);
        }
      }
</code>```

Body:
Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop

//My js file
     $.ajax({
     url : baseUrl + "modules/<myModule>/ajaxfunc.php",
     type: "POST",
     cache: false,
     data : {form_data: 1 , action:'imageuploadAction'},

     beforeSend: function() {
     $('body').append('
Loading...
');},

    success: function(data){
    console.log(data);
       }
      });

// php file
// modules/<myModule>/ajaxfanc.php

   <?php
   include_once('../../config/config.inc.php');
   include_once('../../init.php');
   class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
    {
    public function  imageuploadAction() {
     die('here');
    }
   }
   ?>

I didn't know its be correct or not. please guide me.

Body:
I have found the solution to get the proper Ajax request in prestashop 1.7

//In tpl file

<script>
  var url= {url entity='module' name='<myModuleName>' controller='<MyControllerName>' params = ['var1' => 1,'var2' => 2,action => 'MyControllerAction']}
</script>

//In Js file

$.ajax({
url : url,
type: "POST",
data : 'var3='3,
success : function(response){
  console.log(response);

}
  });

//In Controller Php file

<?php
  require_once(dirname(__FILE__).'../../../../config/config.inc.php');
  require_once(dirname(__FILE__).'../../../../init.php');
  class <MyModule><MyController>ModuleFrontController extends ModuleFrontController
    {
      public function initContent()
      {
       $this->ajax = true;
        parent::initContent();
      }
      // displayAjax for FrontEnd Invoke the ajax action
      // ajaxProcess for BackEnd Invoke the ajax action

       public function displayAjaxMyControllerAction()
        {
         $var1 = Tools::getValue('var1');
         $var2 = Tools::getValue('var2');
         $var3 = Tools::getValue('var3');

         header('Content-Type: application/json');
         die(Tools::jsonEncode(['var1'=> $var3]);
        }
      }


问:
Render ImageData from canvas context.getImageData in React
In a React component how can I render an image created using canvas?</p>

```<code>componentWillMount () {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  canvas.width = 256
  canvas.height = 256
  // omitted canvas painting code
  const image = context.getImageData(0, 0, canvas.width, canvas.height)
  this.setState({image})
}

render() {
  return ?
}
</code>```

答:
I'm not sure you can render it directly in the render method. But you can draw it if you use componentDidMount/componentDidUpdate hooks if you are setting it with state.

class Hi extends React.Component {
  state = {};
  componentWillMount () {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = 256
    canvas.height = 256
    context.rect(20,20,150,100);
    context.stroke();
    const image = context.getImageData(0, 0, canvas.width, canvas.height)
    this.setState({image})
  }
  componentDidMount() {
    const context = this.refs.canvas.getContext('2d');
    context.putImageData(this.state.image, 0, 0);
  }
  render() {
    return <canvas ref="canvas" />
  }
}

ReactDOM.render(<Hi />, document.body);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

Body:
In a React component how can I render an image created using canvas?

componentWillMount () {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  canvas.width = 256
  canvas.height = 256
  // omitted canvas painting code
  const image = context.getImageData(0, 0, canvas.width, canvas.height)
  this.setState({image})
}

render() {
  return ?
}

Body:
I'm not sure you can render it directly in the render method. But you can draw it if you use componentDidMount/componentDidUpdate hooks if you are setting it with state.

class Hi extends React.Component {
  state = {};
  componentWillMount () {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = 256
    canvas.height = 256
    context.rect(20,20,150,100);
    context.stroke();
    const image = context.getImageData(0, 0, canvas.width, canvas.height)
    this.setState({image})
  }
  componentDidMount() {
    const context = this.refs.canvas.getContext('2d');
    context.putImageData(this.state.image, 0, 0);
  }
  render() {
    return <canvas ref="canvas" />
  }
}

ReactDOM.render(<Hi />, document.body);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


问:
JavaScript: Too much recursion?
I am learning JavaScript through Eloquent JavaScript and one of the exercises is to write a recursive function, isEven, that returns true if a number is even or false if a number is odd.

If I understood correctly, the author specifically wanted the following to be implemented:

If a number == 0, then it is even.

If a number == 1, then it is odd.

"For any number N, its evenness is the same as N-2".

But when I use the code I have below, I get an error: InternalError: too much recursion (line 3 in function isEven) … How can I fix this while still using a recursive function?

```<code>// Your code here.
function isEven(n){
  if(n==0){
    return true;
  }
  else if(n==1){
    return false;
  }
  else{
    n = n-2;
    isEven(n);
  }
}

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??
</code>```

答:
To handle it recursion with that function, the value needs to be its absolute value.

console.log("isEven");

function isEven(n) {
  //Ensure that we look at the numbers absolute value
  n = Math.abs(n);
  //Do a loop instead of recursion
  if (n == 0) {
    return true;
  } else if (n == 1) {
    return false;
  } else {
    n = n - 2;
    return isEven(n);
  }
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
console.log("fasterIsEven");
//A faster way that eliminates recursion
function fasterIsEven(n) {
  return n % 2 === 0;
}
console.log(fasterIsEven(50));
console.log(fasterIsEven(75));
console.log(fasterIsEven(-1));```

Javascript has a build-in method to test if something is dividable with something else, called modulus (%). This method is faster, but not recursive.

Title: JavaScript: Too much recursion?

Body:
I am learning JavaScript through Eloquent JavaScript and one of the exercises is to write a recursive function, isEven, that returns true if a number is even or false if a number is odd.

If I understood correctly, the author specifically wanted the following to be implemented:

If a number == 0, then it is even.

If a number == 1, then it is odd.

"For any number N, its evenness is the same as N-2".

But when I use the code I have below, I get an error: InternalError: too much recursion (line 3 in function isEven) … How can I fix this while still using a recursive function?

// Your code here.
function isEven(n){
  if(n==0){
    return true;
  }
  else if(n==1){
    return false;
  }
  else{
    n = n-2;
    isEven(n);
  }
}

console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → ??

Body:
To handle it recursion with that function, the value needs to be its absolute value.

console.log("isEven");

function isEven(n) {
  //Ensure that we look at the numbers absolute value
  n = Math.abs(n);
  //Do a loop instead of recursion
  if (n == 0) {
    return true;
  } else if (n == 1) {
    return false;
  } else {
    n = n - 2;
    return isEven(n);
  }
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
console.log("fasterIsEven");
//A faster way that eliminates recursion
function fasterIsEven(n) {
  return n % 2 === 0;
}
console.log(fasterIsEven(50));
console.log(fasterIsEven(75));
console.log(fasterIsEven(-1));

Javascript has a build-in method to test if something is dividable with something else, called modulus (%). This method is faster, but not recursive.


问:
Desktop applications with Meteor.js
The options I've found for creating desktop applications in HTML, CSS, and JavaScript are:

Electron (formerly Atom-Shell)

NW.js (formerly Node-Webkit)

However, there doesn't seem to be any clear implementation for using meteor.js with these.

NW.js

I've seen some other questions of people asking this, but no implementation. Can't even figure out by the answers what I should be trying to put together:

Meteor leaderboard app on node-webkit

Demeteorizer with node-webkit

How can I start a Meteor instance before launching a node-webkit?

This guys actually got it running but doesn't say how: https://stackoverflow.com/questions/25508737/iron-router-routing-fails-on-reload-in-node-webkit

The idea proposed here is interesting—loading the desktop application completely from the web. However, I would like to allow my users to use the application offline.

Electron

There is an actual implementation, meteor-desktop-app, but it has no clear support for Windows. However, the atom-shell does support Windows just as NW.js does.

Has anyone figured out an implementation to allow meteor.js to operate as a desktop application?

答: Check out mongoclient's scaffold directory, it'll lead you to your electron app if you follow the steps from readme.</p>

Title: Desktop applications with Meteor.js


问:
Android ble setValue like 0x0001
I need send value like 0x0001 , 0x0002 in BLE setValue() ,

Does anyone know how to transmit ?

for Example :

```<code>private void command () {
   ongoing.setValue(0x0001);  //error
   mBluetoothLeService.writeCharacteristic(ongoing);
   BluetoothLeService.setCharacteristicNotification(ongoing, true);
   ...
   ...
   ...
   mBluetoothLeService.readCharacteristic(ongoing);
}

Thanks.
</code>```

in DeviceControlActivity.java :

```<code>private void displayGattServices(List<BluetoothGattService> gattServices){
    UUID UBI_COMMAND = UUID.fromString(SampleGattAttributes.UBI_ONGOING_INFO_SERVICE_UUID);
    ...
    ...
    if (uuid.equals(SampleGattAttributes.UBI_ONGOING_INFO_SERVICE_UUID)){
       ongoing = gattService.getCharacteristic(UBI_ONGOING);
    }
}
</code>```

答:
First define your input format(byte) then set the value of characterstics. Please check below snippet. "writeCharacterstics" function is available in the BluetoothGatt. If you have not a method in your service defined by you then also change the "mBluetoothLeService" object to "gatt" object to write the value.</p>

```<code>            byte[] value = {(byte) 0x01};
            characteristic.setValue(value);
            mBluetoothLeService.writeCharacteristic(characteristic);
</code>```

Title: Android ble setValue like 0x0001

Body:
I need send value like 0x0001 , 0x0002 in BLE setValue() ,

Does anyone know how to transmit ?

for Example :

private void command () {
   ongoing.setValue(0x0001);  //error
   mBluetoothLeService.writeCharacteristic(ongoing);
   BluetoothLeService.setCharacteristicNotification(ongoing, true);
   ...
   ...
   ...
   mBluetoothLeService.readCharacteristic(ongoing);
}

Thanks.

in DeviceControlActivity.java :

private void displayGattServices(List<BluetoothGattService> gattServices){
    UUID UBI_COMMAND = UUID.fromString(SampleGattAttributes.UBI_ONGOING_INFO_SERVICE_UUID);
    ...
    ...
    if (uuid.equals(SampleGattAttributes.UBI_ONGOING_INFO_SERVICE_UUID)){
       ongoing = gattService.getCharacteristic(UBI_ONGOING);
    }
}

Body:
First define your input format(byte) then set the value of characterstics. Please check below snippet. "writeCharacterstics" function is available in the BluetoothGatt. If you have not a method in your service defined by you then also change the "mBluetoothLeService" object to "gatt" object to write the value.

            byte[] value = {(byte) 0x01};
            characteristic.setValue(value);
            mBluetoothLeService.writeCharacteristic(characteristic);


问:
How to total value of checkbox when I check and update value immediately after unchek it using jquery?

$('#r4').change(function() {
  var sum = 0;
  $('#r4:checked').each(function() {
    sum += parseInt($(this).val());
  })

  $(".totcheck").val(sum);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
    <div class="row">
      <div class="col-sm-12" id="Spirit" style="text-align: left;">
        <li>
          <label class="control control--checkbox">Content A
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content B
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content C
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content D
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-12" style="background: #ffdcdc; margin-bottom: 10px;">
    <h3 style="text-align: left;">Result</h3>
    <div class="row">
      <div class="col-sm-12" style="text-align: left;">
        <p>Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />
        </p>
      </div>
    </div>
  </div>
</div></code>```

I have a several div with different id of checkbox. I want to accumulate the value of checkbox when I check,and re-update the value if I uncheck a box.

For example:
If I checked content A and content B, it will update total value to 2, when I unchecked content B, it automatic update total value to 1.

答:
id must be unique, so in case of id it only gets the first element, use classes or specify the selector

$('input[type="checkbox"]').change(function() {
    var sum = 0;

    $('input[type="checkbox"]:checked').each(function() {
        sum += parseInt($(this).val());
    })

    $(".totcheck").val(sum);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
      <div class="row" >
        <div class="col-sm-12" id="Spirit" style="text-align: left;">
          <li>
            <label class="control control--checkbox">Content A
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content B
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content C
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content D
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
        </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-12" style="background: #ffdcdc; margin-bottom: 10px;">
    <h3 style="text-align: left;">Result</h3>
      <div class="row" >
        <div class="col-sm-12" style="text-align: left;">
          <p>Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />
          </p>
        </div>
    </div>
  </div>
</div></code>```

By the way, here is a much shorter solution.

$('input[type="checkbox"]').change(function() {
     $(".totcheck").val($('input[type="checkbox"]:checked').length);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
      <div class="row" >
        <div class="col-sm-12" id="Spirit" style="text-align: left;">
          <li>
            <label class="control control--checkbox">Content A
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content B
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content C
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content D
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
        </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-12" style="background: #ffdcdc; margin-bottom: 10px;">
    <h3 style="text-align: left;">Result</h3>
      <div class="row" >
        <div class="col-sm-12" style="text-align: left;">
          <p>Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />
          </p>
        </div>
    </div>
  </div>
</div></code>```

Body:
$('#r4').change(function() {
  var sum = 0;
  $('#r4:checked').each(function() {
    sum += parseInt($(this).val());
  })

  $(".totcheck").val(sum);

});

Row 4

          Content A
            <input type="checkbox" id="r4" value="1"/>

           Content B
            <input type="checkbox" id="r4" value="1"/>

           Content C
            <input type="checkbox" id="r4" value="1"/>

           Content D
            <input type="checkbox" id="r4" value="1"/>

Result

Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />

I have a several div with different id of checkbox. I want to accumulate the value of checkbox when I check,and re-update the value if I uncheck a box.

For example:
If I checked content A and content B, it will update total value to 2, when I unchecked content B, it automatic update total value to 1.

Body:
id must be unique, so in case of id it only gets the first element, use classes or specify the selector

$('input[type="checkbox"]').change(function() {
    var sum = 0;

    $('input[type="checkbox"]:checked').each(function() {
        sum += parseInt($(this).val());
    })

    $(".totcheck").val(sum);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
      <div class="row" >
        <div class="col-sm-12" id="Spirit" style="text-align: left;">
          <li>
            <label class="control control--checkbox">Content A
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content B
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content C
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content D
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
        </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-12" style="background: #ffdcdc; margin-bottom: 10px;">
    <h3 style="text-align: left;">Result</h3>
      <div class="row" >
        <div class="col-sm-12" style="text-align: left;">
          <p>Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />
          </p>
        </div>
    </div>
  </div>
</div>

By the way, here is a much shorter solution.

$('input[type="checkbox"]').change(function() {
     $(".totcheck").val($('input[type="checkbox"]:checked').length);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
      <div class="row" >
        <div class="col-sm-12" id="Spirit" style="text-align: left;">
          <li>
            <label class="control control--checkbox">Content A
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content B
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content C
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
          <li>
            <label class="control control--checkbox"> Content D
              <input type="checkbox" id="r4" value="1"/>
              <div class="control__indicator"></div>
            </label>
          </li>
        </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-12" style="background: #ffdcdc; margin-bottom: 10px;">
    <h3 style="text-align: left;">Result</h3>
      <div class="row" >
        <div class="col-sm-12" style="text-align: left;">
          <p>Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />
          </p>
        </div>
    </div>
  </div>
</div>


问:
how to properly show / hide UIView on button click in iOS
I have a UIView, added in my xib file. Through connection inspector join it properly.

In viewDidLoad: method I am hiding it and on some button pressed showing it.

Here is my code so far:

.h file

```<code>@property (nonatomic, retain) IBOutlet UIView   *subView;
</code>```

in viewDidLoad: method:

```<code>_subView.hidden = YES;
</code>```

It is hiding this view properly, but on button pressed it is not showing up.

```<code>- (IBAction)customerInvoice:(id)sender
{
//self->_subView.hidden = NO;
_subView.hidden = NO;
}
</code>```

Using both ways it is not showing up. Please, help me to resolve it.

答:
First Declare view:

```<code>  @property (weak, nonatomic) IBOutlet UIView *select_image_uiview;
</code>```

Button Click Action:

```<code>   - (IBAction)cancel_choose_view:(id)sender
 {
    _select_image_uiview.hidden=YES;
   }
</code>```

Body:
I have a UIView, added in my xib file. Through connection inspector join it properly.

In viewDidLoad: method I am hiding it and on some button pressed showing it.

Here is my code so far:

.h file

@property (nonatomic, retain) IBOutlet UIView   *subView;

in viewDidLoad: method:

_subView.hidden = YES;

It is hiding this view properly, but on button pressed it is not showing up.

- (IBAction)customerInvoice:(id)sender
{
//self->_subView.hidden = NO;
_subView.hidden = NO;
}

Using both ways it is not showing up. Please, help me to resolve it.

Body:
First Declare view:

  @property (weak, nonatomic) IBOutlet UIView *select_image_uiview;

Button Click Action:

   - (IBAction)cancel_choose_view:(id)sender
 {
    _select_image_uiview.hidden=YES;
   }


问:
How to save matplotlib plot with the same file name as its filename.py
I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

```<code>if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')
</code>```

I want to change the last line to something like

```<code>  # pseudocode
  plt.savefig(variable, '.png')
</code>```

I tested

```<code>  plt.savefig(__file__, ".png")
</code>```

The saved filename had .py, the file path, and the space before .png which I don't want

答:
To save the figure with same name as the python file, replacing the ".py" by ".png" and removing the path, I would use :

```<code>plt.gcf().savefig(__file__.rstrip('.py').split('/')[-1] + ".png")
</code>```

the rstrip removes ".py" from the right side of the file string,
the split method separate your chains at each "/" and [-1] keeps only the last item of the list
the + can be used to concatenate strings

Body:
I run the python code for Matplotlib plotting from thisfilename.py. Is there a variable that stores this filename without file path? As I want to save the plot as thisfilename.png without typing the file name like this every time?

if __name__ == '__main__':
  ...
  plt.savefig('thisfilename.png')

I want to change the last line to something like

  # pseudocode
  plt.savefig(variable, '.png')

I tested

  plt.savefig(__file__, ".png")

The saved filename had .py, the file path, and the space before .png which I don't want

Body:
To save the figure with same name as the python file, replacing the ".py" by ".png" and removing the path, I would use :

plt.gcf().savefig(__file__.rstrip('.py').split('/')[-1] + ".png")

the rstrip removes ".py" from the right side of the file string,
the split method separate your chains at each "/" and [-1] keeps only the last item of the list
the + can be used to concatenate strings


问:
upload image to multiple models in rails
I am using carrierwave and Minimagick gem to upload an attachment to S3. Now I want to save the some.pdf in two models(ie, assignment, and message). I give the same parameters in attachment field to save in two tables. But the second table attachment saves blurry. First one gets clear view of attachment.

My controller codes like,

```<code>@assignment = Assignment.new(assignment_params)
@message = Message.new
begin
  Message.transaction do
    asign_att = params[:assignment][:attachment]
    @assignment.save!

    @message.attachment = asign_att
    @message.save!
  end
end
</code>```

My model has,

```<code>(in attachment.rb) mount_uploader :attachment, AttachmentUploader
(in message.rb) mount_uploader :attachment, ImageUploader
</code>```

I want to save same file into two models with clear view. What I want to do? Thanks in advance.

答:
Check in your second table uploader file if you have specified any version or something like that.
With version you can create clones of attachment in different resolutions like this.</p>

```<code> version :thumb do
    process resize_to_fit 50, 50
 end
</code>```

Body:
I am using carrierwave and Minimagick gem to upload an attachment to S3. Now I want to save the some.pdf in two models(ie, assignment, and message). I give the same parameters in attachment field to save in two tables. But the second table attachment saves blurry. First one gets clear view of attachment.

My controller codes like,

@assignment = Assignment.new(assignment_params)
@message = Message.new
begin
  Message.transaction do
    asign_att = params[:assignment][:attachment]
    @assignment.save!

    @message.attachment = asign_att
    @message.save!
  end
end

My model has,

(in attachment.rb) mount_uploader :attachment, AttachmentUploader
(in message.rb) mount_uploader :attachment, ImageUploader

I want to save same file into two models with clear view. What I want to do? Thanks in advance.

Body:
Check in your second table uploader file if you have specified any version or something like that.
With version you can create clones of attachment in different resolutions like this.

 version :thumb do
    process resize_to_fit 50, 50
 end


问:
Convert string type to 8 digit in c#
I need to convert this value to 8 digit format. (example : 1 --> 00000001).any help? here's my code</p>

```<code>foreach(DataRow dr in _dsGridCsv.Tables[0].Rows)
  {
     byte empfrmat =byte.Parse(dr["emp_id"].ToString());
     csv += empfrmat;
     csv += "\r\n";
  }
</code>```

答:
strValue.ToString("D8");

D8 means format as a decimal with up to 8 leading zeroes

Title: Convert string type to 8 digit in c#

Body:
I need to convert this value to 8 digit format. (example : 1 --> 00000001).any help? here's my code

foreach(DataRow dr in _dsGridCsv.Tables[0].Rows)
  {
     byte empfrmat =byte.Parse(dr["emp_id"].ToString());
     csv += empfrmat;
     csv += "\r\n";
  }


问:
Force sorting json in PHP
How can I sort label in order:

```<code>1080p
720p
480p
360p
</code>```

I've tried all Sorting Arrays in PHP documentation and some another "User Defined" sorting functions, but no luck, it shows completely random, not in order.

My original json:

```<code>[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]
</code>```

答:
This looks pretty straight forward to me, you use a custom comparison function for the sorting: </p>

```<code><?php
$data = json_decode(<<<JSON
[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]
JSON
);

usort($data, function($a, $b) {
  return intval($a->label) < intval($b->label);
});
print_r($data);
</code>```

<p>The output obviously is: </p>

```<code>Array
(
    [0] => stdClass Object
        (
            [file] => ***
            [label] => 1080p
            [type] => video/mp4
        )

    [1] => stdClass Object
        (
            [file] => ***
            [label] => 720p
            [type] => video/mp4
        )

    [2] => stdClass Object
        (
            [file] => ***
            [label] => 480p
            [type] => video/mp4
        )

    [3] => stdClass Object
        (
            [file] => ***
            [label] => 360p
            [default] => true
            [type] => video/mp4
        )

)
</code>```

Title: Force sorting json in PHP

Body:
How can I sort label in order:

1080p
720p
480p
360p

I've tried all Sorting Arrays in PHP documentation and some another "User Defined" sorting functions, but no luck, it shows completely random, not in order.

My original json:

[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]

Body:
This looks pretty straight forward to me, you use a custom comparison function for the sorting:

<?php
$data = json_decode(<<<JSON
[{"file":"***","label":"360p","default":"true","type":"video\/mp4"},
{"file":"***","label":"720p","type":"video\/mp4"},
{"file":"***","label":"1080p","type":"video\/mp4"},
{"file":"***","label":"480p","type":"video\/mp4"}]
JSON
);

usort($data, function($a, $b) {
  return intval($a->label) < intval($b->label);
});
print_r($data);

The output obviously is:

Array
(
    [0] => stdClass Object
        (
            [file] => ***
            [label] => 1080p
            [type] => video/mp4
        )

    [1] => stdClass Object
        (
            [file] => ***
            [label] => 720p
            [type] => video/mp4
        )

    [2] => stdClass Object
        (
            [file] => ***
            [label] => 480p
            [type] => video/mp4
        )

    [3] => stdClass Object
        (
            [file] => ***
            [label] => 360p
            [default] => true
            [type] => video/mp4
        )

)


问:
PowerShell two parameters either of them can be null but not both null
I'm wondering if this can be done at the parameter level rather in code:
I have 2 parameter: $School and $Class

```<code>Get-Students -School SchooName # Will give me all Students name in all classes in that School
Get-Students -Class ClassName  # Will give me all Students name in that Class across all schools
Get-Students                   # Should return parameter level error.
</code>```

I tried to use following:

```<code>function Get-Students{
param(
    [parameter(ParameterSetName="School no null")]
    [ValidateNotNullOrEmpty()]
    [string]$School,
    [parameter(ParameterSetName="School no null")]
    [AllowNull()]
    [string]$Class,
    [parameter(ParameterSetName="Class no null")]
    [AllowNull()]
    [string]$School,
    [parameter(ParameterSetName="Class no null")]
    [ValidateNotNullOrEmpty()]
    [string]$Class
)
}
</code>```

But it doesn't work in this way...

Hope I explained this correctly. Or if there is no way can do this from parameter only inside of the code?

Thanks
River

答:
You can test them in code instead of trying to stuff this check into parameter set.</p>

```<code>if ($School -eq $null -and $Class -eq $null) {throw "School and Class must not be null together!"}
</code>```

Body:
I'm wondering if this can be done at the parameter level rather in code:
I have 2 parameter: $School and $Class

Get-Students -School SchooName # Will give me all Students name in all classes in that School
Get-Students -Class ClassName  # Will give me all Students name in that Class across all schools
Get-Students                   # Should return parameter level error.

I tried to use following:

function Get-Students{
param(
    [parameter(ParameterSetName="School no null")]
    [ValidateNotNullOrEmpty()]
    [string]$School,
    [parameter(ParameterSetName="School no null")]
    [AllowNull()]
    [string]$Class,
    [parameter(ParameterSetName="Class no null")]
    [AllowNull()]
    [string]$School,
    [parameter(ParameterSetName="Class no null")]
    [ValidateNotNullOrEmpty()]
    [string]$Class
)
}

But it doesn't work in this way...

Hope I explained this correctly. Or if there is no way can do this from parameter only inside of the code?

Thanks
River

Body:
You can test them in code instead of trying to stuff this check into parameter set.

if ($School -eq $null -and $Class -eq $null) {throw "School and Class must not be null together!"}


问:
How to throw compile time exception, if certain value is not set.
I have created an Android library, there is a method setContext()in it. Client need to pass context other wise app will crash at runtime. I need to throw an error on compile time, if user does not set context. I can't pass it throw constructor as its a singleton class.

Client

```<code>SampleLibrary sl= SampleLibrary.getInstance();
sl.setContext(this);
</code>```

Class

```<code>public void setContext(Context context){
  this.context= context;
}
</code>```

Kindly guide me How to throw compile time exception, if certain value is not set or null.

答:
```<code>try {

   //your statement here

}

catch (RuntimeException ex)

{

//do something with the runtime exception

}
</code>```

Body:
I have created an Android library, there is a method setContext()in it. Client need to pass context other wise app will crash at runtime. I need to throw an error on compile time, if user does not set context. I can't pass it throw constructor as its a singleton class.

Client

SampleLibrary sl= SampleLibrary.getInstance();
sl.setContext(this);

Class

public void setContext(Context context){
  this.context= context;
}

Kindly guide me How to throw compile time exception, if certain value is not set or null.


问:
Importing csv file in postgres 9.5 need to replace /n with null
I want to import csv file to a table. The CSV file contains the new line as \N.

While copying it saves to my database. So needs to replace that /n to NULL while importing through

```<code>copy tbl_created_doc_no FROM '/Desktop/admin/document_no.csv' (FORMAT csv, HEADER, DELIMITER ';');
</code>```

Can anyone suggest an option for replacing

答:
https://www.postgresql.org/docs/current/static/sql-copy.html

NULL

Specifies the string that represents a null value. The default is \N
  (backslash-N) in text format, and an unquoted empty string in CSV
  format. You might prefer an empty string even in text format for cases
  where you don't want to distinguish nulls from empty strings. This
  option is not allowed when using binary format.

So if youwant csv format, specify NULL yourself with NULL '\N', example:

```<code>t=# select * from so78;
                h                 | i
----------------------------------+---
 2e346ec46b4ae31f54bf3ad3d90d3183 | 1
t=#  copy so78 from stdin (delimiter ';', null '\N', format csv);
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> a;\N
>> \.
COPY 1
t=# select * from so78;
                h                 | i
----------------------------------+---
 2e346ec46b4ae31f54bf3ad3d90d3183 | 1
 a                                |
</code>```

Body:
I want to import csv file to a table. The CSV file contains the new line as \N.

While copying it saves to my database. So needs to replace that /n to NULL while importing through

copy tbl_created_doc_no FROM '/Desktop/admin/document_no.csv' (FORMAT csv, HEADER, DELIMITER ';');

Can anyone suggest an option for replacing

Body:
https://www.postgresql.org/docs/current/static/sql-copy.html

NULL

Specifies the string that represents a null value. The default is \N
  (backslash-N) in text format, and an unquoted empty string in CSV
  format. You might prefer an empty string even in text format for cases
  where you don't want to distinguish nulls from empty strings. This
  option is not allowed when using binary format.

So if youwant csv format, specify NULL yourself with NULL '\N', example:

t=# select * from so78;
                h                 | i
----------------------------------+---
 2e346ec46b4ae31f54bf3ad3d90d3183 | 1
t=#  copy so78 from stdin (delimiter ';', null '\N', format csv);
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> a;\N
>> \.
COPY 1
t=# select * from so78;
                h                 | i
----------------------------------+---
 2e346ec46b4ae31f54bf3ad3d90d3183 | 1
 a                                |


问:
Public key encryption using PKCS
I have looked into many threads to understand about how to create a PKCS encrypted file, but sadly none of the thread worked for me.

I am working on a requirement where I have to generate a PKCS file (p7 extension) using bounce castle(jdk 8) or any other API if available. If anyone has a working example of generating the PKCS encrypted file that would be great.

答:
Probably the question wasn't very clear, but I figured out the way to create a PKCS envelop using the bouncy castle API's. I am posting the answer here, it may be helpful to someone.</p>

```<code>import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.cms.CMSAlgorithm;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.bc.BcRSAKeyTransRecipientInfoGenerator;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.operator.OutputEncryptor;

// Create the pkcs #7 envelop and add content to it
            CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
            fact.addRecipientInfoGenerator(
                    new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder((X509Certificate) cert)));
            OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC")
                    .build();
            CMSProcessableByteArray content = new CMSProcessableByteArray(zipdata);

            CMSEnvelopedData envdata = fact.generate(content, encryptor);
            byte[] enveloped = envdata.getEncoded();
</code>```

<p>'cert' is the X509 certificate, you can create a self signed certificate or a CA certificate. 'zipdata' is the byte array contents of the zip file and 'enveloped ' is the byte array PKCS envelop which contains the zip data. </p>

Title: Public key encryption using PKCS

Body:
Probably the question wasn't very clear, but I figured out the way to create a PKCS envelop using the bouncy castle API's. I am posting the answer here, it may be helpful to someone.

import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.cms.CMSAlgorithm;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.cms.CMSEnvelopedDataGenerator;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.bc.BcRSAKeyTransRecipientInfoGenerator;
import org.bouncycastle.cms.jcajce.JceCMSContentEncryptorBuilder;
import org.bouncycastle.operator.OutputEncryptor;

// Create the pkcs #7 envelop and add content to it
            CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
            fact.addRecipientInfoGenerator(
                    new BcRSAKeyTransRecipientInfoGenerator(new JcaX509CertificateHolder((X509Certificate) cert)));
            OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider("BC")
                    .build();
            CMSProcessableByteArray content = new CMSProcessableByteArray(zipdata);

            CMSEnvelopedData envdata = fact.generate(content, encryptor);
            byte[] enveloped = envdata.getEncoded();

'cert' is the X509 certificate, you can create a self signed certificate or a CA certificate. 'zipdata' is the byte array contents of the zip file and 'enveloped ' is the byte array PKCS envelop which contains the zip data.