问:
Angular JWT Profile user(getting field of json)
I have a gettProfile() method which includes below code:

```<code>gettProfile(){
    var headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    let options = new RequestOptions({headers: headers});
    return this.http.get('http://localhost:3000/api/profile', options)
      .map(res => res.json()); //res.json() localStorage.getItem('students')
  }
</code>```

In this code, when I write console.log(this.authToken); It shows right JWT Token. But when I pass this data to my ProfileComponent it says:

ERROR TypeError: Cannot read property 'name' of undefined

Profile.component.ts code is below:

```<code>  export class ProfileComponent implements OnInit {
        students: Object;
          constructor(private authService:AuthService,  private router:Router) { }

          ngOnInit() {
            this.authService.gettProfile().subscribe(profile =>
            {
              this.students= profile.students;
            },
            err => {
              console.log(err);
              return false;
            });
          }
}
</code>```

Profile.component.html code:

```<code><div class="col-md-6 col-md-offset-3">
    <h1>Hi {{students.name}}!</h1>
    <p>You're logged in!!</p>
    <h3>Registered user detail:</h3>
    <ul>
        <li *ngIf="students">
            {{students.email}} ({{students.surname}} {{students.address}})
        </li>
    </ul>
    <p><a [routerLink]="['/login']">Logout</a></p>
</div>
</code>```

When I look into LocalStorage:

```<code>students:
{"id":"5960fa785017042b9c54f05c","name":"aaa","surname":"aaa","email":"aaa@gmail.com","address":"aaaa","phoneNumber":"aaaa"}
token: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQiOnt9LCJnZXR0ZXJzIjp7fSwiX2lkIjoiNTk2MGZhNzg1MDE3MDQyYjljNTRmMDVjIiwid2FzUG9wdWxhdGVkIjpmYWxzZFeiYWN0aXZlUGF0aHMiOnsicGF0aHMiOnsicGFzc3dvcmQiOiJpbml0IiwiZW1haWwiOiJpbml0IiwiX192IjoiaW5pdCIsInBob25lTnVtYmVyIjoiaW5pdCIsImFkZHJlc3MiOiJpbml0Iiwic3VybmFtZSI6ImluaXQiLCJuYW1lIjoiaW5pdCIsIl9pZCI6ImluaXQifSwic3RhdGVzIjp7Imlnbm9yZSI6e30sImRlZmF1bHQiOnt9LCJpbml0Ijp7Il9fdiI6dHJ1ZSwicGhvbmVOdW1iZXIiOnRydWUsImFkZHJlc3MiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwic3VybmFtZSI6dHJ1ZSwibmFtZSI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwicGF0aHNUb1Njb3BlcyI6e30sImVtaXR0ZXIiOnsiZG9tYWluIjpudWxsLCJfZXZlbnRzIjp7fSwiX2V2ZW50c0NvdW50IjowLCJfbWF4TGlzdGVuZXJzIjowfX0sImlzTmV3IjpmYWxzZSwiX2RvYyI6eyJfX3YiOjAsInBob25lTnVtYmVyIjoiYWFhYSIsImFkZHJlc3MiOiJhYWFhIiwicGFzc3dvcmQiOiIkMmEkMTAkeDlGcTd1SlBIL3VHeUlEeUd3dnRwdUxlS0w2ZVFTTFpJRzRGVVBQQ2loOGg3RVNwZENPN08iLCJlbWFpbCI6ImFhYUBnbWFpbC5jb20iLCJzdXJuYW1lIjoiYWFhIiwibmFtZSI6ImFhYSIsIl9pZCI6IjU5NjBmYTc4NTAxNzA0MmI5YzU0ZjA1YyJ9LCIkaW5pdCI6dHJ1ZSwiaWF0IjoxNDk5NTI5NzA5LCJleHAiOjE1MDAxMzQ1MDl9.UEtThW_30lmPeIUCa8sIZtCfjtb4ek6qWxXyKpnWveI
</code>```

My register and authentication work well. But Profile does not work.

How can I handle with this problem?

答:
When angular first tries to access students it get's undefined as the getProfile method is asynchronous. So you should declare an empty Object as below:

```<code>export class ProfileComponent implements OnInit {
    students: Object = {};
    // rest of the code as it is
</code>```

Body:
I have a gettProfile() method which includes below code:

gettProfile(){
    var headers = new Headers();
    this.loadToken();
    headers.append('Authorization', this.authToken);
    headers.append('Content-Type','application/json');
    let options = new RequestOptions({headers: headers});
    return this.http.get('http://localhost:3000/api/profile', options)
      .map(res => res.json()); //res.json() localStorage.getItem('students')
  }

In this code, when I write console.log(this.authToken); It shows right JWT Token. But when I pass this data to my ProfileComponent it says:

ERROR TypeError: Cannot read property 'name' of undefined

Profile.component.ts code is below:

  export class ProfileComponent implements OnInit {
        students: Object;
          constructor(private authService:AuthService,  private router:Router) { }

          ngOnInit() {
            this.authService.gettProfile().subscribe(profile =>
            {
              this.students= profile.students;
            },
            err => {
              console.log(err);
              return false;
            });
          }
}

Profile.component.html code:

Hi {{students.name}}!

You're logged in!!

Registered user detail:

            {{students.email}} ({{students.surname}} {{students.address}})

Logout

When I look into LocalStorage:

students:
{"id":"5960fa785017042b9c54f05c","name":"aaa","surname":"aaa","email":"aaa@gmail.com","address":"aaaa","phoneNumber":"aaaa"}
token: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyIkX18iOnsic3RyaWN0TW9kZSI6dHJ1ZSwic2VsZWN0ZWQiOnt9LCJnZXR0ZXJzIjp7fSwiX2lkIjoiNTk2MGZhNzg1MDE3MDQyYjljNTRmMDVjIiwid2FzUG9wdWxhdGVkIjpmYWxzZFeiYWN0aXZlUGF0aHMiOnsicGF0aHMiOnsicGFzc3dvcmQiOiJpbml0IiwiZW1haWwiOiJpbml0IiwiX192IjoiaW5pdCIsInBob25lTnVtYmVyIjoiaW5pdCIsImFkZHJlc3MiOiJpbml0Iiwic3VybmFtZSI6ImluaXQiLCJuYW1lIjoiaW5pdCIsIl9pZCI6ImluaXQifSwic3RhdGVzIjp7Imlnbm9yZSI6e30sImRlZmF1bHQiOnt9LCJpbml0Ijp7Il9fdiI6dHJ1ZSwicGhvbmVOdW1iZXIiOnRydWUsImFkZHJlc3MiOnRydWUsInBhc3N3b3JkIjp0cnVlLCJlbWFpbCI6dHJ1ZSwic3VybmFtZSI6dHJ1ZSwibmFtZSI6dHJ1ZSwiX2lkIjp0cnVlfSwibW9kaWZ5Ijp7fSwicmVxdWlyZSI6e319LCJzdGF0ZU5hbWVzIjpbInJlcXVpcmUiLCJtb2RpZnkiLCJpbml0IiwiZGVmYXVsdCIsImlnbm9yZSJdfSwicGF0aHNUb1Njb3BlcyI6e30sImVtaXR0ZXIiOnsiZG9tYWluIjpudWxsLCJfZXZlbnRzIjp7fSwiX2V2ZW50c0NvdW50IjowLCJfbWF4TGlzdGVuZXJzIjowfX0sImlzTmV3IjpmYWxzZSwiX2RvYyI6eyJfX3YiOjAsInBob25lTnVtYmVyIjoiYWFhYSIsImFkZHJlc3MiOiJhYWFhIiwicGFzc3dvcmQiOiIkMmEkMTAkeDlGcTd1SlBIL3VHeUlEeUd3dnRwdUxlS0w2ZVFTTFpJRzRGVVBQQ2loOGg3RVNwZENPN08iLCJlbWFpbCI6ImFhYUBnbWFpbC5jb20iLCJzdXJuYW1lIjoiYWFhIiwibmFtZSI6ImFhYSIsIl9pZCI6IjU5NjBmYTc4NTAxNzA0MmI5YzU0ZjA1YyJ9LCIkaW5pdCI6dHJ1ZSwiaWF0IjoxNDk5NTI5NzA5LCJleHAiOjE1MDAxMzQ1MDl9.UEtThW_30lmPeIUCa8sIZtCfjtb4ek6qWxXyKpnWveI

My register and authentication work well. But Profile does not work.

How can I handle with this problem?

Body:
When angular first tries to access students it get's undefined as the getProfile method is asynchronous. So you should declare an empty Object as below:

export class ProfileComponent implements OnInit {
    students: Object = {};
    // rest of the code as it is


来源: stackexchange

问:
Can i retrieve array value not using loop?
is there a way to retrieve array value not using any loop function?
I have this sort of array</p>

```<code>$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),
</code>```

答:
try array_values

Sorry this one was suppose to be a comment.

ContentLicense: CC BY-SA 2.5

Body:
is there a way to retrieve array value not using any loop function?
I have this sort of array

$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),


问:
move instruction from eax to es register gives error
i cant figure out a way to move code from one location to other in memory

so i put in a way some thing like this but it doesn't work

```<code>extern _transfer_code_segment

 extern _kernel_segment

  extern _kernel_reloc

 extern _kernel_reloc_segment

  extern _kernel_para_size

    section .text16

    global transfer_to_kernel

transfer_to_kernel:

    ;cld

    ;
    ; Turn off interrupts -- the stack gets destroyed during this routine.
    ; kernel must set up its own stack.
    ;
    ;cli
    ; stack for only for this function

    push ebp
    mov ebp, esp

    mov eax, _kernel_segment             ; source segment
    mov ebx, _kernel_reloc_segment       ; dest segment
    mov ecx, _kernel_para_size

.loop:

    ; XXX: Will changing the segment registers this many times have
    ; acceptable performance?

    mov ds, eax  ;this the place where the error
    mov es, ebx  ; this to
    xor esi, esi
    xor edi, edi
    movsd
    movsd
    movsd
    movsd
    inc eax
    inc ebx
    dec ecx
    jnz .loop

    leave
    ret
</code>```

do have any other way to do it or how can i solve this problem

答:
The segment registers are all 16 bits in size. Compare that to the e?x registers, which are 32 bits in size. Obviously, these two things are not the same size, prompting your assembler to generate an "operand size mismatch" error—the sizes of the two operands do not match.

Presumably, you want to initialize the segment register with the lower 16 bits of the register, so you would do something like:

```<code>mov  ds, ax
mov  es, bx
</code>```

Also, no, you don't actually need to initialize the segment registers on each iteration of the loop. What you're doing now is incrementing the segment and forcing the offset to 0, then copying 4 DWORDs. What you should be doing is leaving the segment alone and just incrementing the offset (which the MOVSD instruction does implicitly).

```<code>    mov eax, _kernel_segment             ; TODO: see why these segment values are not
    mov ebx, _kernel_reloc_segment       ;        already stored as 16 bit values
    mov ecx, _kernel_para_size

    mov ds, ax
    mov es, bx

    xor esi, esi
    xor edi, edi

.loop:

    movsd
    movsd
    movsd
    movsd

    dec  ecx
    jnz .loop
</code>```

But note that adding the REP prefix to the MOVSD instruction would allow you to do this even more efficiently. This basically does MOVSD a total of ECX times. For example:

```<code>mov ds, ax
mov es, bx
xor esi, esi
xor edi, edi
shl ecx, 2         ; adjust size since we're doing 1 MOVSD for each ECX, rather than 4
rep movsd
</code>```

Somewhat counter-intuitively, if your processor implements the ERMSB optimization (Intel Ivy Bridge and later), REP MOVSB may actually be faster than REP MOVSD, so you could do:

```<code>mov ds, ax
mov es, bx
xor esi, esi
xor edi, edi
shl ecx, 4
rep movsb
</code>```

Finally, although you've commented out the CLD instruction in your code, you do need to have this in order to ensure that the moves happen according to plan. You cannot rely on the direction flag having a particular value; you need to initialize it yourself to the value that you want.

(Another alternative would be streaming SIMD instructions or even floating-point stores, neither of which would care about the direction flag. This has the advantage of increasing memory copy bandwidth because you'd be doing 64-bit, 128-bit, or larger copies at a time, but introduces other disadvantages. In a kernel, I'd stick with MOVSD/MOVSB unless you can prove isn't a significant bottleneck and/or you want to have optimized paths for different processors.)

ContentLicense: CC BY-SA 3.0

Body:
i cant figure out a way to move code from one location to other in memory

so i put in a way some thing like this but it doesn't work

extern _transfer_code_segment

 extern _kernel_segment

  extern _kernel_reloc

 extern _kernel_reloc_segment

  extern _kernel_para_size

    section .text16

    global transfer_to_kernel

transfer_to_kernel:

    ;cld

    ;
    ; Turn off interrupts -- the stack gets destroyed during this routine.
    ; kernel must set up its own stack.
    ;
    ;cli
    ; stack for only for this function

    push ebp
    mov ebp, esp

    mov eax, _kernel_segment             ; source segment
    mov ebx, _kernel_reloc_segment       ; dest segment
    mov ecx, _kernel_para_size

.loop:

    ; XXX: Will changing the segment registers this many times have
    ; acceptable performance?

    mov ds, eax  ;this the place where the error
    mov es, ebx  ; this to
    xor esi, esi
    xor edi, edi
    movsd
    movsd
    movsd
    movsd
    inc eax
    inc ebx
    dec ecx
    jnz .loop

    leave
    ret

do have any other way to do it or how can i solve this problem

Body:
The segment registers are all 16 bits in size. Compare that to the e?x registers, which are 32 bits in size. Obviously, these two things are not the same size, prompting your assembler to generate an "operand size mismatch" error—the sizes of the two operands do not match.

Presumably, you want to initialize the segment register with the lower 16 bits of the register, so you would do something like:

mov  ds, ax
mov  es, bx

Also, no, you don't actually need to initialize the segment registers on each iteration of the loop. What you're doing now is incrementing the segment and forcing the offset to 0, then copying 4 DWORDs. What you should be doing is leaving the segment alone and just incrementing the offset (which the MOVSD instruction does implicitly).

    mov eax, _kernel_segment             ; TODO: see why these segment values are not
    mov ebx, _kernel_reloc_segment       ;        already stored as 16 bit values
    mov ecx, _kernel_para_size

    mov ds, ax
    mov es, bx

    xor esi, esi
    xor edi, edi

.loop:

    movsd
    movsd
    movsd
    movsd

    dec  ecx
    jnz .loop

But note that adding the REP prefix to the MOVSD instruction would allow you to do this even more efficiently. This basically does MOVSD a total of ECX times. For example:

mov ds, ax
mov es, bx
xor esi, esi
xor edi, edi
shl ecx, 2         ; adjust size since we're doing 1 MOVSD for each ECX, rather than 4
rep movsd

Somewhat counter-intuitively, if your processor implements the ERMSB optimization (Intel Ivy Bridge and later), REP MOVSB may actually be faster than REP MOVSD, so you could do:

mov ds, ax
mov es, bx
xor esi, esi
xor edi, edi
shl ecx, 4
rep movsb

Finally, although you've commented out the CLD instruction in your code, you do need to have this in order to ensure that the moves happen according to plan. You cannot rely on the direction flag having a particular value; you need to initialize it yourself to the value that you want.

(Another alternative would be streaming SIMD instructions or even floating-point stores, neither of which would care about the direction flag. This has the advantage of increasing memory copy bandwidth because you'd be doing 64-bit, 128-bit, or larger copies at a time, but introduces other disadvantages. In a kernel, I'd stick with MOVSD/MOVSB unless you can prove isn't a significant bottleneck and/or you want to have optimized paths for different processors.)


问:
2 classes for 1 div, class has space in name
I want to give a div 2 classes, however, one of the class names has a space in it. I want to give a div the "section scrollspy" class and carousel class.

Will putting a space in between classes still work?

For example:

```<code><div class="section scrollspy carousel">
</code>```

Or is there a better way to do this?

答:
If you want to preserve the space character, you'll have to update your css :

```<code>.section.scrollspy {
   // css rules
}
</code>```

but it's still two class here. If you want to use just one class, you'll have to use Peter Featherstone's answer :

Body:
I want to give a div 2 classes, however, one of the class names has a space in it. I want to give a div the "section scrollspy" class and carousel class.

Will putting a space in between classes still work?

For example:

Or is there a better way to do this?

Body:
If you want to preserve the space character, you'll have to update your css :

.section.scrollspy {
   // css rules
}

but it's still two class here. If you want to use just one class, you'll have to use Peter Featherstone's answer :

<div class="section-scrollspy carousel">


问:
Plot one histogram(separate) for each variable in the column
I want to plot one histogram(separate) for each variable in the column. The data is import using a CSV file(sample.csv) and looks like

```<code>ip_addr_player_id,  event_name, level, points_earned, stars_earned, moves
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 2, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 3, 1000, 2,   2
203.166.252.219, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,  2
54.166.252.324, Puzzle Complete, Botany Lab Puzzle 5, 1000, 2,  2
</code>```

Given each ip_addr_player_id is unique, I want to plot histograms (for each ip_addr_payer_id) for points_earned, starts_earned and moves.

I tried this based on an example I could find online;

```<code> library(readr)
 dataIn <- read.csv("sample.csv")
 #View(dataIn)
 library(ggplot2)
 plot <- ggplot(dataIn, aes(level, points_earned, fill=points_earned))+
              geom_histogram() + facet_wrap(~ip_addr_player_id)
 plot
</code>```

But this code gives me no output.

答:
You could use loops for example</p>

```<code>X = your_dataframe

vector_of_levels_you_want = 1:ncol(your_dataframe)

subset_level_1 = your_dataframe[which(your_dataframe[,column_of_your_level] == "Botany Lab Puzzle 1"),]
subset_level_2 = your_dataframe[which(your_dataframe[,column_of_your_level] == "Botany Lab Puzzle 2"),]
subset_level_3 = your_dataframe[which(your_dataframe[,column_of_your_level] == "Botany Lab Puzzle 3"),]

for (col in vector_of_levels_you_want {
    hist(subset_level_1[,col])
    hist(subset_level_2[,col])
    hist(subset_level_3[,col])
}
</code>```

Body:
I want to plot one histogram(separate) for each variable in the column. The data is import using a CSV file(sample.csv) and looks like

ip_addr_player_id,  event_name, level, points_earned, stars_earned, moves
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 2, 1000, 2,   2
118.93.180.241, Puzzle Complete, Botany Lab Puzzle 3, 1000, 2,   2
203.166.252.219, Puzzle Complete, Botany Lab Puzzle 1, 1000, 2,  2
54.166.252.324, Puzzle Complete, Botany Lab Puzzle 5, 1000, 2,  2

Given each ip_addr_player_id is unique, I want to plot histograms (for each ip_addr_payer_id) for points_earned, starts_earned and moves.

I tried this based on an example I could find online;

 library(readr)
 dataIn <- read.csv("sample.csv")
 #View(dataIn)
 library(ggplot2)
 plot <- ggplot(dataIn, aes(level, points_earned, fill=points_earned))+
              geom_histogram() + facet_wrap(~ip_addr_player_id)
 plot

But this code gives me no output.

Body:
You could use loops for example

X = your_dataframe

vector_of_levels_you_want = 1:ncol(your_dataframe)

subset_level_1 = your_dataframe[which(your_dataframe[,column_of_your_level] == "Botany Lab Puzzle 1"),]
subset_level_2 = your_dataframe[which(your_dataframe[,column_of_your_level] == "Botany Lab Puzzle 2"),]
subset_level_3 = your_dataframe[which(your_dataframe[,column_of_your_level] == "Botany Lab Puzzle 3"),]

for (col in vector_of_levels_you_want {
    hist(subset_level_1[,col])
    hist(subset_level_2[,col])
    hist(subset_level_3[,col])
}


问:
Content-Only Projects in .NET Core
Using .NET Core, is there a way to have content-only projects in Visual Studio 2017 (no output dlls but automatic copying of content for other projects)? I'm after essentially the same thing as this post, save that I'm working with .NET Core.

I saw something about Shared Projects and wondered if that'd be the appropriate solution. Not exactly sure how they work with .NET Core, though (or if they're even supported).

答:
I did some digging into how Shared Projects work. This appears to be exactly what I'm looking for, provided I don't encounter any major caveats or showstoppers down the road.

For others that are new to Shared Projects, they appear in a separate selection below Projects in the navigation tree of the Reference Manager (when adding project references).

Title: Content-Only Projects in .NET Core


问:
Multiplying the numbers of a String
I want to multiply the numbers in a given string which has one or more spaces.

Example:

If i input 52 26 23

  the output should be 31096.

I've written this code but its not working:

```<code>#include <stdio.h>

int main()
{
    char input[30];
    int i, num = 0, v = 1;
    gets(input);

    for (i = 0; input[i] != '\0'; i++)
    {
        if(input[i] == 32)
        {
            v = v * num;
            if(input[i+1] != 32)
            {
                num = 0;
                continue;
                }
            }
            num = (num * 10) + (input[i] - 48);
    }

    printf("%d",v);
    return 0;
}
</code>```

答:
The problem lies in your nested if statement.  Once it enters the first if statement, that means input[i]==32, therefore it can never enter the next if statement where input[i]!=32.

I also have some suggestions for improving readability.  Instead of using numbers to represent the characters, use the character literals themselves!

Another thing, you only have space for 30 characters in your input buffer.  If a user attempts to enter more than this, you will have a buffer overflow.

Lastly, if the user puts more than one space between numbers, the output will become 0.  That may be something you may or may not want to handle.

Edit: Before, the call to gets was only grabbing characters up to the first whitespace character.  I've fixed this issue with a format string in a call to scanf instead.  Buffer overflow problem still applies.  Also, it was not multiplying with the last parsed integer, so I added code for that after the loop.  Another note, this will only work for non-negative integers, if that's something you weren't aware of initially.  The code just assumes the input is nice.

Edit 2: support for input with any number of spaces before, between, or after inputs.

```<code>#include <stdio.h>

int main() {
  char input[30];
  int i, num = 0, v = 1;

  scanf("%[^\n]s", input);

  // skip leading spaces
  for(i = 0; input[i] == ' '; i++);

  // parse remaining input
  while(input[i] != '\0') {
    if(input[i] == ' ') {
      v *= num;
      num = 0;
      // skip subsequent spaces
      while(input[++i] == ' ');
      continue;
    }

    num *= 10;
    num += input[i] - '0';
    i++;
  }

  // ignore trailing spaces
  if(input[i - 1] != ' ') {
    // get last parsed integer
    v *= num;
  }

  printf("%i\n", v);
  return 0;
}
</code>```

Title: Multiplying the numbers of a String

Body:
I want to multiply the numbers in a given string which has one or more spaces.

Example:

If i input 52 26 23

  the output should be 31096.

I've written this code but its not working:

#include <stdio.h>

int main()
{
    char input[30];
    int i, num = 0, v = 1;
    gets(input);

    for (i = 0; input[i] != '\0'; i++)
    {
        if(input[i] == 32)
        {
            v = v * num;
            if(input[i+1] != 32)
            {
                num = 0;
                continue;
                }
            }
            num = (num * 10) + (input[i] - 48);
    }

    printf("%d",v);
    return 0;
}

Body:
The problem lies in your nested if statement.  Once it enters the first if statement, that means input[i]==32, therefore it can never enter the next if statement where input[i]!=32.

I also have some suggestions for improving readability.  Instead of using numbers to represent the characters, use the character literals themselves!

Another thing, you only have space for 30 characters in your input buffer.  If a user attempts to enter more than this, you will have a buffer overflow.

Lastly, if the user puts more than one space between numbers, the output will become 0.  That may be something you may or may not want to handle.

Edit: Before, the call to gets was only grabbing characters up to the first whitespace character.  I've fixed this issue with a format string in a call to scanf instead.  Buffer overflow problem still applies.  Also, it was not multiplying with the last parsed integer, so I added code for that after the loop.  Another note, this will only work for non-negative integers, if that's something you weren't aware of initially.  The code just assumes the input is nice.

Edit 2: support for input with any number of spaces before, between, or after inputs.

#include <stdio.h>

int main() {
  char input[30];
  int i, num = 0, v = 1;

  scanf("%[^\n]s", input);

  // skip leading spaces
  for(i = 0; input[i] == ' '; i++);

  // parse remaining input
  while(input[i] != '\0') {
    if(input[i] == ' ') {
      v *= num;
      num = 0;
      // skip subsequent spaces
      while(input[++i] == ' ');
      continue;
    }

    num *= 10;
    num += input[i] - '0';
    i++;
  }

  // ignore trailing spaces
  if(input[i - 1] != ' ') {
    // get last parsed integer
    v *= num;
  }

  printf("%i\n", v);
  return 0;
}


问:
Do I need to secure my API key when I push to GitHub?
I am trying to use the Movie Database API to populate a simple Python data structure project for a class I am taking. I am a programming beginner, and have never tried to use an API before.

I have been supplied two things:

1) API Key (V3 Auth)

2) API Read Access Token (v4 auth)

Auth Documentation | v4 Auth Documentation

First of all, what is the difference between these two? I am able to successfully query for what I need using the API key - what would #2 be used for in an actual product?

When I go to turn in my project on GitHub, do I need to worry about the API key being visible? From my understanding, in some API's the key gives total account access, but some keys can be safely displayed on the client's end without worry.

Is this correct? What about in my case - do Movie Database API keys need to be kept secure?

How would I do so assuming I have to turn in the finished project on GitHub?

答: yes its a professional thing to make them private as its your property when you associate your account with the API so you have to make that private.</p>


问:
How can I slice a string according to a list of sorted integers?
let's say I have a string

s = 'ABCDEFGHIJKLMNOP'

and a list of sorted integers

lst = [1, 4, 5, 9]

How do I write a function to take the integers and slice the string accordingly?

Required output:

```<code>1)'A'[:1]

2) 'BCD' [1:4]

3) 'E' [4:5]

4) 'FGHI' [5:9]

5) 'JKLMNOP' [9:]
</code>```

答:
You can construct explicit slice() objects with your indexes and then index the string using those slices.

From then it boils down to the usual "How do I get paired objects from a sequence" that Python doesn't really have a builtin solution for.

A slightly evil, compact solution, making use of the fact that map() can iterate over multiple sequences in lock-step:

```<code>s = 'ABCDEFGHIJKLMNOP'
idx = [1, 4, 5, 9]
parts = [s[slc] for slc in map(slice, [0] + idx, idx + [None])]
</code>```

Don't do this if you have many indexes, since it constructs two intermediate lists on the fly for the indexes.

Obviously, if one can massage idx beforehand, it's also possible to

```<code>from itertools import imap
s = 'ABCDEFGHIJKLMNOP'
idx = [0, 1, 4, 5, 9, None]
parts = [s[slc] for slc in imap(slice, idx[:-1], idx[1:])]
</code>```

Body:
let's say I have a string

s = 'ABCDEFGHIJKLMNOP'

and a list of sorted integers

lst = [1, 4, 5, 9]

How do I write a function to take the integers and slice the string accordingly?

Required output:

1)'A'[:1]

2) 'BCD' [1:4]

3) 'E' [4:5]

4) 'FGHI' [5:9]

5) 'JKLMNOP' [9:]

Body:
You can construct explicit slice() objects with your indexes and then index the string using those slices.

From then it boils down to the usual "How do I get paired objects from a sequence" that Python doesn't really have a builtin solution for.

A slightly evil, compact solution, making use of the fact that map() can iterate over multiple sequences in lock-step:

s = 'ABCDEFGHIJKLMNOP'
idx = [1, 4, 5, 9]
parts = [s[slc] for slc in map(slice, [0] + idx, idx + [None])]

Don't do this if you have many indexes, since it constructs two intermediate lists on the fly for the indexes.

Obviously, if one can massage idx beforehand, it's also possible to

from itertools import imap
s = 'ABCDEFGHIJKLMNOP'
idx = [0, 1, 4, 5, 9, None]
parts = [s[slc] for slc in imap(slice, idx[:-1], idx[1:])]


问:
Rails inserting multiple records for single model
How shall I set the form fields to be able to insert multiple rows in the database for a single model.

I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.

I have a post model and it has a title field.
  I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.

Also I tried to set the Array my self from Rails Console like

```<code>post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save
</code>```

And still nothing is saved.

答:
```<code>posts = Array.new
posts << {:title => "title 1"}
posts << {:title => "title 2"}
Post.create(posts)
</code>```

Body:
How shall I set the form fields to be able to insert multiple rows in the database for a single model.

I am updating a div with another link and cannot use the form helper. So I need to set the field names manually.

I have a post model and it has a title field.
  I want to insert i posts to db like post[0][title] But when I name the form field like this It gets 0 as string and does not record.

Also I tried to set the Array my self from Rails Console like

post = Array.new
post << [:title => "title 1"]
post << [:title => "title 2"]
sav = Post.new(post)
sav.save

And still nothing is saved.


问:
Laravel Passport tokensExpireIn seems not working
i'm using Larave 5.4 passport to create SPA application. However, i was able to make authentication work. but access token are always short-lived tokens with 600s expiration time.

i could not increase expiration time with:

```<code>Passport::tokensExpireIn(Carbon::now()->addDays(15));

Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
</code>```

it have no effect at all.

any help? thanks in advance.

答: Try to use this library: https://github.com/GeneaLabs/laravel-caffeine , and you can look laravel session config options</p>

Body:
i'm using Larave 5.4 passport to create SPA application. However, i was able to make authentication work. but access token are always short-lived tokens with 600s expiration time.

i could not increase expiration time with:

Passport::tokensExpireIn(Carbon::now()->addDays(15));

Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

it have no effect at all.

any help? thanks in advance.


问:
Finding the Kth Largest element in a Python List using recursion
Given an input list that contains some random unsorted numbers, I am trying to write a program that outputs the kth largest distinct element in that list. For example:

```<code>Input:
el = [10,10, 20,30,40, 40]
k = 2
Output: 30 #Since 30 is the second largest distinct element in the list
</code>```

The following function, takes as input a list, the pivot Index and k and populates list "lesser" with all elements lesser than the pivot and populates another list "greater" with all elements greater than the pivot.

Now, looking at the length of the two list, I can determine if the kth largest element is in the lesser list or the greater list. Now I recursively call the same function. However, my program's output is wrong for certain values of k.

```<code>def kthLargest(el, pivotIndex, k):
    pivot = el[pivotIndex]
    lesser = [] #List to store all elements lesser than pivot
    greater = [] #Lsit to store all elements greater than pivot
    equals = [] #List to store all elements equal to pivot

    for x in el:
        if x > pivot:
            greater.append(x)
        elif x < pivot:
            lesser.append(x)
        else:
            equals.append(x)
    g = len(greater) #Length of greater list
    l = len(lesser)

    if(g == k - 1): #If greater list has k-1 elements, that makes the pivot kth largest element
        return pivot
    elif(g < k):
        return kthLargest(lesser, l - 1, k) #If greater list is smaller than k, kth largest element is in lesser list
    else:
        return kthLargest(greater,  g - 1, k) #Else kth largest element is in greater list
</code>```

答:
Here is a simple solution:

```<code>def kthmax(k, list):
    if (k == 1):
        return max(list)
    else:
        m = max(list)
        return(kthmax(k-1, [x for x in list if x != m]))

kthmax(3,[4, 6, 2, 7, 3, 2, 6, 6])
</code>```

Output: 4

Body:
Given an input list that contains some random unsorted numbers, I am trying to write a program that outputs the kth largest distinct element in that list. For example:

Input:
el = [10,10, 20,30,40, 40]
k = 2
Output: 30 #Since 30 is the second largest distinct element in the list

The following function, takes as input a list, the pivot Index and k and populates list "lesser" with all elements lesser than the pivot and populates another list "greater" with all elements greater than the pivot.

Now, looking at the length of the two list, I can determine if the kth largest element is in the lesser list or the greater list. Now I recursively call the same function. However, my program's output is wrong for certain values of k.

def kthLargest(el, pivotIndex, k):
    pivot = el[pivotIndex]
    lesser = [] #List to store all elements lesser than pivot
    greater = [] #Lsit to store all elements greater than pivot
    equals = [] #List to store all elements equal to pivot

    for x in el:
        if x > pivot:
            greater.append(x)
        elif x < pivot:
            lesser.append(x)
        else:
            equals.append(x)
    g = len(greater) #Length of greater list
    l = len(lesser)

    if(g == k - 1): #If greater list has k-1 elements, that makes the pivot kth largest element
        return pivot
    elif(g < k):
        return kthLargest(lesser, l - 1, k) #If greater list is smaller than k, kth largest element is in lesser list
    else:
        return kthLargest(greater,  g - 1, k) #Else kth largest element is in greater list

Body:
Here is a simple solution:

def kthmax(k, list):
    if (k == 1):
        return max(list)
    else:
        m = max(list)
        return(kthmax(k-1, [x for x in list if x != m]))

kthmax(3,[4, 6, 2, 7, 3, 2, 6, 6])

Output: 4


问:
On shiny app ggplotly() renders half the size of plot_ly(). How to fix that?
A plot's width is less than half when using ggplotly vs plot_ly to generate a plotly in a shiny app. Why is that? Is there a way to fix it so that ggplotly produces the plot with the same width as plot_ly or ggplot2? I have tried using the width parameter but that doesn't fix it.

Output from the shiny app:

```<code>library(shiny)
library(plotly)
library(ggplot2)

ui <- fluidPage(
   titlePanel("plotly with shiny"),
      mainPanel(
        h4("Using ggplotly:"), plotlyOutput("ggplotly", width = "200"),
        h4("Using native plotly:"), plotlyOutput("plotly"),
        h4("Using ggplot:"), plotOutput("ggplot")
      )
)

server <- function(input, output) {
  data <- reactive({
    d = diamonds[sample(nrow(diamonds), 300),]
  })
  output$ggplot <- renderPlot({
      ggplot(data(), aes(x=carat, y=price, color=price)) + geom_point()
   })
   output$ggplotly <- renderPlotly({
     v = ggplot(data(), aes(x=carat, y=price, color=price)) + geom_point()
     ggplotly(v)
   })
   output$plotly <- renderPlotly({
     plot_ly(data(), x = ~carat, y = ~price, color = ~price)
   })
}

shinyApp(ui = ui, server = server)
</code>```

答:
Do not use the argument width of plotlyOutput, and use the one of ggplotly:

```<code>ggplotly(v, width=800)
</code>```

Body:
A plot's width is less than half when using ggplotly vs plot_ly to generate a plotly in a shiny app. Why is that? Is there a way to fix it so that ggplotly produces the plot with the same width as plot_ly or ggplot2? I have tried using the width parameter but that doesn't fix it.

Output from the shiny app:

library(shiny)
library(plotly)
library(ggplot2)

ui <- fluidPage(
   titlePanel("plotly with shiny"),
      mainPanel(
        h4("Using ggplotly:"), plotlyOutput("ggplotly", width = "200"),
        h4("Using native plotly:"), plotlyOutput("plotly"),
        h4("Using ggplot:"), plotOutput("ggplot")
      )
)

server <- function(input, output) {
  data <- reactive({
    d = diamonds[sample(nrow(diamonds), 300),]
  })
  output$ggplot <- renderPlot({
      ggplot(data(), aes(x=carat, y=price, color=price)) + geom_point()
   })
   output$ggplotly <- renderPlotly({
     v = ggplot(data(), aes(x=carat, y=price, color=price)) + geom_point()
     ggplotly(v)
   })
   output$plotly <- renderPlotly({
     plot_ly(data(), x = ~carat, y = ~price, color = ~price)
   })
}

shinyApp(ui = ui, server = server)

Body:
Do not use the argument width of plotlyOutput, and use the one of ggplotly:

ggplotly(v, width=800)


问:
numpy corrcoef causes computer to hang
When trying to calculate numpy corrcoef

```<code>cc = np.corrcoef(y, y2)
</code>```

where shapes of y and y2 are

```<code><class 'tuple'>: (32383, 1)
</code>```

My computer hangs. Not only interpreter but entire computer.

How can this be and how to fix?

答:
Computing the correlation coefficient between two shape (32383, 1) arrays will result in a (32383, 32383) array. Such an array will have size (32383 * 32383 * 8) / (1024 ** 3) = 7.8 Gb. Considering that you likely have some overhead in computing the result, you likely need in the order of tens of Gb's to compute this.

What is probably happening is not that your computer hangs, but that the computation overflows your RAM and starts to perform paging, that is, uses the hard-drive to store the partial results. This is exceedingly slow and it will thus seem like your computer has hung. Given enough time, it should give a result.

If you instead want to compute the row-wise cross correlation (which has shape (1, 1)), you can do:

```<code>cc = np.corrcoef(y, y2, rowvar=False)
</code>```

Title: numpy corrcoef causes computer to hang

Body:
When trying to calculate numpy corrcoef

cc = np.corrcoef(y, y2)

where shapes of y and y2 are

<class 'tuple'>: (32383, 1)

My computer hangs. Not only interpreter but entire computer.

How can this be and how to fix?

Body:
Computing the correlation coefficient between two shape (32383, 1) arrays will result in a (32383, 32383) array. Such an array will have size (32383 * 32383 * 8) / (1024 ** 3) = 7.8 Gb. Considering that you likely have some overhead in computing the result, you likely need in the order of tens of Gb's to compute this.

What is probably happening is not that your computer hangs, but that the computation overflows your RAM and starts to perform paging, that is, uses the hard-drive to store the partial results. This is exceedingly slow and it will thus seem like your computer has hung. Given enough time, it should give a result.

If you instead want to compute the row-wise cross correlation (which has shape (1, 1)), you can do:

cc = np.corrcoef(y, y2, rowvar=False)


问:
VueJS nested components: Best practice
I'm a newbie in VueJS.2 and today working with VueJS Components.

So, I ended up with this .vue component:

```<code><template>
  <div class="apps">
    <ul class="icons">
      <li v-for="app in apps" class="app" :style="style">
        <div :class="icon(app)"></div>
        <div class="name">{{app}}</div>
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: 'desktop-apps',
    data () {
      return {
        apps: ['Txt File', 'Img File', ...],
        top: 0,
        left: 0
      }
    },
    methods: {
      icon (name) {
        return 'icon ' + name.toLowerCase().replace(/ /g, '_')
      },
      style () {
        var _top = this.top
        var _left = this.left
        return 'top:' + _top + 'px;left:' + _left + 'px;'
      }
    }
  }
</script>

<style>
  // li has position:absolute and vertically rendered
</style>
</code>```

This Component works well...

I want to know that this code is good or can be improvised (via compute or something else?
If YES, then HOW?

Also, I want to clarify 2 more questions:

1: how can I get the height of ul.icons, so that, if children li.app's overall height is greater, than update the top & left style from style method.

2: How to add and re-style app (li.app) from external component?

Thanks & Regards

答:
You can pet a ref on the
 like this

and then return the height:

```<code>this.$refs.icon.offsetHeight
</code>```

Title: VueJS nested components: Best practice

Body:
I'm a newbie in VueJS.2 and today working with VueJS Components.

So, I ended up with this .vue component:

<template>

{{app}}

</template>

This Component works well...

I want to know that this code is good or can be improvised (via compute or something else?
If YES, then HOW?

Also, I want to clarify 2 more questions:

1: how can I get the height of ul.icons, so that, if children li.app's overall height is greater, than update the top & left style from style method.

2: How to add and re-style app (li.app) from external component?

Thanks & Regards

Body:
You can pet a ref on the <ul> like this <ul class="icons" ref='icon'>

and then return the height:

this.$refs.icon.offsetHeight


问:
Objective c - How save text style with SQLite?
I'm creating a note management app. To save the various notes I am using SQLite. The problem is that if I modify a note, for example, change the font or turn it into bold or italic and then save it, when re-extracting the note, it has lost (of course) all the attributes and is written in a normal way. How can I solve this problem?</p>

答:
You have to store the attributed string, not just the string. Then use NSKeyedArchiver to convert it to raw data. There are a couple of ways to go after that but you can try converting to base64 and then storing it in a blob. Try this to convert the data. In my case "report" is an NSTextView;

```<code>  NSMutableData *data = [[NSMutableData alloc] init];
  NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  [archiver encodeObject:report.textStorage forKey:@"attrs"];
  [archiver finishEncoding];

  NSString *encodedString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
</code>```

The resulting string, encodedString can be inserted into SQLite.

To get it back out reverse the process;

```<code>  NSString *reportCoded = [aReportRecord valueForKey:@"reportContents"];

  NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:reportCoded options:NSDataBase64DecodingIgnoreUnknownCharacters];

  NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:decodedData];

  NSAttributedString* newString = [unarchiver decodeObjectForKey :@"attrs"];

  [[self.report textStorage] appendAttributedString:newString];
</code>```

Body:
You have to store the attributed string, not just the string. Then use NSKeyedArchiver to convert it to raw data. There are a couple of ways to go after that but you can try converting to base64 and then storing it in a blob. Try this to convert the data. In my case "report" is an NSTextView;

  NSMutableData *data = [[NSMutableData alloc] init];
  NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  [archiver encodeObject:report.textStorage forKey:@"attrs"];
  [archiver finishEncoding];

  NSString *encodedString = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

The resulting string, encodedString can be inserted into SQLite.

To get it back out reverse the process;

  NSString *reportCoded = [aReportRecord valueForKey:@"reportContents"];

  NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:reportCoded options:NSDataBase64DecodingIgnoreUnknownCharacters];

  NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:decodedData];

  NSAttributedString* newString = [unarchiver decodeObjectForKey :@"attrs"];

  [[self.report textStorage] appendAttributedString:newString];


问:
SurfaceView with ViewPager in API level 10 has a long delay during a new transition
I have a very similar question to:
ViewPager + SurfaceView = long delay when navigating back to activity

Except that I am using API 10 and so I am not using fragments.

I have SurfaceViews in the ViewPager - and I have that working well, except that when I scroll to a new page, it takes a while to draw.  It is not until the SurfaceView is visible on screen that the SurfaceView.surfaceCreated method is called. I would like to have the surface created at the time that ViewPager's PagerAdapter.instantiateItem is called and the SurfaceView is added to the ViewPager via addView. Is there a way to force the SurfaceView to create a surface at that point?

I am using code based on the Awesome Pager example

```<code>        @Override
        public Object instantiateItem(View collection, int position) {
            Log.i("Main Activity", "instantiateItem p:" + position);
            View p;
            if(position == 1){
                    // Page003 is a surfaceview
                p = new Page003(cxt, position);
            } else {
                    // in the future I will create more pages!
                p = new Page003(cxt, position);
            }
            ((ViewPager) collection).addView(p);

            return p;
        }
</code>```

Is there a method similar to the answer in the other question - by wrapping the SurfaceView in another view? I'd rather not complicate the code unnecessarily.

答:
Implement onAttached() in your Viewpager Adapter
Run an handler for 2 sec thats it

This will load your surface  after 2 sec no more lag

Body:
I have a very similar question to:
ViewPager + SurfaceView = long delay when navigating back to activity

Except that I am using API 10 and so I am not using fragments.

I have SurfaceViews in the ViewPager - and I have that working well, except that when I scroll to a new page, it takes a while to draw.  It is not until the SurfaceView is visible on screen that the SurfaceView.surfaceCreated method is called. I would like to have the surface created at the time that ViewPager's PagerAdapter.instantiateItem is called and the SurfaceView is added to the ViewPager via addView. Is there a way to force the SurfaceView to create a surface at that point?

I am using code based on the Awesome Pager example

        @Override
        public Object instantiateItem(View collection, int position) {
            Log.i("Main Activity", "instantiateItem p:" + position);
            View p;
            if(position == 1){
                    // Page003 is a surfaceview
                p = new Page003(cxt, position);
            } else {
                    // in the future I will create more pages!
                p = new Page003(cxt, position);
            }
            ((ViewPager) collection).addView(p);

            return p;
        }

Is there a method similar to the answer in the other question - by wrapping the SurfaceView in another view? I'd rather not complicate the code unnecessarily.


问:
ng2-toastr with akveo/ng2-admin - CSS not taken into account
I'm using akveo/ng2-admin dashboard (latest with angular 4) and tried to use ng2-toastr following the installation doc.

I imported the CSS in the index.html file and declared the ToastModule in the app.module.ts file.

I also imported the ToastsManager in my component and assigned the ViewContainerRef.

The module gets loaded successfully and everything goes without error so far.

But when I call this.toastr.success('You are awesome!', 'Success!'); the text is displayed without using the CSS.

ng2-admin is using WebPack.

Any idea?

Thanks in advance!
Serge.

URL toastr: https://github.com/PointInside/ng2-toastr

URL ng2-admin: enter link description here

答:
Add

```<code>@import '../node_modules/ng2-toastr/ng2-toastr.css';
</code>```

to ./src/app/theme/theme.cscc

this file is there to add global styles or import other files, that way we can avoid copying files

Body:
Add

@import '../node_modules/ng2-toastr/ng2-toastr.css';

to ./src/app/theme/theme.cscc

this file is there to add global styles or import other files, that way we can avoid copying files


答:
My solution isn't the most elegant, but it is very simple and it scales well.

Looking at the documentation for list slicing syntax, all list slices have the form list[start:end]. Omitting start gives it the value 0, and omitting end gives it the value len(list).

So solving your problem becomes really easy if you add 0 and len(list) to your indexes, effectively removing the trickiest part of your specification, which is the first and last indices:

```<code>numbers = [1, 4, 5, 9]
string = 'ABCDEFGHIJKLMNOP'

numbers.append(len(string))
numbers.insert(0,0)

result = [string[numbers[i]:numbers[i+1]] for i in range(len(numbers)-1)]
</code>```

Output:

```<code>>>> print(result)
['A', 'BCD', 'E', 'FGHI', 'JKLMNOP']
</code>```

Title: How can I slice a string according to a list of sorted integers?

Body:
My solution isn't the most elegant, but it is very simple and it scales well.

Looking at the documentation for list slicing syntax, all list slices have the form list[start:end]. Omitting start gives it the value 0, and omitting end gives it the value len(list).

So solving your problem becomes really easy if you add 0 and len(list) to your indexes, effectively removing the trickiest part of your specification, which is the first and last indices:

numbers = [1, 4, 5, 9]
string = 'ABCDEFGHIJKLMNOP'

numbers.append(len(string))
numbers.insert(0,0)

result = [string[numbers[i]:numbers[i+1]] for i in range(len(numbers)-1)]

Output:

>>> print(result)
['A', 'BCD', 'E', 'FGHI', 'JKLMNOP']


问:
Missing entities after insertion in Google Cloud DataStore
After inserting 29447 entities of a single kind in Google Cloud DataStore I wait about 30 seconds and go and check how many entities are there for that particular kind. The surprising thing is that I notice some of them missing (getCurrentKeys returns a bit less than 29447 entities). When I check after a longer period of time (~1 hour), I can then see that all of the entities are there (getCurrentKeys returns the expected 29447 entities).

The code used to read the number of entities is the following:

```<code>const runQuery = (query) => {
  return new Promise((resolve, reject) => {
    datastore.runQuery(query)
      .then(results => {
        const entities = results[0];
        resolve(entities);
      })
      .catch(e => reject(e));
  });
};

const getCurrentKeys = () => {
  const query = datastore.createQuery(KIND)
    .select('__key__');
  return runQuery(query);
};

async function main() {
  const currentKeys = await getCurrentKeys();
  console.log(`currentKeys: ${currentKeys.length}`);
}

main();
</code>```

Any ideas of what could be happening?

Thanks in advance

答: After a bit more research I think it might be related to the indexes. I believe the indexes aren't getting updated fast enough by the time I run the query. The entities have many properties, so there are many indexes involved.</p>

Body:
After inserting 29447 entities of a single kind in Google Cloud DataStore I wait about 30 seconds and go and check how many entities are there for that particular kind. The surprising thing is that I notice some of them missing (getCurrentKeys returns a bit less than 29447 entities). When I check after a longer period of time (~1 hour), I can then see that all of the entities are there (getCurrentKeys returns the expected 29447 entities).

The code used to read the number of entities is the following:

const runQuery = (query) => {
  return new Promise((resolve, reject) => {
    datastore.runQuery(query)
      .then(results => {
        const entities = results[0];
        resolve(entities);
      })
      .catch(e => reject(e));
  });
};

const getCurrentKeys = () => {
  const query = datastore.createQuery(KIND)
    .select('__key__');
  return runQuery(query);
};

async function main() {
  const currentKeys = await getCurrentKeys();
  console.log(`currentKeys: ${currentKeys.length}`);
}

main();

Any ideas of what could be happening?

Thanks in advance


问:
Updating my Django website's database from a third party service, strategies?
I'm learning Django and to practice I'm currently developing a clone page of YTS, it's a movie torrents repository*.

As of right now, I scrapped all the movies in the website and have them on a single db table called Movie with all the basic information of each movie (I'm planning on adding one more for Genre).

Every few days YTS will post new movies and I want my clone-web to automatically add them to the database. I'm currently stuck on deciding how to do this:

I was planning on comparing the movie id of the last movie in my db against the last movie in the YTS db each time the user enters the website, but that'd mean make a request to YTS every time my page loads, it'd also mean some very slow code should be executed inside my index() views method.

Another strategy would be to query the last time my db was updated (new entries were introduced) and if it's let's say bigger than a day then request new movies to YTS. Problem with this is I don't seem to find any method to query the time of last db updates. Does it even exist such method?

I could also set a cron job to update the information but I'm having problems to make changes from a separated Python function (I import django.db and such but the interpreter refuses to execute django db instructions).

So, all in all, what's the best strategy to update my database from a third party service/website without bothering the user with loading times? How do you set such updates in non-intrusive way to the user? How do you generally do it?

* I know a torrents website borders the illegal and I'm not intended, in any way, to make my project available to the public

答:
I think you should choose definetely the third alternative, a cron job to update the database regularly seems the best option.
 You don' t need to use a seperate python function, you can schedule a task with celery, which can be easily integrated with django using django-celery


问:
Printing Diamond Pattern in Correct Format in Java using Recursion
My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. I'm just having a problem getting everything to line up properly.

The output is supposed to look like this:

```<code>    *
  *   *
*   *   *
  *   *
    *
</code>```

Regarding the format of the output, the directions are:

"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space."

But my output looks like this:

```<code>*
*  *
*  *  *
*  *
*
</code>```

The code I'm using to get this pattern:

```<code>public static void makePattern(int thisRow, int num) {
    if(thisRow >= num) {
        for(int i = 0; i < num; i++) {
            System.out.print("  " + "*" + "  ");
        }
        System.out.println();

    }
    else {
        for(int i = 0; i < thisRow; i++) {
            System.out.print("  " + "*" + "  ");
        }
        System.out.println();

        makePattern(thisRow + 1, num);

        for(int i = 0; i < thisRow; i++) {
            System.out.print("  " + "*" + "  ");
        }
        System.out.println();
    }
}
</code>```

Also my main method:

```<code>import java.util.Scanner;
import java.io.*;

public class Program3 {
    public static void main(String[] args) throws Exception {
        int num = 0;
        int thisRow = 1;
        java.io.File file = new java.io.File("../instr/prog3.dat");
        Scanner fin = new Scanner(file);

        while(fin.hasNext()) {
                num = fin.nextInt();
                if(num >=0 && num <= 25)
                    makePattern(thisRow, num);
                System.out.println();
        }
        fin.close();

    }
</code>```

Any suggestions on how to edit my code to make my output appear like the example pattern I included?

答:
This is code for printing diamond shaped pattern using recursion technique.

```<code>    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.*;
    public class patternRecursion {
    static int n,k;
    public static void main(String[] args) throws IOException{
        try(Scanner s = new Scanner(System.in)){

            n=Integer.parseInt(reader.readLine());
            k=n-1;
            printPattern(n);
        }
    }
    public static void printChar(int m,char c){
        if(m==0) return;
        try{
            printChar(m-1,c);
            System.out.print(c);

        }catch(StackOverflowError s){return;}

    }
    public static void printPattern(int m){
        if(m==0){
            return ;
        }else{

        printChar(m-1,' ');
        printChar(n-m,'#');
        printChar(n-m+1,'#');
           System.out.println();
           printPattern(m-1);
         printChar(m,' ');
         printChar(k-m,'#');
         printChar(k-m+1,'#');
            System.out.println();
         }

    }
</code>```

}

Body:
My program reads in values from a file and uses a recursive method to print patterns of asterisks based on those values. I'm just having a problem getting everything to line up properly.

The output is supposed to look like this:

    *
  *   *
*   *   *
  *   *
    *

Regarding the format of the output, the directions are:

"Note that the pattern is aligned symmetrically (vertically) about the center line. The pattern should be aligned symmetrically on each line (horizontally) as well- hint: use the line value to help space."

But my output looks like this:

*
*  *
*  *  *
*  *
*

The code I'm using to get this pattern:

public static void makePattern(int thisRow, int num) {
    if(thisRow >= num) {
        for(int i = 0; i < num; i++) {
            System.out.print("  " + "*" + "  ");
        }
        System.out.println();

    }
    else {
        for(int i = 0; i < thisRow; i++) {
            System.out.print("  " + "*" + "  ");
        }
        System.out.println();

        makePattern(thisRow + 1, num);

        for(int i = 0; i < thisRow; i++) {
            System.out.print("  " + "*" + "  ");
        }
        System.out.println();
    }
}

Also my main method:

import java.util.Scanner;
import java.io.*;

public class Program3 {
    public static void main(String[] args) throws Exception {
        int num = 0;
        int thisRow = 1;
        java.io.File file = new java.io.File("../instr/prog3.dat");
        Scanner fin = new Scanner(file);

        while(fin.hasNext()) {
                num = fin.nextInt();
                if(num >=0 && num <= 25)
                    makePattern(thisRow, num);
                System.out.println();
        }
        fin.close();

    }

Any suggestions on how to edit my code to make my output appear like the example pattern I included?

Body:
This is code for printing diamond shaped pattern using recursion technique.

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.*;
    public class patternRecursion {
    static int n,k;
    public static void main(String[] args) throws IOException{
        try(Scanner s = new Scanner(System.in)){

            n=Integer.parseInt(reader.readLine());
            k=n-1;
            printPattern(n);
        }
    }
    public static void printChar(int m,char c){
        if(m==0) return;
        try{
            printChar(m-1,c);
            System.out.print(c);

        }catch(StackOverflowError s){return;}

    }
    public static void printPattern(int m){
        if(m==0){
            return ;
        }else{

        printChar(m-1,' ');
        printChar(n-m,'#');
        printChar(n-m+1,'#');
           System.out.println();
           printPattern(m-1);
         printChar(m,' ');
         printChar(k-m,'#');
         printChar(k-m+1,'#');
            System.out.println();
         }

    }

}


问:
Django 1.11 (Python 3.+) doesn't work styles, when I make DEBUG=False
When I try it gives 404 error view, my styles doesn't work. I tried to create custom 404 view but it also doesn't work.

Here is my code.

settings.py

```<code>   DEBUG = False
   TEMPLATE_DEBUG = DEBUG

   ALLOWED_HOSTS = ['*']

   TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'ran_app/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug': DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = '/static/'
</code>```

I have 404.html page too in templates.

Here is the browser error.

Failed to load resource: the server responded with a status of 404
  (Not Found)

答: When there is DEBUG = False default Django package will not serve any static files from your server . You have to use a nginx like tool to serve your files and it is a condition like production server.</p>

Body:
When I try it gives 404 error view, my styles doesn't work. I tried to create custom 404 view but it also doesn't work.

Here is my code.

settings.py

   DEBUG = False
   TEMPLATE_DEBUG = DEBUG

   ALLOWED_HOSTS = ['*']

   TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'ran_app/templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'debug': DEBUG,
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

STATIC_URL = '/static/'

I have 404.html page too in templates.

Here is the browser error.

Failed to load resource: the server responded with a status of 404
  (Not Found)


问:
max. length of List in Java
What is the maximum length of List in java? I mean that how many maximum elements can store in list?</p>

答:
This depends on the specific list implementation. Most people think it's Integer.MAX_VALUE but it isn't limited to that. In fact the documentation of the size() method merely states:

If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

So it might as well contain more elements.

Title: max. length of List in Java


问:
How to get the uri of captured Bitmap correctly?
This code does not work correctly on all Android Versions

On Android 4.x works fine, but on 7.0 this code does not work. the code can capture and save the image but last step about Crop Image : I get balck Screen, means the uri is lost. check the screenshot after the code below pls.

Here is my Demo :

```<code>import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

public class CameraCrop1 extends AppCompatActivity {
    Uri picUri;
    Bitmap bitmap, bitmap2;
    ImageView img, img_original;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_crop1);

        img=(ImageView)findViewById(R.id.imageView);
        img_original=(ImageView)findViewById(R.id.imageView_original);
    }

    public void Capture(View view) {
        Capture_Cam();
    }

    private void Capture_Cam() {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            picUri = data.getData();
            try {
                // bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri); // bitmap2 = original before cur
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file://"+picUri));
                img_original.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
            performCrop();

        } else if (requestCode == 2) {

            bitmap2=(Bitmap) data.getExtras().get("data");
            img.setImageBitmap(bitmap2);

        }else{
            super.onActivityResult(requestCode, resultCode, data);
        }

    }

    private void performCrop(){
        try {

            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            //indicate image type and Uri
            cropIntent.setDataAndType(picUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("outputX", 100);
            cropIntent.putExtra("outputY", 100);
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("return-data", true);
            startActivityForResult(cropIntent, 2);
            Toast toast = Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
        }
        catch(ActivityNotFoundException anfe){
            //display an error message
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }

    }

}
</code>```

Here is xml :

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_camera_crop1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="Test.testing.CameraCrop1">

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/colorAccent"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:text="Capture Camera"
        android:onClick="Capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button4"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/wallet_highlighted_text_holo_dark"
        android:id="@+id/imageView_original"
        android:layout_below="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView" />
</RelativeLayout>
</code>```

Screenshot

答:
@pablobu, If I use the methode of there I get this error :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

error by this line :

```<code>Uri photoURI = FileProvider.getUriForFile(this, // error is here
</code>```

```<code>private void Capture_Cam() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, // error is here
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, 1000);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    }
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );
</code>```

I have fixed the error. New SDK Versions do not support uri form of:  "file://"  I mean TargetVersion. Til version 23 support "file://"
source:Found here

Body:
This code does not work correctly on all Android Versions

On Android 4.x works fine, but on 7.0 this code does not work. the code can capture and save the image but last step about Crop Image : I get balck Screen, means the uri is lost. check the screenshot after the code below pls.

Here is my Demo :

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

public class CameraCrop1 extends AppCompatActivity {
    Uri picUri;
    Bitmap bitmap, bitmap2;
    ImageView img, img_original;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_crop1);

        img=(ImageView)findViewById(R.id.imageView);
        img_original=(ImageView)findViewById(R.id.imageView_original);
    }

    public void Capture(View view) {
        Capture_Cam();
    }

    private void Capture_Cam() {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK && data != null) {

            picUri = data.getData();
            try {
                // bitmap2 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picUri); // bitmap2 = original before cur
                bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file://"+picUri));
                img_original.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
            performCrop();

        } else if (requestCode == 2) {

            bitmap2=(Bitmap) data.getExtras().get("data");
            img.setImageBitmap(bitmap2);

        }else{
            super.onActivityResult(requestCode, resultCode, data);
        }

    }

    private void performCrop(){
        try {

            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            //indicate image type and Uri
            cropIntent.setDataAndType(picUri, "image/*");
            cropIntent.putExtra("crop", "true");
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            cropIntent.putExtra("outputX", 100);
            cropIntent.putExtra("outputY", 100);
            cropIntent.putExtra("scale", true);
            cropIntent.putExtra("return-data", true);
            startActivityForResult(cropIntent, 2);
            Toast toast = Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
        }
        catch(ActivityNotFoundException anfe){
            //display an error message
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            toast.show();
        }

    }

}

Here is xml :

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_camera_crop1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="Test.testing.CameraCrop1">

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/colorAccent"
        android:id="@+id/imageView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:text="Capture Camera"
        android:onClick="Capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button4"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="400px"
        android:layout_height="400px"
        app:srcCompat="@color/wallet_highlighted_text_holo_dark"
        android:id="@+id/imageView_original"
        android:layout_below="@+id/imageView"
        android:layout_alignLeft="@+id/imageView"
        android:layout_alignStart="@+id/imageView" />
</RelativeLayout>

Screenshot

Body:
@pablobu, If I use the methode of there I get this error :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference

error by this line :

Uri photoURI = FileProvider.getUriForFile(this, // error is here

private void Capture_Cam() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File

        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            Uri photoURI = FileProvider.getUriForFile(this, // error is here
                    "com.example.android.fileprovider",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, 1000);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    }
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

I have fixed the error. New SDK Versions do not support uri form of:  "file://"  I mean TargetVersion. Til version 23 support "file://"
source:Found here


问:
Extended glob can't retrace behaviour
I looked at a bash guide where I found this example:
http://guide.bash.academy/expansions/

```<code>$ ls !(my*).txt # All the .txt files that do not begin with my.

hello.txt

$ ls !(my)*.txt # Can you guess why this one matches myscript.txt?

myscript.txt
hello.txt
</code>```

I'm familiar with basic concepts of regular expressions maybe this is confusing me because I'm trying to apply those concepts to extended globs in bash.

I do not understand why !(my)*.txt is expanding myscript.txt in bash. The explanation in the guide does not help me at all.

My reasoning:

!(my*).txt does not match myscript.txt because it does start with my then matches the rest of the characters script and at the end it matches .txt

!(my)*.txt does not (wrong!!!)   match myscript.txt because it is starting with my followed by any characters and at the end it matches .txt

Where am I wrong in my argumentation?

答:
This is a common gotcha with wildcards. The question to ask yourself is, is there any way to split up myscript.txt such that the first piece matches !(my) and the second matches *.txt?

The answer is, counter-intuitively, yes: If you "split" "myscript.txt" into "" (the empty string) and "myscript.txt" then the empty string matches !(my) and "myscript.txt" matches *.txt. The empty string is a valid match!

Title: Extended glob can't retrace behaviour

Body:
I looked at a bash guide where I found this example:
http://guide.bash.academy/expansions/

$ ls !(my*).txt # All the .txt files that do not begin with my.

hello.txt

$ ls !(my)*.txt # Can you guess why this one matches myscript.txt?

myscript.txt
hello.txt

I'm familiar with basic concepts of regular expressions maybe this is confusing me because I'm trying to apply those concepts to extended globs in bash.

I do not understand why !(my)*.txt is expanding myscript.txt in bash. The explanation in the guide does not help me at all.

My reasoning:

!(my*).txt does not match myscript.txt because it does start with my then matches the rest of the characters script and at the end it matches .txt

!(my)*.txt does not (wrong!!!)   match myscript.txt because it is starting with my followed by any characters and at the end it matches .txt

Where am I wrong in my argumentation?


问:
Is it UB to access an element one past the end of a row of a 2d array?
Is the behavior of the following program undefined?

```<code>#include <stdio.h>

int main(void)
{
    int arr[2][3] = { { 1, 2, 3 },
                      { 4, 5, 6 }
    };

    int *ptr1 = &arr[0][0];      // pointer to first elem of { 1, 2, 3 }
    int *ptr3 = ptr1 + 2;        // pointer to last elem of { 1, 2, 3 }
    int *ptr3_plus_1 = ptr3 + 1; // pointer to one past last elem of { 1, 2, 3 }
    int *ptr4 = &arr[1][0];      // pointer to first elem of { 4, 5, 6 }
//    int *ptr_3_plus_2 = ptr3 + 2; // this is not legal

    /* It is legal to compare ptr3_plus_1 and ptr4 */
    if (ptr3_plus_1 == ptr4) {
        puts("ptr3_plus_1 == ptr4");

        /* ptr3_plus_1 is a valid address, but is it legal to dereference it? */
        printf("*ptr3_plus_1 = %d\n", *ptr3_plus_1);
    } else {
        puts("ptr3_plus_1 != ptr4");
    }

    return 0;
}
</code>```

According to §6.5.6 ¶8:

Moreover, if the expression P points to the last element of an
  array object, the expression (P)+1 points one past the last
  element of the array object.... If both the pointer operand and the
  result point to elements of the same array object, or one past the
  last element of the array object, the evaluation shall not produce an
  overflow; otherwise, the behavior is undefined. If the result points
  one past the last element of the array object, it shall not be used as
  the operand of a unary * operator that is evaluated.

From this, it would appear that the behavior of the above program is undefined; ptr3_plus_1 points to an address one past the end of the array object from which it is derived, and dereferencing this address causes undefined behavior.

Further, Annex J.2 suggests that this is undefined behavior:

An array subscript is out of range, even if an object is apparently
  accessible with the given subscript (as in the lvalue expression
  a[1][7] given the declaration int a[4][5]) (6.5.6).

There is some discussion of this issue in the Stack Overflow question, One-dimensional access to a multidimensional array: well-defined C?. The consensus here appears to be that this kind of access to arbitrary elements of a two-dimensional array through one-dimensional subscripts is indeed undefined behavior.

The issue, as I see it, is that it is not even legal to form the address of the pointer ptr3_plus_2, so it is not legal to access arbitrary two-dimensional array elements in this way. But, it is legal to form the address of the pointer ptr3_plus_1 using this pointer arithmetic. Further, it is legal to compare the two pointers ptr3_plus_1 and ptr4, according to §6.5.9 ¶6:

Two pointers compare equal if and only if both are null pointers, both
  are pointers to the same object (including a pointer to an object and
  a subobject at its beginning) or function, both are pointers to one
  past the last element of the same array object, or one is a pointer
  to one past the end of one array object and the other is a pointer to
  the start of a different array object that happens to immediately
  follow the first array object in the address space.

So, if it both ptr3_plus_1 and ptr4 are valid pointers that compare equal and that must point to the same address (the object pointed to by ptr4 must be adjacent in memory to the object pointed to by ptr3 anyway, since array storage must be contiguous), it would seem that *ptr3_plus_1 is as valid as *ptr4.

Is this undefined behavior, as described in §6.5.6 ¶8 and Annex J.2, or is this an exceptional case?

To Clarify

It seems unambiguous that it is undefined behavior to attempt to access the element one past the end of the final row of a two-dimensional array. My interest is in the question of whether it is legal to access the first element of the intermediate rows by forming a new pointer using a pointer to an element from the previous row and pointer arithmetic. It seems to me that a different example in Annex J.2 could have made this more clear.

Is it possible to reconcile the clear statement in §6.5.6 ¶8 that an attempted dereference of a pointer to the location one past the end of an array leads to undefined behavior with the idea that the pointer past the end of the first row of a two-dimensional array of type T[][] is also a pointer of type T * that points to an object of type T, namely the first element of an array of type T[]?

答:
So, if it both ptr3_plus_1 and ptr4 are valid pointers that compare equal and that must point to the same address

They are.

it would seem that *ptr3_plus_1 is as valid as *ptr4.

It is not.

The pointers are equal, but not equivalent. The trivial well-known example of the distinction between equality and equivalence is negative zero:

```<code>double a = 0.0, b = -0.0;
assert (a == b);
assert (1/a != 1/b);
</code>```

Now, to be fair, there is a difference between the two, as positive and negative zero have a different representation, ptr3_plus_1 and ptr4 on typical implementations have the same representation. This is not guaranteed, and on implementations where they would have different representations, it should be clear that your code might fail.

Even on the typical implementations, while there are good arguments to be made that the same representation implies equivalent values, to the best of my knowledge, the official interpretation is that the standard does not guarantee this, therefore programs cannot rely on it, therefore implementations can assume programs do not do this and optimise accordingly.

Body:
Is the behavior of the following program undefined?

#include <stdio.h>

int main(void)
{
    int arr[2][3] = { { 1, 2, 3 },
                      { 4, 5, 6 }
    };

    int *ptr1 = &arr[0][0];      // pointer to first elem of { 1, 2, 3 }
    int *ptr3 = ptr1 + 2;        // pointer to last elem of { 1, 2, 3 }
    int *ptr3_plus_1 = ptr3 + 1; // pointer to one past last elem of { 1, 2, 3 }
    int *ptr4 = &arr[1][0];      // pointer to first elem of { 4, 5, 6 }
//    int *ptr_3_plus_2 = ptr3 + 2; // this is not legal

    /* It is legal to compare ptr3_plus_1 and ptr4 */
    if (ptr3_plus_1 == ptr4) {
        puts("ptr3_plus_1 == ptr4");

        /* ptr3_plus_1 is a valid address, but is it legal to dereference it? */
        printf("*ptr3_plus_1 = %d\n", *ptr3_plus_1);
    } else {
        puts("ptr3_plus_1 != ptr4");
    }

    return 0;
}

According to §6.5.6 ¶8:

Moreover, if the expression P points to the last element of an
  array object, the expression (P)+1 points one past the last
  element of the array object.... If both the pointer operand and the
  result point to elements of the same array object, or one past the
  last element of the array object, the evaluation shall not produce an
  overflow; otherwise, the behavior is undefined. If the result points
  one past the last element of the array object, it shall not be used as
  the operand of a unary * operator that is evaluated.

From this, it would appear that the behavior of the above program is undefined; ptr3_plus_1 points to an address one past the end of the array object from which it is derived, and dereferencing this address causes undefined behavior.

Further, Annex J.2 suggests that this is undefined behavior:

An array subscript is out of range, even if an object is apparently
  accessible with the given subscript (as in the lvalue expression
  a[1][7] given the declaration int a[4][5]) (6.5.6).

There is some discussion of this issue in the Stack Overflow question, One-dimensional access to a multidimensional array: well-defined C?. The consensus here appears to be that this kind of access to arbitrary elements of a two-dimensional array through one-dimensional subscripts is indeed undefined behavior.

The issue, as I see it, is that it is not even legal to form the address of the pointer ptr3_plus_2, so it is not legal to access arbitrary two-dimensional array elements in this way. But, it is legal to form the address of the pointer ptr3_plus_1 using this pointer arithmetic. Further, it is legal to compare the two pointers ptr3_plus_1 and ptr4, according to §6.5.9 ¶6:

Two pointers compare equal if and only if both are null pointers, both
  are pointers to the same object (including a pointer to an object and
  a subobject at its beginning) or function, both are pointers to one
  past the last element of the same array object, or one is a pointer
  to one past the end of one array object and the other is a pointer to
  the start of a different array object that happens to immediately
  follow the first array object in the address space.

So, if it both ptr3_plus_1 and ptr4 are valid pointers that compare equal and that must point to the same address (the object pointed to by ptr4 must be adjacent in memory to the object pointed to by ptr3 anyway, since array storage must be contiguous), it would seem that *ptr3_plus_1 is as valid as *ptr4.

Is this undefined behavior, as described in §6.5.6 ¶8 and Annex J.2, or is this an exceptional case?

To Clarify

It seems unambiguous that it is undefined behavior to attempt to access the element one past the end of the final row of a two-dimensional array. My interest is in the question of whether it is legal to access the first element of the intermediate rows by forming a new pointer using a pointer to an element from the previous row and pointer arithmetic. It seems to me that a different example in Annex J.2 could have made this more clear.

Is it possible to reconcile the clear statement in §6.5.6 ¶8 that an attempted dereference of a pointer to the location one past the end of an array leads to undefined behavior with the idea that the pointer past the end of the first row of a two-dimensional array of type T[][] is also a pointer of type T * that points to an object of type T, namely the first element of an array of type T[]?

Body:
So, if it both ptr3_plus_1 and ptr4 are valid pointers that compare equal and that must point to the same address

They are.

it would seem that *ptr3_plus_1 is as valid as *ptr4.

It is not.

The pointers are equal, but not equivalent. The trivial well-known example of the distinction between equality and equivalence is negative zero:

double a = 0.0, b = -0.0;
assert (a == b);
assert (1/a != 1/b);

Now, to be fair, there is a difference between the two, as positive and negative zero have a different representation, ptr3_plus_1 and ptr4 on typical implementations have the same representation. This is not guaranteed, and on implementations where they would have different representations, it should be clear that your code might fail.

Even on the typical implementations, while there are good arguments to be made that the same representation implies equivalent values, to the best of my knowledge, the official interpretation is that the standard does not guarantee this, therefore programs cannot rely on it, therefore implementations can assume programs do not do this and optimise accordingly.


问:
Send message from server at specific time in php?
Is there any way to send mail at specific time in php?

Please give me hint for that file. I forget to that file which is used to send mail to specific time.

答:
You want to use cron.php
this is file name i think you forget that name
right?</p>


问:
Using goto statement
```<code>static void Main(string[] args)
{
    double i, j;
    Console.WriteLine("Enter fnum");
    i = Convert.ToDouble(Console.ReadLine());
    start:
    Console.WriteLine("Enter snum");
    j = Convert.ToDouble(Console.ReadLine());

    if(j==0)
    {
        goto start;
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}
</code>```

I'm trying to implement Divide by zero using GOTO in c#. I got the result but here I would like to first calculate fnum/snum and print the result and then if I enter snum zero it should ask me enter snum other than zero.Then the goto start label should start working. But here in this case I was only able to execute fnum/snum by default.

```<code>Console.WriteLine("Enter fnum");
i = Convert.ToDouble(Console.ReadLine());
start:
Console.WriteLine("Enter snum");
j = Convert.ToDouble(Console.ReadLine());
</code>```

Here if I enter snum zero it should take me to start label and ask me "enter second number other zero"

Can any one help me?

答:
```<code>if(j==0)
{
    Console.WriteLine("snum cannot be 0!!");
    goto start;
}
</code>```

It is not recommended to use goto statements or get into the habit of using them.

They tend to increase complexity and create spaghetti code, they also affect readability as you add more and more of them. A bug caused by a goto statement can be tricky to fix. etc etc. others can edit more reasons not to use goto statements in if they wish.

Title: Using goto statement

Body:
static void Main(string[] args)
{
    double i, j;
    Console.WriteLine("Enter fnum");
    i = Convert.ToDouble(Console.ReadLine());
    start:
    Console.WriteLine("Enter snum");
    j = Convert.ToDouble(Console.ReadLine());

    if(j==0)
    {
        goto start;
    }

    Console.ReadLine();
    Console.WriteLine("Div result is {0}/{1}={2}", i, j, i / j);
}

I'm trying to implement Divide by zero using GOTO in c#. I got the result but here I would like to first calculate fnum/snum and print the result and then if I enter snum zero it should ask me enter snum other than zero.Then the goto start label should start working. But here in this case I was only able to execute fnum/snum by default.

Console.WriteLine("Enter fnum");
i = Convert.ToDouble(Console.ReadLine());
start:
Console.WriteLine("Enter snum");
j = Convert.ToDouble(Console.ReadLine());

Here if I enter snum zero it should take me to start label and ask me "enter second number other zero"

Can any one help me?

Body:
if(j==0)
{
    Console.WriteLine("snum cannot be 0!!");
    goto start;
}

It is not recommended to use goto statements or get into the habit of using them.

They tend to increase complexity and create spaghetti code, they also affect readability as you add more and more of them. A bug caused by a goto statement can be tricky to fix. etc etc. others can edit more reasons not to use goto statements in if they wish.


问:
How to call local json file using http get method using angular 2 webpack
I am using angular2 webpack and i want to call local json file using get method but its given me same above error

I tried above solution in my demo cli project its work fine for me but its same in webpack not working

Can any one please help me?

答:
Put your file (for example data.json) in the assets directory and then retrieve it using the path `/assets/data.json':</p>

```<code>this.http.get('/assets/data.json')
</code>```

Body:
Put your file (for example data.json) in the assets directory and then retrieve it using the path `/assets/data.json':

this.http.get('/assets/data.json')


问:
Got error on using mysqli_real_escape_string in WHERE IN clause
I'm working on existing project and there is an abstraction layer on database (previous developers made it and I should not change it).
I extracted functions from abstraction and it looks like this:

```<code>$sql = "SELECT id FROM user WHERE username IN ({users})";
$users = "alex,john";
$users = str_replace(',', "','", $users);
$users = mysqli_real_escape_string($dbh, $users);
//Here is a replace placeholder function for sql query
...
$query = mysqli_query($dbh, $sql);
</code>```

And I got an error:

You have an error in your SQL syntax; check the manual that corresponds to your ?MySQL server version for the right syntax to use near '\\'alex\',\\'john\\')' ?at line 1"

How to correct use mysqli_real_escape_string in WHERE IN clause?

答:
Try like this to prepare your $users variable,

```<code>$users = "alex,john";
$users=  "'".str_replace(",", "','", $users)."'";
</code>```

Edit:

```<code> $users_array= explode(',',$users);
 $users= "'". implode("', '", array_map('mysql_real_escape_string', $users_array)). "'";
</code>```

Body:
I'm working on existing project and there is an abstraction layer on database (previous developers made it and I should not change it).
I extracted functions from abstraction and it looks like this:

$sql = "SELECT id FROM user WHERE username IN ({users})";
$users = "alex,john";
$users = str_replace(',', "','", $users);
$users = mysqli_real_escape_string($dbh, $users);
//Here is a replace placeholder function for sql query
...
$query = mysqli_query($dbh, $sql);

And I got an error:

You have an error in your SQL syntax; check the manual that corresponds to your ?MySQL server version for the right syntax to use near '\\'alex\',\\'john\\')' ?at line 1"

How to correct use mysqli_real_escape_string in WHERE IN clause?

Body:
Try like this to prepare your $users variable,

$users = "alex,john";
$users=  "'".str_replace(",", "','", $users)."'";

Edit:

 $users_array= explode(',',$users);
 $users= "'". implode("', '", array_map('mysql_real_escape_string', $users_array)). "'";


问:
How to get on video Shell folder with command line for any windows system?
I'm making a new batch file to convert any *.mp4 files to *.mp3 files with VLC in command line, but i want to improve it to choose the Input folder on Videos for any windows system !

My question is : How to get on videos folder with command line for any windows system?

Here is my code : MP4-MP3_Converter.bat

@echo off
Title Convert (*.mp4) to (*.mp3) with VLC by (c) Hackoo 2017
mode con:cols=85 lines=5 & COLOR 0E
Taskkill /IM "vlc.exe" /F >nul 2>&1
echo.
set "VLC_URL=http://www.videolan.org/vlc/download-windows.html"

IF /I "%PROCESSOR_ARCHITECTURE%"=="x86" (
        Set "vlc=%ProgramFiles%\VideoLAN\VLC\vlc.exe"
    ) else (
        Set "vlc=%ProgramFiles(x86)%\VideoLAN\VLC\vlc.exe"
)

If Not Exist "%vlc%" (
    Cls & COLOR 0C
    echo.
    Echo       "The VLC program is not installed on your system"
    TimeOut /T 5 /NoBreak>nul
    Start "" %VLC_URL%
    Exit
)

Set "MP4Folder=C:\MP4Folder"
Set "MP3Folder=C:\MP3Folder"
If not exist "%MP3Folder%" MD "%MP3Folder%"
CD /D "%MP4Folder%"
for %%a in (*.mp4) do (
    Cls
    echo(
    echo           Please wait a while ... The Conversion is in progress ...
    echo   Conversion of "%%~na.mp4" to "%%~na.mp3"
    "%vlc%" -I dummy "%%a" --sout=#transcode{acodec=mp3,ab=128,vcodec=dummy}:std{access="file",mux="raw",dst="%MP3Folder%\%%~na.mp3"} vlc://quit
)
Explorer "%MP3Folder%" & Exit
```

答:
Thanks to @LotPings,that put me on the right direction !

So we could hack it to get it working in batch, as there are some registry keys that contain this information. we can find them in HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders "My Video" would be the needed value.

So with this batch file we can do it :

@echo off
Set "ShellFolderKey=HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
Set "MyKey=My Video"
@For /f "tokens=4,* Delims= " %%A in ('Reg Query "%ShellFolderKey%" /v "%MyKey%" ^| Findstr /C:"%MyKey%"') Do (
    Set "MyVideoShellFolder=%%A"
)
echo "%MyVideoShellFolder%"
pause
```


问:
php return empty array using angular js?
i want get arrayobject from php file using angular js, this works but array   does not display content in the browser:

my php file:

```<code><?php

include_once '../DAO/DAOadmin.php';

$list = DAOadmin::All();

$json = json_encode($list);
echo $json;
</code>```

angular js:

```<code>scope.all = function(){
       $http.get('/App/Test/getAll.php').then(function(data){
                $scope.model = data;
            });
}
</code>```

the network show this:

Also i tired using print_r but not work:

答:
Something wrong with the script and try to run the php script through the browser and see the results. Then you will probably get the answer.

look like $list is not an array it could be a pdo object, convert pdo object to array and assign it to $list.

Body:
i want get arrayobject from php file using angular js, this works but array   does not display content in the browser:

my php file:

<?php

include_once '../DAO/DAOadmin.php';

$list = DAOadmin::All();

$json = json_encode($list);
echo $json;

angular js:

scope.all = function(){
       $http.get('/App/Test/getAll.php').then(function(data){
                $scope.model = data;
            });
}

the network show this:

Also i tired using print_r but not work:


答:
For that you should use a cron job. Cron may be used to launch scripts of any sort (in your case a phpscript).
The usage is pretty simple.</p>

Title: Send message from server at specific time in php?

Body:
Is there any way to send mail at specific time in php?

Please give me hint for that file. I forget to that file which is used to send mail to specific time.