问:
Unity Hololens Crashes
I am coding an application that uses the camera using Unity and the Hololens. It works ok. Then I changed something (explained later) and I got the following errors after a crash:

d3d11: failed to create staging 2D texture w=896 h=504 d3dfmt=87 [887a0005]

d3d11: failed to lock buffer 1104C69C of size 4194304 [0x8007000E].

DrawBuffers() got a range of indices but no index buffer   (Filename:
  C:\buildslave\unity\build\Runtime/GfxDevice/d3d11/DrawBuffersD3D11.cpp
  Line: 137)

I have searched for these errors and there are no solutions applicable. I hope I could get some insights on this.

What I was doing and what I changed

Basically the program acquired a frame from the camera in a array of bytes byte[] _latestImage;

Originally this image is applied to a Texture as in

```<code>_videoTexture.LoadRawTextureData(_latestImage);
_videoTexture.wrapMode = TextureWrapMode.Clamp;
_videoTexture.Apply();
_videoPanelUIRenderer.sharedMaterial.SetTexture("_MainTex", _videoTexture);
</code>```

where _videoTexture is a Texture2D and _videoPanelUIRenderer is a Renderer.

This works right. Then I processed the array _latestImage to convert it to Grey inside a function ProcessSync. This also works right with the only problem: Since the array is being processed (into Grey) but also is being updated automatically by the camera, when applying into a texture, it flickers, sometimes grey, and sometimes in color. But other than that, no crash.

So my next step was to Clone that array at the start of the processing function so that I can process this new array and apply it to a texture without the interference of new data coming from the camera.

so I did:

```<code> void ProcessSync(byte[] rawimage, Matrix4x4 cTwMatrix, Matrix4x4 pMatrix)
    {
        int rr, gg, bb;
        int p = 0;
        int yval;
        byte[] image=(byte[])rawimage.Clone();//<--THIS is the only change

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
              { //...some processing here
               }

       //Then apply it to the texture like indicated above
}
</code>```

When I apply this, the application works fine, and I can see that I am getting the grey image...but after some time it crashes with the message above.

My image is 896x504 so I guess

d3d11: failed to create staging 2D texture w=896 h=504 d3dfmt=87
  [887a0005]

means that somehow the Texture2D failed to be created but why? My texture is only created once when the video mode is being initialized so I don't understand why this happens.

I guess the error could be related with me cloning the image. Can anyone help me here?

答:
As @Equalsk mentioned in comment, there might be chances that the original array is being reused (considering that Array is a reference type). One thing you can do is to create a copy of array before passing in the ProcessSync() leaving no chance of the original pointer being used in the method.

One more thing I would suggest : Method should have single responsibility (return the processed array). The resulting byte[] should be then applied to texture.

```<code>byte[] ProcessSync(byte[] image, Matrix4x4 cTwMatrix, Matrix4x4 pMatrix)
{
    int rr, gg, bb;
    int p = 0;
    int yval;

    for (int y = 0; y < height; y++)
        for (int x = 0; x < width; x++)
          { //...some processing here
           }
    return image;
}
</code>```

Then use it as following:

```<code>var image = ProcessSync(_latestImage.ToArray(),_cTwCatrix, _pMatrix);

_videoTexture.LoadRawTextureData(image);
_videoTexture.wrapMode = TextureWrapMode.Clamp;
_videoTexture.Apply();
_videoPanelUIRenderer.sharedMaterial.SetTexture("_MainTex", _videoTexture);
</code>```

NOTE: ToArray() is extension from System.Linq which creates a copy. You can use other ways to copy the array if you prefer.

Hope this helps :)

Title: Unity Hololens Crashes

Body:
I am coding an application that uses the camera using Unity and the Hololens. It works ok. Then I changed something (explained later) and I got the following errors after a crash:

d3d11: failed to create staging 2D texture w=896 h=504 d3dfmt=87 [887a0005]

d3d11: failed to lock buffer 1104C69C of size 4194304 [0x8007000E].

DrawBuffers() got a range of indices but no index buffer   (Filename:
  C:\buildslave\unity\build\Runtime/GfxDevice/d3d11/DrawBuffersD3D11.cpp
  Line: 137)

I have searched for these errors and there are no solutions applicable. I hope I could get some insights on this.

What I was doing and what I changed

Basically the program acquired a frame from the camera in a array of bytes byte[] _latestImage;

Originally this image is applied to a Texture as in

_videoTexture.LoadRawTextureData(_latestImage);
_videoTexture.wrapMode = TextureWrapMode.Clamp;
_videoTexture.Apply();
_videoPanelUIRenderer.sharedMaterial.SetTexture("_MainTex", _videoTexture);

where _videoTexture is a Texture2D and _videoPanelUIRenderer is a Renderer.

This works right. Then I processed the array _latestImage to convert it to Grey inside a function ProcessSync. This also works right with the only problem: Since the array is being processed (into Grey) but also is being updated automatically by the camera, when applying into a texture, it flickers, sometimes grey, and sometimes in color. But other than that, no crash.

So my next step was to Clone that array at the start of the processing function so that I can process this new array and apply it to a texture without the interference of new data coming from the camera.

so I did:

 void ProcessSync(byte[] rawimage, Matrix4x4 cTwMatrix, Matrix4x4 pMatrix)
    {
        int rr, gg, bb;
        int p = 0;
        int yval;
        byte[] image=(byte[])rawimage.Clone();//<--THIS is the only change

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++)
              { //...some processing here
               }

       //Then apply it to the texture like indicated above
}

When I apply this, the application works fine, and I can see that I am getting the grey image...but after some time it crashes with the message above.

My image is 896x504 so I guess

d3d11: failed to create staging 2D texture w=896 h=504 d3dfmt=87
  [887a0005]

means that somehow the Texture2D failed to be created but why? My texture is only created once when the video mode is being initialized so I don't understand why this happens.

I guess the error could be related with me cloning the image. Can anyone help me here?

Body:
As @Equalsk mentioned in comment, there might be chances that the original array is being reused (considering that Array is a reference type). One thing you can do is to create a copy of array before passing in the ProcessSync() leaving no chance of the original pointer being used in the method.

One more thing I would suggest : Method should have single responsibility (return the processed array). The resulting byte[] should be then applied to texture.

byte[] ProcessSync(byte[] image, Matrix4x4 cTwMatrix, Matrix4x4 pMatrix)
{
    int rr, gg, bb;
    int p = 0;
    int yval;

    for (int y = 0; y < height; y++)
        for (int x = 0; x < width; x++)
          { //...some processing here
           }
    return image;
}

Then use it as following:

var image = ProcessSync(_latestImage.ToArray(),_cTwCatrix, _pMatrix);

_videoTexture.LoadRawTextureData(image);
_videoTexture.wrapMode = TextureWrapMode.Clamp;
_videoTexture.Apply();
_videoPanelUIRenderer.sharedMaterial.SetTexture("_MainTex", _videoTexture);

NOTE: ToArray() is extension from System.Linq which creates a copy. You can use other ways to copy the array if you prefer.

Hope this helps :)


来源: stackexchange

问:
how to make a get-form in flask
I have a form which is like

```<code><form action="{{ url_for('my_form')}}" method="get">

            <h2><td><input type="hidden" name="user_name" value="{{ user_name }}">{{ user_name }}</td></h2><br>

             <button type="submit" class="btn btn-primary btn-lg" value="Submit">Submit</button>
          </form>
</code>```

And then on flask backend

```<code>@app.route('/my_form', methods=['GET'])
def my_form():
    print request.form.items()
    user_name = request.form['user_name']
    print "exclusive request"
    print "got user name ", user_name
</code>```

But this doesnt work as the submit query becomes
http://local_host/my_form?user_name=foobar  <--- 400 error

which makes sense.. as the query url is my_form
So, the question is how to make a get form in flask?

答:
You are try to access to POST request parameter but your route accept only GET request. To resolve this just add POST in the method argument of your route decorator.</p>

```<code>@app.route('/my_form', methods=['GET', 'POST'])
def my_form():
    print request.args.items()
    user_name = request.form.get('user_name')
    print "exclusive request"
    print "got user name ", user_name
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to make a get-form in flask

Body:
I have a form which is like

<form action="{{ url_for('my_form')}}" method="get">

<input type="hidden" name="user_name" value="{{ user_name }}">{{ user_name }}

             <button type="submit" class="btn btn-primary btn-lg" value="Submit">Submit</button>
          </form>

And then on flask backend

@app.route('/my_form', methods=['GET'])
def my_form():
    print request.form.items()
    user_name = request.form['user_name']
    print "exclusive request"
    print "got user name ", user_name

But this doesnt work as the submit query becomes
http://local_host/my_form?user_name=foobar  <--- 400 error

which makes sense.. as the query url is my_form
So, the question is how to make a get form in flask?

Body:
You are try to access to POST request parameter but your route accept only GET request. To resolve this just add POST in the method argument of your route decorator.

@app.route('/my_form', methods=['GET', 'POST'])
def my_form():
    print request.args.items()
    user_name = request.form.get('user_name')
    print "exclusive request"
    print "got user name ", user_name


问:
Select a randomly number of items from a list and add them to another list (Swift)
I have a list in my VC

```<code>var list : [QCategoryy] = [QCategoryy]()

list = NearbyPlaces.getCategories()
list.shuffled()
</code>```

where getCategories() is the func

```<code>static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }
</code>```

what i would like to do is to take a randomly number of items from this list and add them to another list like var filteredList = [QCategoryy](), how can i do?

UPDATE

i would like to do it when the user tap a button

答:
Try this. It will filter the list and each item has 50% chance to be filtered. </p>

```<code>var filteredList = list.filter { _ in
    arc4random() % 2 == 0
}
</code>```

<p>And for shuffling see this answer. </p>

Body:
I have a list in my VC

var list : [QCategoryy] = [QCategoryy]()

list = NearbyPlaces.getCategories()
list.shuffled()

where getCategories() is the func

static func getCategories() -> [QCategoryy] {
        let list:[QCategoryy] = [QCategoryy(name: "bar", image: UIImage(named: "bar_button.png")!), QCategoryy(name :"night_club", image: UIImage(named: "nightclub_button.png")!), QCategoryy(name: "movie_theater", image: UIImage(named: "cinema_button.png")!), QCategoryy(name: "restaurant", image: UIImage(named: "restaurant_button.png")!), QCategoryy(name: "gym", image: UIImage(named: "gym_button.png")!), QCategoryy(name: "spa", image: UIImage(named: "spa_button.png")!), QCategoryy(name: "museum", image: UIImage(named: "museum_button.png")!)]
        return list
    }

what i would like to do is to take a randomly number of items from this list and add them to another list like var filteredList = [QCategoryy](), how can i do?

UPDATE

i would like to do it when the user tap a button

Body:
Try this. It will filter the list and each item has 50% chance to be filtered.

var filteredList = list.filter { _ in
    arc4random() % 2 == 0
}

And for shuffling see this answer.


问:
Figuring out the proper numpy.reshape for -1 option
I have a (hopefully) quick Numpy question, and I hope you can help me.
I want to use numpy.reshape to convert (5000, 32, 32, 3) into (5000, 3072), and the only clue I got for the assignment is this:

```<code># Reshape each image data into a 1-dim array
print (X_train.shape, X_test.shape) # Should be: (5000, 32, 32, 3) (500, 32, 32, 3)
#####################################################################
# TODO (2):                                                         #
# Reshape the image data to one dimension.                          #
#                                                                   #
# Hint: Look at the numpy reshape function and have a look at -1    #
#       option                                                      #
#####################################################################
X_train =
X_test =
#####################################################################
#                       END OF YOUR CODE                            #
#####################################################################
print (X_train.shape, X_test.shape) # Should be: (5000, 3072) (500, 3072)
</code>```

I've been spending the last day scouring Google for examples, but apparently this is too trivial to warrant an ask. Help?

答:
You can simply do:

```<code>X_train = np.reshape(X_train, (5000, -1))
X_test = np.reshape(X_test, (500, -1))
</code>```

Working example:

```<code>import numpy as np
a = np.zeros((5000,32,32,3))
b = np.reshape(a, (5000, -1))

print(a.shape)
print(b.shape)

# Output
# (5000, 32, 32, 3)
# (5000, 3072)
</code>```

numpy.reshape will try to fit the source array a into an array with first dimension of length 5000. The -1 tells reshape to adjust the length of the second dimension depending on the total length of the source array a.

Body:
I have a (hopefully) quick Numpy question, and I hope you can help me.
I want to use numpy.reshape to convert (5000, 32, 32, 3) into (5000, 3072), and the only clue I got for the assignment is this:

# Reshape each image data into a 1-dim array
print (X_train.shape, X_test.shape) # Should be: (5000, 32, 32, 3) (500, 32, 32, 3)
#####################################################################
# TODO (2):                                                         #
# Reshape the image data to one dimension.                          #
#                                                                   #
# Hint: Look at the numpy reshape function and have a look at -1    #
#       option                                                      #
#####################################################################
X_train =
X_test =
#####################################################################
#                       END OF YOUR CODE                            #
#####################################################################
print (X_train.shape, X_test.shape) # Should be: (5000, 3072) (500, 3072)

I've been spending the last day scouring Google for examples, but apparently this is too trivial to warrant an ask. Help?

Body:
You can simply do:

X_train = np.reshape(X_train, (5000, -1))
X_test = np.reshape(X_test, (500, -1))

Working example:

import numpy as np
a = np.zeros((5000,32,32,3))
b = np.reshape(a, (5000, -1))

print(a.shape)
print(b.shape)

# Output
# (5000, 32, 32, 3)
# (5000, 3072)

numpy.reshape will try to fit the source array a into an array with first dimension of length 5000. The -1 tells reshape to adjust the length of the second dimension depending on the total length of the source array a.


问:
How to create a branch using Bitbucket REST API
How can I create a new branch in Bitbucket repository using REST API?

I'm using Postman client.

答:
I will show you how to create a branch in Bitbucket using postman and programmatically.

Using Postman

Select method type as POST

Add url: https://example.com/git/rest/api/1.0/projects/{projectKey}/repos/{repoName}/branches

Add Authorization to Basic Auth.

```<code>Username and password.
</code>```

Select Body as raw

Select JSON(application/json)

add this to the body as JSON

```<code>{
    "name": "feature/my-feature-branch",
    "startPoint": "refs/heads/master"
}
</code>```

Click on Send

Now Same programmatically

```<code>String authToken = "xyzxyzabcabcabcxyzxyzabcabcabcxyzxyzabcabcabc";

 public boolean createBranchProgrammatically(String projectKey, String repoName, String branchPrefix,String branchName,
            String headStart) {
        Map branches = new HashMap();
        JSONObject json = new JSONObject();
            try {
                String branch = branchPrefix + "/" + branchName;
                json.put("name", branch);
                json.put("startPoint", headStart);
                branches = restTemplate.exchange(myBitbuketUrl + "git/rest/api/1.0/projects/"
                        + projectKey + "repos" + repoName + "/branches",
                        HttpMethod.POST, postRequestEntityForBitbuket(json.toString()), Map.class).getBody();

                break;
            } catch (RestClientException e) {
                logger.error("Branches could not be created from bitbucket for "  , e);

                return false;
            }

            }
        return true;
    }

public HttpEntity<String> postRequestEntityForBitbuket(String jsonAsString) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + authToken);
        headers.add("content-type", "application/json");

        return new HttpEntity<String>(jsonAsString, headers) ;
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I will show you how to create a branch in Bitbucket using postman and programmatically.

Using Postman

Select method type as POST

Add url: https://example.com/git/rest/api/1.0/projects/{projectKey}/repos/{repoName}/branches

Add Authorization to Basic Auth.

Username and password.

Select Body as raw

Select JSON(application/json)

add this to the body as JSON

{
    "name": "feature/my-feature-branch",
    "startPoint": "refs/heads/master"
}

Click on Send

Now Same programmatically

String authToken = "xyzxyzabcabcabcxyzxyzabcabcabcxyzxyzabcabcabc";

 public boolean createBranchProgrammatically(String projectKey, String repoName, String branchPrefix,String branchName,
            String headStart) {
        Map branches = new HashMap();
        JSONObject json = new JSONObject();
            try {
                String branch = branchPrefix + "/" + branchName;
                json.put("name", branch);
                json.put("startPoint", headStart);
                branches = restTemplate.exchange(myBitbuketUrl + "git/rest/api/1.0/projects/"
                        + projectKey + "repos" + repoName + "/branches",
                        HttpMethod.POST, postRequestEntityForBitbuket(json.toString()), Map.class).getBody();

                break;
            } catch (RestClientException e) {
                logger.error("Branches could not be created from bitbucket for "  , e);

                return false;
            }

            }
        return true;
    }

public HttpEntity<String> postRequestEntityForBitbuket(String jsonAsString) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Basic " + authToken);
        headers.add("content-type", "application/json");

        return new HttpEntity<String>(jsonAsString, headers) ;
    }


问:
Sending cookies with websockets using Tornado
I'm currently connecting to websockets using tornado, is there a way I can pass along a cookie with the websocket connection?

```<code>import logging

import tornado.httpclient
import tornado.gen
import tornado.options
import tornado.web
import tornado.websocket

@tornado.gen.coroutine
def connect_websocket():

    url = tornado.options.options.ws_host

    try:
        ws_connection = yield tornado.websocket.websocket_connect(url, connect_timeout=5)
        logging.info("Connection established (%s), waiting for output...", url)
    except Exception as conn_err:
        logging.error("Error connecting to %s", conn_err)
        return

    while True:
        output = yield ws_connection.read_message()
        logging.info(output)

if __name__ == '__main__':
    tornado.options.define(name="ws_host", type=str, help="Websocket host address.")
    tornado.options.parse_command_line()

    tornado.ioloop.IOLoop.instance().run_sync(connect_websocket)
</code>```

Thanks!

答:
The url parameter in websocket_connect(url) can be a plain URL string but it can also be a tornado.httpclient.HTTPRequest object. Although, it's not documented but you can see this in the source code.

So, you can create an instance of HTTPRequest and set the Cookie header there, after all, cookie is just a header.

Example:

```<code>from tornado import httpclient

# create an instace of HTTPRequest with the given url
request = httpclient.HTTPRequest(url, headers={'Cookie': 'name=value'})

# connect to ws using the request object
ws_connection = yield tornado.websocket.websocket_connect(request)
</code>```

Body:
I'm currently connecting to websockets using tornado, is there a way I can pass along a cookie with the websocket connection?

import logging

import tornado.httpclient
import tornado.gen
import tornado.options
import tornado.web
import tornado.websocket

@tornado.gen.coroutine
def connect_websocket():

    url = tornado.options.options.ws_host

    try:
        ws_connection = yield tornado.websocket.websocket_connect(url, connect_timeout=5)
        logging.info("Connection established (%s), waiting for output...", url)
    except Exception as conn_err:
        logging.error("Error connecting to %s", conn_err)
        return

    while True:
        output = yield ws_connection.read_message()
        logging.info(output)

if __name__ == '__main__':
    tornado.options.define(name="ws_host", type=str, help="Websocket host address.")
    tornado.options.parse_command_line()

    tornado.ioloop.IOLoop.instance().run_sync(connect_websocket)

Thanks!

Body:
The url parameter in websocket_connect(url) can be a plain URL string but it can also be a tornado.httpclient.HTTPRequest object. Although, it's not documented but you can see this in the source code.

So, you can create an instance of HTTPRequest and set the Cookie header there, after all, cookie is just a header.

Example:

from tornado import httpclient

# create an instace of HTTPRequest with the given url
request = httpclient.HTTPRequest(url, headers={'Cookie': 'name=value'})

# connect to ws using the request object
ws_connection = yield tornado.websocket.websocket_connect(request)


问:
Synchronize WPF ColorAnimation across several controls
I have several toggle-like buttons that I want to pulsate in unison when in the pressed state.

I have defined a style with a trigger that kicks-off the glow animation and this works just fine, apart from the fact that each button pulsates asynchronously from the others.

How can I have each button synchronize its pulse to the others?

Here's the style:

```<code><Storyboard x:Key="pulseStory">
    <ColorAnimation
        Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
                    From="Red"
                    To="Transparent"
                    Duration="0:0:1" />
</Storyboard>

<Style x:Key="pulseButton" TargetType="Button">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Tag,RelativeSource={RelativeSource Self}}" Value="True">
            <DataTrigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource pulseStory}"/>
            </DataTrigger.EnterActions>
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

Cheers!

答:
Actually you should be doing this via a resource, at least using a hidden control is a bit too much of a hack for me personally.

What needs to be met for it to work:

The property you bind to needs to be a DependencyProperty, hence your enveloping object needs to be a DependencyObject.

You have to reference the object as a static resource (as opposed to a dynamic resource) like this:

```<code><DoubleAnimation
    Storyboard.Target="{StaticResource AnimationValue}"
    Storyboard.TargetProperty="(local:WrappedValue.Value)"
    To="0" Duration="0:0:1"/>
</code>```

Well, admittedly it's a bit hacky as well to have a Wrapper-class for this but it's cleaner than a full control (if you want to use controls you can utilize some unused Tag-property, e.g. of the container that hosts all your controls)

ContentLicense: CC BY-SA 2.5

Body:
I have several toggle-like buttons that I want to pulsate in unison when in the pressed state.

I have defined a style with a trigger that kicks-off the glow animation and this works just fine, apart from the fact that each button pulsates asynchronously from the others.

How can I have each button synchronize its pulse to the others?

Here's the style:

<Storyboard x:Key="pulseStory">
    <ColorAnimation
        Storyboard.TargetProperty="(Control.Background).(SolidColorBrush.Color)"
                    From="Red"
                    To="Transparent"
                    Duration="0:0:1" />
</Storyboard>

</Style>

Cheers!

Body:
Actually you should be doing this via a resource, at least using a hidden control is a bit too much of a hack for me personally.

What needs to be met for it to work:

The property you bind to needs to be a DependencyProperty, hence your enveloping object needs to be a DependencyObject.

You have to reference the object as a static resource (as opposed to a dynamic resource) like this:

<DoubleAnimation
    Storyboard.Target="{StaticResource AnimationValue}"
    Storyboard.TargetProperty="(local:WrappedValue.Value)"
    To="0" Duration="0:0:1"/>

Well, admittedly it's a bit hacky as well to have a Wrapper-class for this but it's cleaner than a full control (if you want to use controls you can utilize some unused Tag-property, e.g. of the container that hosts all your controls)


问:
awk print all parts before a match
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

```<code>awk '/[1-2][0-9][0-9][0-9]/{print $1}'
</code>```

but that only prints the first "word" of the input

```<code>"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"
</code>```

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

```<code> awk -F[1-2][0-9][0-9][0-9] '{print $1}
</code>```

EDIT:
This is what I ended up with and then came back to see a solution posted:

```<code>awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'
</code>```

Thanks all

Title: awk print all parts before a match

Body:
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

awk '/[1-2][0-9][0-9][0-9]/{print $1}'

but that only prints the first "word" of the input

"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

 awk -F[1-2][0-9][0-9][0-9] '{print $1}

EDIT:
This is what I ended up with and then came back to see a solution posted:

awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'

Thanks all

Body:
sed -r 's/(.*[1-2][0-9][0-9][0-9]).*/\1"/' input
"Financial summary 1997"
"v4 Minutes 1995"


问:
SQL to SUM numbers WHEN ITEM number is the same
Trying to work on SUM SQL code to SUM SOH for all ITEM_PARENT numbers. SOH is the result I'm looking for and ITEM_PARENT and STOCK_ON_HAND is what I have.

```<code>CASE WHEN ITEM_PARENT = ITEM_PARENT THEN SUM(STOCK_ON_HAND) ELSE 'DN' END AS SOH_SUM,
</code>```

The code I have already done seems to be not working....

```<code>ITEM_PARENT STOCK_ON_HAND   SOH_SUM
123649336         1           11
123649336         1           11
123649336         1           11
123649336         5           11
123649336         2           11
123649336         1           11
123649328         1           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         1           15
123649328         3           15
123649328         3           15
124566152         3           19
124566152         1           19
124566152         3           19
124566152         3           19
124566152         2           19
124566152         7           19
</code>```

Anyone know what I'm missing there?

答:
You can use window functions to get the desired result.

```<code>select
    [ITEM_PARENT]
    ,[STOCK_ON_HAND]
    ,sum([STOCK_ON_HAND]) over(partition by [ITEM_PARENT]) as [ItemTotal]
from tablename
;
</code>```

Otherwise, if you wanted to just get the total stock on hand for each item then group the data:

```<code>select
    [ITEM_PARENT]
    ,sum([STOCK_ON_HAND]) as [TotalStockOnHand]
from tablename
group by
    [ITEM_PARENT]
;
</code>```

Body:
Trying to work on SUM SQL code to SUM SOH for all ITEM_PARENT numbers. SOH is the result I'm looking for and ITEM_PARENT and STOCK_ON_HAND is what I have.

CASE WHEN ITEM_PARENT = ITEM_PARENT THEN SUM(STOCK_ON_HAND) ELSE 'DN' END AS SOH_SUM,

The code I have already done seems to be not working....

ITEM_PARENT STOCK_ON_HAND   SOH_SUM
123649336         1           11
123649336         1           11
123649336         1           11
123649336         5           11
123649336         2           11
123649336         1           11
123649328         1           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         2           15
123649328         1           15
123649328         1           15
123649328         3           15
123649328         3           15
124566152         3           19
124566152         1           19
124566152         3           19
124566152         3           19
124566152         2           19
124566152         7           19

Anyone know what I'm missing there?

Body:
You can use window functions to get the desired result.

select
    [ITEM_PARENT]
    ,[STOCK_ON_HAND]
    ,sum([STOCK_ON_HAND]) over(partition by [ITEM_PARENT]) as [ItemTotal]
from tablename
;

Otherwise, if you wanted to just get the total stock on hand for each item then group the data:

select
    [ITEM_PARENT]
    ,sum([STOCK_ON_HAND]) as [TotalStockOnHand]
from tablename
group by
    [ITEM_PARENT]
;


问:
Why do we need exception handling?
I can check for the input and if it's an invalid input from the user, I can use a simple "if condition" which prints "input invalid, please re-enter" (in case there is an invalid input).

This approach of "if there is a potential for a failure, verify it using an if condition and then specify the right behavior when failure is encountered..." seems enough for me.

If I can basically cover any kind of failure (divide by zero, etc.) with this approach, why do I need this whole exception handling mechanism (exception class and objects, checked and unchecked, etc.)?

答:
Exceptions are a more object-oriented approach to handling exceptional execution flows than return codes. The drawback of return codes is that you have to come up with 'special' values to indicate different types of exceptional results, for example:

```<code>public double calculatePercentage(int a, int b) {
    if (b == 0) {
        return -1;
    }
    else {
        return 100.0 * (a / b);
    }
}
</code>```

The above method uses a return code of -1 to indicate failure (because it cannot divide by zero). This would work, but your calling code needs to know about this convention, for example this could happen:

```<code>public double addPercentages(int a, int b, int c, int d) {
    double percentage1 = calculatePercentage(a, b);
    double percentage2 = calculatePercentage(c, c);
    return percentage1 + percentage2;
}
</code>```

Above code looks fine at first glance. But when b or d are zero the result will be unexpected. calculatePercentage will return -1 and add it to the other percentage which is likely not correct. The programmer who wrote addPercentages is unaware that there is a bug in this code until he tests it, and even then only if he really checks the validity of the results.

With exceptions you could do this:

```<code>public double calculatePercentage(int a, int b) {
    if (b == 0) {
        throw new IllegalArgumentException("Second argument cannot be zero");
    }
    else {
        return 100.0 * (a / b);
    }
}
</code>```

Code calling this method will compile without exception handling, but it will stop when run with incorrect values. This is often the preferred way since it leaves it up to the programmer if and where to handle exceptions.

If you want to force the programmer to handle this exception you should use a checked exception, for example:

```<code>public double calculatePercentage(int a, int b) throws MyCheckedCalculationException {
    if (b == 0) {
        throw new MyCheckedCalculationException("Second argument cannot be zero");
    }
    else {
        return 100.0 * (a / b);
    }
}
</code>```

Notice that calculatePercentage has to declare the exception in its method signature. Checked exceptions have to be declared like that, and the calling code either has to catch them or declare them in their own method signature.

I think many Java developers currently agree that checked exceptions are bit invasive so most API's lately gravitate towards the use of unchecked exceptions.

The checked exception above could be defined like this:

```<code>public class MyCheckedCalculationException extends Exception {

   public MyCalculationException(String message) {
       super(message);
   }
}
</code>```

Creating a custom exception type like that makes sense if you are developing a component with multiple classes and methods which are used by several other components and you want to make your API (including exception handling) very clear.

(see the Throwable class hierarchy)

Title: Why do we need exception handling?

Body:
Exceptions are a more object-oriented approach to handling exceptional execution flows than return codes. The drawback of return codes is that you have to come up with 'special' values to indicate different types of exceptional results, for example:

public double calculatePercentage(int a, int b) {
    if (b == 0) {
        return -1;
    }
    else {
        return 100.0 * (a / b);
    }
}

The above method uses a return code of -1 to indicate failure (because it cannot divide by zero). This would work, but your calling code needs to know about this convention, for example this could happen:

public double addPercentages(int a, int b, int c, int d) {
    double percentage1 = calculatePercentage(a, b);
    double percentage2 = calculatePercentage(c, c);
    return percentage1 + percentage2;
}

Above code looks fine at first glance. But when b or d are zero the result will be unexpected. calculatePercentage will return -1 and add it to the other percentage which is likely not correct. The programmer who wrote addPercentages is unaware that there is a bug in this code until he tests it, and even then only if he really checks the validity of the results.

With exceptions you could do this:

public double calculatePercentage(int a, int b) {
    if (b == 0) {
        throw new IllegalArgumentException("Second argument cannot be zero");
    }
    else {
        return 100.0 * (a / b);
    }
}

Code calling this method will compile without exception handling, but it will stop when run with incorrect values. This is often the preferred way since it leaves it up to the programmer if and where to handle exceptions.

If you want to force the programmer to handle this exception you should use a checked exception, for example:

public double calculatePercentage(int a, int b) throws MyCheckedCalculationException {
    if (b == 0) {
        throw new MyCheckedCalculationException("Second argument cannot be zero");
    }
    else {
        return 100.0 * (a / b);
    }
}

Notice that calculatePercentage has to declare the exception in its method signature. Checked exceptions have to be declared like that, and the calling code either has to catch them or declare them in their own method signature.

I think many Java developers currently agree that checked exceptions are bit invasive so most API's lately gravitate towards the use of unchecked exceptions.

The checked exception above could be defined like this:

public class MyCheckedCalculationException extends Exception {

   public MyCalculationException(String message) {
       super(message);
   }
}

Creating a custom exception type like that makes sense if you are developing a component with multiple classes and methods which are used by several other components and you want to make your API (including exception handling) very clear.

(see the Throwable class hierarchy)


问:
Python 2.7.14 ,code not working
I'm getting error ,expected an indented block.</p>

```<code> n = input("enter any number")
 for i in range(1,n+1):
 print i,
</code>```

答:
Try this,

```<code>n = int(input("enter any number"))
for i in range(1,n+1):
    print i,
</code>```

Use Indentation.

Title: Python 2.7.14 ,code not working

Body:
I'm getting error ,expected an indented block.

 n = input("enter any number")
 for i in range(1,n+1):
 print i,

Body:
Try this,

n = int(input("enter any number"))
for i in range(1,n+1):
    print i,

Use Indentation.


问:
About different python versions installation
Is it possible to install 3 different python versions on windows 10 simultaneously? I'm using 2.7 for Udacity course, 3.6 for my college project and now I need to install Python 3.5 for "Tensorflow" package. Is it possible to have? Or is there any way to install tensorflow on python 3.6? Any suggestions will be appreciated.</p>

答:
Everyone prefers different ways of using different Python versions. So what I prefer the most is to define different variables for your different Python versions and add/remove the variables in the System variable PATH to use a different Python Version.

So for example:
If you are using anaconda for Python 3, you may make a variable conda3 and add the following in it:

C:\Anaconda3;C:\Anaconda3\Library\mingw-w64\bin;C:\Anaconda3\Library\usr\bin;C:\Anaconda3\Library\bin;C:\Anaconda3\Scripts;

So of course, the values Change depending on where you have installed python.

In a similiar way you can add Python2 and depending on which Version you want to use, you May add(taking the above example as the basis) %Anaconda3% to your System variable PATH.

Note:
Even if you are adding different python variables in the System variable PATH, the System stops searching another python Version as soon as it finds the first one.

If you are using anaconda for python 3.6, I see no Problem in installing tensorflow for python 3.6 - so you can simply do:
conda install tensorflow
and that should work


问:
Slow insert and update commands during mysql to redshift replication
I am trying to make a replication server from MySQL to redshift, for this, I am parsing the MySQL binlog. For initial replication, I am taking the dump of the mysql table, converting it into a CSV file and uploading the same to S3 and then I use the redshift copy command. For this the performance is efficient.

After the initial replication, for the continuous sync when I am reading the binlog the inserts and updates have to be run sequentially which are very slow.

Is there anything that can be done for increasing the performance?

One possible solution that I can think of is to wrap the statements in a transaction and then send the transaction at once, to avoid multiple network calls. But that would not address the problem that single update and insert statements in redshift run very slow. A single update statement is taking 6s. Knowing the limitations of redshift (That it is a columnar database and single row insertion will be slow) what can be done to work around those limitations?

Edit 1:
Regarding DMS: I want to use redshift as a warehousing solution which just replicates our MYSQL continuously, I don't want to denormalise the data since I have 170+ tables in mysql. During ongoing replication, DMS shows many errors multiple times in a day and fails completely after a day or two and it's very hard to decipher DMS error logs. Also, When I drop and reload tables, it deletes the existing tables on redshift and creates and new table and then starts inserting data which causes downtime in my case. What I wanted was to create a new table and then switch the old one with new one and delete old table

答:
Here is what you need to do to get DMS to work

1) create and run a dms task with "migrate and ongoing replication" and "Drop tables on target"

2) this will probably fail, do not worry. "stop" the dms task.

3) on redshift make the following changes to the table

Change all dates and timestamps to varchar (because the options used
by dms for redshift copy cannot cope with '00:00:00 00:00' dates that
you get in mysql)

change all bool to be varchar - due to a bug in dms.

4) on dms - modify the task to "Truncate" in "Target table preparation mode"

5) restart the dms task - full reload

now - the initial copy and ongoing binlog replication should work.

Make sure you are on latest replication instance software version

Make sure you have followed the instructions here exactly

http://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.MySQL.html

If your source is aurora, also make sure you have set binlog_checksum to "none" (bad documentation)


问:
what happened when using the same variable in two layer loops in python?
I test the following code:

```<code>for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)
</code>```

and the output is:

```<code>inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
</code>```

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the  the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

Anyone can explain this? It's a little confusing to me now.

答:
Check @heltonbiker answer :

```<code>>>> for i in range(3):
    print "1-",locals()
    for i in range(3,5):
        print "2-",locals()

1- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 0, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 3, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 4, '__name__': '__main__', '__doc__': None}
1- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 1, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 3, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 4, '__name__': '__main__', '__doc__': None}
1- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 2, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 3, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 4, '__name__': '__main__', '__doc__': None}
>>>
</code>```

You read i data on wrong time (place)!

If there is a single BUS or Variable name You must use the FIFO method.

FIFO  << Here information

Body:
I test the following code:

for i in range(3):
    for i in range(3,5):
        print "inner i: %d"%(i)
    print "outer i: %d"%(i)

and the output is:

inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4
inner i: 3
inner i: 4
outer i: 4

I don't understand why in the outer loop the i is 4 but the outer loop still runs for 3 times. It seems that the  the variable i in the print "outer i: %d"%(i) line is the i in the inner loop , but when goes to the for i in range(3) it uses the i in the outer loop.

Anyone can explain this? It's a little confusing to me now.

Body:
Check @heltonbiker answer :

>>> for i in range(3):
    print "1-",locals()
    for i in range(3,5):
        print "2-",locals()

1- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 0, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 3, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 4, '__name__': '__main__', '__doc__': None}
1- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 1, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 3, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 4, '__name__': '__main__', '__doc__': None}
1- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 2, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 3, '__name__': '__main__', '__doc__': None}
2- {'__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'i': 4, '__name__': '__main__', '__doc__': None}
>>>

You read i data on wrong time (place)!

If there is a single BUS or Variable name You must use the FIFO method.

FIFO  << Here information


问:
Segmentation fault(core dumped) on OpenMP loop
I have an algorithm that looks for a string inside another string, and with some very long strings I got:

Segmentation fault (core dumped)

An that is my code where:
S is the string that is looked for, and B is the big string that maybe contains the S string

```<code>int search( char *S, int sizeS, char *B, int sizeB )
{
    int result = -1;

    #pragma omp parallel shared(result)
    {
        int startB, thread, threads, length;

        threads = omp_get_num_threads();
        thread = omp_get_thread_num();

        length = sizeB / threads;

        for(startB = length * thread; result==-1 && startB <= startB+length; startB++ ) {
            int ind;

            for( ind = 0; ind < sizeS; ind++ ) {
                if ( S[ind] != B[startB+ind] )  break;
            }

            if ( ind == sizeS && result == -1)
                result = startB;
        }
    }
    return result;
}
</code>```

答:
I found two typos in your code:

Wrong for loop condition (which cause the crash):

```<code>for(startB = length * thread; result==-1 && startB <= startB ; startB++ )
</code>```

Should be:

```<code>for(startB = length * thread; result==-1 && startB <= sizeB ; startB++ )
</code>```

Then, the ind test seems wrong (which prevent to find the substring):

```<code>if ( ind == sizeS && result == -1)
    result = startB;
</code>```

Should be

```<code>if ( ind == (sizeS - 1) && result == -1)
    result = startB;
</code>```

Body:
I have an algorithm that looks for a string inside another string, and with some very long strings I got:

Segmentation fault (core dumped)

An that is my code where:
S is the string that is looked for, and B is the big string that maybe contains the S string

int search( char *S, int sizeS, char *B, int sizeB )
{
    int result = -1;

    #pragma omp parallel shared(result)
    {
        int startB, thread, threads, length;

        threads = omp_get_num_threads();
        thread = omp_get_thread_num();

        length = sizeB / threads;

        for(startB = length * thread; result==-1 && startB <= startB+length; startB++ ) {
            int ind;

            for( ind = 0; ind < sizeS; ind++ ) {
                if ( S[ind] != B[startB+ind] )  break;
            }

            if ( ind == sizeS && result == -1)
                result = startB;
        }
    }
    return result;
}

Body:
I found two typos in your code:

Wrong for loop condition (which cause the crash):

for(startB = length * thread; result==-1 && startB <= startB ; startB++ )

Should be:

for(startB = length * thread; result==-1 && startB <= sizeB ; startB++ )

Then, the ind test seems wrong (which prevent to find the substring):

if ( ind == sizeS && result == -1)
    result = startB;

Should be

if ( ind == (sizeS - 1) && result == -1)
    result = startB;


问:
How to submit from page to redirect from.php page with 60sec waiting progress bar in wordpress

How to submit from page to redirect from.php page with 60sec waiting progress bar in wordpress

答:
you can manage the progress bar manually on your form.php file.

I have shared the link. Please follow the steps, Displaying Progress Bar On Form Submission Using jQuery


问:
How to animate a spinning Triangle that changes colors (randomly) as it spins
So I wanted to create and animation of a equilateral triangle that was fixed to a center and that had its three vertices on a circle and as it spun is continuously changed colors in a random pattern.

So far I have:

```<code>Animate[Graphics[{Hue[RandomReal[]],
   Triangle[{{-1/2 - Cos[i], 0 - 1/2 Tan[i]}, {1/2 - Cos[i],
      0 - 1/2 Tan[i]}, {0 - Cos[i], 3^(1/2)/2 - 1/2 Tan[i]}}]}], {i,
  0, 2*Pi}]
</code>```

Output currently (Triangle does everything except spin)

Output I'm hoping for:

Spinning Triangle

I was hoping to know what I have done incorrect and how would I fix my code to work correctly.

答:
Good solving are processing.org
You can create animation, easy to put on web.</p>

Body:
So I wanted to create and animation of a equilateral triangle that was fixed to a center and that had its three vertices on a circle and as it spun is continuously changed colors in a random pattern.

So far I have:

Animate[Graphics[{Hue[RandomReal[]],
   Triangle[{{-1/2 - Cos[i], 0 - 1/2 Tan[i]}, {1/2 - Cos[i],
      0 - 1/2 Tan[i]}, {0 - Cos[i], 3^(1/2)/2 - 1/2 Tan[i]}}]}], {i,
  0, 2*Pi}]

Output currently (Triangle does everything except spin)

Output I'm hoping for:

Spinning Triangle

I was hoping to know what I have done incorrect and how would I fix my code to work correctly.


问:
Comparing a column's value with an array (or a series) of decreasing size
I have the following dataframe. (This isn't necessarily a dataframe; a solution on the numpy array df.values would also be sufficient)

```<code>np.random.seed(42)
df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b'])
df

        a           b
0   0.374540    0.950714
1   0.731994    0.598658
2   0.156019    0.155995
3   0.058084    0.866176
4   0.601115    0.708073
5   0.020584    0.969910
6   0.832443    0.212339
7   0.181825    0.183405
8   0.304242    0.524756
9   0.431945    0.291229
</code>```

I want to include a new column that has the value as per the below logic:

True : If any of the b values after a particular a value is greater than that partiulcar a value
False : Otherwise

The expected output would be:
(See the explanation for some of the rows below)

```<code>       a           b      c
0   0.374540    0.950714  True
1   0.731994    0.598658  True
2   0.156019    0.155995  True
3   0.058084    0.866176  True   <- np.any(0.058084 < np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
4   0.601115    0.708073  True   <- np.any(0.601115 < np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
5   0.020584    0.969910  True   <- np.any(0.020584 < np.array([0.212339, 0.183405, 0.524756, 0.291229]))
6   0.832443    0.212339  False  <- np.any(0.832443 < np.array([0.183405, 0.524756, 0.291229]))
7   0.181825    0.183405  True   <- np.any(0.181825 < np.array([0.524756, 0.291229]))
8   0.304242    0.524756  False  <- np.any(0.304242  < np.array([0.291229]))
9   0.431945    0.291229  UNDEFINED <- Ignore this
</code>```

The above should be possible with a for loop but what is the pandas/numpy way to do that?

I was trying for an approach where I apply a lambda function to a but l couldn't find a way to get the index of the respective a value to do the np.any comparison as shown above. (I have later discovered that apply is just syntactic sugar for a for loop, though)

```<code>df['c'] = df['a'].apply(lambda x: np.any(x < df['b'].values[<i>:])) # Where <i> is the respective index value of x; which I didn't know how to find
</code>```

Body:
I have the following dataframe. (This isn't necessarily a dataframe; a solution on the numpy array df.values would also be sufficient)

np.random.seed(42)
df = pd.DataFrame(np.random.random((10,2)),columns=['a', 'b'])
df

        a           b
0   0.374540    0.950714
1   0.731994    0.598658
2   0.156019    0.155995
3   0.058084    0.866176
4   0.601115    0.708073
5   0.020584    0.969910
6   0.832443    0.212339
7   0.181825    0.183405
8   0.304242    0.524756
9   0.431945    0.291229

I want to include a new column that has the value as per the below logic:

True : If any of the b values after a particular a value is greater than that partiulcar a value
False : Otherwise

The expected output would be:
(See the explanation for some of the rows below)

       a           b      c
0   0.374540    0.950714  True
1   0.731994    0.598658  True
2   0.156019    0.155995  True
3   0.058084    0.866176  True   <- np.any(0.058084 < np.array([0.708073, 0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
4   0.601115    0.708073  True   <- np.any(0.601115 < np.array([0.969910, 0.212339, 0.183405, 0.524756, 0.291229]))
5   0.020584    0.969910  True   <- np.any(0.020584 < np.array([0.212339, 0.183405, 0.524756, 0.291229]))
6   0.832443    0.212339  False  <- np.any(0.832443 < np.array([0.183405, 0.524756, 0.291229]))
7   0.181825    0.183405  True   <- np.any(0.181825 < np.array([0.524756, 0.291229]))
8   0.304242    0.524756  False  <- np.any(0.304242  < np.array([0.291229]))
9   0.431945    0.291229  UNDEFINED <- Ignore this

The above should be possible with a for loop but what is the pandas/numpy way to do that?

I was trying for an approach where I apply a lambda function to a but l couldn't find a way to get the index of the respective a value to do the np.any comparison as shown above. (I have later discovered that apply is just syntactic sugar for a for loop, though)

df['c'] = df['a'].apply(lambda x: np.any(x < df['b'].values[:])) # Where  is the respective index value of x; which I didn't know how to find

Body:
To complement the answer by @Divakar, the pandas approach using cummax() would be:

df['c'] = df['a'] < df['b'][::-1].cummax()[::-1].reset_index(drop=True).shift(-1)

print(df)

        a         b      c
0  0.374540  0.950714   True
1  0.731994  0.598658   True
2  0.156019  0.155995   True
3  0.058084  0.866176   True
4  0.601115  0.708073   True
5  0.020584  0.969910   True
6  0.832443  0.212339  False
7  0.181825  0.183405   True
8  0.304242  0.524756  False
9  0.431945  0.291229  False


问:
Unable to Inspect elements in Java Website (IE Browser)
I want to verify the installed version of java by navigating to this

URL: https://www.java.com/en/download/installed.jsp in IE browser

When I click on Agree and continue button, it will display the java version.

I want to get the text of the java version displayed to verify it with my value, But I couldn't inspect on the block which displays the java version

I tried looking hmtl,the version value is not available in HTML as well.

Can anyone address this issue?

答:
If it have ID then try with id

```<code>driver.findElement(By.id("results_upgrade_block_user_jre"));
</code>```

You can also use xpath like this. also use wait

```<code>WebDriverWait wait = new WebDriverWait(driver,20);
WebElement btn=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(@id,'results_upgrade_block_user_jre')]")));
</code>```

Body:
If it have ID then try with id

driver.findElement(By.id("results_upgrade_block_user_jre"));

You can also use xpath like this. also use wait

WebDriverWait wait = new WebDriverWait(driver,20);
WebElement btn=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(@id,'results_upgrade_block_user_jre')]")));


问:
How can I remove the current year in my developer name in the App Store?
I released an iOS app in the App Store, but my developer name displays as "2017 [developer name]". I need only the developer name to show, without the "2017".Please check attached screenchot.

Screenshot image here

答:
It is likely that you are referring to the copyright details of your application.

You can change the copyright details in iTunes Connect under My Apps/App Store/iOS App/[app version]/General App Information/Copyright. The changes will show up in the App Store after releasing a new version.


问:
What is the best J2ME UI Library
What's the J2ME UI library you recommend?</p>

答:
Lot of UI framework available for developing j2me application. But i suggest LWUIT framework. LWUIT offers advanced UI capabilities and a clean API that is inspired by Swing. You can develop your own theme and animated screens by using LWUIT ResourceEdit. See the LWUIT blog.

You can download latest LWUIT from this repository or you can use latest release of LWUIT version 1.4 available. LWUIT supports Blackberry, Android and Symbian OS.

For more info see this links for your reference,

Introduction of LWUIT

Building theme for LWUIT

Title: What is the best J2ME UI Library


问:
singleton with throwable initializer
I have a singleton:

```<code>public class Manager {
  static let shared = Manager()
  private init() {
    ...
  }
}
</code>```

Other class can access it by:

```<code>Manager.shared
</code>```

No problem here. Now, I start thinking, what if the private initializer is throwable?

```<code>public class Manager {
   // Compiler error: Call can throw, but erros cannot be thrown out of global variable initializer
   static let shared = Manager()

   // throwable initialier
   private init() throws {
     ...
   }
}
</code>```

How to resolve above error if I still want Manager to be singleton?

答:
Getting a singleton instance means you don't know if its already initiated or not. If its throwable that means you wants to track.

Well here is a solution you can follow.

```<code>enum SomeError: Error {
    case unknown
}

public class Manager {
    private static var sharedManger: Manager? = {
        do {
            let manager = try Manager()
            return manager
        } catch {
            return nil
        }
    }()
    private init() throws {
        ...
    }

    class func shared() throws -> Manager {
        if let sm = sharedManger {
            return sm
        } else {
            throw SomeError.unknown
        }
    }
}
</code>```

Now you can do something like

```<code>do {
    try Manager.shared()
} catch {
    print("Throw")
}
</code>```

Title: singleton with throwable initializer

Body:
I have a singleton:

public class Manager {
  static let shared = Manager()
  private init() {
    ...
  }
}

Other class can access it by:

Manager.shared

No problem here. Now, I start thinking, what if the private initializer is throwable?

public class Manager {
   // Compiler error: Call can throw, but erros cannot be thrown out of global variable initializer
   static let shared = Manager()

   // throwable initialier
   private init() throws {
     ...
   }
}

How to resolve above error if I still want Manager to be singleton?

Body:
Getting a singleton instance means you don't know if its already initiated or not. If its throwable that means you wants to track.

Well here is a solution you can follow.

enum SomeError: Error {
    case unknown
}

public class Manager {
    private static var sharedManger: Manager? = {
        do {
            let manager = try Manager()
            return manager
        } catch {
            return nil
        }
    }()
    private init() throws {
        ...
    }

    class func shared() throws -> Manager {
        if let sm = sharedManger {
            return sm
        } else {
            throw SomeError.unknown
        }
    }
}

Now you can do something like

do {
    try Manager.shared()
} catch {
    print("Throw")
}


问:
How to infer the return type of a function?
The return type of a block is inferred.

```<code>fn main() {
    let x = { 5 };
    println!("{}", x);
}
</code>```

But when I give the block a name, I have to specify a type.

```<code>fn five() -> i32 {
    5
}

fn main() {
    let x = five();
    println!("{}", x);
}
</code>```

How can I avoid selecting a type?

答:
You cannot. Rust explicitly prohibits this by design.

However, for large and complex return types, you have the following options:

Use a closure instead - As it is local, it is allowed to infer its type

Return a boxed type

Return an abstract type

You can see a practical example of these in the answer for What is the correct way to return an Iterator (or any other trait)?

Body:
The return type of a block is inferred.

fn main() {
    let x = { 5 };
    println!("{}", x);
}

But when I give the block a name, I have to specify a type.

fn five() -> i32 {
    5
}

fn main() {
    let x = five();
    println!("{}", x);
}

How can I avoid selecting a type?


问:
How to split a sentence into multiple parts in Ruby
I want to split a main string and create multiples strings with the words obtained in Ruby.

```<code>str = "one two three four five"
</code>```

I want to create all these possibilities in an array of strings:

```<code>"one"
"one two"
"one two three"
"one two three four"
"one two three four five"
</code>```

but also:

```<code>"two three four five"
"three four five"
"four five"
"five"
</code>```

Ideally I would also obtain the strings inside too, but not required:

```<code>"two three four"
"two three"
"three four"
</code>```

I tried many things but difficult to have a best way to do that.

For example, I tried to work with each_slice:

```<code>words = string.split(" ")
        number_of_words = words.length
        max_number_of_slices = number_of_words
        array_of_strings_to_match = []
        number_of_slices = 1
        while (number_of_slices <= max_number_of_slices)
          array = words.each_slice(number_of_slices).map do |a| a.join ' ' end
          array.each do |w| array_of_strings_to_match << w end
          number_of_slices = number_of_slices + 1
        end
</code>```

But it's not the good way.

Any idea is welcome. :-)

This question is a little different from this one because I need to split a sentence of words, not a string by letters (even if it's quite the same).

答:
```<code>str = "one two three four five".split
1.upto(str.size).flat_map { |i| str.each_cons(i).to_a }

#⇒ [["one"], ["two"], ["three"], ["four"], ["five"],
#   ["one", "two"], ["two", "three"], ["three", "four"], ["four", "five"],
#   ["one", "two", "three"], ["two", "three", "four"], ["three", "four", "five"],
#   ["one", "two", "three", "four"], ["two", "three", "four", "five"],
#   ["one", "two", "three", "four", "five"]]
</code>```

Body:
I want to split a main string and create multiples strings with the words obtained in Ruby.

str = "one two three four five"

I want to create all these possibilities in an array of strings:

"one"
"one two"
"one two three"
"one two three four"
"one two three four five"

but also:

"two three four five"
"three four five"
"four five"
"five"

Ideally I would also obtain the strings inside too, but not required:

"two three four"
"two three"
"three four"

I tried many things but difficult to have a best way to do that.

For example, I tried to work with each_slice:

words = string.split(" ")
        number_of_words = words.length
        max_number_of_slices = number_of_words
        array_of_strings_to_match = []
        number_of_slices = 1
        while (number_of_slices <= max_number_of_slices)
          array = words.each_slice(number_of_slices).map do |a| a.join ' ' end
          array.each do |w| array_of_strings_to_match << w end
          number_of_slices = number_of_slices + 1
        end

But it's not the good way.

Any idea is welcome. :-)

This question is a little different from this one because I need to split a sentence of words, not a string by letters (even if it's quite the same).


问:
The result not found message displays with the searched data

```

 This is the code for searching and displaying data from a table.The searching works well but it shows  "No result found message " with the searched result even though the searched data in the table.I got the searched data with the no result found message.I need the warning message "no result found" only when the searched result not in the table.

答:
Judging purely from the code you provided, it seems like for every table row as long as there is one no occurrence, the No results found message pops up and the page gets reloaded after 3 seconds. If you want to only show that when all the table rows have no occurrence, try this code below. It is not tested so it may or may not work.

Basically what I have done is to add a counter that will increment everytime the if block goes into !occurrence. So if it matches the tr.length, then it means every table row did have no occurrence and then only then show the not found message.

```<code><script>

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, occurrence;
  var counter = 0;

  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("helpseekers");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
 for (i = 0; i < tr.length; i++) {
     occurrence = false; // Only reset to false once per row.
     td = tr[i].getElementsByTagName("td");
     for(var j=0; j< td.length; j++){
         currentTd = td[j];
         if (currentTd ) {
             if (currentTd.innerHTML.toUpperCase().indexOf(filter) > -1) {
                 tr[i].style.display = "";
                 occurrence = true;
             }
         }
     }
     if(!occurrence){
         tr[i].style.display = "none";
         counter++;
     }
 }
     if(counter === tr.length){
           $('#error4').html('<p style="color:red;font-size:14px;" align="center">No results found</p>');
       window.setTimeout(function(){location.reload()},3000)
 }
}
</script>
</code>```

Body:
Judging purely from the code you provided, it seems like for every table row as long as there is one no occurrence, the No results found message pops up and the page gets reloaded after 3 seconds. If you want to only show that when all the table rows have no occurrence, try this code below. It is not tested so it may or may not work.

Basically what I have done is to add a counter that will increment everytime the if block goes into !occurrence. So if it matches the tr.length, then it means every table row did have no occurrence and then only then show the not found message.

<script>

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, occurrence;
  var counter = 0;

  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("helpseekers");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
 for (i = 0; i < tr.length; i++) {
     occurrence = false; // Only reset to false once per row.
     td = tr[i].getElementsByTagName("td");
     for(var j=0; j< td.length; j++){
         currentTd = td[j];
         if (currentTd ) {
             if (currentTd.innerHTML.toUpperCase().indexOf(filter) > -1) {
                 tr[i].style.display = "";
                 occurrence = true;
             }
         }
     }
     if(!occurrence){
         tr[i].style.display = "none";
         counter++;
     }
 }
     if(counter === tr.length){
           $('#error4').html('<p style="color:red;font-size:14px;" align="center">No results found</p>');
       window.setTimeout(function(){location.reload()},3000)
 }
}
</script>


问:
How can I create a data structure starting at a specified memory address (without using new)?
I asked a similar question before, but I only realized now that the answer I received isn't totally what I wanted.

If I simply have a pointer of some structure type, how can I either move to, or create an instance of the same structure type starting at an address specified by the struct pointer (which I have assigned an address to) without using "new".

答:
That's what placement new is for:

```<code>foo* p = new(0x9000) foo(bar);
</code>```

Body:
That's what placement new is for:

foo* p = new(0x9000) foo(bar);


问:
MATCH AGAINST multiple words AND OR not working in codeigniter model
I have one table like below ,table name is js_skills_achievements

```<code>id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery
</code>```

When admin search key is "java developer"

```<code>SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer');
</code>```

Its working for me , BUT I NEED MULTIPLE KEYWORDS not Working below QUERY

```<code>SELECT * FROM js_skills_achievements
    WHERE MATCH (js_skills_achievements.skill1,js_skills_achievements.skill2,js_skills_achievements.skill3,js_skills_achievements.skill4) AGAINST('java developer') OR (MATCH (js_skills_achievements.skill1,js_skills_achievements.skill2,js_skills_achievements.skill3,js_skills_achievements.skill4) AGAINST('php developer')

//This is Also not working
SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer','php developer');
</code>```

Please any one help  me.

答:
Try it like this:

```<code>SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer php developer');
</code>```

MATCH AGAINST takes only 1 input. So, you can include both of the string in that 1 input.

Body:
I have one table like below ,table name is js_skills_achievements

id   skill1  skill2  skill3  skill4
1     java    php    html    android
2     php     java   jquery  html
3     sql     php    html    jquery

When admin search key is "java developer"

SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer');

Its working for me , BUT I NEED MULTIPLE KEYWORDS not Working below QUERY

SELECT * FROM js_skills_achievements
    WHERE MATCH (js_skills_achievements.skill1,js_skills_achievements.skill2,js_skills_achievements.skill3,js_skills_achievements.skill4) AGAINST('java developer') OR (MATCH (js_skills_achievements.skill1,js_skills_achievements.skill2,js_skills_achievements.skill3,js_skills_achievements.skill4) AGAINST('php developer')

//This is Also not working
SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer','php developer');

Please any one help  me.

Body:
Try it like this:

SELECT * FROM js_skills_achievements
WHERE MATCH(skill1,skill2,skill3,skill4) AGAINST ('java developer php developer');

MATCH AGAINST takes only 1 input. So, you can include both of the string in that 1 input.


问:
DexOverflowException after adding com.google.firebase:firebase-firestore:11.4.2
I have a problem after adding compile "com.google.firebase:firebase-firestore:11.4.2" to my build.

As soon as I add that, it also adds com.google.common among other things to my dex file, which is around 27k extra references, thus bursting through the 64k dex limit.

Does anyone know why that is or am I doing something wrong?

答: Updating to 11.6.0 fixes this issue</p>

Body: Updating to 11.6.0 fixes this issue


问:
How to create a rectangle with two rounded corners?
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.</p>

```<code> rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);
</code>```

答:
The source of drawRoundRect .So if you want to draw two round corners .

```<code>public void drawRoundRect(float left, float top, float right, float bottom, float rx, float ry, Paint paint)
</code>```

And you can try this .Just left and top have round corners.

```<code>canvas.drawRoundRect(10,10,0,0,20,20,facePaint);
</code>```

Body:
I need to create a rectangle view with two rounded corners using canvas.I used drawRoundRect but i am getting rectangle with four rounded corners.Please anyone suggest me a way that can be helpful in solving my problem.

 rect = new RectF(left, top, right, bottom);

 canvas.drawRoundRect(rect, 20, 20, facePaint);

Body:
The source of drawRoundRect .So if you want to draw two round corners .

public void drawRoundRect(float left, float top, float right, float bottom, float rx, float ry, Paint paint)

And you can try this .Just left and top have round corners.

canvas.drawRoundRect(10,10,0,0,20,20,facePaint);


问:
Doctrine Tell me "new Entity was found" when i set a relationship ManyToOne but is not

I have a Project with Symfony

Create a form for a ner entity.

```<code>class EquipoType extends AbstractType{
/**
 * {@inheritdoc}
 */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $equipo = new Equipo();

    $builder
    ->add('unidades', IntegerType::class)
    ->add('accionComercial', EntityType::class, array(
        'class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\AccionComercial',
        'em' => 'adeq',
        'choices' => $equipo->getAccionComercial(),
        'choice_label' => 'nombre',
        'placeholder' => 'Elija Accion Comercial'
    ))
    ->add('modelo', TextType::class)
    ->add('save', SubmitType::class, array(
            'label' => 'Guardar Equipo',
            'attr' => array(
                'class' => "btn btn-info",
                'style' => "margin-top: 7px; margin-left:40%;"
            ))
    );

    $builder->get('modelo')
        ->addModelTransformer(new CallbackTransformer(
            function ($modelo) {
                return $modelo ? $modelo->getModDescModelo() :  $modelo;
            },
            function ($modelo) use ($options) {
                return $modelo ? $options['em']->getRepository(ModModelo::class)->findOneBy(array(
                    'modDescModelo' => $modelo
                )) : $modelo;
            }
        ));
 public function configureOptions(OptionsResolver $resolver)
 {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo',
        'em' => "adeq"
    ));
 }

 /**
  * {@inheritdoc}
  */
 public function getBlockPrefix()
 {
    return 'appbundle_indicogpt_adelantoequipos_equipo';
 }
}
</code>```

This Entity has a relatuionship.
(Equipo has Modelo[oneToMany], Modelo has Many Equipos[oneToMany] )

```<code>    class Equipo
{
    /**
 * @var \AppBundle\Entity\IndicoGpt\catalogo\ModModelo
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\IndicoGpt\catalogo\ModModelo")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="modelo_id", referencedColumnName="MOD_ID_MODELO")
 * })
 */
private $modelo;
</code>```

The entity Modelo is full of rows (in db) with types of equip models. Ergo an Equipo only need to save an existing Id of a Modelo row.

The problem appears when i do $emAedq->flush() Here is my controller:

```<code>    public function crearEquipo(Request $request){

     $emAdeq = $this->getDoctrine()->getManager('adeq');
     $emCatalogo = $this->getDoctrine()->getManager('catalogo');

     $equipo = new Equipo();
     $form = $this->createForm(EquipoType::class, $equipo, array(
        'action' => "crearEquipo",
        'em' =>  $emCatalogo,
        'attr' => array(
            'class' => "form"
        )
     ));

     $form->handleRequest($request);

     if ($form->isSubmitted()) {

         $equipo = $form->getData();

         $emAdeq->persist($equipo);

         $emAdeq->flush();

         $this->addFlash('exito', $equipo->getId());

         return $this->redirectToRoute('portadaAdelantoEquipos');
     }
    ...
</code>```

When I go to save the new Equipo it tells me that it was found a new entity in the relationship and should be saved (reffering to Modelo associated), but that entity is not new, it is an existing Modelo that is now related to the Equipo.

As shown in the image, I choose a Modelo of the existing ones through an autocomplete field.

Just before doin the $emAdeq->persist($equipo) of the entity, i can see in the debugger the object that I am going to save it appears well composed:

The Error is the next:

A new entity was found through the relationship 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo#modelo' that was not configured to cascade persist operations for entity: AppBundle\Entity\IndicoGpt\catalogo\ModModelo@0000000011088ca600000000661c7dca. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'AppBundle\Entity\IndicoGpt\catalogo\ModModelo#__toString()' to get a clue.

I dont understand why thinks that is a new entity and why give me this string refering to modelo:

Why this happends?
How can i save the Equipo with his relationship?
Without make a persist of the Modelo because i can not save the Modelo that allready exist!

I have seen other example here. But this does not work to me...

I run this command php bin/console doctrine:schema:validate and everything is right.

答:
You can configure cascade persist into your entity or you can change this:

```<code>$emAdeq->persist($equipo);
</code>```

to this:

```<code>$emAdeq->merge($equipo);
</code>```

Body:
I have a Project with Symfony

Create a form for a ner entity.

class EquipoType extends AbstractType{
/**
 * {@inheritdoc}
 */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
    $equipo = new Equipo();

    $builder
    ->add('unidades', IntegerType::class)
    ->add('accionComercial', EntityType::class, array(
        'class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\AccionComercial',
        'em' => 'adeq',
        'choices' => $equipo->getAccionComercial(),
        'choice_label' => 'nombre',
        'placeholder' => 'Elija Accion Comercial'
    ))
    ->add('modelo', TextType::class)
    ->add('save', SubmitType::class, array(
            'label' => 'Guardar Equipo',
            'attr' => array(
                'class' => "btn btn-info",
                'style' => "margin-top: 7px; margin-left:40%;"
            ))
    );

    $builder->get('modelo')
        ->addModelTransformer(new CallbackTransformer(
            function ($modelo) {
                return $modelo ? $modelo->getModDescModelo() :  $modelo;
            },
            function ($modelo) use ($options) {
                return $modelo ? $options['em']->getRepository(ModModelo::class)->findOneBy(array(
                    'modDescModelo' => $modelo
                )) : $modelo;
            }
        ));
 public function configureOptions(OptionsResolver $resolver)
 {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo',
        'em' => "adeq"
    ));
 }

 /**
  * {@inheritdoc}
  */
 public function getBlockPrefix()
 {
    return 'appbundle_indicogpt_adelantoequipos_equipo';
 }
}

This Entity has a relatuionship.
(Equipo has Modelo[oneToMany], Modelo has Many Equipos[oneToMany] )

    class Equipo
{
    /**
 * @var \AppBundle\Entity\IndicoGpt\catalogo\ModModelo
 *
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\IndicoGpt\catalogo\ModModelo")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="modelo_id", referencedColumnName="MOD_ID_MODELO")
 * })
 */
private $modelo;

The entity Modelo is full of rows (in db) with types of equip models. Ergo an Equipo only need to save an existing Id of a Modelo row.

The problem appears when i do $emAedq->flush() Here is my controller:

    public function crearEquipo(Request $request){

     $emAdeq = $this->getDoctrine()->getManager('adeq');
     $emCatalogo = $this->getDoctrine()->getManager('catalogo');

     $equipo = new Equipo();
     $form = $this->createForm(EquipoType::class, $equipo, array(
        'action' => "crearEquipo",
        'em' =>  $emCatalogo,
        'attr' => array(
            'class' => "form"
        )
     ));

     $form->handleRequest($request);

     if ($form->isSubmitted()) {

         $equipo = $form->getData();

         $emAdeq->persist($equipo);

         $emAdeq->flush();

         $this->addFlash('exito', $equipo->getId());

         return $this->redirectToRoute('portadaAdelantoEquipos');
     }
    ...

When I go to save the new Equipo it tells me that it was found a new entity in the relationship and should be saved (reffering to Modelo associated), but that entity is not new, it is an existing Modelo that is now related to the Equipo.

As shown in the image, I choose a Modelo of the existing ones through an autocomplete field.

Just before doin the $emAdeq->persist($equipo) of the entity, i can see in the debugger the object that I am going to save it appears well composed:

The Error is the next:

A new entity was found through the relationship 'AppBundle\Entity\IndicoGpt\adelantoequipos\Equipo#modelo' that was not configured to cascade persist operations for entity: AppBundle\Entity\IndicoGpt\catalogo\ModModelo@0000000011088ca600000000661c7dca. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'AppBundle\Entity\IndicoGpt\catalogo\ModModelo#__toString()' to get a clue.

I dont understand why thinks that is a new entity and why give me this string refering to modelo:

Why this happends?
How can i save the Equipo with his relationship?
Without make a persist of the Modelo because i can not save the Modelo that allready exist!

I have seen other example here. But this does not work to me...

I run this command php bin/console doctrine:schema:validate and everything is right.

Body:
You can configure cascade persist into your entity or you can change this:

$emAdeq->persist($equipo);

to this:

$emAdeq->merge($equipo);


问:
What is the difference between func() => {} and func = () => {} in class?
I'm learning to use Class syntax now to create React components now and notice I now have to declare methods like this:

```<code>class Foo extends React.Component {
    ...
    bar = () => {
        this.setState({ ... })
    }
}
</code>```

instead of like this:

```<code>class Foo extends React.Component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}
</code>```

or I can't use this.setState().

Can anybody explain what's the difference between creating methods like this and how they are related to the function prototype?

答:
If you're going to be using this style:

```<code>class Foo extends React.component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}
</code>```

You'd need to bind this to the current context, like this:

```<code>class Foo extends React.component {
    constructor(props) {
       super(props);
       this.bar = this.bar.bind(this);
    }

    bar() {
        this.setState({ ... })  // works
    }
}
</code>```

Body:
I'm learning to use Class syntax now to create React components now and notice I now have to declare methods like this:

class Foo extends React.Component {
    ...
    bar = () => {
        this.setState({ ... })
    }
}

instead of like this:

class Foo extends React.Component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}

or I can't use this.setState().

Can anybody explain what's the difference between creating methods like this and how they are related to the function prototype?

Body:
If you're going to be using this style:

class Foo extends React.component {
    ...
    bar() {
        this.setState({ ... })  // won't work
    }
}

You'd need to bind this to the current context, like this:

class Foo extends React.component {
    constructor(props) {
       super(props);
       this.bar = this.bar.bind(this);
    }

    bar() {
        this.setState({ ... })  // works
    }
}


问:
Compare values from cx_oracle cursor with django queryset
In my project I collect data from an oracle database using cx_Oracle and then I need to compare the result from the cx_Oracle cursor with data from a SQLite database for which I have models.

I have the following code which works for adding missing parameters:

```<code>    def GetParams(self):
    repo_params = Parameters.objects.filter(dbid=self.dbid).only('name','value')
    sql = ("select name, value from v$parameter")
    self.cur.execute(sql)
    res = self.cur.fetchall()
    repo_params = list(repo_params)
    parameters = []
    for i in res:
        if i[1] not in repo_params:
            new_param = Parameters(name=i[1],value=i[2])
            parameters.append(new_param)
    if len(parameters) > 0:
        Parameters.objects.bulk_create(parameters)
</code>```

But what I actually want to do is to merge existing content in my SQLite database with the one from the cursor. If an existing parameter exists with a different values then I need to update its value. If it's a new parameter, then it need to be created. What is the best way to do this? Should I do a MERGE using RAW sql?

Thanks

答:
I answer my own question.
This is a simplified way to handle both inserting new parameters and updating existing ones in SQLite:

```<code>    from django.db import connection

    def GetParams(self):
    sql = ("select name, value from v$parameter")
    self.cur.execute(sql)
    res = self.cur.fetchall()
    cursor = connection.cursor()
    for i in res:
        cursor.execute('''INSERT OR REPLACE
                          INTO Parameters(dbid, name, value)
                          VALUES( %s, %s, %s)''',[self.dbid,i[0],i[1]]
                      )
    connection.commit()
</code>```

UPDATE:

Even better:

```<code> def GetParams(self):
    sql = ("select :dbid, name, value from v$parameter")
    named_params = {'dbid': self.dbid}
    self.cur.execute(sql, named_params)
    res = self.cur.fetchall()
    cursor = connection.cursor()
    cursor.executemany('INSERT OR REPLACE\n'
                       'INTO Parameters(dbid, name, value)\n'
                       'VALUES( ?, ?, ?)', res
                       )
</code>```

Body:
In my project I collect data from an oracle database using cx_Oracle and then I need to compare the result from the cx_Oracle cursor with data from a SQLite database for which I have models.

I have the following code which works for adding missing parameters:

    def GetParams(self):
    repo_params = Parameters.objects.filter(dbid=self.dbid).only('name','value')
    sql = ("select name, value from v$parameter")
    self.cur.execute(sql)
    res = self.cur.fetchall()
    repo_params = list(repo_params)
    parameters = []
    for i in res:
        if i[1] not in repo_params:
            new_param = Parameters(name=i[1],value=i[2])
            parameters.append(new_param)
    if len(parameters) > 0:
        Parameters.objects.bulk_create(parameters)

But what I actually want to do is to merge existing content in my SQLite database with the one from the cursor. If an existing parameter exists with a different values then I need to update its value. If it's a new parameter, then it need to be created. What is the best way to do this? Should I do a MERGE using RAW sql?

Thanks

Body:
I answer my own question.
This is a simplified way to handle both inserting new parameters and updating existing ones in SQLite:

    from django.db import connection

    def GetParams(self):
    sql = ("select name, value from v$parameter")
    self.cur.execute(sql)
    res = self.cur.fetchall()
    cursor = connection.cursor()
    for i in res:
        cursor.execute('''INSERT OR REPLACE
                          INTO Parameters(dbid, name, value)
                          VALUES( %s, %s, %s)''',[self.dbid,i[0],i[1]]
                      )
    connection.commit()

UPDATE:

Even better:

 def GetParams(self):
    sql = ("select :dbid, name, value from v$parameter")
    named_params = {'dbid': self.dbid}
    self.cur.execute(sql, named_params)
    res = self.cur.fetchall()
    cursor = connection.cursor()
    cursor.executemany('INSERT OR REPLACE\n'
                       'INTO Parameters(dbid, name, value)\n'
                       'VALUES( ?, ?, ?)', res
                       )


问:
State Diagram Generator
Is there a tool which generates the state space by seeing the code. i.e., if I give a class definition, it should generate the state machine.

EDIT: State machine I mean is just the graphical representation of the classes and state changes.

答:
I'm afraid you'll have to be more specific.

The state space of a class is the Cartesian product of the state space of each component, and it doesn't take a particularly complicated class to have more possible states than there are protons in the Universe.  With a few exceptions, C++ code is not well suited to analysis with state space.

State machines are usually associated with regular expressions.  Do you want a tool that does something with a regular expression?

If so, what?  Languages that accept regular expressions do something to convert them to a form of state space representation, leaving it in some sort of internal form.  Do you want it in the form of a readable diagram, as the tag implies?

OwnerDisplayName: Vinay

Title: State Diagram Generator

LastEditorDisplayName: Vinay

OwnerDisplayName: David Thornley


问:
Increase tablet container size in Semantic UI and rebuild it
I'm using Semantic UI on a website and it looks pretty well in all the resolutions, but I'd like that, when in tablet size, the containers were a bit wider.

I've found that the variables that control that width are in the file themes/default/elements/container.variables. I read that, to avoid modifying the original files, you have to edit the file site/globals/site.variables, so I've added the following lines:

```<code>@blue  : #00709e;
@green : #75912b;
@black : #464646;

@tabletWidth: (@tabletBreakpoint+201) - (@tabletMinimumGutter * 2) - @scrollbarWidth;
</code>```

I've rebuilt the CSS/JS files using gulp and I can see that the blue, green and black colors have changed, but the tablet container size is the same as before.

Do I have to change something else? Thanks!

答: From my knowledge of theming semantic and what I can see I wouldn't change @tabletWidth but I would just change @tabletBreakpoint and @tabletMinimumGutter the values you want, this should then make @tabletWidth in the container.variables use your variables to workout the width.

Body:
I'm using Semantic UI on a website and it looks pretty well in all the resolutions, but I'd like that, when in tablet size, the containers were a bit wider.

I've found that the variables that control that width are in the file themes/default/elements/container.variables. I read that, to avoid modifying the original files, you have to edit the file site/globals/site.variables, so I've added the following lines:

@blue  : #00709e;
@green : #75912b;
@black : #464646;

@tabletWidth: (@tabletBreakpoint+201) - (@tabletMinimumGutter * 2) - @scrollbarWidth;

I've rebuilt the CSS/JS files using gulp and I can see that the blue, green and black colors have changed, but the tablet container size is the same as before.

Do I have to change something else? Thanks!


问:
awk print all parts before a match
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

```<code>awk '/[1-2][0-9][0-9][0-9]/{print $1}'
</code>```

but that only prints the first "word" of the input

```<code>"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"
</code>```

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

```<code> awk -F[1-2][0-9][0-9][0-9] '{print $1}
</code>```

EDIT:
This is what I ended up with and then came back to see a solution posted:

```<code>awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'
</code>```

Thanks all

答:
awk solution:

```<code>awk 'match($0,/.*\<[12][0-9]{3}/){ print substr($0,RSTART,RLENGTH)"\042" }' file
</code>```

The output:

```<code>"Financial summary 1997"
"v4 Minutes 1995"
</code>```

Title: awk print all parts before a match

Body:
I have some text where I want to grab all the text up to the year, inclusive. I've tried starting with something like this

awk '/[1-2][0-9][0-9][0-9]/{print $1}'

but that only prints the first "word" of the input

"Financial summary 1997 FINAL.doc" => "Financial"
"v4 Minutes 19950705" => "v4"

What I want is "Financial summary 1997" and "v4 Minutes 1995". I've played around with $NF and various others with no success as yet I don't know how many words there are, or how many numbers there are, so I can't jut print $1 $2 $3. I don't have to use awk, but it would be useful since I am actually going to print the results out with some surrounding tags for output to an HTML file.

I can set a field separator to be "4 digits" but that discards the year

 awk -F[1-2][0-9][0-9][0-9] '{print $1}

EDIT:
This is what I ended up with and then came back to see a solution posted:

awk 'match($0,/.*(19|20)[0-9]{2}/){print substr($0,RSTART,RLENGTH)}'

Thanks all

Body:
awk solution:

awk 'match($0,/.*\<[12][0-9]{3}/){ print substr($0,RSTART,RLENGTH)"\042" }' file

The output:

"Financial summary 1997"
"v4 Minutes 1995"


问:
Pivot my sql rows into columns
I have below structure.
|id|value|

|a|v1|

|b|v2|

|c|v3|

|d|v4|

Output needed.

|a|  b| c|d|

|v1|v2|v3|v4|

I tried many, but could get success

```<code>select case  when t1.id  = 'a' then t1.value end as a ,
         case    when t1.id  = 'b' then t1.value end as b ,
          case   when t1.id  = 'c' then t1.value end as b ,
          case   when t1.id  = 'd' then t1.value end as d

           from
t1
</code>```

please advise.

Thanks

答:
You use aggregate function for your required result set

```<code>select max(case  when t1.id  = 'a' then t1.value end) as a ,
       max(case  when t1.id  = 'b' then t1.value end) as b ,
       max(case  when t1.id  = 'c' then t1.value end) as b ,
       max(case  when t1.id  = 'd' then t1.value end) as d
from t1
</code>```

Demo

Note using aggregate function without group by will consider whole table as a single group

Title: Pivot my sql rows into columns

Body:
I have below structure.
|id|value|

|a|v1|

|b|v2|

|c|v3|

|d|v4|

Output needed.

|a|  b| c|d|

|v1|v2|v3|v4|

I tried many, but could get success

select case  when t1.id  = 'a' then t1.value end as a ,
         case    when t1.id  = 'b' then t1.value end as b ,
          case   when t1.id  = 'c' then t1.value end as b ,
          case   when t1.id  = 'd' then t1.value end as d

           from
t1

please advise.

Thanks

Body:
You use aggregate function for your required result set

select max(case  when t1.id  = 'a' then t1.value end) as a ,
       max(case  when t1.id  = 'b' then t1.value end) as b ,
       max(case  when t1.id  = 'c' then t1.value end) as b ,
       max(case  when t1.id  = 'd' then t1.value end) as d
from t1

Demo

Note using aggregate function without group by will consider whole table as a single group


问:
How to write a simple stored procedure in advantage data architect
I am creating a WPF application using Advantage database server. I want to insert some data using stored procedure

Any sample code ?

I tried two input parameter TestID and TestName (both NCHAR)

```<code>INSERT INTO TestTable(
                    Test_Id,
                    Test_Name)
         VALUES (
                     @TestID,
                    @TestName);
</code>```

But show error like

Error 7200:  AQE Error:  State = HY000;   NativeError = 5154;
  [SAP][Advantage SQL Engine][ASA] Error 5154:  Execution of the stored
  procedure failed.   Procedure Name: TestInsert. Error 7200:  AQE
  Error:  State = S0000;   NativeError = 2121;  [SAP][Advantage SQL
  Engine]Column not found: @TestID -- Location of error in the SQL
  statement is: 42 (line: 3 column: 5) Error in stored procedure:
  TestInsert  AdsCommand query execution failed.

I am new in SAP ADS. Please help me.

答:
use _XXXX notation for input parameters.

ie,

INSERT INTO TestTable( Test_Id, Test_Name)
VALUES ( _@TestID, _@TestName);

Body:
I am creating a WPF application using Advantage database server. I want to insert some data using stored procedure

Any sample code ?

I tried two input parameter TestID and TestName (both NCHAR)

INSERT INTO TestTable(
                    Test_Id,
                    Test_Name)
         VALUES (
                     @TestID,
                    @TestName);

But show error like

Error 7200:  AQE Error:  State = HY000;   NativeError = 5154;
  [SAP][Advantage SQL Engine][ASA] Error 5154:  Execution of the stored
  procedure failed.   Procedure Name: TestInsert. Error 7200:  AQE
  Error:  State = S0000;   NativeError = 2121;  [SAP][Advantage SQL
  Engine]Column not found: @TestID -- Location of error in the SQL
  statement is: 42 (line: 3 column: 5) Error in stored procedure:
  TestInsert  AdsCommand query execution failed.

I am new in SAP ADS. Please help me.