问:
yii2 Kartik: Editable (Multi-)Select2 in GridView doesn't show loaded data
I tried to set up Kartik Gridview with Editable Columns. One Column is of type INPUT_SELECT2.

In the View i have the following definition:

```<code>$gridColumns = [
[
        'class'=>'kartik\grid\EditableColumn',
        'attribute'=>'occupation_ids',
         'value' => 'occuList',
        'editableOptions'=>[
            'header'=>'Occupations',
            'inputType'=>Editable::INPUT_SELECT2,
            'options' => [
                'attribute'=>'occupations',
                'data' => ArrayHelper::map(Occupation::find()->all(), 'id', 'description'),
                'options' => [
                    'multiple' => true,
                ],
                'pluginOptions' => [
                    'tags' => true,
                ],
            ],
            'asPopover' => false,
        ],
    ],
...];

echo GridView::widget([
        'dataProvider'=>$dataProvider,
        'columns'=>$gridColumns,
        'filterModel' => $searchModel,
    ]);
</code>```

Saving the values works perfectly. But if it comes to loading and displaying the saved data, i had to trick around to get things running.
The GridView holds a list of MonthlyEmployment. MonthlyEmployment has the following method

```<code> * @property Occupation[] $occupations
 */
class MonthlyEmployment extends \yii\db\ActiveRecord
{
    public $occupation_ids;

    public function getOccuList() {
        $arr = [];
        foreach ($this->occupations as $ocu) {
         $arr[] = $ocu->description;
        }
        if ($arr != null && !empty($arr)) {
            return implode(', ', $arr);
        } else {
             return '';
        }
    }
</code>```

So the saved Occupations are showed in the gridview. But if i open up the modul to edit the field the values aren't selected. Image below, to see what i mean.

GridView Editable Column (Multi)Select2

So has anyone a working example with Kartik GridView, Editable and Select2 ?

答:
have one without tags;
this is the controller:

```<code>public function actionIndex()
    {
      $model = new Model;
      $searchModel = new OrderSearch();
      $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

              if (isset($_POST['hasEditable'])) {
                      \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

                      if ($model->load($_POST)) {
                          $value = $model->status;
                          return ['output'=>$value, 'message'=>''];
                      }
                      else {
                          return ['output'=>'', 'message'=>''];
                      }
                  }

              return $this->render('indextoday', [
                  'searchModel' => $searchModel,
                  'dataProvider' => $dataProvider,
              ]);
    }
</code>```

and this is the column:

```<code><?php $data_from_desiredModel=ArrayHelper::map(desiredModel::find()
->orderBy('id')->asArray()->all(), 'id', 'name');?>

[
      'class'=>'kartik\grid\EditableColumn',
      'attribute'=>'name',
      'editableOptions'=>[
          'header'=>'Name',
          'inputType'=>\kartik\editable\Editable::INPUT_SELECT2,
          'data' => $data_from_desiredModel,
          ],
  ],
</code>```

Body:
I tried to set up Kartik Gridview with Editable Columns. One Column is of type INPUT_SELECT2.

In the View i have the following definition:

$gridColumns = [
[
        'class'=>'kartik\grid\EditableColumn',
        'attribute'=>'occupation_ids',
         'value' => 'occuList',
        'editableOptions'=>[
            'header'=>'Occupations',
            'inputType'=>Editable::INPUT_SELECT2,
            'options' => [
                'attribute'=>'occupations',
                'data' => ArrayHelper::map(Occupation::find()->all(), 'id', 'description'),
                'options' => [
                    'multiple' => true,
                ],
                'pluginOptions' => [
                    'tags' => true,
                ],
            ],
            'asPopover' => false,
        ],
    ],
...];

echo GridView::widget([
        'dataProvider'=>$dataProvider,
        'columns'=>$gridColumns,
        'filterModel' => $searchModel,
    ]);

Saving the values works perfectly. But if it comes to loading and displaying the saved data, i had to trick around to get things running.
The GridView holds a list of MonthlyEmployment. MonthlyEmployment has the following method

 * @property Occupation[] $occupations
 */
class MonthlyEmployment extends \yii\db\ActiveRecord
{
    public $occupation_ids;

    public function getOccuList() {
        $arr = [];
        foreach ($this->occupations as $ocu) {
         $arr[] = $ocu->description;
        }
        if ($arr != null && !empty($arr)) {
            return implode(', ', $arr);
        } else {
             return '';
        }
    }

So the saved Occupations are showed in the gridview. But if i open up the modul to edit the field the values aren't selected. Image below, to see what i mean.

GridView Editable Column (Multi)Select2

So has anyone a working example with Kartik GridView, Editable and Select2 ?

Body:
have one without tags;
this is the controller:

public function actionIndex()
    {
      $model = new Model;
      $searchModel = new OrderSearch();
      $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

              if (isset($_POST['hasEditable'])) {
                      \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

                      if ($model->load($_POST)) {
                          $value = $model->status;
                          return ['output'=>$value, 'message'=>''];
                      }
                      else {
                          return ['output'=>'', 'message'=>''];
                      }
                  }

              return $this->render('indextoday', [
                  'searchModel' => $searchModel,
                  'dataProvider' => $dataProvider,
              ]);
    }

and this is the column:

<?php $data_from_desiredModel=ArrayHelper::map(desiredModel::find()
->orderBy('id')->asArray()->all(), 'id', 'name');?>

[
      'class'=>'kartik\grid\EditableColumn',
      'attribute'=>'name',
      'editableOptions'=>[
          'header'=>'Name',
          'inputType'=>\kartik\editable\Editable::INPUT_SELECT2,
          'data' => $data_from_desiredModel,
          ],
  ],


来源: stackexchange

问:
Replace comma with newline and write to text file
I want to take value on the database and replace the comma with a newline and then write to a text file.

Example:

```<code>SELECT column FROM table WHERE ID = 6
Result: Monday,Tuesday,Wednesday,Thursday,Friday
</code>```

I want it to then remove the commas and write to a .txt file with newline.

Result:

```<code>Monday

Tuesday

Wednesday

Thursday

Friday
</code>```

Hope this makes sense.

答:
File_put_contents saves the file file.txt. http://php.net/manual/en/function.file-put-contents.php<br>
Str_replace replace the commas with new line. http://php.net/manual/en/function.str-replace.php  </p>

```<code>File_put_contents("file.txt", str_replace(",", PHP_EOL, $string));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to take value on the database and replace the comma with a newline and then write to a text file.

Example:

SELECT column FROM table WHERE ID = 6
Result: Monday,Tuesday,Wednesday,Thursday,Friday

I want it to then remove the commas and write to a .txt file with newline.

Result:

Monday

Tuesday

Wednesday

Thursday

Friday

Hope this makes sense.

Body:
File_put_contents saves the file file.txt. http://php.net/manual/en/function.file-put-contents.php

Str_replace replace the commas with new line. http://php.net/manual/en/function.str-replace.php

File_put_contents("file.txt", str_replace(",", PHP_EOL, $string));


问:
How to remove a part of all strings in an array in javascript?
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.

答:
Something Like This

```<code>`for(let index = 0; index < gUser.length; index++) {
    console.log(gUser[index].split('.').splice(0, 1).join('.'));
}`
</code>```

I haven't tested it. Please check and let me know

Body:
Something Like This

`for(let index = 0; index < gUser.length; index++) {
    console.log(gUser[index].split('.').splice(0, 1).join('.'));
}`

I haven't tested it. Please check and let me know


问:
WSO2ESB Rest API error: Invalid UTF-8 middle byte 0x6f (at char #143, byte #127)
I developed a REST API in wso2esb 5.0.0 and I am facing some problems when client send a request that contains ã, ç or é for example, the first mediator on inSequence pipeline, Raise an error about Invalid UTF-8 middle byte.

When we force charset of message in HTTP header as ISO-8859-1, works fine. But we need to work with UTF-8.

Somebody already face this issue and could help me?

Following the stack trace off error:

```<code>TID[-1234] [ESB] [2017-07-04 15:12:26,738] ERROR {API_LOGGER.ResourceAPI} - Could not build full log message: [com.ctc.wstx.exc.WstxLazyException] Invalid UTF-8 middle byte 0x6f (at char #143, byte #127) com.ctc.wstx.exc.WstxLazyException.throwLazily(WstxLazyException.java:45) com.ctc.wstx.sr.StreamScanner.throwLazyError(StreamScanner.java:720) com.ctc.wstx.sr.BasicStreamReader.safeFinishToken(BasicStreamReader.java:3677) com.ctc.wstx.sr.BasicStreamReader.getText(BasicStreamReader.java:858) org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.getText(XMLStreamReaderWrapper.java:164) org.apache.axiom.om.impl.builder.StAXBuilder.createOMText(StAXBuilder.java:289) org.apache.axiom.om.impl.builder.StAXBuilder.createOMText(StAXBuilder.java:250) org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:252) org.apache.axiom.om.impl.llom.OMElementImpl.buildNext(OMElementImpl.java:653) org.apache.axiom.om.impl.llom.OMElementImpl.getFirstOMChild(OMElementImpl.java:670) org.apache.axiom.om.impl.llom.OMElementImpl.getChildren(OMElementImpl.java:352) org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:553) org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875) org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:555) org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875) org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:555) org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875) org.apache.axiom.soap.impl.llom.SOAPEnvelopeImpl.internalSerialize(SOAPEnvelopeImpl.java:230) org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:125) org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:113) org.apache.axiom.om.impl.llom.OMElementImpl.toString(OMElementImpl.java:988) java.lang.String.valueOf(String.java:2994) java.lang.StringBuffer.append(StringBuffer.java:265) org.apache.synapse.mediators.builtin.LogMediator.getFullLogMessage(LogMediator.java:203) org.apache.synapse.mediators.builtin.LogMediator.getLogMessage(LogMediator.java:138) org.apache.synapse.mediators.builtin.LogMediator.mediate(LogMediator.java:101) org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:97) org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:59) org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158) org.apache.synapse.rest.Resource.process(Resource.java:343) org.apache.synapse.rest.API.process(API.java:399) org.apache.synapse.rest.RESTRequestHandler.apiProcess(RESTRequestHandler.java:123) org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:101) org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:69) org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:304) org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:75) org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) org.apache.axis2.transport.http.util.RESTUtil.invokeAxisEngine(RESTUtil.java:144) org.apache.axis2.transport.http.util.RESTUtil.processXMLRequest(RESTUtil.java:89) org.apache.synapse.transport.nhttp.util.RESTUtil.processPOSTRequest(RESTUtil.java:213) org.apache.synapse.transport.nhttp.ServerWorker.processEntityEnclosingMethod(ServerWorker.java:468) org.apache.synapse.transport.nhttp.ServerWorker.run(ServerWorker.java:291) org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)
</code>```

Note: When we use common SOAP proxy and messages works fine. No problem with charset.

[EDITED]

Note: Like @weibeld said, my language is Portuguese.

My REST API has a resource with POST method and I am sending the following request to server:

```<code>POST http://myHost:8280/api/v1/myResource HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json;charset=utf-8
Content-Length: 741
Host: myHost:8280
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

 {
"customerName": "CONSULTORIA EMPRESARIAL EIRELI - ME",
"serviceId": "05948517",
"productName": "Banda Larga Expansão Sul",
"localityCode": "51000",
"status": "OCUPADO",
"isChangeOfAddress": "FALSO",
"serial": "0047848517",
"vlanType": "1Q",
"ont_id": "0047848517",
"modelo_ont": "ZHONE-2425",
"accessType": "GPON",
"streetCode": "4535",
"neighbourhood": "NEIGHBOURHOOD",
"streetNumber": "4428",
"complement1": "2"
</code>```

}

Note: In this line "productName": "Banda Larga Expansão Sul", I have an ão.

Summarizing, I am sending a POST, wiht application/json;charset=utf-8 and the wso2esb is raising an error about the ão, and when I sent an ISO-8859-1 works fine. (when I use soap with utf-8 works properly).

答:
It seems that the the HTTP request that your client sends to the server is encoded with ISO-8859-1 rather than with UTF-8.

The server then tries to decode this request with UTF-8. This works well for all ASCII characters. However, at some point the server encounters the ISO 8859-1 code of one of your reported non-ASCII characters:

ã ==> 0xE3 = 11100011

ç ==> 0xE7 = 11100111

é ==> 0xE9 = 11101001

(Read the above listing as: [character] ==> [ISO 8859-1 code hex.] = [ISO 8859-1 code bin.])

Now UTF-8 interprets this byte as the leading byte of a 3-byte UTF-8 code because it starts with 1110 (see here). Consequently, UTF-8 expects the next byte to be a UTF-8 continuation byte, which must start with 10. However, the next byte is 0x6f, the ISO 8859-1 code for the ASCII character o, which is 01101111 in binary, i.e. does not start with 10.

Hence the error message Invalid UTF-8 middle byte 0x6f.

So, I guess that your request contains the substring ão, ço, or éo, which is likely if your language is Portuguese.

In summary: you need to make sure that the client encodes the request with UTF-8. I don't know how you create the request, but there should be a possibility to set the encoding in whatever function you use.

Body:
I developed a REST API in wso2esb 5.0.0 and I am facing some problems when client send a request that contains ã, ç or é for example, the first mediator on inSequence pipeline, Raise an error about Invalid UTF-8 middle byte.

When we force charset of message in HTTP header as ISO-8859-1, works fine. But we need to work with UTF-8.

Somebody already face this issue and could help me?

Following the stack trace off error:

TID[-1234] [ESB] [2017-07-04 15:12:26,738] ERROR {API_LOGGER.ResourceAPI} - Could not build full log message: [com.ctc.wstx.exc.WstxLazyException] Invalid UTF-8 middle byte 0x6f (at char #143, byte #127) com.ctc.wstx.exc.WstxLazyException.throwLazily(WstxLazyException.java:45) com.ctc.wstx.sr.StreamScanner.throwLazyError(StreamScanner.java:720) com.ctc.wstx.sr.BasicStreamReader.safeFinishToken(BasicStreamReader.java:3677) com.ctc.wstx.sr.BasicStreamReader.getText(BasicStreamReader.java:858) org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper.getText(XMLStreamReaderWrapper.java:164) org.apache.axiom.om.impl.builder.StAXBuilder.createOMText(StAXBuilder.java:289) org.apache.axiom.om.impl.builder.StAXBuilder.createOMText(StAXBuilder.java:250) org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:252) org.apache.axiom.om.impl.llom.OMElementImpl.buildNext(OMElementImpl.java:653) org.apache.axiom.om.impl.llom.OMElementImpl.getFirstOMChild(OMElementImpl.java:670) org.apache.axiom.om.impl.llom.OMElementImpl.getChildren(OMElementImpl.java:352) org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:553) org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875) org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:555) org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875) org.apache.axiom.om.impl.util.OMSerializerUtil.serializeChildren(OMSerializerUtil.java:555) org.apache.axiom.om.impl.llom.OMElementImpl.internalSerialize(OMElementImpl.java:875) org.apache.axiom.soap.impl.llom.SOAPEnvelopeImpl.internalSerialize(SOAPEnvelopeImpl.java:230) org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:125) org.apache.axiom.om.impl.llom.OMSerializableImpl.serialize(OMSerializableImpl.java:113) org.apache.axiom.om.impl.llom.OMElementImpl.toString(OMElementImpl.java:988) java.lang.String.valueOf(String.java:2994) java.lang.StringBuffer.append(StringBuffer.java:265) org.apache.synapse.mediators.builtin.LogMediator.getFullLogMessage(LogMediator.java:203) org.apache.synapse.mediators.builtin.LogMediator.getLogMessage(LogMediator.java:138) org.apache.synapse.mediators.builtin.LogMediator.mediate(LogMediator.java:101) org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:97) org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:59) org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:158) org.apache.synapse.rest.Resource.process(Resource.java:343) org.apache.synapse.rest.API.process(API.java:399) org.apache.synapse.rest.RESTRequestHandler.apiProcess(RESTRequestHandler.java:123) org.apache.synapse.rest.RESTRequestHandler.dispatchToAPI(RESTRequestHandler.java:101) org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:69) org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:304) org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:75) org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180) org.apache.axis2.transport.http.util.RESTUtil.invokeAxisEngine(RESTUtil.java:144) org.apache.axis2.transport.http.util.RESTUtil.processXMLRequest(RESTUtil.java:89) org.apache.synapse.transport.nhttp.util.RESTUtil.processPOSTRequest(RESTUtil.java:213) org.apache.synapse.transport.nhttp.ServerWorker.processEntityEnclosingMethod(ServerWorker.java:468) org.apache.synapse.transport.nhttp.ServerWorker.run(ServerWorker.java:291) org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) java.lang.Thread.run(Thread.java:745)

Note: When we use common SOAP proxy and messages works fine. No problem with charset.

[EDITED]

Note: Like @weibeld said, my language is Portuguese.

My REST API has a resource with POST method and I am sending the following request to server:

POST http://myHost:8280/api/v1/myResource HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: application/json;charset=utf-8
Content-Length: 741
Host: myHost:8280
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)

 {
"customerName": "CONSULTORIA EMPRESARIAL EIRELI - ME",
"serviceId": "05948517",
"productName": "Banda Larga Expansão Sul",
"localityCode": "51000",
"status": "OCUPADO",
"isChangeOfAddress": "FALSO",
"serial": "0047848517",
"vlanType": "1Q",
"ont_id": "0047848517",
"modelo_ont": "ZHONE-2425",
"accessType": "GPON",
"streetCode": "4535",
"neighbourhood": "NEIGHBOURHOOD",
"streetNumber": "4428",
"complement1": "2"

}

Note: In this line "productName": "Banda Larga Expansão Sul", I have an ão.

Summarizing, I am sending a POST, wiht application/json;charset=utf-8 and the wso2esb is raising an error about the ão, and when I sent an ISO-8859-1 works fine. (when I use soap with utf-8 works properly).


问:
How to check if a given path is possible child of another path?
I am trying to find if given path is possible child of another path using java. Both path may not exist.

Say c:\Program Files\My Company\test\My App is a possible child of c:\Program Files.

Currently I am doing this with

```<code>boolean myCheck(File maybeChild, File possibleParent)
{
    return maybeChild.getAbsolutePath().startsWith( possibleParent.getAbsolutePath());
}
</code>```

答:
Old question but a pre-1.7 solution:

```<code>public boolean startsWith(String possibleRoot, String possibleChildOrSame) {
        String[] possiblePath = new File(possibleRoot).getAbsolutePath().replace('\\', '/').split("/");
        String[] possibleChildOrSamePath = new File(possibleChildOrSame).getAbsolutePath().replace('\\', '/').split("/");

        if (possibleChildOrSamePath.length < possiblePath.length) {
            return false;
        }

        // not ignoring case
        for (int i = 0; i < possiblePath.length; i++) {
            if (!possiblePath[i].equals(possibleChildOrSamePath[i])) {
                return false;
            }
        }
        return true;
}
</code>```

For completeness the java 1.7+ solution:

```<code>public boolean startsWith(String possibleRoot, String possibleChildOrSame) {
        Path p1 = Paths.get(possibleChildOrSame).toAbsolutePath();
        Path p2 = Paths.get(possibleRoot).toAbsolutePath();
        return p1.startsWith(p2);
}
</code>```

Body:
I am trying to find if given path is possible child of another path using java. Both path may not exist.

Say c:\Program Files\My Company\test\My App is a possible child of c:\Program Files.

Currently I am doing this with

boolean myCheck(File maybeChild, File possibleParent)
{
    return maybeChild.getAbsolutePath().startsWith( possibleParent.getAbsolutePath());
}

Body:
Old question but a pre-1.7 solution:

public boolean startsWith(String possibleRoot, String possibleChildOrSame) {
        String[] possiblePath = new File(possibleRoot).getAbsolutePath().replace('\\', '/').split("/");
        String[] possibleChildOrSamePath = new File(possibleChildOrSame).getAbsolutePath().replace('\\', '/').split("/");

        if (possibleChildOrSamePath.length < possiblePath.length) {
            return false;
        }

        // not ignoring case
        for (int i = 0; i < possiblePath.length; i++) {
            if (!possiblePath[i].equals(possibleChildOrSamePath[i])) {
                return false;
            }
        }
        return true;
}

For completeness the java 1.7+ solution:

public boolean startsWith(String possibleRoot, String possibleChildOrSame) {
        Path p1 = Paths.get(possibleChildOrSame).toAbsolutePath();
        Path p2 = Paths.get(possibleRoot).toAbsolutePath();
        return p1.startsWith(p2);
}


问:
How can I use Sidekiq delay with a worker
I have a situation where I have a worker that makes multiple calls to an external API. The problem is that we have a threshold of many calls we can make to this API per hour.

What I'd like to do is to create a worker which will make these many sequential calls to this external API. If in between these calls we get an error because we've reached the number of connections we're allowed in that hour, the worker would then save the document and schedule a new worker to complete the remaining API calls at a later time (maybe 1, 2 hours later. Ideally this should be configurable e.g.: 10mins, 1hour, etc).

Is there someway I could achieve this?

答:
With SideKiq you can scheduled when a job will be executed with a friendly API :

```<code>MyWorker.perform_in(3.hours, 'mike', 1) # Expect a duration
MyWorker.perform_at(3.hours.from_now, 'mike', 1) # Expect a date
</code>```

Check it out : Scheduled Jobs

Body:
With SideKiq you can scheduled when a job will be executed with a friendly API :

MyWorker.perform_in(3.hours, 'mike', 1) # Expect a duration
MyWorker.perform_at(3.hours.from_now, 'mike', 1) # Expect a date

Check it out : Scheduled Jobs


问:
jQuery CSS - Write into the

    ...

       // ....

```

<p><strong>jQuery</strong></p>

```$('body').css('background-color','#ff0000');
```

<p><strong>Result</strong></p>

```
   // ....

```

答:
As commented above, jqueryEl.text should also work:

```<code>$("<style/>").text(css).appendTo(document.head);
</code>```

Title: jQuery CSS - Write into the <style>-tag

Body:
I want to change the background-color of the body of my HTML document. My problem is that jQuery adds the style to the body tag, but I want to change the value in the style tag. Is this possible using jQuery?

Example-Code

    ...

       // ....

jQuery

$('body').css('background-color','#ff0000');

Result

   // ....

Body:
As commented above, jqueryEl.text should also work:

$("<style/>").text(css).appendTo(document.head);

ContentLicense: CC BY-SA 4.0


答:
assuming you know how to execute your query and fetch the result:

it basically comes to the function str_replace. (could also be replaced in the query using mysql's REPLACE() function)

```<code><?php
  file_put_contents('/myfile.txt', str_replace(',', PHP_EOL, $row['column']));
</code>```

But your question is quit limited in information.

btw: should the file not be overwritten: Use FILE_APPEND as 3rd parameter of file_put_contents

Title: Replace comma with newline and write to text file

Body:
assuming you know how to execute your query and fetch the result:

it basically comes to the function str_replace. (could also be replaced in the query using mysql's REPLACE() function)

<?php
  file_put_contents('/myfile.txt', str_replace(',', PHP_EOL, $row['column']));

But your question is quit limited in information.

btw: should the file not be overwritten: Use FILE_APPEND as 3rd parameter of file_put_contents


问:
Tab Layout tutorial incomplete?
I've been trying to implement the tab UI described in this tutorial: https://developer.android.com/resources/tutorials/views/hello-tabwidget.html

I follow all the steps described in the process but I keep getting a runtime exception which I believe has something to do with the fact that nowhere in the tutorial I added the extra activities (songs, artists and albums) related to the content of each tab into the android manifest file.

Am I correct? is this tutorial (like many others) faulty or incomplete?

答:
Since they seem to update these tutorials occasionally, I wouldn't doubt they forgot to mention this part back when this question was asked. They appear to have added a mention to this requirement in the tutorial now (as of 12/20/2010) in step 2:

Duplicate this for each of the three activities, and add the corresponding  tags to the Android Manifest file.

Unfortunately, since these are beginner tutorials, they should probably include what the XML tags should look like. Prior to this tutorial, they don't mention how to add activities to the manifest (though you add an activity at the end for hiding the title bar). The markup I used was identical to that on the other question mentioned in the OPs own answer:

```<code><activity android:name=".ArtistsActivity"></activity>
<activity android:name=".AlbumsActivity"></activity>
<activity android:name=".SongsActivity"></activity>
</code>```

There is a full reference on manifest activities on the Android developer site.

Title: Tab Layout tutorial incomplete?

Body:
Since they seem to update these tutorials occasionally, I wouldn't doubt they forgot to mention this part back when this question was asked. They appear to have added a mention to this requirement in the tutorial now (as of 12/20/2010) in step 2:

Duplicate this for each of the three activities, and add the corresponding  tags to the Android Manifest file.

Unfortunately, since these are beginner tutorials, they should probably include what the XML tags should look like. Prior to this tutorial, they don't mention how to add activities to the manifest (though you add an activity at the end for hiding the title bar). The markup I used was identical to that on the other question mentioned in the OPs own answer:

<activity android:name=".ArtistsActivity"></activity>
<activity android:name=".AlbumsActivity"></activity>
<activity android:name=".SongsActivity"></activity>

There is a full reference on manifest activities on the Android developer site.

ContentLicense: CC BY-SA 2.5


问:
Error Handling in UFT/QTP
I've a framework where the methods are called inside an action from Function Libraries. I'm trying to do error handling to avoid errors thrown by code written inside the function Libraries.

Below is my action code:

```<code>on error resume next
call TestMe()
if err.number Then: msgbox err.description
on error goto 0
</code>```

And here is the function inside function library:

```<code>Function TestMe()
   x = 1/0
End Function
</code>```

When I execute my test, on error resume next doesn't seems to be working as I get an error pop-up for division by zero inside the function TestMe().

How can I get these error handled without moving the code?

答:
Surprisingly with all the time using QTP/UFT never came up against such case. Was quite intriguing as well.
I Found out (or so it seems at first glance) that the scope of on error resume next is limited to its level (Library/Action) and couldn't be carried over to either.

You might wanna try something like:

Action Code:

```<code>Call Test3()
</code>```

Function Library:

```<code>Function Test1()
      x = 1/0
End Function

Function Test2()
   Call Test1()
   MsgBox "Test2"
End Function

Function Test3()
   On Error Resume next
   Call Test2()
   MsgBox err.Description
End Function
</code>```

The execution using this statement continues until it finds a handler. So you may set up a condition where ever you deem fit.

Another alternative is to use a flag (could be an environment variable) like

```<code>Environment("Flag") = True
</code>```

Whose condition can be checked directly in action code

Hope this helps. I'll still try to dig up more about this

Title: Error Handling in UFT/QTP

Body:
I've a framework where the methods are called inside an action from Function Libraries. I'm trying to do error handling to avoid errors thrown by code written inside the function Libraries.

Below is my action code:

on error resume next
call TestMe()
if err.number Then: msgbox err.description
on error goto 0

And here is the function inside function library:

Function TestMe()
   x = 1/0
End Function

When I execute my test, on error resume next doesn't seems to be working as I get an error pop-up for division by zero inside the function TestMe().

How can I get these error handled without moving the code?

Body:
Surprisingly with all the time using QTP/UFT never came up against such case. Was quite intriguing as well.
I Found out (or so it seems at first glance) that the scope of on error resume next is limited to its level (Library/Action) and couldn't be carried over to either.

You might wanna try something like:

Action Code:

Call Test3()

Function Library:

Function Test1()
      x = 1/0
End Function

Function Test2()
   Call Test1()
   MsgBox "Test2"
End Function

Function Test3()
   On Error Resume next
   Call Test2()
   MsgBox err.Description
End Function

The execution using this statement continues until it finds a handler. So you may set up a condition where ever you deem fit.

Another alternative is to use a flag (could be an environment variable) like

Environment("Flag") = True

Whose condition can be checked directly in action code

Hope this helps. I'll still try to dig up more about this


问:
Rails multiple exceptions handler with "exceptions_app" per route namespace
is there any solution how to handle Rails exceptions per route namespace with defined direction config.exceptions_app ?

I have versioned interface eg /api/v1, /api/v2. Every namespace uses different JSON/XML/HTML response structure.

Global definition is nice, but i need something more dynamic.

RESOLVE:

config.exceptions_app takes closure/lambda block. In that block i could create simple case statement like this:

```<code>config.exceptions_app = lambda do |env|
  case env['REQUEST_PATH']
  when %r{^(\/api\/v1)}
    Api::V1::ExceptionsController.action(:show).call(env)
  when %r{^(\/api\/v2)}
    Api::V2::ExceptionsController.action(:show).call(env)
  when %r{^(\/cms\/)}
    Cms::ExceptionsController.action(:show).call(env)
  end
end
</code>```

答:
Well you could subclass ActionDispatch::PublicExceptions and overwrite the call method to use the path information in the request object to get more dynamic. If you want to render different static files you'll have to overwrite render_html as well and use something more dynamic that just public_path.
Can't give a more detailed answer without more input from you.

Body:
is there any solution how to handle Rails exceptions per route namespace with defined direction config.exceptions_app ?

I have versioned interface eg /api/v1, /api/v2. Every namespace uses different JSON/XML/HTML response structure.

Global definition is nice, but i need something more dynamic.

RESOLVE:

config.exceptions_app takes closure/lambda block. In that block i could create simple case statement like this:

config.exceptions_app = lambda do |env|
  case env['REQUEST_PATH']
  when %r{^(\/api\/v1)}
    Api::V1::ExceptionsController.action(:show).call(env)
  when %r{^(\/api\/v2)}
    Api::V2::ExceptionsController.action(:show).call(env)
  when %r{^(\/cms\/)}
    Cms::ExceptionsController.action(:show).call(env)
  end
end


问:
How can I put some text with transparency and rotation in textbox with xlsxwriter
I am using module xlsxwriter to generate the sample reports and I want to add a graphic text to sign it. Like this:

I have read the documentation on Xlsxwriter's Site but I cannot find any solutions for setting transparency (I mean that you can see the Qty underneath character l) and rotation for the text. Could anyone have any ideas on this case?

答:
You can set transparency in a textbox in XlsxWriter by turning the solid fill  and the border off. Here is an example:
    import xlsxwriter

```<code>workbook = xlsxwriter.Workbook('textbox.xlsx')
worksheet = workbook.add_worksheet()

# Set the column wider for clarity.
worksheet.set_column('A:A', 60)

# Add some sample text.
for row in range(10):
    worksheet.write(row, 0, "Here is some text in the background")

# Set the textbox options.
options = {
    'width': 500,
    'height': 100,
    'font': {'italic': True,
             'color': '#DDDDDD',
             'size': 60},
    'fill': {'none': True},
    'line': {'none': True},
}

# Insert the textbox over the cell text.
worksheet.insert_textbox('A3', 'Sample Report', options)

workbook.close()
</code>```

Output:

See the Working with Textboxes section of the XlsxWriter documentation.

However, I don't think it is possible in Excel to rotate the text in a textbox (apart from vertical and rotate up/down). The option to rotate at an angle is greyed out in Excel.

I think the image in your post is probably achieved using WordArt, which isn't supported by XlsxWriter.

Body:
You can set transparency in a textbox in XlsxWriter by turning the solid fill  and the border off. Here is an example:
    import xlsxwriter

workbook = xlsxwriter.Workbook('textbox.xlsx')
worksheet = workbook.add_worksheet()

# Set the column wider for clarity.
worksheet.set_column('A:A', 60)

# Add some sample text.
for row in range(10):
    worksheet.write(row, 0, "Here is some text in the background")

# Set the textbox options.
options = {
    'width': 500,
    'height': 100,
    'font': {'italic': True,
             'color': '#DDDDDD',
             'size': 60},
    'fill': {'none': True},
    'line': {'none': True},
}

# Insert the textbox over the cell text.
worksheet.insert_textbox('A3', 'Sample Report', options)

workbook.close()

Output:

See the Working with Textboxes section of the XlsxWriter documentation.

However, I don't think it is possible in Excel to rotate the text in a textbox (apart from vertical and rotate up/down). The option to rotate at an angle is greyed out in Excel.

I think the image in your post is probably achieved using WordArt, which isn't supported by XlsxWriter.


问:
SDK location not found
am new in using react native.
I install android studio , nodejs , npm .
Then i connect my device to run the app.When running it i get this  error

could anyone help me How  to fix sdk  location in my app ?
ps: am using linux mint as OS .

Thanks for help

答:
If this is your first build you must define %ANDROID_HOME% path first in the "Environment Variables"

Copy path to your sdk folder

Open System Properties\Advanced\Environment Variables (search for keyword "environment" for shortcut)

Press "New" in "User variables..." panel

Type "ANDROID_HOME" in "variable name" and paste your SDK path --> press Ok

Title: SDK location not found


问:
Storing Images in Firebase with Authentication ID- Xamarin
I am able to save images into my firebase storage but then, in the storage, there is nothing to tell me the id of the user who uploaded the photo. In my app, users can upload photos for blogs and as much as that is concerned, every photo updated should have the id of the user and also an the key of the blog respectively. So it would be easy for me to fetch the images respectively for each blog. How can i achieve this?

This is how i save my images

```<code> public void OnClick(View v)
        {
            Intent intent = new Intent();
            intent.SetType("image/*");
            intent.SetAction(Intent.ActionPick);
            StartActivityForResult(Intent.CreateChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);

        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            try{
                Bitmap bitmap = MediaStore.Images.Media.GetBitmap(this.ContentResolver, data.Data);
                using (MemoryStream stream = new MemoryStream())
                {
                    bitmap.Compress(Bitmap.CompressFormat.Jpeg,100,stream);
                    byte[] array = stream.ToArray();

                    imageViewDrop.SetImageBitmap(bitmap);

                }

                if(data.Data != null){
                     pd = new ProgressDialog(this);
                   pd.SetTitle("Uploading");
                    pd.Show();

                    StorageReference images = storageRef.Child("images");

                    images.PutFile(data.Data).AddOnSuccessListener(this);
                    images.PutFile(data.Data).AddOnProgressListener(this);
                }

                else {

                }

                imageViewDrop.SetImageBitmap(bitmap);

            }
            catch (Java.Lang.Exception e){

            }

        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();
        }

        public void OnProgress(Java.Lang.Object snapshot)
        {

        }
</code>```

答:
You can use user's Uid to create a reference in storage for each user.

I assume your storageRef in StorageReference images = storageRef.Child("images"); means FirebaseStorage.Instance.Reference, then firstly, check the current user like this:

```<code>FirebaseAuth mAuth = FirebaseAuth.Instance;
FirebaseUser user = mAuth.CurrentUser;
</code>```

If user is null, of course we need to authenticate, but if it is not null, create an user reference first then under this reference create your "images" or "blogs" and so on... For example:

```<code>FirebaseStorage storage = FirebaseStorage.Instance;
//create child reference
StorageReference storageRef = storage.Reference;

var userRef = storageRef.Child(user.Uid);
var imageRef = userRef.Child("images");
</code>```

Body:
I am able to save images into my firebase storage but then, in the storage, there is nothing to tell me the id of the user who uploaded the photo. In my app, users can upload photos for blogs and as much as that is concerned, every photo updated should have the id of the user and also an the key of the blog respectively. So it would be easy for me to fetch the images respectively for each blog. How can i achieve this?

This is how i save my images

 public void OnClick(View v)
        {
            Intent intent = new Intent();
            intent.SetType("image/*");
            intent.SetAction(Intent.ActionPick);
            StartActivityForResult(Intent.CreateChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);

        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);

            try{
                Bitmap bitmap = MediaStore.Images.Media.GetBitmap(this.ContentResolver, data.Data);
                using (MemoryStream stream = new MemoryStream())
                {
                    bitmap.Compress(Bitmap.CompressFormat.Jpeg,100,stream);
                    byte[] array = stream.ToArray();

                    imageViewDrop.SetImageBitmap(bitmap);

                }

                if(data.Data != null){
                     pd = new ProgressDialog(this);
                   pd.SetTitle("Uploading");
                    pd.Show();

                    StorageReference images = storageRef.Child("images");

                    images.PutFile(data.Data).AddOnSuccessListener(this);
                    images.PutFile(data.Data).AddOnProgressListener(this);
                }

                else {

                }

                imageViewDrop.SetImageBitmap(bitmap);

            }
            catch (Java.Lang.Exception e){

            }

        }

        public void OnSuccess(Java.Lang.Object result)
        {
            pd.Dismiss();
        }

        public void OnProgress(Java.Lang.Object snapshot)
        {

        }

Body:
You can use user's Uid to create a reference in storage for each user.

I assume your storageRef in StorageReference images = storageRef.Child("images"); means FirebaseStorage.Instance.Reference, then firstly, check the current user like this:

FirebaseAuth mAuth = FirebaseAuth.Instance;
FirebaseUser user = mAuth.CurrentUser;

If user is null, of course we need to authenticate, but if it is not null, create an user reference first then under this reference create your "images" or "blogs" and so on... For example:

FirebaseStorage storage = FirebaseStorage.Instance;
//create child reference
StorageReference storageRef = storage.Reference;

var userRef = storageRef.Child(user.Uid);
var imageRef = userRef.Child("images");


问:
Silverlight 4 TargetNullValue to Resource
I have a databound button that has a TargetNullValue:

```<code><Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue='None'}" />
</code>```

That works fine, and when NextItem is null, the button shows "None." But I want to bind the null value to something.

To simplify things, let's assume that I have a property on my ViewModel called NullValue that returns a string that I want to be bound to when null:

```<code><Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue={Binding Path=NullValue}}" />
</code>```

But this throws:

```<code>System.Windows.Markup.XamlParseException: Provide value on 'System.Windows.Data.Binding' threw an exception. [Line: 129 Position: 92]
---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at MS.Internal.XamlManagedRuntimeRPInvokes.TryApplyMarkupExtensionValue(Object target, XamlPropertyToken propertyToken, Object value)
at MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType, XamlQualifiedObject& inObj, XamlPropertyToken inProperty, XamlQualifiedObject& inValue)
</code>```

What I really want to do is bind the null value to a resx, so I have that in the control's resource dictionary and change the binding like so:

```<code><res:AppResources x:Key="appResources" />
...
<Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue={Binding Path=NullValue,Source={StaticResource appResources}}}" />
</code>```

This also throws the same exception. Any suggestions?

答:
I created an issue for this at Connect. If anyone out there comes across this, please vote up the bug.

https://connect.microsoft.com/VisualStudio/feedback/details/632602/silverlight-4-targetnullvalue-binding-to-resource

Body:
I have a databound button that has a TargetNullValue:

<Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue='None'}" />

That works fine, and when NextItem is null, the button shows "None." But I want to bind the null value to something.

To simplify things, let's assume that I have a property on my ViewModel called NullValue that returns a string that I want to be bound to when null:

<Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue={Binding Path=NullValue}}" />

But this throws:

System.Windows.Markup.XamlParseException: Provide value on 'System.Windows.Data.Binding' threw an exception. [Line: 129 Position: 92]
---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at MS.Internal.XamlManagedRuntimeRPInvokes.TryApplyMarkupExtensionValue(Object target, XamlPropertyToken propertyToken, Object value)
at MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType, XamlQualifiedObject& inObj, XamlPropertyToken inProperty, XamlQualifiedObject& inValue)

What I really want to do is bind the null value to a resx, so I have that in the control's resource dictionary and change the binding like so:

<res:AppResources x:Key="appResources" />
...
<Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue={Binding Path=NullValue,Source={StaticResource appResources}}}" />

This also throws the same exception. Any suggestions?


问:
Error in setting up ckanext-wordpresser
I'm trying to make a wordpress interface for my ckan instance and I found the following plugin:

ckanext-wordpresser

But when I execute the following command:

```<code>$ pip install -e  git+https://github.com/okfn/ckanext-wordpresser#egg=ckanext-wordpresser
</code>```

I get this error:

Obtaining ckanext-wordpresser from

  git+https://github.com/okfn/ckanext-wordpresser#egg=ckanext-wordpresser

  Updating /usr/lib/ckan/default/src/ckanext-wordpresser clone

      Complete output from command python setup.py egg_info:

      running egg_info

      writing requirements to ckanext_wordpresser.egg-info/requires.txt

      writing ckanext_wordpresser.egg-info/PKG-INFO

      writing namespace_packages to ckanext_wordpresser.egg-info/namespace_packages.txt

      writing top-level names to ckanext_wordpresser.egg-info/top_level.txt

      writing dependency_links to ckanext_wordpresser.egg-info/dependency_links.txt

      writing entry points to ckanext_wordpresser.egg-info/entry_points.txt

      writing pbr to ckanext_wordpresser.egg-info/pbr.json

      error: Namespace package problem: ckanext.wordpresser is a namespace package, but its
      init.py does not call declare_namespace()! Please fix it.
      (See the setuptools manual under "Namespace Packages" for details.)
      "

Command "python setup.py egg_info" failed with error code 1 in
  /usr/lib/ckan/default/src/ckanext-wordpresser/

答:
The problem is this line in setup.py:

```<code>namespace_packages=['ckanext', 'ckanext.wordpresser'],
</code>```

it will work if it is changed to:

```<code>namespace_packages=['ckanext'],
</code>```

but I wouldn't do a PR myself since I'm not willing to test it still works (although I think it would). So I suggest you could git clone the repo, make that change and then:

```<code>pip install -e ../ckanext-wordpresser
</code>```

and it will install ready to try. If it works (and the extension is v. old, so I think a bit of a long-shot) then do create a PR.

Title: Error in setting up ckanext-wordpresser

Body:
I'm trying to make a wordpress interface for my ckan instance and I found the following plugin:

ckanext-wordpresser

But when I execute the following command:

$ pip install -e  git+https://github.com/okfn/ckanext-wordpresser#egg=ckanext-wordpresser

I get this error:

Obtaining ckanext-wordpresser from

  git+https://github.com/okfn/ckanext-wordpresser#egg=ckanext-wordpresser

  Updating /usr/lib/ckan/default/src/ckanext-wordpresser clone

      Complete output from command python setup.py egg_info:

      running egg_info

      writing requirements to ckanext_wordpresser.egg-info/requires.txt

      writing ckanext_wordpresser.egg-info/PKG-INFO

      writing namespace_packages to ckanext_wordpresser.egg-info/namespace_packages.txt

      writing top-level names to ckanext_wordpresser.egg-info/top_level.txt

      writing dependency_links to ckanext_wordpresser.egg-info/dependency_links.txt

      writing entry points to ckanext_wordpresser.egg-info/entry_points.txt

      writing pbr to ckanext_wordpresser.egg-info/pbr.json

      error: Namespace package problem: ckanext.wordpresser is a namespace package, but its
      init.py does not call declare_namespace()! Please fix it.
      (See the setuptools manual under "Namespace Packages" for details.)
      "

Command "python setup.py egg_info" failed with error code 1 in
  /usr/lib/ckan/default/src/ckanext-wordpresser/

Body:
The problem is this line in setup.py:

namespace_packages=['ckanext', 'ckanext.wordpresser'],

it will work if it is changed to:

namespace_packages=['ckanext'],

but I wouldn't do a PR myself since I'm not willing to test it still works (although I think it would). So I suggest you could git clone the repo, make that change and then:

pip install -e ../ckanext-wordpresser

and it will install ready to try. If it works (and the extension is v. old, so I think a bit of a long-shot) then do create a PR.


问:
Prevent Revit window from opening
I'm trying to intercept Revit and keep a window from opening.  Specifically, I'm trying to apply a keynote to an object and then let the user create a keynote tag, however any way I do it it lets them place the keynote but then immediately gives them the dialog to select a keynote, but I don't want that dialog to come up because I already know what the selection should be.  However every way I can think of isn't able to interrupt the process to apply the keynote before the user gets the dialog.  Is it possible to perhaps monitor for the window to appear then close it via Windows API?  or even better intercept when it's going to be shown and stop it from showing?</p>

答:
you can always delete warrnings with:failuresAccessor.DeleteWarning(fma);

this is what i use for my code

```<code>    public class FloorPreProcessor : IFailuresPreprocessor
{
    FailureProcessingResult
      IFailuresPreprocessor.PreprocessFailures(
        FailuresAccessor failuresAccessor)
    {

        IList<FailureMessageAccessor> fmas
          = failuresAccessor.GetFailureMessages();

        if (fmas.Count == 0)
        {
            return FailureProcessingResult.Continue;
        }

        // We already know the transaction name.

        if (fmas.Count != 0)
        {
            foreach (FailureMessageAccessor fma in fmas)
            {
                // DeleteWarning mimics clicking 'Ok' button.
                failuresAccessor.DeleteWarning(fma);
            }

            return FailureProcessingResult
              .ProceedWithCommit;
        }
        return FailureProcessingResult.Continue;
    }
}
</code>```

I hope it will help

Title: Prevent Revit window from opening

Body:
you can always delete warrnings with:failuresAccessor.DeleteWarning(fma);

this is what i use for my code

    public class FloorPreProcessor : IFailuresPreprocessor
{
    FailureProcessingResult
      IFailuresPreprocessor.PreprocessFailures(
        FailuresAccessor failuresAccessor)
    {

        IList<FailureMessageAccessor> fmas
          = failuresAccessor.GetFailureMessages();

        if (fmas.Count == 0)
        {
            return FailureProcessingResult.Continue;
        }

        // We already know the transaction name.

        if (fmas.Count != 0)
        {
            foreach (FailureMessageAccessor fma in fmas)
            {
                // DeleteWarning mimics clicking 'Ok' button.
                failuresAccessor.DeleteWarning(fma);
            }

            return FailureProcessingResult
              .ProceedWithCommit;
        }
        return FailureProcessingResult.Continue;
    }
}

I hope it will help


问:
Loading Javascript : HTTP Requests -v- Asynchronous Loading
I'm having difficulty in deciding which approach is better in terms of site performance.

Either to have all required jQuery plugins in one file to be included on every page on the site OR split the plugins out to individual files and use the jQuery.getScript() method to load them as and when required.

Is there any real benefit in loading the scripts asynchronously over one http request?

All my Javascript will be minified and gzipped.

Thanks!

答:
Try the YSlow plugin to Firefox and try your different setups.

That said, minifying your js to one file would be an easy way with great results. You will get one file, and it's often very much smaller than the sum of the parts.


问:
Multiple number from EditText with assigned number Android
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

```<code>public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}
</code>```

答:
You are implementing OnItemSelectedListener</p>

```<code>change OnItemSelectedListener to View.OnClickListener
</code>```

Body:
I'm trying to get number which user inputs and multiple it with some assigned value. I can't see where I've made mistake, my app keeps crashing. I can't even run it.

MainActivity.java

public abstract class MainActivity extends AppCompatActivity implements OnItemSelectedListener {

    Button calculateBtn;
    EditText userEcts;
    TextView summary;
    int price = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEcts = (EditText) findViewById(R.id.ects_input);
        summary = (TextView) findViewById(R.id.text_summary);

        calculateBtn = (Button) findViewById(R.id.calculate);
        calculateBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //When the button is clicked, call the calculate method.
                calculate();
            }
        });
    }

    public void calculate() {
        //gets entered text from the EditText,and convert to integers.
        Double ects = Double.parseDouble(userEcts.getText().toString());
        //do the calculation
        Double calculatedPrice = ects * price;
        //set the value to the TextView, to display on screen.
        summary.setText("Ukupno za platit: " + Double.toString(calculatedPrice) + "kn");
    }
}

Body:
You are implementing OnItemSelectedListener

change OnItemSelectedListener to View.OnClickListener


问:
How to display a dropbox from an external js file inside php?
How to display this specific dropdown(country and region) from an external js file??. In a regular HTML form with select and option tags it works perfectly but when using with php it does not.The js file is located in the some folder I am using and it works properly in a regular html file. With php it does not run. Somehow it seems that it is not possible to call the .js file inside the php with select and option </p>

```<code><!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style>
        </style>
        <body>
        <form action="" method="POST">
        Select Country (with states):
        <select id="country" name="country" required></select>
        <br>State:
        <select name="region" id="region" required></select>
        <br>
        <input type="submit" name="submit" value="Registros">

        <script src="locations.js"></script>
        <script src="locations2.js" language="javascript"></script>
        </form>

        </head>

        <?php

        if(isset($_POST['submit'])){

        echo "<tr><form action='' method='POST'>";
        echo "<td><select name='technology'><option>ERP/CRM/EPM/BI</option><option>Cyber Security</option><option>Networking</option><option>Infrastructure</option><option>Big Data/M2M/IoT/Blockchain</option><option>Physical Security</option></select></td>";
        echo "<td><select name='description'><option>VENDOR</option><option>VAD</option><option>VAR</option><option>CUSTOMER</option></td>";

        echo "<td><select id='country' name='country'><option><script src='locations.js'></script></option></select></td>";
        echo  "<td><select id='region' name='region'><option><script src='locations2.js'></script></option></select></td>";
        echo"</form></tr>";

        }

        ?>

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

答:
Instead of 2 javascript, you can use the country-region library to ease you development. Check this free library: https://github.com/geodatasource/country-region-dropdown-menu. Hosted library available and you no need to refer locally if you want.</p>

```<code><html>
  <head>
    <meta charset="UTF-8">
    <script src="//cdnjs.cloudflare.com/ajax/libs/country-region-dropdown-menu/1.1.0/geodatasource-cr.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="dist/geodatasource-countryflag.css">
  </head>
  <body>

    <div>
        Country: <select class="gds-cr" country-data-region-id="gds-cr-one" ></select>

        Region: <select id="gds-cr-one" ></select>
    </div>

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

Body:
How to display this specific dropdown(country and region) from an external js file??. In a regular HTML form with select and option tags it works perfectly but when using with php it does not.The js file is located in the some folder I am using and it works properly in a regular html file. With php it does not run. Somehow it seems that it is not possible to call the .js file inside the php with select and option

<!DOCTYPE html>

        <title></title>

        <form action="" method="POST">
        Select Country (with states):
        <select id="country" name="country" required></select>

State:
        <select name="region" id="region" required></select>

        <input type="submit" name="submit" value="Registros">

        </form>

        <?php

        if(isset($_POST['submit'])){

        echo "
<form action='' method='POST'>";
        echo "<select name='technology'><option>ERP/CRM/EPM/BI</option><option>Cyber Security</option><option>Networking</option><option>Infrastructure</option><option>Big Data/M2M/IoT/Blockchain</option><option>Physical Security</option></select>	";
        echo "<select name='description'><option>VENDOR</option><option>VAD</option><option>VAR</option><option>CUSTOMER</option>	";

        echo "<select id='country' name='country'><option></option></select>	";
        echo  "<select id='region' name='region'><option></option></select>	";
        echo"</form>
";

        }

        ?>

Body:
Instead of 2 javascript, you can use the country-region library to ease you development. Check this free library: https://github.com/geodatasource/country-region-dropdown-menu. Hosted library available and you no need to refer locally if you want.

<html>
  <head>
    <meta charset="UTF-8">
    <script src="//cdnjs.cloudflare.com/ajax/libs/country-region-dropdown-menu/1.1.0/geodatasource-cr.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="dist/geodatasource-countryflag.css">
  </head>
  <body>

    <div>
        Country: <select class="gds-cr" country-data-region-id="gds-cr-one" ></select>

        Region: <select id="gds-cr-one" ></select>
    </div>

  </body>
</html>


问:
Using PHP to split a URL
I am creating a PHP proxy where it accepts a url and confirms it is on my list of servers.

When importing the url from the application i ran it to an issue where i needed 2 parser tags. i need it to split along a "\?" tag as well as a string, in my case, "export?"

i am using preg for the first tag. Does this accept the strings like my export tag or is there some other method for doing this?

please le me know how this is accomplished or if you have more questions.

答: Hey guys i ended up using an explode which looked for the string (export?) and then i used the preg split command to search for the \?. this provided me with the protion i was looking for. thanks guys.</p>

Title: Using PHP to split a URL


问:
MVC 5, globalize, validate german date: How to bundle the js-scripts?
In the answer to this question (MVC 5 - can not get globalisation running) I solve the problem with a bunch of "<sript src="..." declarations and some js.

What I not managed: I want to bundle the scripts. If I try it like this (excerpt from bundleConfig.cs):

```<code> bundles.Add(new ScriptBundle("~/bundles/jqueryvalDe").Include(
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js",
                    "~/Scripts/cldr.js",
                        "~/Scripts/cldr/event.js",
                        "~/Scripts/cldr/supplemental.js",
                        "~/Scripts/cldr/unresolved.js",
                        "~/Scripts/globalize.js",
                        "~/Scripts/globalize/currency.js",
                        "~/Scripts/globalize/number.js",
                        "~/Scripts/globalize/date.js",
                        "~/Scripts/globalize/plural.js",
                        "~/Scripts/globalize/relative-time.js",
                        "~/Scripts/globalize/unit.js",
                        "~/Scripts/jquery.validate.globalize.js"
                    ));
</code>```

But I get an error from JavaScript: "Globalize" is undefined

It seems, the order of scrpts is changed...

At the moment I use a Workaround: I wrote an custom HTM-Helper.

```<code> public static class GermanDateValidationExtension
{
    public static MvcHtmlString ScriptsForGermanDateValidation(this HtmlHelper helper)
    {
        return new MvcHtmlString("<script src=\"~/ Scripts / jquery.validate.js\"></script>\n" +
                                 "<script src = \"~/Scripts/jquery.validate.unobtrusive.js\"></script>\n" +
                                 "<script src = \"~/Scripts/cldr.js\"></script>\n" +
                                 "<script src = \"~/Scripts/cldr/event.js\"></ script>\n" +
                                 "<script src = \"~/Scripts/cldr/supplemental.js\"></script>\n" +
                                 "<script src = \"~/Scripts/cldr/unresolved.js\"></script>\n" +
                                 "<script src = \"~/Scripts/globalize.js\"></script>\n" +
                                 "<script src = \"~/Scripts/globalize/currency.js\" ></script>\n" +
                                 "<script src = \"~/Scripts/globalize/number.js\"></script>\n" +
                                 "<script src = \"~/Scripts/globalize/date.js\"></script>\n" +
                                 "<script src = \"~/Scripts/globalize/plural.js\" ></script>\n" +
                                 "<script src = \"~/Scripts/globalize/relative-time.js\"></script>\n" +
                                 "<script src = \"~/Scripts/globalize/unit.js\"></script>\n" +
                                 "<script src = \"~/Scripts/jquery.validate.globalize.js\"></script>\n" +
                                 "<script>\n" +
                                 "$.when(\n" +
                                 "$.get(\"/Scripts/cldr/main/de/ca-gregorian.json\"),\n" +
                                 "$.get(\"/Scripts/cldr/main/de/numbers.json\"),\n" +
                                 "$.get(\"/Scripts/cldr/supplemental/likelySubtags.json\"),\n" +
                                 "$.get(\"/Scripts/cldr/supplemental/timeData.json\"),\n" +
                                 "$.get(\"/Scripts/cldr/supplemental/weekData.json\")\n" +
                                 ").then(function() {\n" +
                                 "return [].slice.apply(arguments, [0]).map(function(result) {\n" +
                                 "return result[0];\n" +
                                 "});\n" +
                                 "}).then(Globalize.load)\n" +
                                 ".then(function() {\n" +
                                 "Globalize.locale(\"de-DE\");\n" +
                                 "});\n" +
                                 "</ script > ");
    }

}
</code>```

And use it in the view:

```<code>...
@section Scripts {
@Html.ScriptsForGermanDateValidation()
}
...
</code>```

My question is: How to bundle the scripts correctly?

答:
The solution is - how Tetsuya Yamamoto says: Write your own orderer.

```<code>public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
    {
        return files;
    }
</code>```

and use it:

```<code> var qvDeBundle  =new ScriptBundle("~/bundles/jqueryvalDe").Include(
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js",
                    "~/Scripts/cldr.js",
                        "~/Scripts/cldr/event.js",
                        "~/Scripts/cldr/supplemental.js",
                        "~/Scripts/cldr/unresolved.js",
                        "~/Scripts/globalize.js",
                        "~/Scripts/globalize/currency.js",
                        "~/Scripts/globalize/number.js",
                        "~/Scripts/globalize/date.js",
                        "~/Scripts/globalize/plural.js",
                        "~/Scripts/globalize/relative-time.js",
                        "~/Scripts/globalize/unit.js",
                        "~/Scripts/jquery.validate.globalize.js"
                    );
        qvDeBundle.Orderer=new UnorderBundleOrderer();
        bundles.Add(qvDeBundle);
</code>```

Body:
In the answer to this question (MVC 5 - can not get globalisation running) I solve the problem with a bunch of "<sript src="..." declarations and some js.

What I not managed: I want to bundle the scripts. If I try it like this (excerpt from bundleConfig.cs):

 bundles.Add(new ScriptBundle("~/bundles/jqueryvalDe").Include(
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js",
                    "~/Scripts/cldr.js",
                        "~/Scripts/cldr/event.js",
                        "~/Scripts/cldr/supplemental.js",
                        "~/Scripts/cldr/unresolved.js",
                        "~/Scripts/globalize.js",
                        "~/Scripts/globalize/currency.js",
                        "~/Scripts/globalize/number.js",
                        "~/Scripts/globalize/date.js",
                        "~/Scripts/globalize/plural.js",
                        "~/Scripts/globalize/relative-time.js",
                        "~/Scripts/globalize/unit.js",
                        "~/Scripts/jquery.validate.globalize.js"
                    ));

But I get an error from JavaScript: "Globalize" is undefined

It seems, the order of scrpts is changed...

At the moment I use a Workaround: I wrote an custom HTM-Helper.

 public static class GermanDateValidationExtension
{
    public static MvcHtmlString ScriptsForGermanDateValidation(this HtmlHelper helper)
    {
        return new MvcHtmlString("\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "\n" +
                                 "

Body:
The solution is - how Tetsuya Yamamoto says: Write your own orderer.

public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
    {
        return files;
    }

and use it:

 var qvDeBundle  =new ScriptBundle("~/bundles/jqueryvalDe").Include(
                    "~/Scripts/jquery.validate.js",
                    "~/Scripts/jquery.validate.unobtrusive.js",
                    "~/Scripts/cldr.js",
                        "~/Scripts/cldr/event.js",
                        "~/Scripts/cldr/supplemental.js",
                        "~/Scripts/cldr/unresolved.js",
                        "~/Scripts/globalize.js",
                        "~/Scripts/globalize/currency.js",
                        "~/Scripts/globalize/number.js",
                        "~/Scripts/globalize/date.js",
                        "~/Scripts/globalize/plural.js",
                        "~/Scripts/globalize/relative-time.js",
                        "~/Scripts/globalize/unit.js",
                        "~/Scripts/jquery.validate.globalize.js"
                    );
        qvDeBundle.Orderer=new UnorderBundleOrderer();
        bundles.Add(qvDeBundle);


问:
How can I test the validations of a model if I use backbone validation
I have a backbone model

```<code>var MyModel= Backbone.Model.extend({
   validation: function ()
      var validate= {
           name: {
               required: true,
           },
      };

      return validate;

   },
});
</code>```

I use sinon, mocha and chai for test. When I call model.validate() in the test it tells me that the function does not exist, how can I check that the validation works?

答:
It seems you should do the following for validation plugin to work:</p>

```<code>_.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
</code>```

Body:
I have a backbone model

var MyModel= Backbone.Model.extend({
   validation: function ()
      var validate= {
           name: {
               required: true,
           },
      };

      return validate;

   },
});

I use sinon, mocha and chai for test. When I call model.validate() in the test it tells me that the function does not exist, how can I check that the validation works?

Body:
It seems you should do the following for validation plugin to work:

_.extend(Backbone.Model.prototype, Backbone.Validation.mixin);


问:
404 NOT FOUND AJAX REQUEST GT
i have some problem with this request :

When i make a request with value of 2017

http://01tm.com/wp-content/themes/voetvolk_2017/core/process/aru.php?request=&target=arrange_url&method=method_target&year=2017&month=06&project=all&country=all&tour=all

No problem,

But when i make a request with value 2018 i got en error 404 on GET. But in the developer tools in tab Sources i have an output correct.

http://01tm.com/wp-content/themes/voetvolk_2017/core/process/aru.php?request=&target=arrange_url&method=method_target&year=2018&month=06&project=all&country=all&tour=all

Thx for reply

答:
I fix it with :

include_once('../../../../../wp-blog-header.php');

header("HTTP/1.1 200 OK");

Title: 404 NOT FOUND AJAX REQUEST GT


问:
HA proxy grouping requests
I am using HA proxy as the load balancer.
I have specified two nodes for load balancing in round robin fashion. The things are  working fine if i post request manually i can see that the req is getting routed to each node in a round robin fashion. When i use curl to fire some 5000 req then i see the that around 100 req are going to one node and then 100 to another another node. so it is not alternating based on req. I dont think this is the correct beahviour. Is there some config which i need to change ?
or is it curl behaviour?</p>

```<code>curl -k  <url>?name=[1-5000]
</code>```

答:
You're directing curl to make sequential requests with an incrementing counter, with those numbers in brackets in the URL, and curl is going to reuse the connection to HAProxy, via http keep-alive.

HAProxy is also going to reuse the connection to the backend by default, because that's the most efficient behavior, avoiding the overhead of estsblishing a new TCP connection.  There's no reason to artificially force a round robin distribution when all the requests are coming from a single client on a reused connection, with a concurrency of 1.

You can force a change to this behavior with one of several options, but it should be unnecessary since this is primarily an artifact of your test methodology.

By default HAProxy operates in keep-alive mode with regards to persistent
  connections: for each connection it processes each request and response, and
  leaves the connection idle on both sides between the end of a response and
  the start of a new request. This mode may be changed by several options such
  as "option http-server-close", "option forceclose", "option httpclose" or
  "option http-tunnel". Setting "option http-server-close" enables HTTP
  connection-close mode on the server side while keeping the ability to support
  HTTP keep-alive and pipelining on the client side.  This provides the lowest
  latency on the client side (slow network) and the fastest session reuse on
  the server side to save server resources, similarly to "option forceclose".
  It also permits non-keepalive capable servers to be served in keep-alive mode
  to the clients if they conform to the requirements of RFC7230. Please note
  that some servers do not always conform to those requirements when they see
  "Connection: close" in the request. The effect will be that keep-alive will
  never be used. A workaround consists in enabling "option
  http-pretend-keepalive".

http://cbonte.github.io/haproxy-dconv/1.6/configuration.html#4-option%20http-server-close

So why does it alternate every ~100?  Keep-alive connections can't usually be used indefinitely, so either the client or the server will eventially close the connection and a new one will be established.

Title: HA proxy grouping requests

Body:
I am using HA proxy as the load balancer.
I have specified two nodes for load balancing in round robin fashion. The things are  working fine if i post request manually i can see that the req is getting routed to each node in a round robin fashion. When i use curl to fire some 5000 req then i see the that around 100 req are going to one node and then 100 to another another node. so it is not alternating based on req. I dont think this is the correct beahviour. Is there some config which i need to change ?
or is it curl behaviour?

curl -k  <url>?name=[1-5000]


问:
How to get all projections by a type with Spring Data REST
Is there a way to get all projections by an appropriate type?

I've got a class with several projections. I would like to get a Map<String, Class<?>> where

a String is a name of the projection

a Class<?> is a class over which this annotation is

An example:

```<code>class A { ... }

@Projection(name = "a1", types = A.class)
interface ProjectionA1 { ... }

@Projection(name = "a2", types = A.class)
interface ProjectionA2 { ... }
</code>```

A result might be:

```<code>-> A.class
<- ImmutableMap.of("a1", ProjectionA1.class, "a2", ProjectionA2.class);
</code>```

Thank you.

答:
Have a look at: RepositoryRestConfiguration

There you can get the ProjectionDefinitionConfiguration and your desired results via ProjectionDefinitionConfiguration::getProjectionsFor.

Body:
Is there a way to get all projections by an appropriate type?

I've got a class with several projections. I would like to get a Map<String, Class<?>> where

a String is a name of the projection

a Class<?> is a class over which this annotation is

An example:

class A { ... }

@Projection(name = "a1", types = A.class)
interface ProjectionA1 { ... }

@Projection(name = "a2", types = A.class)
interface ProjectionA2 { ... }

A result might be:

-> A.class
<- ImmutableMap.of("a1", ProjectionA1.class, "a2", ProjectionA2.class);

Thank you.


答:
The problem seems originated from bundling order which rendered jquery.validate.globalize.js before globalize.js, which uses "dependency tree" established in favor of well-known libraries & their custom extensions will rendered before others. Hence, in order to set load order as you want, create a class which implements IBundleOrder interface & its corresponding extension method:

```<code>// from Sebastián Rojas (/a/26602075)
class UnorderedBundleOrderer : IBundleOrderer
{
    public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
    {
        return files;
    }
}

static class BundleExtensions
{
    public static Bundle UnorderedBundling(this Bundle bundle)
    {
        bundle.Orderer = new UnorderedBundleOrderer();
        return bundle;
    }
}
</code>```

Then you can use custom bundling order above in BundleConfig.cs file:

```<code>public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jqueryvalDe")
           .UnorderedBundling()
           .Include(
            "~/Scripts/jquery.validate.js",
            "~/Scripts/jquery.validate.unobtrusive.js",
            ...
            ...
            "~/Scripts/globalize.js",
            ...
            ...
            "~/Scripts/jquery.validate.globalize.js"
    ));
}
</code>```

Related issue:

ASP.NET MVC - Bundle Config order

Ordering of Files within a bundle - What are the known libraries?

Title: MVC 5, globalize, validate german date: How to bundle the js-scripts?

Body:
The problem seems originated from bundling order which rendered jquery.validate.globalize.js before globalize.js, which uses "dependency tree" established in favor of well-known libraries & their custom extensions will rendered before others. Hence, in order to set load order as you want, create a class which implements IBundleOrder interface & its corresponding extension method:

// from Sebastián Rojas (/a/26602075)
class UnorderedBundleOrderer : IBundleOrderer
{
    public IEnumerable<BundleFile> OrderFiles(BundleContext context, IEnumerable<BundleFile> files)
    {
        return files;
    }
}

static class BundleExtensions
{
    public static Bundle UnorderedBundling(this Bundle bundle)
    {
        bundle.Orderer = new UnorderedBundleOrderer();
        return bundle;
    }
}

Then you can use custom bundling order above in BundleConfig.cs file:

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jqueryvalDe")
           .UnorderedBundling()
           .Include(
            "~/Scripts/jquery.validate.js",
            "~/Scripts/jquery.validate.unobtrusive.js",
            ...
            ...
            "~/Scripts/globalize.js",
            ...
            ...
            "~/Scripts/jquery.validate.globalize.js"
    ));
}

Related issue:

ASP.NET MVC - Bundle Config order

Ordering of Files within a bundle - What are the known libraries?


问:
Software License Web Application
We are in the process of building a web application for a client and they have inquired about owning the code for the site. We would like to issue a license agreement to the client for use of the code if we for any reason we are no longer working on the project.  We would like to have ownership of the code but allow them use wherever they see fit, the only limitation we would like to have is the sale of the code.  The are a company with several employees and will only be using the application within their company.

Thanks in advance

-JN

答: Sounds to me like you need an attorney.  Try this: http://www.google.com/search?btnG=1&pws=0&q=software+licensing+attorney</p>

Title: Software License Web Application


问:
Where to place a downcast (prior to calling a method in the super class)?
I'm working on an assignment that uses the UnfoldingMaps library (http://unfoldingmaps.org/javadoc/index.html?overview-summary.html).

The assignment has a class called CommonMarker. This class inherits from the class SimplePointMarker which inherits from the class AbstractMarker. AbstractMarker implements the interface Marker.

I'm confused with casting that occurs in method selectMarkerIfHover that calls the isInside method.

Following is the skeleton code we have to complete. The objective is to set the instance variable lastSelected for the first Marker it finds that mouseX and mouseY is inside of. We are to use the isInside( UnfoldingMap m, float x, float y ) method defined in the AbstractMarker abstract class to check if a location is inside a marker.

lastSelected is defined as:

```<code>private CommonMarker lastSelected;
</code>```

The skeleton code given is:

```<code>private void selectMarkerIfHover(List<Marker> markers)
    {
        // TODO: Implement this method
    }
</code>```

My solution is as below where I do downcasting just prior to assigning m to lastSelected.

```<code>for(Marker m:markers)
        {
            if(m.isInside(map, mouseX, mouseY))
            {
                m.setSelected(true);
                lastSelected = (CommonMarker)m;
                return;
            }
        }
</code>```

The solution given by the instructor is slightly different from mine where downcasting is done even before inInside is called.

```<code>for (Marker m : markers)
        {
            CommonMarker marker = (CommonMarker)m;
            if (marker.isInside(map,  mouseX, mouseY))
            {
                marker.setSelected(true);
                lastSelected = marker;
                return;
            }
        }
</code>```

I'm not sure why the markers are 'downcasted' prior to calling the method isInside. Is this the best practice approach? Kindly share your thoughts, I'm pretty new to Java and I've tried to trace the code as much as I can but it's still quite overwhelming to me.

答:
There is exactly one difference: your version will throw a ClassCastException when exactly that m which gives true for  m.isInside(map, mouseX, mouseY) is also not an instance of CommonMarker.

Whereas the second solution will throw that exception in case any of the markers in that List isn't a CommonMarker (to be precise: any object prior to some m that gives true for the if condition).

In that sense, there is a subtle difference in behavior. If that matters in your environment depends on your context. My gut feeling is: if that difference matters in your environment - then I would see this as a design smell and I would further investigate that context.

Beyond that: I think both options are "ok". But ideally you would make things even more explicit, like:

```<code>if (m instanceOf CommonMarker) {
  ... cast
} else {
  ... throw exception with meaningful error message
</code>```

And of course: the second version has a minimal performance hit, as the cast is performed for each loop iteration; instead of just once. But instanceof/cast are both insignificant regarding performance.

Having said that: many people consider downcasts themselves to be a design smell. So, again - I would step back and figure if there are other options to avoid the downcast completely.

Body:
I'm working on an assignment that uses the UnfoldingMaps library (http://unfoldingmaps.org/javadoc/index.html?overview-summary.html).

The assignment has a class called CommonMarker. This class inherits from the class SimplePointMarker which inherits from the class AbstractMarker. AbstractMarker implements the interface Marker.

I'm confused with casting that occurs in method selectMarkerIfHover that calls the isInside method.

Following is the skeleton code we have to complete. The objective is to set the instance variable lastSelected for the first Marker it finds that mouseX and mouseY is inside of. We are to use the isInside( UnfoldingMap m, float x, float y ) method defined in the AbstractMarker abstract class to check if a location is inside a marker.

lastSelected is defined as:

private CommonMarker lastSelected;

The skeleton code given is:

private void selectMarkerIfHover(List<Marker> markers)
    {
        // TODO: Implement this method
    }

My solution is as below where I do downcasting just prior to assigning m to lastSelected.

for(Marker m:markers)
        {
            if(m.isInside(map, mouseX, mouseY))
            {
                m.setSelected(true);
                lastSelected = (CommonMarker)m;
                return;
            }
        }

The solution given by the instructor is slightly different from mine where downcasting is done even before inInside is called.

for (Marker m : markers)
        {
            CommonMarker marker = (CommonMarker)m;
            if (marker.isInside(map,  mouseX, mouseY))
            {
                marker.setSelected(true);
                lastSelected = marker;
                return;
            }
        }

I'm not sure why the markers are 'downcasted' prior to calling the method isInside. Is this the best practice approach? Kindly share your thoughts, I'm pretty new to Java and I've tried to trace the code as much as I can but it's still quite overwhelming to me.

Body:
There is exactly one difference: your version will throw a ClassCastException when exactly that m which gives true for  m.isInside(map, mouseX, mouseY) is also not an instance of CommonMarker.

Whereas the second solution will throw that exception in case any of the markers in that List isn't a CommonMarker (to be precise: any object prior to some m that gives true for the if condition).

In that sense, there is a subtle difference in behavior. If that matters in your environment depends on your context. My gut feeling is: if that difference matters in your environment - then I would see this as a design smell and I would further investigate that context.

Beyond that: I think both options are "ok". But ideally you would make things even more explicit, like:

if (m instanceOf CommonMarker) {
  ... cast
} else {
  ... throw exception with meaningful error message

And of course: the second version has a minimal performance hit, as the cast is performed for each loop iteration; instead of just once. But instanceof/cast are both insignificant regarding performance.

Having said that: many people consider downcasts themselves to be a design smell. So, again - I would step back and figure if there are other options to avoid the downcast completely.


问:
Three-dimensional array in PHP
How can I iterate over this array? Syntax of loop</p>

```<code>$t = array(
  'grn_id' => array(
    'status_id' => array(1, 2, 3, 4)
  )
)
</code>```

答:
In simple words, if you want that, you can get:

```<code>foreach ($t["grn_id"]["status_id"] as $statusId)
  echo $statusId;
</code>```

You will get 1, 2, 3, 4 in each iteration.

```<code>foreach ($t["grn_id"] as $grn) {
  foreach ($grn as $statusId) {
    echo $statusId;
  }
}
</code>```

Title: Three-dimensional array in PHP

Body:
How can I iterate over this array? Syntax of loop

$t = array(
  'grn_id' => array(
    'status_id' => array(1, 2, 3, 4)
  )
)

Body:
In simple words, if you want that, you can get:

foreach ($t["grn_id"]["status_id"] as $statusId)
  echo $statusId;

You will get 1, 2, 3, 4 in each iteration.

foreach ($t["grn_id"] as $grn) {
  foreach ($grn as $statusId) {
    echo $statusId;
  }
}


问:
detecting the change of content of UITextField when the change is not made by the keyboard
I have a UIButton and a UITextField,when the button is pressed the textfield's content string will be equal to: This is a test string, how can I detect that this text field has changed its contents in this case?

p.s. UITextField's delegate methods do not work in such case

UPDATE: I want this behavior to be on iOS 6+ devices.

答:
Here is a Swift3 version of akashivskyy's answer:</p>

```<code>func startObservingTextView() {
    textView.addObserver(self, forKeyPath:"text", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}

func stopObservingTextView() {
    textView.removeObserver(self, forKeyPath: "text")
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let textViewObject = object as? UITextView, textViewObject == textView, keyPath == "text" {
        // text has changed
    }
}
</code>```

Body:
Here is a Swift3 version of akashivskyy's answer:

func startObservingTextView() {
    textView.addObserver(self, forKeyPath:"text", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}

func stopObservingTextView() {
    textView.removeObserver(self, forKeyPath: "text")
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let textViewObject = object as? UITextView, textViewObject == textView, keyPath == "text" {
        // text has changed
    }
}


问:
Getting IP Cam video stream on Android (MJEPG)
I am currently doing an AndAR project in group of 3. I'm the person who's in charge of video streaming into the Android phone.
I got ourselves a D-Link DCS-920 IP camera and I found out that it uses MJPEG codec for the live video stream and the webserver uses Jview to view the live stream. As far as I know MJPG is not a supported file type for Android OS so I've came out with an idea, instead of using ImageView, I use WebView to stream the video.
I've implemented a very simple concept and it works! But the problem is, refresh rate is terrible.
I get the video image (eg: http://192.168.1.10/image.jpg) to view on the WebView and implement a Timer to control the refresh rate (supposed to set it to 30fps, which is refresh every 33ms) but it can only go up to 500ms interval, any lower interval I notice it will not be any smoother,sometimes the image wont load and connection is unstable (eg: dropped). Could this be I'm refreshing at a rate faster than it can receive?
But over on the webserver Jview it has no problem! was trying to find the source code for the jview but I have no hope.
Anyway here's the code I've written

```<code>package org.example.test;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class Webview extends Activity {

public WebView webView;
public Timer autoUpdate;
public String url;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings();
        final EditText urlText = (EditText) findViewById(R.id.urlText);

        //Buttons//////////////////------------
        final Button connectB = (Button)findViewById(R.id.connectButton);
        connectB.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            //Actions goes here
          url = urlText.getText().toString();
          webView.loadUrl(url);
          timerSetup();
         }
        });
        final Button exitB = (Button)findViewById(R.id.exitButton);
     exitB.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
       //Actions goes here
       finish();
      }
     });
   }

    //refresh timer//////////////-----------------
    public void timerSetup(){
     autoUpdate = new Timer();
     autoUpdate.schedule(new TimerTask() {
      @Override
      public void run() {
       runOnUiThread(new Runnable() {
        @Override
     public void run() {
         //Actions goes here
         webView.loadUrl(url);
        }
       });
      }
     }, 0, 500);//refresh rate time interval (ms)
    }
}
</code>```

Is there anyway I can get the video stream in by at least 15fps/have a faster refresh rate?
Are there any such thing as MJPEG viewer/source code that I can use to display these images?

here's the screenshot of the app
http://s945.photobucket.com/albums/ad295/kevinybh/?action=view&current=video.jpg
(not enough points to post pictures) :(

I just need to make the video stream around 15-30fps. any suggestions/help would be very deeply appreciated :) Thanks!

答:
MJPEG is a terribly inefficient way to deliver motion video to a mobile device, because each frame is compressed as it's own independent picture.  For an application which doesn't need video (someone was asking about a camera watching waiting lines last week) your solution of pushing a static frame every second or so sounds good.

If you need motion video, I would recommend you do transcoding on your webserver from MJPEG to a supported video format which utilizes frame-to-frame compression.  This will result in far less data to push, both over the user's 3g connection and from your server to all of its clients.  You should only need to run one transcoding engine to support all clients - and you'll be able to use the same one for android & iphone devices, though you may want to also have a higher resolution output for tablets and pc's if your camera output is good enough to justify it.

Body:
I am currently doing an AndAR project in group of 3. I'm the person who's in charge of video streaming into the Android phone.
I got ourselves a D-Link DCS-920 IP camera and I found out that it uses MJPEG codec for the live video stream and the webserver uses Jview to view the live stream. As far as I know MJPG is not a supported file type for Android OS so I've came out with an idea, instead of using ImageView, I use WebView to stream the video.
I've implemented a very simple concept and it works! But the problem is, refresh rate is terrible.
I get the video image (eg: http://192.168.1.10/image.jpg) to view on the WebView and implement a Timer to control the refresh rate (supposed to set it to 30fps, which is refresh every 33ms) but it can only go up to 500ms interval, any lower interval I notice it will not be any smoother,sometimes the image wont load and connection is unstable (eg: dropped). Could this be I'm refreshing at a rate faster than it can receive?
But over on the webserver Jview it has no problem! was trying to find the source code for the jview but I have no hope.
Anyway here's the code I've written

package org.example.test;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;

public class Webview extends Activity {

public WebView webView;
public Timer autoUpdate;
public String url;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings();
        final EditText urlText = (EditText) findViewById(R.id.urlText);

        //Buttons//////////////////------------
        final Button connectB = (Button)findViewById(R.id.connectButton);
        connectB.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            //Actions goes here
          url = urlText.getText().toString();
          webView.loadUrl(url);
          timerSetup();
         }
        });
        final Button exitB = (Button)findViewById(R.id.exitButton);
     exitB.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
       //Actions goes here
       finish();
      }
     });
   }

    //refresh timer//////////////-----------------
    public void timerSetup(){
     autoUpdate = new Timer();
     autoUpdate.schedule(new TimerTask() {
      @Override
      public void run() {
       runOnUiThread(new Runnable() {
        @Override
     public void run() {
         //Actions goes here
         webView.loadUrl(url);
        }
       });
      }
     }, 0, 500);//refresh rate time interval (ms)
    }
}

Is there anyway I can get the video stream in by at least 15fps/have a faster refresh rate?
Are there any such thing as MJPEG viewer/source code that I can use to display these images?

here's the screenshot of the app
http://s945.photobucket.com/albums/ad295/kevinybh/?action=view&current=video.jpg
(not enough points to post pictures) :(

I just need to make the video stream around 15-30fps. any suggestions/help would be very deeply appreciated :) Thanks!