问:
Static analysis error when using custom 3rd party component in Angular project
I have an Angular (2+) datepicker component (link to Github) that I am currently using in two Angular projects

Angular CLI v1.0.0-beta.30, Angular v2.3

Angular CLI v1.0.0, Angular v4.0

App 1 works perfectly, both during development using ng serve and when building using ng build -prod --aot. App 2 however throws the following error both when attempting to serve and build;

```<code>ERROR in Error encountered resolving symbol values statically. Calling function 'makeDecorator', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/src/metadata/ng_module.d.ts, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/src/metadata.d.ts, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/src/core.d.ts, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/index.d.ts, resolving symbol IcDatepickerModule in /path/to/angular4-app/node_modules/ic-datepicker/dist/src/ic-datepicker.module.d.ts, resolving symbol IcDatepickerModule in /path/to/angular4-app/node_modules/ic-datepicker/dist/src/ic-datepicker.module.d.ts

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/path/to/angular4-app/src'
 @ ./src/main.ts 4:0-74
 @ multi ./src/main.ts
</code>```

My assumption based on this Github issue comment is that the version being used in app 1 above did not perform the static analysis required to trigger this error.

What would cause this error to occur?

Edit

So I've just tried copying the library, stripping it right back to a module and a component that does nothing but output a
 element and try that and the exact same error occurs (link to the stripped back version).

I came across this page and looked into the points there, namely point #8. I moved the Angular dependencies to be peerDependencies (you can see that in the second repo above) but that has not fixed the error.

答:
After hours of digging and trial and error I found the answer. In my question edit I refer to this page and claim that moving the Angular dependencies to peerDependencies in package.json does not fix the issue. This however was not true as I was using npm link to test the library within a new Angular project.

I believe the reason Angular's dependencies should be peerDependencies and not dependencies is because errors occur when node_modules/ic-datepicker/node_modules contains @angular/* dependencies. Moving Angular into peer will instead use the app-level @angular deps preventing this error.

As a side note for anyone who may be testing their local versions of a library, if you have your @angular dependencies added to devDependencies for usage during development, run npm link -production instead of just npm link to prevent the development deps from being installed.

Body:
I have an Angular (2+) datepicker component (link to Github) that I am currently using in two Angular projects

Angular CLI v1.0.0-beta.30, Angular v2.3

Angular CLI v1.0.0, Angular v4.0

App 1 works perfectly, both during development using ng serve and when building using ng build -prod --aot. App 2 however throws the following error both when attempting to serve and build;

ERROR in Error encountered resolving symbol values statically. Calling function 'makeDecorator', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/src/metadata/ng_module.d.ts, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/src/metadata.d.ts, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/src/core.d.ts, resolving symbol NgModule in /path/to/angular4-app/node_modules/ic-datepicker/node_modules/@angular/core/index.d.ts, resolving symbol IcDatepickerModule in /path/to/angular4-app/node_modules/ic-datepicker/dist/src/ic-datepicker.module.d.ts, resolving symbol IcDatepickerModule in /path/to/angular4-app/node_modules/ic-datepicker/dist/src/ic-datepicker.module.d.ts

ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/path/to/angular4-app/src'
 @ ./src/main.ts 4:0-74
 @ multi ./src/main.ts

My assumption based on this Github issue comment is that the version being used in app 1 above did not perform the static analysis required to trigger this error.

What would cause this error to occur?

Edit

So I've just tried copying the library, stripping it right back to a module and a component that does nothing but output a
 element and try that and the exact same error occurs (link to the stripped back version).

I came across this page and looked into the points there, namely point #8. I moved the Angular dependencies to be peerDependencies (you can see that in the second repo above) but that has not fixed the error.


来源: stackexchange

问:
Read the first two lines of each document in a corpus in R
I am having trouble figuring out how to read the first two lines of each document in a corpus in R. The first two lines contain headlines from news articles that I want to analyze. I want to search the headlines (not the rest of each text) for the word 'abortion.'

Here is my code for creating the corpus:

```<code>myCorp <- corpus(readtext(file='~/R/win-library/3.3/quanteda/Abortion/1972/*'))
</code>```

I have tried using readLines in a for loop:

```<code>for (mycorp in myCorp) {
titles <- readLines(mycorp, n = 2)
write.table(mycorp, "1972_text_P.txt", sep="\n\n", append=TRUE)
write.table(titles, "1972_text_P.txt", append=TRUE)
}
</code>```

Error in readLines(mycorp, n = 2) : 'con' is not a connection

I have intentionally not created a DFM because I want to keep the 465 files as single documents in the corpus. How can I get the headlines from the article textx? Or, ideally, how would I search only the first two lines of each document for a keyword (abortion) and create a file that contains only those headlines with the keyword in them? Thanks for any and all help with this.

答:
The readLines function needs a connection object as argument. So as the corpus function doesn't return a connection, you need to create a connection  to the string in the corpus in your loop.

```<code>myCorp <- Corpus(quanteda::data_corpus_inaugural)

for (text in myCorp$documents$texts) {
  con <- textConnection(text,)
  first_lines <- readLines(con, n = 2)
  close.connection(con)

  # Test if the word "speaker" is in the two lines
  if(any(grepl(pattern = "speaker",x = first_lines, ignore.case = T))){
    print(first_lines)
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble figuring out how to read the first two lines of each document in a corpus in R. The first two lines contain headlines from news articles that I want to analyze. I want to search the headlines (not the rest of each text) for the word 'abortion.'

Here is my code for creating the corpus:

myCorp <- corpus(readtext(file='~/R/win-library/3.3/quanteda/Abortion/1972/*'))

I have tried using readLines in a for loop:

for (mycorp in myCorp) {
titles <- readLines(mycorp, n = 2)
write.table(mycorp, "1972_text_P.txt", sep="\n\n", append=TRUE)
write.table(titles, "1972_text_P.txt", append=TRUE)
}

Error in readLines(mycorp, n = 2) : 'con' is not a connection

I have intentionally not created a DFM because I want to keep the 465 files as single documents in the corpus. How can I get the headlines from the article textx? Or, ideally, how would I search only the first two lines of each document for a keyword (abortion) and create a file that contains only those headlines with the keyword in them? Thanks for any and all help with this.

Body:
The readLines function needs a connection object as argument. So as the corpus function doesn't return a connection, you need to create a connection  to the string in the corpus in your loop.

myCorp <- Corpus(quanteda::data_corpus_inaugural)

for (text in myCorp$documents$texts) {
  con <- textConnection(text,)
  first_lines <- readLines(con, n = 2)
  close.connection(con)

  # Test if the word "speaker" is in the two lines
  if(any(grepl(pattern = "speaker",x = first_lines, ignore.case = T))){
    print(first_lines)
  }
}

ContentLicense: CC BY-SA 4.0


问:
javaScript - Find the sum of all divisors of a given integer
i'm doing some coding exercises and i'm not being able to solve this one.

Find the sum of all divisors of a given integer.
For n = 12, the  input should be
sumOfDivisors(n) = 28.

example: 1 + 2 + 3 + 4 + 6 + 12 = 28.

Constraints:
1 ≤ n ≤ 15.

how can i solve this exercise? i'm not being able to.

```<code>function(n){
    var arr = [],
        finalSum;

    if(n <= 1 || n => 16){
       return false ;
   }
   for(var i = 0; i < n; i++){
       var tmp= n/2;
       arr.push(tmp)
       // i need to keep on dividing n but i can't get the way of how to
   }
  return finalSum;
}
</code>```

答:
This is another way to do it:

var divisors = n=>[...Array(n+1).keys()].slice(1)
   .reduce((s, a)=>s+(!(n % a) && a), 0);

console.log(divisors(12));```
</div>
</div>
</p>

<p>JSFiddle: https://jsfiddle.net/32n5jdnb/141/</p>

<p>Explaining:</p>

<ul>
<li><code>n=></code>                   this is an arrow function, the equivalent to function(n) {. You don't need the () if there's only one parameter.</li>
<li><code>Array(n+1)</code>              creates an empty array of n+1 elements</li>
<li><code>.keys()</code>                 gets the keys of the empty array (the indexes i.e. 0, 1, 2) so this is a way to create a numeric sequence</li>
<li><code>[...Array(n+1)].keys()]</code> uses the spread (...) operator to transform the iterator in another array so creating an array with the numeric sequence</li>
<li><code>.slice(1)</code>              removes the first element thus creating a sequence starting with 1. Remember the n+1 ?</li>
<li><code>.reduce()</code>              is a method that iterates though each element and calculates a value in order to reduce the array to one value. It receives as parameter a callback function to calculate the value and the initial value of the calculation</li>
<li><code>(s, a)=></code>               is the callback function for reduce. It's an arrow function equivalent to function(s, a) {</li>
<li><code>s+(!(n % a) && a)</code>    is the calculation of the value. </li>
<li><code>s+</code>                     s (for sum) or the last value calculated + </li>
<li><code>!(n % a)</code>            this returns true only for the elements that have a 0 as modular value.</li>
<li><code>(!(n % a) && a)</code>      is a js 'trick'. The case is that boolean expressions in javascript don't return true or false. They return a 'truthy' or 'falsy' value which is then converted to boolean. So the actual returned value is the right value for && (considering both have to be truthy) and the first thuthy value found for || (considering only one need to be truthy). So this basically means: if <code>a</code> is a modular value (i.e. != 0) return <code>a</code> to add to the sum, else return 0.</li>
<li><code>, 0</code>                    is the initial value for the reduce calculation. </li>
</ul>

<p>Reduce documentation: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce</p>

<p><strong>Edit</strong></p>

<p>Answering to Tristan Forward:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var divisorsList = [];
var divisors = (n)=>[...Array(n+1).keys()].slice(1)
       .reduce((s, a)=>{
          var divisor = !(n % a) && a;
          if (divisor) divisorsList.push(divisor);
          return s+divisor;
       }, 0);

console.log('Result:', divisors(12));
console.log('Divisors:', divisorsList);</code>```

Body:
i'm doing some coding exercises and i'm not being able to solve this one.

Find the sum of all divisors of a given integer.
For n = 12, the  input should be
sumOfDivisors(n) = 28.

example: 1 + 2 + 3 + 4 + 6 + 12 = 28.

Constraints:
1 ≤ n ≤ 15.

how can i solve this exercise? i'm not being able to.

function(n){
    var arr = [],
        finalSum;

    if(n <= 1 || n => 16){
       return false ;
   }
   for(var i = 0; i < n; i++){
       var tmp= n/2;
       arr.push(tmp)
       // i need to keep on dividing n but i can't get the way of how to
   }
  return finalSum;
}

Body:
This is another way to do it:

var divisors = n=>[...Array(n+1).keys()].slice(1)
   .reduce((s, a)=>s+(!(n % a) && a), 0);

console.log(divisors(12));

JSFiddle: https://jsfiddle.net/32n5jdnb/141/

Explaining:

n=>                   this is an arrow function, the equivalent to function(n) {. You don't need the () if there's only one parameter.

Array(n+1)              creates an empty array of n+1 elements

.keys()                 gets the keys of the empty array (the indexes i.e. 0, 1, 2) so this is a way to create a numeric sequence

[...Array(n+1)].keys()] uses the spread (...) operator to transform the iterator in another array so creating an array with the numeric sequence

.slice(1)              removes the first element thus creating a sequence starting with 1. Remember the n+1 ?

.reduce()              is a method that iterates though each element and calculates a value in order to reduce the array to one value. It receives as parameter a callback function to calculate the value and the initial value of the calculation

(s, a)=>               is the callback function for reduce. It's an arrow function equivalent to function(s, a) {

s+(!(n % a) && a)    is the calculation of the value.

s+                     s (for sum) or the last value calculated +

!(n % a)            this returns true only for the elements that have a 0 as modular value.

(!(n % a) && a)      is a js 'trick'. The case is that boolean expressions in javascript don't return true or false. They return a 'truthy' or 'falsy' value which is then converted to boolean. So the actual returned value is the right value for && (considering both have to be truthy) and the first thuthy value found for || (considering only one need to be truthy). So this basically means: if a is a modular value (i.e. != 0) return a to add to the sum, else return 0.

, 0                    is the initial value for the reduce calculation.

Reduce documentation: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Edit

Answering to Tristan Forward:

var divisorsList = [];
var divisors = (n)=>[...Array(n+1).keys()].slice(1)
       .reduce((s, a)=>{
          var divisor = !(n % a) && a;
          if (divisor) divisorsList.push(divisor);
          return s+divisor;
       }, 0);

console.log('Result:', divisors(12));
console.log('Divisors:', divisorsList);


问:
Merging two ul menus that contain child ul with jQuery
I'm trying to merge two unordered lists using jQuery. The second list contains child lists. How would I go about doing this? My HTML looks like this.

```<code><ul class="Menu A">
    <li><a href="#">Item One</a></li>
    <li><a href="#">Item Two</a></li>
    <li><a href="#">Item Three</a></li>
    <li><a href="#">Item Four</a></li>
</ul>

<ul class="Menu B">
    <li><a href="#">Item A</a></li>
    <li><a href="#">Item B</a>
        <ul class="childMenu">
            <li><a href="#">Item B1</a></li>
            <li><a href="#">Item B2</a></li>
            <li><a href="#">Item B3</a></li>
            <li><a href="#">Item B4</a></li>
        </ul>
    </li>
    <li><a href="#">Item C</a></li>
    <li><a href="#">Item D</a></li>
</ul>
</code>```

I tried the solution here merge 2 separate menus into a single menu but it won't work for child lists.

答:
What about simply append the HTML from Menu B after Menu A. So you don't have to worry about looping through multiple levels of list items.

$(function(){
  $("#MenuBoth")
    .html($("#MenuA").html())
    .append($("#MenuB").html());
});```
<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>Menu A</div>
<ul id="MenuA">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
<li>Item Four</li></ul>
<div>Menu B</div>
<ul id="MenuB">
<li>Item A</li>
<li>Item B
        <ul class="childMenu">
            <li>Item B1</li>
            <li>Item B2</li>
            <li>Item B3</li>
            <li>Item B4</li>
    </ul>
</li>
<li>Item C</li>
<li>Item D</li></ul>
<div>Menu Both</div>
<ul id="MenuBoth"></code>```

Body:
I'm trying to merge two unordered lists using jQuery. The second list contains child lists. How would I go about doing this? My HTML looks like this.

Item One

Item Two

Item Three

Item Four

Item A

Item B

Item B1

Item B2

Item B3

Item B4

Item C

Item D

I tried the solution here merge 2 separate menus into a single menu but it won't work for child lists.

Body:
What about simply append the HTML from Menu B after Menu A. So you don't have to worry about looping through multiple levels of list items.

$(function(){
  $("#MenuBoth")
    .html($("#MenuA").html())
    .append($("#MenuB").html());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Menu A</div>
<ul id="MenuA">
<li><a href="#">Item One</a></li>
<li><a href="#">Item Two</a></li>
<li><a href="#">Item Three</a></li>
<li><a href="#">Item Four</a></li></ul>
<div>Menu B</div>
<ul id="MenuB">
<li><a href="#">Item A</a></li>
<li><a href="#">Item B</a>
        <ul class="childMenu">
            <li><a href="#">Item B1</a></li>
            <li><a href="#">Item B2</a></li>
            <li><a href="#">Item B3</a></li>
            <li><a href="#">Item B4</a></li>
    </ul>
</li>
<li><a href="#">Item C</a></li>
<li><a href="#">Item D</a></li></ul>
<div>Menu Both</div>
<ul id="MenuBoth">


问:
Neested loops in pandas python
I have two DataFrames One with many rows and another one with a few rows and I need to merge these two Dataframes according some conditions (in strings). I used nested loops in Pandas like this:

```<code>density = []

for row in df.itertuples():
    for row1 in df2.itertuples():
        if(row['a'].find(row1['b']))>0:
            density.append(row1['c'])
</code>```

But I receive the error message:

```<code>TypeError: tuple indices must be integers, not str
</code>```

What's wrong?

答:
Consider df and df2

```<code>df = pd.DataFrame(dict(
        a=['abcd', 'stk', 'shij', 'dfffedeffj', 'abcdefghijk'],
    ))

df2 = pd.DataFrame(dict(
        b=['abc', 'hij', 'def'],
        c=[1, 2, 3]
    ))
</code>```

You can produce decent-ish speed with get_value and set_value.  And I'd store the values in a dataframe

```<code>density = pd.DataFrame(index=df.index, columns=df2.index)

for i in df.index:
    for j in df2.index:
        a = df.get_value(i, 'a')
        b = df2.get_value(j, 'b')
        if a.find(b) >= 0:
            density.set_value(i, j, df2.get_value(j, 'c'))

print(density)

     0    1    2
0    1  NaN  NaN
1  NaN  NaN  NaN
2  NaN    2  NaN
3  NaN  NaN    3
4    1    2    3
</code>```

You can also use a composite numpy str functions

```<code>t = df2.b.apply(lambda x: df.a.str.contains(x)).values

c = df2.c.values[:, None]

density = pd.DataFrame(
    np.where(t, np.hstack([c] * t.shape[1]), np.nan).T,
    df.index, df2.index)
</code>```

Title: Neested loops in pandas python

Body:
I have two DataFrames One with many rows and another one with a few rows and I need to merge these two Dataframes according some conditions (in strings). I used nested loops in Pandas like this:

density = []

for row in df.itertuples():
    for row1 in df2.itertuples():
        if(row['a'].find(row1['b']))>0:
            density.append(row1['c'])

But I receive the error message:

TypeError: tuple indices must be integers, not str

What's wrong?

Body:
Consider df and df2

df = pd.DataFrame(dict(
        a=['abcd', 'stk', 'shij', 'dfffedeffj', 'abcdefghijk'],
    ))

df2 = pd.DataFrame(dict(
        b=['abc', 'hij', 'def'],
        c=[1, 2, 3]
    ))

You can produce decent-ish speed with get_value and set_value.  And I'd store the values in a dataframe

density = pd.DataFrame(index=df.index, columns=df2.index)

for i in df.index:
    for j in df2.index:
        a = df.get_value(i, 'a')
        b = df2.get_value(j, 'b')
        if a.find(b) >= 0:
            density.set_value(i, j, df2.get_value(j, 'c'))

print(density)

     0    1    2
0    1  NaN  NaN
1  NaN  NaN  NaN
2  NaN    2  NaN
3  NaN  NaN    3
4    1    2    3

You can also use a composite numpy str functions

t = df2.b.apply(lambda x: df.a.str.contains(x)).values

c = df2.c.values[:, None]

density = pd.DataFrame(
    np.where(t, np.hstack([c] * t.shape[1]), np.nan).T,
    df.index, df2.index)


问:
Comparing data in 2 separate DataFrames and producing a result in Python/Pandas
I am new to Python and I'm trying to produce a similar result of Excel's IndexMatch function with Python & Pandas, though I'm struggling to get it working.

Basically, I have 2 separate DataFrames:

The first DataFrame ('market') has 7 columns, though I only need 3 of those columns for this exercise ('symbol', 'date', 'close'). This df has 13,948,340 rows.

The second DataFrame ('transactions') has 14 columns, though only I only need 2 of those columns ('i_symbol', 'acceptance_date'). This df has 1,428,026 rows.

My logic is: If i_symbol is equal to symbol and acceptance_date is equal to date: print symbol, date & close. This should be easy.

I have achieved it with iterrows() but because of the size of the dataset, it returns a single result every 3 minutes - which means I would have to run the script for 1,190 hours to get the final result.

Based on what I have read online, itertuples should be a faster approach, but I am currently getting an error:

ValueError: too many values to unpack (expected 2)

This is the code I have written (which currently produces the above ValueError):

```<code>for i_symbol, acceptance_date in transactions.itertuples(index=False):
  for symbol, date in market.itertuples(index=False):
    if i_symbol == symbol and acceptance_date == date:
        print(market.symbol + market.date + market.close)
</code>```

2 questions:

Is itertuples() the best/fastest approach? If so, how can I get the above working?

Does anyone know a better way? Would indexing work? Should I use an external db (e.g. mysql) instead?

Thanks, Matt

答:
Regarding question 1: pandas.itertuples() yields one namedtuple for each row. You can either unpack these like standard tuples or access the tuple elements by name:

```<code>for t in transactions.itertuples(index=False):
  for m in market.itertuples(index=False):
    if t.i_symbol == m.symbol and t.acceptance_date == m.date:
        print(m.symbol + m.date + m.close)
</code>```

(I did not test this with data frames of your size but I'm pretty sure it's still painfully slow)

Regarding question 2: You can simply merge both data frames on symbol and date.

Rename your "transactions" DataFrame so that it also has columns named "symbol" and "date":

```<code>transactions = transactions[['i_symbol', 'acceptance_date']]
transactions.columns = ['symbol','date']
</code>```

Then merge both DataFrames on symbol and date:

```<code>result = pd.merge(market, transactions, on=['symbol','date'])
</code>```

The result DataFrame consists of one row for each symbol/date combination which exists in both DataFrames. The operation only takes a few seconds on my machine with DataFrames of your size.

Body:
I am new to Python and I'm trying to produce a similar result of Excel's IndexMatch function with Python & Pandas, though I'm struggling to get it working.

Basically, I have 2 separate DataFrames:

The first DataFrame ('market') has 7 columns, though I only need 3 of those columns for this exercise ('symbol', 'date', 'close'). This df has 13,948,340 rows.

The second DataFrame ('transactions') has 14 columns, though only I only need 2 of those columns ('i_symbol', 'acceptance_date'). This df has 1,428,026 rows.

My logic is: If i_symbol is equal to symbol and acceptance_date is equal to date: print symbol, date & close. This should be easy.

I have achieved it with iterrows() but because of the size of the dataset, it returns a single result every 3 minutes - which means I would have to run the script for 1,190 hours to get the final result.

Based on what I have read online, itertuples should be a faster approach, but I am currently getting an error:

ValueError: too many values to unpack (expected 2)

This is the code I have written (which currently produces the above ValueError):

for i_symbol, acceptance_date in transactions.itertuples(index=False):
  for symbol, date in market.itertuples(index=False):
    if i_symbol == symbol and acceptance_date == date:
        print(market.symbol + market.date + market.close)

2 questions:

Is itertuples() the best/fastest approach? If so, how can I get the above working?

Does anyone know a better way? Would indexing work? Should I use an external db (e.g. mysql) instead?

Thanks, Matt

Body:
Regarding question 1: pandas.itertuples() yields one namedtuple for each row. You can either unpack these like standard tuples or access the tuple elements by name:

for t in transactions.itertuples(index=False):
  for m in market.itertuples(index=False):
    if t.i_symbol == m.symbol and t.acceptance_date == m.date:
        print(m.symbol + m.date + m.close)

(I did not test this with data frames of your size but I'm pretty sure it's still painfully slow)

Regarding question 2: You can simply merge both data frames on symbol and date.

Rename your "transactions" DataFrame so that it also has columns named "symbol" and "date":

transactions = transactions[['i_symbol', 'acceptance_date']]
transactions.columns = ['symbol','date']

Then merge both DataFrames on symbol and date:

result = pd.merge(market, transactions, on=['symbol','date'])

The result DataFrame consists of one row for each symbol/date combination which exists in both DataFrames. The operation only takes a few seconds on my machine with DataFrames of your size.


问:
Remove Words Less Than 4 Characters from Pandas Series
I am trying to remove all words with less than 4 characters from each scalar value in a Pandas Series. What is the best way to do it? Here is my failed attempt:

```<code>df['text'] = df['text'].str.join(word for word in df['text'].str.split() if len(word)>3)
</code>```

I receive the following error message:

AttributeError: 'generator' object has no attribute 'join'

I based my attempt off of this post regarding the same in a string: Remove small words using Python

Side note: If its better to tokenize my words before removing with less than 4 characters please let me know.

EDIT: Each scalar value contains sentences so I want to remove for any words less than a length of 4 within the value.

答:
Using regex with .str.findall and .str.join appears to be fastest:

```<code>df['text'].str.findall('\w{4,}').str.join(' ')
</code>```

Timings

Using the following setup:

```<code>df = pd.DataFrame({'text':["The quick brown fox", "jumped over the lazy dog", "foo bar baz", 'words exceeding desired length']})
df = pd.concat([df]*10**4, ignore_index=True)

def pir2(df):
    t = df.text.str.split(expand=True).stack()
    return t.loc[t.str.len() >= 4].groupby(level=0).apply(' '.join)
</code>```

I get the following timings:

```<code>%timeit df['text'].str.findall('\w{4,}').str.join(' ')
10 loops, best of 3: 44.8 ms per loop

%timeit df.text.apply(lambda i: ' '.join(filter(lambda j: len(j) > 3, i.split())))
10 loops, best of 3: 79.3 ms per loop

%timeit df['text'].str.split().map(lambda sl: " ".join(s for s in sl if len(s) > 3))
10 loops, best of 3: 87.2 ms per loop

%timeit pir2(df)
1 loop, best of 3: 2.87 s per loop
</code>```

Body:
I am trying to remove all words with less than 4 characters from each scalar value in a Pandas Series. What is the best way to do it? Here is my failed attempt:

df['text'] = df['text'].str.join(word for word in df['text'].str.split() if len(word)>3)

I receive the following error message:

AttributeError: 'generator' object has no attribute 'join'

I based my attempt off of this post regarding the same in a string: Remove small words using Python

Side note: If its better to tokenize my words before removing with less than 4 characters please let me know.

EDIT: Each scalar value contains sentences so I want to remove for any words less than a length of 4 within the value.

Body:
Using regex with .str.findall and .str.join appears to be fastest:

df['text'].str.findall('\w{4,}').str.join(' ')

Timings

Using the following setup:

df = pd.DataFrame({'text':["The quick brown fox", "jumped over the lazy dog", "foo bar baz", 'words exceeding desired length']})
df = pd.concat([df]*10**4, ignore_index=True)

def pir2(df):
    t = df.text.str.split(expand=True).stack()
    return t.loc[t.str.len() >= 4].groupby(level=0).apply(' '.join)

I get the following timings:

%timeit df['text'].str.findall('\w{4,}').str.join(' ')
10 loops, best of 3: 44.8 ms per loop

%timeit df.text.apply(lambda i: ' '.join(filter(lambda j: len(j) > 3, i.split())))
10 loops, best of 3: 79.3 ms per loop

%timeit df['text'].str.split().map(lambda sl: " ".join(s for s in sl if len(s) > 3))
10 loops, best of 3: 87.2 ms per loop

%timeit pir2(df)
1 loop, best of 3: 2.87 s per loop


问:
Jetty RewriteHandler and contextHandler
I have an application running on an embeded jetty server. I'm trying to add a write to add a RewriteHandler in order to redirect from the root of my web-application (http:///www.example.com) to (http:www.example.com/web).
I added the RewriteHandler, however I'm being redirected to http://www.example.com/home.html (or main.html, depending on if the user has signed in or not).

I actually want to be redirected to http://www.example.com/web/home.html.
How should I modify the code below, in order for that to happen:

```<code>ServletContextHandler servletHandler =
            new ServletContextHandler(ServletContextHandler.SESSIONS);
    ServletHolder jerseyServlet = servletHandler.addServlet(ServletContainer.class, "/*");

    String staticPath = StartServer.class.getResource("/resources/www-static/").toExternalForm();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource(staticPath));
    resourceHandler.setWelcomeFiles(new String[] { "home.html" });
    ContextHandler staticHandler = new ContextHandler("/web");
    staticHandler.setHandler(resourceHandler);

    RewriteHandler rewriteHandler = new RewriteHandler();
    rewriteHandler.setRewriteRequestURI(true);
    rewriteHandler.setRewritePathInfo(false);
    RewritePatternRule redirect = new RewritePatternRule();
    redirect.setPattern("^/?$");
    redirect.setReplacement("/web");
    rewriteHandler.addRule(redirect);
    rewriteHandler.setHandler(resourceHandler);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { servletHandler, staticHandler, rewriteHandler  });

    jetty.setHandler(handlers);
</code>```

答:
Put RewriteHandler first.

And don't mix ServletContextHandler and ResourceHandler.

See https://stackoverflow.com/a/28419106/775715 and https://stackoverflow.com/a/34277268/775715

Title: Jetty RewriteHandler and contextHandler

Body:
I have an application running on an embeded jetty server. I'm trying to add a write to add a RewriteHandler in order to redirect from the root of my web-application (http:///www.example.com) to (http:www.example.com/web).
I added the RewriteHandler, however I'm being redirected to http://www.example.com/home.html (or main.html, depending on if the user has signed in or not).

I actually want to be redirected to http://www.example.com/web/home.html.
How should I modify the code below, in order for that to happen:

ServletContextHandler servletHandler =
            new ServletContextHandler(ServletContextHandler.SESSIONS);
    ServletHolder jerseyServlet = servletHandler.addServlet(ServletContainer.class, "/*");

    String staticPath = StartServer.class.getResource("/resources/www-static/").toExternalForm();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource(staticPath));
    resourceHandler.setWelcomeFiles(new String[] { "home.html" });
    ContextHandler staticHandler = new ContextHandler("/web");
    staticHandler.setHandler(resourceHandler);

    RewriteHandler rewriteHandler = new RewriteHandler();
    rewriteHandler.setRewriteRequestURI(true);
    rewriteHandler.setRewritePathInfo(false);
    RewritePatternRule redirect = new RewritePatternRule();
    redirect.setPattern("^/?$");
    redirect.setReplacement("/web");
    rewriteHandler.addRule(redirect);
    rewriteHandler.setHandler(resourceHandler);

    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { servletHandler, staticHandler, rewriteHandler  });

    jetty.setHandler(handlers);


问:
Can't find bundle for base name /Bundle, locale en_US
I'm using a library that has a dependency on JSF.

When I try to run my project, it show following exception massage..

```<code>java.util.MissingResourceException: Can't find bundle for base name /Bundle, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:705)
</code>```

Any ideas ?

答:
The problem must be that the resource-bunde > base-name attribute at the faces-config.xml file has a different path to your properties. This happened to me on the firstcup Java EE tutorial, I gave a different package name on then project creation and then Glassfish was unable to find the properties folder which is on "firstcup.web".

I hope it helps.

Body:
I'm using a library that has a dependency on JSF.

When I try to run my project, it show following exception massage..

java.util.MissingResourceException: Can't find bundle for base name /Bundle, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:705)

Any ideas ?


问:
Django url pattern
This should be an easy question.  I have two url patterns in Django:

```<code>url(r'^wiki/page/(?P<page_title>.*)', views.wiki_view, name = 'wiki_view'),
url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),
</code>```

When I visit /wiki/page/test, it takes me to views.wiki_view.  This is correct.  I need the first pattern to capture all characters after the "page/", which is why I used .*

When I visit /wiki/page/, it also takes me to views.wiki_view.  This is incorrect.

I could alter the second url pattern to read:

```<code>url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),
</code>```

Thus, when I visit /wiki/page, it will take me to views.wiki_page_index.  But I'd rather fix the problem instead of avoiding it.

How do I format the first url pattern so that it won't pick up the instance of /wiki/page/?

答:
Change the first one to:</p>

```<code>url(r'^wiki/page/(?P<page_title>.+)', views.wiki_view, name = 'wiki_view'),
</code>```

ContentLicense: CC BY-SA 2.5

Title: Django url pattern

Body:
This should be an easy question.  I have two url patterns in Django:

url(r'^wiki/page/(?P<page_title>.*)', views.wiki_view, name = 'wiki_view'),
url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),

When I visit /wiki/page/test, it takes me to views.wiki_view.  This is correct.  I need the first pattern to capture all characters after the "page/", which is why I used .*

When I visit /wiki/page/, it also takes me to views.wiki_view.  This is incorrect.

I could alter the second url pattern to read:

url(r'^wiki/page/$', views.wiki_page_index, name = 'wiki_page_index'),

Thus, when I visit /wiki/page, it will take me to views.wiki_page_index.  But I'd rather fix the problem instead of avoiding it.

How do I format the first url pattern so that it won't pick up the instance of /wiki/page/?

Body:
Change the first one to:

url(r'^wiki/page/(?P<page_title>.+)', views.wiki_view, name = 'wiki_view'),


问:
creating a date with variables passed into a method
I need to create a date as part of a method by passing in 2 parameters.User chooses numeric year and month and these are passed into the method.There is more to it than this but i keep getting the error "comparison of String with 0 failed (ArgumentError)"  </p>

```<code>def printMonth(year, month)
 y= year.to_i
 x= month.to_i
 z= x + 1
 now= Date.new("#{y}, #{x}, 1")
 puts(now)

end
</code>```

答:
You wanted to pass three arguments to Date constructor, but wrapped it in quotes and passed as one. There's also no reason to convert them to integers to convert them to strings again:

```<code>now = Date.new(year, month, 1)
</code>```

Body:
I need to create a date as part of a method by passing in 2 parameters.User chooses numeric year and month and these are passed into the method.There is more to it than this but i keep getting the error "comparison of String with 0 failed (ArgumentError)"

def printMonth(year, month)
 y= year.to_i
 x= month.to_i
 z= x + 1
 now= Date.new("#{y}, #{x}, 1")
 puts(now)

end

Body:
You wanted to pass three arguments to Date constructor, but wrapped it in quotes and passed as one. There's also no reason to convert them to integers to convert them to strings again:

now = Date.new(year, month, 1)


问:
Rails belongs_to STI table with scope
I've a STI table "parties" as follows:

```<code># app/models/party.rb
class Party < ApplicationRecord
  has_many :party_contacts

  scope :vendors, -> { where(type: 'Party::Vendor') }
  scope :customers, -> { where(type: 'Party::Customer') }
end

# app/models/party/vendor.rb
class Party::Vendor < Party
end

# app/models/party/customer.rb
class Party::Customer < Party
end
</code>```

And "party_contacts" table as follow:

```<code>class PartyContact < ApplicationRecord
  belongs_to :party

  scope :of_vendors, -> {# fetch all contacts belongs to all vendors logic }
  scope :of_customers, -> {# fetch all contacts belongs to all customers logic }
end
</code>```

I want to make query on "party_contacts" to get list of all vendors/customers contacts. How can I write the scope for "party_contacts" (or should it be in parent model)?

I'm trying following scopes:

```<code>scope :of_vendors, -> { joins(:party).includes(:party).where( party: { type: "Party::Vendor" } ) }
scope :of_customers, -> { joins(:party).includes(:party).where( party: { type: "Party::Customer" } ) }
</code>```

But get error:

```<code>ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "party"
LINE 1: ...parties"."id" = "party_contacts"."party_id" WHERE "party"."t...
</code>```

答:
Thank you @Swards, I figured it out just a while before. The scope should be as follows:

```<code>scope :of_vendors, -> { joins(:party).includes(:parties).where( parties: { type: "Party::Vendor" } ) }
scope :of_customers, -> { joins(:party).includes(:parties).where( parties: { type: "Party::Customer" } ) }
</code>```

It constructs right query:

```<code>2.4.0 :042 > PartyContact.of_vendors
PartyContact Load (8.8ms)  SELECT "party_contacts".* FROM "party_contacts" INNER JOIN "parties" ON "parties"."id" = "party_contacts"."party_id" WHERE "parties"."type" = $1  [["type", "Party::Vendor"]]
=> #<ActiveRecord::Relation []>
2.4.0 :043 > PartyContact.of_customers
PartyContact Load (0.5ms)  SELECT "party_contacts".* FROM "party_contacts" INNER JOIN "parties" ON "parties"."id" = "party_contacts"."party_id" WHERE "parties"."type" = $1  [["type", "Party::Customer"]]
=> #<ActiveRecord::Relation []>
</code>```

Here party is singular in joins(:party) as it is belongs_to relation. And parties is plural in includes(:parties) and where(parties:{...}) as it is name of table.

Title: Rails belongs_to STI table with scope

Body:
I've a STI table "parties" as follows:

# app/models/party.rb
class Party < ApplicationRecord
  has_many :party_contacts

  scope :vendors, -> { where(type: 'Party::Vendor') }
  scope :customers, -> { where(type: 'Party::Customer') }
end

# app/models/party/vendor.rb
class Party::Vendor < Party
end

# app/models/party/customer.rb
class Party::Customer < Party
end

And "party_contacts" table as follow:

class PartyContact < ApplicationRecord
  belongs_to :party

  scope :of_vendors, -> {# fetch all contacts belongs to all vendors logic }
  scope :of_customers, -> {# fetch all contacts belongs to all customers logic }
end

I want to make query on "party_contacts" to get list of all vendors/customers contacts. How can I write the scope for "party_contacts" (or should it be in parent model)?

I'm trying following scopes:

scope :of_vendors, -> { joins(:party).includes(:party).where( party: { type: "Party::Vendor" } ) }
scope :of_customers, -> { joins(:party).includes(:party).where( party: { type: "Party::Customer" } ) }

But get error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "party"
LINE 1: ...parties"."id" = "party_contacts"."party_id" WHERE "party"."t...

Body:
Thank you @Swards, I figured it out just a while before. The scope should be as follows:

scope :of_vendors, -> { joins(:party).includes(:parties).where( parties: { type: "Party::Vendor" } ) }
scope :of_customers, -> { joins(:party).includes(:parties).where( parties: { type: "Party::Customer" } ) }

It constructs right query:

2.4.0 :042 > PartyContact.of_vendors
PartyContact Load (8.8ms)  SELECT "party_contacts".* FROM "party_contacts" INNER JOIN "parties" ON "parties"."id" = "party_contacts"."party_id" WHERE "parties"."type" = $1  [["type", "Party::Vendor"]]
=> #<ActiveRecord::Relation []>
2.4.0 :043 > PartyContact.of_customers
PartyContact Load (0.5ms)  SELECT "party_contacts".* FROM "party_contacts" INNER JOIN "parties" ON "parties"."id" = "party_contacts"."party_id" WHERE "parties"."type" = $1  [["type", "Party::Customer"]]
=> #<ActiveRecord::Relation []>

Here party is singular in joins(:party) as it is belongs_to relation. And parties is plural in includes(:parties) and where(parties:{...}) as it is name of table.


问:
What is wrong with this code? I can't seem to get the bullet to be shot from the rocket
Basically the rocket moves up and down, stops when it reaches the top or bottom and recognizes that the spacebar is being pressed. However the bullet won't shoot from the ship. I'm new to python and pygame. Anyways here is the code, thank you for any help!:</p>

```<code>import pygame
import sys
from pygame.locals import*

bg_color = (0, 191, 255)
d_w = 1200
d_h= 800
class Rocket(object):
    def __init__(self):
        self.image = pygame.image.load('Rocket.bmp')
        self.x = 0
        self.y = d_h/2

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 6.5
        if key[pygame.K_UP]:
            if self.y > 0:
                self.y -= dist
        elif key[pygame.K_DOWN]:
            if self.y < 775:
                self.y += dist
        elif key[pygame.K_SPACE]:
            Bullet.update(Bullet)
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))
class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()

        self.image = pygame.Surface([2, 5])
        self.image.fill(0, 0, 0)

        self.rect = self.image.get_rect()

    def update(self):
        """ Move the bullet. """
        self.image = pygame.Surface([2, 5])
        self.image.fill((0, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x += 3
pygame.init()
screen = pygame.display.set_mode((d_w, d_h))
pygame.display.set_caption("Game Character")
Mario = pygame.image.load('Mario_Sprite.bmp')
rocket = Rocket()
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    rocket.handle_keys()
    screen.fill(bg_color)
    rocket.draw(screen)
    pygame.display.update()
    clock.tick(72)
</code>```

答:
```<code>Bullet.update(Bullet)
</code>```

You're calling update statically. You need to create an instance of the class and then update that instance, as in:

```<code>bullet = Bullet()
...
bullet.update()
</code>```

Body:
Basically the rocket moves up and down, stops when it reaches the top or bottom and recognizes that the spacebar is being pressed. However the bullet won't shoot from the ship. I'm new to python and pygame. Anyways here is the code, thank you for any help!:

import pygame
import sys
from pygame.locals import*

bg_color = (0, 191, 255)
d_w = 1200
d_h= 800
class Rocket(object):
    def __init__(self):
        self.image = pygame.image.load('Rocket.bmp')
        self.x = 0
        self.y = d_h/2

    def handle_keys(self):
        key = pygame.key.get_pressed()
        dist = 6.5
        if key[pygame.K_UP]:
            if self.y > 0:
                self.y -= dist
        elif key[pygame.K_DOWN]:
            if self.y < 775:
                self.y += dist
        elif key[pygame.K_SPACE]:
            Bullet.update(Bullet)
    def draw(self, surface):
        surface.blit(self.image, (self.x, self.y))
class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()

        self.image = pygame.Surface([2, 5])
        self.image.fill(0, 0, 0)

        self.rect = self.image.get_rect()

    def update(self):
        """ Move the bullet. """
        self.image = pygame.Surface([2, 5])
        self.image.fill((0, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x += 3
pygame.init()
screen = pygame.display.set_mode((d_w, d_h))
pygame.display.set_caption("Game Character")
Mario = pygame.image.load('Mario_Sprite.bmp')
rocket = Rocket()
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    rocket.handle_keys()
    screen.fill(bg_color)
    rocket.draw(screen)
    pygame.display.update()
    clock.tick(72)

Body:
Bullet.update(Bullet)

You're calling update statically. You need to create an instance of the class and then update that instance, as in:

bullet = Bullet()
...
bullet.update()


问:
align inner div in vertical, horizontal center against the parent div without line breaking for the following span text element
If I didn't make parent container be  inline-block style

The inner arrow will be aligned in the center position which is I expected.
However, there will be a line-break for the following text.

If I make the parent container be inline-block style

HTML

```<code>    <div class="queue-view-entry-line" name="Name">
        <div class="mycompany-document" style="/* display: inline-block; */">
            <div class="arrow-right">
            </div>
        </div>
        <span class="entry-label">File Name</span><span class="entry-value"><a href="/mycompany/servlet/servlet.    FileDownload?file=00P41000007XUEEEA4" target="_blank">Planned Payment Dates 2017</a>
        </span>

    </div>
</code>```

CSS rules

```<code>div{
  .mycompany-document{
    background: #F7F7F7;
    border: 1px solid #AAAAAA;
    left: 64px;
    top: 64px;
    width: 32px;
    height: 32px;
    vertical-align: middle;
    border-radius: 5px;
    letter-spacing: 1px;
    text-align: center;
    display: table-cell;

    .arrow-right{
      margin: auto;
      vertical-align: middle;
      display:inline-block;
      width: 0.4em;
      height: 0.4em;
      border-right: 0.2em solid black;
      border-top: 0.2em solid black;
      transform: rotate(45deg);
    }

  }

}
</code>```

答:
I recommend you give flexbox a try. It will quickly be your best friend!
I didn't feel like wrestling with your HTML, so I created a new example to show how you could achieve the desired effect.

Check out this fiddle.
https://jsfiddle.net/omucfbzh/

```<code>   <div class="box">
      <h2>Documents</h2>
      <div class="others">
        <div class="arrow-container">
          <div> > </div>
        </div>
        <p>Planned Payment Dates 2017</p>
      </div>
    </div>

.box {
  background-color: orange;
  display: flex;
  flex-direction: column;
  padding: 7.5px;
}

.others {
  display: flex;
}

.arrow-container {
  background-color: grey;
  border-radius: 5px;
  height: 50px;
  width: 50px;
  margin-right: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</code>```

Body:
If I didn't make parent container be  inline-block style

The inner arrow will be aligned in the center position which is I expected.
However, there will be a line-break for the following text.

If I make the parent container be inline-block style

HTML

        File NamePlanned Payment Dates 2017

CSS rules

div{
  .mycompany-document{
    background: #F7F7F7;
    border: 1px solid #AAAAAA;
    left: 64px;
    top: 64px;
    width: 32px;
    height: 32px;
    vertical-align: middle;
    border-radius: 5px;
    letter-spacing: 1px;
    text-align: center;
    display: table-cell;

    .arrow-right{
      margin: auto;
      vertical-align: middle;
      display:inline-block;
      width: 0.4em;
      height: 0.4em;
      border-right: 0.2em solid black;
      border-top: 0.2em solid black;
      transform: rotate(45deg);
    }

  }

}

Body:
I recommend you give flexbox a try. It will quickly be your best friend!
I didn't feel like wrestling with your HTML, so I created a new example to show how you could achieve the desired effect.

Check out this fiddle.
https://jsfiddle.net/omucfbzh/

   <div class="box">
      <h2>Documents</h2>
      <div class="others">
        <div class="arrow-container">
          <div> > </div>
        </div>
        <p>Planned Payment Dates 2017</p>
      </div>
    </div>

.box {
  background-color: orange;
  display: flex;
  flex-direction: column;
  padding: 7.5px;
}

.others {
  display: flex;
}

.arrow-container {
  background-color: grey;
  border-radius: 5px;
  height: 50px;
  width: 50px;
  margin-right: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}


问:
No Gradle Tool Window in IntelliJ IDEA 13?
I can't find the Gradle Tool Window in IntelliJ IDEA 13 anymore. Is it removed?

Furthermore I can't run any Gradle Tasks within my Gradle build file (via context-menu -> Run). The error message: Module XY is not backed by gradle occurs. All these runs perfectly in IntelliJ IDEA 12.

What is going wrong here?

答:
You can add a gradle.xml file in your .idea directory

```<code><?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="distributionType" value="LOCAL" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="$USER_HOME$/.gradle" />
        <option name="gradleJvm" value="1.8.0_40" />
      </GradleProjectSettings>
    </option>
  </component>
</project>
</code>```

This should enable the gradle panel to show up.

Make sure to replace the correct paths above

Body:
You can add a gradle.xml file in your .idea directory

<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="GradleSettings">
    <option name="linkedExternalProjectsSettings">
      <GradleProjectSettings>
        <option name="distributionType" value="LOCAL" />
        <option name="externalProjectPath" value="$PROJECT_DIR$" />
        <option name="gradleHome" value="$USER_HOME$/.gradle" />
        <option name="gradleJvm" value="1.8.0_40" />
      </GradleProjectSettings>
    </option>
  </component>
</project>

This should enable the gradle panel to show up.

Make sure to replace the correct paths above


问:
Flush output in for loop in Jupyter notebook
I want to print out i in my iteration on Jupyter notebook and flush it out. After the next iteration, I'll print the next i. I tried solutions from this question and this question, however, it just print out 0123...9 without flushing the output for me. Here is my working code:

```<code>import sys
import time

for i in range(10):
    sys.stdout.write(str(i)) # or print(i, flush=True) ?
    time.sleep(0.5)
    sys.stdout.flush()
</code>```

these are my setup: ipython 5.1, python 3.6. Maybe, I missed something in the previous solution?

答:
```<code>#Try this:
import sys
import time

for i in range (10):
    sys.stdout.write('\r'+str(i))
    time.sleep(0.5)
</code>```

<h1>'\r' will print at the beginning of the line</h1>

Body:
I want to print out i in my iteration on Jupyter notebook and flush it out. After the next iteration, I'll print the next i. I tried solutions from this question and this question, however, it just print out 0123...9 without flushing the output for me. Here is my working code:

import sys
import time

for i in range(10):
    sys.stdout.write(str(i)) # or print(i, flush=True) ?
    time.sleep(0.5)
    sys.stdout.flush()

these are my setup: ipython 5.1, python 3.6. Maybe, I missed something in the previous solution?

Body:
#Try this:
import sys
import time

for i in range (10):
    sys.stdout.write('\r'+str(i))
    time.sleep(0.5)

'\r' will print at the beginning of the line


问:
In python is there a cross-platform way of determining what process is listening to a given port?
In linux, I can use lsof -i as in the following function:

```<code>def FindProcessUsingPort(portnum):
    import os
    fp = os.popen("lsof -i :%s" % portnum)
    lines = fp.readlines()
    fp.close()
    pid = None
    if len(lines) >= 2:
        pid = int(lines[1].split()[1])
    return pid
</code>```

Is there a cross-platform way to figure this out?

As a relevant reference, once I know the process id, the psutil library is very nice and lets me determine all sorts of useful process information for it in a cross-platform way.  I just can't get the first part to work (finding the pid) cross-platform at the moment.

If not familiar with the lsof -i switch, the output looks like below (after launching a python process that opens a TCP socket listening on port 1234):

```
$ lsof -i :1234
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
python  22380 russ   15u  IPv4 4015476      0t0  TCP *:1234 (LISTEN)
```

答: No, this is not built into python.</p>

Body:
In linux, I can use lsof -i as in the following function:

def FindProcessUsingPort(portnum):
    import os
    fp = os.popen("lsof -i :%s" % portnum)
    lines = fp.readlines()
    fp.close()
    pid = None
    if len(lines) >= 2:
        pid = int(lines[1].split()[1])
    return pid

Is there a cross-platform way to figure this out?

As a relevant reference, once I know the process id, the psutil library is very nice and lets me determine all sorts of useful process information for it in a cross-platform way.  I just can't get the first part to work (finding the pid) cross-platform at the moment.

If not familiar with the lsof -i switch, the output looks like below (after launching a python process that opens a TCP socket listening on port 1234):

$ lsof -i :1234
COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
python  22380 russ   15u  IPv4 4015476      0t0  TCP *:1234 (LISTEN)

Body: No, this is not built into python.


问:
Pause Azure Function until 12am next day
I know you can add spending limit for your azure functions per month, But I need to find a way to limit number of executions for an Azure function per day. The Function I am developing is calling a 3rd party API where we have a limit of 25,000 calls per day. When we reach that limit we get a response "LIMIT_REACH". I want to be able to pause the azure function execution until 12AM the next day. I am using a storage Queue to trigger the Azure Function. I know an option is in the function.json. I can update ["disabled": false] But i will need to set it through programatically. Then I will have to trigger a process to turn on the function again. </p>

答: Why not keep a flag, or a "next valid execution time" in TableStorage when you have hit the LIMIT_REACH response. Each time the function triggers, interrogate that time and either execute or abort. Update the flag / next execution time when you are able to re-hit that 3rd party API.</p>


问:
Easy way to generate http date (GMT) string in ruby
I need to generate an HTTP (GMT) date string in Ruby. This is because of a requirement of an API that I'm consuming.

What is an easy (out of the box) way to generate it?

答:
I found that Ruby comes with a method for the Time class out of the box for this:

```<code>Time.now.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"
</code>```

The time class also supports the following methods

```<code>Time.now.iso8601  # => "2011-10-05T22:26:12-04:00"
Time.now.rfc2822  # => "Wed, 05 Oct 2011 22:26:12 -0400"
</code>```

Source: http://ruby-doc.org/stdlib-2.0.0/libdoc/time/rdoc/Time.html#class-Time-label-Converting+to+a+String

Body:
I found that Ruby comes with a method for the Time class out of the box for this:

Time.now.httpdate # => "Thu, 06 Oct 2011 02:26:12 GMT"

The time class also supports the following methods

Time.now.iso8601  # => "2011-10-05T22:26:12-04:00"
Time.now.rfc2822  # => "Wed, 05 Oct 2011 22:26:12 -0400"

Source: http://ruby-doc.org/stdlib-2.0.0/libdoc/time/rdoc/Time.html#class-Time-label-Converting+to+a+String


问:
Am I right about the meaning of coupling?
I'm gonna try to write some ideas ideas about software coupling and cohesion, but I'm not sure they mean anything practical at all. So if you want to explain your answers with examples please use simple algebraic expressions imagining that algebra is a sequential programming language so we all can understand what you´re talking about...

Read about it in wikipedia

So here is what I want to believe (is this correct?):

```<code>'Implementation of A with Low Cohesion
'(Coincidental cohesion because there is no
' good reason or need to group the functions
' in this way)
a(x) = 2x + 1
b(x) = 3x + 2
r(x) = a(x) + b(x)
</code>```

...

```<code>'Implementation of A with High Cohesion (Almost Atomic)
r(x) = 5x + 3
</code>```

...

```<code>'Implementation of A with Low Cohesion too
a(x) = 2x + 1
r(x) = a(x) + 3x + 2
</code>```

...

```<code>'Implementations of A with Functional Cohesion
a(x, y) = x * y   'Groups multiplication
b(x, y) = x + y   'Groups addition
r(x) = b(a(5,x), 3)
</code>```

答:
Interesting view and you are on the right path to understanding the larger concept.  Since you referenced the Wikipedia article, do you think that your example represents any of the ten coupling types listed?

I see that perhaps your example could represent data and/or message coupling, but that's about it because basic algebra statements do not maintain state (i.e. store values), for example.

First realize this simple algebra will eventually be too simplistic to represent all important coupling patterns in software development.  Right away I would suggest adding more than one variable to your functions and also using different variable names, etc. to increase the possible ways the functions can be convolved.

To illustrate some of the other coupling patterns, you at least need some way to store values and reference previously stored values... something we all do while solving algebra problems but something that is not taught with a universal syntax or structure. (Recall the scratch paper and working problems in the margins to get a problem done?  Probably nobody taught you a strict system for doing this, nor one that everyone follows.)  By the time you start adding these kind of features to your example just to illustrate different couplings, you'll essentially end up with an equivalent of your own programming language.  Depending on what your intentions are, that might be a very worth-while and enjoyable exercise, but you also might find that trying to represent the coupling types with an existing language to be more efficient at learning the concepts.

Body:
I'm gonna try to write some ideas ideas about software coupling and cohesion, but I'm not sure they mean anything practical at all. So if you want to explain your answers with examples please use simple algebraic expressions imagining that algebra is a sequential programming language so we all can understand what you´re talking about...

Read about it in wikipedia

So here is what I want to believe (is this correct?):

'Implementation of A with Low Cohesion
'(Coincidental cohesion because there is no
' good reason or need to group the functions
' in this way)
a(x) = 2x + 1
b(x) = 3x + 2
r(x) = a(x) + b(x)

...

'Implementation of A with High Cohesion (Almost Atomic)
r(x) = 5x + 3

...

'Implementation of A with Low Cohesion too
a(x) = 2x + 1
r(x) = a(x) + 3x + 2

...

'Implementations of A with Functional Cohesion
a(x, y) = x * y   'Groups multiplication
b(x, y) = x + y   'Groups addition
r(x) = b(a(5,x), 3)


问:
ksoap setProperity is not working in android
I am building an app that consume .asmx web service

I am facing a strange problem , all parameters that I sent with the request is null in the server

This is my method

```<code>try {

                    SoapObject request = new SoapObject(DealightsConstants.NAMESPACE, DealightsConstants.METHOD_MOBILE_LOGIN);
                    //request.addProperty(DealightsConstants.METHOD_MOBILE_LOGIN_USERNAME, username);
                    //request.addProperty(DealightsConstants.METHOD_MOBILE_LOGIN_PASSWORD, password);
                    PropertyInfo pi = new PropertyInfo();
                    pi.setName(DealightsConstants.METHOD_MOBILE_LOGIN_USERNAME);
                    pi.setValue(username);
                    pi.setType(String.class);

                    PropertyInfo pi1 = new PropertyInfo();
                    pi1.setName(DealightsConstants.METHOD_MOBILE_LOGIN_PASSWORD);
                    pi1.setValue(password);
                    pi1.setType(String.class);

                    request.addProperty(pi);
                    request.addProperty(pi1);

                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    envelope.dotNet=true;
                    envelope.setOutputSoapObject(request);

                    HttpTransportSE androidHttpTransport = new HttpTransportSE(DealightsConstants.URL);
                    androidHttpTransport.call(DealightsConstants.SOAP_ACTION + DealightsConstants.METHOD_MOBILE_LOGIN, envelope);
                    androidHttpTransport.debug=true;

                    Object result = envelope.getResponse();
                    if (result != null) {

                        Log.i("AMIRA" , result.toString());
                        JSONArray array = new JSONArray(result.toString());
                        if (array != null && array.length() > 0) {
                            return array.getJSONObject(0);
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
</code>```

I have use a lot of formats and nothing work with me

EDIT

part of asmx method description

```<code>    POST /DealightsWS.asmx HTTP/1.1
Host: ------
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "Dealights/mobileLogin"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <mobileLogin xmlns="Dealights">
      <uname>string</uname>
      <pass>string</pass>
    </mobileLogin>
  </soap:Body>
</soap:Envelope>
</code>```

答:
comparing to my own soap projects, maybe this will fix it:

```<code>androidHttpTransport.call(DealightsConstants.SOAP_ACTION, envelope);
</code>```

notice that I've removed:

```<code>+ DealightsConstants.METHOD_MOBILE_LOGIN
</code>```

which is already provided in the request that is attached to the envelope

Body:
I am building an app that consume .asmx web service

I am facing a strange problem , all parameters that I sent with the request is null in the server

This is my method

try {

                    SoapObject request = new SoapObject(DealightsConstants.NAMESPACE, DealightsConstants.METHOD_MOBILE_LOGIN);
                    //request.addProperty(DealightsConstants.METHOD_MOBILE_LOGIN_USERNAME, username);
                    //request.addProperty(DealightsConstants.METHOD_MOBILE_LOGIN_PASSWORD, password);
                    PropertyInfo pi = new PropertyInfo();
                    pi.setName(DealightsConstants.METHOD_MOBILE_LOGIN_USERNAME);
                    pi.setValue(username);
                    pi.setType(String.class);

                    PropertyInfo pi1 = new PropertyInfo();
                    pi1.setName(DealightsConstants.METHOD_MOBILE_LOGIN_PASSWORD);
                    pi1.setValue(password);
                    pi1.setType(String.class);

                    request.addProperty(pi);
                    request.addProperty(pi1);

                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    envelope.dotNet=true;
                    envelope.setOutputSoapObject(request);

                    HttpTransportSE androidHttpTransport = new HttpTransportSE(DealightsConstants.URL);
                    androidHttpTransport.call(DealightsConstants.SOAP_ACTION + DealightsConstants.METHOD_MOBILE_LOGIN, envelope);
                    androidHttpTransport.debug=true;

                    Object result = envelope.getResponse();
                    if (result != null) {

                        Log.i("AMIRA" , result.toString());
                        JSONArray array = new JSONArray(result.toString());
                        if (array != null && array.length() > 0) {
                            return array.getJSONObject(0);
                        } else {
                            return null;
                        }
                    } else {
                        return null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }

I have use a lot of formats and nothing work with me

EDIT

part of asmx method description

    POST /DealightsWS.asmx HTTP/1.1
Host: ------
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "Dealights/mobileLogin"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <mobileLogin xmlns="Dealights">
      <uname>string</uname>
      <pass>string</pass>
    </mobileLogin>
  </soap:Body>
</soap:Envelope>

Body:
comparing to my own soap projects, maybe this will fix it:

androidHttpTransport.call(DealightsConstants.SOAP_ACTION, envelope);

notice that I've removed:

+ DealightsConstants.METHOD_MOBILE_LOGIN

which is already provided in the request that is attached to the envelope


问:
Find all posts with more than a defined number of comments
I have a simple rails 3 blog app where posts have many comments and comments belong to a post.

I want to create a scope that will fetch all posts that have more than 5 comments.
What's the best way of doing this without a counter cache column.

答:
Like this, perhaps?</p>

```<code>Post.select('posts.*, count(comments.id) as comment_count').
  joins(:comments).
  group('posts.id').
  having('comment_count > 5')
</code>```

Body:
Like this, perhaps?

Post.select('posts.*, count(comments.id) as comment_count').
  joins(:comments).
  group('posts.id').
  having('comment_count > 5')


问:
Am I implementing the SOLID principles the right way?
This is the first time I am writing a C++ code using SOLID principles. Therefore I do not know if the following sample code implements the principles correctly. My questions follow the code.

I highly appreciate all responses. Thanks!

Here is the sample:

```<code>class ICustomer
{
public:
        virtual char* GetName() = 0;
        virtual char* GetSurname() = 0;
        virtual char* GetAddress() = 0;
};

class CCustomer : public ICustomer
{
public:
        virtual char* GetName()
        {
               return "Name1";
        }

        virtual char* GetSurname()
        {
               return "Surname1";
        }

        virtual char* GetAddress()
        {
               return "Address1";
        }
};

class IExporter
{
public:
        virtual void Export() = 0;
};

class CExportToExcel : public IExporter
{
public:
        virtual void Export()
        {
               ICustomer* pCustomer = new CCustomer;
               printf("%s, %s, %s\n", pCustomer->GetName(), pCustomer->GetSurname(), pCustomer->GetAddress());
        }
};

class IShopOwner
{
public:
        virtual void Execute() = 0;
};

class CShopOwner : public IShopOwner
{
public:
        virtual void Execute()
        {
            IExporter* pExp = new CExportToExcel;
            pExp->Export();
        }
};

void main()
{
        IShopOwner* pOwner = new CShopOwner;
        pOwner->Execute();
}
</code>```

Questions:

Is it a valid SOLID implementation? If no, how it should be.

In the sample ICustomer has GetName(), GetSurname() and GetAddress(). I want an additional info GetPhoneNumber(). Where should I put that in? What changes will it incur?

In the sample there is CExportToExcel. Now I want an additional class CExportToHTML and use it. How should I do that?

答:
The key feedback is to take the dependencies through the concrete class constructors, and take these dependencies as the interfaces not the concrete class, so .. In your object composition root you can decide which actual concrete implementation to pass on to create your objects, ie another product implementation of an interface or just a test mock class for testability purposes. it will also nicely fit with dependency injection pattern and frameworks.

as an example:
change your CShopOwner class to have a constructor that takes an IExporter object, keep that object as a property and use that inside your Execute method. When you are creating your CShopOwner object, on run time you can decide what exact concrete implementation of IExporter interface to pass it on  ie. CExportToHTML.

This should cover your 1st and 3rd questions. About your second question. If GetPhoneNumber() would be relevant for all implementation s of ICustomer, puristically speaking you should create a new interface still, inheriting from ICustomer with one method - GetPhoneNumber() - and not change the ICustomer interface especially if it is already being used by client code because you are breaking the contract by changing it and may cause issues on the existing clients. On the other hand if you asses the situation and risk you could change the ICustomer interface directly and all consumers of it, if this is all your own code which will be much easier. we have all done it :)

Body:
This is the first time I am writing a C++ code using SOLID principles. Therefore I do not know if the following sample code implements the principles correctly. My questions follow the code.

I highly appreciate all responses. Thanks!

Here is the sample:

class ICustomer
{
public:
        virtual char* GetName() = 0;
        virtual char* GetSurname() = 0;
        virtual char* GetAddress() = 0;
};

class CCustomer : public ICustomer
{
public:
        virtual char* GetName()
        {
               return "Name1";
        }

        virtual char* GetSurname()
        {
               return "Surname1";
        }

        virtual char* GetAddress()
        {
               return "Address1";
        }
};

class IExporter
{
public:
        virtual void Export() = 0;
};

class CExportToExcel : public IExporter
{
public:
        virtual void Export()
        {
               ICustomer* pCustomer = new CCustomer;
               printf("%s, %s, %s\n", pCustomer->GetName(), pCustomer->GetSurname(), pCustomer->GetAddress());
        }
};

class IShopOwner
{
public:
        virtual void Execute() = 0;
};

class CShopOwner : public IShopOwner
{
public:
        virtual void Execute()
        {
            IExporter* pExp = new CExportToExcel;
            pExp->Export();
        }
};

void main()
{
        IShopOwner* pOwner = new CShopOwner;
        pOwner->Execute();
}

Questions:

Is it a valid SOLID implementation? If no, how it should be.

In the sample ICustomer has GetName(), GetSurname() and GetAddress(). I want an additional info GetPhoneNumber(). Where should I put that in? What changes will it incur?

In the sample there is CExportToExcel. Now I want an additional class CExportToHTML and use it. How should I do that?


问:
Getting Pixel Color from an Image using CGPoint
I'm experiencing a great deal of difficulty just getting the pixel color of a certain pixel (specified by a CGPoint) in Swift. Here is my code thus far:

```<code>@IBOutlet weak var graphImage: UIImageView!

var image : UIImage?

override func viewDidLoad() {
    super.viewDidLoad()
}

func getPixelColor(pos: CGPoint) -> UIColor {
    var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.graphImage.image!.CGImage))
    var data : UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    var pixelInfo : Int = ((Int(graphImage.image!.size.width) * Int(pos.y) + Int(pos.x)*4))

    let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
    let g = CGFloat(data[pixelInfo]+1) / CGFloat(255.0)
    let b = CGFloat(data[pixelInfo]+2) / CGFloat(255.0)
    let a = CGFloat(data[pixelInfo]+3) / CGFloat(255.0)

    return UIColor(red: r, green: g, blue: b, alpha: a)
}

@IBAction func playTapped(sender: AnyObject) {

    getPixelColor(CGPoint(x: 100.0, y: 100.0))

}
</code>```

My app crashes, after tapping play, on the line "let g = CGFloat..." I don't see any errors at all in this, though I am quite new to anything to do with images. I'm wondering if I need to use a different type of image, or whether something in my pixelInfo variable is wrong. By the way, I got a majority of this code from How do I get the color of a pixel in a UIImage with Swift?. Can anyone point to what may be the problem? Any help would be greatly appreciated!

答: After struggling for hours I discovered that the RGBA information is stored like BGRA. Check this answer for an extension in SWIFT 3/xcode8/ios10</p>

Body:
I'm experiencing a great deal of difficulty just getting the pixel color of a certain pixel (specified by a CGPoint) in Swift. Here is my code thus far:

@IBOutlet weak var graphImage: UIImageView!

var image : UIImage?

override func viewDidLoad() {
    super.viewDidLoad()
}

func getPixelColor(pos: CGPoint) -> UIColor {
    var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.graphImage.image!.CGImage))
    var data : UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

    var pixelInfo : Int = ((Int(graphImage.image!.size.width) * Int(pos.y) + Int(pos.x)*4))

    let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
    let g = CGFloat(data[pixelInfo]+1) / CGFloat(255.0)
    let b = CGFloat(data[pixelInfo]+2) / CGFloat(255.0)
    let a = CGFloat(data[pixelInfo]+3) / CGFloat(255.0)

    return UIColor(red: r, green: g, blue: b, alpha: a)
}

@IBAction func playTapped(sender: AnyObject) {

    getPixelColor(CGPoint(x: 100.0, y: 100.0))

}

My app crashes, after tapping play, on the line "let g = CGFloat..." I don't see any errors at all in this, though I am quite new to anything to do with images. I'm wondering if I need to use a different type of image, or whether something in my pixelInfo variable is wrong. By the way, I got a majority of this code from How do I get the color of a pixel in a UIImage with Swift?. Can anyone point to what may be the problem? Any help would be greatly appreciated!


答:
does    Time.now.getgm work for you?

```<code>Time.now.gmt? #=> fale
Time.now.getgm.gmt? #=> true
</code>```

Title: Easy way to generate http date (GMT) string in ruby

Body:
I need to generate an HTTP (GMT) date string in Ruby. This is because of a requirement of an API that I'm consuming.

What is an easy (out of the box) way to generate it?

Body:
does    Time.now.getgm work for you?

Time.now.gmt? #=> fale
Time.now.getgm.gmt? #=> true


问:
How is one supposed to make sense out of this error?
Invocation details says: "Failure Script compilation failed." It doesn't tell me what file or what line. This is a real productivity impediment.

Develop log is empty.

Monitor log show:

```<code>Exception while executing function: Functions.DmsBlobTrigger2
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.DmsBlobTrigger2 ---> Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount)
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync()
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context)
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`1.InvokeAsync[TReflected](Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,Object[] invokeParameters,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,IReadOnlyDictionary`2 parameters,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   End of inner exception
</code>```

答:
This, plus the lack of good intellisense, compile time error checking, and unit testability is why I do not recommend proceeding with the CSX approach. Instead, I would suggest the pre-compiled function approach as described here

I have done it and never looked back. Makes our function development 100x more productive.

Body:
Invocation details says: "Failure Script compilation failed." It doesn't tell me what file or what line. This is a real productivity impediment.

Develop log is empty.

Monitor log show:

Exception while executing function: Functions.DmsBlobTrigger2
Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Functions.DmsBlobTrigger2 ---> Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken)
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount)
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync()
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context)
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`1.InvokeAsync[TReflected](Object[] arguments)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeAsync(IFunctionInvoker invoker,Object[] invokeParameters,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstance instance,IReadOnlyDictionary`2 parameters,TraceWriter traceWriter,CancellationTokenSource functionCancellationTokenSource)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   at async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(??)
   End of inner exception


问:
Python - How do I go about deleting a custom maya UI window when the user clicks outside of it?
I have a custom window that basically acts as a popup whenever a user clicks on a shelf item.

```<code>def drawUI():
    mouse_pos = QtGui.QCursor().pos()
    print 'mouse x: %d y: %d' % (mouse_pos.x(), mouse_pos.y())
    if cmds.window("SET_SELECTION_UI", exists = True):
        cmds.deleteUI("SET_SELECTION_UI", window=True)

    cmds.window("SET_SELECTION_UI", title = "Example", wh = (102, 300), rtf=True, mnb = False, mxb = False, tb = False, sizeable = False, tlc=(mouse_pos.y(),mouse_pos.x()))
    cmds.columnLayout()
    cmds.button(label = "Set 00",   w = 100, command=button00)
    cmds.button(label = "Set 10",   w = 100, command=Button10)
    cmds.button(label = "Set 25",   w = 100, command=Button25)
    cmds.separator( height=10, style='double' )
    cmds.button(bgc=[1,1,1], label = "Cancel", w = 100, command=DeleteButton)
    cmds.showWindow() #shows window

    cmds.window("SET_SELECTION_UI", edit=True, tlc=(mouse_pos.y(),mouse_pos.x()))
</code>```

The window appears properly, all the buttons do what they're supposed to do, and whenever a button is pressed, I delete the window. It's all fine and dandy.

What I'm trying to do, is to detect when the user clicks anywhere outside of the window so that I can delete the UI (much like a pop-up menu works).

Thanks!

ANSWER

I've integrated Cronicryo's script and suggestions into my own and it works perfectly now! Here it is:

```<code>from PySide import QtGui, QtCore
import maya.OpenMayaUI as omui
import pymel.core as pm
from shiboken import wrapInstance

fltr    = None
qtObj   = None
_WINDOW_NAME_ = "SET_SELECTION_UI"

class FilterObj(QtCore.QObject):
    def eventFilter(self, obj , event):
        print event.type()
        if event.type() == event.WindowDeactivate:
            print "focused out"
            pm.window(_WINDOW_NAME_,edit=True,visible=False)
            return True #must return a bool set False to allow normal events to pass through or True to stop any further events
        else:
            return False

def run():
    global fltr
    global qtObj

    if qtObj:
        del qtObj

    mouse_pos = QtGui.QCursor().pos()
    print 'mouse x: %d y: %d' % (mouse_pos.x(), mouse_pos.y())
    if pm.window(_WINDOW_NAME_, exists = True):
        pm.deleteUI(_WINDOW_NAME_, window=True)

    win = pm.window(_WINDOW_NAME_, title = "Set Select", mnb = False, mxb = False, tb = False, sizeable = False)
    pm.columnLayout()
    pm.button(label = "Do nothing",   w = 100)
    pm.separator( h=15, w=100, style='doubleDash' )
    pm.button(bgc=[1,1,1], label = "Cancel", w = 100, command=DeleteButton)
    pm.showWindow(win) #shows window

    pm.window(_WINDOW_NAME_, edit=True, wh = (102, 245),tlc=(mouse_pos.y(),mouse_pos.x()))

    qtObj = wrapInstance(long(omui.MQtUtil.findControl(_WINDOW_NAME_)), QtGui.QWidget)
    fltr = FilterObj()
    qtObj.installEventFilter(fltr)

def DeleteButton(*args):
    pm.deleteUI(_WINDOW_NAME_)
</code>```

答:
EDIT:

i took a look and it looks like there is no focus signal that gets emitted. seems like the only way to do it is to make a custom qt window and re-implement the focus functions or to install an event filter which is almost non evasive

```<code>import maya.OpenMayaUI as omui
import pymel.core as pm
pysideSupport = True
try:
    from PySide import QtGui
    from shiboken import wrapInstance
except:
    pysideSupport = False

win = pm.window("aaa")
win.show()

from PySide import QtCore

class FilterObj(QtCore.QObject):
    def eventFilter(self, obj , event):
        print event.type()
        if event.type() == event.WindowDeactivate:
            print "focused out"
            return False #must return a bool set False to allow normal events to pass through or True to stop any further events
        else:
            return False

qtObj = wrapInstance(long(omui.MQtUtil.findControl("aaa")), QtGui.QWidget)
fltr = FilterObj()
qtObj.installEventFilter(fltr)
</code>```

ORIG:

this is a snippet of my own code that ive used to connect to the destroy signal of a window.
you can do the same of losing window focus

```<code>import maya.OpenMayaUI as omui
pysideSupport = True
try:
    from PySide import QtGui
    from shiboken import wrapInstance
except:
    pysideSupport = False

def onUIDelete(uiName, function):
    """
    extends mayas ui by being able to run a function when the ui gets deleted
    this requires maya to have PySide

    """
    if pysideSupport:
        if isinstance(uiName, pm.ui.PyUI):
            uiName = uiName.name()
        qtObj = wrapInstance(long(omui.MQtUtil.findControl(uiName)), QtGui.QWidget)
        qtObj.destroyed.connect(function)
    else:
        pm.error("Maya doesn't have PySide Support")
</code>```

Body:
I have a custom window that basically acts as a popup whenever a user clicks on a shelf item.

def drawUI():
    mouse_pos = QtGui.QCursor().pos()
    print 'mouse x: %d y: %d' % (mouse_pos.x(), mouse_pos.y())
    if cmds.window("SET_SELECTION_UI", exists = True):
        cmds.deleteUI("SET_SELECTION_UI", window=True)

    cmds.window("SET_SELECTION_UI", title = "Example", wh = (102, 300), rtf=True, mnb = False, mxb = False, tb = False, sizeable = False, tlc=(mouse_pos.y(),mouse_pos.x()))
    cmds.columnLayout()
    cmds.button(label = "Set 00",   w = 100, command=button00)
    cmds.button(label = "Set 10",   w = 100, command=Button10)
    cmds.button(label = "Set 25",   w = 100, command=Button25)
    cmds.separator( height=10, style='double' )
    cmds.button(bgc=[1,1,1], label = "Cancel", w = 100, command=DeleteButton)
    cmds.showWindow() #shows window

    cmds.window("SET_SELECTION_UI", edit=True, tlc=(mouse_pos.y(),mouse_pos.x()))

The window appears properly, all the buttons do what they're supposed to do, and whenever a button is pressed, I delete the window. It's all fine and dandy.

What I'm trying to do, is to detect when the user clicks anywhere outside of the window so that I can delete the UI (much like a pop-up menu works).

Thanks!

ANSWER

I've integrated Cronicryo's script and suggestions into my own and it works perfectly now! Here it is:

from PySide import QtGui, QtCore
import maya.OpenMayaUI as omui
import pymel.core as pm
from shiboken import wrapInstance

fltr    = None
qtObj   = None
_WINDOW_NAME_ = "SET_SELECTION_UI"

class FilterObj(QtCore.QObject):
    def eventFilter(self, obj , event):
        print event.type()
        if event.type() == event.WindowDeactivate:
            print "focused out"
            pm.window(_WINDOW_NAME_,edit=True,visible=False)
            return True #must return a bool set False to allow normal events to pass through or True to stop any further events
        else:
            return False

def run():
    global fltr
    global qtObj

    if qtObj:
        del qtObj

    mouse_pos = QtGui.QCursor().pos()
    print 'mouse x: %d y: %d' % (mouse_pos.x(), mouse_pos.y())
    if pm.window(_WINDOW_NAME_, exists = True):
        pm.deleteUI(_WINDOW_NAME_, window=True)

    win = pm.window(_WINDOW_NAME_, title = "Set Select", mnb = False, mxb = False, tb = False, sizeable = False)
    pm.columnLayout()
    pm.button(label = "Do nothing",   w = 100)
    pm.separator( h=15, w=100, style='doubleDash' )
    pm.button(bgc=[1,1,1], label = "Cancel", w = 100, command=DeleteButton)
    pm.showWindow(win) #shows window

    pm.window(_WINDOW_NAME_, edit=True, wh = (102, 245),tlc=(mouse_pos.y(),mouse_pos.x()))

    qtObj = wrapInstance(long(omui.MQtUtil.findControl(_WINDOW_NAME_)), QtGui.QWidget)
    fltr = FilterObj()
    qtObj.installEventFilter(fltr)

def DeleteButton(*args):
    pm.deleteUI(_WINDOW_NAME_)

Body:
EDIT:

i took a look and it looks like there is no focus signal that gets emitted. seems like the only way to do it is to make a custom qt window and re-implement the focus functions or to install an event filter which is almost non evasive

import maya.OpenMayaUI as omui
import pymel.core as pm
pysideSupport = True
try:
    from PySide import QtGui
    from shiboken import wrapInstance
except:
    pysideSupport = False

win = pm.window("aaa")
win.show()

from PySide import QtCore

class FilterObj(QtCore.QObject):
    def eventFilter(self, obj , event):
        print event.type()
        if event.type() == event.WindowDeactivate:
            print "focused out"
            return False #must return a bool set False to allow normal events to pass through or True to stop any further events
        else:
            return False

qtObj = wrapInstance(long(omui.MQtUtil.findControl("aaa")), QtGui.QWidget)
fltr = FilterObj()
qtObj.installEventFilter(fltr)

ORIG:

this is a snippet of my own code that ive used to connect to the destroy signal of a window.
you can do the same of losing window focus

import maya.OpenMayaUI as omui
pysideSupport = True
try:
    from PySide import QtGui
    from shiboken import wrapInstance
except:
    pysideSupport = False

def onUIDelete(uiName, function):
    """
    extends mayas ui by being able to run a function when the ui gets deleted
    this requires maya to have PySide

    """
    if pysideSupport:
        if isinstance(uiName, pm.ui.PyUI):
            uiName = uiName.name()
        qtObj = wrapInstance(long(omui.MQtUtil.findControl(uiName)), QtGui.QWidget)
        qtObj.destroyed.connect(function)
    else:
        pm.error("Maya doesn't have PySide Support")


问:
Line detection in noisy image (and no detection when it is not present)
I have tried to extract the dark line inside very noisy images without success. Some tips?

My current steps for the first example:

1) Clahe: with clip_limit = 10 and grid_size = (8,8)

2) Box Filter: with size = (5,5)

3) Inverted Image: 255 - image

4) Threshold: when inverted_image < 64

UPDATE

I have performed some preprocessing steps to improve the quality of tested images. I adjusted my ROI mask to crop top and down (because they are low intensities) and added a illumination correction to see better the line. Follow below the current images:

答:
Even though the images are noisy, you are only looking for straight lines towards the north of image. So, why don't use some kind of matched filter with morphological operations?

EDIT: I have modified it.

1) Use median filter along the x and y axis, and normalize the images.
2) Matched filter with all possible orientations of lines.

```<code>% im=imread('JwXON.png');
% im=imread('Fiy72.png');
% im=imread('Ya9AN.png');
im=imread('OcgaIt8.png');

imOrig=im;

matchesx = fl(im, 1);
matchesy = fl(im, 0);

matches = matchesx + matchesy;

[x, y] = find(matches);

figure(1);
imagesc(imOrig), axis image
hold on, plot(y, x, 'r.', 'MarkerSize',5)
colormap gray

%----------

function matches = fl(im, direc)

if size(im,3)~=1
    im = double(rgb2gray(im));
else
    im=double(im);
end
[n, m] = size(im);

mask = bwmorph(imfill(im>0,'holes'),'thin',10);
indNaN=find(im==0); im=255-im; im(indNaN)=0;

N = n - numel(find(im(:,ceil(m/2))==0));
N = ceil(N*0.8); % possible line length

% Normalize the image with median filter
if direc
    background= medfilt2(im,[1,30],'symmetric');
    thetas = 31:149;
else
    background= medfilt2(im,[30,1],'symmetric');
    thetas = [1:30 150:179];
end

normIm = im - background;
normIm(normIm<0)=0;

% initialize matched filter result
matches=im*0;

% search for different angles of lines
for theta=thetas
    normIm2 = imclose(normIm>0,strel('line',5,theta));
    normIm3 = imopen(normIm2>0,strel('line',N,theta));
    matches = matches + normIm3;
end

% eliminate false alarms
matches = imclose(matches,strel('disk',2));
matches = matches>3 & mask;
matches = bwareaopen(matches,100);
</code>```

Body:
Even though the images are noisy, you are only looking for straight lines towards the north of image. So, why don't use some kind of matched filter with morphological operations?

EDIT: I have modified it.

1) Use median filter along the x and y axis, and normalize the images.
2) Matched filter with all possible orientations of lines.

% im=imread('JwXON.png');
% im=imread('Fiy72.png');
% im=imread('Ya9AN.png');
im=imread('OcgaIt8.png');

imOrig=im;

matchesx = fl(im, 1);
matchesy = fl(im, 0);

matches = matchesx + matchesy;

[x, y] = find(matches);

figure(1);
imagesc(imOrig), axis image
hold on, plot(y, x, 'r.', 'MarkerSize',5)
colormap gray

%----------

function matches = fl(im, direc)

if size(im,3)~=1
    im = double(rgb2gray(im));
else
    im=double(im);
end
[n, m] = size(im);

mask = bwmorph(imfill(im>0,'holes'),'thin',10);
indNaN=find(im==0); im=255-im; im(indNaN)=0;

N = n - numel(find(im(:,ceil(m/2))==0));
N = ceil(N*0.8); % possible line length

% Normalize the image with median filter
if direc
    background= medfilt2(im,[1,30],'symmetric');
    thetas = 31:149;
else
    background= medfilt2(im,[30,1],'symmetric');
    thetas = [1:30 150:179];
end

normIm = im - background;
normIm(normIm<0)=0;

% initialize matched filter result
matches=im*0;

% search for different angles of lines
for theta=thetas
    normIm2 = imclose(normIm>0,strel('line',5,theta));
    normIm3 = imopen(normIm2>0,strel('line',N,theta));
    matches = matches + normIm3;
end

% eliminate false alarms
matches = imclose(matches,strel('disk',2));
matches = matches>3 & mask;
matches = bwareaopen(matches,100);


问:
Watir getting started error
I was trying to begin one project of Watir, to do so i create one file (test.rb)

```<code>require 'watir'

browser = Watir::Browser.new
browser.goto 'google.com'
browser.text_field(title: 'Search').set 'Hello World!'
browser.button(type: 'submit').click

puts browser.title
# => 'Hello World! - Google Search'
browser.closeenter code here
</code>```

But when i run (ruby teste.rb), it gives me one error

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- watir/loader
 (LoadError)
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /Library/Ruby/Gems/2.0.0/gems/commonwatir-4.0.0/lib/watir.rb:1:in `<top (required)>'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:144:in `require'
        from teste.rb:1:in `<main>'
</code>```

I already install watir (gem install watir).
Can someone help me?

Thanks

答: You need to bundle update. You should not be seeing commonwatir gem dependency with Watir 6.x

Title: Watir getting started error

Body:
I was trying to begin one project of Watir, to do so i create one file (test.rb)

require 'watir'

browser = Watir::Browser.new
browser.goto 'google.com'
browser.text_field(title: 'Search').set 'Hello World!'
browser.button(type: 'submit').click

puts browser.title
# => 'Hello World! - Google Search'
browser.closeenter code here

But when i run (ruby teste.rb), it gives me one error

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- watir/loader
 (LoadError)
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /Library/Ruby/Gems/2.0.0/gems/commonwatir-4.0.0/lib/watir.rb:1:in `<top (required)>'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:144:in `require'
        from teste.rb:1:in `'

I already install watir (gem install watir).
Can someone help me?

Thanks


问:
Angular2 pipe regex url detection
I would like to have a pipe which is detecting any url in a string and creating a link with it. At the moment I created this, which seems not working:

```<code>@Pipe({name:'matchUrl'})
export class MatchUrlPipe implements PipeTransform {
    transform(value: string, arg?: any): any {
      var exp = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
      return value.replace(exp, "<a href='$1'>$1</a>");
    }
}
</code>```

How can I fix it?

答:
Seems like there are two problems with your implementation:

Your regex has the first capturing group ( $1 ) matching the 'www' part of the url. You want to change the regex like this for it to work (note the extra pair of parethesis at the start and end of the regex):

var exp = /(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))/g;

Pipes can't render html normally. You need a trick to do that as mentioned in other questione like this. You need to assign your 'piped value' to the attribute outerHTML of a span for example (the span will not be rendered).

Plunker example

Title: Angular2 pipe regex url detection

Body:
I would like to have a pipe which is detecting any url in a string and creating a link with it. At the moment I created this, which seems not working:

@Pipe({name:'matchUrl'})
export class MatchUrlPipe implements PipeTransform {
    transform(value: string, arg?: any): any {
      var exp = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g;
      return value.replace(exp, "$1");
    }
}

How can I fix it?