问:
Remove font-size from string
I am trying to figure out how to .replace() the font-size from a string while I am re-writing a stylesheet.  I'm not so great with regex, I tried this:

```<code>string.replace(/font-size:.*S.;/, '');
</code>```

it didn't work, I've been messing around with it for a bit, any help appreciated..

答:
You can try:

```<code>font-size\s?:\s?\d+(px|em);
</code>```

Please check the link
https://regexr.com/3h6cq

It supports px/em, if you need any other units just add them with the pipe symbol.

Update:
You can also go with a more general approach which will accept anything after the : up until the semi-colon ;

```<code>font-size\s?:([^;]+)
</code>```

https://regexr.com/3h6ct

Update 2 if you want to support decimals (and only px units) you could do:

```<code>font-size\s?:\s?\d+\.?\d+(px);
</code>```

https://regexr.com/3h6d3

Hope this helps.

Title: Remove font-size from string

Body:
I am trying to figure out how to .replace() the font-size from a string while I am re-writing a stylesheet.  I'm not so great with regex, I tried this:

string.replace(/font-size:.*S.;/, '');

it didn't work, I've been messing around with it for a bit, any help appreciated..

Body:
You can try:

font-size\s?:\s?\d+(px|em);

Please check the link
https://regexr.com/3h6cq

It supports px/em, if you need any other units just add them with the pipe symbol.

Update:
You can also go with a more general approach which will accept anything after the : up until the semi-colon ;

font-size\s?:([^;]+)

https://regexr.com/3h6ct

Update 2 if you want to support decimals (and only px units) you could do:

font-size\s?:\s?\d+\.?\d+(px);

https://regexr.com/3h6d3

Hope this helps.


来源: stackexchange

问:
Display a custom field image on Visual Composer Custom Grid Template
I'm working on a WP site with Visual Composer.

In the homepage I've inserted a "Post Grid" element which load a specific custom post type.

This custom post has multiple custom fields (made with Advanced Custom Fields Plugin): one of these fields is an image.

This Post Grid uses a custom grid to display these custom fields.

When I preview the page, it displays correctly the post thumb (the post featured image), some text custom fields, but the secondary image (created with a custom field) displays only text (in the specific the Array Object or ID of the image).

How can I render the image? Is it possible to insert some code for that custom field (ex. the omg html tag) to avoid the text render?

Thanks in advance,
Francesco

答:
Open the file js_composer\include\classes\vendors\plugins\acf\class-vc-gitem-acf-shortcode.php

And put this code: before the return, and you can comment the original return:

```<code>     $f = get_field_object($field_key);

     if ( $f['type'] == 'image') {
         return '<div ' . $field_key . ' class="' . esc_attr( $css_class ) . '">'
                 . '<img src=" {{ acf' . ( ! empty( $field_key ) ? ':' . $field_key : '' ) . ' }} ">'
              . '</div>';
     } else {
         return '<div ' . $field_key . ' class="' . esc_attr( $css_class ) . '">'
                 . '{{ acf' . ( ! empty( $field_key ) ? ':' . $field_key : '' ) . ' }}'
              . '</div>';
     }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Open the file js_composer\include\classes\vendors\plugins\acf\class-vc-gitem-acf-shortcode.php

And put this code: before the return, and you can comment the original return:

     $f = get_field_object($field_key);

     if ( $f['type'] == 'image') {
         return '<div ' . $field_key . ' class="' . esc_attr( $css_class ) . '">'
                 . '<img src=" {{ acf' . ( ! empty( $field_key ) ? ':' . $field_key : '' ) . ' }} ">'
              . '</div>';
     } else {
         return '<div ' . $field_key . ' class="' . esc_attr( $css_class ) . '">'
                 . '{{ acf' . ( ! empty( $field_key ) ? ':' . $field_key : '' ) . ' }}'
              . '</div>';
     }


问:
How to rescue data after malformed chunk in a byte stream which is written with writeDelimitedTo()
I use protobuf-java-util:3.0.0-beta-2.

I create a file which contains a lot of Protobuf messages which are written with Message#writeDelimitedTo(). The code is something like this:

```<code>Iterable<SomeMessage> messages = getHugeDataSet();
OutputStream os = new FileOutputStream("a_lot_of_messages.protobuf");
for (SomeMessage msg : messages) msg.writeDelimitedTo(os);
</code>```

And I read those files with Builder#mergeDelimitedFrom(). Something like this:

```<code>InputStream is = new FileInputStream("a_lot_of_messages.protobuf");
SomeMessage msg1 = SomeMessage.newBuilder().mergeDelimitedFrom(is).build();
SomeMessage msg2 = SomeMessage.newBuilder().mergeDelimitedFrom(is).build();
... // This is simplified - it's implemented as an Iterator in the real code
</code>```

With that way, I can read the vast majority of files without any problems but I sometimes get exceptions like this:

```<code>com.google.protobuf.InvalidProtocolBufferException: Protocol message had invalid UTF-8. ...
</code>```

The code which writes those files run on mobile devices which get power failure sometimes. In such cases, my app keeps writing to the same file and  chances of getting that exceptions are high. So, apparently my code creates some malformed files on such occasions. My code can read some parts of the file, but it can't read the parts after the malformed chunk due to the error.

Now I need to rescue and read the data after the malformed chunk, but I couldn't find any way to do that. So, I'd like to know the following:

Is there any way to rescue and read the parts which are written by the code above after the malformed chunk?

If there is no way to do that, how can I improve my code so my app can cope with such problems? Is there any best practice which is power failure tolerant?

Full exception stacktrace is something like this:

```<code>com.google.protobuf.InvalidProtocolBufferException: Protocol message had invalid UTF-8.
    at com.google.protobuf.InvalidProtocolBufferException.invalidUtf8(InvalidProtocolBufferException.java:120) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.CodedInputStream.readStringRequireUtf8(CodedInputStream.java:410) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.example.Model$SomeData.<init>(Model.java:14775) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeData.<init>(Model.java:14717) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeData$1.parsePartialFrom(Model.java:18240) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeData$1.parsePartialFrom(Model.java:18234) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.google.protobuf.CodedInputStream.readMessage(CodedInputStream.java:495) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.example.Model$SomeMessage.<init>(Model.java:27250) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage.<init>(Model.java:27197) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$1.parsePartialFrom(Model.java:28678) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$1.parsePartialFrom(Model.java:28672) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$Builder.mergeFrom(Model.java:27802) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$Builder.mergeFrom(Model.java:27653) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.google.protobuf.AbstractMessageLite$Builder.mergeFrom(AbstractMessageLite.java:235) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeFrom(AbstractMessage.java:516) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeFrom(AbstractMessage.java:290) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessageLite$Builder.mergeDelimitedFrom(AbstractMessageLite.java:305) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeDelimitedFrom(AbstractMessage.java:530) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessageLite$Builder.mergeDelimitedFrom(AbstractMessageLite.java:311) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeDelimitedFrom(AbstractMessage.java:522) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.example.MyUtils.read(MyUtils.java:54) [my-app-1.0-SNAPSHOT.jar:na]
</code>```

答:
It is quite problematic to recover message boundaries from raw protobuf data. This in general applies to data formats, the smaller and more compressed it is, the less resilient it is to transmission errors.

The best way would be if there is some byte sequence that always occurs in the beginning of a message. For example, if you happen to have any nearly-constant fields like required string software_version = 1;, you could search for that in the binary data and so find the starting point of the next message.

If that is not the case, you can introduce such a marker when writing your message. For example, pick some 64 bit random number as your marker. Either you can write it separately to the file outside protobuf, or you can have a fixed64 field with index 1 in your message to get it near the beginning.

Even though the marker might occur elsewhere in your data randomly, that shouldn't cause too large problems as you can just skip messages that do not parse.

Body:
I use protobuf-java-util:3.0.0-beta-2.

I create a file which contains a lot of Protobuf messages which are written with Message#writeDelimitedTo(). The code is something like this:

Iterable<SomeMessage> messages = getHugeDataSet();
OutputStream os = new FileOutputStream("a_lot_of_messages.protobuf");
for (SomeMessage msg : messages) msg.writeDelimitedTo(os);

And I read those files with Builder#mergeDelimitedFrom(). Something like this:

InputStream is = new FileInputStream("a_lot_of_messages.protobuf");
SomeMessage msg1 = SomeMessage.newBuilder().mergeDelimitedFrom(is).build();
SomeMessage msg2 = SomeMessage.newBuilder().mergeDelimitedFrom(is).build();
... // This is simplified - it's implemented as an Iterator in the real code

With that way, I can read the vast majority of files without any problems but I sometimes get exceptions like this:

com.google.protobuf.InvalidProtocolBufferException: Protocol message had invalid UTF-8. ...

The code which writes those files run on mobile devices which get power failure sometimes. In such cases, my app keeps writing to the same file and  chances of getting that exceptions are high. So, apparently my code creates some malformed files on such occasions. My code can read some parts of the file, but it can't read the parts after the malformed chunk due to the error.

Now I need to rescue and read the data after the malformed chunk, but I couldn't find any way to do that. So, I'd like to know the following:

Is there any way to rescue and read the parts which are written by the code above after the malformed chunk?

If there is no way to do that, how can I improve my code so my app can cope with such problems? Is there any best practice which is power failure tolerant?

Full exception stacktrace is something like this:

com.google.protobuf.InvalidProtocolBufferException: Protocol message had invalid UTF-8.
    at com.google.protobuf.InvalidProtocolBufferException.invalidUtf8(InvalidProtocolBufferException.java:120) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.CodedInputStream.readStringRequireUtf8(CodedInputStream.java:410) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.example.Model$SomeData.<init>(Model.java:14775) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeData.<init>(Model.java:14717) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeData$1.parsePartialFrom(Model.java:18240) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeData$1.parsePartialFrom(Model.java:18234) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.google.protobuf.CodedInputStream.readMessage(CodedInputStream.java:495) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.example.Model$SomeMessage.<init>(Model.java:27250) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage.<init>(Model.java:27197) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$1.parsePartialFrom(Model.java:28678) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$1.parsePartialFrom(Model.java:28672) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$Builder.mergeFrom(Model.java:27802) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.example.Model$SomeMessage$Builder.mergeFrom(Model.java:27653) ~[my-app-1.0-SNAPSHOT.jar:na]
    at com.google.protobuf.AbstractMessageLite$Builder.mergeFrom(AbstractMessageLite.java:235) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeFrom(AbstractMessage.java:516) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeFrom(AbstractMessage.java:290) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessageLite$Builder.mergeDelimitedFrom(AbstractMessageLite.java:305) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeDelimitedFrom(AbstractMessage.java:530) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessageLite$Builder.mergeDelimitedFrom(AbstractMessageLite.java:311) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.google.protobuf.AbstractMessage$Builder.mergeDelimitedFrom(AbstractMessage.java:522) ~[protobuf-java-3.0.0-beta-2.jar:na]
    at com.example.MyUtils.read(MyUtils.java:54) [my-app-1.0-SNAPSHOT.jar:na]


问:
Call method on downcasted class
I have a certain SomeInterface and I have a number of classes implementing this interface. All these classes have someMethod() that is not defined by the interface.

Say I have a variable someVariable of type SomeInterface and I want to call someMethod() on it. One way to do it is to downcast SomeInterface to SomeClass that implements SomeInterface and call the someMethod on it like this:

```<code>((SomeClass) someVariable).someMethod()
</code>```

But I do not know which one of the classes that implement SomeInterface is stored in someVariable. What is the alternative clean way to call a method that is implemented by an underlying class but not defined by the interface I am coding against.

答:
You can use reflection to call the method

```<code>public static void main(String[] args) {
        TestI t = new Test();
        Class c = t.getClass();

        try {
           Method m = c.getDeclaredMethod("someMethod");
            m.invoke(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
</code>```

Here TestI is an interface which do not have someMethod in it. Using reflection get the method of the class and invoke method someMethod in t
object.

Title: Call method on downcasted class

Body:
I have a certain SomeInterface and I have a number of classes implementing this interface. All these classes have someMethod() that is not defined by the interface.

Say I have a variable someVariable of type SomeInterface and I want to call someMethod() on it. One way to do it is to downcast SomeInterface to SomeClass that implements SomeInterface and call the someMethod on it like this:

((SomeClass) someVariable).someMethod()

But I do not know which one of the classes that implement SomeInterface is stored in someVariable. What is the alternative clean way to call a method that is implemented by an underlying class but not defined by the interface I am coding against.

Body:
You can use reflection to call the method

public static void main(String[] args) {
        TestI t = new Test();
        Class c = t.getClass();

        try {
           Method m = c.getDeclaredMethod("someMethod");
            m.invoke(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Here TestI is an interface which do not have someMethod in it. Using reflection get the method of the class and invoke method someMethod in t
object.


问:
What steps are required to create a custom Android version?

Background

We are handing out phones for people to use while visiting our exhibition, and in those phones we are running a j2me app. The people will be using the device on their own while walking around, and returning it when leaving.

Problem

While our app is made specifically to be easy to use and understand for someone who has never used it before, the phone OS is not... (Currently HTCs with Brew MP)

People are accidentally pressing the front buttons and are thrown back into the menus, or the screen locks and they dont know how to get back.

Solution?

The only solution I can think of is to create a custom Android version that we can use in our phones.

The thing I would like to change is to disable all hardware buttons and special swipes. So people are essentially locked into our app when it is launched.

A few questions comes to mind:

How hard it is to get a custom built android version up and running on a device?

Does disabling buttons mean I have to dig deep into the kernel, or is it easily accessible?

Are some handsets better suited for running custom android? (We are currently planning on using ZTE Blade)

Does android come with drivers for GSM/camera/GPS etc for most chipsets, or will that be a problem?

Am I over-complicating things? Perhaps regular apps can override what the buttons do already?

答:
Based on your requirement, I am not sure if you need a custom Android version. If you want to control the app not responding to buttons, there should be other ways.. (I truly believe Android will have that flexibility)

Try this forum thread to start with. Android - Is It possible to disable the click of home button

ContentLicense: CC BY-SA 2.5


问:
Angular with Express: Why is my PUT request not triggering?
My GET request works but my PUT request doesn't seem to trigger. The function it is inside of definitely runs because the console.log statements show in my console. The console.log statements inside the http PUT request don't show in the google chrome console or in my terminal.

Angular:

```<code>getCitiesSaved(): Observable<string[]> {
    return this.http.get(this.url).map((data: Response) => {
      this.currentCityList = data.json().cityAlerts;
      return data.json().cityAlerts;
    });
  }

  addCity(cityName) {
    let cityArr = this.currentCityList;
    cityArr.push(cityName);
    const body = JSON.stringify({
      id: this.userId,
      cityAlerts: cityArr
    });
    const headers = new Headers({ 'Content-Type': 'application/json' });
    console.log(body);
    return this.http
      .put(this.url, body, { headers: headers })
      .map((response: Response) => {
        console.log('http put request ran in frontend');
        response.json();
      })
      .catch((error: Response) => {
        this.errorService.handleSigninError(error.json());
        return Observable.throw(error.json());
      });
  }
</code>```

Express:

```<code>router.get('/users/:id', (req, res) => {
  console.log('get user info');
  User.findOne({
    _id: req.params.id
  }).exec((err, user) => {
    if (err) {
      return res.status(500).json({
        title: 'An error occured',
        error: err
      });
    } else {
      console.log(user);
      res.status(200).json(user);
    }
  });
});

router.put('/:users/:id', (req, res) => {
  console.log('backend triggered');
  User.findOneAndUpdate(
    {
      _id: req.params.id
    },
    { $set: { cityAlerts: req.body.cityAlerts } },
    { upsert: true },
    function(err, newCityAlert) {
      if (err) {
        console.log(err);
      } else {
        console.log(newCityAlert);
        res.send(newCityAlert);
      }
    }
  );
});
</code>```

答:
You have to call subscribe on your observable before the request executes.
It looks like you need to change map to subscribe within addCity().

From the docs: https://angular.io/guide/http

Note the subscribe() method. All Observables returned from HttpClient are cold, which is to say that they are blueprints for making requests. Nothing will happen until you call subscribe(), and every such call will make a separate request. For example, this code sends a POST request with the same data twice:

Their Example:

```<code>const req = http.post('/api/items/add', body);
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.
</code>```

I hope that helps - I stumbled over this too.

Body:
My GET request works but my PUT request doesn't seem to trigger. The function it is inside of definitely runs because the console.log statements show in my console. The console.log statements inside the http PUT request don't show in the google chrome console or in my terminal.

Angular:

getCitiesSaved(): Observable<string[]> {
    return this.http.get(this.url).map((data: Response) => {
      this.currentCityList = data.json().cityAlerts;
      return data.json().cityAlerts;
    });
  }

  addCity(cityName) {
    let cityArr = this.currentCityList;
    cityArr.push(cityName);
    const body = JSON.stringify({
      id: this.userId,
      cityAlerts: cityArr
    });
    const headers = new Headers({ 'Content-Type': 'application/json' });
    console.log(body);
    return this.http
      .put(this.url, body, { headers: headers })
      .map((response: Response) => {
        console.log('http put request ran in frontend');
        response.json();
      })
      .catch((error: Response) => {
        this.errorService.handleSigninError(error.json());
        return Observable.throw(error.json());
      });
  }

Express:

router.get('/users/:id', (req, res) => {
  console.log('get user info');
  User.findOne({
    _id: req.params.id
  }).exec((err, user) => {
    if (err) {
      return res.status(500).json({
        title: 'An error occured',
        error: err
      });
    } else {
      console.log(user);
      res.status(200).json(user);
    }
  });
});

router.put('/:users/:id', (req, res) => {
  console.log('backend triggered');
  User.findOneAndUpdate(
    {
      _id: req.params.id
    },
    { $set: { cityAlerts: req.body.cityAlerts } },
    { upsert: true },
    function(err, newCityAlert) {
      if (err) {
        console.log(err);
      } else {
        console.log(newCityAlert);
        res.send(newCityAlert);
      }
    }
  );
});

Body:
You have to call subscribe on your observable before the request executes.
It looks like you need to change map to subscribe within addCity().

From the docs: https://angular.io/guide/http

Note the subscribe() method. All Observables returned from HttpClient are cold, which is to say that they are blueprints for making requests. Nothing will happen until you call subscribe(), and every such call will make a separate request. For example, this code sends a POST request with the same data twice:

Their Example:

const req = http.post('/api/items/add', body);
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.

I hope that helps - I stumbled over this too.


问:
wso2 Missing boundary in multipart/form-data POST
I'm trying to implement this scenario:

wso2Proxy sends POST to joao.php

joao.php gets id value and returns it.

if i call joao.php from a browser and a form with a field called id it works. If i do the same in WSO2 Proxy i get the php error Missing boundary in multipart/form-data POST.

I used TCPMon to analyse the calls and WSO2 sends Content-Type: multipart/form-data but no boundary.

Can someone point me in the right direction?

Here are the 2 calls:

From Browser:

```<code>POST /joao.php HTTP/1.1
Host: localhost:7590
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarytcskUke6yP5MNOzt
Origin: http://localhost:7590
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8
Referer: http://localhost:7590/joao.php
Upgrade-Insecure-Requests: 1
DNT: 1
Content-Length: 135
Connection: keep-alive

------WebKitFormBoundarytcskUke6yP5MNOzt
Content-Disposition: form-data; name="id"

sd
------WebKitFormBoundarytcskUke6yP5MNOzt--
</code>```

From WSO2 Proxy:

```<code>POST /joao.php HTTP/1.1
Content-Type: multipart/form-data
Content-Length: 264
Host: localhost:7590
Connection: Keep-Alive
User-Agent: Synapse-PT-HttpComponents-NIO

--MIMEBoundary_4e039051f0592881a6551113d958f38436c2e8eef5b85bba
Content-Disposition: form-data; name="id"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit

teste123
--MIMEBoundary_4e039051f0592881a6551113d958f38436c2e8eef5b85bba--
</code>```

I have the following commented sections on axis2.xml:

```<code><!--messageFormatter contentType="multipart/form-data"
                    class="org.wso2.carbon.relay.ExpandingMessageFormatter"/-->

<!--messageBuilder contentType="multipart/form-data"
                    class="org.wso2.carbon.relay.BinaryRelayBuilder"/-->
</code>```

This is because if I enable them then the content gets posted as XML and not multipart/data.

As a result, these are the builders and formatters that are enabled for multipart/data:

```<code><messageFormatter class="org.apache.axis2.transport.http.MultipartFormDataFormatter" contentType="multipart/form-data"/>

<messageBuilder class="org.apache.axis2.builder.MultipartFormDataBuilder" contentType="multipart/form-data"/>
</code>```

Here is the proxy configuration I am using:

```<code><proxy xmlns="http://ws.apache.org/ns/synapse"
   name="testeSendFile"
   transports="http https"
   startOnLoad="true">
<description/>
<target>
  <inSequence>
     <payloadFactory media-type="xml">
        <format>
           <params xmlns="">
              <id>teste123</id>
           </params>
        </format>
        <args/>
     </payloadFactory>
     <property name="messageType" value="multipart/form-data" scope="axis2"/>
     <property name="DISABLE_CHUNKING"
               value="true"
               scope="axis2"
               type="STRING"/>
     <log level="full"/>
     <send>
        <endpoint>
           <http method="POST" uri-template="http://localhost:7590/joao.php"/>
        </endpoint>
     </send>
     <log level="full"/>
  </inSequence>
</target>
</proxy>
</code>```

答: This is a bug. Will be fixed in next release.</p>

Body:
I'm trying to implement this scenario:

wso2Proxy sends POST to joao.php

joao.php gets id value and returns it.

if i call joao.php from a browser and a form with a field called id it works. If i do the same in WSO2 Proxy i get the php error Missing boundary in multipart/form-data POST.

I used TCPMon to analyse the calls and WSO2 sends Content-Type: multipart/form-data but no boundary.

Can someone point me in the right direction?

Here are the 2 calls:

From Browser:

POST /joao.php HTTP/1.1
Host: localhost:7590
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarytcskUke6yP5MNOzt
Origin: http://localhost:7590
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.1.2 Safari/603.3.8
Referer: http://localhost:7590/joao.php
Upgrade-Insecure-Requests: 1
DNT: 1
Content-Length: 135
Connection: keep-alive

------WebKitFormBoundarytcskUke6yP5MNOzt
Content-Disposition: form-data; name="id"

sd
------WebKitFormBoundarytcskUke6yP5MNOzt--

From WSO2 Proxy:

POST /joao.php HTTP/1.1
Content-Type: multipart/form-data
Content-Length: 264
Host: localhost:7590
Connection: Keep-Alive
User-Agent: Synapse-PT-HttpComponents-NIO

--MIMEBoundary_4e039051f0592881a6551113d958f38436c2e8eef5b85bba
Content-Disposition: form-data; name="id"
Content-Type: text/plain; charset=US-ASCII
Content-Transfer-Encoding: 8bit

teste123
--MIMEBoundary_4e039051f0592881a6551113d958f38436c2e8eef5b85bba--

I have the following commented sections on axis2.xml:

This is because if I enable them then the content gets posted as XML and not multipart/data.

As a result, these are the builders and formatters that are enabled for multipart/data:

<messageFormatter class="org.apache.axis2.transport.http.MultipartFormDataFormatter" contentType="multipart/form-data"/>

<messageBuilder class="org.apache.axis2.builder.MultipartFormDataBuilder" contentType="multipart/form-data"/>

Here is the proxy configuration I am using:

<proxy xmlns="http://ws.apache.org/ns/synapse"
   name="testeSendFile"
   transports="http https"
   startOnLoad="true">
<description/>
<target>
  <inSequence>
     <payloadFactory media-type="xml">
        <format>
           <params xmlns="">
              <id>teste123</id>
           </params>
        </format>
        <args/>
     </payloadFactory>
     <property name="messageType" value="multipart/form-data" scope="axis2"/>
     <property name="DISABLE_CHUNKING"
               value="true"
               scope="axis2"
               type="STRING"/>
     <log level="full"/>
     <send>
        <endpoint>
           <http method="POST" uri-template="http://localhost:7590/joao.php"/>
        </endpoint>
     </send>
     <log level="full"/>
  </inSequence>
</target>
</proxy>


问:
Update location in Background
I want to get user location even when the user does not use the app.now i can get location after press home button and application goes to background state, but after a few second location update stoped. And when I'm killing the app location update against stoped. this is my code in app delegate.

```<code> let locationManager = CLLocationManager()
  var LatitudeGPS = String()
  var LongitudeGPS = String()
  var speedGPS = String()
  var Course = String()
  var Altitude = String()
  var bgtimer = Timer()

func applicationDidEnterBackground(_ application: UIApplication) {

    self.doBackgroundTask()
  }

  func beginBackgroundUpdateTask() {

    backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
      self.endBackgroundUpdateTask()
    })

  }

  func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
  }
func doBackgroundTask() {

  DispatchQueue.global(qos: .background).async {

    self.beginBackgroundUpdateTask()
    self.StartupdateLocation()
    self.bgtimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.bgtimer(timer:)), userInfo: nil, repeats: true)
    RunLoop.current.add(self.bgtimer, forMode: RunLoopMode.defaultRunLoopMode)
    RunLoop.current.run()
    self.endBackgroundUpdateTask()

  }

}

func bgtimer(timer:Timer!){
  print("Fired from Background ************************************")
  updateLocation()
}
  func StartupdateLocation() {
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.requestAlwaysAuthorization()
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.pausesLocationUpdatesAutomatically = false
  }

  func updateLocation() {
locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()
    print("Latitude: \(LatitudeGPS)")
    print("Longitude: \(LongitudeGPS)")
    print("Speed: \(speedGPS)")
    print("Heading: \(Course)")
    print("Altitude BG: \(Altitude)")
    DispatchQueue.main.async {
      print(UIApplication.shared.backgroundTimeRemaining)

    }
  }

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    LatitudeGPS = String(format: "%.10f", manager.location!.coordinate.latitude)
    LongitudeGPS = String(format: "%.10f", manager.location!.coordinate.longitude)
    speedGPS = String(format: "%.3f", manager.location!.speed)
    Altitude = String(format: "%.3f", manager.location!.altitude)
    Course = String(format: "%.3f", manager.location!.course)

  }
}
</code>```

i think after a few second my application terminated and location update stoped.
I want to after 20 min that application terminated (os or user) stop updating location to keep the battery charge.
where is my problem in location update.

答:
Couple of things to be changed.

Step 1:

Make sure you have enabled location updates background mode in capabilities section of your project as shown below

Step 2:

And when I'm killing the app location update against stoped.

Quoting from apple docs

If you start this service and your app is subsequently terminated, the
  system automatically relaunches the app into the background if a new
  event arrives. In such a case, the options dictionary passed to the
  application(:willFinishLaunchingWithOptions:) and
  application(:didFinishLaunchingWithOptions:) methods of your app
  delegate contains the key location to indicate that your app was
  launched because of a location event. Upon relaunch, you must still
  configure a location manager object and call this method to continue
  receiving location events. When you restart location services, the
  current event is delivered to your delegate immediately. In addition,
  the location property of your location manager object is populated
  with the most recent location object even before you start location
  services.

link : https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati

important thing to notice in above statement is

Upon relaunch, you must still, configure a location manager object and
  call this method to continue receiving location events.

Meaning, your current location manager will not be of much use and you should create a new one and configure the new instance and call startMonitorSignificantLocationChanges again.

So iOS will send location updates to terminated apps only when you use startMonitoringSignificantLocationChanges.

All that are applicable only if your app was terminated and iOS relaunched it on receiving location update. But if your app is simply in background you need not do any thing on using startMonitorSignificantLocationChanges

on the other hand startUpdatingLocation will work only when app is in background/foreground mode. iOS will stop updating location if your app gets suspended or killed.

If you start this service and your app is suspended, the system stops
  the delivery of events until your app starts running again (either in
  the foreground or background). If your app is terminated, the delivery
  of new location events stops altogether. Therefore, if your app needs
  to receive location events while in the background, it must include
  the UIBackgroundModes key (with the location value) in its Info.plist
  file.

link: https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation

So modify your code

```<code> locationManager.startMonitoringSignificantLocationChange()
</code>```

Ok that was about proper usage of startMonitoringSignificantLocationChanges and startupdatinglocation. Now timer for mistakes in your code.

Mistake 1:

```<code>self.bgtimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.bgtimer(timer:)), userInfo: nil, repeats: true)
</code>```

Using timer to get timely updates on location. Thats not how it works!!! You cant run Timer forever. Timer stops as soon as your app suspends or gets terminated. Location Manager informs the app when location changes and you should rely on that only. You cant run timer to timely check location updates. It won't run in suspended or terminated state.

Mistake 2:

```<code>  func updateLocation() {
    locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()
</code>```

Why start and stopping update locations in subsequent statements? That does not make much sense.

Mistake 3:

```<code>func StartupdateLocation() {
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
</code>```

Your StartupdateLocation gets called multiple time and every time you called this method you are repeatedly calling startUpdatingLocation on same instance of location manager. You need not do that! You can call startUpdatingLocation or startMonitoringSignificantLocationChange only once.

Title: Update location in Background

Body:
I want to get user location even when the user does not use the app.now i can get location after press home button and application goes to background state, but after a few second location update stoped. And when I'm killing the app location update against stoped. this is my code in app delegate.

 let locationManager = CLLocationManager()
  var LatitudeGPS = String()
  var LongitudeGPS = String()
  var speedGPS = String()
  var Course = String()
  var Altitude = String()
  var bgtimer = Timer()

func applicationDidEnterBackground(_ application: UIApplication) {

    self.doBackgroundTask()
  }

  func beginBackgroundUpdateTask() {

    backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
      self.endBackgroundUpdateTask()
    })

  }

  func endBackgroundUpdateTask() {
    UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
  }
func doBackgroundTask() {

  DispatchQueue.global(qos: .background).async {

    self.beginBackgroundUpdateTask()
    self.StartupdateLocation()
    self.bgtimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.bgtimer(timer:)), userInfo: nil, repeats: true)
    RunLoop.current.add(self.bgtimer, forMode: RunLoopMode.defaultRunLoopMode)
    RunLoop.current.run()
    self.endBackgroundUpdateTask()

  }

}

func bgtimer(timer:Timer!){
  print("Fired from Background ************************************")
  updateLocation()
}
  func StartupdateLocation() {
    locationManager.delegate = self
    locationManager.startUpdatingLocation()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.requestAlwaysAuthorization()
    locationManager.allowsBackgroundLocationUpdates = true
    locationManager.pausesLocationUpdatesAutomatically = false
  }

  func updateLocation() {
locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()
    print("Latitude: \(LatitudeGPS)")
    print("Longitude: \(LongitudeGPS)")
    print("Speed: \(speedGPS)")
    print("Heading: \(Course)")
    print("Altitude BG: \(Altitude)")
    DispatchQueue.main.async {
      print(UIApplication.shared.backgroundTimeRemaining)

    }
  }

  func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    LatitudeGPS = String(format: "%.10f", manager.location!.coordinate.latitude)
    LongitudeGPS = String(format: "%.10f", manager.location!.coordinate.longitude)
    speedGPS = String(format: "%.3f", manager.location!.speed)
    Altitude = String(format: "%.3f", manager.location!.altitude)
    Course = String(format: "%.3f", manager.location!.course)

  }
}

i think after a few second my application terminated and location update stoped.
I want to after 20 min that application terminated (os or user) stop updating location to keep the battery charge.
where is my problem in location update.

Body:
Couple of things to be changed.

Step 1:

Make sure you have enabled location updates background mode in capabilities section of your project as shown below

Step 2:

And when I'm killing the app location update against stoped.

Quoting from apple docs

If you start this service and your app is subsequently terminated, the
  system automatically relaunches the app into the background if a new
  event arrives. In such a case, the options dictionary passed to the
  application(:willFinishLaunchingWithOptions:) and
  application(:didFinishLaunchingWithOptions:) methods of your app
  delegate contains the key location to indicate that your app was
  launched because of a location event. Upon relaunch, you must still
  configure a location manager object and call this method to continue
  receiving location events. When you restart location services, the
  current event is delivered to your delegate immediately. In addition,
  the location property of your location manager object is populated
  with the most recent location object even before you start location
  services.

link : https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati

important thing to notice in above statement is

Upon relaunch, you must still, configure a location manager object and
  call this method to continue receiving location events.

Meaning, your current location manager will not be of much use and you should create a new one and configure the new instance and call startMonitorSignificantLocationChanges again.

So iOS will send location updates to terminated apps only when you use startMonitoringSignificantLocationChanges.

All that are applicable only if your app was terminated and iOS relaunched it on receiving location update. But if your app is simply in background you need not do any thing on using startMonitorSignificantLocationChanges

on the other hand startUpdatingLocation will work only when app is in background/foreground mode. iOS will stop updating location if your app gets suspended or killed.

If you start this service and your app is suspended, the system stops
  the delivery of events until your app starts running again (either in
  the foreground or background). If your app is terminated, the delivery
  of new location events stops altogether. Therefore, if your app needs
  to receive location events while in the background, it must include
  the UIBackgroundModes key (with the location value) in its Info.plist
  file.

link: https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation

So modify your code

 locationManager.startMonitoringSignificantLocationChange()

Ok that was about proper usage of startMonitoringSignificantLocationChanges and startupdatinglocation. Now timer for mistakes in your code.

Mistake 1:

self.bgtimer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.bgtimer(timer:)), userInfo: nil, repeats: true)

Using timer to get timely updates on location. Thats not how it works!!! You cant run Timer forever. Timer stops as soon as your app suspends or gets terminated. Location Manager informs the app when location changes and you should rely on that only. You cant run timer to timely check location updates. It won't run in suspended or terminated state.

Mistake 2:

  func updateLocation() {
    locationManager.startUpdatingLocation()
    locationManager.stopUpdatingLocation()

Why start and stopping update locations in subsequent statements? That does not make much sense.

Mistake 3:

func StartupdateLocation() {
    locationManager.delegate = self
    locationManager.startUpdatingLocation()

Your StartupdateLocation gets called multiple time and every time you called this method you are repeatedly calling startUpdatingLocation on same instance of location manager. You need not do that! You can call startUpdatingLocation or startMonitoringSignificantLocationChange only once.


问:
L5 custom validation messages not displayed
I'm using the following code in my controller action for validation. I'm 100% sure this is the code that's being used for the validation as removing and adding validations is working as expected:

```<code>$this->validate($request, [
    'email' => 'required|email',
    'password' => 'required'
], [
    'email.required' => 'Vul een e-mailadres in.',
    'email.email' => 'Vul een geldig e-mailadres in.',
    'password.required' => 'Vul een wachtwoord in.'
]);
</code>```

The problem is that it keeps showing the default error messages ("The email field is required.") instead of the messages I'm providing ("Vul een e-mailadres in.").

I'm using the following code to display the errors in the view:

```<code>{{ $errors->first('email') }}
</code>```

I guess this is the right way to do this, because when I choose Go To Declaration of the validate method in PhpStorm I see the following function:

```<code>vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:

public function validate(Request $request, array $rules, array $messages = array())
{
    $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);

    if ($validator->fails())
    {
        $this->throwValidationException($request, $validator);
    }
}
</code>```

Why does it keep displaying the default error messages?

答:
You can use the Validato::make() method.

```<code>$data = Input::all();
$rules = array(
    'email' => 'required|email',
    'password' => 'required'
);
$messages = array(
    'email.required' => 'Vul een e-mailadres in.',
    'email.email' => 'Vul een geldig e-mailadres in.',
    'password.required' => 'Vul een wachtwoord in.'
);
$validator = Validator::make($data, $rules, $messages);
if ($validator->fails())
{
    return Response::json(['error' => $validator->errors()->first()]);
}
</code>```

Body:
I'm using the following code in my controller action for validation. I'm 100% sure this is the code that's being used for the validation as removing and adding validations is working as expected:

$this->validate($request, [
    'email' => 'required|email',
    'password' => 'required'
], [
    'email.required' => 'Vul een e-mailadres in.',
    'email.email' => 'Vul een geldig e-mailadres in.',
    'password.required' => 'Vul een wachtwoord in.'
]);

The problem is that it keeps showing the default error messages ("The email field is required.") instead of the messages I'm providing ("Vul een e-mailadres in.").

I'm using the following code to display the errors in the view:

{{ $errors->first('email') }}

I guess this is the right way to do this, because when I choose Go To Declaration of the validate method in PhpStorm I see the following function:

vendor\laravel\framework\src\Illuminate\Foundation\Validation\ValidatesRequests.php:

public function validate(Request $request, array $rules, array $messages = array())
{
    $validator = $this->getValidationFactory()->make($request->all(), $rules, $messages);

    if ($validator->fails())
    {
        $this->throwValidationException($request, $validator);
    }
}

Why does it keep displaying the default error messages?

Body:
You can use the Validato::make() method.

$data = Input::all();
$rules = array(
    'email' => 'required|email',
    'password' => 'required'
);
$messages = array(
    'email.required' => 'Vul een e-mailadres in.',
    'email.email' => 'Vul een geldig e-mailadres in.',
    'password.required' => 'Vul een wachtwoord in.'
);
$validator = Validator::make($data, $rules, $messages);
if ($validator->fails())
{
    return Response::json(['error' => $validator->errors()->first()]);
}


问:
Pythonic way to loop over dictionary
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

```<code>directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}
</code>```

```<code># My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]
</code>```

Which way is more "Pythonic"? Or is there a better way to approach this?

答:
Your Approach 2:

```<code>columns = [dataframes[year].shape[1] for year in dataframes]
</code>```

is more Pythonic and concise with the future use of dataframes in merging, plotting, manipulating, etc.since the keys are implied in the comprehension and shape gives the number of columns

Title: Pythonic way to loop over dictionary

Body:
I am practicing Pandas and have the following task:

Create a list whose elements are the # of columns of each .csv file

.csv files are stored in the dictionary directory keyed by year

I use a dictionary comprehension dataframes (again keyed by year) to store the .csv files as pandas dataframes

directory = {2009: 'path_to_file/data_2009.csv', ... , 2018: 'path_to_file/data_2018.csv'}

dataframes = {year: pandas.read_csv(file) for year, file in directory.items()}

# My Approach 1
columns = [df.shape[1] for year, df in dataframes.items()]

# My Approach 2
columns = [dataframes[year].shape[1] for year in dataframes]

Which way is more "Pythonic"? Or is there a better way to approach this?

Body:
Your Approach 2:

columns = [dataframes[year].shape[1] for year in dataframes]

is more Pythonic and concise with the future use of dataframes in merging, plotting, manipulating, etc.since the keys are implied in the comprehension and shape gives the number of columns


问:
Check for username while typing in field?
I am fluent with HTML, and mostly PHP.

I can do the scanning part with PHP.. I'm just not sure how to call a function in PHP with JavaScript, because I don't know JavaScript.

My PHP code will connect to my MySQL database and see if the text currently in the textbox (Not clicked enter yet, still typing) is in the database..

Do you know how to do this, or at least know a link that tells you how to do it?

答: Consider using jQuery in conjunction with jQuery UI, specifically something called autocomplete. I'm fairly certain it does what you're wanting, and it's completely themable for your site.</p>


问:
Allow PHP in Contact Form 7 editor
I need a form to be able to get dynamic date values from php

My current form looks like the following:

```<code>[radio date default:1 "1" "2017-11-16" "2017-11-17" "2017-11-18" "2017-11-20" "2017-11-21"]
</code>```

Is there any way to use php values instead?

Ideally, I would be able to put something like this in the editor itself

```<code>[radio date default:1 "1" "<?php echo date('Y-m-d'); ?>"]
</code>```

Is this possible?

答:
you can make your own radio button shortcodes with different names you shoud go on this way. not to run php on editor.

you can use this hook

```<code>wpcf7_add_shortcode('date_radio_button', 'wpcf7_date_radio_button');
function wpcf7_date_radio_button($tag) {
    if (!is_array($tag)) return '';

    $name = $tag['name'];
    if (empty($name)) return '';

    $html = '<input type="radio" name="' . $name . '" value="' . date('Y-m-d') . '" />';
    return $html;
}
</code>```

Title: Allow PHP in Contact Form 7 editor

Body:
I need a form to be able to get dynamic date values from php

My current form looks like the following:

[radio date default:1 "1" "2017-11-16" "2017-11-17" "2017-11-18" "2017-11-20" "2017-11-21"]

Is there any way to use php values instead?

Ideally, I would be able to put something like this in the editor itself

[radio date default:1 "1" "<?php echo date('Y-m-d'); ?>"]

Is this possible?

Body:
you can make your own radio button shortcodes with different names you shoud go on this way. not to run php on editor.

you can use this hook

wpcf7_add_shortcode('date_radio_button', 'wpcf7_date_radio_button');
function wpcf7_date_radio_button($tag) {
    if (!is_array($tag)) return '';

    $name = $tag['name'];
    if (empty($name)) return '';

    $html = '<input type="radio" name="' . $name . '" value="' . date('Y-m-d') . '" />';
    return $html;
}


问:
How to make list from two or more arrays in C# using LinQ?
I have two string say cityIds and cityNames.

```<code>cityIds="1,2,3"
cityNames="Pune,Mumbai,Surat"
</code>```

I have one class say City.cs

```<code>public class City
{
    public int CityId { get; set; }
    public string CityName { get; set; }
}
</code>```

From cityIds and cityNames I want to create List.

So if I have Input like this

```<code>cityIds="1,2,3"
cityNames="Pune,Mumbai,Surat"
</code>```

I want output like this

```<code>list[0]=CityId=1,CityName="Pune"
list[1]=CityId=2,CityName="Mumbai"
list[2]=CityId=3,CityName="Surat"
</code>```

I tried this

```<code>var listOfIds = cityIds.Split(',');
var listOfNames = cityNames.Split(',');
for(int i = 0; i < listOfIds.Count; i++)
{
     listOfDealerCities.Add(new City()
     {
          CityId = Int32.Parse(listOfIds[i]),
          CityName = listOfNames[i]
     });
}
</code>```

Is there any better way to do this like using LINQ?

答:
You could use Linq's Zip method for this:</p>

```<code>listOfDealerCities.AddRange(listOfIds.Zip(
listOfNames, (id, name) => new City()
{
    CityId = int.Parse(id), CityName = name
}));
</code>```

Body:
I have two string say cityIds and cityNames.

cityIds="1,2,3"
cityNames="Pune,Mumbai,Surat"

I have one class say City.cs

public class City
{
    public int CityId { get; set; }
    public string CityName { get; set; }
}

From cityIds and cityNames I want to create List.

So if I have Input like this

cityIds="1,2,3"
cityNames="Pune,Mumbai,Surat"

I want output like this

list[0]=CityId=1,CityName="Pune"
list[1]=CityId=2,CityName="Mumbai"
list[2]=CityId=3,CityName="Surat"

I tried this

var listOfIds = cityIds.Split(',');
var listOfNames = cityNames.Split(',');
for(int i = 0; i < listOfIds.Count; i++)
{
     listOfDealerCities.Add(new City()
     {
          CityId = Int32.Parse(listOfIds[i]),
          CityName = listOfNames[i]
     });
}

Is there any better way to do this like using LINQ?

Body:
You could use Linq's Zip method for this:

listOfDealerCities.AddRange(listOfIds.Zip(
listOfNames, (id, name) => new City()
{
    CityId = int.Parse(id), CityName = name
}));


问:
After updating Azure Powershell module cannot import my module anymore and getting strange error
I just updated to the latest Azure powershell but after that I can no longer import my module (worked fine for a very long time). This is the error that I am getting:

Import-Module : Method 'get_DataCollectionWarning' in type 'Microsoft.Azure.Commands.Automation.Cmdlet.GetAzureAutomationCertificate' from assembly
  'Microsoft.Azure.Commands.Automation, Version=4.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.
  At line:1 char:1
  + im .\MyResources.psd1
  + ~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : NotSpecified: (:) [Import-Module], TypeLoadException
      + FullyQualifiedErrorId : System.TypeLoadException,Microsoft.PowerShell.Commands.ImportModuleCommand

Can someone please suggest what may be going on wrong here. Note that the method without implementation seem to be from the Azure PS package.

答:
If you have upgraded your Azure PowerShell to version 5.0.0, it is a BREAKING CHANGE RELEASE based on its release notes.

You should refer to see the migration guide for a full list of introduced breaking changes.

In addition, the Azure PowerShell team has also released a newer version 5.0.1 which fixed the issue which might also related to your problem.

Fixed assembly loading issue that caused some cmdlets to fail when
  executing in the following modules:

AzureRM.ApiManagement

AzureRM.Backup

AzureRM.Batch

AzureRM.Compute

AzureRM.DataFactories

AzureRM.HDInsight

AzureRM.KeyVault

AzureRM.RecoveryServices

AzureRM.RecoveryServices.Backup

AzureRM.RecoveryServices.SiteRecovery

AzureRM.RedisCache

AzureRM.SiteRecovery

AzureRM.Sql

AzureRM.Storage

AzureRM.StreamAnalytics

Hope this helps.


问:
sqlalchemy trying to count parents in database efficiently
The following function rank counts the parents in the database properly, but I have to send it like Group.query.(user_id==1).rank(0, Group.query.(user_id==1)) which does not seem very efficient. Is there a better way to write this function?</p>

```<code>class Group(db.Model):
    #data
    id=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(32), nullable=False)
    #relationships
    parent_id=db.Column(db.Integer, db.ForeignKey('group.id'))
    children=db.relationship('Group', backref=db.backref('parent', remote_side=[id]))

    def rank(self, count, parent):
        if parent.parent:
            count=count+1
            parent.rank(count, parent.parent)
        else:
            return count
</code>```

答:
Passing the instance that you're calling the method on as another argument is redundant, and your function is also missing a return statement. Not to mention performing the same query twice just to get going. You could and should simply use self and self.parent. Your recursive function's base case would be when there is no parent:

```<code>class Group(db.Model):

    def rank(self):
        if not self.parent:
            return 0

        else:
            # Python has no TCO, so no point in trying to
            # use an accumulator
            return 1 + self.parent.rank()
</code>```

But you're right that this might not perform ideally, if you have deeply nested structures, but for just a few levels of nesting the simple recursion might beat more complex methods. Every first access of Group.parent on an instance will issue a new SELECT statement to the DB. You could take the operation to your data, or in other words perform it in the DB. Tree like structures can be handled with a recursive Common Table Expression:

```<code>def rank(self):
    cls = type(self)
    parents = db.session.query(cls.parent_id).\
        filter_by(id=self.id).\
        cte(recursive=True)

    parent_alias = db.aliased(parents)
    group_alias = db.aliased(cls)

    parents = parents.union_all(
        db.session.query(group_alias.parent_id).
            filter(group_alias.id == parent_alias.c.parent_id))

    # Subtract one so that only the parents count
    return db.session.query(db.func.count() - 1).\
        select_from(parents).\
        scalar()
</code>```

You could also possibly turn this in to a hybrid property, if you need the count SQL side some time.

Body:
The following function rank counts the parents in the database properly, but I have to send it like Group.query.(user_id==1).rank(0, Group.query.(user_id==1)) which does not seem very efficient. Is there a better way to write this function?

class Group(db.Model):
    #data
    id=db.Column(db.Integer, primary_key=True)
    name=db.Column(db.String(32), nullable=False)
    #relationships
    parent_id=db.Column(db.Integer, db.ForeignKey('group.id'))
    children=db.relationship('Group', backref=db.backref('parent', remote_side=[id]))

    def rank(self, count, parent):
        if parent.parent:
            count=count+1
            parent.rank(count, parent.parent)
        else:
            return count

Body:
Passing the instance that you're calling the method on as another argument is redundant, and your function is also missing a return statement. Not to mention performing the same query twice just to get going. You could and should simply use self and self.parent. Your recursive function's base case would be when there is no parent:

class Group(db.Model):

    def rank(self):
        if not self.parent:
            return 0

        else:
            # Python has no TCO, so no point in trying to
            # use an accumulator
            return 1 + self.parent.rank()

But you're right that this might not perform ideally, if you have deeply nested structures, but for just a few levels of nesting the simple recursion might beat more complex methods. Every first access of Group.parent on an instance will issue a new SELECT statement to the DB. You could take the operation to your data, or in other words perform it in the DB. Tree like structures can be handled with a recursive Common Table Expression:

def rank(self):
    cls = type(self)
    parents = db.session.query(cls.parent_id).\
        filter_by(id=self.id).\
        cte(recursive=True)

    parent_alias = db.aliased(parents)
    group_alias = db.aliased(cls)

    parents = parents.union_all(
        db.session.query(group_alias.parent_id).
            filter(group_alias.id == parent_alias.c.parent_id))

    # Subtract one so that only the parents count
    return db.session.query(db.func.count() - 1).\
        select_from(parents).\
        scalar()

You could also possibly turn this in to a hybrid property, if you need the count SQL side some time.


问:
shell script for checking files in a directory with count
Iam trying to write a shell script to check the files in a particular path ,
if files available then i need to get success mail else I need to get failure mail .
but I my query even if 1 file is available I am getting success mail but daily I am getting 9 files , even if 1 file is not available I need to get failure mail please help me to write a script for the above logic</p>

```<code>cd /file path
if [ -f $(date '+%Y%m%d') file name ]; then
echo "Hi Team,  Input Files have been received successfully" |  mailx -s "SUCCESS" -r "FILE_CHK" userid@doamin.com
else
echo "Hi Team,  Input Files have NOT been received . Please check" |  mailx -s "FAILED" -r "FILE_CHK" userid@doamin.com
fi
exit
</code>```

答:
You need to check that all the files exist and only if this is the case send the mail that it was successful. If you have only one file not present, then you should directly send the error message.

The following code prototype does the trick:

```<code>#!/bin/bash
files=( "file1" "file2" "file3" )
for i in "${files[@]}"
do
    echo "Checking if file: $i exists."
    if [ ! -f $i ]; then
        echo "Hi Team, Input File $i has NOT been received! Please check" |  mailx -s "FAILED" -r "FILE_CHK" userid@doamin.com
        exit 0;
    fi
done
echo "Hi Team, Input Files have been received successfully" |  mailx -s "SUCCESS" -r "FILE_CHK" userid@doamin.com
</code>```

Basically you have a list of files you need to check, you check element by element that it does exist and if one of the element of the list is not present then you send the failure notification by mail and you exit.

If and only if all the files are present then you send the success message!!!

Last but not least, this script is just a skeleton that you need to adapt to your particular needs (adding a timestamp etc).

Body:
Iam trying to write a shell script to check the files in a particular path ,
if files available then i need to get success mail else I need to get failure mail .
but I my query even if 1 file is available I am getting success mail but daily I am getting 9 files , even if 1 file is not available I need to get failure mail please help me to write a script for the above logic

cd /file path
if [ -f $(date '+%Y%m%d') file name ]; then
echo "Hi Team,  Input Files have been received successfully" |  mailx -s "SUCCESS" -r "FILE_CHK" userid@doamin.com
else
echo "Hi Team,  Input Files have NOT been received . Please check" |  mailx -s "FAILED" -r "FILE_CHK" userid@doamin.com
fi
exit

Body:
You need to check that all the files exist and only if this is the case send the mail that it was successful. If you have only one file not present, then you should directly send the error message.

The following code prototype does the trick:

#!/bin/bash
files=( "file1" "file2" "file3" )
for i in "${files[@]}"
do
    echo "Checking if file: $i exists."
    if [ ! -f $i ]; then
        echo "Hi Team, Input File $i has NOT been received! Please check" |  mailx -s "FAILED" -r "FILE_CHK" userid@doamin.com
        exit 0;
    fi
done
echo "Hi Team, Input Files have been received successfully" |  mailx -s "SUCCESS" -r "FILE_CHK" userid@doamin.com

Basically you have a list of files you need to check, you check element by element that it does exist and if one of the element of the list is not present then you send the failure notification by mail and you exit.

If and only if all the files are present then you send the success message!!!

Last but not least, this script is just a skeleton that you need to adapt to your particular needs (adding a timestamp etc).


问:
Adding files to an Xcode project (SVN)
I "checked out" an SVN repo. The repo contains a few Xcode projects and a workspace. I can open the workspace, build everything, run the app etc. If I make changes to any existing file they will be taken into account when building the app.

Now I want to add two new files to the workspace/project. I want to modify these files and when ready "commit" and "push" (I normally use git) the files to the repo. I added MyClass.h and MyClass.m to the Xcode project via right clicking on the appropriate group in Xcode and selecting "Add file to MyProject...".

The project won't build because MyClass.h can't be found. I also see a warning from the workspace that "MyClass.h is missing from the working copy".

How can I add files to an Xcode project under SVN version control?

I tried the suggestions here Xcode adding new files to existing project in svn but nothing works yet. For example when the files I just added to Xcode are selected the menu option "Add Selected Files" in the Source Control menu is greyed out.

I'm using Xcode 5.

答: As a work around, you can use smartsvn which has options for adding and removing files in Modify  top menu</p>

Title: Adding files to an Xcode project (SVN)


问:
Is it possible to use `ng-click` inside of `.append`
I am trying to call one method using angular which is placed inside of .append.
But the method is not called.Can I use ng-click inside .append?otherwise is there any alternative way to append element in angular?

```<code>var app=angular
.module('myApp',[])
.controller('myController',function($scope){

  $scope.clickMe = function(){
        $('.paragraph').append('<span ng-click="closeMe()"><i class="fa fa-times" aria-hidden="true"></i></span>');
  }
  $scope.closeMe = function(){
    alert("closed")
  }
})
</code>```

Sample: https://jsfiddle.net/fjhbbnno/

答:
Check if this logic helps

jsfiddle

```<code>var app=angular.module('myApp',[])
        .controller('myController',function($scope){
            $scope.clicked = false;
          $scope.clickMe = function(){
                $scope.clicked = true;
          }
          $scope.closeMe = function(){
            alert("closed")
          }
        })
</code>```

HTML:

```<code><section ng-app="myApp" ng-controller="myController" ng-init="init()">
<div class="paragraph">
<p>
This is a sample.
</p>
<span ng-if="clicked"><i class="fa fa-times" aria-hidden="true" ng-click="closeMe()"></i></span>
</div>
<button ng-click="clickMe()">Add Close ICon</button>
</section>
</code>```

Body:
I am trying to call one method using angular which is placed inside of .append.
But the method is not called.Can I use ng-click inside .append?otherwise is there any alternative way to append element in angular?

var app=angular
.module('myApp',[])
.controller('myController',function($scope){

  $scope.clickMe = function(){
        $('.paragraph').append('');
  }
  $scope.closeMe = function(){
    alert("closed")
  }
})

Sample: https://jsfiddle.net/fjhbbnno/

Body:
Check if this logic helps

jsfiddle

var app=angular.module('myApp',[])
        .controller('myController',function($scope){
            $scope.clicked = false;
          $scope.clickMe = function(){
                $scope.clicked = true;
          }
          $scope.closeMe = function(){
            alert("closed")
          }
        })

HTML:

<section ng-app="myApp" ng-controller="myController" ng-init="init()">
<div class="paragraph">
<p>
This is a sample.
</p>
<span ng-if="clicked"><i class="fa fa-times" aria-hidden="true" ng-click="closeMe()"></i></span>
</div>
<button ng-click="clickMe()">Add Close ICon</button>
</section>


问:
replace older resources file with newest at flavours
In my project I have 2 flavour. in main module I have a raw folder contain a json file.In my flavour I need to change this json file.I have created this file into raw folder at res folder in my flavour and according this link

I added this line to my build.gradle:

```<code>    productFlavors {
    main {

    }
    abfa {
        applicationIdSuffix ".abfa"
        versionName '1.1.61-Abfa'
        sourceSets {
            res.raw = ['resources/abfa']
        }
    }
</code>```

but I got this error:

```<code>Error:(98, 0) Could not set unknown property 'raw' for source set res of type com.android.build.gradle.internal.api.DefaultAndroidSourceSet.
</code>```

how could I replace older resources file with newest at every flavour?

答:
Just create in the folder of your flavor same file structure tree as in main flavor folder.

See as in example

Here I've got flavor global_dev additionally and if it is chosen one, then its resources are overriding the main flavor resources. Then this line

```<code>sourceSets {
        res.raw = ['resources/abfa']
    }
</code>```

is not needed.

Body:
In my project I have 2 flavour. in main module I have a raw folder contain a json file.In my flavour I need to change this json file.I have created this file into raw folder at res folder in my flavour and according this link

I added this line to my build.gradle:

    productFlavors {
    main {

    }
    abfa {
        applicationIdSuffix ".abfa"
        versionName '1.1.61-Abfa'
        sourceSets {
            res.raw = ['resources/abfa']
        }
    }

but I got this error:

Error:(98, 0) Could not set unknown property 'raw' for source set res of type com.android.build.gradle.internal.api.DefaultAndroidSourceSet.

how could I replace older resources file with newest at every flavour?

Body:
Just create in the folder of your flavor same file structure tree as in main flavor folder.

See as in example

Here I've got flavor global_dev additionally and if it is chosen one, then its resources are overriding the main flavor resources. Then this line

sourceSets {
        res.raw = ['resources/abfa']
    }

is not needed.


问:
Nodejs express application on nginx linux server
I have created my first nodejs application with nodejs express.
The server is

```<code>var express = require("express");
global.app = express();
require("src/app-modules/common/yamaha/yamaha.controller.api");
app.listen(8080, function() {
console.log("Listening on http://127.0.0.1:8080");
});
</code>```

On windows development machine Is working.
Now I try to publish this app on a Synology NAS.
I access this application on url: //192.168.1.151/YamahaCtrl
and I have a 404 error.
Update 2: I discover what is realy the problem: how to configure the nginx server fromn
Routes are defined on yamaha.controller.api like this one:

```<code>    app.get("/api/yamaha/getBasicInfo", function (req, res) {
        //do something
    });
</code>```

I found a nodejs 8 beta package to install on NAS, and now I have nodejs version 8. But the error still remain.

So the nodejs app server is open on localhost:8080, but url access is http://192.168.1.151/YamahaCtrl, on 80.

That mean the problem is how to configure Virtual Host on NAS, and which port on node server I should use.

Update: The problem is: need to configure a redirect port on nginx server installed on Synology. I found this article:
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04

and I create configuration file /etc/nginx/sites-available/default:

```<code>server {
listen 80;

server_name _;

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}
</code>```

}

And still not working: the html files are accessible , but api is available on port 8080 only.

答:
I figured out what the problem was: nodejs server is serving static files too, but my config for static files was wrong. For development was working, and that why I didn't know that is wrong.

So it's no need to configure something on NAS :). To start nodejs application is enough.

Body:
I have created my first nodejs application with nodejs express.
The server is

var express = require("express");
global.app = express();
require("src/app-modules/common/yamaha/yamaha.controller.api");
app.listen(8080, function() {
console.log("Listening on http://127.0.0.1:8080");
});

On windows development machine Is working.
Now I try to publish this app on a Synology NAS.
I access this application on url: //192.168.1.151/YamahaCtrl
and I have a 404 error.
Update 2: I discover what is realy the problem: how to configure the nginx server fromn
Routes are defined on yamaha.controller.api like this one:

    app.get("/api/yamaha/getBasicInfo", function (req, res) {
        //do something
    });

I found a nodejs 8 beta package to install on NAS, and now I have nodejs version 8. But the error still remain.

So the nodejs app server is open on localhost:8080, but url access is http://192.168.1.151/YamahaCtrl, on 80.

That mean the problem is how to configure Virtual Host on NAS, and which port on node server I should use.

Update: The problem is: need to configure a redirect port on nginx server installed on Synology. I found this article:
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04

and I create configuration file /etc/nginx/sites-available/default:

server {
listen 80;

server_name _;

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

}

And still not working: the html files are accessible , but api is available on port 8080 only.


答:
You can also use the ng-bind-html

```<code>$scope.clickMe = function(){
      $scope.htmlCode= $sce.trustAsHtml('<span ng-click="closeMe()"><i class="fa fa-times" aria-hidden="true"></i></span>');
}

<p>
  This is a sample.
  <span ng-bind-html="htmlCode">
  </span>
</p>
</code>```

also inject the $sce to the controller. Demo

Title: Is it possible to use `ng-click` inside of `.append`

Body:
You can also use the ng-bind-html

$scope.clickMe = function(){
      $scope.htmlCode= $sce.trustAsHtml('<span ng-click="closeMe()"><i class="fa fa-times" aria-hidden="true"></i></span>');
}

<p>
  This is a sample.
  <span ng-bind-html="htmlCode">
  </span>
</p>

also inject the $sce to the controller. Demo


答:
It is, but it is not the best practice.
Often it will not work as the element is not is scope range until it is created which is too late.

Angular has very particular set of rules that were made to keep it 'clear' let's say.
Another example is dependency injection, which means you cannot provide multiple dependencies between different modules with the same name, this is not very smart either, for if you have a main module, that other controllers just derive from him, declare all of your dependencies in the main module and keep your code clear.

Solution:

1) Create your close me button and keep it hidden, show it after you append your html.

2) Another solution is to create a popup that will contain the relevant info.

3) If you must append the ng-click, use the $compile dependency that will bring your directives to scope from the appended html:

```<code> var compile = $compile(appendedElement)($scope)
</code>```

Body:
It is, but it is not the best practice.
Often it will not work as the element is not is scope range until it is created which is too late.

Angular has very particular set of rules that were made to keep it 'clear' let's say.
Another example is dependency injection, which means you cannot provide multiple dependencies between different modules with the same name, this is not very smart either, for if you have a main module, that other controllers just derive from him, declare all of your dependencies in the main module and keep your code clear.

Solution:

1) Create your close me button and keep it hidden, show it after you append your html.

2) Another solution is to create a popup that will contain the relevant info.

3) If you must append the ng-click, use the $compile dependency that will bring your directives to scope from the appended html:

 var compile = $compile(appendedElement)($scope)


问:
Is there a shorter way for if-else chains?
```<code>if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"
</code>```

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

答:
Yes, you could do it this way, but it doesn't reduce the code much:

```<code>if m < 50:
    g = "U"
elif m < 60:
    g = "D"
elif m < 70:
    g = "C"
elif m < 80:
    g = "B"
else:
    g = 'A'
</code>```

as a one liner (which is hard to read):

```<code>g = 'U' if m < 50 else "D" if m < 60 else "C" if m < 70 else "B" if m < 80 else "A"
</code>```

Body:
if (80 <= m <= 100):
    g = "A"
elif (70 <= m < 80):
    g = "B"
elif (60 <= m < 70):
    g = "C"
elif (50 <= m < 60):
    g = "D"
elif (m < 50):
    g = "U"

This is basically a grade measuring piece of code that takes in value m, meaning mark, and obtains grade g. Is there a shorter not necessarily more pythonic way for the same purpose?

Thanks in advance.

Body:
Yes, you could do it this way, but it doesn't reduce the code much:

if m < 50:
    g = "U"
elif m < 60:
    g = "D"
elif m < 70:
    g = "C"
elif m < 80:
    g = "B"
else:
    g = 'A'

as a one liner (which is hard to read):

g = 'U' if m < 50 else "D" if m < 60 else "C" if m < 70 else "B" if m < 80 else "A"


问:
How do I display a ratio in Excel in the format A:B?
I have an Excel spreadsheet of data like:

```<code>ColumnA ColumnB
33        11
25        5
6         4
</code>```

What i would like to do is add a third column which shows the ratio of columnA to columnB in the format of A:B. For example:

```<code>ColumnA ColumnB   Ratio
33        11       3:1
25        5    5:1
6         4    3:2
</code>```

How can this be done?

答:
Try this formula:

```<code>=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")
</code>```

Result:

```<code>A   B   C
33  11  3:1
25  5   5:1
6   4   3:2
</code>```

Explanation:

TEXT(A1/B1,"?/?") turns A/B into an improper fraction

SUBSTITUTE(...) replaces the "/" in the fraction with a colon

This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.

Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).

OwnerDisplayName: Vincent

ContentLicense: CC BY-SA 4.0

Body:
I have an Excel spreadsheet of data like:

ColumnA ColumnB
33        11
25        5
6         4

What i would like to do is add a third column which shows the ratio of columnA to columnB in the format of A:B. For example:

ColumnA ColumnB   Ratio
33        11       3:1
25        5    5:1
6         4    3:2

How can this be done?

LastEditorDisplayName: Vincent

Body:
Try this formula:

=SUBSTITUTE(TEXT(A1/B1,"?/?"),"/",":")

Result:

A   B   C
33  11  3:1
25  5   5:1
6   4   3:2

Explanation:

TEXT(A1/B1,"?/?") turns A/B into an improper fraction

SUBSTITUTE(...) replaces the "/" in the fraction with a colon

This doesn't require any special toolkits or macros. The only downside might be that the result is considered text--not a number--so you can easily use it for further calculations.

Note: as @Robin Day suggested, increase the number of question marks (?) as desired to reduce rounding (thanks Robin!).

OwnerDisplayName: Michael Haren

LastEditorDisplayName: Michael Haren


问:
gitlab issue- not able to save application after changing the context-root
I am working on a ADF application,with jdeveloper. I have to change context root of the application, the project is a git repository. After changing the context root, I am unable to save the project. Below is the issue:

Issue - Unable to save /Users/{username}/gitlab/{project name}/ViewController/ViewController.jpr (The project /Users/{username}/gitlab/{project name}/ViewController/ViewController.jpr is in a merge conflict state.  Please resolve the merge conflicts in the project file before attempting to save further changes.).

答:
I dont know the exact cause of this. But i have gone through same case and it seems like it is caused due to some conflict in project properties.
 So i would recommend you to right click on viewcontroller go to properties> Java EE application and there instead of making changes directly in default project properties. Use customized settings option given by JDeveloper and change your context-root there. It wont cause any conflict there.


问:
Rasa NLU:Entity Synonyms detection inconsistency
Me and my team have been using Rasa NLU as a replacement for MS LUIS for over 2 months now, and it has worked out pretty well for us so far. Now we have around 900 entries as Entity Synonyms(as we were using List entity in LUIS).

And only for some utterances, the entity is detected as synonyms and for the majority of utterances, it is unable to detect Entity Synonyms. In order to detect synonyms, I have to create another simple entity which again we are manually training with all the synonym values, once the intents are trained with this simple Entity Rasa seems to detect entity for this intent as both simple and synonyms.

And another quick question, Is the Entity Synonyms in Rasa designed to return only one matched entity(unlike LUIS which used to return all the matched entities values)?

Is there any alternative to list entity from LUIS here in Rasa?

答:
Entity Synonyms in Rasa can lead to some confusion. The actual functionality that they provide is very simple. For each entity that is parsed by the model the value of that entity is checked against the list of entity synonyms. If the value matches an entity synonym then it is replaced with the synonym value.

The big catch in the above statement is that the the entity has to be identified by the model before it can be replaced with a synonym.

So take this as a simplified example. Here is my entity synonym definition:

```<code>{
  "value": "New York City",
  "synonyms": ["NYC", "nyc", "the big apple"]
}
</code>```

If my training data only provides this example:

```<code>{
  "text": "in the center of NYC",
  "intent": "search",
  "entities": [
    {
      "start": 17,
      "end": 20,
      "value": "New York City",
      "entity": "city"
    }
  ]
}
</code>```

It is very unlikely that my model will be able to detect an entity in a sentence like In the center of the big apple. As I said above if the big apple isn't parsed as an entity by the model it cannot be replaced by the entity synonyms to read New York City.

For this reason you should include more examples in the actual common_examples of the training data with the entities labeled. Once all of the variations of the entity are being classified correctly then add those values to the entity synonym and they will be replaced.

```<code>[
  {
    "text": "in the center of NYC",
    "intent": "search",
    "entities": [
      {
        "start": 17,
        "end": 20,
        "value": "New York City",
        "entity": "city"
      }
    ]
  },
  {
    "text": "in the centre of New York City",
    "intent": "search",
    "entities": [
      {
        "start": 17,
        "end": 30,
        "value": "New York City",
        "entity": "city"
      }
    ]
  }
]
</code>```

I've opened a pull request into the Rasa docs page to add a note to this effect.

Body:
Entity Synonyms in Rasa can lead to some confusion. The actual functionality that they provide is very simple. For each entity that is parsed by the model the value of that entity is checked against the list of entity synonyms. If the value matches an entity synonym then it is replaced with the synonym value.

The big catch in the above statement is that the the entity has to be identified by the model before it can be replaced with a synonym.

So take this as a simplified example. Here is my entity synonym definition:

{
  "value": "New York City",
  "synonyms": ["NYC", "nyc", "the big apple"]
}

If my training data only provides this example:

{
  "text": "in the center of NYC",
  "intent": "search",
  "entities": [
    {
      "start": 17,
      "end": 20,
      "value": "New York City",
      "entity": "city"
    }
  ]
}

It is very unlikely that my model will be able to detect an entity in a sentence like In the center of the big apple. As I said above if the big apple isn't parsed as an entity by the model it cannot be replaced by the entity synonyms to read New York City.

For this reason you should include more examples in the actual common_examples of the training data with the entities labeled. Once all of the variations of the entity are being classified correctly then add those values to the entity synonym and they will be replaced.

[
  {
    "text": "in the center of NYC",
    "intent": "search",
    "entities": [
      {
        "start": 17,
        "end": 20,
        "value": "New York City",
        "entity": "city"
      }
    ]
  },
  {
    "text": "in the centre of New York City",
    "intent": "search",
    "entities": [
      {
        "start": 17,
        "end": 30,
        "value": "New York City",
        "entity": "city"
      }
    ]
  }
]

I've opened a pull request into the Rasa docs page to add a note to this effect.


问:
My Python regular expression is not matching any data in my text file for YYYY date format
I have a text file that contains dates in different formats. e.g.

2014

2015

January 7, 2015

6th January 2012

.

.

etc.

Now, I am trying to write a regular expression to print all the dates that are in YYYY format in the .txt file such as 2014, 2015.

However, I am not getting any matches from the code I executed. Could anyone please help with the problem ? Thanks.

My Python Code:

```<code>import re

for i in "file.txt":

    match = re.match(r'\d{2}-\d{2}-(\d{4})', i)

    print(match)
</code>```

Current Output:

```<code>None

None

None

None

None

None
</code>```

答:
There are three problems: first, you have not actually opened the file. So, for i in "file.txt" actually returns the letters "f", "i", ... in each loop iteration. Second, your regular expression is looking for DD-MM-YYYY, which is not present in your sample file. Lastly, match is not a string that you can print. Instead, this code works:

```<code>import re
myfile = open("file.txt", "r")
for i in myfile:
    match = re.match(r'\d{4}$', i[:-1])
    print(match.string)
</code>```

Body:
I have a text file that contains dates in different formats. e.g.

2014

2015

January 7, 2015

6th January 2012

.

.

etc.

Now, I am trying to write a regular expression to print all the dates that are in YYYY format in the .txt file such as 2014, 2015.

However, I am not getting any matches from the code I executed. Could anyone please help with the problem ? Thanks.

My Python Code:

import re

for i in "file.txt":

    match = re.match(r'\d{2}-\d{2}-(\d{4})', i)

    print(match)

Current Output:

None

None

None

None

None

None

Body:
There are three problems: first, you have not actually opened the file. So, for i in "file.txt" actually returns the letters "f", "i", ... in each loop iteration. Second, your regular expression is looking for DD-MM-YYYY, which is not present in your sample file. Lastly, match is not a string that you can print. Instead, this code works:

import re
myfile = open("file.txt", "r")
for i in myfile:
    match = re.match(r'\d{4}$', i[:-1])
    print(match.string)


问:
Change Package Name of Windows Store App
How do we change the package name of a Windows Store App? Please note we do not want to change the app display name.

We have published a UWP app to the Windows Store. Visual Studio generated a package name <PublisherName>.<AppName>in the package manifest.

When I changed the package name in the package manifest to a guid and published to the store I got the errors

```<code> Invalid package identity name
 Invalid package family name
</code>```

I can see the store app is associated with the package name. Do we have to delete the store app and create a new submission?

Can a UWP store app have a guid for a package name?

答:
It looks like I've misunderstood the store process. I was incorrect in thinking the app identity was generated by Visual Studio. The app identity is assigned by the store.

If you use Microsoft Visual Studio to build your packages, and are signed in with the same Microsoft account that you have associated with your developer account, these details are included automatically.

So it looks like we will have to live with the app folder being discoverable by users.

Body:
How do we change the package name of a Windows Store App? Please note we do not want to change the app display name.

We have published a UWP app to the Windows Store. Visual Studio generated a package name <PublisherName>.<AppName>in the package manifest.

When I changed the package name in the package manifest to a guid and published to the store I got the errors

 Invalid package identity name
 Invalid package family name

I can see the store app is associated with the package name. Do we have to delete the store app and create a new submission?

Can a UWP store app have a guid for a package name?


问:
SubString across different string lengths
I have the following SUBSTRING command:

```<code>RTRIM(LTRIM(SUBSTRING(FileName, CHARINDEX('-', FileName, 0)+1, CHARINDEX('-', FileName, 0)-7 )))
</code>```

and have file paths like the below:

```<code>"C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514"
"C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585 MR"
</code>```

The first one returns the correct result, but the second returns extra characters. Does anyone see a way of ensuring the V* number is always returned correctly?

答:
You can use this formula.

```<code>RTRIM(LTRIM(SUBSTRING(FileName, CHARINDEX('-', FileName, 0)+1, 7 )))
</code>```

Sample:

```<code>DECLARE @FileName1 VARCHAR(255) = 'C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514'

DECLARE @FileName2 VARCHAR(255) = 'C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585 MR'

SELECT
RTRIM(LTRIM(SUBSTRING(@FileName1, CHARINDEX('-', @FileName1, 0)+1, 7 ))) F1,
RTRIM(LTRIM(SUBSTRING(@FileName2, CHARINDEX('-', @FileName2, 0)+1, 7 ))) F2
</code>```

Result:

```<code>F1      F2
------- -------
V00015  V00015
</code>```

Body:
I have the following SUBSTRING command:

RTRIM(LTRIM(SUBSTRING(FileName, CHARINDEX('-', FileName, 0)+1, CHARINDEX('-', FileName, 0)-7 )))

and have file paths like the below:

"C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514"
"C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585 MR"

The first one returns the correct result, but the second returns extra characters. Does anyone see a way of ensuring the V* number is always returned correctly?

Body:
You can use this formula.

RTRIM(LTRIM(SUBSTRING(FileName, CHARINDEX('-', FileName, 0)+1, 7 )))

Sample:

DECLARE @FileName1 VARCHAR(255) = 'C:\James\AAA(9) - V0001514 MR J BLOGGS.pdf"    returns "V0001514'

DECLARE @FileName2 VARCHAR(255) = 'C:\James\test(100) - V0001585 MRS A SMITH.pdf  returns "V0001585 MR'

SELECT
RTRIM(LTRIM(SUBSTRING(@FileName1, CHARINDEX('-', @FileName1, 0)+1, 7 ))) F1,
RTRIM(LTRIM(SUBSTRING(@FileName2, CHARINDEX('-', @FileName2, 0)+1, 7 ))) F2

Result:

F1      F2
------- -------
V00015  V00015


问:
List of common docstring :types for pycharm
Pycharm has a nice feature, whereby it reads the type declaration within a function docstring and does correct-usage checks where that function is used.

Is there a nice resource, that lists rules and names for all commonly used types?

Note:

I have provided an answer below, with everything that I have been able to figure out. Its far from comprehensive, though.

答:
Here is an excerpt from README-obsolete.md Types section, mentioned by user2235698):

```<code>Foo                # Class Foo visible in the current scope
x.y.Bar            # Class Bar from x.y module
Foo | Bar          # Foo or Bar
(Foo, Bar)         # Tuple of Foo and Bar
list[Foo]          # List of Foo elements
dict[Foo, Bar]     # Dict from Foo to Bar
T                  # Generic type (T-Z are reserved for generics)
T <= Foo           # Generic type with upper bound Foo
Foo[T]             # Foo parameterized with T
(Foo, Bar) -> Baz  # Function of Foo and Bar that returns Baz

unknown            # Unknown type
None               # type(None)
string             # Py2: str | unicode, Py3: str
bytestring         # Py2: str | unicode, Py3: bytes
bytes              # Py2: str, Py3: bytes
unicode            # Py2: unicode, Py3: str
</code>```

By the way: there is also section mentioning Type Hinting, in the PyCharm documentation.

Body:
Here is an excerpt from README-obsolete.md Types section, mentioned by user2235698):

Foo                # Class Foo visible in the current scope
x.y.Bar            # Class Bar from x.y module
Foo | Bar          # Foo or Bar
(Foo, Bar)         # Tuple of Foo and Bar
list[Foo]          # List of Foo elements
dict[Foo, Bar]     # Dict from Foo to Bar
T                  # Generic type (T-Z are reserved for generics)
T <= Foo           # Generic type with upper bound Foo
Foo[T]             # Foo parameterized with T
(Foo, Bar) -> Baz  # Function of Foo and Bar that returns Baz

unknown            # Unknown type
None               # type(None)
string             # Py2: str | unicode, Py3: str
bytestring         # Py2: str | unicode, Py3: bytes
bytes              # Py2: str, Py3: bytes
unicode            # Py2: unicode, Py3: str

By the way: there is also section mentioning Type Hinting, in the PyCharm documentation.


问:
SI To DI copy error for reverse
Suppose We have number 321 which si points to offset 1
and temp's offset is in di .

```<code>mov di,offset temp
</code>```

Now we want to copy from si to di by this commands :

```<code>mov cx,3
reverse:
 mov dl,byte ptr [si]
 mov byte ptr[di],dl
 inc di
 dec si
loop reverse
mov byte ptr[di],'$'
</code>```

but outputs me 113 not 123 , it means the integer 2 will be removed.

答: Looks okay to me - step through it in a debugger to see where it goes awry.</p>

Title: SI To DI copy error for reverse

Body:
Suppose We have number 321 which si points to offset 1
and temp's offset is in di .

mov di,offset temp

Now we want to copy from si to di by this commands :

mov cx,3
reverse:
 mov dl,byte ptr [si]
 mov byte ptr[di],dl
 inc di
 dec si
loop reverse
mov byte ptr[di],'$'

but outputs me 113 not 123 , it means the integer 2 will be removed.


问:
TypeError: missing 2 required positional arguments: 'number' and 'open_number'
I'm writing a little program that tweets numbers starting from zero and then adds 1, writes it to a text document and then tweets it again with the new written value. Here is my current code I have:

```<code>def tweet(number, open_number):
    print(number)
    threading.Timer(20.0, tweet).start()
    while int(number) >= 0:
        api.update_status(number)
        number = number + 1
        number_str = str(number)
        open_number.truncate()
        open_number.write(number_str)
        break
    print(number)
def main():
    open_number = open("number.txt", "r+")
    print(open_number)
    number = int(open_number.read())
    tweet(number, open_number)
main()
</code>```

Im taking in the number.txt file which has my starting number, in my case it is 0. I then create a number variable that reads the text document and turns it into an integer as seen in my main function:

```<code>    def main():
    open_number = open("number.txt", "r+")
    print(open_number)
    number = int(open_number.read())
    tweet(number, open_number)
main()
</code>```

from there I call my tweet function that has a timer every time it breads and restarts after 20 seconds. After it makes the first tweet of "0" it then waits 20 seconds and when it tries to make the second tweet I get the following error:

```<code>TypeError: tweet() missing 2 required positional arguments: 'number' and 'open_number'
</code>```

another issue Im running into is when it writes the new number It ends up just appending it after the zero e.g.

first run:

```<code>0
</code>```

second run:

```<code>01
</code>```

rather than just overwriting the entire .txt file.

Not sure how to fix these two issues, any help is appreciated! :)

答:
You are not passing the required parameters to the tweet function which is required. You need to start thread with the below line of code. Also, you should start the thread after executing the while loop, otherwise the code inside while loop will not be executed.</p>

```<code>threading.Timer(2, hello, (number,open_number)).start()
</code>```

Body:
I'm writing a little program that tweets numbers starting from zero and then adds 1, writes it to a text document and then tweets it again with the new written value. Here is my current code I have:

def tweet(number, open_number):
    print(number)
    threading.Timer(20.0, tweet).start()
    while int(number) >= 0:
        api.update_status(number)
        number = number + 1
        number_str = str(number)
        open_number.truncate()
        open_number.write(number_str)
        break
    print(number)
def main():
    open_number = open("number.txt", "r+")
    print(open_number)
    number = int(open_number.read())
    tweet(number, open_number)
main()

Im taking in the number.txt file which has my starting number, in my case it is 0. I then create a number variable that reads the text document and turns it into an integer as seen in my main function:

    def main():
    open_number = open("number.txt", "r+")
    print(open_number)
    number = int(open_number.read())
    tweet(number, open_number)
main()

from there I call my tweet function that has a timer every time it breads and restarts after 20 seconds. After it makes the first tweet of "0" it then waits 20 seconds and when it tries to make the second tweet I get the following error:

TypeError: tweet() missing 2 required positional arguments: 'number' and 'open_number'

another issue Im running into is when it writes the new number It ends up just appending it after the zero e.g.

first run:

0

second run:

01

rather than just overwriting the entire .txt file.

Not sure how to fix these two issues, any help is appreciated! :)

Body:
You are not passing the required parameters to the tweet function which is required. You need to start thread with the below line of code. Also, you should start the thread after executing the while loop, otherwise the code inside while loop will not be executed.

threading.Timer(2, hello, (number,open_number)).start()