问:
C# - Split Fully Uppercase String Into Separate Words (No Spaces)
Im currently working on a project where I will need to separate individual words from a string. The catch is that all the words in the string are capitalized and have no spaces. The following is an example of the kind of input the program is receiving:

"COMPUTERFIVECODECOLOR"

This should be split into the following result:

"COMPUTER"
"FIVE"
"CODE"
"COLOR"

So far, I have been using the following method to split my strings (and it has worked for all scenarios except this edge case):

```<code>private static List<string> NormalizeSections(List<string> wordList)
        {
            var modifiedList = new List<string>();
            foreach (var word in wordList)
            {
                int index = wordList.IndexOf(word);
                var split = Regex.Split(word, @"(\p{Lu}\p{Ll}+)").ToList();
                split.RemoveAll(i => i == "");

                modifiedList.AddRange(split);
            }
            return modifiedList;
        }
</code>```

If anyone has any ideas on how to handle this, I would be more than happy to hear them. Also, please let me know if I can provide additional information.

答:
Assuming the words in the dictionary do not contain each other (e.g. "TOO" and "TOOK"), I fail to see why this problem requires a solution that is any more complicated than this one-line function:

```<code>static public List<string> Normalize(string input, List<string> dictionary)
{
    return dictionary.Where(a => input.Contains(a)).ToList();
}
</code>```

(If the words DO contain each other, see below.)

Full example:

```<code>using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    static public List<string> Normalize(string input, List<string> dictionary)
    {
        return dictionary.Where(a => input.Contains(a)).ToList();
    }

    public static void Main()
    {
        List<string> dictionary = new List<string>
        {
            "COMPUTER","FIVE","CODE","COLOR","FOO"
        };
        string input = "COMPUTERFIVECODECOLORBAR";
        var normalized = Normalize(input, dictionary);
        foreach (var s in normalized)
        {
            Console.WriteLine(s);
        }
    }
}
</code>```

Output:

```<code>COMPUTER
FIVE
CODE
COLOR
</code>```

Code on DotNetFiddle

On the other hand, if you've determined that your keywords DO in fact overlap, you're not totally out of luck. If you are certain that the input string contains only words that are in the dictionary, and that they are continguous, you can use a more complicated function.

```<code>    static public List<string> Normalize2(string input, List<string> dictionary)
    {
        var sorted = dictionary.OrderByDescending( a => a.Length).ToList();
        var results = new List<string>();
        bool found = false;

        do
        {
            found = false;
            foreach (var s in sorted)
            {
                if (input.StartsWith(s))
                {
                    found = true;
                    results.Add(s);
                    input = input.Substring(s.Length);
                    break;
                }
            }
        }
        while (input != "" && found);

        return results;
    }

    public static void Main()
    {
        List<string> dictionary = new List<string>
        {
            "SHORT","LONG","LONGER","FOO","FOOD"
        };
        string input = "FOODSHORTLONGERFOO";
        var normalized = Normalize2(input, dictionary);
        foreach (var s in normalized)
        {
            Console.WriteLine(s);
        }
    }
</code>```

The way this works is that it only looks at the beginning of the string and looks for the longest keywords first. When one is found, it removes it from the input string and continues searching.

Output:

```<code>FOOD
SHORT
LONGER
FOO
</code>```

Notice that "LONG" is not included because we included "LONGER", but "FOO" is included because it is in the string separate from "FOOD".

Also, with this second solution, the keywords will appear in the results dictionary in the same order they appeared in the original string. So if the requirement was to actually split the phrase rather than just detect the keywords in any order, you should use the second function.

Code

Body:
Im currently working on a project where I will need to separate individual words from a string. The catch is that all the words in the string are capitalized and have no spaces. The following is an example of the kind of input the program is receiving:

"COMPUTERFIVECODECOLOR"

This should be split into the following result:

"COMPUTER"
"FIVE"
"CODE"
"COLOR"

So far, I have been using the following method to split my strings (and it has worked for all scenarios except this edge case):

private static List<string> NormalizeSections(List<string> wordList)
        {
            var modifiedList = new List<string>();
            foreach (var word in wordList)
            {
                int index = wordList.IndexOf(word);
                var split = Regex.Split(word, @"(\p{Lu}\p{Ll}+)").ToList();
                split.RemoveAll(i => i == "");

                modifiedList.AddRange(split);
            }
            return modifiedList;
        }

If anyone has any ideas on how to handle this, I would be more than happy to hear them. Also, please let me know if I can provide additional information.

Body:
Assuming the words in the dictionary do not contain each other (e.g. "TOO" and "TOOK"), I fail to see why this problem requires a solution that is any more complicated than this one-line function:

static public List<string> Normalize(string input, List<string> dictionary)
{
    return dictionary.Where(a => input.Contains(a)).ToList();
}

(If the words DO contain each other, see below.)

Full example:

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    static public List<string> Normalize(string input, List<string> dictionary)
    {
        return dictionary.Where(a => input.Contains(a)).ToList();
    }

    public static void Main()
    {
        List<string> dictionary = new List<string>
        {
            "COMPUTER","FIVE","CODE","COLOR","FOO"
        };
        string input = "COMPUTERFIVECODECOLORBAR";
        var normalized = Normalize(input, dictionary);
        foreach (var s in normalized)
        {
            Console.WriteLine(s);
        }
    }
}

Output:

COMPUTER
FIVE
CODE
COLOR

Code on DotNetFiddle

On the other hand, if you've determined that your keywords DO in fact overlap, you're not totally out of luck. If you are certain that the input string contains only words that are in the dictionary, and that they are continguous, you can use a more complicated function.

    static public List<string> Normalize2(string input, List<string> dictionary)
    {
        var sorted = dictionary.OrderByDescending( a => a.Length).ToList();
        var results = new List<string>();
        bool found = false;

        do
        {
            found = false;
            foreach (var s in sorted)
            {
                if (input.StartsWith(s))
                {
                    found = true;
                    results.Add(s);
                    input = input.Substring(s.Length);
                    break;
                }
            }
        }
        while (input != "" && found);

        return results;
    }

    public static void Main()
    {
        List<string> dictionary = new List<string>
        {
            "SHORT","LONG","LONGER","FOO","FOOD"
        };
        string input = "FOODSHORTLONGERFOO";
        var normalized = Normalize2(input, dictionary);
        foreach (var s in normalized)
        {
            Console.WriteLine(s);
        }
    }

The way this works is that it only looks at the beginning of the string and looks for the longest keywords first. When one is found, it removes it from the input string and continues searching.

Output:

FOOD
SHORT
LONGER
FOO

Notice that "LONG" is not included because we included "LONGER", but "FOO" is included because it is in the string separate from "FOOD".

Also, with this second solution, the keywords will appear in the results dictionary in the same order they appeared in the original string. So if the requirement was to actually split the phrase rather than just detect the keywords in any order, you should use the second function.

Code


来源: stackexchange

问:
Update nuget package for ASP.NET Web Application
When I create a ASP.NET Web Application (.net framework), there are dozens of packages are installed by default. In the development of our projects, we need to update some of those default nuget packages.

I know I could use nuget update in the Package Manager Console to update them. However, when we create the new projects, we need to remember which packages need to be upgraded. This is very inconvenient.

So my question is whether there is a way to update the list of specific packages so that we do not need to update it each time when we create the new project?
 Whether I could use Pre-build event to achieve what I want?

答:
whether there is a way to update the list of specific packages so that we do not need to update it each time when we create the new project?

Agree with Yuri S. The best way to resolve this question is using project template.

Detail Steps:

Create a default ASP.NET Web Application (.net framework) project.

Update those packages which you want to upgrade.

Export Template. (For VS2015 and before, File->Export Template... For VS 2017, Project->Export Template)

You can find the new project template in your template list.

Note: Make sure the checkbox "Automatically import the template into Visual Studio" is checked in the export template wizard window.

Whether I could use Pre-build event to achieve what I want?

I am afraid you can not do this with pro-build event. That because you just want to upgrade some of default packages not all default packages. When you use the update command nuget.exe update "xx" in the build event, nuget will prompt that you need give the package.config, project.json or solution file. So it will upgrade all default packages.

Besides, with this build event, Visual Studio will execute the upgrade every time when you build you project, which is unreasonable.

So the best way is using project template.

ContentLicense: CC BY-SA 3.0


问:
Ant XPath support
Is it possible in Ant to get the value of the attribute based on the value of another attribute?

I need the value of templateId.extension when templateId.root="2.16.840.1.113883.2.20.6.9". I am using the xmlproperty task but I have not figured out how to embed an XPath expression in my query.

extract from XML file

```<code>  <templateId extension="111" root="2.16.840.1.113883.2.20.6.9"/>
  <templateId extension="4" root="2.16.840.1.113883.2.20.6.11"/>
</code>```

my ant snippet

```<code>    <xmlproperty file="input/${id}.xml" keeproot="false" collapseattributes="true"></xmlproperty>
    <echo>content template: ${templateId[/.root="2.16.840.1.113883.2.20.6.9"].extension}</echo>
</code>```

答:
Ant's native xmlproperty task doesn't have full XPath support. If multiple elements with the same name exist in the same location, their attributes are each assigned to the same property, in comma-delimited lists. At that point, they can be difficult to work with.

If you need to do advanced XML parsing, there's a 3rd party library called XMLTask available here: http://www.oopsconsultancy.com/software/xmltask

Then you can do something like this:

```<code><taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask">
    <classpath location="lib/xmltask.jar"/>
</taskdef>

<target name="default">
    <xmltask source="test.xml">
        <copy path="/parent/templateId[@root='2.16.840.1.113883.2.20.6.9']/@extension" property="xmltask.property" />
    </xmltask>

    <echo message="templateId extension with root value '2.16.840.1.113883.2.20.6.9' = ${xmltask.property}" />
</target>
</code>```

Title: Ant XPath support

Body:
Is it possible in Ant to get the value of the attribute based on the value of another attribute?

I need the value of templateId.extension when templateId.root="2.16.840.1.113883.2.20.6.9". I am using the xmlproperty task but I have not figured out how to embed an XPath expression in my query.

extract from XML file

  <templateId extension="111" root="2.16.840.1.113883.2.20.6.9"/>
  <templateId extension="4" root="2.16.840.1.113883.2.20.6.11"/>

my ant snippet

    <xmlproperty file="input/${id}.xml" keeproot="false" collapseattributes="true"></xmlproperty>
    <echo>content template: ${templateId[/.root="2.16.840.1.113883.2.20.6.9"].extension}</echo>

Body:
Ant's native xmlproperty task doesn't have full XPath support. If multiple elements with the same name exist in the same location, their attributes are each assigned to the same property, in comma-delimited lists. At that point, they can be difficult to work with.

If you need to do advanced XML parsing, there's a 3rd party library called XMLTask available here: http://www.oopsconsultancy.com/software/xmltask

Then you can do something like this:

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask">
    <classpath location="lib/xmltask.jar"/>
</taskdef>

<target name="default">
    <xmltask source="test.xml">
        <copy path="/parent/templateId[@root='2.16.840.1.113883.2.20.6.9']/@extension" property="xmltask.property" />
    </xmltask>

    <echo message="templateId extension with root value '2.16.840.1.113883.2.20.6.9' = ${xmltask.property}" />
</target>


问:
How tensorflow knows what variables to fit if I use classes from tf.layers package?
tf.layers package contains layer definition function, which does not contain explicit tensors to train. For example, layers.conv2d does not have filter tensor like nn.conv2d has.

How tensorflow finds variables to fit?

If I mix operations from layers and nn how can I provide my variables in the same way?

Suppose, I collect variables to train into list:

```<code>    weights = tf.Variable(tf.truncated_normal([kernel_size[0], kernel_size[0], input_depth, filters],
                                              dtype=tf.float32, stddev=self.init_stddev), trainable=True)

    self.var_list.append(weights)

    biases = tf.Variable(tf.truncated_normal([filters], dtype=tf.float32, stddev=self.init_stddev), trainable=True)

    self.var_list.append(biases)

    x = tf.nn.conv2d(x, weights, [1, 1, 1, 1], padding=padding)

    x = tf.nn.bias_add(x, biases)
</code>```

and then

```<code>self.step = opt.minimize(self.cross_entropy, var_list=self.var_list)
</code>```

答:
I'm a bit confused with your question. Of course tf.layers.conv2d has parameters for defining tensors(second one):

tf.layers.conv2d
  conv2d(
      inputs,
      filters,
      kernel_size,
      strides=(1, 1),
      padding='valid',
      data_format='channels_last',
      dilation_rate=(1, 1),
      activation=None,
      use_bias=True,
      kernel_initializer=None,
      bias_initializer=tf.zeros_initializer(),
      kernel_regularizer=None,
      bias_regularizer=None,
      activity_regularizer=None,
      kernel_constraint=None,
      bias_constraint=None,
      trainable=True,
      name=None,
      reuse=None
  )

Also, in the tensorflow document, it was mentioned explicitly:

tf.nn.conv2d - Computes a 2-D convolution given 4-D input and filter tensors.

So you should be using tf.layers.conv2d for building networks and tf.nn.conv2d for computations.

Body:
tf.layers package contains layer definition function, which does not contain explicit tensors to train. For example, layers.conv2d does not have filter tensor like nn.conv2d has.

How tensorflow finds variables to fit?

If I mix operations from layers and nn how can I provide my variables in the same way?

Suppose, I collect variables to train into list:

    weights = tf.Variable(tf.truncated_normal([kernel_size[0], kernel_size[0], input_depth, filters],
                                              dtype=tf.float32, stddev=self.init_stddev), trainable=True)

    self.var_list.append(weights)

    biases = tf.Variable(tf.truncated_normal([filters], dtype=tf.float32, stddev=self.init_stddev), trainable=True)

    self.var_list.append(biases)

    x = tf.nn.conv2d(x, weights, [1, 1, 1, 1], padding=padding)

    x = tf.nn.bias_add(x, biases)

and then

self.step = opt.minimize(self.cross_entropy, var_list=self.var_list)


问:
Insert a File to MySQL database
I searched on how to insert an image here that helps me,now I need to insert a file to my database,please help me I have a data type of LONGBLOB for column name (binary) and nvarchar(50) for column name (file),but cannot insert a file and gives me an error that says I have an error in sql syntax.Any help will much appreciated.Thanks

This is my code for upload

```<code> '          Extract File name
        Dim FullFileName() As String = OpenFileDialog1.FileName.Split("\")
        Dim fname As String = FullFileName.Last.ToString()
        Try
            '  read data file
            Dim fileContent() As Byte

            Dim FSteream As New FileStream(OpenFileDialog1.FileName, FileMode.Open)
            Dim BReader As New BinaryReader(FSteream)

            fileContent = BReader.ReadBytes(FSteream.Length)
            FSteream.Close()
            BReader.Close()

            '  insert file to db
            conn.Open()
            cmd.Connection = conn
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "insert into file_tbl(file,binary) values (@name,@data)"
            cmd.Parameters.Clear()
            cmd.Parameters.AddWithValue("@name", fname)
            cmd.Parameters.AddWithValue("@data", fileContent)

            cmd.ExecuteNonQuery()
            '    '----
        Catch ex As Exception
            MsgBox(ex.Message + " inside upload button")
        Finally
            MsgBox("File : " & fname & " Uploaded .")
            conn.Close()
            cmd.Dispose()
        End Try
</code>```

答: Instead of converting to file into byte, save file to common folder and save link to the file in database table field.</p>

Title: Insert a File to MySQL database

Body:
I searched on how to insert an image here that helps me,now I need to insert a file to my database,please help me I have a data type of LONGBLOB for column name (binary) and nvarchar(50) for column name (file),but cannot insert a file and gives me an error that says I have an error in sql syntax.Any help will much appreciated.Thanks

This is my code for upload

 '          Extract File name
        Dim FullFileName() As String = OpenFileDialog1.FileName.Split("\")
        Dim fname As String = FullFileName.Last.ToString()
        Try
            '  read data file
            Dim fileContent() As Byte

            Dim FSteream As New FileStream(OpenFileDialog1.FileName, FileMode.Open)
            Dim BReader As New BinaryReader(FSteream)

            fileContent = BReader.ReadBytes(FSteream.Length)
            FSteream.Close()
            BReader.Close()

            '  insert file to db
            conn.Open()
            cmd.Connection = conn
            cmd.CommandType = CommandType.Text
            cmd.CommandText = "insert into file_tbl(file,binary) values (@name,@data)"
            cmd.Parameters.Clear()
            cmd.Parameters.AddWithValue("@name", fname)
            cmd.Parameters.AddWithValue("@data", fileContent)

            cmd.ExecuteNonQuery()
            '    '----
        Catch ex As Exception
            MsgBox(ex.Message + " inside upload button")
        Finally
            MsgBox("File : " & fname & " Uploaded .")
            conn.Close()
            cmd.Dispose()
        End Try


问:
How frequently can I send data using Socket.IO?
I'm creating a web application that would require small amounts of data (3 integer values per socket) to be sent from the server to the client very frequently and I wanted to see if there's a maximum frequency for updating the client using Socket.IO.

I was hoping to achieve at least 50 socket connections sending 20 updates per second each. With the ideal number being 200 socket connections sending 50 updates per second.

Question: Is there a limit to how often I can send new data using Socket.IO?

Note: I recognize this also becomes a speed issue of the server-client connection so any information on how fast of a connection I would need is appreciated. I calculated that if each data packet being sent is approximately 500 bytes, then I would be able to send 20 updates a second to 100 connections on a 1 MB/s connection.

答:
How frequently can I send data using Socket.IO?

Is there a limit to how often I can send new data using Socket.IO?

There is no coded limit.  It will only depend upon your ability to process the messages at both ends and the bandwidth to deliver them.  If you really wanted to know your own limit with the hardware, network and OS you're running, you'd have to devise a test to send rapid fire packets of a representative size and see how many you can send in a second where they all get to the destination and no errors are seen on either end.

With the ideal number being 200 socket connections sending 50 updates per second.

Your server would need to be able to send 10,000 messages per second and each client would need to be able to process 50 incoming messages per second.  That's all theoretically possible with the right hardware and right network connection.

But, 50 updates per second sounds like it's probably both unnecessary and inefficient.  No end-user is going to perceive some change every 20ms which is what 50 updates per second comes down to.  So, it would be a LOT more efficient to batch your updates to each client into maybe 10 updates per second.

I calculated that if each data packet being sent is approximately 500 bytes, then I would be able to send 20 updates a second to 100 connections on a 1 MB/s connection.

That type of calculation only works for sending large blocks of data.  For lots of small messages, there are lots of inefficiencies as the TCP packet overhead and the webSocket/socket.io overhead for lots of small messages starts to become a measurable percentage of the overall bandwidth consumption and because TCP is a reliable protocol, there are also ACKs flowing back and forth to acknowledge delivery.  If the packets are small, you probably don't have an overall bandwidth problem, the issue will be more with processing lots of small packets and the overhead to do that.

If you can combine updates into a smaller number of updates per second, you will get a lot better scalability.


问:
Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."
Important notice:

If you register for testing, go to your profile settings and to your interests add delete profile.

Trying to login with Facebook to my website:

I get the following error:

URL Blocked: This redirect failed because the redirect URI is not
  whitelisted in the app’s Client OAuth Settings. Make sure Client and
  Web OAuth Login are on and add all your app domains as Valid OAuth
  Redirect URIs.

My settings (Basics) in Facebook are:

App Domains: openstrategynetwork.com

Site URL for website: http://openstrategynetwork.com/

In the advanced tab, Valid OAuth redirect URIs is set to:

http://openstrategynetwork.com/_oauth/facebook?close

App is public.

More settings (Advanced) here:

App key and secret are correct. I'm using Meteor and its accounts packages.

答: In my case, I was integrating Facebook login within a Rails app tutorial. I had added http://localhost:3000/adsf to my Valid OAuth Redirect URIs, but the Rails app would open the url as http://0.0.0.0:3000 and would therefore try to redirect to http://0.0.0.0:3000/asdf. After adding http://0.0.0.0:3000/asdf to the Valid OAuth Redirect URIs, or navigating to http://localhost:3000/asdf, it worked as expected.</p>


问:
Python: Converting Pseudo-code to code
I tried coding these lines:

```<code>copy the first {ceiling of} n/2 points of P to array Pleft
copy the same {ceiling of} n/2 points from Q to array Qleft
copy the remaining {floor of} n/2 points of P to array Pright
copy the same {floor of} n/2 points from Q to array Qright
m = P[ ({ceiling of} n/2) - 1].x
</code>```

And I got:

```<code>mid = len(P) / 2

Pl = P[:mid]
Ql = Q[:mid]
Pr = P[mid:]
Qr = Q[mid:]
m = P[:mid - 1].x
</code>```

But I do not know how to code this line:

```<code>copy all the points of array Q for which |x - m| < d into new array S[0..num - 1]
</code>```

Please help.

答:
EDIT:  Oops!  Forgot that m is a list!

This is what list comprehensions are for.  Because m is a list, you'll also need to make use of python's zip function.  The definition of the new array is:

```<code>S = [x for x, y in zip(Q, m) if abs(x - y) < d]
</code>```

You'll have to supply d.  Also, for completeness:

```<code>num = len(S)
</code>```

Title: Python: Converting Pseudo-code to code

Body:
I tried coding these lines:

copy the first {ceiling of} n/2 points of P to array Pleft
copy the same {ceiling of} n/2 points from Q to array Qleft
copy the remaining {floor of} n/2 points of P to array Pright
copy the same {floor of} n/2 points from Q to array Qright
m = P[ ({ceiling of} n/2) - 1].x

And I got:

mid = len(P) / 2

Pl = P[:mid]
Ql = Q[:mid]
Pr = P[mid:]
Qr = Q[mid:]
m = P[:mid - 1].x

But I do not know how to code this line:

copy all the points of array Q for which |x - m| < d into new array S[0..num - 1]

Please help.

Body:
EDIT:  Oops!  Forgot that m is a list!

This is what list comprehensions are for.  Because m is a list, you'll also need to make use of python's zip function.  The definition of the new array is:

S = [x for x, y in zip(Q, m) if abs(x - y) < d]

You'll have to supply d.  Also, for completeness:

num = len(S)


问:
Invert interpolation to give the variable associated with a desired interpolation function value
I am trying to invert an interpolated function using scipy's interpolate function. Let's say I create an interpolated function,

```<code>import scipy.interpolate as interpolate
interpolatedfunction = interpolated.interp1d(xvariable,data,kind='cubic')
</code>```

Is there some function that can find x when I specify a:

```<code>interpolatedfunction(x) == a
</code>```

In other words, "I want my interpolated function to equal a; what is the value of xvariable such that my function is equal to a?"

I appreciate I can do this with some numerical scheme, but is there a more straightforward method? What if the interpolated function is multivalued in xvariable?

答:
After creating an interpolated function interp_fn, you can find the value of x where interp_fn(x) == a by the roots of the function

```<code>interp_fn2 = lambda x: interp_fn(x) - a
</code>```

There are number of options to find the roots in scipy.optimize.  For instance, to use Newton's method with the initial value starting at 10:

```<code>from scipy import optimize

optimize.newton(interp_fn2, 10)
</code>```

Actual example

Create an interpolated function and then find the roots where fn(x) == 5

```<code>import numpy as np
from scipy import interpolate, optimize

x = np.arange(10)
y = 1 + 6*np.arange(10) - np.arange(10)**2
y2 = 5*np.ones_like(x)
plt.scatter(x,y)
plt.plot(x,y)
plt.plot(x,y2,'k-')
plt.show()
</code>```

```<code># create the interpolated function, and then the offset
# function used to find the roots

interp_fn = interpolate.interp1d(x, y, 'quadratic')
interp_fn2 = lambda x: interp_fn(x)-5

# to find the roots, we need to supply a starting value
# because there are more than 1 root in our range, we need
# to supply multiple starting values.  They should be
# fairly close to the actual root

root1, root2 = optimize.newton(interp_fn2, 1), optimize.newton(interp_fn2, 5)

root1, root2
# returns:
(0.76393202250021064, 5.2360679774997898)
</code>```

Body:
I am trying to invert an interpolated function using scipy's interpolate function. Let's say I create an interpolated function,

import scipy.interpolate as interpolate
interpolatedfunction = interpolated.interp1d(xvariable,data,kind='cubic')

Is there some function that can find x when I specify a:

interpolatedfunction(x) == a

In other words, "I want my interpolated function to equal a; what is the value of xvariable such that my function is equal to a?"

I appreciate I can do this with some numerical scheme, but is there a more straightforward method? What if the interpolated function is multivalued in xvariable?

Body:
After creating an interpolated function interp_fn, you can find the value of x where interp_fn(x) == a by the roots of the function

interp_fn2 = lambda x: interp_fn(x) - a

There are number of options to find the roots in scipy.optimize.  For instance, to use Newton's method with the initial value starting at 10:

from scipy import optimize

optimize.newton(interp_fn2, 10)

Actual example

Create an interpolated function and then find the roots where fn(x) == 5

import numpy as np
from scipy import interpolate, optimize

x = np.arange(10)
y = 1 + 6*np.arange(10) - np.arange(10)**2
y2 = 5*np.ones_like(x)
plt.scatter(x,y)
plt.plot(x,y)
plt.plot(x,y2,'k-')
plt.show()

# create the interpolated function, and then the offset
# function used to find the roots

interp_fn = interpolate.interp1d(x, y, 'quadratic')
interp_fn2 = lambda x: interp_fn(x)-5

# to find the roots, we need to supply a starting value
# because there are more than 1 root in our range, we need
# to supply multiple starting values.  They should be
# fairly close to the actual root

root1, root2 = optimize.newton(interp_fn2, 1), optimize.newton(interp_fn2, 5)

root1, root2
# returns:
(0.76393202250021064, 5.2360679774997898)


问:
How do you change the background color of the empty tab space in vim?
In vim, when you create a new tab, the tab bar appears at the top of the screen.  On the left are all your tabs, on the far right is an "X" for closing the tabs.  In between, there is "empty" space, that on my screen appears white.

I'll admit, I'm very picky about how my terminal looks, and this bright white bar at the top of the screen is distracting.  Is it possible to change this color to black, or maybe even gray?

答: That color is controlled by the current colorscheme. You can use :colorscheme to change schemes and find one you like (that has a better color for that area). You can see some sample schemes here (albeit without a tab bar shown).

ContentLicense: CC BY-SA 2.5


问:
Difference between String replace() and replaceAll()
What's the difference between java.lang.String 's replace() and replaceAll() methods,
other than later uses regex? For simple substitutions like, replace . with /  ,
is there any difference?

答:
Both replace() and replaceAll() replace all occurrences in the String.

Examples

I always find examples helpful to understand the differences.

replace()

Use replace() if you just want to replace some char with another char or some String with another String (actually CharSequence).

Example 1

Replace all occurrences of the character x with o.

```<code>String myString = "__x___x___x_x____xx_";

char oldChar = 'x';
char newChar = 'o';

String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_
</code>```

Example 2

Replace all occurrences of the string fish with sheep.

```<code>String myString = "one fish, two fish, three fish";

String target = "fish";
String replacement = "sheep";

String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep
</code>```

replaceAll()

Use replaceAll() if you want to use a regular expression pattern.

Example 3

Replace any number with an x.

```<code>String myString = "__1_6____3__6_345____0";

String regex = "\\d";
String replacement = "x";

String newString = myString.replaceAll(regex, replacement);
// __x_x____x__x_xxx____x
</code>```

Example 4

Remove all whitespace.

```<code>String myString = "   Horse         Cow\n\n   \r Camel \t\t Sheep \n Goat        ";

String regex = "\\s";
String replacement = "";

String newString = myString.replaceAll(regex, replacement);
// HorseCowCamelSheepGoat
</code>```

See also

Documentation

replace(char oldChar, char newChar)

replace(CharSequence target, CharSequence replacement)

replaceAll(String regex, String replacement)

replaceFirst(String regex, String replacement)

Regular Expressions

Tutorial

List of patterns

Body:
Both replace() and replaceAll() replace all occurrences in the String.

Examples

I always find examples helpful to understand the differences.

replace()

Use replace() if you just want to replace some char with another char or some String with another String (actually CharSequence).

Example 1

Replace all occurrences of the character x with o.

String myString = "__x___x___x_x____xx_";

char oldChar = 'x';
char newChar = 'o';

String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_

Example 2

Replace all occurrences of the string fish with sheep.

String myString = "one fish, two fish, three fish";

String target = "fish";
String replacement = "sheep";

String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep

replaceAll()

Use replaceAll() if you want to use a regular expression pattern.

Example 3

Replace any number with an x.

String myString = "__1_6____3__6_345____0";

String regex = "\\d";
String replacement = "x";

String newString = myString.replaceAll(regex, replacement);
// __x_x____x__x_xxx____x

Example 4

Remove all whitespace.

String myString = "   Horse         Cow\n\n   \r Camel \t\t Sheep \n Goat        ";

String regex = "\\s";
String replacement = "";

String newString = myString.replaceAll(regex, replacement);
// HorseCowCamelSheepGoat

See also

Documentation

replace(char oldChar, char newChar)

replace(CharSequence target, CharSequence replacement)

replaceAll(String regex, String replacement)

replaceFirst(String regex, String replacement)

Regular Expressions

Tutorial

List of patterns


问:
MySQL record between fixed date range
I have an small application which was build with CodeIgniter 3 and need to perform a report which will be converted to Chart.js. The report should be in yearly basis but at given specific date every month. The requirement are all data count must be from 4th to 3rd monthly. Like this:

For example January Report would be from 4th January to 3rd February, 4th February to 3rd March,... and so on.

I have created a MySQL query but I'm stuck on how to get the date too date. My Query are as follows:

```<code>SELECT DATE_FORMAT(odd_date_created, '%Y') as 'year',
DATE_FORMAT(odd_date_created, '%m') as 'month',
COUNT(odd_id) as 'total', status
FROM odd_data
WHERE status = $id and
GROUP BY DATE_FORMAT(odd_date_created, '%Y%m'), status
</code>```

I'm new to MySQl. Could somebody help me on this. I'm stuck where should I put the date to date query.

答:
Given the specification,  I think I would tempted to cheat it... subtract 3 days from the date.  Doing that, Jan 4 backs up to Jan 1,  Feb 3 backs up to Jan 31...   so those all end up as January.

```<code>  SELECT DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y') AS `year`
       , DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%m') AS `month`
       , ...
    FROM ...

   GROUP
      BY DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y')
       , DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%m')
</code>```

This falls apart if there's oddball ranges...  if it's not always the 4th and 3rd.

Title: MySQL record between fixed date range

Body:
I have an small application which was build with CodeIgniter 3 and need to perform a report which will be converted to Chart.js. The report should be in yearly basis but at given specific date every month. The requirement are all data count must be from 4th to 3rd monthly. Like this:

For example January Report would be from 4th January to 3rd February, 4th February to 3rd March,... and so on.

I have created a MySQL query but I'm stuck on how to get the date too date. My Query are as follows:

SELECT DATE_FORMAT(odd_date_created, '%Y') as 'year',
DATE_FORMAT(odd_date_created, '%m') as 'month',
COUNT(odd_id) as 'total', status
FROM odd_data
WHERE status = $id and
GROUP BY DATE_FORMAT(odd_date_created, '%Y%m'), status

I'm new to MySQl. Could somebody help me on this. I'm stuck where should I put the date to date query.

Body:
Given the specification,  I think I would tempted to cheat it... subtract 3 days from the date.  Doing that, Jan 4 backs up to Jan 1,  Feb 3 backs up to Jan 31...   so those all end up as January.

  SELECT DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y') AS `year`
       , DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%m') AS `month`
       , ...
    FROM ...

   GROUP
      BY DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%Y')
       , DATE_FORMAT(odd_date_created + INTERVAL -3 DAY, '%m')

This falls apart if there's oddball ranges...  if it's not always the 4th and 3rd.


问:
Ignore certain words when spell checking with Enchant
I am spell checking some files with Python Enchant, and want it to ignore proper nouns. The trade off between it correcting incorrectly spelled proper nouns and incorrectly 'correcting' ones it doesn't know seems too large (although any advice on this also aprreciated!)

This is my code, but at the moment it is still correcting the words in the NNP list.

```<code>chkr = SpellChecker("en_GB")

f = open('test_file.txt', 'r', encoding = 'utf-8')
text = f.read()
tagged = pos_tag(word_tokenize(text))
NNP = [(word) for word, tag in tagged if tag == 'NNP']
chkr.set_text(text)
for err in chkr:
    if err is word in NNP:
        err.ignore_always()
else:
    sug = err.suggest()[0]
    err.replace(sug)

corrected = chkr.get_text()
print (NNP)
print (corrected)
</code>```

In the output, for example, 'Boojum' is changed to Boomer even though it is in the NNP list.

Could someone point me in the right direction? I'm fairly new to Python. Thanks in advance.

答:
I figured this out. Had to tell it that the error words were stings so that it could compare them to the words in the NNP list. New code:

```<code>chkr = SpellChecker("en_GB")

for file in os.listdir(path):
        f = open(file, 'r', encoding = 'utf-8')
        text = f.read()
        tagged = pos_tag(word_tokenize(text))
        NNP = [word for word, tag in tagged if tag == 'NNP']
        chkr.set_text(text)
        for err in chkr:
            if str(err.word) in NNP:
                err.ignore_always()
            else:
                sug = chkr.suggest()
                if len(sug) is not 0:
                    err.replace(sug[0])

        corrected = chkr.get_text()
</code>```

Also corrected so that if Enchant doesn't have any suggestions, it will leave the error in place.

ContentLicense: CC BY-SA 4.0

Body:
I am spell checking some files with Python Enchant, and want it to ignore proper nouns. The trade off between it correcting incorrectly spelled proper nouns and incorrectly 'correcting' ones it doesn't know seems too large (although any advice on this also aprreciated!)

This is my code, but at the moment it is still correcting the words in the NNP list.

chkr = SpellChecker("en_GB")

f = open('test_file.txt', 'r', encoding = 'utf-8')
text = f.read()
tagged = pos_tag(word_tokenize(text))
NNP = [(word) for word, tag in tagged if tag == 'NNP']
chkr.set_text(text)
for err in chkr:
    if err is word in NNP:
        err.ignore_always()
else:
    sug = err.suggest()[0]
    err.replace(sug)

corrected = chkr.get_text()
print (NNP)
print (corrected)

In the output, for example, 'Boojum' is changed to Boomer even though it is in the NNP list.

Could someone point me in the right direction? I'm fairly new to Python. Thanks in advance.

Body:
I figured this out. Had to tell it that the error words were stings so that it could compare them to the words in the NNP list. New code:

chkr = SpellChecker("en_GB")

for file in os.listdir(path):
        f = open(file, 'r', encoding = 'utf-8')
        text = f.read()
        tagged = pos_tag(word_tokenize(text))
        NNP = [word for word, tag in tagged if tag == 'NNP']
        chkr.set_text(text)
        for err in chkr:
            if str(err.word) in NNP:
                err.ignore_always()
            else:
                sug = chkr.suggest()
                if len(sug) is not 0:
                    err.replace(sug[0])

        corrected = chkr.get_text()

Also corrected so that if Enchant doesn't have any suggestions, it will leave the error in place.


问:
Python - return intersection of two arrays
I have two arrays and I am trying to return a new array that equals the intersection of my original two arrays. The two original arrays should be of the same length. For example, if I have:

arr1 = np.array([(255, 255, 255), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get:

intersectedArr = ([(255, 255, 255), (255, 255, 255])

However, if I have:

arr1 = np.array([(100, 100, 100), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get

([(255, 255, 255)])

So far i've tried:

intersectedArr = np.intersect1d(arr1, arr2)

but this returns [255] instead of the expected ([(255, 255, 255)])

Can someone help? Thanks in advance!

答:
NOTE: This assumes [a, b, c] and [b, c, a] gives [a, b, c], that is the order of elements is ignored.

OK, I've done a little experimenting and this might be what you are after. Given:

```<code>arr1a = np.array([(255, 255, 255), (255, 255, 255)])
arr1b = np.array([(100, 100, 100), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
</code>```

Then we can find an intersection with:

```<code>np.array([item in arr2 for item in arr1a])
</code>```

ie, for each element in arr1a, check to see it appears in arr2 also. This gives a result of:

```<code>>>> array([ True,  True], dtype=bool)
</code>```

Similarly:

```<code>np.array([item in arr2 for item in arr1b])
>>> array([False,  True], dtype=bool)
</code>```

Now, we can use this result to pick the common values from the original lists:

```<code>mask = np.array([item in arr2 for item in arr1a])
arr1a[mask]
>>> array([[255, 255, 255],
           [255, 255, 255]])
</code>```

And:

```<code>mask = np.array([item in arr2 for item in arr1b])
arr1b[mask]
>>> array([[255, 255, 255]])
</code>```

Body:
NOTE: This assumes [a, b, c] and [b, c, a] gives [a, b, c], that is the order of elements is ignored.

OK, I've done a little experimenting and this might be what you are after. Given:

arr1a = np.array([(255, 255, 255), (255, 255, 255)])
arr1b = np.array([(100, 100, 100), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])

Then we can find an intersection with:

np.array([item in arr2 for item in arr1a])

ie, for each element in arr1a, check to see it appears in arr2 also. This gives a result of:

>>> array([ True,  True], dtype=bool)

Similarly:

np.array([item in arr2 for item in arr1b])
>>> array([False,  True], dtype=bool)

Now, we can use this result to pick the common values from the original lists:

mask = np.array([item in arr2 for item in arr1a])
arr1a[mask]
>>> array([[255, 255, 255],
           [255, 255, 255]])

And:

mask = np.array([item in arr2 for item in arr1b])
arr1b[mask]
>>> array([[255, 255, 255]])


问:
A/B testing a controller method?
I recently worked on refactoring a class for my company's web site which in essence assembles a user profile.  Say the old class is called User::Profile::OldImpl and my refactored version is User::Profile::NewImpl.  The two classes have exactly the same public interface and are expected to behave identically.  The new class is just much easier to read and more efficient--or such was my intention.

I changed the place where the profiler is instantiated from this:

```<code>profile = User::Profile::OldImpl.new(...)
</code>```

...to this:

```<code>profile = User::Profile::NewImpl.new(...)
</code>```

During code review, my reviewer flagged this line and told me to add an A/B test here.  By this I suppose he means to sometimes use the old class and sometimes use the new class.

I'm mightily confused.  I understand "A/B testing" to mean showing different versions of a web page to end users and tracking which version generates the best response, but my code is meant to be invisible to end users--it doesn't touch the view at all.  I've searched around and haven't been able to find a discussion of A/B testing that relates to backend code like mine, and I can't imagine why my change merits an A/B test when the great majority of checkins don't.

The review was submitted near end-of-day Friday, and I'm obviously going to chat with the reviewer first thing tomorrow, but I was hoping to first learn from the SO community whether A/B testing can legitimately be applied to a change like mine, and if so, how.

答: You reviewer is worried that despite no visible changes, your implementation may affect some important business metrics. What he wants you to do is to prove empirically that there's in fact no change from the user perspective, i.e. that your A/B test is actually an A/A test. I'd ask him what KPIs he has in mind.</p>

Title: A/B testing a controller method?

Body:
I recently worked on refactoring a class for my company's web site which in essence assembles a user profile.  Say the old class is called User::Profile::OldImpl and my refactored version is User::Profile::NewImpl.  The two classes have exactly the same public interface and are expected to behave identically.  The new class is just much easier to read and more efficient--or such was my intention.

I changed the place where the profiler is instantiated from this:

profile = User::Profile::OldImpl.new(...)

...to this:

profile = User::Profile::NewImpl.new(...)

During code review, my reviewer flagged this line and told me to add an A/B test here.  By this I suppose he means to sometimes use the old class and sometimes use the new class.

I'm mightily confused.  I understand "A/B testing" to mean showing different versions of a web page to end users and tracking which version generates the best response, but my code is meant to be invisible to end users--it doesn't touch the view at all.  I've searched around and haven't been able to find a discussion of A/B testing that relates to backend code like mine, and I can't imagine why my change merits an A/B test when the great majority of checkins don't.

The review was submitted near end-of-day Friday, and I'm obviously going to chat with the reviewer first thing tomorrow, but I was hoping to first learn from the SO community whether A/B testing can legitimately be applied to a change like mine, and if so, how.


问:
Enter Insert/Edit mode of CLion IDE
New to CLion, not sure if its just me, but everytime I type, the "Search for" bar appears in the Project directory left side bar. I am unable to type anything into the opened file. The caret does not even appear on the file. It's like when using Vim, but you're not in Insert mode. I have no idea how to go and start typing into the IDE. Any recommendations to how to use this thing? </p>

答: I know it's painful, but just restart the IDE. That's what I did and it works now.</p>

Title: Enter Insert/Edit mode of CLion IDE


问:
Creating a csv file from a dictionary
I have a dictionary like this:

```<code>culture= {13298341: [18.81,1155,'09-10-06',"['Africa', 'books', 'storytelling',
          'writing']", 'The danger of a single story','Chimamanda Ngozi'],

          14689301: [21.26,970,'06-09-25',"['TED Brain Trust', 'brain', 'evolution']",
          'The surprising science of happiness','Dan Gilbert']}
</code>```

Which each key has multiple values.
How can I store this dictionary in a new csv file in a way that each key and each value be in one separated column?

The result should be a csv file like this:

```<code> views    duration   comments  Published_date               tags                                title                              speaker
13298341   18.81       1155       09-10-06    ['Africa', 'books', 'storytelling']        The danger of a single story          Chimamanda Ngozi
14689301   21.26       970        06-09-25    ['TED Brain Trust', 'brain', 'evolution']  The surprising science of happiness   Dan Gilbert
</code>```

答:
First, I removed the double-quotes around your list. I don't think they're needed, so hopefully that doesn't cause undue issues.

Second, hope you're okay with a pandas-centric solution.

```<code>import pandas as pd

culture= {13298341: [18.81, 1155, '09-10-06', ['Africa', 'books', 'storytelling', 'writing'],
                 'The danger of a single story','Chimamanda Ngozi'],

      14689301: [21.26, 970, '06-09-25', ['TED Brain Trust', 'brain', 'evolution'],
      'The surprising science of happiness','Dan Gilbert']}

df = pd.DataFrame(culture).transpose().reset_index()

df.columns = ['views', 'duration', 'comments', 'Published_date', 'tags', 'title', 'speaker']

df.set_index('views', inplace = True)
df.to_csv('df.csv')
</code>```

Third, I'd recommend an index other than "views". You can get this by deleting the df.set_index(...) line in the above.

ETA: Just checked and it works with the double quotes in there. I don't think it affects the CSV output. However, with the quotes, pandas stores the data as a string; without the quotes, it stores them as a list, which means you can access them via indexing. Cool.

Title: Creating a csv file from a dictionary

Body:
I have a dictionary like this:

culture= {13298341: [18.81,1155,'09-10-06',"['Africa', 'books', 'storytelling',
          'writing']", 'The danger of a single story','Chimamanda Ngozi'],

          14689301: [21.26,970,'06-09-25',"['TED Brain Trust', 'brain', 'evolution']",
          'The surprising science of happiness','Dan Gilbert']}

Which each key has multiple values.
How can I store this dictionary in a new csv file in a way that each key and each value be in one separated column?

The result should be a csv file like this:

 views    duration   comments  Published_date               tags                                title                              speaker
13298341   18.81       1155       09-10-06    ['Africa', 'books', 'storytelling']        The danger of a single story          Chimamanda Ngozi
14689301   21.26       970        06-09-25    ['TED Brain Trust', 'brain', 'evolution']  The surprising science of happiness   Dan Gilbert

Body:
First, I removed the double-quotes around your list. I don't think they're needed, so hopefully that doesn't cause undue issues.

Second, hope you're okay with a pandas-centric solution.

import pandas as pd

culture= {13298341: [18.81, 1155, '09-10-06', ['Africa', 'books', 'storytelling', 'writing'],
                 'The danger of a single story','Chimamanda Ngozi'],

      14689301: [21.26, 970, '06-09-25', ['TED Brain Trust', 'brain', 'evolution'],
      'The surprising science of happiness','Dan Gilbert']}

df = pd.DataFrame(culture).transpose().reset_index()

df.columns = ['views', 'duration', 'comments', 'Published_date', 'tags', 'title', 'speaker']

df.set_index('views', inplace = True)
df.to_csv('df.csv')

Third, I'd recommend an index other than "views". You can get this by deleting the df.set_index(...) line in the above.

ETA: Just checked and it works with the double quotes in there. I don't think it affects the CSV output. However, with the quotes, pandas stores the data as a string; without the quotes, it stores them as a list, which means you can access them via indexing. Cool.


问:
Why is the SlowEquals function important to compare hashed passwords?
I recently read an article on password hashing and salting wherein it was explained (under "How does the SlowEquals code work?") that a SlowEquals function must be used to compare the hash of the password entered to the hash of the password in the database.

As I understand it the SlowEquals function is used because it uses XOR instead of == and as a result will check every character in the both strings rather than failing on the first non-matching characters.

There are two things I don't understand:

Why will the XOR continue to check the string after a fail condition is reached.

If the main idea is to not give the attacker any useful information while trying to crack a password, wouldn't a sleep() function with a randomly generated time do the trick just fine?

答:
If there is no slowEquals.

Let’s consider the compute compares two chararters using 2 seconds(more faster in true compute, but a large amount of testing could work), and we use  1234554321 as the password.
The attacker uses 0000000000 to attempt. Because we don’t use slowEquals function, the comparison takes only 2 seconds because of 0!=1,
so when attacker knows the “2 seconds”, he will change the ‘0’ to another one until using “1000000000” then the server takes 4 seconds.


答:
Not sure how big your arrays will get, but if they remain fairly small, this could work:</p>

```<code>import numpy as np

arr1 = np.array([(255, 255, 255), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
intersectedArr = []

for a1, a2 in zip(arr1, arr2):
    if np.array_equal(a1, a2):
        intersectedArr.append(a1)
print(np.array(intersectedArr))

arr1 = np.array([(100, 100, 100), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
intersectedArr = []

for a1, a2 in zip(arr1, arr2):
    if np.array_equal(a1, a2):
        intersectedArr.append(a1)
print(np.array(intersectedArr))
</code>```

Title: Python - return intersection of two arrays

Body:
I have two arrays and I am trying to return a new array that equals the intersection of my original two arrays. The two original arrays should be of the same length. For example, if I have:

arr1 = np.array([(255, 255, 255), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get:

intersectedArr = ([(255, 255, 255), (255, 255, 255])

However, if I have:

arr1 = np.array([(100, 100, 100), (255, 255, 255)])

arr2 = np.array([(255, 255, 255), (255, 255, 255)])

I should get

([(255, 255, 255)])

So far i've tried:

intersectedArr = np.intersect1d(arr1, arr2)

but this returns [255] instead of the expected ([(255, 255, 255)])

Can someone help? Thanks in advance!

Body:
Not sure how big your arrays will get, but if they remain fairly small, this could work:

import numpy as np

arr1 = np.array([(255, 255, 255), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
intersectedArr = []

for a1, a2 in zip(arr1, arr2):
    if np.array_equal(a1, a2):
        intersectedArr.append(a1)
print(np.array(intersectedArr))

arr1 = np.array([(100, 100, 100), (255, 255, 255)])
arr2 = np.array([(255, 255, 255), (255, 255, 255)])
intersectedArr = []

for a1, a2 in zip(arr1, arr2):
    if np.array_equal(a1, a2):
        intersectedArr.append(a1)
print(np.array(intersectedArr))


问:
How can I execute a command inside another folder and return to original directory?
I use this command to make inside a folder:

```<code>cd build/ && make
</code>```

But I want to return to original directory after the command

I tried this:

```<code>cd build/ && make && cd ..
</code>```

But this doesn't work. How can I do it? Would help in quick testing...

答:
You can use below commands</p>

```<code>cd build;
make;
cd -
</code>```

Body:
I use this command to make inside a folder:

cd build/ && make

But I want to return to original directory after the command

I tried this:

cd build/ && make && cd ..

But this doesn't work. How can I do it? Would help in quick testing...

Body:
You can use below commands

cd build;
make;
cd -


问:
How to check whether input value is integer or float?
How to check whether input value is integer or float?

Suppose 312/100=3.12
Here i need check whether 3.12 is a float value or integer value, i.e., without any decimal place value.

答:
You should check that fractional part of the number is 0.
Use

```<code>x==Math.ceil(x)
</code>```

or

```<code>x==Math.round(x)
</code>```

or something like that

Body:
You should check that fractional part of the number is 0.
Use

x==Math.ceil(x)

or

x==Math.round(x)

or something like that


问:
422 (Unprocessable Entity) POST using rails
I just started using ruby on rails a few days ago. I am trying to send data from html tags to a ruby function using ajax.

Here is the error that I am getting:

```<code>POST http://localhost:3000/ajax/ounces 422 (Unprocessable Entity)
</code>```

I am calling the javascript function using an html button onclick attribute:

```<code><button class="btn btn-primary" style="width:24%;" type="button" onclick="ounces_fn()">Fluid Ounces</button>
</code>```

Here is my ajax call using javascript:

```<code><script>
    function ounces_fn() {
        var meas1 = $("#m1").val().replace( /^\D+/g, '');
        var meas2 = $("#m2").val().replace( /^\D+/g, '');
        var meas3 = $("#m3").val().replace( /^\D+/g, '');
        var meas4 = $("#m4").val().replace( /^\D+/g, '');
        $.post('/ajax/ounces', {
             num1: meas1,
             num2: meas2,
             num3: meas3,
             num4: meas4
        }, function(data) {
             alert("success!");
             $("m1").val(data[0].result.toString() + "oz.");
             $("m2").val(data[1].result.toString() + "oz.");
             $("m3").val(data[2].result.toString() + "oz.");
             $("m4").val(data[3].result.toString() + "oz.");
        });
    }
</script>
</code>```

Here is my controller:

```<code>post '/ajax/ounces' => 'welcome#ajax_ounces'
</code>```

And here is my ruby function:

```<code>def ajax_ounces
    numArray = [params["num1"].to_f, params["num2"].to_f, params["num3"].to_f, params["num4"].to_f]
    returnArray = Array.new(4);
    i = 0

    while i < numArray.length do
        returnArray[i] = numArray[i] / 30
        i += 1
    end

    respond_to do |format|
          format.json {render :json => {:result => returnArray}}
    end
end
</code>```

I checked many different sites, but I could not relate any of it to what I was working on. I appreciate any help you can give. Thank you.

答:
The error could cause because of the CSRF token.

Try to add this line on top of controller.

```<code>skip_before_action :verify_authenticity_token
</code>```

Body:
I just started using ruby on rails a few days ago. I am trying to send data from html tags to a ruby function using ajax.

Here is the error that I am getting:

POST http://localhost:3000/ajax/ounces 422 (Unprocessable Entity)

I am calling the javascript function using an html button onclick attribute:

<button class="btn btn-primary" style="width:24%;" type="button" onclick="ounces_fn()">Fluid Ounces</button>

Here is my ajax call using javascript:

Here is my controller:

post '/ajax/ounces' => 'welcome#ajax_ounces'

And here is my ruby function:

def ajax_ounces
    numArray = [params["num1"].to_f, params["num2"].to_f, params["num3"].to_f, params["num4"].to_f]
    returnArray = Array.new(4);
    i = 0

    while i < numArray.length do
        returnArray[i] = numArray[i] / 30
        i += 1
    end

    respond_to do |format|
          format.json {render :json => {:result => returnArray}}
    end
end

I checked many different sites, but I could not relate any of it to what I was working on. I appreciate any help you can give. Thank you.

Body:
The error could cause because of the CSRF token.

Try to add this line on top of controller.

skip_before_action :verify_authenticity_token


问:
Running Google Cloud SQL Proxy on Raspberry
I'm getting an error while trying to connect raspberry running ubuntu mate to my Google Cloud SQL instance.

These are the step I did to install:

```<code>git clone https://github.com/GoogleCloudPlatform/cloudsql-proxy
cd cloudsql-proxy/
sudo sh download_proxy.sh
</code>```

My instance is configured this way (I deleted some characters in the image and in the code):

I didn't set the network because I'll be using proxy

Then I download into the same folder my JSON key.

```<code>wget https://drive.google.com/file/d/my_key.json
</code>```

And the start the proxy

```<code>sudo ./cloud_sql_proxy -instances=be   -     21:us-central1:be   =tcp:3306 \
                  -credential_file=./my_key.json &
</code>```

But I'm getting the error:

pi@pi:~/cloudsql-proxy$ ./cloud_sql_proxy: 1: ./cloud_sql_proxy:
  Syntax error: ")" unexpected

I've tried removing the .json and I was getting the same error before without credential, I think that the problem is in the setup.

My dir ls is:

Any help is appreciated :)

答:
download_proxy.sh downloads the proxy compiled for the amd64 architecture of CPU (aka x86_64). Your raspberry Pi has a ARM CPU, so this binary cannot run on your machine.

Google does not provide pre-build ARM versions of the proxy. I don't even know if it is able to build on ARM CPU. If it is possible, this is how you must do it:

Install go, e.g. with apt-get install golang

Setup a GOPATH, as per https://github.com/golang/go/wiki/GOPATH

Run go get github.com/GoogleCloudPlatform/cloudsql-proxy/cmd/cloud_sql_proxy

Run the proxy with $GOPATH/cloud_sql_proxy -instances=...

Body:
I'm getting an error while trying to connect raspberry running ubuntu mate to my Google Cloud SQL instance.

These are the step I did to install:

git clone https://github.com/GoogleCloudPlatform/cloudsql-proxy
cd cloudsql-proxy/
sudo sh download_proxy.sh

My instance is configured this way (I deleted some characters in the image and in the code):

I didn't set the network because I'll be using proxy

Then I download into the same folder my JSON key.

wget https://drive.google.com/file/d/my_key.json

And the start the proxy

sudo ./cloud_sql_proxy -instances=be   -     21:us-central1:be   =tcp:3306 \
                  -credential_file=./my_key.json &

But I'm getting the error:

pi@pi:~/cloudsql-proxy$ ./cloud_sql_proxy: 1: ./cloud_sql_proxy:
  Syntax error: ")" unexpected

I've tried removing the .json and I was getting the same error before without credential, I think that the problem is in the setup.

My dir ls is:

Any help is appreciated :)


问:
Java String split() method returns unexpected length of string array
```<code>String source = "s5 g900 sued_p033178672__.____ ____.__4.5cm"; // __ __ is not a delimiter

String deli = "__.__"; // this is my separator string to split target

String[] splittedString = source.split(deli, -1);

splittedString.length; // I expected 3 but was 4
</code>```

what should I do to split target string properly?

答:
String.split() takes a regular expression as its input. Therefore, . matches any characters, so "__ __" is treated as a delimiter as well.

To make it matches only "__.__", you need to escape the special character ., i.e.,

```<code>String deli = "__\\.__";
</code>```

Body:
String source = "s5 g900 sued_p033178672__.____ ____.__4.5cm"; // __ __ is not a delimiter

String deli = "__.__"; // this is my separator string to split target

String[] splittedString = source.split(deli, -1);

splittedString.length; // I expected 3 but was 4

what should I do to split target string properly?

Body:
String.split() takes a regular expression as its input. Therefore, . matches any characters, so "__ __" is treated as a delimiter as well.

To make it matches only "__.__", you need to escape the special character ., i.e.,

String deli = "__\\.__";


问:
How to Clear Office Clipboard with VBA
How would you clear the Microsoft Office Clipboard using VBA, specifically Word VBA?

I am copying a lot of data at time into the clipboard and don't want excessive data kept in the Clipboard.

答:
Here's a solution that worked for me.  This is based on a post by by Zack Barresse on VBAexpress.com:

```<code>Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Public Sub ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Sub
</code>```

After copying this function to your VBA project, use ClearClipboard to clear it.

Title: How to Clear Office Clipboard with VBA

Body:
Here's a solution that worked for me.  This is based on a post by by Zack Barresse on VBAexpress.com:

Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Public Sub ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Sub

After copying this function to your VBA project, use ClearClipboard to clear it.


问:
Check product availability on form - return stock.quants - Odoo v8
I need to check on my object lines for the locations on which the products are available, this are my classes:

```<code>class bsi_production_order(models.Model):
    _name = 'bsi.production.order'

    @api.model
    def create(self, vals):
        if vals.get('name', 'New') == 'New':
            if vals.get('production_type') == 'budgeted':
                vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.budgeted') or '/'
            elif vals.get('production_type') == 'nonbudgeted':
                vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.non_budgeted') or '/'
            elif vals.get('production_type') == 'direct':
                vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.direct') or '/'
        return super(bsi_production_order, self).create(vals)

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    date = fields.Date(string="Production Date")
    production_type = fields.Selection([
        ('budgeted','Budgeted'),
        ('nonbudgeted','Non Budgeted'),
        ('direct','Direct Order'),
    ], string='Type of Order', index=True,
    track_visibility='onchange', copy=False,
    help=" ")
    notes = fields.Text(string="Notes")
    order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True)
    print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders")
</code>```

On order_lines I should know what product quantity is available by returning the view with all the quants from this product (isbn)

This is bsi.production.line object (referred by order_lines One2many field):

```<code>class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    product_template = fields.Many2one('product.template', string="Product")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func") #

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.qty or self.consumed_qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)
</code>```

I've taken the Qty on Hand method from product_template as inspiration, so this is my method (on bsi.production.order):

```<code>@api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
    isbn = []
    product_variant_ids = isbn.search(domain)
    for prodtmpl in self.order_lines:
        isbn += [x.id for x in prodtmpl.product_variant_ids]
    return isbn

@api.one
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    act_obj = self.env['ir.actions.act_window']
    result = mod_obj.xmlid_to_res_id(name, raise_if_not_found=True)
    result = act_obj.read([result])[0]
    return result

@api.multi
def action_open_isbn(self):
    isbn = self._get_products()
    result = self._get_act_window_dict('stock.product_open_quants')
    result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn)) + "])]"
    result['context'] = "{'search_default_locationgroup': 1, 'search_default_internal_loc': 1}"
    return result
</code>```

Right now, it throws me this:

```<code>Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 948, in call_button
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 399, in old_api
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1045, in action_open_isbn
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1030, in _get_products
AttributeError: 'list' object has no attribute 'search'
</code>```

The error comes on this line product_variant_ids = isbn.search(domain), I know it's kind of weird, but I need to define this since product_variant_ids isn't defined on my method, also, I need to check this on product.product model, not product.template.

How can I adapt this method accordingly?

EDIT

I've tried @afwanwh solution, but now _get_act_window_dict method throws me this:

```<code>Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 948, in call_button
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 399, in old_api
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1669, in action_open_isbn
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 266, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1663, in _get_act_window_dict
IndexError: list index out of range
</code>```

I think it's because of the decorator, but I'm not sure, this method originally looked like this:

```<code>def _get_act_window_dict(self, cr, uid, name, context=None):
    mod_obj = self.pool.get('ir.model.data')
    act_obj = self.pool.get('ir.actions.act_window')
    result = mod_obj.xmlid_to_res_id(cr, uid, name, raise_if_not_found=True)
    result = act_obj.read(cr, uid, [result], context=context)[0]
    return result
</code>```

答:
I think, you have to do this:

```<code>@api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
    isbn = self.env['product.product']
    for prodtmpl in self.order_lines:
        isbn |= prodtmpl.isbn
    return isbn
</code>```

and this line in your method action_open_isbn

```<code>result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"
</code>```

[UPDATE] Second error:

```<code>@api.model
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    result = mod_obj.xmlid_to_object(name)
    if not result:
        # this is just fallback if module stock is not installed
        # make sure you installed module stock and give dependency in your module
        result = {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'stock.quant',
            'name': 'Stock On Hand',
            'type': 'ir.actions.act_window',
        }
    else:
        result = result[0].read()[0]
    return result
</code>```

Body:
I need to check on my object lines for the locations on which the products are available, this are my classes:

class bsi_production_order(models.Model):
    _name = 'bsi.production.order'

    @api.model
    def create(self, vals):
        if vals.get('name', 'New') == 'New':
            if vals.get('production_type') == 'budgeted':
                vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.budgeted') or '/'
            elif vals.get('production_type') == 'nonbudgeted':
                vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.non_budgeted') or '/'
            elif vals.get('production_type') == 'direct':
                vals['name'] = self.env['ir.sequence'].next_by_code('bsi.production.direct') or '/'
        return super(bsi_production_order, self).create(vals)

    name = fields.Char('Reference', required=True, index=True, copy=False, readonly='True', default='New')
    date = fields.Date(string="Production Date")
    production_type = fields.Selection([
        ('budgeted','Budgeted'),
        ('nonbudgeted','Non Budgeted'),
        ('direct','Direct Order'),
    ], string='Type of Order', index=True,
    track_visibility='onchange', copy=False,
    help=" ")
    notes = fields.Text(string="Notes")
    order_lines = fields.One2many('bsi.production.order.lines', 'production_order', states={'finished': [('readonly', True)], 'cancel': [('readonly', True)]}, string="Order lines", copy=True)
    print_orders = fields.One2many('bsi.print.order', 'production_orders', string="Print Orders")

On order_lines I should know what product quantity is available by returning the view with all the quants from this product (isbn)

This is bsi.production.line object (referred by order_lines One2many field):

class bsi_production_order_lines(models.Model):
    _name = 'bsi.production.order.lines'

    production_order = fields.Many2one('bsi.production.order', string="Production Orders")
    isbn = fields.Many2one('product.product', string="ISBN", domain="[('is_isbn', '=', True)]")
    qty = fields.Float(string="Quantity")
    product_template = fields.Many2one('product.template', string="Product")
    consumed_qty = fields.Float(string="Consumed quantity")
    remaining_qty = fields.Float(string="Remaining quantity", compute="_remaining_func") #

    @api.onchange('qty', 'consumed_qty')
    def _remaining_func(self):
        if self.qty or self.consumed_qty:
            self.remaining_qty = self.qty +(-self.consumed_qty)

I've taken the Qty on Hand method from product_template as inspiration, so this is my method (on bsi.production.order):

@api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
    isbn = []
    product_variant_ids = isbn.search(domain)
    for prodtmpl in self.order_lines:
        isbn += [x.id for x in prodtmpl.product_variant_ids]
    return isbn

@api.one
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    act_obj = self.env['ir.actions.act_window']
    result = mod_obj.xmlid_to_res_id(name, raise_if_not_found=True)
    result = act_obj.read([result])[0]
    return result

@api.multi
def action_open_isbn(self):
    isbn = self._get_products()
    result = self._get_act_window_dict('stock.product_open_quants')
    result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn)) + "])]"
    result['context'] = "{'search_default_locationgroup': 1, 'search_default_internal_loc': 1}"
    return result

Right now, it throws me this:

Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 948, in call_button
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 399, in old_api
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1045, in action_open_isbn
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1030, in _get_products
AttributeError: 'list' object has no attribute 'search'

The error comes on this line product_variant_ids = isbn.search(domain), I know it's kind of weird, but I need to define this since product_variant_ids isn't defined on my method, also, I need to check this on product.product model, not product.template.

How can I adapt this method accordingly?

EDIT

I've tried @afwanwh solution, but now _get_act_window_dict method throws me this:

Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 546, in _handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 583, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 319, in _call_function
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\service\model.py", line 118, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 316, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 812, in __call__
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\http.py", line 412, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 948, in call_button
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\web\controllers\main.py", line 936, in _call_kw
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 268, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 399, in old_api
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1669, in action_open_isbn
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\.\openerp\api.py", line 266, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20170914\server\openerp\addons\bsi\models\models.py", line 1663, in _get_act_window_dict
IndexError: list index out of range

I think it's because of the decorator, but I'm not sure, this method originally looked like this:

def _get_act_window_dict(self, cr, uid, name, context=None):
    mod_obj = self.pool.get('ir.model.data')
    act_obj = self.pool.get('ir.actions.act_window')
    result = mod_obj.xmlid_to_res_id(cr, uid, name, raise_if_not_found=True)
    result = act_obj.read(cr, uid, [result], context=context)[0]
    return result

Body:
I think, you have to do this:

@api.depends('order_lines', 'order_lines.isbn')
def _get_products(self):
    isbn = self.env['product.product']
    for prodtmpl in self.order_lines:
        isbn |= prodtmpl.isbn
    return isbn

and this line in your method action_open_isbn

result['domain'] = "[('isbn','in',[" + ','.join(map(str, isbn.ids)) + "])]"

[UPDATE] Second error:

@api.model
def _get_act_window_dict(self, name):
    mod_obj = self.env['ir.model.data']
    result = mod_obj.xmlid_to_object(name)
    if not result:
        # this is just fallback if module stock is not installed
        # make sure you installed module stock and give dependency in your module
        result = {
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'stock.quant',
            'name': 'Stock On Hand',
            'type': 'ir.actions.act_window',
        }
    else:
        result = result[0].read()[0]
    return result


问:
Transforming CSV to multiple formats using python
I have a CSV file which needs to be transformed for two different purposes.

for Event booklet printing ( Day wise schedule sorted by time)
16/11/2017 (Thursday)
Time, Vocal/Violin/Mrudagam ( If Event is 'Vocal')
Time, Dance/Violin/Mrudangam (If Event is 'Dance')
Time, Drama  ( if Event is 'Drama')

for Firebase upload ( JSON )

Date,Time,Event,Vocal,Violin,Mrudangam,Ghatam,Kanjira,Bharatanatyam,Dance,Flute, Drama

Not all columns will have values for all rows.  For example, if the event is a 'VOCAL' then only 'Vocal', 'Violin' and 'Mrudangam' will have values.

I read the CSV file and sort the same using

```<code>with open(args.eventfile,'r') as csvfile:
    eventreader = csv.DictReader(csvfile, delimiter=",")
    #sortedlist = sorted(eventreader, key=lambda row:(row['Date'],row['Time']), reverse=False)
    sortedlist = sorted(eventreader, key=lambda each_dict: (datetime.strptime(each_dict['Date'], '%m/%d/%Y'),
                          datetime.strptime(each_dict['Time'], '%I:%M %p')))
</code>```

and then process every row, like so,

```<code>def form_event_string(event):
    fevent=""
    print("formatting event: " + event['Event'])
    if event['Event'] == 'VOCAL':
        fevent = "{Vocal}/{Violin}/{Veena}/{Mrudangam}/{Ghatam}/{Kanjira}/{Morsing}/{Flute}/{Other}/{Venue}".format(**event)
    elif event['Event'] == 'VIOLIN':
        fevent = "{Violin}/{Mrudangam}/{Ghatam}/{Kanjira}".format(**event)
    elif event['Event'] == 'VEENA':
        fevent = "{Veena}/{Flute}/{Violin}/{Mrudangam}/{Ghatam}/{Kanjira}/{Morsing}/{GottuVadhyam}".format(**event)
    elif event['Event'] == 'GHATAM':
        fevent = "{Ghatam}/{Violin}/{Mrudangam}/{Kanjira}/{Morsing}".format(**event)
    else event['Event'] == 'BHARATANATYAM':
        fevent = "{Bharatanatyam}".format(**event)
return fevent
</code>```

and keep appending this string into a CSV file.

My question is - is there a different way to get this done?  Any help is appreciated.

答:
There is a much better way! Pandas! just transform the csv as a data frame and you can create a column using a custom function with new_column = df['column'].apply(function). Afterwards you can save the df as a json.
http://pandas.pydata.org</p>

Body:
I have a CSV file which needs to be transformed for two different purposes.

for Event booklet printing ( Day wise schedule sorted by time)
16/11/2017 (Thursday)
Time, Vocal/Violin/Mrudagam ( If Event is 'Vocal')
Time, Dance/Violin/Mrudangam (If Event is 'Dance')
Time, Drama  ( if Event is 'Drama')

for Firebase upload ( JSON )

Date,Time,Event,Vocal,Violin,Mrudangam,Ghatam,Kanjira,Bharatanatyam,Dance,Flute, Drama

Not all columns will have values for all rows.  For example, if the event is a 'VOCAL' then only 'Vocal', 'Violin' and 'Mrudangam' will have values.

I read the CSV file and sort the same using

with open(args.eventfile,'r') as csvfile:
    eventreader = csv.DictReader(csvfile, delimiter=",")
    #sortedlist = sorted(eventreader, key=lambda row:(row['Date'],row['Time']), reverse=False)
    sortedlist = sorted(eventreader, key=lambda each_dict: (datetime.strptime(each_dict['Date'], '%m/%d/%Y'),
                          datetime.strptime(each_dict['Time'], '%I:%M %p')))

and then process every row, like so,

def form_event_string(event):
    fevent=""
    print("formatting event: " + event['Event'])
    if event['Event'] == 'VOCAL':
        fevent = "{Vocal}/{Violin}/{Veena}/{Mrudangam}/{Ghatam}/{Kanjira}/{Morsing}/{Flute}/{Other}/{Venue}".format(**event)
    elif event['Event'] == 'VIOLIN':
        fevent = "{Violin}/{Mrudangam}/{Ghatam}/{Kanjira}".format(**event)
    elif event['Event'] == 'VEENA':
        fevent = "{Veena}/{Flute}/{Violin}/{Mrudangam}/{Ghatam}/{Kanjira}/{Morsing}/{GottuVadhyam}".format(**event)
    elif event['Event'] == 'GHATAM':
        fevent = "{Ghatam}/{Violin}/{Mrudangam}/{Kanjira}/{Morsing}".format(**event)
    else event['Event'] == 'BHARATANATYAM':
        fevent = "{Bharatanatyam}".format(**event)
return fevent

and keep appending this string into a CSV file.

My question is - is there a different way to get this done?  Any help is appreciated.


问:
Make ajax POST and return JSON in Rails
I'm trying to make an AJAX POST request to one of my routes and return some JSON, but I'm running into an issue where the JSON is not being returned and a page is rendering instead like a GET request. Here is my code:

View

```<code><%= form_with url: users_add_skill_path, id: "skills-form", format: 'json' do |f| %>
  <%= f.text_field :skill, placeholder: "Submit your skill" %>
  <%= f.submit "Submit Skill" %>
<% end %>
</code>```

This becomes in HTML:

```<code><form id="skills-form" action="/users/add_skill" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="token_hereadnfjahbsdkfjabsd">
    <label for="skill">Skill</label>
    <input placeholder="Submit your skill" type="text" name="skill">

    <input type="submit" name="commit" value="Submit Skill" data-disable-with="Submit Skill">

</form>
</code>```

Routes

```<code>devise_scope :user do
    post '/users/add_skill' => 'users/registrations#add_skill', :defaults =>
{ :format => :json }
end
</code>```

Controller

```<code>class Users::RegistrationsController < Devise::RegistrationsController

respond_to :html, except: [:add_skill]
respond_to :json, only: [:add_skill]

def add_skill
  @user = current_user
  @user.skills.push(params[:skill])

  respond_to do |format|
    if @user.save
      format.json { render json: @user.skills, status: :created, location: @user }
    else
      format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end
</code>```

Javascript

```<code>const skillsForm = document.getElementById("skills-form");
skillsForm.addEventListener('ajax:success', function(res) {
    console.log("added skill");
});
</code>```

The 'skill' is being persisted to the database so I know that the request is being made correctly - and if I remove the :defaults => { :format => :json} from the routes, and change a few other things in the respond_to block (sorry I don't remember exactly what I had changed), the data is persisted the page does not change, so I'm pretty sure the Ajax request is working well, but I don't know how to get the response.

I saw a lot of questions using jQuery ajax() but I'm not using jQuery so I'm not sure what I should be doing. Any help would be greatly appreciated!

答:
First, replace ajax:success with ajax:complete in your eventListener

You should add remote: true in your form html params, then, your request Will respond as the format that you want (default should be as 'JS')

For example: with format: js, in your controller  do

```<code>respond_to do |format|
  format.js { # TODO block }
end
</code>```

Finally with send_data, you can send data to your Ajax callback

Title: Make ajax POST and return JSON in Rails

Body:
I'm trying to make an AJAX POST request to one of my routes and return some JSON, but I'm running into an issue where the JSON is not being returned and a page is rendering instead like a GET request. Here is my code:

View

<%= form_with url: users_add_skill_path, id: "skills-form", format: 'json' do |f| %>
  <%= f.text_field :skill, placeholder: "Submit your skill" %>
  <%= f.submit "Submit Skill" %>
<% end %>

This becomes in HTML:

<form id="skills-form" action="/users/add_skill" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="token_hereadnfjahbsdkfjabsd">
    Skill
    <input placeholder="Submit your skill" type="text" name="skill">

    <input type="submit" name="commit" value="Submit Skill" data-disable-with="Submit Skill">

</form>

Routes

devise_scope :user do
    post '/users/add_skill' => 'users/registrations#add_skill', :defaults =>
{ :format => :json }
end

Controller

class Users::RegistrationsController < Devise::RegistrationsController

respond_to :html, except: [:add_skill]
respond_to :json, only: [:add_skill]

def add_skill
  @user = current_user
  @user.skills.push(params[:skill])

  respond_to do |format|
    if @user.save
      format.json { render json: @user.skills, status: :created, location: @user }
    else
      format.json { render json: @user.errors, status: :unprocessable_entity }
  end
end

Javascript

const skillsForm = document.getElementById("skills-form");
skillsForm.addEventListener('ajax:success', function(res) {
    console.log("added skill");
});

The 'skill' is being persisted to the database so I know that the request is being made correctly - and if I remove the :defaults => { :format => :json} from the routes, and change a few other things in the respond_to block (sorry I don't remember exactly what I had changed), the data is persisted the page does not change, so I'm pretty sure the Ajax request is working well, but I don't know how to get the response.

I saw a lot of questions using jQuery ajax() but I'm not using jQuery so I'm not sure what I should be doing. Any help would be greatly appreciated!

Body:
First, replace ajax:success with ajax:complete in your eventListener

You should add remote: true in your form html params, then, your request Will respond as the format that you want (default should be as 'JS')

For example: with format: js, in your controller  do

respond_to do |format|
  format.js { # TODO block }
end

Finally with send_data, you can send data to your Ajax callback


问:
iOS 11 disable password autofill accessory view option?
As of now I would like to opt out of the new option iOS 11 gives, that is to suggest passwords in the app. When I run the app on iOS 11 I get the autofill option on top of the keyboard and my username and password textfield don't even show up.

So, my question is, how can I disable the new password autofill feature all together so the key on the keyboard is not shown at all and the overall behavior is the same as pre iOS 11?

答:
You can add extension for UITextContentType like this </p>

```<code>extension UITextContentType {
    public static let unspecified = UITextContentType("unspecified")
}
</code>```

<p>after that, you can use it </p>

```<code>if #available(iOS 10.0, *) {
    passwordField.textContentType = .unspecified
}
</code>```

Body:
You can add extension for UITextContentType like this

extension UITextContentType {
    public static let unspecified = UITextContentType("unspecified")
}

after that, you can use it

if #available(iOS 10.0, *) {
    passwordField.textContentType = .unspecified
}


问:
CV Python WebCam Stream to HTTP
I have this python WebCam preview code, it doesn't record or any fancy stuff. It is using cv2 library, and I was wondering if it's possible to broadcast/stream via HTTP? If that is the case, this can be set up with raspberry pi later.</p>

```<code>import time
import os
import sys
import cv2

try:
    def show_webcam(mirror=False):
            cam = cv2.VideoCapture(0)
            while True:
                    ret_val, img = cam.read()
                    if mirror:
                            img = cv2.flip(img, 1)
                    cv2.imshow('my webcam', img)
                    if cv2.waitKey(1) == 27:
                            break  # esc to quit
            cv2.destroyAllWindows()

        def main():
                show_webcam(mirror=True)

    if __name__ == '__main__':
            main()
except KeyboardInterrupt:
    print('User Ended Session\n')
    sys.exit(0)
</code>```

答:
It is possible. there is an example here gist source .  Python version should available too. In my opinion this approach is hard and will cost you ton of time.

If you just want the simplest solution. Just save your processed image on local disk. Then use and web-server to expose that image file to outside world through http. Finally, make an html page to refresh that image every 0.5 second. This approach is indeed should satisfied all of you need.

Title: CV Python WebCam Stream to HTTP

Body:
I have this python WebCam preview code, it doesn't record or any fancy stuff. It is using cv2 library, and I was wondering if it's possible to broadcast/stream via HTTP? If that is the case, this can be set up with raspberry pi later.

import time
import os
import sys
import cv2

try:
    def show_webcam(mirror=False):
            cam = cv2.VideoCapture(0)
            while True:
                    ret_val, img = cam.read()
                    if mirror:
                            img = cv2.flip(img, 1)
                    cv2.imshow('my webcam', img)
                    if cv2.waitKey(1) == 27:
                            break  # esc to quit
            cv2.destroyAllWindows()

        def main():
                show_webcam(mirror=True)

    if __name__ == '__main__':
            main()
except KeyboardInterrupt:
    print('User Ended Session\n')
    sys.exit(0)