问:
Streaming a file in ASP.NET, C#?
Assume we have the access to sth.avi on www.dl.com with a direct link.

e.g : www.dl.com\sth.avi

Also we have a website => www.dl2.com.

Now, we wanna let some users to download sth.avi from www.dl2.com, but we don't have enough space on www.dl2.com to save sth.avi.

Is it possible in ASP.NET for us to read sth.avi from www.dl.com as streaming file and share it without saving the file on our domain.

P.S:

I don't wanna share this link www.dl.com\sth.avi, actually I wanna share something like this link www.dl2.com\downloads\sth.avi

答:
Well.... this is feasible, but it looks to me as a bad idea.

In order to achieve your result, you must open an HTTP request to www.dl.com (the hoster of the video) and then, once you read bytes from there, redirect them to Response stream.

I can't provide you with working code, but here is pseudo code

```<code>using (Stream fileStream = [open HTTP request to www.dl.com])
{
    while (fileStream is not ended)
    {
        buffer = fileStream.Read();
        Response.Write(buffer);
    }
}
</code>```

I repeat: that was pseudo-code!!!

ContentLicense: CC BY-SA 2.5

Title: Streaming a file in ASP.NET, C#?

Body:
Well.... this is feasible, but it looks to me as a bad idea.

In order to achieve your result, you must open an HTTP request to www.dl.com (the hoster of the video) and then, once you read bytes from there, redirect them to Response stream.

I can't provide you with working code, but here is pseudo code

using (Stream fileStream = [open HTTP request to www.dl.com])
{
    while (fileStream is not ended)
    {
        buffer = fileStream.Read();
        Response.Write(buffer);
    }
}

I repeat: that was pseudo-code!!!


来源: stackexchange

问:
Custom background color in conditional formatting using Apache POI
I have a XSSF workbook and I want to define a custom background color in a set of cells with a conditional formatting defined, but the problem is that the setFillBackgroundColor() method in the PatternFormatting class only accepts a type short argument, not a XSSFColor like this:

PatternFormatting fill = rule1.createPatternFormatting();
fill.setFillBackgroundColor(new XSSFColor(new java.awt.Color(80, 80, 100));
fill.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
```

I can do fill.setFillBackgroundColor(IndexedColors.RED.index), but I want to define a custom color. How can i do this?.

答:
For anyone still reading this and having the problem the requester describes back in 2014, you are probably on a version of Apache POI before 3.13. Try upgrading to at least 3.13 where you should indeed be able to do:

```<code>fill.setFillBackgroundColor(new XSSFColor(new java.awt.Color(80, 80, 100))
</code>```

(see also here: https://bz.apache.org/bugzilla/show_bug.cgi?id=56774)

ContentLicense: CC BY-SA 3.0

Body:
I have a XSSF workbook and I want to define a custom background color in a set of cells with a conditional formatting defined, but the problem is that the setFillBackgroundColor() method in the PatternFormatting class only accepts a type short argument, not a XSSFColor like this:

PatternFormatting fill = rule1.createPatternFormatting();
fill.setFillBackgroundColor(new XSSFColor(new java.awt.Color(80, 80, 100));
fill.setFillPattern(PatternFormatting.SOLID_FOREGROUND);

I can do fill.setFillBackgroundColor(IndexedColors.RED.index), but I want to define a custom color. How can i do this?.

Body:
For anyone still reading this and having the problem the requester describes back in 2014, you are probably on a version of Apache POI before 3.13. Try upgrading to at least 3.13 where you should indeed be able to do:

fill.setFillBackgroundColor(new XSSFColor(new java.awt.Color(80, 80, 100))

(see also here: https://bz.apache.org/bugzilla/show_bug.cgi?id=56774)


问:
Indices of fixed size sub-matrices of numpy array
I am implementing an algorithm which requires me to look at non-overlapping consecutive submatrices within a (strictly two dimensional) numpy array. eg, for the 12 by 12

```<code>>>> a = np.random.randint(20, size=(12, 12)); a
array([[ 4,  0, 12, 14,  3,  8, 14, 12, 11, 18,  6,  6],
       [15, 13,  2, 18, 15, 15, 16,  2,  9, 16,  6,  4],
       [18, 18,  3,  8,  1, 15, 14, 13, 13, 13,  7,  0],
       [ 1,  9,  3,  6,  0,  4,  3, 15,  0,  9, 11, 12],
       [ 5, 15,  5,  6,  4,  4, 18, 13, 10, 17, 11,  8],
       [13, 17,  8, 15, 17, 12,  7,  1, 13, 15,  0, 18],
       [ 2,  1, 11, 12,  3, 16, 11,  9, 10, 15,  4, 16],
       [19, 11, 10,  7, 10, 19,  7, 13, 11,  9, 17,  8],
       [14, 14, 17,  0,  0,  0, 11,  1, 10, 14,  2,  7],
       [ 6, 15,  6,  7, 15, 19,  2,  4,  6, 16,  0,  3],
       [ 5, 10,  7,  5,  0,  8,  5,  8,  9, 14,  4,  3],
       [17,  2,  0,  3, 15, 10, 14,  1,  0,  7, 16,  2]])
</code>```

and looking at 3x3 submatrices, I would want the first 3x3 submatrix to be from the upper left corner:

```<code>>>> a[0:3, 0:3]
array([[ 4,  0, 12],
       [15, 13,  2],
       [18, 18,  3]])
</code>```

The next along to be given by a[0:3, 3:6] and so on. It doesn't matter if the last such set of indices in each row or column runs off the end of the array - numpy's behavior of simply giving the portion within the slice that exists is sufficient.

I want a way to generate these slice indices programatically for arbitrarily sized matrices and submatrices. I currently have this:

```<code>size = 3
x_max = a.shape[0]
xcoords = range(0, x_max, size)
xcoords = zip(xcoords, xcoords[1:])
</code>```

and similarly to generate y_coords, so that the series of indices is given by itertools.product(xcoords, ycoords).

My question is: is there a more direct way to do this, perhaps using numpy.mgrid or some other numpy technique?

答:
I'm adding this answer to an old question since an edit has bumped this question up.  Here's an alternative way to calculate blocks:

```<code>size = 3
lenr, lenc = int(a.shape[0]/size), int(a.shape[1]/size)

t = a.reshape(lenr,size,lenc,size).transpose(0, 2, 1, 3)
</code>```

Profiling shows that this is the fastest.  Profiling done with python 3.5, and the results from map passed to array() for compatibility, since in 3.5 map returns an iterator.

```<code>reshape/transpose:   643 ns per loop
reshape/index:       45.8 µs per loop
Map/split:           10.3 µs per loop
</code>```

It's interesting that the iterator version of map is faster.  In any case, using reshape and transpose is fastest.

Body:
I am implementing an algorithm which requires me to look at non-overlapping consecutive submatrices within a (strictly two dimensional) numpy array. eg, for the 12 by 12

>>> a = np.random.randint(20, size=(12, 12)); a
array([[ 4,  0, 12, 14,  3,  8, 14, 12, 11, 18,  6,  6],
       [15, 13,  2, 18, 15, 15, 16,  2,  9, 16,  6,  4],
       [18, 18,  3,  8,  1, 15, 14, 13, 13, 13,  7,  0],
       [ 1,  9,  3,  6,  0,  4,  3, 15,  0,  9, 11, 12],
       [ 5, 15,  5,  6,  4,  4, 18, 13, 10, 17, 11,  8],
       [13, 17,  8, 15, 17, 12,  7,  1, 13, 15,  0, 18],
       [ 2,  1, 11, 12,  3, 16, 11,  9, 10, 15,  4, 16],
       [19, 11, 10,  7, 10, 19,  7, 13, 11,  9, 17,  8],
       [14, 14, 17,  0,  0,  0, 11,  1, 10, 14,  2,  7],
       [ 6, 15,  6,  7, 15, 19,  2,  4,  6, 16,  0,  3],
       [ 5, 10,  7,  5,  0,  8,  5,  8,  9, 14,  4,  3],
       [17,  2,  0,  3, 15, 10, 14,  1,  0,  7, 16,  2]])

and looking at 3x3 submatrices, I would want the first 3x3 submatrix to be from the upper left corner:

>>> a[0:3, 0:3]
array([[ 4,  0, 12],
       [15, 13,  2],
       [18, 18,  3]])

The next along to be given by a[0:3, 3:6] and so on. It doesn't matter if the last such set of indices in each row or column runs off the end of the array - numpy's behavior of simply giving the portion within the slice that exists is sufficient.

I want a way to generate these slice indices programatically for arbitrarily sized matrices and submatrices. I currently have this:

size = 3
x_max = a.shape[0]
xcoords = range(0, x_max, size)
xcoords = zip(xcoords, xcoords[1:])

and similarly to generate y_coords, so that the series of indices is given by itertools.product(xcoords, ycoords).

My question is: is there a more direct way to do this, perhaps using numpy.mgrid or some other numpy technique?

Body:
I'm adding this answer to an old question since an edit has bumped this question up.  Here's an alternative way to calculate blocks:

size = 3
lenr, lenc = int(a.shape[0]/size), int(a.shape[1]/size)

t = a.reshape(lenr,size,lenc,size).transpose(0, 2, 1, 3)

Profiling shows that this is the fastest.  Profiling done with python 3.5, and the results from map passed to array() for compatibility, since in 3.5 map returns an iterator.

reshape/transpose:   643 ns per loop
reshape/index:       45.8 µs per loop
Map/split:           10.3 µs per loop

It's interesting that the iterator version of map is faster.  In any case, using reshape and transpose is fastest.


问:
javascript foreach find and update
Let say I have an array of tree type data

```<code>[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ]
</code>```

is it possible to update the array to

```<code>[ { 'id': 1, 'name': 'root', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3, 'parent_name': 'level 2' } ]
</code>```

using lodash forEach and find?

```<code>_.forEach(arr, function (o) {
  let item = _.find(arr, {'id': o.parent_id})
  o.parent_name = item.name
})
</code>```

my problem is inside the function of forEach, it has no idea what arr is, I got it working replacing the forEach with a plain for loop.

```<code>for (i = 0; i < arr.length; i++) {
  let item = _.find(arr, {'id': arr[i].parent_id})
  arr[i].parent_name = item.name
}
</code>```

So wondering if there're any more elegant way to accomplish this

答:
you can use .map to change object as-</p>

```<code>const arr =[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ];

const newArr = arr.map((item) => {
  if(name === 'root') return Object.assign({}, item, {parent_name: 'root'});
  const findIndexOfParent = arr.findIndex((pItem) => pItem.id == item.parent_id);
  if(findIndexOfParent > -1){
    return Object.assign({}, item, {parent_name: arr[findIndexOfParent].name});
  }
});

console.log(newArr);
</code>```

Title: javascript foreach find and update

Body:
Let say I have an array of tree type data

[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ]

is it possible to update the array to

[ { 'id': 1, 'name': 'root', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1, 'parent_name': 'root' },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3, 'parent_name': 'level 2' } ]

using lodash forEach and find?

_.forEach(arr, function (o) {
  let item = _.find(arr, {'id': o.parent_id})
  o.parent_name = item.name
})

my problem is inside the function of forEach, it has no idea what arr is, I got it working replacing the forEach with a plain for loop.

for (i = 0; i < arr.length; i++) {
  let item = _.find(arr, {'id': arr[i].parent_id})
  arr[i].parent_name = item.name
}

So wondering if there're any more elegant way to accomplish this

Body:
you can use .map to change object as-

const arr =[ { 'id': 1, 'name': 'root', 'parent_id': 1 },
  { 'id': 2, 'name': 'level 1', 'parent_id': 1 },
  { 'id': 3, 'name': 'level 2', 'parent_id': 1 },
  { 'id': 4, 'name': 'level 2.1', 'parent_id': 3 } ];

const newArr = arr.map((item) => {
  if(name === 'root') return Object.assign({}, item, {parent_name: 'root'});
  const findIndexOfParent = arr.findIndex((pItem) => pItem.id == item.parent_id);
  if(findIndexOfParent > -1){
    return Object.assign({}, item, {parent_name: arr[findIndexOfParent].name});
  }
});

console.log(newArr);


答:
Slicing a string is easy as:

```<code>"$400.00".slice(1);
</code>```

or

```<code>var currencyString = "$400.00";
var valueString = mystring.slice(1);
</code>```

Where the 1 is the index the character you want to slice at.

This assumes that the $ sign will always be at the 1st position.

Title: String slicing in javascript

Body:
export class Prices{
value : string;
}

const PRICES : Prices[] =[
{value :'$10,000'},{value :'$20,000'},{value :'$30,000'},{value
:'$40,000'},{value :'$50,000'},
{value :'$60,000'},{value :'$70,000'},{value :'$80,000'},{value
:'$90,000'},{value :'$100,000'},
{value :'$125,000'},{value :'$150,000'},{value :'$175,000'},{value
:'$200,000'},{value :'$225,000'},
{value :'$250,000'},{value :'$275,000'},{value :'$300,000'},{value
:'$325,000'},{value :'$350,000'},
{value :'$375,000'},{value :'$400,000'},{value :'$425,000'},{value
:'$450,000'},{value :'$475,000'},
{value :'$500,000'},{value :'$525,000'},{value :'$550,000'},{value
:'$575,000'},{value :'$600,000'}]

export class ConstantProperty implements OnInit{
prices=PRICES;
selectedPriceMin : Prices;
}

I am selecting the price from a drop down menu in html,
Now I want to slice that selected price in order to remove dollar sign.

Body:
Slicing a string is easy as:

"$400.00".slice(1);

or

var currencyString = "$400.00";
var valueString = mystring.slice(1);

Where the 1 is the index the character you want to slice at.

This assumes that the $ sign will always be at the 1st position.


问:
PHP performance question
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

```<code>if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
</code>```

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.

答: I would say, if you can, keep a cached version for the people who are not logged in, and generate everything when they're logged in.</p>

Title: PHP performance question

Body:
Wondering which would be better for performance. The site will be viewed by people that are logged in and people that are not. The site is almost the same for the users that are logged in except they have more privledges. So I am wondering what would be more efficient.

//OPTION ONE

if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access.
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.

I am wondering if it would be better for performance using option one because the function would first be checked once, and wouldn't need to be checked again, if the user is logged in the first chunk would be loaded, if the user is not logged in, it would ignore the first chunk and load the second chunk.


问:
Collecting card details within the app on Telr Payment gateway
I am integrating "Telr" payment gateway on my current app.I have read all docs part. My app will be collecting the card details (rather than using the hosted payment pages).This is the request i am making.If anybody has some demo or integrated Telr payment gateway, please feel free to reply.

```<code>let paramString: String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<mobile>" +
        "<store>\(12345)</store>" + "<key>somekey</key>" +
        "<device>" +
        "<type>\("iPhone6")</type>" +
        "<id>\(deviceId)</id>" +
        "<agent></agent>" +
        "<accept></accept>" +
        "</device>" +
        "<app>" +
        "<name>Telr_Payment_Demo</name>" +
        "<version>1.0</version>" +
        "<user>xyz.Demo</user>" +
        "<id>1234567</id>" +
        "</app>" +
        "<tran>" +
        "<test>12</test>" +
        "<type>paypage</type>" +
        "<class>moto</class>" +
        "<cartid>syste1075</cartid>" +
        "<description>this is demo on telr</description>" +
        "<currency>AED</currency>" +
        "<amount>\(9.80)</amount>" +
        "<ref>\("000000000001")</ref>" +
        "</tran>" +
        "<card>" +
        "<number>\("5555555555554444")</number>" +
        "<expiry>" +
        "<month>\(02)</month>" +
        "<year>\(2018)</year>" +
        "</expiry>" +
        "<cvv>\(123)</cvv>" +
        "</card>" +
        "<billing>" +
        "<name>" +
        "<title>\("fsfsfs")</title>" +
        "<first>\("First")</first>" +
        "<last>\("last")</last>" +
        "</name>\n" +
        "<address>" +
        "<line1>\("Kathmandu bazar")</line1>" +
        "<line2>\("address 6")</line2>" +
        "<line3>\("Near gausala")</line3>" +
        "<city>\("kathmandu")</city>" +
        "<region>\("Bagmati")</region>" +
        "<country>\("Nepal")</country>" +
        "<zip>\("977")</zip>" +
        "</address>" +
        "<email>\("s*********@gmail.com")</email>" +
        "</billing>" +
    "</mobile>"
</code>```

I am getting following response from server

```<code> <mobile>
 <webview>
 <start>https://secure.innovatepayments.com/gateway/webview_start.html? code=f1caa6ce6c23595b71dc00369</start>
<close>https://secure.innovatepayments.com/gateway/webview_close.html</close>
<abort>https://secure.innovatepayments.com/gateway/webview_abort.html</abort>
<code>f1caa6ce6c23595b71dc00369</code>
</webview>
<trace>40008/1683846/595b7168dc</trace>
</mobile>
</code>```

The first url will redirect to hosted payment pages card details view.I do not know what should i do with that response.This is the payment integration guidelines for developer.

答:
From the docs you linked to say:

When a webview response is received, the App will need to direct the
  customer to the URL given as the start address. The App should monitor
  the progress of the webview, and once it reaches the URL provided as
  the close address, it should close the web display and continue with
  the transaction process.

To complete the transaction, the App must now make a second request to
  the gateway. This request includes will trigger the final
  authorisation stage of the transaction, and return the authorisation
  response. The request must be sent to:

https://secure.innovatepayments.com/gateway/mobile_complete.xml
  ...

so I would start with that and see what happens

Body:
I am integrating "Telr" payment gateway on my current app.I have read all docs part. My app will be collecting the card details (rather than using the hosted payment pages).This is the request i am making.If anybody has some demo or integrated Telr payment gateway, please feel free to reply.

let paramString: String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
        "<mobile>" +
        "<store>\(12345)</store>" + "<key>somekey</key>" +
        "<device>" +
        "<type>\("iPhone6")</type>" +
        "<id>\(deviceId)</id>" +
        "<agent></agent>" +
        "<accept></accept>" +
        "</device>" +
        "<app>" +
        "<name>Telr_Payment_Demo</name>" +
        "<version>1.0</version>" +
        "<user>xyz.Demo</user>" +
        "<id>1234567</id>" +
        "</app>" +
        "<tran>" +
        "<test>12</test>" +
        "<type>paypage</type>" +
        "<class>moto</class>" +
        "<cartid>syste1075</cartid>" +
        "<description>this is demo on telr</description>" +
        "<currency>AED</currency>" +
        "<amount>\(9.80)</amount>" +
        "<ref>\("000000000001")</ref>" +
        "</tran>" +
        "<card>" +
        "<number>\("5555555555554444")</number>" +
        "<expiry>" +
        "<month>\(02)</month>" +
        "<year>\(2018)</year>" +
        "</expiry>" +
        "<cvv>\(123)</cvv>" +
        "</card>" +
        "<billing>" +
        "<name>" +
        "<title>\("fsfsfs")</title>" +
        "<first>\("First")</first>" +
        "<last>\("last")</last>" +
        "</name>\n" +
        "<address>" +
        "<line1>\("Kathmandu bazar")</line1>" +
        "<line2>\("address 6")</line2>" +
        "<line3>\("Near gausala")</line3>" +
        "<city>\("kathmandu")</city>" +
        "<region>\("Bagmati")</region>" +
        "<country>\("Nepal")</country>" +
        "<zip>\("977")</zip>" +
        "</address>" +
        "<email>\("s*********@gmail.com")</email>" +
        "</billing>" +
    "</mobile>"

I am getting following response from server

 <mobile>
 <webview>
 <start>https://secure.innovatepayments.com/gateway/webview_start.html? code=f1caa6ce6c23595b71dc00369</start>
<close>https://secure.innovatepayments.com/gateway/webview_close.html</close>
<abort>https://secure.innovatepayments.com/gateway/webview_abort.html</abort>
f1caa6ce6c23595b71dc00369
</webview>
<trace>40008/1683846/595b7168dc</trace>
</mobile>

The first url will redirect to hosted payment pages card details view.I do not know what should i do with that response.This is the payment integration guidelines for developer.


问:
Can't import opencv in Python 2.7: ImportError: No module named cv2 despite installed opencv 3.2.0
I used brew to install opencv 3.2.0 and it seems successful to me. Yet module cv2 still cannot be found when I tried to run this:

```<code>FF-MBP:read_video_frames ff$ python v2f.py
Traceback (most recent call last):
  File "v2f.py", line 4, in <module>
    import cv2
ImportError: No module named cv2
</code>```

The brew installation looks like this:

```<code>FF-MBP:read_video_frames ff$ brew install opencv3
==> Installing opencv3 from homebrew/science
==> Installing dependencies for homebrew/science/opencv3: eigen, jpeg, libpng, libtiff, ilmbase, openexr
==> Installing homebrew/science/opencv3 dependency: eigen
==> Downloading https://homebrew.bintray.com/bottles/eigen-3.3.4.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring eigen-3.3.4.sierra.bottle.tar.gz
==> Using the sandbox
  /usr/local/Cellar/eigen/3.3.4: 486 files, 6.5MB
==> Installing homebrew/science/opencv3 dependency: jpeg
==> Downloading https://homebrew.bintray.com/bottles/jpeg-8d.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring jpeg-8d.sierra.bottle.2.tar.gz
  /usr/local/Cellar/jpeg/8d: 19 files, 708.3KB
==> Installing homebrew/science/opencv3 dependency: libpng
==> Downloading https://homebrew.bintray.com/bottles/libpng-1.6.29.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libpng-1.6.29.sierra.bottle.tar.gz
  /usr/local/Cellar/libpng/1.6.29: 26 files, 1.2MB
==> Installing homebrew/science/opencv3 dependency: libtiff
==> Downloading https://homebrew.bintray.com/bottles/libtiff-4.0.8.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libtiff-4.0.8.sierra.bottle.tar.gz
  /usr/local/Cellar/libtiff/4.0.8: 245 files, 3.4MB
==> Installing homebrew/science/opencv3 dependency: ilmbase
==> Downloading https://homebrew.bintray.com/bottles/ilmbase-2.2.0.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring ilmbase-2.2.0.sierra.bottle.2.tar.gz
  /usr/local/Cellar/ilmbase/2.2.0: 362 files, 5.6MB
==> Installing homebrew/science/opencv3 dependency: openexr
==> Downloading https://homebrew.bintray.com/bottles/openexr-2.2.0.sierra.bottle.1.tar.gz
######################################################################## 100.0%
==> Pouring openexr-2.2.0.sierra.bottle.1.tar.gz
  /usr/local/Cellar/openexr/2.2.0: 131 files, 11.2MB
==> Installing homebrew/science/opencv3
==> Downloading https://homebrew.bintray.com/bottles-science/opencv3-3.2.0.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring opencv3-3.2.0.sierra.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because opencv3 and opencv install many of the same files.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/opencv3/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/opencv3/lib
    CPPFLAGS: -I/usr/local/opt/opencv3/include

If you need Python to find bindings for this keg-only formula, run:
  echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth
==> Summary
  /usr/local/Cellar/opencv3/3.2.0: 286 files, 47.4MB
</code>```

Is it because opencv 3.0+ only compiles with Python3.x? I tried import cv3 - doesn't work.
Appreciate any inputs. Thank you!

Mac OS X: Sierra 10.12.5

Python: 2.7

OpenCV: 3.2.0

答: Actually this is solved! I managed to get it correctly installed on PyCharm. Tutorial: https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html#d64763e97</p>

Body:
I used brew to install opencv 3.2.0 and it seems successful to me. Yet module cv2 still cannot be found when I tried to run this:

FF-MBP:read_video_frames ff$ python v2f.py
Traceback (most recent call last):
  File "v2f.py", line 4, in <module>
    import cv2
ImportError: No module named cv2

The brew installation looks like this:

FF-MBP:read_video_frames ff$ brew install opencv3
==> Installing opencv3 from homebrew/science
==> Installing dependencies for homebrew/science/opencv3: eigen, jpeg, libpng, libtiff, ilmbase, openexr
==> Installing homebrew/science/opencv3 dependency: eigen
==> Downloading https://homebrew.bintray.com/bottles/eigen-3.3.4.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring eigen-3.3.4.sierra.bottle.tar.gz
==> Using the sandbox
  /usr/local/Cellar/eigen/3.3.4: 486 files, 6.5MB
==> Installing homebrew/science/opencv3 dependency: jpeg
==> Downloading https://homebrew.bintray.com/bottles/jpeg-8d.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring jpeg-8d.sierra.bottle.2.tar.gz
  /usr/local/Cellar/jpeg/8d: 19 files, 708.3KB
==> Installing homebrew/science/opencv3 dependency: libpng
==> Downloading https://homebrew.bintray.com/bottles/libpng-1.6.29.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libpng-1.6.29.sierra.bottle.tar.gz
  /usr/local/Cellar/libpng/1.6.29: 26 files, 1.2MB
==> Installing homebrew/science/opencv3 dependency: libtiff
==> Downloading https://homebrew.bintray.com/bottles/libtiff-4.0.8.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring libtiff-4.0.8.sierra.bottle.tar.gz
  /usr/local/Cellar/libtiff/4.0.8: 245 files, 3.4MB
==> Installing homebrew/science/opencv3 dependency: ilmbase
==> Downloading https://homebrew.bintray.com/bottles/ilmbase-2.2.0.sierra.bottle.2.tar.gz
######################################################################## 100.0%
==> Pouring ilmbase-2.2.0.sierra.bottle.2.tar.gz
  /usr/local/Cellar/ilmbase/2.2.0: 362 files, 5.6MB
==> Installing homebrew/science/opencv3 dependency: openexr
==> Downloading https://homebrew.bintray.com/bottles/openexr-2.2.0.sierra.bottle.1.tar.gz
######################################################################## 100.0%
==> Pouring openexr-2.2.0.sierra.bottle.1.tar.gz
  /usr/local/Cellar/openexr/2.2.0: 131 files, 11.2MB
==> Installing homebrew/science/opencv3
==> Downloading https://homebrew.bintray.com/bottles-science/opencv3-3.2.0.sierra.bottle.tar.gz
######################################################################## 100.0%
==> Pouring opencv3-3.2.0.sierra.bottle.tar.gz
==> Caveats
This formula is keg-only, which means it was not symlinked into /usr/local,
because opencv3 and opencv install many of the same files.

If you need to have this software first in your PATH run:
  echo 'export PATH="/usr/local/opt/opencv3/bin:$PATH"' >> ~/.bash_profile

For compilers to find this software you may need to set:
    LDFLAGS:  -L/usr/local/opt/opencv3/lib
    CPPFLAGS: -I/usr/local/opt/opencv3/include

If you need Python to find bindings for this keg-only formula, run:
  echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth
==> Summary
  /usr/local/Cellar/opencv3/3.2.0: 286 files, 47.4MB

Is it because opencv 3.0+ only compiles with Python3.x? I tried import cv3 - doesn't work.
Appreciate any inputs. Thank you!

Mac OS X: Sierra 10.12.5

Python: 2.7

OpenCV: 3.2.0


问:
No matching distribution found for antlr-python-runtime
```<code>pip install google_appengine
Collecting google-appengine
  Using cached google-appengine-1.5.1.tar.gz
Collecting pyyaml (from google-appengine)
  Using cached PyYAML-3.11.tar.gz
Collecting webob==0.9 (from google-appengine)
  Using cached WebOb-0.9.tar.gz
Collecting ipaddr (from google-appengine)
  Using cached ipaddr-2.1.11.tar.gz
Collecting antlr-python-runtime (from google-appengine)
  Could not find a version that satisfies the requirement antlr-python-runtime (from google-appengine) (from versions: )
No matching distribution found for antlr-python-runtime (from google-appengine)
</code>```

Pip shows it is available but doesn't install it:

```<code>pip search antlr
antlr4-python-alt          - Alternative Python runtime for ANTLR 4
antlr_python_runtime       - Runtime package for ANTLR3
antlr4-python3-runtime     - ANTLR 4.5.2.1 runtime for Python 3.4.0
antlr4-python2-runtime     - ANTLR 4.5.2.1 runtime for Python 2.7.6
  INSTALLED: 4.5.2.1 (latest)

pip install antlr_python_runtime
Collecting antlr-python-runtime
  Could not find a version that satisfies the requirement antlr-python-runtime (from versions: )
No matching distribution found for antlr-python-runtime
</code>```

antlr4-python2-runtime is installed but seems not to be enough:

```<code>pip install antlr4-python2-runtime
Requirement already satisfied (use --upgrade to upgrade): antlr4-python2-runtime
</code>```

This issue suggests to install with --allow-unverified and --allow-external but both arguments don't work in the latest version of pip (8.0.2) anymore.

Any help is appreciated.

答:
Found the 3.1.3 version of antlr in the following link

After running:

```<code>pip install http://www.antlr3.org/download/Python/antlr_python_runtime-3.1.3.tar.gz
</code>```

the pip google-appengine worked ok

Body:
pip install google_appengine
Collecting google-appengine
  Using cached google-appengine-1.5.1.tar.gz
Collecting pyyaml (from google-appengine)
  Using cached PyYAML-3.11.tar.gz
Collecting webob==0.9 (from google-appengine)
  Using cached WebOb-0.9.tar.gz
Collecting ipaddr (from google-appengine)
  Using cached ipaddr-2.1.11.tar.gz
Collecting antlr-python-runtime (from google-appengine)
  Could not find a version that satisfies the requirement antlr-python-runtime (from google-appengine) (from versions: )
No matching distribution found for antlr-python-runtime (from google-appengine)

Pip shows it is available but doesn't install it:

pip search antlr
antlr4-python-alt          - Alternative Python runtime for ANTLR 4
antlr_python_runtime       - Runtime package for ANTLR3
antlr4-python3-runtime     - ANTLR 4.5.2.1 runtime for Python 3.4.0
antlr4-python2-runtime     - ANTLR 4.5.2.1 runtime for Python 2.7.6
  INSTALLED: 4.5.2.1 (latest)

pip install antlr_python_runtime
Collecting antlr-python-runtime
  Could not find a version that satisfies the requirement antlr-python-runtime (from versions: )
No matching distribution found for antlr-python-runtime

antlr4-python2-runtime is installed but seems not to be enough:

pip install antlr4-python2-runtime
Requirement already satisfied (use --upgrade to upgrade): antlr4-python2-runtime

This issue suggests to install with --allow-unverified and --allow-external but both arguments don't work in the latest version of pip (8.0.2) anymore.

Any help is appreciated.

Body:
Found the 3.1.3 version of antlr in the following link

After running:

pip install http://www.antlr3.org/download/Python/antlr_python_runtime-3.1.3.tar.gz

the pip google-appengine worked ok


问:
Python sockets error TypeError: a bytes-like object is required, not 'str' with send function
I am trying to create a program that will open a port on the local machine and let others connect into it via netcat. My current code is.

```<code>s = socket.socket()
host = '127.0.0.1'
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    c.send('Thank you for connecting')
    c.close()
</code>```

I am new to Python and sockets. But when I run this code it will allow me to send a netcat connection with the command:

```<code>nc 127.0.0.1 12345
</code>```

But then on my Python script I get the error for the c.send:

```<code>TypeError: a bytes-like object is required, not 'str'
</code>```

I am basically just trying to open a port, allow netcat to connect and have a full shell on that machine.

答: You can decode it to str with receive.decode('utf_8').

Body:
I am trying to create a program that will open a port on the local machine and let others connect into it via netcat. My current code is.

s = socket.socket()
host = '127.0.0.1'
port = 12345
s.bind((host, port))

s.listen(5)
while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    c.send('Thank you for connecting')
    c.close()

I am new to Python and sockets. But when I run this code it will allow me to send a netcat connection with the command:

nc 127.0.0.1 12345

But then on my Python script I get the error for the c.send:

TypeError: a bytes-like object is required, not 'str'

I am basically just trying to open a port, allow netcat to connect and have a full shell on that machine.


问:
Which constructor should I use for the StringBuilder class?
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

```<code>Dim sb = New StringBuilder(averageCharacterCount * items.Count)
</code>```

instead of

```<code>Dim sb = New StringBuilder()
</code>```

even if the specified capacity is just a guess?

答: I would guess the former because it will help minimize reallocations but I would guess the difference is de minimis (we call this a "micro optimization") as this is unlikely to even be a bottleneck. But only you can answer which will definitely give you the better performance based on your specific use-case. If you really want to know, write the code both ways, measure the performance of each and you'll have a definitive answer.</p>

Body:
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

Dim sb = New StringBuilder(averageCharacterCount * items.Count)

instead of

Dim sb = New StringBuilder()

even if the specified capacity is just a guess?


问:
Hide select if when don´t found any results
I have a select like this:

```<code><select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select>
</code>```

I try to hide select if I don´t have options with ng-hide as:

```<code><select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos " ng-hide="item.Catalogos == 0"></select>
</code>```

or with ng-show as:

```<code><select class="form-control" ng-show="Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
</code>```

But no one works, it still showing up, can anyone help me there?

Note: I found an issue, if I debbug select with chrome or firefox I
  get a default option as:

```<code><option value="?" selected="selected"></option>
</code>```

Is it possible to skip this?

答:
Your ng-hide should be using item.Catalogos.length:

```<code>ng-hide="item.Catalogos.length == 0"
</code>```

or

```<code>ng-hide="!item.Catalogos"
</code>```

Body:
I have a select like this:

<select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select>

I try to hide select if I don´t have options with ng-hide as:

<select class="form-control" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos " ng-hide="item.Catalogos == 0"></select>

or with ng-show as:

<select class="form-control" ng-show="Catalogos" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

But no one works, it still showing up, can anyone help me there?

Note: I found an issue, if I debbug select with chrome or firefox I
  get a default option as:

<option value="?" selected="selected"></option>

Is it possible to skip this?

Body:
Your ng-hide should be using item.Catalogos.length:

ng-hide="item.Catalogos.length == 0"

or

ng-hide="!item.Catalogos"


问:
Shift register implementation with arbitrary shift amount
I want to develop a shift register in VHDL for a processor. In the Instruction Register (IR) of processor there is a section that determines the shift amount. Now I want to check it to implement this operation.

For example, bit numbers 5 to 10 show the shift amount. If there is "000001" in this section, when the timing signal t1 occurs the shift register should function and the t2 timing signal arrives.

But why does the following code not show any effect on the shift register when running with modelsim?

```<code>IF sc=t1 AND R2 (10 DOWNTO 5)= "000001" THEN
R2<=R2(62 DOWNTO 0) & R2(63);
END IF;
</code>```

答:
I think that your approach is correct. Since in VHDL is always better to use as most constant values as possible, so synthesis can be easier I would write a code for your case

```<code>process(clk, reset)
begin
  if reset then
   --reset everything
  elsif posedge(clk) then
  if sc = t1 then
    case R2(10 DOWNTO 5)
      when "00001" =>
        R2 <= R2(62 DOWNTO 0) & R2(63)
      when "00010" =>
  end if
end process
</code>```

The above code is just an idea of what needs to be done. We need to shows more of the actual code you are using.

Body:
I want to develop a shift register in VHDL for a processor. In the Instruction Register (IR) of processor there is a section that determines the shift amount. Now I want to check it to implement this operation.

For example, bit numbers 5 to 10 show the shift amount. If there is "000001" in this section, when the timing signal t1 occurs the shift register should function and the t2 timing signal arrives.

But why does the following code not show any effect on the shift register when running with modelsim?

IF sc=t1 AND R2 (10 DOWNTO 5)= "000001" THEN
R2<=R2(62 DOWNTO 0) & R2(63);
END IF;

Body:
I think that your approach is correct. Since in VHDL is always better to use as most constant values as possible, so synthesis can be easier I would write a code for your case

process(clk, reset)
begin
  if reset then
   --reset everything
  elsif posedge(clk) then
  if sc = t1 then
    case R2(10 DOWNTO 5)
      when "00001" =>
        R2 <= R2(62 DOWNTO 0) & R2(63)
      when "00010" =>
  end if
end process

The above code is just an idea of what needs to be done. We need to shows more of the actual code you are using.


问:
Getting round Max string size of 32347 in a VBA function
My VBA function stops working with one additional line of code. The final line of code in the working function is: returnString = returnString + "some text from some cell". If I copy paste that line of code, it breaks.

The only cause I can see is string length. When I output the length of returnString in the working function it is 32347. EDIT: So 32347 works, but adding a further 10 characters or so it starts to fail. This looks suspiciously close to a maximum length of some sort. Is there any way round this?

At the moment I am using this Function (not Sub) to return the string to an Excel cell. A separate Sub-routine then picks up the contents of the cell, to integrate it with other data and output a JSON file.

This question appears to ask the same thing, but the max was 255, and so the answers don't help me: Getting around the Max String size in a vba function?. Please note, though, that when I save the 32347-length string, it is 32k. So I can't have hit the 2GB limit!

Any help appreciated!

```<code>Function getData(str)

Dim lArray() As String
Dim pData As String
Dim ctr As Integer
Dim ctr2 As Integer
Dim ctr3 As Integer
Dim returnString As String
Set rangetoexport = Worksheets("mysheet").Range("c2:m2728")
Dim id As Long
Dim rowRef As Long
Dim colRef As Integer
Dim var(47) As String

Const idColumn = 1
Const webColumn = 2
Const nameColumn = 3
Const revColumn = 4
Const empColumn = 5
Const ctryColumn = 10
Const indyColumn = 11

Const numFactors = 47

Const labelRow = 1

Const apost = """"

lArray = Split(str, ",")

returnString = "["

  If UBound(lArray) <> 0 Then

        pData = ""

        For ctr = 0 To UBound(lArray)

            'Open the object
            returnString = returnString + "{"

            'Find the row
            id = lArray(ctr)
            rowRef = -1

            For ctr2 = 0 To rangetoexport.Rows.Count
                If rangetoexport.Cells(ctr2, idColumn) = id Then
                    rowRef = ctr2
                    Exit For
                End If
            Next

            'add the parts
            'add the ID and new object

            returnString = returnString & """company"": {"

            returnString = returnString & """ID"":" & rangetoexport.Cells(rowRef, idColumn) & ","
            returnString = returnString & """Website"":""" & rangetoexport.Cells(rowRef, webColumn) & ""","
            returnString = returnString & """Company Name"":""" & rangetoexport.Cells(rowRef, nameColumn) & ""","
            returnString = returnString & """Revenue"":""" & rangetoexport.Cells(rowRef, revColumn) & ""","
            returnString = returnString & """Employee Count"":" & rangetoexport.Cells(rowRef, empColumn) & ","
            returnString = returnString & """Country"":""" & rangetoexport.Cells(rowRef, ctryColumn) & ""","
            returnString = returnString & """Industry Classification (SIC4)"":""" & rangetoexport.Cells(rowRef, indyColumn) & """}},"

            'returnString = returnString & """factors"": {"

            'For ctr3 = 1 To 10

            'Next

            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","
            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","
            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","
            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","

            'returnString = returnString & rangetoexport.Cells(rowRef, webColumn) & "},"

        Next

    Else
        returnString = ""

    End If

returnString = Left(returnString, Len(returnString) - 1)

getData = returnString & "]"
</code>```

答: I would recommend the use of an Array instead. You could create a dynamically sized array and at the end, it is easier to manipulate it.</p>

Body:
My VBA function stops working with one additional line of code. The final line of code in the working function is: returnString = returnString + "some text from some cell". If I copy paste that line of code, it breaks.

The only cause I can see is string length. When I output the length of returnString in the working function it is 32347. EDIT: So 32347 works, but adding a further 10 characters or so it starts to fail. This looks suspiciously close to a maximum length of some sort. Is there any way round this?

At the moment I am using this Function (not Sub) to return the string to an Excel cell. A separate Sub-routine then picks up the contents of the cell, to integrate it with other data and output a JSON file.

This question appears to ask the same thing, but the max was 255, and so the answers don't help me: Getting around the Max String size in a vba function?. Please note, though, that when I save the 32347-length string, it is 32k. So I can't have hit the 2GB limit!

Any help appreciated!

Function getData(str)

Dim lArray() As String
Dim pData As String
Dim ctr As Integer
Dim ctr2 As Integer
Dim ctr3 As Integer
Dim returnString As String
Set rangetoexport = Worksheets("mysheet").Range("c2:m2728")
Dim id As Long
Dim rowRef As Long
Dim colRef As Integer
Dim var(47) As String

Const idColumn = 1
Const webColumn = 2
Const nameColumn = 3
Const revColumn = 4
Const empColumn = 5
Const ctryColumn = 10
Const indyColumn = 11

Const numFactors = 47

Const labelRow = 1

Const apost = """"

lArray = Split(str, ",")

returnString = "["

  If UBound(lArray) <> 0 Then

        pData = ""

        For ctr = 0 To UBound(lArray)

            'Open the object
            returnString = returnString + "{"

            'Find the row
            id = lArray(ctr)
            rowRef = -1

            For ctr2 = 0 To rangetoexport.Rows.Count
                If rangetoexport.Cells(ctr2, idColumn) = id Then
                    rowRef = ctr2
                    Exit For
                End If
            Next

            'add the parts
            'add the ID and new object

            returnString = returnString & """company"": {"

            returnString = returnString & """ID"":" & rangetoexport.Cells(rowRef, idColumn) & ","
            returnString = returnString & """Website"":""" & rangetoexport.Cells(rowRef, webColumn) & ""","
            returnString = returnString & """Company Name"":""" & rangetoexport.Cells(rowRef, nameColumn) & ""","
            returnString = returnString & """Revenue"":""" & rangetoexport.Cells(rowRef, revColumn) & ""","
            returnString = returnString & """Employee Count"":" & rangetoexport.Cells(rowRef, empColumn) & ","
            returnString = returnString & """Country"":""" & rangetoexport.Cells(rowRef, ctryColumn) & ""","
            returnString = returnString & """Industry Classification (SIC4)"":""" & rangetoexport.Cells(rowRef, indyColumn) & """}},"

            'returnString = returnString & """factors"": {"

            'For ctr3 = 1 To 10

            'Next

            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","
            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","
            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","
            'returnString = returnString & apost & rangetoexport.Cells(labelRow, 12) & apost & ":" & rangetoexport.Cells(rowRef, 12) & ","

            'returnString = returnString & rangetoexport.Cells(rowRef, webColumn) & "},"

        Next

    Else
        returnString = ""

    End If

returnString = Left(returnString, Len(returnString) - 1)

getData = returnString & "]"


问:
Python - mock imported dictionary
At the top of the code I want to test I have an import like:

```<code>from resources import RESOURCES
</code>```

where RESOURCES is a dictionary of values.

How can I mock it in the test?

What I would like to is, no matter what is in the real module, return a well known dictionary.

For example in one test I want RESOURCES to be:

```<code>{
  'foo': 'bar'
}
</code>```

while in another test I want it to be:

```<code>{
  'something': 'else'
}
</code>```

答:
The way I made it to patch the RESOURCE object is using:

```<code>from default import RESOURCES
from mock import patch

with patch.dict(RESOURCES, {'foo': 'bar'}, clear=True):
    assert(RESOUCES['foo'], 'bar')
</code>```

Note that you'll need to import the dictionary you want to patch in the test suite

It's also possible to use the decorator syntax:

```<code>from default import RESOURCES
from mock import patch

@patch.dict(RESOURCES, {'foo': 'bar'}, clear=True)
def test(self):
    self.assert(RESOUCES['foo'], 'bar')
</code>```

Title: Python - mock imported dictionary

Body:
At the top of the code I want to test I have an import like:

from resources import RESOURCES

where RESOURCES is a dictionary of values.

How can I mock it in the test?

What I would like to is, no matter what is in the real module, return a well known dictionary.

For example in one test I want RESOURCES to be:

{
  'foo': 'bar'
}

while in another test I want it to be:

{
  'something': 'else'
}

Body:
The way I made it to patch the RESOURCE object is using:

from default import RESOURCES
from mock import patch

with patch.dict(RESOURCES, {'foo': 'bar'}, clear=True):
    assert(RESOUCES['foo'], 'bar')

Note that you'll need to import the dictionary you want to patch in the test suite

It's also possible to use the decorator syntax:

from default import RESOURCES
from mock import patch

@patch.dict(RESOURCES, {'foo': 'bar'}, clear=True)
def test(self):
    self.assert(RESOUCES['foo'], 'bar')


Title: String slicing in javascript

Body:
If {value :'$10,000'} is the structure of your data, then,
you could remove the $ sign in this way:

const data = [{value :'$10,000'},{value :'$20,000'},{value :'$30,000'},{value:'$40,000'},{value :'$50,000'},
{value :'$60,000'},{value :'$70,000'},{value :'$80,000'},{value
:'$90,000'},{value :'$100,000'},
{value :'$125,000'},{value :'$150,000'},{value :'$175,000'},{value
:'$200,000'},{value :'$225,000'},
{value :'$250,000'},{value :'$275,000'},{value :'$300,000'},{value
:'$325,000'},{value :'$350,000'},
{value :'$375,000'},{value :'$400,000'},{value :'$425,000'},{value
:'$450,000'},{value :'$475,000'},
{value :'$500,000'},{value :'$525,000'},{value :'$550,000'},{value
:'$575,000'},{value :'$600,000'}];

console.log(
  data.map(i => Object.assign({}, i, {value: i.value.substr(1)}))
)


问:
Minify / Obfuscate PHP Code
I use Haxe to generate PHP code. (This means you write you code in the Haxe language and get a bunch of php files after compiling.) Today a customer told me that he needs a new feature on a old project made with Haxe. He also told me that he altered some small things on the code for his own needs. Now I first have port his changes to my Haxe code and then add the new feature, because otherwise his changes will be overwritten by the next time I compile the project.

To prevent that this happens again I am looking for some kind of program that minifies / obfuscates the PHP code. The goal is to make the code unreadable / uneditable as possible.

The ideal tool would run under Linux and could process whole folders and all it containing files.

Anybody any suggestions?

答:
I have just find minify-service for PHP. It's really looks usefull. They says, that obfuscating will be available soon. I hope this is true :)
http://customhost.com.ua/php-minify/</p>

Title: Minify / Obfuscate PHP Code


问:
BroadcastReceiver for Incoming calls in android doesn't work
I'm trying to develop android app for that can record phone calls. So, in the initial step, I've to see if BroadcastReceiver is getting fired or not.
I've added permissions, receiver tag in AndroidManifest file. I'm testing on OnePlus X. Activity is gets started but BroadcastReceiver doesn't get fired when I get call. What's going wrong here?

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity
        android:name="com.example.myapp.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".PhoneStateReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

</application>

</manifest>
</code>```

PhoneStateReceiver.Java

```<code>package com.example.myapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class PhoneStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        try {
            System.out.println("Receiver start");
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

            if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
                Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();

            }
            if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
                Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
            }
            if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}
</code>```

答:
The permission READ_PHONE_STATE is a dangerous permission, if  you are on a marshmallow device you must request runtime permission else your broadcast receiver will not work neither it will throw an error.

That is the most likely the cause of issue from your code because you have correctly registered in the Intent filter other than that there is nothing wrong as it is just a broadcast receiver and should work, i.e get called by the Android system.

Body:
I'm trying to develop android app for that can record phone calls. So, in the initial step, I've to see if BroadcastReceiver is getting fired or not.
I've added permissions, receiver tag in AndroidManifest file. I'm testing on OnePlus X. Activity is gets started but BroadcastReceiver doesn't get fired when I get call. What's going wrong here?

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity
        android:name="com.example.myapp.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <receiver android:name=".PhoneStateReceiver">
        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
    </receiver>

</application>

</manifest>

PhoneStateReceiver.Java

package com.example.myapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class PhoneStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        try {
            System.out.println("Receiver start");
            String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
            String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

            if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
                Toast.makeText(context,"Incoming Call State",Toast.LENGTH_SHORT).show();
                Toast.makeText(context,"Ringing State Number is -"+incomingNumber,Toast.LENGTH_SHORT).show();

            }
            if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
                Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
            }
            if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
                Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}


问:
html/template: optional outer element around sub-template if it's not empty
I have a template with an inner content template and I want to render it in a way that there is an outer wrapping element around inner content which is only shown if the content is not empty.

For example:

```<code>...
{{if template-content-exists-and-not-blank}}
  <div class="content">
   {{template "content" .}}
  </div>
{{end}}
...
</code>```

I want to render
 only when the result of {{template "content" .}} is not empty. I don't want to put the enclosing
 into content, as it doesn't really belong there, and it will be duplicated across all content sub-templates.

I cannot use {{template ...}} as a function argument, so it's not possible to test it.

I wrote a custom defined boolean function that tests if a sub-template is defined, but the content template is executed regardless of whether it's true or false (no short-circuiting), and obviously fails if it's not defined.

```<code>t.Funcs(
    html.FuncMap{
        "defined": func(name string) bool {
            return t.Lookup(name) != nil
        },
    },
)
</code>```

答:
You would need to do one of two things:

Put the containing tag in the sub-template

Pre-render the sub-template and pass it to the outer template as a string

Body:
I have a template with an inner content template and I want to render it in a way that there is an outer wrapping element around inner content which is only shown if the content is not empty.

For example:

...
{{if template-content-exists-and-not-blank}}

   {{template "content" .}}

{{end}}
...

I want to render
 only when the result of {{template "content" .}} is not empty. I don't want to put the enclosing
 into content, as it doesn't really belong there, and it will be duplicated across all content sub-templates.

I cannot use {{template ...}} as a function argument, so it's not possible to test it.

I wrote a custom defined boolean function that tests if a sub-template is defined, but the content template is executed regardless of whether it's true or false (no short-circuiting), and obviously fails if it's not defined.

t.Funcs(
    html.FuncMap{
        "defined": func(name string) bool {
            return t.Lookup(name) != nil
        },
    },
)


问:
Max of all columns based on distinct first column
How do I change the code if I have more than two columns. Let's say the data is like this

```<code>ifile.dat
1   10  15
3   34  20
1   4   22
3   32  33
5   3   46
2   2   98
4   20  100
3   13  23
4   50  65
1   40  76
2   20  22
</code>```

How do I achieve this?

```<code>ofile.dat
1   40  76
2   20  98
3   34  33
4   50  100
5   3   46
</code>```

I mean the max of each column by comparing first column. Thanks.

Here is what I have tried(on a sample file with 13columns). But the highest value is not coming up this way.

```<code>cat input.txt | sort -k1,1 -k2,2nr -k3,3nr -k4,4nr -k5,5nr -k6,6nr -k7,7nr -k8,8nr -k9,9nr -k10,10nr -nrk11,11 -nrk12,12 -nrk13,13 | sort -k1,1 -u
</code>```

答:
Instead of relying on sort, you could switch over to something more robust like awk:

```<code> awk 'BEGIN{PROCINFO["sorted_in"] = "@val_num_asc"} {for(i=2;i<=NF;++i) if (a[$1][i]<$i){a[$1][i]=$i}} END{n=asorti(a, asorted); for(col1 in asorted){print col1, a[col1][2], a[col1][3]}}' input.txt
</code>```

That's a mouthful. It breaks down like:

Before processing the file set the PROCINFO setting of sorted_in to @val_num_asc since we will be sorting the contents of an array by its index which will be numeric: (BEGIN{PROCINFO["sorted_in"] = "@val_num_asc"})

Loop through each field in the record for(i=2;i<=NF;++i)

Test to see if the current value is greater than the stored value in the array which has as its index the first field's value. If it is greater, then store it in place of whatever is currently held in the array for that index at that fields position: (if (a[$1][i]<$i){a[$1][i]=$i})

When done processing all of the records, sort the array into new array asorted: (END{n=asorti(a, asorted);)

Iterate through the array and print each element (for(col1 in asorted){print col1, a[col1][2], a[col1][3]})

There may be a more elegant way to do this in awk, but this will do the trick.

Example:

```<code>:~$ cat test
1   10  15
3   34  20
1   4   22
3   32  33
5   3   46
2   2   98
4   20  100
3   13  23
4   50  65
1   40  76
2   20  22
:~$ awk 'BEGIN{PROCINFO["sorted_in"] = "@val_num_asc"} {for(i=2;i<=NF;++i) if (a[$1][i]<$i){a[$1][i]=$i}} END{n=asorti(a, asorted); for(col1 in asorted){print col1, a[col1][2], a[col1][3]}}' test
1 40 76
2 20 98
3 34 33
4 50 100
5 3 46
</code>```

Body:
How do I change the code if I have more than two columns. Let's say the data is like this

ifile.dat
1   10  15
3   34  20
1   4   22
3   32  33
5   3   46
2   2   98
4   20  100
3   13  23
4   50  65
1   40  76
2   20  22

How do I achieve this?

ofile.dat
1   40  76
2   20  98
3   34  33
4   50  100
5   3   46

I mean the max of each column by comparing first column. Thanks.

Here is what I have tried(on a sample file with 13columns). But the highest value is not coming up this way.

cat input.txt | sort -k1,1 -k2,2nr -k3,3nr -k4,4nr -k5,5nr -k6,6nr -k7,7nr -k8,8nr -k9,9nr -k10,10nr -nrk11,11 -nrk12,12 -nrk13,13 | sort -k1,1 -u

Body:
Instead of relying on sort, you could switch over to something more robust like awk:

 awk 'BEGIN{PROCINFO["sorted_in"] = "@val_num_asc"} {for(i=2;i<=NF;++i) if (a[$1][i]<$i){a[$1][i]=$i}} END{n=asorti(a, asorted); for(col1 in asorted){print col1, a[col1][2], a[col1][3]}}' input.txt

That's a mouthful. It breaks down like:

Before processing the file set the PROCINFO setting of sorted_in to @val_num_asc since we will be sorting the contents of an array by its index which will be numeric: (BEGIN{PROCINFO["sorted_in"] = "@val_num_asc"})

Loop through each field in the record for(i=2;i<=NF;++i)

Test to see if the current value is greater than the stored value in the array which has as its index the first field's value. If it is greater, then store it in place of whatever is currently held in the array for that index at that fields position: (if (a[$1][i]<$i){a[$1][i]=$i})

When done processing all of the records, sort the array into new array asorted: (END{n=asorti(a, asorted);)

Iterate through the array and print each element (for(col1 in asorted){print col1, a[col1][2], a[col1][3]})

There may be a more elegant way to do this in awk, but this will do the trick.

Example:

:~$ cat test
1   10  15
3   34  20
1   4   22
3   32  33
5   3   46
2   2   98
4   20  100
3   13  23
4   50  65
1   40  76
2   20  22
:~$ awk 'BEGIN{PROCINFO["sorted_in"] = "@val_num_asc"} {for(i=2;i<=NF;++i) if (a[$1][i]<$i){a[$1][i]=$i}} END{n=asorti(a, asorted); for(col1 in asorted){print col1, a[col1][2], a[col1][3]}}' test
1 40 76
2 20 98
3 34 33
4 50 100
5 3 46


问:
Invoke a ContextMenu to open
I need to do something like Google Maps does (but in WPF):

when RightClick on the map I have a ContextMenu.

when RightDoubleClicking I have the UnZoom action.

So, apparently, this is a little difficult in WPF...
After struggling and searching a lot, read people that compains that "we can't predict the future" (I ask myself how does Google predict it), I decided to "wait" SystemInformation.DoubleClickTime and only then display a contextMenu.

Surely, this is not ideal, even human-observable, but I don't know other method.

So, the problem that I have with the following code is (I have a custom Canvas):

```<code>ContextMenuEventArgs lastContextMenuEventArgs = null;
bool? lastContextMenuEventArgsHandled = null;

protected override void OnContextMenuOpening(ContextMenuEventArgs e)
{
    lastContextMenuEventArgs = e;
    lastContextMenuEventArgsHandled = e.Handled;

    e.Handled = true;
    //base.OnContextMenuOpening(e);
}

bool rightMouseClickedOnce = false;
protected override void OnPreviewMouseRightButtonUp(MouseButtonEventArgs e)
{
    //base.OnPreviewMouseRightButtonUp(e);

    Console.WriteLine(">>>>>>>>>>> OnPreviewMouseRightButtonUp");
    if (!rightMouseClickedOnce)
    {
        rightMouseClickedOnce = true;
        Thread thread = new Thread(
            new System.Threading.ThreadStart(
                delegate()
                {
                    Thread.Sleep(System.Windows.Forms.SystemInformation.DoubleClickTime);
                    this.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Background,
                        new Action(
                            delegate()
                            {
                                if (rightMouseClickedOnce)
                                {
                                    Console.WriteLine(">>>>>>>>>>> Right Click");
                                    rightMouseClickedOnce = false;
                                    base.OnPreviewMouseRightButtonUp(e);

                                    if (lastContextMenuEventArgsHandled.HasValue)
                                    {
                                        Console.WriteLine(">>>>>>>>>>> lastContextMenuEventArgsHandled");
                                        lastContextMenuEventArgs.Handled = lastContextMenuEventArgsHandled.Value;
                                        base.OnContextMenuOpening(lastContextMenuEventArgs);
                                        lastContextMenuEventArgsHandled = null;
                                    }
                                    //if (this.ContextMenu != null)
                                    //{
                                    //  this.ContextMenu.PlacementTarget = this;
                                    //  this.ContextMenu.IsOpen = true;
                                    //}
                                }
                            }
                    ));
                }
        ));
        thread.Start();
    }
    else if (rightMouseClickedOnce)
    {
        Console.WriteLine(">>>>>>>>>>> Right Double Click");
        rightMouseClickedOnce = false;
        base.OnPreviewMouseRightButtonUp(e);
        this.OnMouseRightDoubleClick(e);
    }

}
</code>```

Everything works great but a little problem: base.OnContextMenuOpening(lastContextMenuEventArgs); does not seem to work...

I set before

```<code>if (this.ContextMenu != null)
{
  this.ContextMenu.PlacementTarget = this;
  this.ContextMenu.IsOpen = true;
}
</code>```

and that worked, but finally this blocks child contextMenu elements from opening, and open always the parent (canvas) contextMenu.

Can I just invoke the contextMenu event?

答:
I don't know much about WPF, but can you show the menu, say, a pixel away from the cursor and see if the user right-clicks again in the same spot and in the system double click time? I've used a similar technique once in a game and it performed nice enough.

A menu "fade in" (optionally, out, too) animation could make it even better.

Title: Invoke a ContextMenu to open

Body:
I need to do something like Google Maps does (but in WPF):

when RightClick on the map I have a ContextMenu.

when RightDoubleClicking I have the UnZoom action.

So, apparently, this is a little difficult in WPF...
After struggling and searching a lot, read people that compains that "we can't predict the future" (I ask myself how does Google predict it), I decided to "wait" SystemInformation.DoubleClickTime and only then display a contextMenu.

Surely, this is not ideal, even human-observable, but I don't know other method.

So, the problem that I have with the following code is (I have a custom Canvas):

ContextMenuEventArgs lastContextMenuEventArgs = null;
bool? lastContextMenuEventArgsHandled = null;

protected override void OnContextMenuOpening(ContextMenuEventArgs e)
{
    lastContextMenuEventArgs = e;
    lastContextMenuEventArgsHandled = e.Handled;

    e.Handled = true;
    //base.OnContextMenuOpening(e);
}

bool rightMouseClickedOnce = false;
protected override void OnPreviewMouseRightButtonUp(MouseButtonEventArgs e)
{
    //base.OnPreviewMouseRightButtonUp(e);

    Console.WriteLine(">>>>>>>>>>> OnPreviewMouseRightButtonUp");
    if (!rightMouseClickedOnce)
    {
        rightMouseClickedOnce = true;
        Thread thread = new Thread(
            new System.Threading.ThreadStart(
                delegate()
                {
                    Thread.Sleep(System.Windows.Forms.SystemInformation.DoubleClickTime);
                    this.Dispatcher.Invoke(
                        System.Windows.Threading.DispatcherPriority.Background,
                        new Action(
                            delegate()
                            {
                                if (rightMouseClickedOnce)
                                {
                                    Console.WriteLine(">>>>>>>>>>> Right Click");
                                    rightMouseClickedOnce = false;
                                    base.OnPreviewMouseRightButtonUp(e);

                                    if (lastContextMenuEventArgsHandled.HasValue)
                                    {
                                        Console.WriteLine(">>>>>>>>>>> lastContextMenuEventArgsHandled");
                                        lastContextMenuEventArgs.Handled = lastContextMenuEventArgsHandled.Value;
                                        base.OnContextMenuOpening(lastContextMenuEventArgs);
                                        lastContextMenuEventArgsHandled = null;
                                    }
                                    //if (this.ContextMenu != null)
                                    //{
                                    //  this.ContextMenu.PlacementTarget = this;
                                    //  this.ContextMenu.IsOpen = true;
                                    //}
                                }
                            }
                    ));
                }
        ));
        thread.Start();
    }
    else if (rightMouseClickedOnce)
    {
        Console.WriteLine(">>>>>>>>>>> Right Double Click");
        rightMouseClickedOnce = false;
        base.OnPreviewMouseRightButtonUp(e);
        this.OnMouseRightDoubleClick(e);
    }

}

Everything works great but a little problem: base.OnContextMenuOpening(lastContextMenuEventArgs); does not seem to work...

I set before

if (this.ContextMenu != null)
{
  this.ContextMenu.PlacementTarget = this;
  this.ContextMenu.IsOpen = true;
}

and that worked, but finally this blocks child contextMenu elements from opening, and open always the parent (canvas) contextMenu.

Can I just invoke the contextMenu event?


问:
SpyOn $ Jquery with Jasmine not working
I am trying to Mock a Jquery selector with Jasmine SpyOn

```<code>describe('initialising the navigation bar', ()=> {
it('should do something', () => {

  spyOn(window, '$').and.returnValue("bar");
  expect(utilityNavigation.test()).toBe('bar');

});
</code>```

});

The code is as follows:

```<code>utilityNavigation = {
  test() {
    let foo = $('.utility-navigation');
    return foo;
  }
}
</code>```

Simple stuff. When I debug the code in the Karma debugger and execute the $('.utility-navigation') in the console I get bar as expected from the spy. But the test result gives me a empty JQuery object not the return value from the spy.

答:
Use of window.$ should work just fine from a plain jasmine-javascript-jquery perspective

I suspect the reason for empty div is may be the html element is not available on the page yet

Can you try with an async callback beforeEach so that the div is loaded up just in case

Here is how I tried async div load up test using just jQuery and jasmine and it works fine

```<code>utilityNavigation = {
  test: function() {
    let foo = $('.utility-navigation');
    return foo;
  }
}

describe('initialising the navigation bar', () => {
  beforeEach(function(done) {
    setTimeout(function() {
      console.log("waiting to ensure the div is loaded up on the page");
      done();
    }, 1);
  });
  it('should do something', () => {
    //pre
    console.log(utilityNavigation.test().data('test'));
    var spy = spyOn(window, '$').and.returnValue("bar");
    //post
    console.log($('.utility-navigation'));
    expect(utilityNavigation.test()).toBe('bar');
  });
});
</code>```

Title: SpyOn $ Jquery with Jasmine not working

Body:
I am trying to Mock a Jquery selector with Jasmine SpyOn

describe('initialising the navigation bar', ()=> {
it('should do something', () => {

  spyOn(window, '$').and.returnValue("bar");
  expect(utilityNavigation.test()).toBe('bar');

});

});

The code is as follows:

utilityNavigation = {
  test() {
    let foo = $('.utility-navigation');
    return foo;
  }
}

Simple stuff. When I debug the code in the Karma debugger and execute the $('.utility-navigation') in the console I get bar as expected from the spy. But the test result gives me a empty JQuery object not the return value from the spy.

Body:
Use of window.$ should work just fine from a plain jasmine-javascript-jquery perspective

I suspect the reason for empty div is may be the html element is not available on the page yet

Can you try with an async callback beforeEach so that the div is loaded up just in case

Here is how I tried async div load up test using just jQuery and jasmine and it works fine

<div class='utility-navigation' data-test="testString"></div>

utilityNavigation = {
  test: function() {
    let foo = $('.utility-navigation');
    return foo;
  }
}

describe('initialising the navigation bar', () => {
  beforeEach(function(done) {
    setTimeout(function() {
      console.log("waiting to ensure the div is loaded up on the page");
      done();
    }, 1);
  });
  it('should do something', () => {
    //pre
    console.log(utilityNavigation.test().data('test'));
    var spy = spyOn(window, '$').and.returnValue("bar");
    //post
    console.log($('.utility-navigation'));
    expect(utilityNavigation.test()).toBe('bar');
  });
});


问:
python myhdl package how to generate verilog initial block
From the code mostly from the sample of myhdl:

```<code>from myhdl import Signal, intbv, delay, always, now, Simulation, toVerilog

__debug = True

def ClkDriver(clk):
    halfPeriod = delay(10)
    @always(halfPeriod)
    def driveClk():
        clk.next = not clk
    return driveClk

def HelloWorld(clk, outs):

    counts = intbv(3)[32:]

    @always(clk.posedge)
    def sayHello():
        outs.next = not outs
        if counts >= 3 - 1:
            counts.next = 0
        else:
            counts.next = counts + 1
        if __debug__:
            print "%s Hello World! outs %s %s" % (
              now(), str(outs), str(outs.next))

    return sayHello

clk = Signal(bool(0))
outs = Signal(intbv(0)[1:])
clkdriver_inst = ClkDriver(clk)
hello_inst = toVerilog(HelloWorld, clk, outs)
sim = Simulation(clkdriver_inst, hello_inst)
sim.run(150)
</code>```

I expect it to generate a verilog program that contains an initial block, like something:

```<code>module HelloWorld(...)
reg [31:0] counts;
initial begin
    counts = 32'h3
end
always @(...
</code>```

How can you get the initial block generated?

Note that on the google cache for old.myhdl.org/doku.php/dev:initial_values it links to example https://bitbucket.org/cfelton/examples/src/tip/ramrom/ . So it looks the feature should be supported. However the rom sample generates static case statements. That's not what I'm looking for.

答:
Three steps to resolve it:

Update to the latest myhdl on master or a version that contains the hash 87784ad which added the feature under issue #105 or #150. As an example for virtualenv, run a git clone, followed by pip install -e <path-to-myhdl-dir>.

Change the signal to a list.

Set toVerilog.initial_values=True before calling toVerilog.

Code snippet follows.

```<code>def HelloWorld(clk, outs):

    counts = [Signal(intbv(3)[32:])]

    @always(clk.posedge)
    def sayHello():
        outs.next = not outs
        if counts[0] >= 3 - 1:
            counts[0].next = 0
        else:
            counts[0].next = counts[0] + 1
        if __debug__:
            print "%s Hello World! outs %s %s %d" % (
                  now(), str(outs), str(outs.next), counts[0])
    return sayHello

clk = Signal(bool(0))
outs = Signal(intbv(0)[1:])
clkdriver_inst = ClkDriver(clk)
toVerilog.initial_values=True
hello_inst = toVerilog(HelloWorld, clk, outs)
sim = Simulation(clkdriver_inst, hello_inst)
sim.run(150)
</code>```

Body:
From the code mostly from the sample of myhdl:

from myhdl import Signal, intbv, delay, always, now, Simulation, toVerilog

__debug = True

def ClkDriver(clk):
    halfPeriod = delay(10)
    @always(halfPeriod)
    def driveClk():
        clk.next = not clk
    return driveClk

def HelloWorld(clk, outs):

    counts = intbv(3)[32:]

    @always(clk.posedge)
    def sayHello():
        outs.next = not outs
        if counts >= 3 - 1:
            counts.next = 0
        else:
            counts.next = counts + 1
        if __debug__:
            print "%s Hello World! outs %s %s" % (
              now(), str(outs), str(outs.next))

    return sayHello

clk = Signal(bool(0))
outs = Signal(intbv(0)[1:])
clkdriver_inst = ClkDriver(clk)
hello_inst = toVerilog(HelloWorld, clk, outs)
sim = Simulation(clkdriver_inst, hello_inst)
sim.run(150)

I expect it to generate a verilog program that contains an initial block, like something:

module HelloWorld(...)
reg [31:0] counts;
initial begin
    counts = 32'h3
end
always @(...

How can you get the initial block generated?

Note that on the google cache for old.myhdl.org/doku.php/dev:initial_values it links to example https://bitbucket.org/cfelton/examples/src/tip/ramrom/ . So it looks the feature should be supported. However the rom sample generates static case statements. That's not what I'm looking for.

Body:
Three steps to resolve it:

Update to the latest myhdl on master or a version that contains the hash 87784ad which added the feature under issue #105 or #150. As an example for virtualenv, run a git clone, followed by pip install -e <path-to-myhdl-dir>.

Change the signal to a list.

Set toVerilog.initial_values=True before calling toVerilog.

Code snippet follows.

def HelloWorld(clk, outs):

    counts = [Signal(intbv(3)[32:])]

    @always(clk.posedge)
    def sayHello():
        outs.next = not outs
        if counts[0] >= 3 - 1:
            counts[0].next = 0
        else:
            counts[0].next = counts[0] + 1
        if __debug__:
            print "%s Hello World! outs %s %s %d" % (
                  now(), str(outs), str(outs.next), counts[0])
    return sayHello

clk = Signal(bool(0))
outs = Signal(intbv(0)[1:])
clkdriver_inst = ClkDriver(clk)
toVerilog.initial_values=True
hello_inst = toVerilog(HelloWorld, clk, outs)
sim = Simulation(clkdriver_inst, hello_inst)
sim.run(150)


问:
Multiple Updates in MySQL
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

Edit:
For example I have the following

```<code>Name   id  Col1  Col2
Row1   1    6     1
Row2   2    2     3
Row3   3    9     5
Row4   4    16    8
</code>```

I want to combine all the following Updates into one query

```<code>UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;
</code>```

答:
Why does no one mention multiple statements in one query?

In php, you use multi_query method of mysqli instance.

From the php manual

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found here which is based on answer from @Dakusan

Transaction: 5.5194580554962

Insert: 0.20669293403625

Case: 16.474853992462

Multi: 0.0412278175354

As you can see, multiple statements query is more efficient than the highest answer.

If you get error message like this:

```<code>PHP Warning:  Error while sending SET_OPTION packet
</code>```

You may need to increase the max_allowed_packet in mysql config file which in my machine is /etc/mysql/my.cnf and then restart mysqld.

Title: Multiple Updates in MySQL

Body:
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

Edit:
For example I have the following

Name   id  Col1  Col2
Row1   1    6     1
Row2   2    2     3
Row3   3    9     5
Row4   4    16    8

I want to combine all the following Updates into one query

UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;

LastEditorDisplayName: Teifion

Body:
Why does no one mention multiple statements in one query?

In php, you use multi_query method of mysqli instance.

From the php manual

MySQL optionally allows having multiple statements in one statement string. Sending multiple statements at once reduces client-server round trips but requires special handling.

Here is the result comparing to other 3 methods in update 30,000 raw. Code can be found here which is based on answer from @Dakusan

Transaction: 5.5194580554962

Insert: 0.20669293403625

Case: 16.474853992462

Multi: 0.0412278175354

As you can see, multiple statements query is more efficient than the highest answer.

If you get error message like this:

PHP Warning:  Error while sending SET_OPTION packet

You may need to increase the max_allowed_packet in mysql config file which in my machine is /etc/mysql/my.cnf and then restart mysqld.


问:
Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
I am using google maps in Xcode 9 beta, iOS 11.

I am getting an error outputted to the log as follows:

Main Thread Checker: UI API called on a background thread: -[UIApplication applicationState]
  PID: 4442, TID: 837820, Thread name: com.google.Maps.LabelingBehavior, Queue name: com.apple.root.default-qos.overcommit, QoS: 21

Why would this be occurring as I am almost certain I'm not altering any interface elements from the main thread in my code.

 override func viewDidLoad() {

    let locationManager = CLLocationManager()

    locationManager.requestAlwaysAuthorization()

    locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {

            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()
        }

      viewMap.delegate = self

     let camera = GMSCameraPosition.camera(withLatitude: 53.7931183329367, longitude: -1.53649874031544, zoom: 17.0)

        viewMap.animate(to: camera)

    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }

    func mapView(_ mapView: GMSMapView, willMove gesture: Bool) {

    }

    func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) {

        if(moving > 1){
            moving = 1
        UIView.animate(withDuration: 0.5, delay: 0, animations: {

            self.topBarConstraint.constant = self.topBarConstraint.constant + (self.topBar.bounds.height / 2)

            self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant + (self.topBar.bounds.height / 2)

            self.view.layoutIfNeeded()
        }, completion: nil)
    }
         moving = 1
    }

    // Camera change Position this methods will call every time
    func mapView(_ mapView: GMSMapView, didChange position: GMSCameraPosition) {
        moving = moving + 1
        if(moving == 2){

            UIView.animate(withDuration: 0.5, delay: 0, animations: {

                self.topBarConstraint.constant = self.topBarConstraint.constant - (self.topBar.bounds.height / 2)

                self.bottomHalfConstraint.constant = self.bottomHalfConstraint.constant - (self.topBar.bounds.height / 2)

                self.view.layoutIfNeeded()
            }, completion: nil)
        }
        DispatchQueue.main.async {

            print("Moving: \(moving) Latitude: \(self.viewMap.camera.target.latitude)")
            print("Moving: \(moving)  Longitude: \(self.viewMap.camera.target.longitude)")
        }
    }
```

答: Wrap the lines of code that modify the UI in DispatchQueue.main.async {} in order to make sure they execute on the main thread. Otherwise, you may be calling them from a background thread, where UI modifications are not allowed. All such lines of code must be executed from the main thread.

ContentLicense: CC BY-SA 4.0


问:
Select String Based on Iteration
I've been trying to practice my Javascript using CodeWars and I'm still in the beginner phase of learning. I've gotten stuck on this one question and I am hoping someone can explain to me in the most simplest way how to iterate (I believe that's what it's called) through numerous strings based on a number input.

Here is the question:

You pick a petal off a flower saying each of the following phrases
  each time a petal was torn:

I love you

a little

a lot

passionately

madly

not at all

Your goal in this kata is to determine which phrase you would say for
  a flower of a given number of petals, where nb_petals > 0.

So far I have this:

```<code>function howMuchILoveYou(nbPetals) {

var petalSaying = ["I love you", "A little", "A lot", "Passionately",
"Madly", "Not at all"];

for(var petals = 0; nbPetals > 0; nbPetals--);
}
</code>```

And I'm not sure where to go after this to get it to print out the string necessary based on the number input for nbPetals.

Also, if the number input is 7 for example, it would output I love you.

Thanks in advance for any help.

答:
You don't need to do iteration, just access the given array element by index. If the number is more than the number of elements, use modulus to wrap around.

```<code>function howMuchILoveYou(nbPetals) {
    var petalSaying = ["I love you", "A little", "A lot", "Passionately", "Madly", "Not at all"];
    var index = (nbPetals - 1) % petalSaying.length;
    return petalSaying[index];
}
</code>```

nbPetals - 1 adjusts for the fact that array indexes start at 0, but nbPetals starts at 1.

Title: Select String Based on Iteration

Body:
I've been trying to practice my Javascript using CodeWars and I'm still in the beginner phase of learning. I've gotten stuck on this one question and I am hoping someone can explain to me in the most simplest way how to iterate (I believe that's what it's called) through numerous strings based on a number input.

Here is the question:

You pick a petal off a flower saying each of the following phrases
  each time a petal was torn:

I love you

a little

a lot

passionately

madly

not at all

Your goal in this kata is to determine which phrase you would say for
  a flower of a given number of petals, where nb_petals > 0.

So far I have this:

function howMuchILoveYou(nbPetals) {

var petalSaying = ["I love you", "A little", "A lot", "Passionately",
"Madly", "Not at all"];

for(var petals = 0; nbPetals > 0; nbPetals--);
}

And I'm not sure where to go after this to get it to print out the string necessary based on the number input for nbPetals.

Also, if the number input is 7 for example, it would output I love you.

Thanks in advance for any help.

Body:
You don't need to do iteration, just access the given array element by index. If the number is more than the number of elements, use modulus to wrap around.

function howMuchILoveYou(nbPetals) {
    var petalSaying = ["I love you", "A little", "A lot", "Passionately", "Madly", "Not at all"];
    var index = (nbPetals - 1) % petalSaying.length;
    return petalSaying[index];
}

nbPetals - 1 adjusts for the fact that array indexes start at 0, but nbPetals starts at 1.


问:
Generated recursive object based on array
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

```<code>{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}
</code>```

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?

答:
```<code>let arr = ['one', 'two', 'three'], obj = {};

obj['path'] = arr[arr.length - 1];
for(let i = arr.length - 2; i >= 0; i--) {
  obj = {
    path: arr[i],
    nested: obj
  };
}
console.log(obj);
</code>```

Body:
I have an array, which is a list of keys: ['one', 'two', 'three'].

I need to generate an object, of the following format:

{
  path: 'one',
  nested: {
    path: 'two',
    nested: {
      path: 'three'
    }
  }
}

So far I've tried a couple of approaches, but they seem quite messy (I have one method which uses while(current = array.pop()) but it requires several conditionals to handle the first and last elements.

Is there a neater recursive strategy?


问:
case_when in mutate pipe
It seems dplyr::case_when doesn't behave as other commands in a dplyr::mutate call. For instance:

```<code>library(dplyr)

case_when(mtcars$carb <= 2 ~ "low",
          mtcars$carb > 2 ~ "high") %>%
  table
</code>```

works:

```<code>.
high  low
  15   17
</code>```

But put case_when in a mutate chain:

```<code>mtcars %>%
  mutate(cg = case_when(carb <= 2 ~ "low",
                        carb > 2 ~ "high"))
</code>```

and you get:

```<code> Error: object 'carb' not found
</code>```

while this works fine

```<code>mtcars %>%
  mutate(cg = carb %>%
           cut(c(0, 2, 8)))
</code>```

答:
As of version 0.7.0 of dplyr, case_when works within mutate as follows:

```<code>library(dplyr) # >= 0.7.0
mtcars %>%
  mutate(cg = case_when(carb <= 2 ~ "low",
                        carb > 2  ~ "high"))
</code>```

For more information: http://dplyr.tidyverse.org/reference/case_when.html

Title: case_when in mutate pipe

Body:
It seems dplyr::case_when doesn't behave as other commands in a dplyr::mutate call. For instance:

library(dplyr)

case_when(mtcars$carb <= 2 ~ "low",
          mtcars$carb > 2 ~ "high") %>%
  table

works:

.
high  low
  15   17

But put case_when in a mutate chain:

mtcars %>%
  mutate(cg = case_when(carb <= 2 ~ "low",
                        carb > 2 ~ "high"))

and you get:

 Error: object 'carb' not found

while this works fine

mtcars %>%
  mutate(cg = carb %>%
           cut(c(0, 2, 8)))

Body:
As of version 0.7.0 of dplyr, case_when works within mutate as follows:

library(dplyr) # >= 0.7.0
mtcars %>%
  mutate(cg = case_when(carb <= 2 ~ "low",
                        carb > 2  ~ "high"))

For more information: http://dplyr.tidyverse.org/reference/case_when.html


问:
jQuery disable/re-enable validators on a page
When I need to disable/re-enable validator I usually use jQuery code like so:

```<code>      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], false);
</code>```

and to re-enable it back:

```<code>      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            var validator = $('[id*=DueDateRequiredValidator]')[0];
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);
</code>```

And it works. But now I need to disable/re-enable a large number of validators, but only a subset of validators, not entire set on a page. There's too many of them to refer each validator by "id".

I tried something like this but it didn't work, don't know why:

```<code>      $.each(Page_Validators, function(index, validator) {
                if ( validator.CssClass == "noinjuries" )

                { ValidatorEnable(validator, false); }

      });
</code>```

What's the best way to do this, if any?

答:
I found the following javascript code on a blog, it uses a ValidationGroup to toggle Validation controls, but you could just as easily remove the if (Page_Validators[i].validationGroup == validationGroupName) line and toggle the whole collection of Validators.

You will have to add your own enabling code after the 'ValidatorEnable' method call.

```<code>function HasPageValidators() {
    var hasValidators = false;

    try {
        if (Page_Validators.length > 0) {
            hasValidators = true;
        }
    }
    catch (error) {
    }

    return hasValidators;
}

function ValidationGroupEnable(validationGroupName, isEnable) {
    if (HasPageValidators()) {
        for (i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i].validationGroup == validationGroupName) {
                ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            }
        }
    }
}
</code>```

Edit: Victor, based on your comment, I think you could get the same results by adding Attributes to your controls. This would group them without using the ValidationGroups, and you can access the attributes from JavaScript.

In your code behind, you need to set the attributes for your Validation controls like so:

```<code>SampleValidator1.Attributes.Add("myGroupName", "sample1");
SampleValidator2.Attributes.Add("myGroupName", "sample2");
</code>```

Then, in the Javascript function, rather than this line `if (Page_Validators[i].validationGroup == validationGroupName) {', use this:

```<code>if (Page_Validators[i].getAttribute('myClass') == 'sample1') {
</code>```

That should get you what you want without Groups, but sorry - you will have to set the Attribute

One Last Edit: I was making this harder than it needs to be. I haven't tried it, but if you want to get the CSS class of an object in JavaScript it is .className, not .class. Try that before any of my earlier suggestions.

Body:
When I need to disable/re-enable validator I usually use jQuery code like so:

      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], false);

and to re-enable it back:

      ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            var validator = $('[id*=DueDateRequiredValidator]')[0];
            validator.isvalid = true;
            ValidatorUpdateDisplay(validator);

And it works. But now I need to disable/re-enable a large number of validators, but only a subset of validators, not entire set on a page. There's too many of them to refer each validator by "id".

I tried something like this but it didn't work, don't know why:

      $.each(Page_Validators, function(index, validator) {
                if ( validator.CssClass == "noinjuries" )

                { ValidatorEnable(validator, false); }

      });

What's the best way to do this, if any?

Body:
I found the following javascript code on a blog, it uses a ValidationGroup to toggle Validation controls, but you could just as easily remove the if (Page_Validators[i].validationGroup == validationGroupName) line and toggle the whole collection of Validators.

You will have to add your own enabling code after the 'ValidatorEnable' method call.

function HasPageValidators() {
    var hasValidators = false;

    try {
        if (Page_Validators.length > 0) {
            hasValidators = true;
        }
    }
    catch (error) {
    }

    return hasValidators;
}

function ValidationGroupEnable(validationGroupName, isEnable) {
    if (HasPageValidators()) {
        for (i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i].validationGroup == validationGroupName) {
                ValidatorEnable($('[id*=DueDateRequiredValidator]')[0], true);
            }
        }
    }
}

Edit: Victor, based on your comment, I think you could get the same results by adding Attributes to your controls. This would group them without using the ValidationGroups, and you can access the attributes from JavaScript.

In your code behind, you need to set the attributes for your Validation controls like so:

SampleValidator1.Attributes.Add("myGroupName", "sample1");
SampleValidator2.Attributes.Add("myGroupName", "sample2");

Then, in the Javascript function, rather than this line `if (Page_Validators[i].validationGroup == validationGroupName) {', use this:

if (Page_Validators[i].getAttribute('myClass') == 'sample1') {

That should get you what you want without Groups, but sorry - you will have to set the Attribute

One Last Edit: I was making this harder than it needs to be. I haven't tried it, but if you want to get the CSS class of an object in JavaScript it is .className, not .class. Try that before any of my earlier suggestions.


问:
Powershell test if folder empty
In Powershell, how do I test if a directory is empty?</p>

答:
Example of removing empty folder:</p>

```<code>IF ((Get-ChildItem "$env:SystemDrive\test" | Measure-Object).Count -eq 0) {
    remove-Item "$env:SystemDrive\test" -force
}
</code>```

Title: Powershell test if folder empty

Body:
Example of removing empty folder:

IF ((Get-ChildItem "$env:SystemDrive\test" | Measure-Object).Count -eq 0) {
    remove-Item "$env:SystemDrive\test" -force
}