问:
Random string generator: Unicode out of range?
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}
</code>```

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

```<code>public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}
</code>```

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

答:
Why all these bitwise arithmetics? First, let's state the problem:

I want to generate random string of characters length; the string should consist of a..z
  which should have uniform distribution

And implementation will be easy:

```<code>// Simplest, but not thread safe
private static Random s_Random = new Random();

// Not thread safe
public static string RandomString(int characters) {
  if (characters < 0)
    throw new ArgumentOutOfRangeException("characters");

  StringBuilder sb = new StringBuilder(characters);

  // I personally, prefer Linq + Concat, but let's preserve the loop
  for (int i = 0; i < characters; ++i) {
    char c = (char)(s_Random.Next('z' - 'a' + 1) + 'a'); // +1 - 'z' should be included

    sb.Append(c);
  }

  return sb.ToString();
}
</code>```

Linq version is shorter, but, probably, less readable:

```<code>// Not thread safe
public static string RandomString(int characters) {
  if (characters < 0)
    throw new ArgumentOutOfRangeException("characters");

  return string.Concat(Enumerable
    .Range(0, characters)
    .Select(i => (char)(s_Random.Next('z' - 'a' + 1) + 'a')));
}
</code>```

Test:

```<code>Console.Write(RandomString(10));
</code>```

Outcome (may vary):

```<code>dcdwwvzhnz
</code>```

Finally, let's have a look at the actual distribution "...But the frequencies of the letters before k were very low.."

```<code>  int count = 1000; // we examine "count" random string
  int length = 10;  // each of "length" length

  var distribution = String
    .Concat(Enumerable.Range(1, count).Select(i => RandomString(length)))
    .GroupBy(c => c, (k, s) => new {
      key = k,
      freq = (double)s.Count() / length / count
    })
    .OrderBy(item => item.freq)
    .Select(item => $"{item.key}: {item.freq:F4}")
    .ToArray();

  Console.Write(string.Join(Environment.NewLine, distribution));
</code>```

Outcome (may vary): no evidence of such a skew

```<code>p: 0.0351
a: 0.0359
r: 0.0360
y: 0.0362
l: 0.0363
z: 0.0364
n: 0.0369
u: 0.0370
h: 0.0371
e: 0.0373
c: 0.0375
v: 0.0376
x: 0.0376
o: 0.0380
q: 0.0380
m: 0.0388
k: 0.0389
d: 0.0391
s: 0.0391
g: 0.0396
w: 0.0401
b: 0.0406
t: 0.0406
f: 0.0422
i: 0.0434
j: 0.0447
</code>```

Body:
I'm trying to make a random string generator in C#, given a length of the string. My first attempt was this:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        s += Convert.ToChar((97 + r.Next(26)));
    }
    return s;
}

But the frequencies of the letters before k were very low, so I tried to change it by writing my own randomizer:

public static string RandomString(int characters)
{
    string s = "";
    for (int i = 0; i < characters; i++)
    {
        int randomLetter = 0;

        for (int bit = 0; i < 5; bit++)
        {
            if (r.Next(2) == 0)
                continue;
            randomLetter += 1 << bit;

            if (randomLetter + (1 << (bit + 1)) > 26)
                break;
        }
        s += Convert.ToChar(97 + randomLetter);
    }
    return s;
}

But sometimes randomLetter will be greater than 26, sometimes way too great. I can't find the cause of this problem, can you?

Body:
Why all these bitwise arithmetics? First, let's state the problem:

I want to generate random string of characters length; the string should consist of a..z
  which should have uniform distribution

And implementation will be easy:

// Simplest, but not thread safe
private static Random s_Random = new Random();

// Not thread safe
public static string RandomString(int characters) {
  if (characters < 0)
    throw new ArgumentOutOfRangeException("characters");

  StringBuilder sb = new StringBuilder(characters);

  // I personally, prefer Linq + Concat, but let's preserve the loop
  for (int i = 0; i < characters; ++i) {
    char c = (char)(s_Random.Next('z' - 'a' + 1) + 'a'); // +1 - 'z' should be included

    sb.Append(c);
  }

  return sb.ToString();
}

Linq version is shorter, but, probably, less readable:

// Not thread safe
public static string RandomString(int characters) {
  if (characters < 0)
    throw new ArgumentOutOfRangeException("characters");

  return string.Concat(Enumerable
    .Range(0, characters)
    .Select(i => (char)(s_Random.Next('z' - 'a' + 1) + 'a')));
}

Test:

Console.Write(RandomString(10));

Outcome (may vary):

dcdwwvzhnz

Finally, let's have a look at the actual distribution "...But the frequencies of the letters before k were very low.."

  int count = 1000; // we examine "count" random string
  int length = 10;  // each of "length" length

  var distribution = String
    .Concat(Enumerable.Range(1, count).Select(i => RandomString(length)))
    .GroupBy(c => c, (k, s) => new {
      key = k,
      freq = (double)s.Count() / length / count
    })
    .OrderBy(item => item.freq)
    .Select(item => $"{item.key}: {item.freq:F4}")
    .ToArray();

  Console.Write(string.Join(Environment.NewLine, distribution));

Outcome (may vary): no evidence of such a skew

p: 0.0351
a: 0.0359
r: 0.0360
y: 0.0362
l: 0.0363
z: 0.0364
n: 0.0369
u: 0.0370
h: 0.0371
e: 0.0373
c: 0.0375
v: 0.0376
x: 0.0376
o: 0.0380
q: 0.0380
m: 0.0388
k: 0.0389
d: 0.0391
s: 0.0391
g: 0.0396
w: 0.0401
b: 0.0406
t: 0.0406
f: 0.0422
i: 0.0434
j: 0.0447


来源: stackexchange

问:
Is importing a file good in Python
I have around 80 lines of a function in a file. I need the same functionality in another file so I am currently importing the other file for the function.

My question is that in terms of running time on a machine which technique would be better :- importing the complete file and running the function or copying the function as it is and run it from same package.

I know it won't matter in a large sense but I want to learn it in the sense that if we are making a large project is it better to import a complete file in Python or just add the function in the current namespace.....

答: Copy/Paste cannot be better. Importing affects load-time performance, not run-time (if you import it at the top-level).</p>

ContentLicense: CC BY-SA 2.5

Title: Is importing a file good in Python


答:
Thanks to @Evk I figured it out. My final approach:</p>

```<code>public static string RandomString(int characters)
    {
        string s = "";
        for (int i = 0; i < characters; i++)
        {
            int ascii = 0;

            for (int bit = 0; bit < 5; bit++)
            {
                if (r.Next(2) == 0)
                    continue;
                ascii += 1 << bit;

                if (ascii + (1 << (bit + 1)) > 25)
                    break;
            }
            s += Convert.ToChar(97 + ascii);
        }
        return s;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Random string generator: Unicode out of range?

Body:
Thanks to @Evk I figured it out. My final approach:

public static string RandomString(int characters)
    {
        string s = "";
        for (int i = 0; i < characters; i++)
        {
            int ascii = 0;

            for (int bit = 0; bit < 5; bit++)
            {
                if (r.Next(2) == 0)
                    continue;
                ascii += 1 << bit;

                if (ascii + (1 << (bit + 1)) > 25)
                    break;
            }
            s += Convert.ToChar(97 + ascii);
        }
        return s;
    }


问:
The supplied API key is not configured for use from this Android app in Google map Road Api
Below are the steps I have done:

Select Google Maps Road API and restrict the key to android by passing SHA key and Package name.

I have also enable the another API i.e Google Maps Android API which is working fine with the code.

I have removed the restriction of key but getting same result.

On Developer console, every google map road API request goes into the  error column.

Please, help me solve this issue as I'm not able to figure out what's wrong with this another API key's are working fine but getting error in road API.

```<code>{
  "error": {
    "code": 403,
    "message": "The supplied API key is not configured for use from this Android app.",
    "status": "PERMISSION_DENIED",
    "details": [
    {
      "@type": "type.googleapis.com/google.rpc.Help",
      "links": [
      {
        "description": "Google developer console API key",
        "url": "https://console.developers.google.com/project/41764599888/apiui/credential"
      }
      ]
    }
    ]
  }
}
</code>```

答:
After spending hours on google map road api ,

i came to the solution:

This is tip which is over google map road api:

During development and testing, you can register a project for testing
  purposes in the Google API Console and use a generic, unrestricted API
  key. When you are ready to move your app or website into production,
  register a separate project for production, create a server-restricted
  API key, and add the key to your application.

You just need to remove restriction from the key as i was doing this before in wrong way.

Body:
Below are the steps I have done:

Select Google Maps Road API and restrict the key to android by passing SHA key and Package name.

I have also enable the another API i.e Google Maps Android API which is working fine with the code.

I have removed the restriction of key but getting same result.

On Developer console, every google map road API request goes into the  error column.

Please, help me solve this issue as I'm not able to figure out what's wrong with this another API key's are working fine but getting error in road API.

{
  "error": {
    "code": 403,
    "message": "The supplied API key is not configured for use from this Android app.",
    "status": "PERMISSION_DENIED",
    "details": [
    {
      "@type": "type.googleapis.com/google.rpc.Help",
      "links": [
      {
        "description": "Google developer console API key",
        "url": "https://console.developers.google.com/project/41764599888/apiui/credential"
      }
      ]
    }
    ]
  }
}


问:
How to handle print output from yahoo-finance quote reader?
I'm designing a tool that will help me manage risk in my equities portfolio. I've got some code that gathers current price data from yahoo finance for 4 equities, 2x longs and 2x shorts. This is using the yahoo-finance tool.

I can gather the data but I can't work out how to divide the prices by each other to return the value of the spread (stockA/stockB as a relative value trade)

```<code>#always helpful to show the version:
(env) LaurencsonsiMac:~ admin$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

from yahoo_finance import Share
>>> L1 = Share('YHOO')
>>> L2 = Share('GOOG')
>>> S1 = Share('AAPL')
>>> S2 = Share('MSFT')
>>> print L1.get_price()
50.55
>>> print S1.get_price()
154.45
</code>```

A small victory! I can fetch the price :) but
I dont know how to manipulate this output as an object and define Long1 as “whatever is returned by print L1.get_price()”
The final output would be a table like this, with the spread values as a single (super important!) number to two or three (whatever) decimal places.

```<code>Position, Spread
YHOO/AAPL, 0.327 #value of Yahoo stock price/Apple stock price
GOOG/MSF,  4.55
ticker/ticker, 10.14
ticker/ticker, 0.567
</code>```

I attempted to define Long1 and Short1 as the number that L1.get_price() prints:

```<code>>>> Long1 = "L1.get_price()"
>>> Short1 = "S2.get_price()"
</code>```

then hopefully I should get a number by dividing those two:

```<code>>>> Long1/Short1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'
</code>```

so i tried to convert these numbers to a float [because it might work why not] but I’m clearly misunderstanding something:

```<code>>>> float(Long1)/float(Short1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: L1.get_price()
</code>```

Alternatively I did manage to get an output using this piece of code using the pandas module: (thank you Brad Solomon for this:)

```<code>import pandas_datareader.data as web

def get_quotes(symbols, type='dict'):
    quotes = web.get_quote_yahoo(symbols)['last']
    if type == 'dict':
        quotes = quotes.to_dict() # otherwise, Series
    return quotes

quotes = get_quotes(symbols=['RAD', 'MSFT']); quotes
Out[16]: {'MSFT': 70.409999999999997, 'RAD': 3.46}
</code>```

But how would you realise MSFT / RAD, get python to "read the string"?

I'm really quite stuck, can anyone hint me how I can get my quoted prices into real objects I can use?

答:
Putting the values in quotes is telling Python that it is a String datatype. Using that you are dividing which will fail. Even when using the function float since the value is actually a string and not the value of expression that you might be hoping it to be resulting in failing the function call inside quotes.
You do not need to use quotes and direct function calls should do the trick.</p>

```<code>>>> Long1 = L1.get_price()

>>> Short1 = S2.get_price()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm designing a tool that will help me manage risk in my equities portfolio. I've got some code that gathers current price data from yahoo finance for 4 equities, 2x longs and 2x shorts. This is using the yahoo-finance tool.

I can gather the data but I can't work out how to divide the prices by each other to return the value of the spread (stockA/stockB as a relative value trade)

#always helpful to show the version:
(env) LaurencsonsiMac:~ admin$ python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin

from yahoo_finance import Share
>>> L1 = Share('YHOO')
>>> L2 = Share('GOOG')
>>> S1 = Share('AAPL')
>>> S2 = Share('MSFT')
>>> print L1.get_price()
50.55
>>> print S1.get_price()
154.45

A small victory! I can fetch the price :) but
I dont know how to manipulate this output as an object and define Long1 as “whatever is returned by print L1.get_price()”
The final output would be a table like this, with the spread values as a single (super important!) number to two or three (whatever) decimal places.

Position, Spread
YHOO/AAPL, 0.327 #value of Yahoo stock price/Apple stock price
GOOG/MSF,  4.55
ticker/ticker, 10.14
ticker/ticker, 0.567

I attempted to define Long1 and Short1 as the number that L1.get_price() prints:

>>> Long1 = "L1.get_price()"
>>> Short1 = "S2.get_price()"

then hopefully I should get a number by dividing those two:

>>> Long1/Short1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

so i tried to convert these numbers to a float [because it might work why not] but I’m clearly misunderstanding something:

>>> float(Long1)/float(Short1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: L1.get_price()

Alternatively I did manage to get an output using this piece of code using the pandas module: (thank you Brad Solomon for this:)

import pandas_datareader.data as web

def get_quotes(symbols, type='dict'):
    quotes = web.get_quote_yahoo(symbols)['last']
    if type == 'dict':
        quotes = quotes.to_dict() # otherwise, Series
    return quotes

quotes = get_quotes(symbols=['RAD', 'MSFT']); quotes
Out[16]: {'MSFT': 70.409999999999997, 'RAD': 3.46}

But how would you realise MSFT / RAD, get python to "read the string"?

I'm really quite stuck, can anyone hint me how I can get my quoted prices into real objects I can use?

Body:
Putting the values in quotes is telling Python that it is a String datatype. Using that you are dividing which will fail. Even when using the function float since the value is actually a string and not the value of expression that you might be hoping it to be resulting in failing the function call inside quotes.
You do not need to use quotes and direct function calls should do the trick.

>>> Long1 = L1.get_price()

>>> Short1 = S2.get_price()


问:
Detecting questions using Parsey's Dependency parser
Is there any way to detect if there exists a question in the sentence using Parsey's dependency parser alone? The regular stanford parser provides a tag of SBARQ or SQ for questions. Is there anything similar for parsey's dependency parser?</p>

答:
I'm assuming you refer to Google's Parsey McParseface. This parser is said to be compliant to the annotation guidelines from Universal Dependencies (http://universaldependencies.org/), so I believe you should find answer there.

At least in case of English, no question-marking item is documented. I've searched “English (UDv2.0)” corpus at http://bionlp-www.utu.fi/dep_search/ and there is no trace of this information (aside from the interrogative pronoun, which may be ambiguous), for instance:

```<code>1   Who who PRON    WP  PronType=Int    2   nsubj   _   _
2   cares   care    VERB    VBZ Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin   0   root    _   SpaceAfter=No
3   ??????  ??????  PUNCT   .   _   2   punct   _   _
</code>```

Dependency parsing is more focused on the surface form and probably whether the sentence is a question or not is deemed here part of semantics, so not decided on this level. The Stanford constituency parser outputs something which resembles the oldish Chomskian X-bar theory, where things look quite differently.

Body:
I'm assuming you refer to Google's Parsey McParseface. This parser is said to be compliant to the annotation guidelines from Universal Dependencies (http://universaldependencies.org/), so I believe you should find answer there.

At least in case of English, no question-marking item is documented. I've searched “English (UDv2.0)” corpus at http://bionlp-www.utu.fi/dep_search/ and there is no trace of this information (aside from the interrogative pronoun, which may be ambiguous), for instance:

1   Who who PRON    WP  PronType=Int    2   nsubj   _   _
2   cares   care    VERB    VBZ Mood=Ind|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin   0   root    _   SpaceAfter=No
3   ??????  ??????  PUNCT   .   _   2   punct   _   _

Dependency parsing is more focused on the surface form and probably whether the sentence is a question or not is deemed here part of semantics, so not decided on this level. The Stanford constituency parser outputs something which resembles the oldish Chomskian X-bar theory, where things look quite differently.


问:
Discretisize Pandas' column given the data distribution
I have a pandas' dataframe with one column that holds real data ranging from 0 to 50. They are not evenly distributed.

I can get the distribution using:

```<code>hist, bins = np.histogram(df["col"])
</code>```

What I would like to do is to replace every value with the bins' number it falls in.

To do so, this was working:

```<code>for i in range(len(df["speed_array"])):
    df["speed_array"].iloc[i] = np.searchsorted(bins, df["speed_array"].iloc[i])
</code>```

However, with an dataframe with more the 4 millions of row, it is quite slow (50 minutes). I am searching for a more efficient way to this. Do you guys have a better idea ?

答:
Simply use np.searchsorted on the entire underlying array data -

```<code>df["speed_array"] = np.searchsorted(bins, df["speed_array"].values)
</code>```

Runtime test -

```<code>In [140]: # 4 million rows with 100 bins
     ...: df = pd.DataFrame(np.random.randint(0,1000,(4000000,1)))
     ...: df.columns = [['speed_array']]
     ...: bins = np.sort(np.random.choice(1000, size=100, replace=0))
     ...:

In [141]: def searchsorted_app(df):
     ...:     df["speed_array"] = np.searchsorted(bins, df["speed_array"].values)
     ...:

In [142]: %timeit searchsorted_app(df)
10 loops, best of 3: 15.3 ms per loop
</code>```

Body:
I have a pandas' dataframe with one column that holds real data ranging from 0 to 50. They are not evenly distributed.

I can get the distribution using:

hist, bins = np.histogram(df["col"])

What I would like to do is to replace every value with the bins' number it falls in.

To do so, this was working:

for i in range(len(df["speed_array"])):
    df["speed_array"].iloc[i] = np.searchsorted(bins, df["speed_array"].iloc[i])

However, with an dataframe with more the 4 millions of row, it is quite slow (50 minutes). I am searching for a more efficient way to this. Do you guys have a better idea ?

Body:
Simply use np.searchsorted on the entire underlying array data -

df["speed_array"] = np.searchsorted(bins, df["speed_array"].values)

Runtime test -

In [140]: # 4 million rows with 100 bins
     ...: df = pd.DataFrame(np.random.randint(0,1000,(4000000,1)))
     ...: df.columns = [['speed_array']]
     ...: bins = np.sort(np.random.choice(1000, size=100, replace=0))
     ...:

In [141]: def searchsorted_app(df):
     ...:     df["speed_array"] = np.searchsorted(bins, df["speed_array"].values)
     ...:

In [142]: %timeit searchsorted_app(df)
10 loops, best of 3: 15.3 ms per loop


问:
Can i put text in the left and in the right side of the elements of a listview?
i have to make a listview that haves a list of names, and also, aligned to the left, but in the same field, the sex of the person, male or female

is possible to do it? how?

code examples welcome

EDIT

I try with the first user answer, and i got this exception: 12-14 22:39:56.191: ERROR/AndroidRuntime(917): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

this is the code of the XML item i make:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left side"
        android:layout_alignParentLeft="true"/>
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right side"
        android:layout_alignParentRight="true"/>
</RelativeLayout>
</code>```

and this is the code where i have my list:

```<code>public class PendingInvitations extends ListActivity {

......
.....
....
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    private List<String> usernames=new ArrayList<String>();
        for (int i=0;i<friends.size();i++)
              {
                usernames.add(i,friends.get(i).getFullName());
              }

              setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item2, usernames));
</code>```

答: Each item of a ListView has to be a View. This includes ViewGroups. So you can use any Layout to arrange several Views inside a ListView item.</p>

Body:
i have to make a listview that haves a list of names, and also, aligned to the left, but in the same field, the sex of the person, male or female

is possible to do it? how?

code examples welcome

EDIT

I try with the first user answer, and i got this exception: 12-14 22:39:56.191: ERROR/AndroidRuntime(917): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView

this is the code of the XML item i make:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left side"
        android:layout_alignParentLeft="true"/>
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right side"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

and this is the code where i have my list:

public class PendingInvitations extends ListActivity {

......
.....
....
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
    private List<String> usernames=new ArrayList<String>();
        for (int i=0;i<friends.size();i++)
              {
                usernames.add(i,friends.get(i).getFullName());
              }

              setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item2, usernames));


问:
How to run python scripts using gimpfu from command line?
I'm trying to use functions of gimp 2.8.22 to convert a pdf to jpeg and i want to do that with a python script using the gimpfu library from my windows cmd (i have installed python 3.6.1).

Right now, i't trying to do that with an example script:

```<code>#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world(initstr, font, size, color) :
    # First do a quick sanity check on the font
    if font == 'Comic Sans MS' :
        initstr = "Comic Sans? Are you sure?"

    # Make a new image. Size 10x10 for now -- we'll resize later.
    img = gimp.Image(1, 1, RGB)

    # Save the current foreground color:
    pdb.gimp_context_push()

    # Set the text color
    gimp.set_foreground(color)

    # Create a new text layer (-1 for the layer means create a new layer)
    layer = pdb.gimp_text_fontname(img, None, 0, 0, initstr, 10,
                                   True, size, PIXELS, font)

    # Resize the image to the size of the layer
    img.resize(layer.width, layer.height, 0, 0)

    # Background layer.
    # Can't add this first because we don't know the size of the text layer.
    background = gimp.Layer(img, "Background", layer.width, layer.height,
                            RGB_IMAGE, 100, NORMAL_MODE)
    background.fill(BACKGROUND_FILL)
    img.add_layer(background, 1)

    # Create a new image window
    gimp.Display(img)
    # Show the new image window
    gimp.displays_flush()

    # Restore the old foreground color:
    pdb.gimp_context_pop()

register(
    "python_fu_hello_world",
    "Hello world image",
    "Create a new image with your text string",
    "Akkana Peck",
    "Akkana Peck",
    "2010",
    "Hello world (Py)...",
    "",      # Create a new image, don't work on an existing one
    [
        (PF_STRING, "string", "Text string", 'Hello, world!'),
        (PF_FONT, "font", "Font face", "Sans"),
        (PF_SPINNER, "size", "Font size", 50, (1, 3000, 1)),
        (PF_COLOR, "color", "Text color", (1.0, 0.0, 0.0))
    ],
    [],
    hello_world, menu="<Image>/File/Create")

main()
</code>```

I try to run the script from my cmd like this:

```<code>gimp-2.8 --no-interface --batch '(python_fu_hello_world RUN-NONINTERACTIVE "Hello" Arial 50 red)' -b '(gimp-quit 1)'
</code>```

However, no matter what i do, i always geht the same error message:

(gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read():
  error

edit: Ok, thanks. I left out the interface statement and I also tried out the most simple example to figure out whats wrong:

```<code>#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world():
 gimp.message("Hello, GIMP world!\n")

register(
 "hello_world",
 'A simple Python-Fu "Hello, World" plug-in',
 'When run this plug-in prints "Hello, GIMP world!" in a dialog box.',
 "Tony Podlaski",
 "Tony Podlaski 2017. MIT License",
 "2017",
 "Hello World",
 "",
 [],
 [],
 hello_world,
 menu="<Image>/Filters/HelloWorld",
)

main()
</code>```

The script actually works when i run it from Gimp itself, but when i try to run it from my cmd, Gimp opens with another cmd saying: Error: ( : 1) eval: unbound variable: hello_world

Does someone know what i'm missing here?

答:
To run a python script you don't need to have it register as a plugin. IMHO you should even avoid this, this unnecessarily pollutes Gimp's menus and procedure name space. Here is an example:

The batch script (saved as batch.py):

```<code>#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import os, glob, sys, time
from gimpfu import *

def process(infile):
        print "Processing file %s " % infile
        image = pdb.gimp_file_load(infile, infile, run_mode=RUN_NONINTERACTIVE)
        drawable = image.active_layer

        print "File %s loaded OK" % infile
        pdb.plug_in_photocopy(image, drawable,8.,0.8,0.2,0.2)
        pdb.plug_in_cartoon(image, drawable, 7.,0.2)
        outfile=os.path.join('processed',os.path.basename(infile))
        outfile=os.path.join(os.path.dirname(infile),outfile)
        print "Saving to %s" % outfile
        pdb.file_jpeg_save(image, drawable, outfile, outfile, "0.5",0,1,0,"",0,1,0,0)
        print "Saved to %s" % outfile
        pdb.gimp_image_delete(image)

def run(directory):
        start=time.time()
        print "Running on directory \"%s\"" % directory
#   os.mkdir(os.path.join(directory,'processed'))
        for infile in glob.glob(os.path.join(directory, '*.jpg')):
                process(infile)
        end=time.time()
        print "Finished, total processing time: %.2f seconds" % (end-start)

if __name__ == "__main__":
        print "Running as __main__ with args: %s" % sys.argv
</code>```

To call it:

```<code>gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')" -b "pdb.gimp_quit(1)"
</code>```

The parameters in slow-motion:

-idf: work without user interface, and load neither data nor fonts (you may perhaps need to keep the fonts to load pdfs)

--batch-interpreter python-fu-eval: whatever follows -b is Python, not script-fu

"import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')": the code that we ask Gimp to execute, namely:

import sys;sys.path=['.']+sys.path;: extend the import path to include the current directory

import batch;: import the file with our script, which is now in a directory which is part of the path.

batch.run('./images'): call the run() function of the batch module we imported, giving it the name of a directory containing the images to process.

-b "pdb.gimp_quit(1)": another piece of python: exit when done.

Note how the command line cleverly uses double and single quotes to pass all parameters to Gimp and then to Python(*). And yes, you can use forward slashes as file separators in Windows.

To debug, matters are bit complicated in Windows because there is no always a stdout stream. Things that can help:

remove the -i parameter temporarily so that you get the UI and perhaps a chance to see messages.

Add --verbose which makes Gimp start a secondary console window.

There are other tricks to see messages listed here.

You can also start Gimp normally and run your script from the Python-fu console (Filters>Python-fu>Console). You will have to extend the path and import the file "manually".

(*) In a Linux/OSX shell one would do the opposite: single quotes for the shell, double quotes for Python.

Body:
I'm trying to use functions of gimp 2.8.22 to convert a pdf to jpeg and i want to do that with a python script using the gimpfu library from my windows cmd (i have installed python 3.6.1).

Right now, i't trying to do that with an example script:

#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world(initstr, font, size, color) :
    # First do a quick sanity check on the font
    if font == 'Comic Sans MS' :
        initstr = "Comic Sans? Are you sure?"

    # Make a new image. Size 10x10 for now -- we'll resize later.
    img = gimp.Image(1, 1, RGB)

    # Save the current foreground color:
    pdb.gimp_context_push()

    # Set the text color
    gimp.set_foreground(color)

    # Create a new text layer (-1 for the layer means create a new layer)
    layer = pdb.gimp_text_fontname(img, None, 0, 0, initstr, 10,
                                   True, size, PIXELS, font)

    # Resize the image to the size of the layer
    img.resize(layer.width, layer.height, 0, 0)

    # Background layer.
    # Can't add this first because we don't know the size of the text layer.
    background = gimp.Layer(img, "Background", layer.width, layer.height,
                            RGB_IMAGE, 100, NORMAL_MODE)
    background.fill(BACKGROUND_FILL)
    img.add_layer(background, 1)

    # Create a new image window
    gimp.Display(img)
    # Show the new image window
    gimp.displays_flush()

    # Restore the old foreground color:
    pdb.gimp_context_pop()

register(
    "python_fu_hello_world",
    "Hello world image",
    "Create a new image with your text string",
    "Akkana Peck",
    "Akkana Peck",
    "2010",
    "Hello world (Py)...",
    "",      # Create a new image, don't work on an existing one
    [
        (PF_STRING, "string", "Text string", 'Hello, world!'),
        (PF_FONT, "font", "Font face", "Sans"),
        (PF_SPINNER, "size", "Font size", 50, (1, 3000, 1)),
        (PF_COLOR, "color", "Text color", (1.0, 0.0, 0.0))
    ],
    [],
    hello_world, menu="<Image>/File/Create")

main()

I try to run the script from my cmd like this:

gimp-2.8 --no-interface --batch '(python_fu_hello_world RUN-NONINTERACTIVE "Hello" Arial 50 red)' -b '(gimp-quit 1)'

However, no matter what i do, i always geht the same error message:

(gimp-2.8:1020): LibGimpBase-WARNING **: gimp-2.8: gimp_wire_read():
  error

edit: Ok, thanks. I left out the interface statement and I also tried out the most simple example to figure out whats wrong:

#!/usr/bin/env python

# Hello World in GIMP Python

from gimpfu import *

def hello_world():
 gimp.message("Hello, GIMP world!\n")

register(
 "hello_world",
 'A simple Python-Fu "Hello, World" plug-in',
 'When run this plug-in prints "Hello, GIMP world!" in a dialog box.',
 "Tony Podlaski",
 "Tony Podlaski 2017. MIT License",
 "2017",
 "Hello World",
 "",
 [],
 [],
 hello_world,
 menu="<Image>/Filters/HelloWorld",
)

main()

The script actually works when i run it from Gimp itself, but when i try to run it from my cmd, Gimp opens with another cmd saying: Error: ( : 1) eval: unbound variable: hello_world

Does someone know what i'm missing here?

Body:
To run a python script you don't need to have it register as a plugin. IMHO you should even avoid this, this unnecessarily pollutes Gimp's menus and procedure name space. Here is an example:

The batch script (saved as batch.py):

#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import os, glob, sys, time
from gimpfu import *

def process(infile):
        print "Processing file %s " % infile
        image = pdb.gimp_file_load(infile, infile, run_mode=RUN_NONINTERACTIVE)
        drawable = image.active_layer

        print "File %s loaded OK" % infile
        pdb.plug_in_photocopy(image, drawable,8.,0.8,0.2,0.2)
        pdb.plug_in_cartoon(image, drawable, 7.,0.2)
        outfile=os.path.join('processed',os.path.basename(infile))
        outfile=os.path.join(os.path.dirname(infile),outfile)
        print "Saving to %s" % outfile
        pdb.file_jpeg_save(image, drawable, outfile, outfile, "0.5",0,1,0,"",0,1,0,0)
        print "Saved to %s" % outfile
        pdb.gimp_image_delete(image)

def run(directory):
        start=time.time()
        print "Running on directory \"%s\"" % directory
#   os.mkdir(os.path.join(directory,'processed'))
        for infile in glob.glob(os.path.join(directory, '*.jpg')):
                process(infile)
        end=time.time()
        print "Finished, total processing time: %.2f seconds" % (end-start)

if __name__ == "__main__":
        print "Running as __main__ with args: %s" % sys.argv

To call it:

gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')" -b "pdb.gimp_quit(1)"

The parameters in slow-motion:

-idf: work without user interface, and load neither data nor fonts (you may perhaps need to keep the fonts to load pdfs)

--batch-interpreter python-fu-eval: whatever follows -b is Python, not script-fu

"import sys;sys.path=['.']+sys.path;import batch;batch.run('./images')": the code that we ask Gimp to execute, namely:

import sys;sys.path=['.']+sys.path;: extend the import path to include the current directory

import batch;: import the file with our script, which is now in a directory which is part of the path.

batch.run('./images'): call the run() function of the batch module we imported, giving it the name of a directory containing the images to process.

-b "pdb.gimp_quit(1)": another piece of python: exit when done.

Note how the command line cleverly uses double and single quotes to pass all parameters to Gimp and then to Python(*). And yes, you can use forward slashes as file separators in Windows.

To debug, matters are bit complicated in Windows because there is no always a stdout stream. Things that can help:

remove the -i parameter temporarily so that you get the UI and perhaps a chance to see messages.

Add --verbose which makes Gimp start a secondary console window.

There are other tricks to see messages listed here.

You can also start Gimp normally and run your script from the Python-fu console (Filters>Python-fu>Console). You will have to extend the path and import the file "manually".

(*) In a Linux/OSX shell one would do the opposite: single quotes for the shell, double quotes for Python.


问:
How to check if radio is checked in blade Laravel 5
I have two radio in my blade and i want if radio 1 checked display some step in modal popup
 else if radio 2 checked display another step in this modal event

this is my radio in view :

```<code>  <div class="row setup-content" id="step-1">
  <div class="col-xs-6 col-md-offset-3">
  <div class="col-md-12">
  <h3> Step 1</h3>
  <label><input type="radio" class="message_pri" id="web" name="web" value="Web">Web</label>
  <label><input type="radio" class="message_pri" id="mobile" name="web" value="Mobile">Mobile</label>
  <button class="btn btn-primary nextBtn btn-lg pull-right btnnext" type="button" >Next</button>
</div>
</code>```

答:
Try this:

$('.message_pri').change(function(){
  if($(this).val() == 'Web')
  {
    alert('Web is selected')
  }
  else
  {
    alert('Mobile is selected')
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row setup-content" id="step-1">
  <div class="col-xs-6 col-md-offset-3">
  <div class="col-md-12">
  <h3> Step 1</h3>
  <label><input type="radio" class="message_pri" id="web" name="web" value="Web">Web</label>
  <label><input type="radio" class="message_pri" id="mobile" name="web" value="Mobile">Mobile</label>
  <button class="btn btn-primary nextBtn btn-lg pull-right btnnext" type="button" >Next</button>
</div></code>```

Body:
I have two radio in my blade and i want if radio 1 checked display some step in modal popup
 else if radio 2 checked display another step in this modal event

this is my radio in view :

 Step 1

  <input type="radio" class="message_pri" id="web" name="web" value="Web">Web
  <input type="radio" class="message_pri" id="mobile" name="web" value="Mobile">Mobile
  <button class="btn btn-primary nextBtn btn-lg pull-right btnnext" type="button" >Next</button>

Body:
Try this:

$('.message_pri').change(function(){
  if($(this).val() == 'Web')
  {
    alert('Web is selected')
  }
  else
  {
    alert('Mobile is selected')
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row setup-content" id="step-1">
  <div class="col-xs-6 col-md-offset-3">
  <div class="col-md-12">
  <h3> Step 1</h3>
  <label><input type="radio" class="message_pri" id="web" name="web" value="Web">Web</label>
  <label><input type="radio" class="message_pri" id="mobile" name="web" value="Mobile">Mobile</label>
  <button class="btn btn-primary nextBtn btn-lg pull-right btnnext" type="button" >Next</button>
</div>


问:
Add songs to Jquery JAudio playlist without refreshing player
I am building a custom mp3 player for a entertainment web site and i need to add songs continuously even when playing a song. to do that i'm using this function.

```<code>var temp = [];
var tempObj = [];

function popUp(file,thumb,trackName,trackArtist,trackAlbum) {

    var validate = true;
    if (temp.length>0) {
        for (var x = 0; x < temp.length; x++) {
            if (temp[x]['trackName'] == trackName) {
                validate = false;
            }
        }
    }
    if (validate==true){

        // Save data to object
        tempObj = { file: file, thumb: thumb, trackName: trackName, trackArtist: trackArtist, trackAlbum: trackAlbum };
        temp.push(tempObj); // push object to existing array
        $("#player").jAudio({playlist: temp});

    }
}
</code>```

Problem is that to add songs to player we need to run that "jAudio()" function. because of that every time "popUp()" function called it calling the "jAudio()" function. if any one have a solution, please shear it..

This is the JAudio API.

```<code>!function (t) {
    function i(i, a) {
        this.settings = t.extend(!0, r, a), this.$context = i, this.domAudio = this.$context.find("audio")[0], this.$domPlaylist = this.$context.find(".jAudio--playlist"), this.$domControls = this.$context.find(".jAudio--controls"), this.$domVolumeBar = this.$context.find(".jAudio--volume"), this.$domDetails = this.$context.find(".jAudio--details"), this.$domStatusBar = this.$context.find(".jAudio--status-bar"), this.$domProgressBar = this.$context.find(".jAudio--progress-bar-wrapper"), this.$domTime = this.$context.find(".jAudio--time"), this.$domElapsedTime = this.$context.find(".jAudio--time-elapsed"), this.$domTotalTime = this.$context.find(".jAudio--time-total"), this.$domThumb = this.$context.find(".jAudio--thumb"), this.currentState = "pause", this.currentTrack = this.settings.defaultTrack, this.timer = void 0, this.init()
    }

    function a(t, i) {
        for (var t = String(t); t.length < i;)t = "0" + t;
        return t
    }

    var e = "jAudio", r = {
        playlist: [],
        defaultAlbum: void 0,
        defaultArtist: void 0,
        defaultTrack: 0,
        autoPlay: !1,
        debug: !1
    };
    i.prototype = {
        init: function () {
            var t = this;
            t.renderPlaylist(), t.preLoadTrack(), t.highlightTrack(), t.updateTotalTime(), t.events(), t.debug(), t.domAudio.volume = .2
        }, play: function () {
            var t = this, i = t.$domControls.find("#btn-play");
            t.currentState = "play", t.domAudio.play(), clearInterval(t.timer), t.timer = setInterval(t.run.bind(t), 50), i.data("action", "pause"), i.attr("id", "btn-pause"), i.toggleClass("active")
        }, pause: function () {
            var t = this, i = t.$domControls.find("#btn-pause");
            t.domAudio.pause(), clearInterval(t.timer), t.currentState = "pause", i.data("action", "play"), i.attr("id", "btn-play"), i.toggleClass("active")
        }, stop: function () {
            var t = this;
            t.domAudio.pause(), t.domAudio.currentTime = 0, t.animateProgressBarPosition(), clearInterval(t.timer), t.updateElapsedTime(), t.currentState = "stop"
        }, prev: function () {
            var t, i = this;
            t = 0 === i.currentTrack ? i.settings.playlist.length - 1 : i.currentTrack - 1, i.changeTrack(t)
        }, next: function () {
            var t, i = this;
            t = i.currentTrack === i.settings.playlist.length - 1 ? 0 : i.currentTrack + 1, i.changeTrack(t)
        }, preLoadTrack: function () {
            var t = this;
            t.changeTrack(t.settings.defaultTrack), t.settings.autoPlay && t.play()
        }, changeTrack: function (t) {
            var i = this;
            i.currentTrack = t, i.domAudio.src = i.settings.playlist[t].file, i.highlightTrack(), i.updateThumb(), i.renderDetails(), "play" === i.currentState && i.play()
        }, events: function () {
            var i = this;
            i.$domControls.on("click", "button", function () {
                var a = t(this).data("action");
                switch (a) {
                    case"prev":
                        i.prev.call(i);
                        break;
                    case"next":
                        i.next.call(i);
                        break;
                    case"pause":
                        i.pause.call(i);
                        break;
                    case"stop":
                        i.stop.call(i);
                        break;
                    case"play":
                        i.play.call(i)
                }
            }), i.$domPlaylist.on("click", ".jAudio--playlist-item", function () {
                var a = t(this), e = (a.data("track"), a.index());
                i.currentTrack !== e && i.changeTrack(e)
            }), i.$domProgressBar.on("click", function (t) {
                i.updateProgressBar(t), i.updateElapsedTime()
            }), t(i.domAudio).on("loadedmetadata", function () {
                i.animateProgressBarPosition.call(i), i.updateElapsedTime.call(i), i.updateTotalTime.call(i)
            })
        }, getAudioSeconds: function (t) {
            var t = t % 60;
            return t = a(Math.floor(t), 2), t = 60 > t ? t : "00"
        }, getAudioMinutes: function (t) {
            var t = t / 60;
            return t = a(Math.floor(t), 2), t = 60 > t ? t : "00"
        }, highlightTrack: function () {
            var t = this, i = t.$domPlaylist.children(), a = "active";
            i.removeClass(a), i.eq(t.currentTrack).addClass(a)
        }, renderDetails: function () {
            var t = this, i = t.settings.playlist[t.currentTrack], a = (i.file, i.thumb, i.trackName), e = i.trackArtist, r = (i.trackAlbum, "");
            r += "<p>", r += "<span>" + a + "</span>", r += "<span>" + e + "</span>", r += "</p>", t.$domDetails.html(r)
        }, renderPlaylist: function () {
            var i = this, a = "";
            t.each(i.settings.playlist, function (t, i) {
                {
                    var e = i.file, r = i.thumb, o = i.trackName, s = i.trackArtist;
                    i.trackAlbum
                }
                trackDuration = "00:00", a += "<div class='jAudio--playlist-item' data-track='" + e + "'>", a += "<div class='jAudio--playlist-thumb'><img src='" + r + "'></div>", a += "<div class='jAudio--playlist-meta-text'>", a += "<h4>" + o + "</h4>", a += "<p>" + s + "</p>", a += "</div>", a += "</div>"
            }), i.$domPlaylist.html(a)
        }, run: function () {
            var t = this;
            t.animateProgressBarPosition(), t.updateElapsedTime(), t.domAudio.ended && t.next()
        }, animateProgressBarPosition: function () {
            var t = this, i = 100 * t.domAudio.currentTime / t.domAudio.duration + "%", a = {width: i};
            t.$domProgressBar.children().eq(0).css(a)
        }, updateProgressBar: function (t) {
            var i, a, e, r = this;
            t.offsetX && (i = t.offsetX), void 0 === i && t.layerX && (i = t.layerX), a = i / r.$domProgressBar.width(), e = r.domAudio.duration * a, r.domAudio.currentTime = e, r.animateProgressBarPosition()
        }, updateElapsedTime: function () {
            var t = this, i = t.domAudio.currentTime, a = t.getAudioMinutes(i), e = t.getAudioSeconds(i), r = a + ":" + e;
            t.$domElapsedTime.text(r)
        }, updateTotalTime: function () {
            var t = this, i = t.domAudio.duration, a = t.getAudioMinutes(i), e = t.getAudioSeconds(i), r = a + ":" + e;
            t.$domTotalTime.text(r)
        }, updateThumb: function () {
            var t = this, i = t.settings.playlist[t.currentTrack].thumb, a = {"background-image": "url(" + i + ")"};
            t.$domThumb.css(a)
        }, debug: function () {
            var t = this;
            t.settings.debug && console.log(t)
        }
    }, t.fn[e] = function (a) {
        var e = function () {
            return new i(t(this), a)
        };
        t(this).each(e)
    }
}(jQuery);

// initialize
(function () {

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

答:
This is old, but if you are willing to go a little nasty, I have a working workaround. Forgive me for the nasty approach, in the end though - it works.

We are gonna make use of window here to use as a global scope across the functions.

```<code>init: function()
{
  var self = this;
  self.renderPlaylist();
  self.preLoadTrack();
  self.highlightTrack();
  self.updateTotalTime();
  self.events();
  self.debug();
  self.domAudio.volume = 0.05;
  window.jAudioCore = self; // This line returns the self
},
</code>```

Now you can change the playlist accordingly, anytime, just by changing window.playlist global variable, everywhere in the code.

```<code>    renderPlaylist: function()
{
  var self = this,
      template = "";

  $.each(window.playlist, function(i, a) //added window.playlist as the parameter
</code>```

Your renderPlaylist function should look the one above.

To test this here's a simple code for you to use :

```<code>(function(){
window.playlist = [
      {
        file: "http://192.168.1.99:5000/mpeg",
        thumb: "https://i.ytimg.com/vi/Kd57YHWqrsI/mqdefault.jpg",
        trackName: "Carnival Of Rust",
        trackArtist: "Poets Of The Fall",
        trackAlbum: "Single",
        trackDuration:"04:06",
      },
      {
        file: "http://127.0.0.1:5000/mpeg",
        thumb: "https://i.ytimg.com/vi/Kd57YHWqrsI/mqdefault.jpg",
        trackName: "Carnival Of Rust",
        trackArtist: "Poets Of The Fall",
        trackAlbum: "Single",
        trackDuration:"04:06",
      }
  ];

  var t = {
    playlist: [], // this is no longer needed, you can remove it from the source code later
    debug:true
  }
  $(".jAudio").jAudio(t);
    setTimeout(function(){
    window.playlist.push({
        file: "http://127.0.0.1:5000/mpeg",
        thumb: "https://i.ytimg.com/vi/Kd57YHWqrsI/mqdefault.jpg",
        trackName: "Carnival Of Rust",
        trackArtist: "Poets Of The Fall",
        trackAlbum: "Single",
        trackDuration:"04:06",
      });
       window.jAudioCore.renderPlaylist(); // renders the playlists
       window.jAudioCore.preLoadTrack(); // will preload the current track
       window.jAudioCore.highlightTrack(); // will highlight in the css

    },3000);

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

As I said, in the end, it works dynamically without refresh. There might be some underlying bugs, I couldn't test much on this. Cheers.

Body:
I am building a custom mp3 player for a entertainment web site and i need to add songs continuously even when playing a song. to do that i'm using this function.

var temp = [];
var tempObj = [];

function popUp(file,thumb,trackName,trackArtist,trackAlbum) {

    var validate = true;
    if (temp.length>0) {
        for (var x = 0; x < temp.length; x++) {
            if (temp[x]['trackName'] == trackName) {
                validate = false;
            }
        }
    }
    if (validate==true){

        // Save data to object
        tempObj = { file: file, thumb: thumb, trackName: trackName, trackArtist: trackArtist, trackAlbum: trackAlbum };
        temp.push(tempObj); // push object to existing array
        $("#player").jAudio({playlist: temp});

    }
}

Problem is that to add songs to player we need to run that "jAudio()" function. because of that every time "popUp()" function called it calling the "jAudio()" function. if any one have a solution, please shear it..

This is the JAudio API.

!function (t) {
    function i(i, a) {
        this.settings = t.extend(!0, r, a), this.$context = i, this.domAudio = this.$context.find("audio")[0], this.$domPlaylist = this.$context.find(".jAudio--playlist"), this.$domControls = this.$context.find(".jAudio--controls"), this.$domVolumeBar = this.$context.find(".jAudio--volume"), this.$domDetails = this.$context.find(".jAudio--details"), this.$domStatusBar = this.$context.find(".jAudio--status-bar"), this.$domProgressBar = this.$context.find(".jAudio--progress-bar-wrapper"), this.$domTime = this.$context.find(".jAudio--time"), this.$domElapsedTime = this.$context.find(".jAudio--time-elapsed"), this.$domTotalTime = this.$context.find(".jAudio--time-total"), this.$domThumb = this.$context.find(".jAudio--thumb"), this.currentState = "pause", this.currentTrack = this.settings.defaultTrack, this.timer = void 0, this.init()
    }

    function a(t, i) {
        for (var t = String(t); t.length < i;)t = "0" + t;
        return t
    }

    var e = "jAudio", r = {
        playlist: [],
        defaultAlbum: void 0,
        defaultArtist: void 0,
        defaultTrack: 0,
        autoPlay: !1,
        debug: !1
    };
    i.prototype = {
        init: function () {
            var t = this;
            t.renderPlaylist(), t.preLoadTrack(), t.highlightTrack(), t.updateTotalTime(), t.events(), t.debug(), t.domAudio.volume = .2
        }, play: function () {
            var t = this, i = t.$domControls.find("#btn-play");
            t.currentState = "play", t.domAudio.play(), clearInterval(t.timer), t.timer = setInterval(t.run.bind(t), 50), i.data("action", "pause"), i.attr("id", "btn-pause"), i.toggleClass("active")
        }, pause: function () {
            var t = this, i = t.$domControls.find("#btn-pause");
            t.domAudio.pause(), clearInterval(t.timer), t.currentState = "pause", i.data("action", "play"), i.attr("id", "btn-play"), i.toggleClass("active")
        }, stop: function () {
            var t = this;
            t.domAudio.pause(), t.domAudio.currentTime = 0, t.animateProgressBarPosition(), clearInterval(t.timer), t.updateElapsedTime(), t.currentState = "stop"
        }, prev: function () {
            var t, i = this;
            t = 0 === i.currentTrack ? i.settings.playlist.length - 1 : i.currentTrack - 1, i.changeTrack(t)
        }, next: function () {
            var t, i = this;
            t = i.currentTrack === i.settings.playlist.length - 1 ? 0 : i.currentTrack + 1, i.changeTrack(t)
        }, preLoadTrack: function () {
            var t = this;
            t.changeTrack(t.settings.defaultTrack), t.settings.autoPlay && t.play()
        }, changeTrack: function (t) {
            var i = this;
            i.currentTrack = t, i.domAudio.src = i.settings.playlist[t].file, i.highlightTrack(), i.updateThumb(), i.renderDetails(), "play" === i.currentState && i.play()
        }, events: function () {
            var i = this;
            i.$domControls.on("click", "button", function () {
                var a = t(this).data("action");
                switch (a) {
                    case"prev":
                        i.prev.call(i);
                        break;
                    case"next":
                        i.next.call(i);
                        break;
                    case"pause":
                        i.pause.call(i);
                        break;
                    case"stop":
                        i.stop.call(i);
                        break;
                    case"play":
                        i.play.call(i)
                }
            }), i.$domPlaylist.on("click", ".jAudio--playlist-item", function () {
                var a = t(this), e = (a.data("track"), a.index());
                i.currentTrack !== e && i.changeTrack(e)
            }), i.$domProgressBar.on("click", function (t) {
                i.updateProgressBar(t), i.updateElapsedTime()
            }), t(i.domAudio).on("loadedmetadata", function () {
                i.animateProgressBarPosition.call(i), i.updateElapsedTime.call(i), i.updateTotalTime.call(i)
            })
        }, getAudioSeconds: function (t) {
            var t = t % 60;
            return t = a(Math.floor(t), 2), t = 60 > t ? t : "00"
        }, getAudioMinutes: function (t) {
            var t = t / 60;
            return t = a(Math.floor(t), 2), t = 60 > t ? t : "00"
        }, highlightTrack: function () {
            var t = this, i = t.$domPlaylist.children(), a = "active";
            i.removeClass(a), i.eq(t.currentTrack).addClass(a)
        }, renderDetails: function () {
            var t = this, i = t.settings.playlist[t.currentTrack], a = (i.file, i.thumb, i.trackName), e = i.trackArtist, r = (i.trackAlbum, "");
            r += "
", r += "" + a + "", r += "" + e + "", r += "
", t.$domDetails.html(r)
        }, renderPlaylist: function () {
            var i = this, a = "";
            t.each(i.settings.playlist, function (t, i) {
                {
                    var e = i.file, r = i.thumb, o = i.trackName, s = i.trackArtist;
                    i.trackAlbum
                }
                trackDuration = "00:00", a += "
", a += "

", a += "
", a += "
" + o + "
", a += "
" + s + "
", a += "
", a += "
"
            }), i.$domPlaylist.html(a)
        }, run: function () {
            var t = this;
            t.animateProgressBarPosition(), t.updateElapsedTime(), t.domAudio.ended && t.next()
        }, animateProgressBarPosition: function () {
            var t = this, i = 100 * t.domAudio.currentTime / t.domAudio.duration + "%", a = {width: i};
            t.$domProgressBar.children().eq(0).css(a)
        }, updateProgressBar: function (t) {
            var i, a, e, r = this;
            t.offsetX && (i = t.offsetX), void 0 === i && t.layerX && (i = t.layerX), a = i / r.$domProgressBar.width(), e = r.domAudio.duration * a, r.domAudio.currentTime = e, r.animateProgressBarPosition()
        }, updateElapsedTime: function () {
            var t = this, i = t.domAudio.currentTime, a = t.getAudioMinutes(i), e = t.getAudioSeconds(i), r = a + ":" + e;
            t.$domElapsedTime.text(r)
        }, updateTotalTime: function () {
            var t = this, i = t.domAudio.duration, a = t.getAudioMinutes(i), e = t.getAudioSeconds(i), r = a + ":" + e;
            t.$domTotalTime.text(r)
        }, updateThumb: function () {
            var t = this, i = t.settings.playlist[t.currentTrack].thumb, a = {"background-image": "url(" + i + ")"};
            t.$domThumb.css(a)
        }, debug: function () {
            var t = this;
            t.settings.debug && console.log(t)
        }
    }, t.fn[e] = function (a) {
        var e = function () {
            return new i(t(this), a)
        };
        t(this).each(e)
    }
}(jQuery);

// initialize
(function () {

}());

Body:
This is old, but if you are willing to go a little nasty, I have a working workaround. Forgive me for the nasty approach, in the end though - it works.

We are gonna make use of window here to use as a global scope across the functions.

init: function()
{
  var self = this;
  self.renderPlaylist();
  self.preLoadTrack();
  self.highlightTrack();
  self.updateTotalTime();
  self.events();
  self.debug();
  self.domAudio.volume = 0.05;
  window.jAudioCore = self; // This line returns the self
},

Now you can change the playlist accordingly, anytime, just by changing window.playlist global variable, everywhere in the code.

    renderPlaylist: function()
{
  var self = this,
      template = "";

  $.each(window.playlist, function(i, a) //added window.playlist as the parameter

Your renderPlaylist function should look the one above.

To test this here's a simple code for you to use :

(function(){
window.playlist = [
      {
        file: "http://192.168.1.99:5000/mpeg",
        thumb: "https://i.ytimg.com/vi/Kd57YHWqrsI/mqdefault.jpg",
        trackName: "Carnival Of Rust",
        trackArtist: "Poets Of The Fall",
        trackAlbum: "Single",
        trackDuration:"04:06",
      },
      {
        file: "http://127.0.0.1:5000/mpeg",
        thumb: "https://i.ytimg.com/vi/Kd57YHWqrsI/mqdefault.jpg",
        trackName: "Carnival Of Rust",
        trackArtist: "Poets Of The Fall",
        trackAlbum: "Single",
        trackDuration:"04:06",
      }
  ];

  var t = {
    playlist: [], // this is no longer needed, you can remove it from the source code later
    debug:true
  }
  $(".jAudio").jAudio(t);
    setTimeout(function(){
    window.playlist.push({
        file: "http://127.0.0.1:5000/mpeg",
        thumb: "https://i.ytimg.com/vi/Kd57YHWqrsI/mqdefault.jpg",
        trackName: "Carnival Of Rust",
        trackArtist: "Poets Of The Fall",
        trackAlbum: "Single",
        trackDuration:"04:06",
      });
       window.jAudioCore.renderPlaylist(); // renders the playlists
       window.jAudioCore.preLoadTrack(); // will preload the current track
       window.jAudioCore.highlightTrack(); // will highlight in the css

    },3000);

})();

As I said, in the end, it works dynamically without refresh. There might be some underlying bugs, I couldn't test much on this. Cheers.


问:
WooCommerce remove product from loop by id
I'm trying to hide woocommerce products from the loop if any of the variation are out of stock.

What I have tried so far

1: Get the current logged in users "region"
2: Get a list of all product variation which are regions to check against the user region.
3: Run a check and if matches hide the product
4: Exclude the product from the loop

Any incite would be greatly appreciated.

```<code>function tm_remove_product_stock_region($query) {

    $product_variable = new WC_Product_Variable();
    $product_variations = $product_variable->get_available_variations();

/** Get users region. */
    $user_region = tm_get_user_region();

    $post__in = array();

    foreach ( $product_variations as $variation ) {

        /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

        if ($user_region === $product_region && !$variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

          add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = false;
                return $is_visible;
            }, 10,2);

        } else if ($user_region === $product_region && $variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

            add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = true;
                return $is_visible;
            }, 10,2);

        }

    }

    if(is_array($post__in) && $post__in != null){
        $query->set('post__in', $post__in);
    }

    return $query;

 }

 add_action('pre_get_posts', 'tm_remove_product_stock_region', 10, 2);
</code>```

Update 2:

I update the above and got it to work, BUT woocommerce_product_is_visible filter only works on category archive pages, Noting gets filtered for search page or when WP_Query is used on a custom page which is a real shame. Also is their a reason why $is_visible for woocommerce wont work with pre_get_posts

```<code>Function tm_remove_product_stock_region($is_visible, $id) {

    $product = wc_get_product(get_the_ID());

    $product_variable = new WC_Product_Variable(get_the_ID());
    $product_variations = $product_variable->get_available_variations();

    /** Get users region. */
    $user_region = tm_get_user_region();

    foreach ($product_variations as $variation) {

       /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

       if (!$product->is_in_stock() && $user_region === $product_region) {

            $is_visible = false;
            return $is_visible;

       }

       else if ($product->is_in_stock() && $user_region === $product_region) {

            $is_visible = true;
            return $is_visible;

       }
    }

}

add_filter('woocommerce_product_is_visible', 'tm_remove_product_stock_region', 10,2);
</code>```

Update 3:

After more hours of fiddling about I just noticed that $product_variable in both functions returns a different set of results ie with "woocommerce_product_is_visible" the products parent ID get returned but with "pre_get_posts" it's the variation ID.

So I don't get the result I wanted and pre_get_posts fails which is what  I actually need to work, I still have not solved this.

答:
You need to set the meta_query before loop,</p>

```<code>function tm_remove_product_stock_region($query) {
    $query->set( 'meta_query', array(array(
        'key'       => '_stock_status',
        'value'     => 'outofstock',
        'compare'   => 'NOT IN'
    )));
return $query;

    }
add_action('pre_get_posts', 'tm_remove_product_stock_region');
</code>```

Body:
I'm trying to hide woocommerce products from the loop if any of the variation are out of stock.

What I have tried so far

1: Get the current logged in users "region"
2: Get a list of all product variation which are regions to check against the user region.
3: Run a check and if matches hide the product
4: Exclude the product from the loop

Any incite would be greatly appreciated.

function tm_remove_product_stock_region($query) {

    $product_variable = new WC_Product_Variable();
    $product_variations = $product_variable->get_available_variations();

/** Get users region. */
    $user_region = tm_get_user_region();

    $post__in = array();

    foreach ( $product_variations as $variation ) {

        /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

        if ($user_region === $product_region && !$variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

          add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = false;
                return $is_visible;
            }, 10,2);

        } else if ($user_region === $product_region && $variation->is_in_stock()) {

          $post__in[] = $variation['product_id'];

            add_filter('woocommerce_product_is_visible', function($is_visible, $id) {
                $is_visible = true;
                return $is_visible;
            }, 10,2);

        }

    }

    if(is_array($post__in) && $post__in != null){
        $query->set('post__in', $post__in);
    }

    return $query;

 }

 add_action('pre_get_posts', 'tm_remove_product_stock_region', 10, 2);

Update 2:

I update the above and got it to work, BUT woocommerce_product_is_visible filter only works on category archive pages, Noting gets filtered for search page or when WP_Query is used on a custom page which is a real shame. Also is their a reason why $is_visible for woocommerce wont work with pre_get_posts

Function tm_remove_product_stock_region($is_visible, $id) {

    $product = wc_get_product(get_the_ID());

    $product_variable = new WC_Product_Variable(get_the_ID());
    $product_variations = $product_variable->get_available_variations();

    /** Get users region. */
    $user_region = tm_get_user_region();

    foreach ($product_variations as $variation) {

       /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];

       if (!$product->is_in_stock() && $user_region === $product_region) {

            $is_visible = false;
            return $is_visible;

       }

       else if ($product->is_in_stock() && $user_region === $product_region) {

            $is_visible = true;
            return $is_visible;

       }
    }

}

add_filter('woocommerce_product_is_visible', 'tm_remove_product_stock_region', 10,2);

Update 3:

After more hours of fiddling about I just noticed that $product_variable in both functions returns a different set of results ie with "woocommerce_product_is_visible" the products parent ID get returned but with "pre_get_posts" it's the variation ID.

So I don't get the result I wanted and pre_get_posts fails which is what  I actually need to work, I still have not solved this.

Body:
You need to set the meta_query before loop,

function tm_remove_product_stock_region($query) {
    $query->set( 'meta_query', array(array(
        'key'       => '_stock_status',
        'value'     => 'outofstock',
        'compare'   => 'NOT IN'
    )));
return $query;

    }
add_action('pre_get_posts', 'tm_remove_product_stock_region');


问:
How To Perform asynchronous task in django?
I am a bit lost here. I want to send email using django on a post request. But I don't want the user to wait for a reply so I am sending it in a background thread. Also the  emails are to be send every 30 seconds in a sequential order provided by the user.

But there is a option for the user to cancel sending the emails i.e a different post request to handle the cancel input.

How do I listen for cancel operation in the thread sending the email?
How do I implement the 30 second delay?
I thought of using sleep but if I do that then will it skip the cancel signal?

答: As mentioned above, it would probably be the case of using a Celery task for sending the e-mails asynchronously. Then, for cancelling the e-mails sending, your view handling the POST (for cancelling) request could revoke the tasks responsible for sending that sequence of e-mails. This question/answer shows how to do it.</p>


问:
Prompt file download with XMLHttpRequest
I'm aware that jQuery's ajax method cannot handle downloads, and I do not want to add a jQuery plugin to do this.

I want to know how to send POST data with XMLHttpRequest to download a file.

Here's what I've tried:

```<code>var postData = new FormData();
postData.append('cells', JSON.stringify(output));

var xhr = new XMLHttpRequest();
xhr.open('POST', '/export/', true);
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    console.log(e);
    console.log(xhr);
}
xhr.send(postData);
</code>```

I'm working with Django, and the file appears to be sending back to the client successfully.   In the network tab in Chrome, I can see gibberish in the preview tab (which I expect).  But I want to send back a zip file, not a text representation of the zip file.  Here's the Django back end:

```<code>wrapper = FileWrapper(tmp_file)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = "attachment; filename=export.zip"
response['Content-Length'] = tmp_file.tell()
return response
</code>```

I've searched this for hours now without finding a proper example on how to do this with XMLHttpRequests.  I don't want to create a proper html form with a POST action because the form data is rather large, and dynamically created.

Is there something wrong with the above code?  Something I'm missing?  I just don't know how to actually send the data to the client as a download.

答:
If you set the XMLHttpRequest.responseType property to 'blob' before sending the request, then when you get the response back, it will be represented as a blob.  You can then save the blob to a temporary file and navigate to it.

```<code>var postData = new FormData();
postData.append('cells', JSON.stringify(output));

var xhr = new XMLHttpRequest();
xhr.open('POST', '/export/', true);
xhr.setRequestHeader('X-CSRFToken', csrftoken);
xhr.responseType = 'blob';
xhr.onload = function (e) {
    var blob = e.currentTarget.response;
    var contentDispo = e.currentTarget.getResponseHeader('Content-Disposition');
    // https://stackoverflow.com/a/23054920/
    var fileName = contentDispo.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1];
    saveOrOpenBlob(blob, fileName);
}
xhr.send(postData);
</code>```

And here's an example implementation of saveOrOpenBlob:

```<code>function saveOrOpenBlob(blob, fileName) {
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
        fs.root.getFile(fileName, { create: true }, function (fileEntry) {
            fileEntry.createWriter(function (fileWriter) {
                fileWriter.addEventListener("writeend", function () {
                    window.location = fileEntry.toURL();
                }, false);
                fileWriter.write(blob, "_blank");
            }, function () { });
        }, function () { });
    }, function () { });
}
</code>```

If you don't care about having the browser navigate to the file when it's a viewable file type, then making a method that always saves directly to file is much simpler:

```<code>function saveBlob(blob, fileName) {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(blob);
    a.download = fileName;
    a.dispatchEvent(new MouseEvent('click'));
}
</code>```

Body:
I'm aware that jQuery's ajax method cannot handle downloads, and I do not want to add a jQuery plugin to do this.

I want to know how to send POST data with XMLHttpRequest to download a file.

Here's what I've tried:

var postData = new FormData();
postData.append('cells', JSON.stringify(output));

var xhr = new XMLHttpRequest();
xhr.open('POST', '/export/', true);
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    console.log(e);
    console.log(xhr);
}
xhr.send(postData);

I'm working with Django, and the file appears to be sending back to the client successfully.   In the network tab in Chrome, I can see gibberish in the preview tab (which I expect).  But I want to send back a zip file, not a text representation of the zip file.  Here's the Django back end:

wrapper = FileWrapper(tmp_file)
response = HttpResponse(wrapper, content_type='application/zip')
response['Content-Disposition'] = "attachment; filename=export.zip"
response['Content-Length'] = tmp_file.tell()
return response

I've searched this for hours now without finding a proper example on how to do this with XMLHttpRequests.  I don't want to create a proper html form with a POST action because the form data is rather large, and dynamically created.

Is there something wrong with the above code?  Something I'm missing?  I just don't know how to actually send the data to the client as a download.

Body:
If you set the XMLHttpRequest.responseType property to 'blob' before sending the request, then when you get the response back, it will be represented as a blob.  You can then save the blob to a temporary file and navigate to it.

var postData = new FormData();
postData.append('cells', JSON.stringify(output));

var xhr = new XMLHttpRequest();
xhr.open('POST', '/export/', true);
xhr.setRequestHeader('X-CSRFToken', csrftoken);
xhr.responseType = 'blob';
xhr.onload = function (e) {
    var blob = e.currentTarget.response;
    var contentDispo = e.currentTarget.getResponseHeader('Content-Disposition');
    // https://stackoverflow.com/a/23054920/
    var fileName = contentDispo.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)[1];
    saveOrOpenBlob(blob, fileName);
}
xhr.send(postData);

And here's an example implementation of saveOrOpenBlob:

function saveOrOpenBlob(blob, fileName) {
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) {
        fs.root.getFile(fileName, { create: true }, function (fileEntry) {
            fileEntry.createWriter(function (fileWriter) {
                fileWriter.addEventListener("writeend", function () {
                    window.location = fileEntry.toURL();
                }, false);
                fileWriter.write(blob, "_blank");
            }, function () { });
        }, function () { });
    }, function () { });
}

If you don't care about having the browser navigate to the file when it's a viewable file type, then making a method that always saves directly to file is much simpler:

function saveBlob(blob, fileName) {
    var a = document.createElement('a');
    a.href = window.URL.createObjectURL(blob);
    a.download = fileName;
    a.dispatchEvent(new MouseEvent('click'));
}


问:
How can I fetch values from object array using jquery and javascript
I have this array structure :

```<code>var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };
</code>```

I want to fetch data from $obj->section2->row4->key2. How can I make it using jquery and javascript both.

UPDATE: I want it to print the value in a paragraph or div

```<code><p id="array"></p>
</code>```

答:
Actually it looks quiet simple your requirement
You can use the array notation or (.) dot operator

1) Array notation  $obj['section2']['row4']['key2'];

2) Dot operator $obj.section2.row4.key2;

Nb: Please use array notation It would be safe in case of unknown keys if the key has a space in it

If you need it iterate through all the keys you can use for in loop

Body:
I have this array structure :

var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

I want to fetch data from $obj->section2->row4->key2. How can I make it using jquery and javascript both.

UPDATE: I want it to print the value in a paragraph or div


问:
MS Access Field splitting
I am trying to split following data field in separate columns like using ":" separator,

Actual Data

```<code>DSLAM name:Port address
M301-41-301_DDOW3:1-0-7-1
</code>```

Result

```<code>DSLAM name  Port address
M301-41-301_DDOW3   1-0-7-1
</code>```

I am using following script but having missing operator syntax error.

```<code>UPDATE 14052017 SET

NodeName= left(DSLAMname:Port address, InStr( DSLAMname: Port address, ":") -1),
PortAddress= Mid(DSLAMname:Port address, InStr( DSLAM name: Port address, ":") +1);
</code>```

please point out the mistake here or a better solution

答:
You could make a Function:</p>

```<code>Public Function SplitValue(ByVal value_ As Variant, ByVal index As Long) As String
    If Not IsNull(value_) Then SplitValue = Split(value_, ":")(index)
End Function

'....

UPDATE 14052017 SET
NodeName= SplitValue([DSLAMname:Port address], 0),
PortAddress= SplitValue([DSLAMname:Port address], 1);
</code>```

Title: MS Access Field splitting

Body:
I am trying to split following data field in separate columns like using ":" separator,

Actual Data

DSLAM name:Port address
M301-41-301_DDOW3:1-0-7-1

Result

DSLAM name  Port address
M301-41-301_DDOW3   1-0-7-1

I am using following script but having missing operator syntax error.

UPDATE 14052017 SET

NodeName= left(DSLAMname:Port address, InStr( DSLAMname: Port address, ":") -1),
PortAddress= Mid(DSLAMname:Port address, InStr( DSLAM name: Port address, ":") +1);

please point out the mistake here or a better solution

Body:
You could make a Function:

Public Function SplitValue(ByVal value_ As Variant, ByVal index As Long) As String
    If Not IsNull(value_) Then SplitValue = Split(value_, ":")(index)
End Function

'....

UPDATE 14052017 SET
NodeName= SplitValue([DSLAMname:Port address], 0),
PortAddress= SplitValue([DSLAMname:Port address], 1);


问:
Bash URL not working with youtube-dl
So, until recently i could execute commands without a problem in my Terminal.
Example:

$ youtube-dl COMMAND

done

all is well.

Now i am experiencing strange behaviour form job control, and it looks like an extra process is getting ran every time i am running something.

Example:

Ice$ youtube-dl https://www.youtube.com/watch?v=Kgjkth6BRRY&index=14&list=PL05E1623111A9A860

[1] 3535

[2] 3536

[2]+  Done                    index=14

Ice$ [youtube] Kgjkth6BRRY: Downloading webpage
  [youtube] Kgjkth6BRRY: Downloading video info webpage

****At This point i am forced to press Enter to finish my command which i have never done before******

[1]+  Done                    youtube-dl https://www.youtube.com/watch?v=Kgjkth6BRRY
  Ice$

How, do i verify what the Proccess are and how would i go about fixing this?

答:
Put the URL inside single quotes to preserve the contents inside the quotes. Note that Character like &, $ has special meaning in bash and bash try to interpret them.  To prevent this from happening use single quotes.

Here: Your URL contains & and it means to send any command to the background.

Title: Bash URL not working with youtube-dl


问:
PHP / MySQL - Search query
I need help making a search query for comments (it's for a WordPress site).

the comments are retrieved this way- if user is logged in:

```<code>       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));
</code>```

if not:

```<code>       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));
</code>```

so I how can I filter comments that contain a specific search string, like $_GET['search_query'] ?

this is WP's database structure. The search string I'm looking for is in comment_content

答:
thanks, I'll try. btw what does the percentage sign do before and after $_GET ?

It'll match any number of characters before and after the search string.

Title: PHP / MySQL - Search query

Body:
I need help making a search query for comments (it's for a WordPress site).

the comments are retrieved this way- if user is logged in:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (user_id = %d AND comment_approved = '0'))
       ORDER BY comment_date_gmt", $post->ID, $user_ID));

if not:

       $comments = $wpdb->get_results($wpdb->prepare("
       SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d
       AND (comment_approved = '1' OR (comment_author = %s
         AND comment_author_email = %s AND comment_approved = '0'))
       ORDER BY comment_date_gmt",
       $post->ID, wp_specialchars_decode($comment_author,ENT_QUOTES),
       $comment_author_email));

so I how can I filter comments that contain a specific search string, like $_GET['search_query'] ?

this is WP's database structure. The search string I'm looking for is in comment_content


问:
Android 6 can not communicate with secured server using Self Sign Certificate
I am unable to establish connection between Android 6 app and Secured Server where the server is using self signed certificate generated by Java (jdk 1.6) keytool command. Android 6 app is showing following error.

Excepton Log:

```<code>javax.net.ssl.SSLHandshakeException: Handshake failed : javax.net.ssl.SSLHandshakeException: Handshake failed
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:429)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connectTls(Connection.java:235)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connectSocket(Connection.java:199)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connect(Connection.java:172)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
</code>```

I am using the below code and it is working fine upto android 5.9 but it is not working with android 6(marshmallow); following link provides the code to communicate to ssl -

https://developer.android.com/training/articles/security-ssl.html

```<code>// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
    ca = cf.generateCertificate(caInput);
    System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
    caInput.close();
}

// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);
</code>```

Can anybody please suggest how to resolve this? Is this any certificate generation problem or do I need to follow any new technique to communicate with server?

答:
Android 6 no longer accepts insecure connections, you should use a secure certificate or work around the issue by letting the app ignore insecure certificates (this creates heavy security issues and is not recommended at all).

From Android Developers: https://developer.android.com/training/articles/security-ssl.html

Self-signed server certificate The second case of SSLHandshakeException is due to a self-signed certificate, which means
  the server is behaving as its own CA. This is similar to an unknown
  certificate authority, so you can use the same approach from the
  previous section.

You can create your own TrustManager, this time trusting the server
  certificate directly. This has all of the downsides discussed earlier
  of tying your app directly to a certificate, but can be done securely.
  However, you should be careful to make sure your self-signed
  certificate has a reasonably strong key. As of 2012, a 2048-bit RSA
  signature with an exponent of 65537 expiring yearly is acceptable.
  When rotating keys, you should check for recommendations from an
  authority (such as NIST) about what is acceptable

Body:
I am unable to establish connection between Android 6 app and Secured Server where the server is using self signed certificate generated by Java (jdk 1.6) keytool command. Android 6 app is showing following error.

Excepton Log:

javax.net.ssl.SSLHandshakeException: Handshake failed : javax.net.ssl.SSLHandshakeException: Handshake failed
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:429)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connectTls(Connection.java:235)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connectSocket(Connection.java:199)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connect(Connection.java:172)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
05-23 17:21:03.498 3602-6487/issac.wise.pay I/System.out:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)

I am using the below code and it is working fine upto android 5.9 but it is not working with android 6(marshmallow); following link provides the code to communicate to ssl -

https://developer.android.com/training/articles/security-ssl.html

// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
Certificate ca;
try {
    ca = cf.generateCertificate(caInput);
    System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
    caInput.close();
}

// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
HttpsURLConnection urlConnection =
    (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();
copyInputStreamToOutputStream(in, System.out);

Can anybody please suggest how to resolve this? Is this any certificate generation problem or do I need to follow any new technique to communicate with server?


问:
How can I use a list comprehension to extend a list in python?
I'm not experienced in Python, and I often write code that (simplified) looks like this:

```<code>accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.append(y)
return accumulationList
</code>```

Then after my test passes, I refactor to

```<code>return [doSomething(x) for x in originalList]
</code>```

But suppose it turns out a little different, and my loop looks like this:

```<code>accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.extend(y)
return accumulationList
</code>```

where the doSomething list returns a list. What is the most Pythonic way to accomplish this? Obviously, the previous list comprehension would give a list of lists.

答:
Much simpler and cleaner with list comprehension:</p>

```<code>[y for x in originalList for y in doSomething(x)]
</code>```

Body:
I'm not experienced in Python, and I often write code that (simplified) looks like this:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.append(y)
return accumulationList

Then after my test passes, I refactor to

return [doSomething(x) for x in originalList]

But suppose it turns out a little different, and my loop looks like this:

accumulationList = []
for x in originalList:
    y = doSomething(x)
    accumulationList.extend(y)
return accumulationList

where the doSomething list returns a list. What is the most Pythonic way to accomplish this? Obviously, the previous list comprehension would give a list of lists.

Body:
Much simpler and cleaner with list comprehension:

[y for x in originalList for y in doSomething(x)]


问:
Find the date for the first Monday after a given date
Given a particular date, say 2011-07-02, how can I find the date of the next Monday (or any weekday day for that matter) after that date?</p>

答:
Another simple elegant solution is to use pandas offsets.

I find it very helpful and robust when playing with dates.

If you want the first Sunday just modify the frequency to freq='W-SUN'.

If you want a couple of next Sundays, change the offsets.Day(days).

Using pandas offsets allow you to ignore holidays, work only with Business Days and more.

You can also apply this method easily on a whole DataFrame using the apply method.

```<code>import pandas as pd
import datetime

# 1. Getting the closest monday from a given date
date = datetime.date(2011, 7, 2)
closest_monday = pd.date_range(start=date, end=date + pd.offsets.Day(6), freq="W-MON")[
    0
]

# 2. Adding a 'ClosestMonday' column with the closest monday for each row in
# a pandas df using apply. Requires you to have a 'Date' column in your df
def get_closest_monday(row):
    return pd.date_range(
        start=row.Date, end=row.Date + pd.offsets.Day(6), freq="W-MON"
    )[0]

df = pd.DataFrame([datetime.date(2011, 7, 2)], columns=["Date"])
df["ClosestMonday"] = df.apply(lambda row: get_closest_monday(row), axis=1)
print(df)
</code>```

Body:
Another simple elegant solution is to use pandas offsets.

I find it very helpful and robust when playing with dates.

If you want the first Sunday just modify the frequency to freq='W-SUN'.

If you want a couple of next Sundays, change the offsets.Day(days).

Using pandas offsets allow you to ignore holidays, work only with Business Days and more.

You can also apply this method easily on a whole DataFrame using the apply method.

import pandas as pd
import datetime

# 1. Getting the closest monday from a given date
date = datetime.date(2011, 7, 2)
closest_monday = pd.date_range(start=date, end=date + pd.offsets.Day(6), freq="W-MON")[
    0
]

# 2. Adding a 'ClosestMonday' column with the closest monday for each row in
# a pandas df using apply. Requires you to have a 'Date' column in your df
def get_closest_monday(row):
    return pd.date_range(
        start=row.Date, end=row.Date + pd.offsets.Day(6), freq="W-MON"
    )[0]

df = pd.DataFrame([datetime.date(2011, 7, 2)], columns=["Date"])
df["ClosestMonday"] = df.apply(lambda row: get_closest_monday(row), axis=1)
print(df)