问:
Unexpected output when multiple threads update same variable
```<code>#include<stdio.h>
#include<pthread.h>
#define NUM_THREAD (5)

int sum=0;
void* runner(void * param);

int main(int argc,char **argv){

    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for(i=0;i<NUM_THREAD;i++){
    pthread_create(&tid[i],&attr,runner,NULL);
    }
    for(i=0;i<NUM_THREAD;i++){
    pthread_join(tid[i],NULL);
            }
    printf("After threading %d",sum);
    return 0;
}

void * runner(void *param){
    for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}
</code>```

output: 225

In the following code, the output is 225. But the correct should be 45

I know threads share global variables!. so this function should correctly output right. But adding that sum=0 inside only gives correct output.  Whats happening here I don't understand!

```<code>void * runner(void *param){
sum=0;   // MY DOUBT
for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}
</code>```

output: 45

答:
You are modifying one global object from 5 threads. One thread increases value of sum by 45, so when you multiply it by 5 you have 225.

Another issue here is that you modify one variable from each thread which may end up in some mess caused by races.

Body:
#include<stdio.h>
#include<pthread.h>
#define NUM_THREAD (5)

int sum=0;
void* runner(void * param);

int main(int argc,char **argv){

    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for(i=0;i<NUM_THREAD;i++){
    pthread_create(&tid[i],&attr,runner,NULL);
    }
    for(i=0;i<NUM_THREAD;i++){
    pthread_join(tid[i],NULL);
            }
    printf("After threading %d",sum);
    return 0;
}

void * runner(void *param){
    for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}

output: 225

In the following code, the output is 225. But the correct should be 45

I know threads share global variables!. so this function should correctly output right. But adding that sum=0 inside only gives correct output.  Whats happening here I don't understand!

void * runner(void *param){
sum=0;   // MY DOUBT
for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}

output: 45


来源: stackexchange

问:
Get date from coming day and specified date in Carbon?
In Carbon, I can do

```<code>Carbon::parse("This Sunday"); // This gives me coming date for Sunday
</code>```

But I want to get date for day like get coming date of Sunday after 2018-01-01. Is it possible to achieve something like this?

答:
You could do

```<code>$sunday = Carbon::parse("This Sunday");
$sunday->next(Carbon::SUNDAY);
</code>```

Docs

ContentLicense: CC BY-SA 3.0

Body:
In Carbon, I can do

Carbon::parse("This Sunday"); // This gives me coming date for Sunday

But I want to get date for day like get coming date of Sunday after 2018-01-01. Is it possible to achieve something like this?

Body:
You could do

$sunday = Carbon::parse("This Sunday");
$sunday->next(Carbon::SUNDAY);

Docs


问:
int max = ~0; What does it mean?
int max = ~0;

What does it mean?

答:
As noted, ~0 yields 0xFFFFFFFF.

However, I suspect the original programmer is confused. executing int max = ~0 ; sets the signed integer max to the value -1.

ContentLicense: CC BY-SA 2.5

Title: int max = ~0; What does it mean?

Body:
int max = ~0;

What does it mean?


问:
manipulate data set using R
I have a data set which has for example the following column entries

```<code>Data: 05.12.2017   |   Acceleration: 0,0042414...

Data: 05.12.2017   |   Acceleration: 0,004235235...

Data: 05.12.2017   |   Acceleration: 0,04235235...

Data: 05.12.2017   |   Acceleration: 0,0023414...
</code>```

I want to manipulate the data, such that the name before the ":" is the name of the column.

In other words I want this:

```<code>Data         |  Acceleration

05.12.2017   |  0,0042414...

05.12.2017   |  0,004235235...

05.12.2017   |  0,04235235...

05.12.2017   |  0,0023414...
</code>```

Is there a possibility to do that?

答:
You can set the new names of your dataset and then erase those strings from your entries. Not a general approach though. </p>

```<code>library(stringr)

names(your_data_set) = c("Data", "Acceleration")

your_data_set$Data = str_replace_all(your_data_set$Data, "Data: ", "")
your_data_set$Acceleration= str_replace_all(your_data_set$Acceleration, "Acceleration: ", "")
</code>```

Title: manipulate data set using R

Body:
I have a data set which has for example the following column entries

Data: 05.12.2017   |   Acceleration: 0,0042414...

Data: 05.12.2017   |   Acceleration: 0,004235235...

Data: 05.12.2017   |   Acceleration: 0,04235235...

Data: 05.12.2017   |   Acceleration: 0,0023414...

I want to manipulate the data, such that the name before the ":" is the name of the column.

In other words I want this:

Data         |  Acceleration

05.12.2017   |  0,0042414...

05.12.2017   |  0,004235235...

05.12.2017   |  0,04235235...

05.12.2017   |  0,0023414...

Is there a possibility to do that?

Body:
You can set the new names of your dataset and then erase those strings from your entries. Not a general approach though.

library(stringr)

names(your_data_set) = c("Data", "Acceleration")

your_data_set$Data = str_replace_all(your_data_set$Data, "Data: ", "")
your_data_set$Acceleration= str_replace_all(your_data_set$Acceleration, "Acceleration: ", "")


问:
todoist - Fetching the list of projects with python library
I am specifically trying to get the project id given the project name. I saw in the api the api.sync() is supposed to return to me all the projects as in array in a key which I was then planning to iterate through.

I tried using sync with the python library but my projects array is empty, is it some sort of promise mechanism if so how do I wait for success response in python language?

```<code>import todoist
api = todoist.TodoistAPI(token)
response = api.sync()
projects = response['projects']
for project in projects:
   print(project['name'] + '-' + project['id'])
</code>```

答: The library takes care of the Sync for you. In case you already did a Sync in the past, it stores a hash into your $HOME/.todoist-sync/. I recommend you to try to clean this path and try again.

Body:
I am specifically trying to get the project id given the project name. I saw in the api the api.sync() is supposed to return to me all the projects as in array in a key which I was then planning to iterate through.

I tried using sync with the python library but my projects array is empty, is it some sort of promise mechanism if so how do I wait for success response in python language?

import todoist
api = todoist.TodoistAPI(token)
response = api.sync()
projects = response['projects']
for project in projects:
   print(project['name'] + '-' + project['id'])


问:
Data table multiple condition with string vector
I would like to subset a data table with a condition that I want to apply on all column in vector of strings with a & condition in between. Example:

```<code>library(data.table)
test <- setDT(as.data.frame(list(ID = c(rep(1,10),rep(2,10)), time = rep(c(1:10),2),
                                 Input = rep(c(array(data = 0, dim = 5),1,array(data = 0, dim = 4)),2),
                                 replicate(4,sample(c(1:20), 10, replace = TRUE)))))

signalcolumns <- colnames(test)[! colnames(test) %in% c("ID","Input","time")]
</code>```

Now I want

```<code>test[X1 > 5 & X2 > 5 & X3 > 5 & X4 > 5]
</code>```

and I would like to write it with the signalcolumns.

```<code>test[get(signalcolumns) > 5]
</code>```

doesn't work as it set the condition only on the first X1 column. I don't see what syntax I could use here. I though of trying to evaluate an expression like

```<code>c(paste0(signalcolumns[1:(length(signalcolumns)-1)],">5 &"),
paste0(signalcolumns[(length(signalcolumns)-1)],">5") )
</code>```

but I am a bit stuck here.

Body:
I would like to subset a data table with a condition that I want to apply on all column in vector of strings with a & condition in between. Example:

library(data.table)
test <- setDT(as.data.frame(list(ID = c(rep(1,10),rep(2,10)), time = rep(c(1:10),2),
                                 Input = rep(c(array(data = 0, dim = 5),1,array(data = 0, dim = 4)),2),
                                 replicate(4,sample(c(1:20), 10, replace = TRUE)))))

signalcolumns <- colnames(test)[! colnames(test) %in% c("ID","Input","time")]

Now I want

test[X1 > 5 & X2 > 5 & X3 > 5 & X4 > 5]

and I would like to write it with the signalcolumns.

test[get(signalcolumns) > 5]

doesn't work as it set the condition only on the first X1 column. I don't see what syntax I could use here. I though of trying to evaluate an expression like

c(paste0(signalcolumns[1:(length(signalcolumns)-1)],">5 &"),
paste0(signalcolumns[(length(signalcolumns)-1)],">5") )

but I am a bit stuck here.

Body:
I would do something like this:

testVars <- function(x, y){
  X <- test[, x, with = F]
  X <- X > y
  X <- rowSums(X)
  X == length(x)
}

test[testVars(signalcolumns, 5)]
#    ID time Input X1 X2 X3 X4
# 1:  1    4     0 14  9 15  6
# 2:  1    5     0 14 12 20 16
# 3:  1    6     1 17  8 19 18
# 4:  1   10     0  6 17  8 14
# 5:  2    4     0 14  9 15  6
# 6:  2    5     0 14 12 20 16
# 7:  2    6     1 17  8 19 18
# 8:  2   10     0  6 17  8 14


问:
How to display the array index value at console in angular 2
How can I display array index value in console window on click of the button which is present inside the carousel component? where the console window is displaying index value twice  and at last its redirecting to 1st array index value as 1.
Console window should only display the index value with increment of 1 so it starts displaying array index value from.

guide.html

  {{guide.Type}}
  {{guide.PageColor}}

   <carousel class="carousel slide" data-interval="false">
     <slide  *ngFor="let image of images; let i=index ">

Image: {{i+1}}

         <input type="file" name="file" id="file" />
         {{image.change}}

      </slide>
   </carousel>

```
</div>
</div>
</p>

<h2>guide.component.ts</h2>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import { CarouselModule } from 'ngx-bootstrap';
@Component({
  templateUrl: './guide.html'
})
export class GuideComponent {
 guides : any = [{ Type: 'Company', PageColor: 'red'},{ Type: 'Company', PageColor: 'Blue'}];

 images:any = [{image :'img1.jpg', change:'change'},{image: 'img2.jpg', change:'add'},{image:'img3.jpg', change:'edit'},{image:'im4.jpg',change:'delete' }];

 idValue(i) {
  i=i+1;
  console.log(i);
 }
}</code>```

答:
Here is a simplified version of your code, that works.
In two words = simple types (number is our case) copied to click-handler arguments, not send by ref. So every time you got same value from i.</p>

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <div  *ngFor="let image of images; let i=index ">
          <p>Image: {{i+1}}</p>

          <p (click)="idValue(i)">
          Button
          </p>
         </div>
  `,
})
export class AppComponent  {

  images:any = [{image :'img1.jpg', change:'change'},{image: 'img2.jpg', change:'add'},{image:'img3.jpg', change:'edit'},{image:'im4.jpg',change:'delete' }];
  indexArr = new Array(this.images.length + 1);

    idValue(i) {
      if(!this.indexArr[i]) { this.indexArr[i] = 0};
        this.indexArr[i] += 1;
        console.log('index:', i, ' Click number', this.indexArr[i]);
    }

}
</code>```

Body:
How can I display array index value in console window on click of the button which is present inside the carousel component? where the console window is displaying index value twice  and at last its redirecting to 1st array index value as 1.
Console window should only display the index value with increment of 1 so it starts displaying array index value from.

guide.html

  {{guide.Type}}
  {{guide.PageColor}}

   <carousel class="carousel slide" data-interval="false">
     <slide  *ngFor="let image of images; let i=index ">

Image: {{i+1}}

         <input type="file" name="file" id="file" />
         {{image.change}}

      </slide>
   </carousel>

guide.component.ts

import { Component } from '@angular/core';
import { CarouselModule } from 'ngx-bootstrap';
@Component({
  templateUrl: './guide.html'
})
export class GuideComponent {
 guides : any = [{ Type: 'Company', PageColor: 'red'},{ Type: 'Company', PageColor: 'Blue'}];

 images:any = [{image :'img1.jpg', change:'change'},{image: 'img2.jpg', change:'add'},{image:'img3.jpg', change:'edit'},{image:'im4.jpg',change:'delete' }];

 idValue(i) {
  i=i+1;
  console.log(i);
 }
}

Body:
Here is a simplified version of your code, that works.
In two words = simple types (number is our case) copied to click-handler arguments, not send by ref. So every time you got same value from i.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <div  *ngFor="let image of images; let i=index ">
          <p>Image: {{i+1}}</p>

          <p (click)="idValue(i)">
          Button
          </p>
         </div>
  `,
})
export class AppComponent  {

  images:any = [{image :'img1.jpg', change:'change'},{image: 'img2.jpg', change:'add'},{image:'img3.jpg', change:'edit'},{image:'im4.jpg',change:'delete' }];
  indexArr = new Array(this.images.length + 1);

    idValue(i) {
      if(!this.indexArr[i]) { this.indexArr[i] = 0};
        this.indexArr[i] += 1;
        console.log('index:', i, ' Click number', this.indexArr[i]);
    }

}


问:
Phusion Passenger - Sticky session - How to add options to set-cookie header?
Enabling sticky sessions in Phusion Passenger adds set-cooke header in next form:

```<code>Set-Cookie: _passenger_route=598708409; Path=/
</code>```

Questions:

How to alter Path?

How to set httpOnly option?

How to set secure option?

How to set other options?

答:
Path is set to the value of passenger_base_uri
httpOnly is not set by Passenger because it stops cookies being sent over websockets on Chrome (Last confirmed on Chrome 25).

To set httpOnly, secure, and other options, perhaps using something like header_filter_by_lua_block from the ngx_http_lua_module might be of use (this is included in the apt packaged nginx provided by Phusion, and can be installed as a dynamic module otherwise).

Body:
Enabling sticky sessions in Phusion Passenger adds set-cooke header in next form:

Set-Cookie: _passenger_route=598708409; Path=/

Questions:

How to alter Path?

How to set httpOnly option?

How to set secure option?

How to set other options?


问:
How can I make this code shorter? Is it possible to create this in one loop?
```<code>var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
</code>```

It's a javascript code. In my html is this

```<code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>
</code>```

My task is, come this code together below one loop.

Thank you so much for your help!

答:
In my understanding, you can do following:

Create a nested loop and set initial value of y based on iteration.

Create a variable for increment factor and use it across. This will make it easy to change in future.

Though this is minor, you can move declaration of x and y to for loop, since you are initializing it in every for loop. This will be useful if you switch to ES6 in future.

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var xFactor = 60;
var yFactor = 57;
var noOfItems = 5;

for (var i = 0; i < noOfItems; i++) {
  for (var x = 10, y = 10 + (i * yFactor); y < 240; x += xFactor, y += yFactor) {
    ctx.fillStyle = "orange";
    ctx.fillRect(x, y, rw, rh);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas></code>```

Body:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var x = 10;
var y = 10;

for (x=10, y=10; y<240; x=x+60, y=y+57) {
  ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}
  for (x=10, y=67; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=124; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=181; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

  for (x=10, y=238; y<240; x=x+60, y=y+57) {
ctx.fillStyle = "orange";
ctx.fillRect(x,y,rw,rh);
}

It's a javascript code. In my html is this

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>

My task is, come this code together below one loop.

Thank you so much for your help!

Body:
In my understanding, you can do following:

Create a nested loop and set initial value of y based on iteration.

Create a variable for increment factor and use it across. This will make it easy to change in future.

Though this is minor, you can move declaration of x and y to for loop, since you are initializing it in every for loop. This will be useful if you switch to ES6 in future.

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

var rw = 50;
var rh = 50;
var xFactor = 60;
var yFactor = 57;
var noOfItems = 5;

for (var i = 0; i < noOfItems; i++) {
  for (var x = 10, y = 10 + (i * yFactor); y < 240; x += xFactor, y += yFactor) {
    ctx.fillStyle = "orange";
    ctx.fillRect(x, y, rw, rh);
  }
}

<canvas id="myCanvas" height="300" width="450" style="border: 1px solid black"></canvas>


问:
New screen in matlab GUI
How to create a GUI in MATLAB that when clicking the button it changes to a new interface (new screen).

I have a program that generates a certain graphic, i wanted that when i clicked on a button it changed the screen of the GUI to another one with another graphic.

答:
When you save a GUI in MATLAB, there are two files. One is fig file which is a user-designed figure, namely a picture. Another one is a m file which contains the code. There is no relationship between two figures. This is totally different with C# and other languages. So, we consider this m file is an isolated program. To execute it, we run it with following code.</p>

```<code>run('.\MfileName.m')
</code>```

Title: New screen in matlab GUI

Body:
When you save a GUI in MATLAB, there are two files. One is fig file which is a user-designed figure, namely a picture. Another one is a m file which contains the code. There is no relationship between two figures. This is totally different with C# and other languages. So, we consider this m file is an isolated program. To execute it, we run it with following code.

run('.\MfileName.m')


问:
Logic behind selecting number of peers for an organization in hyperledger

Hi I am looking to find what is the logic behind selecting number of peers in Hyperledger fabric for an organization

答:
AFAIK:
1 peer = 1 Org = 1 Peer admin

If you set up a company network, where every department needs an individual peer admin. You would use multiple Orgs within this company.

Each client gets access through its department-peer.

Please correct me if this assumption is wrong.


问:
How to check for both POST and GET data whilst using filter_input?
I'm wondering if it's possible to get a variable whether it is in POST or GET and then use filter_input() to sanitize it.

At first I thought that $var = filter_input(INPUT_POST | INPUT_GET, "var", FILTER_SANITIZE_STRING) might work, however it doesn't and the PHP manual states you can only pass one type of input.

I also tried INPUT_REQUEST, which strangely didn't work. The function recognises it (i.e. it doesn't throw up an error saying I've put something wrong in $input), yet it won't get any code. And yes, I know not to use INPUT_REQUEST in a live environment, I was just purely testing to see if it would work.

Currently I do the following:

```<code>$var = filter_input(INPUT_POST, "var", FILTER_SANITIZE_STRING);
if(!$var) $var = filter_input(INPUT_GET, "var", FILTER_SANITIZE_STRING);
</code>```

however with many things in PHP, there is often simpler way that will do it all for me in one command. I'm wondering if that is the case here, can I combine them into one check? I performed a cursory search on Google and couldn't even find any references to anyone trying this before, let alone a solution, so now I turn to you good folks.

答:
If you sanitize properly your input, I would personally test the result of filtre_input for null, because the if(!$var) condition could be triggered by a falsy but existing value like 0.

For instance :

```<code>function getLatitude($name) {
  $var = filter_input(INPUT_POST, 'latitude', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
  if($var === null){
      $var = filter_input(INPUT_GET, 'latitude', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
  }
  return $var;
}
</code>```

With the usual !$var condition and FILTER_SANITIZE_NUMBER_FLOAT, you will get a null value instead of 0.

Body:
I'm wondering if it's possible to get a variable whether it is in POST or GET and then use filter_input() to sanitize it.

At first I thought that $var = filter_input(INPUT_POST | INPUT_GET, "var", FILTER_SANITIZE_STRING) might work, however it doesn't and the PHP manual states you can only pass one type of input.

I also tried INPUT_REQUEST, which strangely didn't work. The function recognises it (i.e. it doesn't throw up an error saying I've put something wrong in $input), yet it won't get any code. And yes, I know not to use INPUT_REQUEST in a live environment, I was just purely testing to see if it would work.

Currently I do the following:

$var = filter_input(INPUT_POST, "var", FILTER_SANITIZE_STRING);
if(!$var) $var = filter_input(INPUT_GET, "var", FILTER_SANITIZE_STRING);

however with many things in PHP, there is often simpler way that will do it all for me in one command. I'm wondering if that is the case here, can I combine them into one check? I performed a cursory search on Google and couldn't even find any references to anyone trying this before, let alone a solution, so now I turn to you good folks.

Body:
If you sanitize properly your input, I would personally test the result of filtre_input for null, because the if(!$var) condition could be triggered by a falsy but existing value like 0.

For instance :

function getLatitude($name) {
  $var = filter_input(INPUT_POST, 'latitude', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
  if($var === null){
      $var = filter_input(INPUT_GET, 'latitude', FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
  }
  return $var;
}

With the usual !$var condition and FILTER_SANITIZE_NUMBER_FLOAT, you will get a null value instead of 0.


问:
Logging with log4j on tomcat jruby-rack for a Rails 3 application
I just spent the better part of 3 hours trying to get my Rails application logging with Log4j. I've finally got it working, but I'm not sure if what I did is correct. I tried various methods to no avail until my very last attempt. So I'm really looking for some validation here, perhaps some pointers and tips as well -- anything would be appreciated to be honest. I've summarized all my feeble methods into three attempts below. I'm hoping for some enlightenment on where I went wrong with each attempt -- even if it means I get ripped up.

Thanks for the help in advance!

System Specs

Rails 3.0

Windows Server 2008

Log4j 1.2

Tomact 6.0.29

Java 6

Attempt 1 - Configured Tomcat to Use Log4J

I basically followed the guide on the Apache Tomcat website here. The steps are:

Create a log4j.properties file in $CATALINA_HOME/lib

Download and copy the log4j-x.y.z.jar into $CATALINA_HOME/lib

Replace $CATALINA_HOME/bin/tomcat-juli.jar with the tomcat-juli.jar from the Apache Tomcat Extras folder

Copy tomcat-juli-adapters.jar from the Apache Tomcat Extras folder into $CATALINA_HOME/lib

Delete $CATALINA_BASE/conf/logging.properties

Start Tomcat (as a service)

Expected Results According to the Guide

I should have seen a tomcat.log file in my $CATALINA_BASE/logs folder.

Actual Results

No tomcat.log

Saw three of the standard logs instead

jakarta_service_20101231.log

stderr_20101231.log

stdout_20101231.log

Question

Shouldn't I have at least seen a tomcat.log file?

Attempt 2 - Use default Tomcat logging (commons-logging)

Reverted all the changes from the previous setup

Modified $CATALINA_BASE/conf/logging.properties by doing the following:

Adding a setting for my application in the handlers line: 5rails3.org.apache.juli.FileHandler

Adding Handler specific properties

```<code>5rails3.org.apache.juli.FileHandler.level = FINE
5rails3.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
5rails3.org.apache.juli.FileHandler.prefix = rails3.
</code>```

Adding Facility specific properties

```<code>org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/rails3].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/rails3].handlers = 4host-manager.org.apache.juli.FileHandler
</code>```

Modified my web.xml by adding the following context parameter as per the Logging section of the jruby-rack README (I also modified my warbler.rb accordingly, but I opted to change the web.xml directly to test things faster).

```<code><context-param>
  <param-name>jruby.rack.logging</param-name>
  <param-value>commons_logging</param-value>
</context-param>
</code>```

Restarted Tomcat

Results

A log file was created (rails3.log), however there was no log information in the file.

Attempt 2A - Use Log4j with existing set up

I decided to give Log4j another whirl with this new web.xml setting.

Copied the log4j.jar into my WEB-INF/lib folder

Created a log4j.properties file and put it into WEB-INF/classes

```<code>log4j.rootLogger=INFO, R
log4j.logger.javax.servlet=DEBUG

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.base}/logs/rails3.log
log4j.appender.R.MaxFileSize=5036KB
log4j.appender.R.MaxBackupIndex=4
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n
</code>```

Restarted Tomcat

Results

Same as Attempt 2

NOTE: I used log4j.logger.javax.servlet=DEBUG because I read in the jruby-rack README that all logging output is automatically redirected to the javax.servlet.ServletContext#log method. So I thought this would capture it, but I was obviously wrong.

Question

Why didn't this work?

Isn't Log4J using the commons_logging API?

Attempt 3 - Tried out slf4j (WORKED)

A bit uncertain as to why Attempt 2A didn't work, I thought to myself, maybe I can't use commons_logging for the jruby.rack.logging parameter because it's probably not using commons_logging API... (but I was still not sure). I saw slf4j as an option. I have never heard of it and out of curiosity, I decided to look it up. After reading about it briefly, I thought it was as good of a shot as any and decided to try it out following the instructions here.

Continuing from the setup of Attempt 2A:

Copied slf4j-api-1.6.1.jar and slf4j-simple-1.6.1.jar into my WEB-INF/lib folder

I also copied slf4j-log4j12-1.6.1.jar into my WEB-INF/lib folder

Restarted Tomcat

And VIOLA! I now have logging information going into my rails3.log file.

So the big question is:

WTF?

Even though logging seems to be working now, I'm really not sure if what I did is right. So like I said earlier, I'm really looking for some validation more or less. I'd also appreciate any pointers/tips/advice if you have any. Thanks!

答:
We also did various experiments and finally settled with slf4j option. Coming from Java background we knew slf4j, so we didn't go further.

```<code><context-param>
   <param-name>jruby.rack.logging</param-name>
   <param-value>slf4j</param-value>
 </context-param>
</code>```

btw, there is no need to copy slf4j-simple-1.6.1.jar into tomcat/lib or WEB-INF/lib when using slf4j-log4jxxx.jar

Body:
I just spent the better part of 3 hours trying to get my Rails application logging with Log4j. I've finally got it working, but I'm not sure if what I did is correct. I tried various methods to no avail until my very last attempt. So I'm really looking for some validation here, perhaps some pointers and tips as well -- anything would be appreciated to be honest. I've summarized all my feeble methods into three attempts below. I'm hoping for some enlightenment on where I went wrong with each attempt -- even if it means I get ripped up.

Thanks for the help in advance!

System Specs

Rails 3.0

Windows Server 2008

Log4j 1.2

Tomact 6.0.29

Java 6

Attempt 1 - Configured Tomcat to Use Log4J

I basically followed the guide on the Apache Tomcat website here. The steps are:

Create a log4j.properties file in $CATALINA_HOME/lib

Download and copy the log4j-x.y.z.jar into $CATALINA_HOME/lib

Replace $CATALINA_HOME/bin/tomcat-juli.jar with the tomcat-juli.jar from the Apache Tomcat Extras folder

Copy tomcat-juli-adapters.jar from the Apache Tomcat Extras folder into $CATALINA_HOME/lib

Delete $CATALINA_BASE/conf/logging.properties

Start Tomcat (as a service)

Expected Results According to the Guide

I should have seen a tomcat.log file in my $CATALINA_BASE/logs folder.

Actual Results

No tomcat.log

Saw three of the standard logs instead

jakarta_service_20101231.log

stderr_20101231.log

stdout_20101231.log

Question

Shouldn't I have at least seen a tomcat.log file?

Attempt 2 - Use default Tomcat logging (commons-logging)

Reverted all the changes from the previous setup

Modified $CATALINA_BASE/conf/logging.properties by doing the following:

Adding a setting for my application in the handlers line: 5rails3.org.apache.juli.FileHandler

Adding Handler specific properties

5rails3.org.apache.juli.FileHandler.level = FINE
5rails3.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
5rails3.org.apache.juli.FileHandler.prefix = rails3.

Adding Facility specific properties

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/rails3].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/rails3].handlers = 4host-manager.org.apache.juli.FileHandler

Modified my web.xml by adding the following context parameter as per the Logging section of the jruby-rack README (I also modified my warbler.rb accordingly, but I opted to change the web.xml directly to test things faster).

<context-param>
  <param-name>jruby.rack.logging</param-name>
  <param-value>commons_logging</param-value>
</context-param>

Restarted Tomcat

Results

A log file was created (rails3.log), however there was no log information in the file.

Attempt 2A - Use Log4j with existing set up

I decided to give Log4j another whirl with this new web.xml setting.

Copied the log4j.jar into my WEB-INF/lib folder

Created a log4j.properties file and put it into WEB-INF/classes

log4j.rootLogger=INFO, R
log4j.logger.javax.servlet=DEBUG

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.base}/logs/rails3.log
log4j.appender.R.MaxFileSize=5036KB
log4j.appender.R.MaxBackupIndex=4
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} [%t] %-5p %c %x - %m%n

Restarted Tomcat

Results

Same as Attempt 2

NOTE: I used log4j.logger.javax.servlet=DEBUG because I read in the jruby-rack README that all logging output is automatically redirected to the javax.servlet.ServletContext#log method. So I thought this would capture it, but I was obviously wrong.

Question

Why didn't this work?

Isn't Log4J using the commons_logging API?

Attempt 3 - Tried out slf4j (WORKED)

A bit uncertain as to why Attempt 2A didn't work, I thought to myself, maybe I can't use commons_logging for the jruby.rack.logging parameter because it's probably not using commons_logging API... (but I was still not sure). I saw slf4j as an option. I have never heard of it and out of curiosity, I decided to look it up. After reading about it briefly, I thought it was as good of a shot as any and decided to try it out following the instructions here.

Continuing from the setup of Attempt 2A:

Copied slf4j-api-1.6.1.jar and slf4j-simple-1.6.1.jar into my WEB-INF/lib folder

I also copied slf4j-log4j12-1.6.1.jar into my WEB-INF/lib folder

Restarted Tomcat

And VIOLA! I now have logging information going into my rails3.log file.

So the big question is:

WTF?

Even though logging seems to be working now, I'm really not sure if what I did is right. So like I said earlier, I'm really looking for some validation more or less. I'd also appreciate any pointers/tips/advice if you have any. Thanks!

Body:
We also did various experiments and finally settled with slf4j option. Coming from Java background we knew slf4j, so we didn't go further.

<context-param>
   <param-name>jruby.rack.logging</param-name>
   <param-value>slf4j</param-value>
 </context-param>

btw, there is no need to copy slf4j-simple-1.6.1.jar into tomcat/lib or WEB-INF/lib when using slf4j-log4jxxx.jar


问:
Http load testing with bytes counting
I need some possibility to conduct load testing of our REST API with traffic counting.

For example to run 20 concurrent user for 1 hour. As a result I want to get information about responses (avg time, delays, etc) and overall traffic that has been produced.

I overlooked JMeter and Gatling, but found no possibilities to count bytes.

I don't really need big amount of concurrent users (100 would be enough) and high throughput (more than 10 requests per second from single user).

My goal is just to produce some load on our system and to check that it shows correct statistic data.

答:
By default JMeter should be saving sent and received bytes in .jtl results file

If it doesn't - add the next lines to user.properties file (lives in "bin" folder of your JMeter installation)

```<code>jmeter.save.saveservice.bytes=true
jmeter.save.saveservice.sent_bytes=true
</code>```

Also make sure you have HttpClient4 implementation selected on the "Advanced" tab of HTTP Request sampler (or HTTP Request Defaults)

Title: Http load testing with bytes counting

Body:
By default JMeter should be saving sent and received bytes in .jtl results file

If it doesn't - add the next lines to user.properties file (lives in "bin" folder of your JMeter installation)

jmeter.save.saveservice.bytes=true
jmeter.save.saveservice.sent_bytes=true

Also make sure you have HttpClient4 implementation selected on the "Advanced" tab of HTTP Request sampler (or HTTP Request Defaults)


问:
How to Stop a Service in Android when the application is not running.
I have Started my service in one of my main activity class.The problem is that when my application is not running I want to Stop my service.How can i implement this.Is there any option to stop it without stopping it using any button click or other click events of the control.

Also is there any way to indicate the service is running or not while my application is running

答:
Using intent you can stop the service.

```<code>Intent intentStartervice = new Intent(context, MyService.class);
stopService(intentStartService);
</code>```

or

just pass the Context.

```<code>context.stopService(new Intent(context, MyService.class));
</code>```

Body:
Using intent you can stop the service.

Intent intentStartervice = new Intent(context, MyService.class);
stopService(intentStartService);

or

just pass the Context.

context.stopService(new Intent(context, MyService.class));


问:
JSON from php to js
What is the best way to parse a php-variable with json data to js?
On the php-site I have the following:

```<code>  $pdo = new PDO('mysql:host=localhost;dbname=test', 'homedbuser', 'homedbuser');
    $sqlQuery ="SELECT `serie`, `abtrag` FROM `testem`";

    $q = $pdo->query($sqlQuery);

    $result = $q->fetch(PDO::FETCH_ASSOC);

    $rowcount = $q->rowCount();

    $data = array();

    for($x=0; $x < $rowcount-1;$x++){

    $data[]  = $q->fetch(PDO::FETCH_ASSOC);

    $myJson = json_encode($data);

    echo $myJson;

The Output looks like this:

  [
  {"serie":"KK718X","abtrag":"71"},
  {"serie":"KK712X","abtrag":"337"},
  {"serie":"LK719X","abtrag":"93"},
  {"serie":"KK790Y","abtrag":"78"}
 ]
</code>```

Now I want to put the data into a js-variable.

What kind of variable do I have to choose ?
I tried it with axaj / xmlhttp request but that did not work for jet.
Can some one tell, how to do this the right way?

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("show").innerHTML = "myObject[1].serie";
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();``
</code>```

答:
Use following code :</p>

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        //document.getElementById("show").innerHTML = "myObject[1].serie" add a text node to element html.

        document.getElementById("show").innerHTML = myObj[1].serie; //For Obhect data serie.
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();
</code>```

Title: JSON from php to js

Body:
What is the best way to parse a php-variable with json data to js?
On the php-site I have the following:

  $pdo = new PDO('mysql:host=localhost;dbname=test', 'homedbuser', 'homedbuser');
    $sqlQuery ="SELECT `serie`, `abtrag` FROM `testem`";

    $q = $pdo->query($sqlQuery);

    $result = $q->fetch(PDO::FETCH_ASSOC);

    $rowcount = $q->rowCount();

    $data = array();

    for($x=0; $x < $rowcount-1;$x++){

    $data[]  = $q->fetch(PDO::FETCH_ASSOC);

    $myJson = json_encode($data);

    echo $myJson;

The Output looks like this:

  [
  {"serie":"KK718X","abtrag":"71"},
  {"serie":"KK712X","abtrag":"337"},
  {"serie":"LK719X","abtrag":"93"},
  {"serie":"KK790Y","abtrag":"78"}
 ]

Now I want to put the data into a js-variable.

What kind of variable do I have to choose ?
I tried it with axaj / xmlhttp request but that did not work for jet.
Can some one tell, how to do this the right way?

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        document.getElementById("show").innerHTML = "myObject[1].serie";
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();``

Body:
Use following code :

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myObj = JSON.parse(this.responseText);
        //document.getElementById("show").innerHTML = "myObject[1].serie" add a text node to element html.

        document.getElementById("show").innerHTML = myObj[1].serie; //For Obhect data serie.
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();


问:
Aggregation + sorting +pagination in elastic search
I need to do an aggregation + sorting + pagination in one of the indexes.

I learned about internal functionality of Elastic search,

I have 5 total shards, it will sort the individual shards and fetch the result, by default each shard will return  in 10 records. Then the 50 records are sorted again and it will fetch the top 10 record since by default size is 10.

ouput:

The aggregated results are returned in separate field named as "aggregations".In order to do pagination in this aggregated data,size and from are not working.

So tired of doing termBuilder.size(500), now the logic was differs as per this link (http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html)

It leads to inaccuracy of data.

Can any one suggest me how to deal with aggregation + pagination.

答:
In elasticsearch, there is no accurate solution for it. You may use filtering with partition options but applied partitioner can break your sorted result. ES performs partition operation over a given field and returns buckets from requested partition. So your result end up with partition ordered.(you need to make subsequent request with other partition number to gather data from all partitions.)

My suggestion is give a higher size value for each term as you mentioned in your question.


问:
Call parent's activity from a fragment
If I'm inside a Fragment how can I call a parent's activity?</p>

答:
Simply call your parent activity using getActivity() method.</p>

```<code>CardView cardView = (CardView) getActivity().findView(R.id.your_view);
</code>```

Title: Call parent's activity from a fragment

Body:
Simply call your parent activity using getActivity() method.

CardView cardView = (CardView) getActivity().findView(R.id.your_view);


问:
Calculate business days
I need a method for adding "business days" in PHP. For example, Friday 12/5 + 3 business days = Wednesday 12/10.

At a minimum I need the code to understand weekends, but ideally it should account for US federal holidays as well. I'm sure I could come up with a solution by brute force if necessary, but I'm hoping there's a more elegant approach out there. Anyone?

Thanks.

答:
Here is another solution without for loop for each day.</p>

```<code>$from = new DateTime($first_date);
$to = new DateTime($second_date);

$to->modify('+1 day');
$interval = $from->diff($to);
$days = $interval->format('%a');

$extra_days = fmod($days, 7);
$workdays = ( ( $days - $extra_days ) / 7 ) * 5;

$first_day = date('N', strtotime($first_date));
$last_day = date('N', strtotime("1 day", strtotime($second_date)));
$extra = 0;
if($first_day > $last_day) {
   if($first_day == 7) {
       $first_day = 6;
   }

   $extra = (6 - $first_day) + ($last_day - 1);
   if($extra < 0) {
       $extra = $extra * -1;
   }
}
if($last_day > $first_day) {
    $extra = $last_day - $first_day;
}
$days = $workdays + $extra
</code>```

OwnerDisplayName: AdamTheHutt

Title: Calculate business days

Body:
Here is another solution without for loop for each day.

$from = new DateTime($first_date);
$to = new DateTime($second_date);

$to->modify('+1 day');
$interval = $from->diff($to);
$days = $interval->format('%a');

$extra_days = fmod($days, 7);
$workdays = ( ( $days - $extra_days ) / 7 ) * 5;

$first_day = date('N', strtotime($first_date));
$last_day = date('N', strtotime("1 day", strtotime($second_date)));
$extra = 0;
if($first_day > $last_day) {
   if($first_day == 7) {
       $first_day = 6;
   }

   $extra = (6 - $first_day) + ($last_day - 1);
   if($extra < 0) {
       $extra = $extra * -1;
   }
}
if($last_day > $first_day) {
    $extra = $last_day - $first_day;
}
$days = $workdays + $extra


问:
Multiple column in FormPanel ExtJs 3.2
I am trying to create a form in ExtJs that has rows of two columns and others of three, i have this:

but i want that the fields: "Fecha Escritura", "Acción" y "Fecha Escritura" to be in the same row.

this is my code:

```<code> formBuscador = new Ext.FormPanel({
    labelWidth : 120,
    frame : true,
    title : buscador,
    bodyStyle : 'padding:5px 5px 0',
    width : 1200,
    renderTo : 'gridFormularioBusqueda',
    items : [ {
        //xtype: 'form',
        layout : 'column',
        labelAlign: 'left',
        defaults: {
              xtype: 'container',
              layout: 'form',
              columnWidth: 0.5,
              labelWidth: 185
           },
           items: [
                    {items: [{
                                xtype : 'textfield',
                                fieldLabel : idEmpleado,
                                allowBlank : true,
                                name : 'idEmpleadoP',
                                id : 'idEmpleadoPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '9'}
                            }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : nif,
                                allowBlank : true,
                                name : 'nifP',
                                id : 'nifPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '9'}
                              }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : nombre,
                                allowBlank : false,
                                blankText : campoNoVacioNombre,
                                name : 'nombreP',
                                id : 'nombrePB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '100'}
                              }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : apellidos,
                                allowBlank : false,
                                blankText : campoNoVacioApellido,
                                name : 'apellidosP',
                                id : 'apellidosPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '100'}
                              }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : notario,
                                allowBlank : false,
                                blankText : campoNoVacioNotario,
                                name : 'notarioP',
                                id : 'notarioPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '75'}
                              }]
                    },{items: [{
                                xtype : 'numberfield',
                                fieldLabel : numeroProtocolo,
                                allowBlank : false,
                                blankText : campoNoVacioNumeroProtocolo,
                                name : 'numeroProtocoloP',
                                id : 'numeroProtocoloPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '5'}
                              }]
                    },{items: [{
                                fieldLabel : incluidaDelegacion,
                                html: "<select id='incluidaDelegacionPB' name='incluidaDelegacionP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:9px;margin-top: 1px;' >" +
                                        "<option id='incluidaDelegacionPBNo' value='false'>No</option>" +
                                        "<option id='incluidaDelegacionPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                fieldLabel : revocacionDelegacion,
                                html: "<select id='revocacionDelegacionBP' name='revocacionDelegacionB' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:9px;margin-top: 6px;' >" +
                                        "<option id='revocacionDelegacionPBNo' value='false'>No</option>" +
                                        "<option id='revocacionDelegacionPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                fieldLabel : revocado,
                                html: "<select id='revocadoPB' name='revocadoP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:10px;margin-top: 1px;' >" +
                                        "<option id='revocadoPBNo' value='false'>No</option>" +
                                        "<option id='revocadoPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                fieldLabel : limiteCuantitativo,
                                html: "<select id='limiteCuantitativoBP' name='limiteCuantitativoP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:10px;margin-top: 1px;' >" +
                                        "<option id='limiteCuantitativoPBNo' value='false'>No</option>" +
                                        "<option id='limiteCuantitativoPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                xtype : 'datefield',
                                fieldLabel : fechaEscritura,
                                allowBlank : false,
                                blankText : campoNoVacioFechaEscritura,
                                labelWidth: 100,
                                name : 'fechaEscrituraP',
                                id : 'fechaEscrituraPB',
                                editable : false,
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '10'}
                              }]
                    },{items: [{
                                fieldLabel : 'Acción',
                                html: "<select id='accionFechaEscrituraBP' name='accionFechaEscrituraBP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:10px;margin-top: 1px;' >" +
                                        "<option id='accionFechaEscrituraBPAnterior' value='Anterior'>Anterior</option>" +
                                        "<option id='accionFechaEscrituraBPPosterior' value='Posterior'>Posterior</option>" +
                                        "<option id='accionFechaEscrituraBPEntre' value='Entre'>Entre</option>" +
                                        "<option id='accionFechaEscrituraBPIgualA' value='IgualA'>Igual A</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                xtype : 'datefield',
                                fieldLabel : fechaEscritura,
                                allowBlank : false,
                                blankText : campoNoVacioFechaEscritura,
                                name : 'fechaEscrituraPFin',
                                id : 'fechaEscrituraPBFin',
                                editable : false,
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '10'}
                              }]
                    }]
            }]

    });
</code>```

The last three are the ones that do not work, i have been trying with a new columnWith, and with but that don't work, any idea?

答:
As per your requirement for column layout. I have worked around to create multiple column in form.

In this FIDDLE, you can check it is working fine. Hope this will guide you or help you to achieve you requirement.

```<code>Ext.onReady(function() {
    var form = new Ext.FormPanel({
        renderTo: Ext.getBody(),
        frame: true,
        title: 'Multi Column, Nested Layouts and Anchoring',
        bodyStyle: 'padding:10px;',
        items: [{
            layout: 'column',
            defaults: {
                columnWidth: .5,
                layout: 'form'
            },
            items: [{
                defaults: {
                    xtype: 'textfield',
                    anchor: '95%',
                },
                items: [{
                    fieldLabel: 'A'
                }, {
                    fieldLabel: 'B'
                }, {
                    fieldLabel: 'C'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 1',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 2',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'datefield',
                    fieldLabel: 'date 1'
                }, {
                    xtype: 'datefield',
                    fieldLabel: 'date 2'
                }]
            }, {
                defaults: {
                    xtype: 'textfield',
                    anchor: '95%'
                },
                items: [{
                    fieldLabel: 'D'
                }, {
                    fieldLabel: 'E'
                }, {
                    fieldLabel: 'F'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 3',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 4',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 5',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }]
            }]
        }],

        buttons: [{
            text: 'Save'
        }, {
            text: 'Cancel'
        }]
    });
});
</code>```

Title: Multiple column in FormPanel ExtJs 3.2

Body:
I am trying to create a form in ExtJs that has rows of two columns and others of three, i have this:

but i want that the fields: "Fecha Escritura", "Acción" y "Fecha Escritura" to be in the same row.

this is my code:

 formBuscador = new Ext.FormPanel({
    labelWidth : 120,
    frame : true,
    title : buscador,
    bodyStyle : 'padding:5px 5px 0',
    width : 1200,
    renderTo : 'gridFormularioBusqueda',
    items : [ {
        //xtype: 'form',
        layout : 'column',
        labelAlign: 'left',
        defaults: {
              xtype: 'container',
              layout: 'form',
              columnWidth: 0.5,
              labelWidth: 185
           },
           items: [
                    {items: [{
                                xtype : 'textfield',
                                fieldLabel : idEmpleado,
                                allowBlank : true,
                                name : 'idEmpleadoP',
                                id : 'idEmpleadoPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '9'}
                            }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : nif,
                                allowBlank : true,
                                name : 'nifP',
                                id : 'nifPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '9'}
                              }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : nombre,
                                allowBlank : false,
                                blankText : campoNoVacioNombre,
                                name : 'nombreP',
                                id : 'nombrePB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '100'}
                              }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : apellidos,
                                allowBlank : false,
                                blankText : campoNoVacioApellido,
                                name : 'apellidosP',
                                id : 'apellidosPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '100'}
                              }]
                    },{items: [{
                                xtype : 'textfield',
                                fieldLabel : notario,
                                allowBlank : false,
                                blankText : campoNoVacioNotario,
                                name : 'notarioP',
                                id : 'notarioPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '75'}
                              }]
                    },{items: [{
                                xtype : 'numberfield',
                                fieldLabel : numeroProtocolo,
                                allowBlank : false,
                                blankText : campoNoVacioNumeroProtocolo,
                                name : 'numeroProtocoloP',
                                id : 'numeroProtocoloPB',
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '5'}
                              }]
                    },{items: [{
                                fieldLabel : incluidaDelegacion,
                                html: "<select id='incluidaDelegacionPB' name='incluidaDelegacionP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:9px;margin-top: 1px;' >" +
                                        "<option id='incluidaDelegacionPBNo' value='false'>No</option>" +
                                        "<option id='incluidaDelegacionPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                fieldLabel : revocacionDelegacion,
                                html: "<select id='revocacionDelegacionBP' name='revocacionDelegacionB' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:9px;margin-top: 6px;' >" +
                                        "<option id='revocacionDelegacionPBNo' value='false'>No</option>" +
                                        "<option id='revocacionDelegacionPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                fieldLabel : revocado,
                                html: "<select id='revocadoPB' name='revocadoP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:10px;margin-top: 1px;' >" +
                                        "<option id='revocadoPBNo' value='false'>No</option>" +
                                        "<option id='revocadoPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                fieldLabel : limiteCuantitativo,
                                html: "<select id='limiteCuantitativoBP' name='limiteCuantitativoP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:10px;margin-top: 1px;' >" +
                                        "<option id='limiteCuantitativoPBNo' value='false'>No</option>" +
                                        "<option id='limiteCuantitativoPBSi' value='true'>Si</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                xtype : 'datefield',
                                fieldLabel : fechaEscritura,
                                allowBlank : false,
                                blankText : campoNoVacioFechaEscritura,
                                labelWidth: 100,
                                name : 'fechaEscrituraP',
                                id : 'fechaEscrituraPB',
                                editable : false,
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '10'}
                              }]
                    },{items: [{
                                fieldLabel : 'Acción',
                                html: "<select id='accionFechaEscrituraBP' name='accionFechaEscrituraBP' style='border-color:#b5b8c8;background-color:white;width:20%;height:95%;margin-bottom:10px;margin-top: 1px;' >" +
                                        "<option id='accionFechaEscrituraBPAnterior' value='Anterior'>Anterior</option>" +
                                        "<option id='accionFechaEscrituraBPPosterior' value='Posterior'>Posterior</option>" +
                                        "<option id='accionFechaEscrituraBPEntre' value='Entre'>Entre</option>" +
                                        "<option id='accionFechaEscrituraBPIgualA' value='IgualA'>Igual A</option>" +
                                        "</select> "
                              }]
                    },{items: [{
                                xtype : 'datefield',
                                fieldLabel : fechaEscritura,
                                allowBlank : false,
                                blankText : campoNoVacioFechaEscritura,
                                name : 'fechaEscrituraPFin',
                                id : 'fechaEscrituraPBFin',
                                editable : false,
                                autoCreate: {tag: 'input', type: 'text', autocomplete: 'off',maxlength: '10'}
                              }]
                    }]
            }]

    });

The last three are the ones that do not work, i have been trying with a new columnWith, and with but that don't work, any idea?

Body:
As per your requirement for column layout. I have worked around to create multiple column in form.

In this FIDDLE, you can check it is working fine. Hope this will guide you or help you to achieve you requirement.

Ext.onReady(function() {
    var form = new Ext.FormPanel({
        renderTo: Ext.getBody(),
        frame: true,
        title: 'Multi Column, Nested Layouts and Anchoring',
        bodyStyle: 'padding:10px;',
        items: [{
            layout: 'column',
            defaults: {
                columnWidth: .5,
                layout: 'form'
            },
            items: [{
                defaults: {
                    xtype: 'textfield',
                    anchor: '95%',
                },
                items: [{
                    fieldLabel: 'A'
                }, {
                    fieldLabel: 'B'
                }, {
                    fieldLabel: 'C'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 1',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 2',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'datefield',
                    fieldLabel: 'date 1'
                }, {
                    xtype: 'datefield',
                    fieldLabel: 'date 2'
                }]
            }, {
                defaults: {
                    xtype: 'textfield',
                    anchor: '95%'
                },
                items: [{
                    fieldLabel: 'D'
                }, {
                    fieldLabel: 'E'
                }, {
                    fieldLabel: 'F'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 3',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 4',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }, {
                    xtype: 'combo',
                    fieldLabel: 'Combo 5',
                    store: new Ext.data.ArrayStore({
                        fields: ['text', 'value'],
                        data: [{
                            abbr: 'yes',
                            state: 'NO'
                        }]
                    }),
                    displayField: 'text',
                    valueField: 'text',
                    typeAhead: true,
                    queryMode: 'local'
                }]
            }]
        }],

        buttons: [{
            text: 'Save'
        }, {
            text: 'Cancel'
        }]
    });
});


问:
collapsable master detail gridview structure
I need an advice for a c# asp.net project.
My client wants to see some reports via the gridview object with master/detail structure.

The main gridview will be full by all master data and each row will have a + icon (or button) on the first cells.
When user clicks this icon, the all details data of that master row should be seen under that master row with collaps action.

I can handle the database proccess but i can not figure out the collapsing part.
How can i put some extra rows under the specific row on the gridview object?

Thanks in advance..

答:
This is the easiest to use control I've ever run across:

http://code.msdn.microsoft.com/CompleteGridView

OwnerDisplayName: Adam Right


问:
CSS Image Split with Two Columns and a Split in the Center
I've looked a bit for this, and can't find it on SO. I basically have to put together a design as follows...

I'm using Bootstrap4 and I'm pretty good at CSS, and this is still giving me a bit of an issue. It should be full-screen, but I'd be open to giving it a max-width of 1400px.

My Idea: I currently had the idea of doing an element with the two elements on the side, and then use transform to rotate, and then put another element inside that has the background image and then uses transform to un-rotate it.

Here's my codepen to show what I've tried -
https://codepen.io/Gwapedwink/pen/ZaPvyo?editors=1100

```<code><section>
  <div class="image-splitter">
    <div class="inner left">
      <span style="background-image:url('http://placehold.it/940x240/222222/fff&text=left"></span>
    </div>
    <div class="inner right">
      <span style="background-image:url('http://placehold.it/940x240/b4d455/fff&text=right"></span>
    </div>
  </div>
</section>
</code>```

with the CSS of:

```<code>.image-splitter {
  background-color: #f1f1f1;
  position: relative; /* allows for absolute inside */
  height: 240px; /* height of this section is 240px */
  width: 100%;
  overflow: hidden; /* important for this idea */
}
.image-splitter .inner {
  position: absolute;
  width:1000px;
  height: 500px;
  top:50%;
  transform:translateY(-50%);
  -webkit-transform:translateY(-50%);
  overflow:hidden;
}
.image-splitter .inner.left {
  right: 50%;
  transform: rotate(5deg) translateY(-50%);
  z-index:10;
}
.image-splitter .inner.right {
  left: 50%;
  z-index:9;
}
.image-splitter .inner span {
  display: block;
  position: absolute;
  top: 50%;
  height:350px;
  width: 100%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  /* background image properties */
  background-position: center;
  background-size: cover;
}
.image-splitter .inner.left span {
  right: -50px;
  transform: rotate(-5deg) translateY(-50%);
  -webkit-transform: rotate(-5deg) translateY(-50%);
}
.image-splitter .inner.right span {
 left: 0;
}
</code>```

You can see that there are so many issues already, and I want to know if I'm missing something that's available. You can see that the text in the codepen should be level, but it isn't.

Thanks in advance!

答:
After recommendations from @dference, it became clear to use clip-path. The issue is of browser compatibility.

So, I took his answer above and then converted it to using SVG - but also had to use foreignObject to allow Edge support.

```<code>  <div class="image-splitter">
    <div class="inner left" style="background-image:url('https://picsum.photos/760/240?image=1067"></div>
    <div class="inner right">

    <!-- SVG CLIP -->
    <svg width="100%" height="240px">
      <defs>
        <clipPath id="clipPolygon">
          <polygon points="0 240,2000 240,2000 0,50 0">
          </polygon>
        </clipPath>
      </defs>
      <foreignObject clip-path="url(#clipPolygon)" width="100%" height="100%">
        <img src="https://picsum.photos/760/240?image=1049">
      </foreignObject>
    </svg>
    <!-- / SVG CLIP -->

    </div> <!-- /.inner.right -->
  </div> <!-- /.image-splitter -->
</code>```

Throw that in with the CSS

```<code>/* image splitter */

.image-splitter {
  position: relative;
  height: 230px;
  overflow: hidden;
  & .inner {
    overflow: hidden;
    width: 60%;
    height: 240px;
    background: transparent no-repeat center center / cover;
  }
  & .right {
    position: absolute;
    top: 0;
    width:50%;
    right: 0;
    /*-webkit-clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);
    clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);*/

    /* Clipping */
    -webkit-clip-path: polygon(0px 240px,2000px 240px,2000px 0px,50px 0px);
    clip-path: url("#clipPolygon");
    & img {
      width: 100%;
      min-height: 240px;
    }
  }
}
</code>```

You can take a look at this at my codepen - and you can also see the neat way that I did the content splitter below also.

Body:
I've looked a bit for this, and can't find it on SO. I basically have to put together a design as follows...

I'm using Bootstrap4 and I'm pretty good at CSS, and this is still giving me a bit of an issue. It should be full-screen, but I'd be open to giving it a max-width of 1400px.

My Idea: I currently had the idea of doing an element with the two elements on the side, and then use transform to rotate, and then put another element inside that has the background image and then uses transform to un-rotate it.

Here's my codepen to show what I've tried -
https://codepen.io/Gwapedwink/pen/ZaPvyo?editors=1100

with the CSS of:

.image-splitter {
  background-color: #f1f1f1;
  position: relative; /* allows for absolute inside */
  height: 240px; /* height of this section is 240px */
  width: 100%;
  overflow: hidden; /* important for this idea */
}
.image-splitter .inner {
  position: absolute;
  width:1000px;
  height: 500px;
  top:50%;
  transform:translateY(-50%);
  -webkit-transform:translateY(-50%);
  overflow:hidden;
}
.image-splitter .inner.left {
  right: 50%;
  transform: rotate(5deg) translateY(-50%);
  z-index:10;
}
.image-splitter .inner.right {
  left: 50%;
  z-index:9;
}
.image-splitter .inner span {
  display: block;
  position: absolute;
  top: 50%;
  height:350px;
  width: 100%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  /* background image properties */
  background-position: center;
  background-size: cover;
}
.image-splitter .inner.left span {
  right: -50px;
  transform: rotate(-5deg) translateY(-50%);
  -webkit-transform: rotate(-5deg) translateY(-50%);
}
.image-splitter .inner.right span {
 left: 0;
}

You can see that there are so many issues already, and I want to know if I'm missing something that's available. You can see that the text in the codepen should be level, but it isn't.

Thanks in advance!

Body:
After recommendations from @dference, it became clear to use clip-path. The issue is of browser compatibility.

So, I took his answer above and then converted it to using SVG - but also had to use foreignObject to allow Edge support.

  <div class="image-splitter">
    <div class="inner left" style="background-image:url('https://picsum.photos/760/240?image=1067"></div>
    <div class="inner right">

    <!-- SVG CLIP -->
    <svg width="100%" height="240px">
      <defs>
        <clipPath id="clipPolygon">
          <polygon points="0 240,2000 240,2000 0,50 0">
          </polygon>
        </clipPath>
      </defs>
      <foreignObject clip-path="url(#clipPolygon)" width="100%" height="100%">
        <img src="https://picsum.photos/760/240?image=1049">
      </foreignObject>
    </svg>
    <!-- / SVG CLIP -->

    </div> <!-- /.inner.right -->
  </div> <!-- /.image-splitter -->

Throw that in with the CSS

/* image splitter */

.image-splitter {
  position: relative;
  height: 230px;
  overflow: hidden;
  & .inner {
    overflow: hidden;
    width: 60%;
    height: 240px;
    background: transparent no-repeat center center / cover;
  }
  & .right {
    position: absolute;
    top: 0;
    width:50%;
    right: 0;
    /*-webkit-clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);
    clip-path: polygon(calc(16.667% + 50px) 0%, 100% 0%, 100% 100%, 16.667% 100%);*/

    /* Clipping */
    -webkit-clip-path: polygon(0px 240px,2000px 240px,2000px 0px,50px 0px);
    clip-path: url("#clipPolygon");
    & img {
      width: 100%;
      min-height: 240px;
    }
  }
}

You can take a look at this at my codepen - and you can also see the neat way that I did the content splitter below also.


问:
How to extract only one string from regex in Python?
I have been trying to build a simple account manager sort of application for myself using Python which will read SMS from my phone and extract information based on some regex patterns.

I wrote a complex regex pattern and tested the same on https://pythex.org/.
Example:

```<code>Text: 1.00 is debited from ******1234  for food

Pattern: (account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)

Result: from ******1234
</code>```

However, when I try to do the same in Python using the str.extract() method, rather than getting a single result, I am getting a dataframe with a column for each group.

Python code looks like this:

```<code>all_sms=pd.read_csv("all_sms.csv")

pattern = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)'

test = all_sms.extract(pattern, expand = False)
</code>```

Output of the python code for the message above:

```<code>0           from
1
2            NaN
3            NaN
4            NaN
5     ******1234
6           1234
7           1234
8
9
10
</code>```

I am very new to Python and trying to learn by hands-on experience, it would be really helpful if someone can point out where I am going wrong with this?

答:
Before diving into your regex pattern you should understand why you are using
pandas. Pandas is suitable for data analysis (thus suitable for your problem)
but seems like an overkill here.

If you are a beginner I advice you to stick with pure python not because pandas
is complicated but because knowing the python standard library will help you in
the long run. If you skip the basics now this may hurt you in the long run.

Considering you are going to use python3 (without pandas) I would proceed as
follow:

```<code># Needed imports from standard library.
import csv
import re

# Declare the constants of my tiny program.
PATTERN = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)'
COMPILED_REGEX = re.compile(PATTERN)

# This list will store the matched regex.
found_regexes = list()

# Do the necessary loading to enable searching for the regex.
with open('mysmspath.csv', newline='') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=' ', quotechar='"')
    # Iterate over rows in your csv file.
    for row in csv_reader:
        match = COMPILED_REGEX.search(row)
        if match:
            found_regexes.append(row)

print(found_regexes)
</code>```

Not necessarily this is going to solve your problem with copy-paste but this might give you an
idea of a more simpler approach to your problem.

Body:
I have been trying to build a simple account manager sort of application for myself using Python which will read SMS from my phone and extract information based on some regex patterns.

I wrote a complex regex pattern and tested the same on https://pythex.org/.
Example:

Text: 1.00 is debited from ******1234  for food

Pattern: (account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)

Result: from ******1234

However, when I try to do the same in Python using the str.extract() method, rather than getting a single result, I am getting a dataframe with a column for each group.

Python code looks like this:

all_sms=pd.read_csv("all_sms.csv")

pattern = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)'

test = all_sms.extract(pattern, expand = False)

Output of the python code for the message above:

0           from
1
2            NaN
3            NaN
4            NaN
5     ******1234
6           1234
7           1234
8
9
10

I am very new to Python and trying to learn by hands-on experience, it would be really helpful if someone can point out where I am going wrong with this?

Body:
Before diving into your regex pattern you should understand why you are using
pandas. Pandas is suitable for data analysis (thus suitable for your problem)
but seems like an overkill here.

If you are a beginner I advice you to stick with pure python not because pandas
is complicated but because knowing the python standard library will help you in
the long run. If you skip the basics now this may hurt you in the long run.

Considering you are going to use python3 (without pandas) I would proceed as
follow:

# Needed imports from standard library.
import csv
import re

# Declare the constants of my tiny program.
PATTERN = '(account|a\/c|ac|from|acct|savings|credit in|ac\/|sb\-|acc|a\/c)(\s|\.|\-)*(no|number)*(\.|\s|:)*\s*(ending)*\s*(((n{1,}|x{1,}|[0-9]+|\*{1,}))+)\-*((n{1,}|x{1,}|[0-9]+|\*{1,}|\s))*\-*([0-9]*)'
COMPILED_REGEX = re.compile(PATTERN)

# This list will store the matched regex.
found_regexes = list()

# Do the necessary loading to enable searching for the regex.
with open('mysmspath.csv', newline='') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=' ', quotechar='"')
    # Iterate over rows in your csv file.
    for row in csv_reader:
        match = COMPILED_REGEX.search(row)
        if match:
            found_regexes.append(row)

print(found_regexes)

Not necessarily this is going to solve your problem with copy-paste but this might give you an
idea of a more simpler approach to your problem.


问:
Windows Service running but event logs not working
I have a windows service listening to messages from a queue but the messages are not read from the queue.I created an event log to check for logs during service startup and shutdown but the logs are not written. I do not want to debug the service since it is a painful process.Is there a way to solve this issue.The messages need to be read by the service and written to a database.</p>

答: If you want to use logging instead of debugging don't use the event log. Use plain old text logs.</p>

OwnerDisplayName: kjayakum

LastEditorDisplayName: Ben Alpert

OwnerDisplayName: Igal Serban


问:
iOS app crashes upon opening when switching rotation views
I am trying to develop an app in XCode that will switch to a new view upon rotation.

Here is the code for view1controller.h:

```<code>#import UIKit/UIKit.h

@interface TestViewController : UIViewController {}

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end
</code>```

and here is the code for view1controller.m:

```<code>#import "view1controller.h"

@implementation TestViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
    {
        self.view = landscape;
    } else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
        self.view = portrait;
    }

    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@synthesize portrait,landscape;

@end
</code>```

Anyway so the app opens but it crashes upon opening.

答:
Try something like:</p>

```<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        self.view = landscapeleft;
    }

    if (interfaceOrientation == UIInterfaceOrientationPortrait)
    {
        self.view = portrait;
    }

    if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        self.view = portraitupsidedown;
    }

    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        self.view = landscapeleft;
    }

    return YES;
}
</code>```

Body:
I am trying to develop an app in XCode that will switch to a new view upon rotation.

Here is the code for view1controller.h:

#import UIKit/UIKit.h

@interface TestViewController : UIViewController {}

IBOutlet UIView *portrait;
IBOutlet UIView *landscape;

@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *landscape;

@end

and here is the code for view1controller.m:

#import "view1controller.h"

@implementation TestViewController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight)))
    {
        self.view = landscape;
    } else if (((interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))) {
        self.view = portrait;
    }

    return YES;
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

@synthesize portrait,landscape;

@end

Anyway so the app opens but it crashes upon opening.

Body:
Try something like:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
    {
        self.view = landscapeleft;
    }

    if (interfaceOrientation == UIInterfaceOrientationPortrait)
    {
        self.view = portrait;
    }

    if (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        self.view = portraitupsidedown;
    }

    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
        self.view = landscapeleft;
    }

    return YES;
}


问:
How to publish a react based component through npm without including react?
I have a simple component that requires react and mobx to use. When I build my library through webpack, it is including react and mobx and mobx-react in the bundle. However I would like to add them as a peer dependency and let the user of my module install the libraries.

Is this possible? My webpack config looks like this and it builds nicely into dist/build.js I just need to work out how to exclude the libraries.

```<code>module.exports = {
    entry: [ './index.js' ],
    output: {
        path: path.resolve('./dist'),
        filename: 'build.js',
        library: 'myLibrary',
        libraryTarget: 'commonjs'
    },
    module: {
        rules: loaders
    },
    plugins: [
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]
}
</code>```

答:
You have to mark as "external" dependency in your package.json:

```<code>externals: { 'react': 'commonjs react' }
</code>```

Here is a short but very useful article about publishing components on npm flawlessy:

https://medium.com/@BrodaNoel/how-to-create-a-react-component-and-publish-it-in-npm-668ad7d363ce

Body:
I have a simple component that requires react and mobx to use. When I build my library through webpack, it is including react and mobx and mobx-react in the bundle. However I would like to add them as a peer dependency and let the user of my module install the libraries.

Is this possible? My webpack config looks like this and it builds nicely into dist/build.js I just need to work out how to exclude the libraries.

module.exports = {
    entry: [ './index.js' ],
    output: {
        path: path.resolve('./dist'),
        filename: 'build.js',
        library: 'myLibrary',
        libraryTarget: 'commonjs'
    },
    module: {
        rules: loaders
    },
    plugins: [
        new webpack.NoEmitOnErrorsPlugin(),
        new webpack.optimize.UglifyJsPlugin({
            sourceMap: true,
            compress: {
                warnings: false
            }
        })
    ]
}

Body:
You have to mark as "external" dependency in your package.json:

externals: { 'react': 'commonjs react' }

Here is a short but very useful article about publishing components on npm flawlessy:

https://medium.com/@BrodaNoel/how-to-create-a-react-component-and-publish-it-in-npm-668ad7d363ce


问:
updating a chart in chart.JS using a dropdown button
I am using chart.Js to render charts in an application.
What I am looking for is to give the user to be able to compare two dataset using a dropdown button.

I tried to edit something I found but I can manage to make it work.
I tried that code :

```<code> document.getElementById('test').addEventListener('click', function() {
      var newDataset = {
        label: 'Dataset ' + config.data.datasets.length,
        backgroundColor: "black",
        borderColor: "black",
        data: [],
        fill: false
      };
      for (var index = 0; index < config.data.labels.length; ++index) {
        newDataset.data.push(randomScalingFactor());
      }
      config.data.datasets.push(newDataset);
      window.myLine.update();
    });
</code>```

I created a JSfiddle with all the code to give you an overview:
https://jsfiddle.net/ben2pop/219hry2s/36/

答:
You need to place the ID test on the select box and not the option.
Change

```<code>document.getElementById('test').addEventListener('click', function() {
</code>```

To

```<code>document.getElementById('test').addEventListener('change', function(e) {
</code>```

now you can access the value of the change by e.target.val and decide what data you want to insert / remove based on the user interaction.

Body:
I am using chart.Js to render charts in an application.
What I am looking for is to give the user to be able to compare two dataset using a dropdown button.

I tried to edit something I found but I can manage to make it work.
I tried that code :

 document.getElementById('test').addEventListener('click', function() {
      var newDataset = {
        label: 'Dataset ' + config.data.datasets.length,
        backgroundColor: "black",
        borderColor: "black",
        data: [],
        fill: false
      };
      for (var index = 0; index < config.data.labels.length; ++index) {
        newDataset.data.push(randomScalingFactor());
      }
      config.data.datasets.push(newDataset);
      window.myLine.update();
    });

I created a JSfiddle with all the code to give you an overview:
https://jsfiddle.net/ben2pop/219hry2s/36/

Body:
You need to place the ID test on the select box and not the option.
Change

document.getElementById('test').addEventListener('click', function() {

To

document.getElementById('test').addEventListener('change', function(e) {

now you can access the value of the change by e.target.val and decide what data you want to insert / remove based on the user interaction.


问:
router link attribute within the button tag doesnt work
I am unable to navigate with router link attribute that is placed within the button tag. Here is my code,</p>

```<code><button mat-raised-button color="primary"><a routerLink="/message-inbox">Inbox</a></button>
    <button mat-raised-button color="accent"><a routerLink="/sent">Sent</a></button>
    <a routerLink="/message-compose"><button color="warn">Compose</button></a>
</code>```

答:
I dint import the the router module. It worked after that,</p>

```<code>import { RouterModule } from '@angular/router';
</code>```

Body:
I am unable to navigate with router link attribute that is placed within the button tag. Here is my code,

<button mat-raised-button color="primary">Inbox</button>
    <button mat-raised-button color="accent">Sent</button>
    <button color="warn">Compose</button>

Body:
I dint import the the router module. It worked after that,

import { RouterModule } from '@angular/router';


问:
Unexpected output when multiple threads update same variable
```<code>#include<stdio.h>
#include<pthread.h>
#define NUM_THREAD (5)

int sum=0;
void* runner(void * param);

int main(int argc,char **argv){

    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for(i=0;i<NUM_THREAD;i++){
    pthread_create(&tid[i],&attr,runner,NULL);
    }
    for(i=0;i<NUM_THREAD;i++){
    pthread_join(tid[i],NULL);
            }
    printf("After threading %d",sum);
    return 0;
}

void * runner(void *param){
    for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}
</code>```

output: 225

In the following code, the output is 225. But the correct should be 45

I know threads share global variables!. so this function should correctly output right. But adding that sum=0 inside only gives correct output.  Whats happening here I don't understand!

```<code>void * runner(void *param){
sum=0;   // MY DOUBT
for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}
</code>```

output: 45

答:
You have data race because sum is accessed/modified by all threads without any synchronisation. So both 45 and 225 are "wrong". You may see different values in different runs. You need to synchronize the access to sum.

Another thing to note you haven't initialized attr that you pass to pthread_create. You need to initialize it with pthread_attr_init.

Body:
#include<stdio.h>
#include<pthread.h>
#define NUM_THREAD (5)

int sum=0;
void* runner(void * param);

int main(int argc,char **argv){

    pthread_t tid[NUM_THREAD];
    pthread_attr_t attr;
    pthread_attr_init(&attr);

    for(i=0;i<NUM_THREAD;i++){
    pthread_create(&tid[i],&attr,runner,NULL);
    }
    for(i=0;i<NUM_THREAD;i++){
    pthread_join(tid[i],NULL);
            }
    printf("After threading %d",sum);
    return 0;
}

void * runner(void *param){
    for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}

output: 225

In the following code, the output is 225. But the correct should be 45

I know threads share global variables!. so this function should correctly output right. But adding that sum=0 inside only gives correct output.  Whats happening here I don't understand!

void * runner(void *param){
sum=0;   // MY DOUBT
for(int j = 0;j<10;j++)  sum+=j;
    pthread_exit(0);

}

output: 45


问:
CS0188 Error in Structure
Take a look at this code.

```<code>public struct Customer
{
    private int _id;
    private string _name;

    public int Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // Error - CS0188: The 'this' object cannot be used before all of its fields are assigned to.
        this._name = Name;
    }
}
</code>```

`
Why do I get this error on the above line.

Now look at this code.

```<code>public struct Customer
{
    private string _name;
    public int Id { get; set; }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // No error recieved.
        this._name = Name;
    }
}
</code>```

In the above code I implemented Id as an Auto-Implemented property.
This time I don't get any errors. Why?

Just to make it clear following link does not have my answer.

Compilation error. Using properties with struct

答:
You need to initialize all the fields of struct first. When you assign a value to an Auto-Implemented property it always sets the backing field, however, with custom setters, it's not always guaranteed. That's why you don't get any error

For custom properties:

```<code>public struct Customer
{
    private int _id;
    private string _name;

    public int Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public Customer(int Id, string Name)
    {
        _id=0;
        this._name = Name;
        this.Id = Id; // This will work now
    }
}
</code>```

Title: CS0188 Error in Structure

Body:
Take a look at this code.

public struct Customer
{
    private int _id;
    private string _name;

    public int Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // Error - CS0188: The 'this' object cannot be used before all of its fields are assigned to.
        this._name = Name;
    }
}

`
Why do I get this error on the above line.

Now look at this code.

public struct Customer
{
    private string _name;
    public int Id { get; set; }

    public Customer(int Id, string Name)
    {
        this.Id = Id; // No error recieved.
        this._name = Name;
    }
}

In the above code I implemented Id as an Auto-Implemented property.
This time I don't get any errors. Why?

Just to make it clear following link does not have my answer.

Compilation error. Using properties with struct

Body:
You need to initialize all the fields of struct first. When you assign a value to an Auto-Implemented property it always sets the backing field, however, with custom setters, it's not always guaranteed. That's why you don't get any error

For custom properties:

public struct Customer
{
    private int _id;
    private string _name;

    public int Id
    {
        get { return this._id; }
        set { this._id = value; }
    }

    public Customer(int Id, string Name)
    {
        _id=0;
        this._name = Name;
        this.Id = Id; // This will work now
    }
}