问:
Representing a large number using __int128
__int128 can be used to represent 16 byte numbers, i.e:

```<code>__int128 a = -1;
</code>```

Will set a to 128 bits of 1.
However the following does not compile:

```<code>int main(){
  __int128 a = 113427455640312821154458202477256070485;
  return 0;
}
</code>```

With the error:

```<code>error: integer literal is too large to be represented in any integer type
</code>```

Why is the number unable to b represented although it's 127 bits wide?

答:
Because an integer constant in C is treated as, from the standard, "the first of the corresponding list in which its value can be represented".

The list for a non-suffixed decimal integer is:

int;

long int; and

long long int.

Unless your long long int types are the full 128 bits, that value won't fit. The standard allows for an implementation to fix this by virtue of the text (my emphasis):

If an integer constant cannot be represented by any type in its list, it may have an extended integer type, if the extended integer type can represent its value.

However, the use of the word "may" means that an implementation is not required to do this. You'd think it would make sense for a compiler with an extended type to provide a way of creating a constant of that type(1). Unfortunately, gcc appears not to do this, meaning you'll have to do some trickery along the lines of (check those digit counts, I'm not guaranteeing they're correct, just showing you the ugly nature of the workaround):

```<code>// long long int can go to 9223372036854775807,
// so break into chunks of 15.
__int128 a = 113427455;
a *=  1000000000000000; // 1e15
a +=   640312821154458;
a *=  1000000000000000;
a +=   202477256070485;
</code>```

Alternatively, if you want to keep the number together and don't mind a small performance hit, you can use a function to build it at runtime, as per the example program below:

```<code>int Mk128(char *str, __int128 *p128) {
    // Handle sign.

    __int128 mult = 1;
    if (*str == '-') {
        mult = -1;
        str++;
    }

    // Collect digits into number, handling grouping.

    *p128 = 0;
    while (*str != '\0') {
        if (*str >= '0' && *str <= '9') {
            *p128 = *p128 * 10 + *str - '0';
        } else if (*str != ',' && *str != ' ' && *str != '.') {
            return 0;
        }
        str++;
    }

    // Adjust for sign and return.

    *p128 *= mult;
    return 1;
}

#include <stdio.h>

// Recursive printer for large numbers, with grouping.

void print128(__int128 x, char *sep) {
     // Handle negatives.

    if (x < 0) {
        putchar('-');
        print128(-x, sep);
        return;
    }

    // Print the top section, we're on the last recursion.

    if (x < 1000) {
        printf("%d", (int)x);
        return;
    }

    // Otherwise recurse, then print this grouping.

    print128(x / 1000, sep);
    printf("%s%03d", sep, (int)(x % 1000));
}

// Test harness, just provide test data as arguments.

int main(int argc, char *argv[]){
    __int128 a;
    puts("=====");
    for (int i = 1; i < argc; i++) {
        puts(argv[i]);
        if (! Mk128(argv[i], &a)) {
            puts("*** Failed to make big int");
        } else {
            print128(a, ",");
            putchar('\n');
        }
        puts("=====");
    }

    return 0;
}
</code>```

This allows a string to be used with the following properties:

It can have either no, or one, leading - sign. If you want a positive number, just leave it off the -, no leading + allowed. This is basically how most people would write an integer constant in their code.

It can have spaces, commas, or periods, interspersed with the digits in any manner, but intended to allow for grouping of digits as per the sample run below. The periods are to cater for the Euro habit of swapping commas and periods for grouping and decimal points.

It also has a recursive print function so you can test it, used by the main function to show that the evaluation of the strings has worked.

A sample run:

```<code>pax:~> ./testprog 12345 -77 '-12.345,111,111.678.734.333,222 555 777' hello
=====
12345
12,345
=====
-77
-77
=====
-12.345,111,111.678.734.333,222 555 777
-12,345,111,111,678,734,333,222,555,777
=====
hello
*** Failed to make big int
=====
</code>```

(1) There are some subtle interactions in the standard that make this difficult. Specifically, the [u]intmax_t types are supposed to be able to handle any of the integral types so, in cases where they remain at 64-bit, the 128-bit value is not actually considered an extended integer type, but rather a non-standard extension.

GCC actually calls this out in their documentation:

GNU C provides several language features not found in ISO standard C.

If it was an extended integer type, it would be covered by the standard.

Body:
__int128 can be used to represent 16 byte numbers, i.e:

__int128 a = -1;

Will set a to 128 bits of 1.
However the following does not compile:

int main(){
  __int128 a = 113427455640312821154458202477256070485;
  return 0;
}

With the error:

error: integer literal is too large to be represented in any integer type

Why is the number unable to b represented although it's 127 bits wide?

Body:
Because an integer constant in C is treated as, from the standard, "the first of the corresponding list in which its value can be represented".

The list for a non-suffixed decimal integer is:

int;

long int; and

long long int.

Unless your long long int types are the full 128 bits, that value won't fit. The standard allows for an implementation to fix this by virtue of the text (my emphasis):

If an integer constant cannot be represented by any type in its list, it may have an extended integer type, if the extended integer type can represent its value.

However, the use of the word "may" means that an implementation is not required to do this. You'd think it would make sense for a compiler with an extended type to provide a way of creating a constant of that type(1). Unfortunately, gcc appears not to do this, meaning you'll have to do some trickery along the lines of (check those digit counts, I'm not guaranteeing they're correct, just showing you the ugly nature of the workaround):

// long long int can go to 9223372036854775807,
// so break into chunks of 15.
__int128 a = 113427455;
a *=  1000000000000000; // 1e15
a +=   640312821154458;
a *=  1000000000000000;
a +=   202477256070485;

Alternatively, if you want to keep the number together and don't mind a small performance hit, you can use a function to build it at runtime, as per the example program below:

int Mk128(char *str, __int128 *p128) {
    // Handle sign.

    __int128 mult = 1;
    if (*str == '-') {
        mult = -1;
        str++;
    }

    // Collect digits into number, handling grouping.

    *p128 = 0;
    while (*str != '\0') {
        if (*str >= '0' && *str <= '9') {
            *p128 = *p128 * 10 + *str - '0';
        } else if (*str != ',' && *str != ' ' && *str != '.') {
            return 0;
        }
        str++;
    }

    // Adjust for sign and return.

    *p128 *= mult;
    return 1;
}

#include <stdio.h>

// Recursive printer for large numbers, with grouping.

void print128(__int128 x, char *sep) {
     // Handle negatives.

    if (x < 0) {
        putchar('-');
        print128(-x, sep);
        return;
    }

    // Print the top section, we're on the last recursion.

    if (x < 1000) {
        printf("%d", (int)x);
        return;
    }

    // Otherwise recurse, then print this grouping.

    print128(x / 1000, sep);
    printf("%s%03d", sep, (int)(x % 1000));
}

// Test harness, just provide test data as arguments.

int main(int argc, char *argv[]){
    __int128 a;
    puts("=====");
    for (int i = 1; i < argc; i++) {
        puts(argv[i]);
        if (! Mk128(argv[i], &a)) {
            puts("*** Failed to make big int");
        } else {
            print128(a, ",");
            putchar('\n');
        }
        puts("=====");
    }

    return 0;
}

This allows a string to be used with the following properties:

It can have either no, or one, leading - sign. If you want a positive number, just leave it off the -, no leading + allowed. This is basically how most people would write an integer constant in their code.

It can have spaces, commas, or periods, interspersed with the digits in any manner, but intended to allow for grouping of digits as per the sample run below. The periods are to cater for the Euro habit of swapping commas and periods for grouping and decimal points.

It also has a recursive print function so you can test it, used by the main function to show that the evaluation of the strings has worked.

A sample run:

pax:~> ./testprog 12345 -77 '-12.345,111,111.678.734.333,222 555 777' hello
=====
12345
12,345
=====
-77
-77
=====
-12.345,111,111.678.734.333,222 555 777
-12,345,111,111,678,734,333,222,555,777
=====
hello
*** Failed to make big int
=====

(1) There are some subtle interactions in the standard that make this difficult. Specifically, the [u]intmax_t types are supposed to be able to handle any of the integral types so, in cases where they remain at 64-bit, the 128-bit value is not actually considered an extended integer type, but rather a non-standard extension.

GCC actually calls this out in their documentation:

GNU C provides several language features not found in ISO standard C.

If it was an extended integer type, it would be covered by the standard.


来源: stackexchange

问:
How can I multiply together every nth cell in a row to get the product?
I want to calculate the product of the investment returns (compound interest), which in this instance would give a return of 162%:

Additional stock return data will be added in future, so I need a formula that compounds every nth (2nd) value. I am able to sum the cells using:
=SUMIF(ARRAYFORMULA(MOD((COLUMN(A2:H2)-COLUMN(A2)+1),2)),0,A2:H2)

However I cannot find an equivalent 'PRODUCTIF' function and have not been able to make a formula that works. Writing the formula out long hand would be:
=B2*D2*F2*H2

答:
You can also use the following formula:

```<code>=PRODUCT(TRANSPOSE(2:2))</code>```

and format the result as Percent from the menu

Functions used:

TRANSPOSE

PRODUCT

EDIT

As correctly noted by Mat, an even simpler formula can also give the correct results.

```<code>=PRODUCT(2:2)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can also use the following formula:

=PRODUCT(TRANSPOSE(2:2))

and format the result as Percent from the menu

Functions used:

TRANSPOSE

PRODUCT

EDIT

As correctly noted by Mat, an even simpler formula can also give the correct results.

=PRODUCT(2:2)


问:
Different array declaration in c while using scanf
What is the difference  with </p>

```<code>  for(i=0;i<j;i++)
  scanf("%d",&a[i]);
</code>```

<p>and </p>

```<code>for(i=0;i<j;i++)
scanf("%d",a+i);
</code>```

答:
There is no difference.  &a[i] is exactly the same as a+i.

Section 6.5.2.1p2 of the C standard regarding the array index operator [] states:

A  postfix  expression  followed  by  an  expression  in  square
  brackets [] is  a  subscripted designation of an element of an array
  object.  The definition of the subscript operator [] is that
  E1[E2] is identical to (*((E1)+(E2))). Because of the conversion
  rules that apply  to  the  binary + operator,  if E1 is  an  array
  object  (equivalently,  a  pointer  to  the initial  element  of  an
  array  object)  and E2 is  an  integer, E1[E2] designates  the
  E2-th element of E1 (counting from zero).

Body:
What is the difference  with

  for(i=0;i<j;i++)
  scanf("%d",&a[i]);

and

for(i=0;i<j;i++)
scanf("%d",a+i);


问:
The CGI application did not return a valid set of HTTP errors. 502.3 - Bad Gateway: Forwarder Connection Error (ARR) on Azure ASP.NET Core App
All of a sudden we are seeing this random error / exception in our web application.

Failed to load resource: the server responded with a status of 502 (Bad Gateway).

In the Log Stream, we are seeing the following details, with specific error code as 502.3 - Bad Gateway: Forwarder Connection Error (ARR).

Also, sometimes in the browser itself we see "The CGI application did not return a valid set of HTTP errors." getting displayed.

Most of the searches for these error codes refer to "IIS / Proxy Server" configuration. But, we haven't changed any such settings.

The error happens very randomly and not specific to any user action/function. Same functionality works first and on second execution immediately after first one throws this error.

How to figure out what is causing this and how to fix?

答:
I google this question, because the program was normal at the beginning, and the subsequent 502.3 error. After I checked the information on the Internet, I feel that it can only give us an inspiration, and it cannot solve your problem immediately.

So my suggestion is that first you browse  post1 and post2  I provided.

Next, proceed to Troubleshoot according to the steps of the official documentation. Specific errors require specific analysis.


问:
Combine equivalent of RxJS iif
iif is a useful operator that can decide which Observable to subscribe to at runtime. Is there an equivalent in Swift Combine framework with publisher? If not, what's a good workaround?</p>

答:
There isn't a direct equivalent, but you can use a Deferred publisher:

```<code>let p1: AnyPublisher<Int, Never> = ...
let p2: AnyPublisher<Int, Never> = ...

let condition = Bool.random()

let iif = Deferred { condition ? p1 : p2 }

</code>```

Title: Combine equivalent of RxJS iif

Body:
There isn't a direct equivalent, but you can use a Deferred publisher:

let p1: AnyPublisher<Int, Never> = ...
let p2: AnyPublisher<Int, Never> = ...

let condition = Bool.random()

let iif = Deferred { condition ? p1 : p2 }


问:
Python- Why does it say password denied even when I enter a password that should work?
```<code>
userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):

    if userpass[i].isupper():
        uppercounter=uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].islower():
        lowercounter=lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")
            print("Password Accepted")
    else:
        print('Password Denied')
        raise SystemExit(0)

</code>```

<p>I’m trying to make a program for a password that must contain one uppercase letter, one lowercase letter, and one number. But the if statements don’t seem to be working properly and whenever I enter a password like “Py11”, it says password denied. </p>

答:
For every char of the password you are checking againt all three conditions:
lets say you typed in: "hi"

for the first loop you'll be in letter "h"
if it is upper (which is not) your else you be executed running the password denied part (thats the problem)

In order to acomplish what you want I suggest checking like this:

```<code>if condition1:
    pass #add here the counting you are making
elif condition2:
    pass #add here the counting you are making
elif condition3:
    pass #add here the counting you are making
# [...]
else:
    print("password denied")
</code>```

and for the conditions you check for upper, lower, numeric and if you want to allow special chars you need to check for them also

Other way you could do it:

```<code>userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):
    if userpass[i].isupper():
        uppercounter=uppercounter+1
    if userpass[i].islower():
        lowercounter=lowercounter+1
    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
if uppercounter == 0 or lowercounter == 0 or numbercounter == 0:
    print("Password denied")
    raise SystemExit(0)
</code>```

this way you don't have to check against other special chars

Body:
userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):

    if userpass[i].isupper():
        uppercounter=uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].islower():
        lowercounter=lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")
            print("Password Accepted")
    else:
        print('Password Denied')
        raise SystemExit(0)

I’m trying to make a program for a password that must contain one uppercase letter, one lowercase letter, and one number. But the if statements don’t seem to be working properly and whenever I enter a password like “Py11”, it says password denied.

Body:
For every char of the password you are checking againt all three conditions:
lets say you typed in: "hi"

for the first loop you'll be in letter "h"
if it is upper (which is not) your else you be executed running the password denied part (thats the problem)

In order to acomplish what you want I suggest checking like this:

if condition1:
    pass #add here the counting you are making
elif condition2:
    pass #add here the counting you are making
elif condition3:
    pass #add here the counting you are making
# [...]
else:
    print("password denied")

and for the conditions you check for upper, lower, numeric and if you want to allow special chars you need to check for them also

Other way you could do it:

userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):
    if userpass[i].isupper():
        uppercounter=uppercounter+1
    if userpass[i].islower():
        lowercounter=lowercounter+1
    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
if uppercounter == 0 or lowercounter == 0 or numbercounter == 0:
    print("Password denied")
    raise SystemExit(0)

this way you don't have to check against other special chars


问:
RichText WYSIWYG editor without UI (JavaScript API only)
I am looking for a very clean project to add cross-browser JavaScript API to contenteditable div.

If it has UI, then it should be possible not to load it (as opposed to disabling it) or completely remove from sources.

I am looking for basic features really without huge focus on backward-compatibility but rather a cleaner code.

Some of the features, I would expect from this API would be:

Insert HTML snippet at the position of the cursor

Clean up contents after paste (such as spans and font sizes)

Return node, where cursor currently is positioned

Add new item to item list

I suppose I could code them with some jQuery, but if someone have it, why not re-use it.

答: TinyMice is also good choice. It has jQuery API

ContentLicense: CC BY-SA 3.0


问:
How can you use kendo-fileselect to upload from an angular app to a C# web API?
We're implementing kendo for angular in our project.  We have an existing project that is using kendo-upload which immediately fires a call to the server, but I can't do that for this page.

The page is for an employee to upload a resume.  They may have an existing resume and will need to be asked if they want to replace it first, and they are given a field for entering a description.  Thus, I think I need to use kendo-fileselect and potentially trigger a dialog (are you sure you want to replace?), and send along the description and employee's ID on a button click. So I've created an object to carry this data.

You can see that the object is populated when it calls the API:

But when I try to call the API method, I get an error:

```<code>Failed to load resource: the server responded with a status of 400 (Bad Request) [http://localhost:6300/api/employee/resume]
</code>```

Relevant code is below.

Server-side:

```<code>public class EmployeeResume
{
    public int ResumeId { get; set; }
    public int EmployeeId { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Description { get; set; }
    public byte[] FileContent { get; set; }
    public string FileName { get; set; }
}

[HttpPut("resume")]
    public async Task<IActionResult> UploadResume([FromBody] EmployeeResume resume)
    {
        if (resume == null)
        {
            return BadRequest();
        }

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

Client-side:

```<code>// Model
export interface EmployeeResume {
    createdDate?: string;
    description?: string;
    employeeId: string;
    fileContent: any;
    fileName: string;
    resumeId?: string;
}

// CHILD component
// -----------------------------------------------------------

// Kendo FileSelect in template
<kendo-fileselect
    formControlName="uploadFile"
    [restrictions]="uploadRestrictions"
    [multiple]="false"
    (select)="selectEventHandler($event)">
</kendo-fileselect>

// Sets a component property to the selected file
selectEventHandler(e: SelectEvent): void {
    this.uploadfile = e.files[0];
}

// When upload button is clicked, create the
// resume object and emit an event to parent
upload(): void {

    if (this.uploadfile.validationErrors) return;

    const thisComponent = this;
    const reader = new FileReader();

    reader.onload = function (ev) {
      const request = {
        description: thisComponent.f.description.value,
        employeeId: thisComponent.employeeId,
        fileContent: ev.target.result,
        fileName: thisComponent.uploadfile.name
      } as EmployeeResume;

      thisComponent.onUpload.emit(request);
    }

    reader.readAsDataURL(this.uploadfile.rawFile);
}

// PARENT component
// -----------------------------------------------------------

// Template
<app-employee-resume
    [employeeId]="(employeeId$ | async)"
    (onUpload)="uploadResume($event)">
</app-employee-resume>

// Handler
uploadResume(resume: EmployeeResume) {
    this.svc.upsertResume(resume)
}

// 'svc'
upsertResume(resume: EmployeeResume) {
    return this.http.put(`${this.apiUrl}/employee/resume`, resume);
}
</code>```

答:
You can use the ts FormData and a custom FileData object with any extra properties you want to store to the DB for this:

```<code>  onFileSelected(e: SelectEvent): void {
    this.uploadfile = e.files[0].rawFile;
  }

upload(): void {

const formData = new FormData();
const fileForSave = new FileData();

fileForSave.fileCategoryId = FileCategory.EmployeeResume;
fileForSave.description = this.f['description'].value;
fileForSave.employeeId = this.employeeId;

if (this.uploadfile) formData.append('file', this.uploadfile);
formData.append('fileForSave', JSON.stringify(fileForSave));

this.onUpload.emit(formData);
this.resetForm();
  }

  addFile(form: FormData): Observable<FileData> {
    return this.http.post<FileData>(`${this.apiUrl}/file/`, form);
  }
</code>```

Then your API method will look something like this:

```<code>    [HttpPost]
    public async Task<IActionResult> AddFile(
        IFormFile file,
        [ModelBinder(BinderType = typeof(JsonModelBinder))] Contracts.Entities.File fileForSave)
    {
        // Check any file validations if you want

        /* Save the IFormFile file to disk */

        /* Save entity fileForSave File object to the DB */

        return Ok(newFile);
    }
</code>```

And I'll even throw this in for ya:

```<code>public class JsonModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // Check the value sent in
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != ValueProviderResult.None)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            // Attempt to convert the input value
            var valueAsString = valueProviderResult.FirstValue;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType);
            if (result != null)
            {
                bindingContext.Result = ModelBindingResult.Success(result);
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }
}
</code>```

Body:
We're implementing kendo for angular in our project.  We have an existing project that is using kendo-upload which immediately fires a call to the server, but I can't do that for this page.

The page is for an employee to upload a resume.  They may have an existing resume and will need to be asked if they want to replace it first, and they are given a field for entering a description.  Thus, I think I need to use kendo-fileselect and potentially trigger a dialog (are you sure you want to replace?), and send along the description and employee's ID on a button click. So I've created an object to carry this data.

You can see that the object is populated when it calls the API:

But when I try to call the API method, I get an error:

Failed to load resource: the server responded with a status of 400 (Bad Request) [http://localhost:6300/api/employee/resume]

Relevant code is below.

Server-side:

public class EmployeeResume
{
    public int ResumeId { get; set; }
    public int EmployeeId { get; set; }
    public DateTime CreatedDate { get; set; }
    public string Description { get; set; }
    public byte[] FileContent { get; set; }
    public string FileName { get; set; }
}

[HttpPut("resume")]
    public async Task<IActionResult> UploadResume([FromBody] EmployeeResume resume)
    {
        if (resume == null)
        {
            return BadRequest();
        }

        return Ok();
    }

Client-side:

// Model
export interface EmployeeResume {
    createdDate?: string;
    description?: string;
    employeeId: string;
    fileContent: any;
    fileName: string;
    resumeId?: string;
}

// CHILD component
// -----------------------------------------------------------

// Kendo FileSelect in template
<kendo-fileselect
    formControlName="uploadFile"
    [restrictions]="uploadRestrictions"
    [multiple]="false"
    (select)="selectEventHandler($event)">
</kendo-fileselect>

// Sets a component property to the selected file
selectEventHandler(e: SelectEvent): void {
    this.uploadfile = e.files[0];
}

// When upload button is clicked, create the
// resume object and emit an event to parent
upload(): void {

    if (this.uploadfile.validationErrors) return;

    const thisComponent = this;
    const reader = new FileReader();

    reader.onload = function (ev) {
      const request = {
        description: thisComponent.f.description.value,
        employeeId: thisComponent.employeeId,
        fileContent: ev.target.result,
        fileName: thisComponent.uploadfile.name
      } as EmployeeResume;

      thisComponent.onUpload.emit(request);
    }

    reader.readAsDataURL(this.uploadfile.rawFile);
}

// PARENT component
// -----------------------------------------------------------

// Template
<app-employee-resume
    [employeeId]="(employeeId$ | async)"
    (onUpload)="uploadResume($event)">
</app-employee-resume>

// Handler
uploadResume(resume: EmployeeResume) {
    this.svc.upsertResume(resume)
}

// 'svc'
upsertResume(resume: EmployeeResume) {
    return this.http.put(`${this.apiUrl}/employee/resume`, resume);
}

Body:
You can use the ts FormData and a custom FileData object with any extra properties you want to store to the DB for this:

  onFileSelected(e: SelectEvent): void {
    this.uploadfile = e.files[0].rawFile;
  }

upload(): void {

const formData = new FormData();
const fileForSave = new FileData();

fileForSave.fileCategoryId = FileCategory.EmployeeResume;
fileForSave.description = this.f['description'].value;
fileForSave.employeeId = this.employeeId;

if (this.uploadfile) formData.append('file', this.uploadfile);
formData.append('fileForSave', JSON.stringify(fileForSave));

this.onUpload.emit(formData);
this.resetForm();
  }

  addFile(form: FormData): Observable<FileData> {
    return this.http.post<FileData>(`${this.apiUrl}/file/`, form);
  }

Then your API method will look something like this:

    [HttpPost]
    public async Task<IActionResult> AddFile(
        IFormFile file,
        [ModelBinder(BinderType = typeof(JsonModelBinder))] Contracts.Entities.File fileForSave)
    {
        // Check any file validations if you want

        /* Save the IFormFile file to disk */

        /* Save entity fileForSave File object to the DB */

        return Ok(newFile);
    }

And I'll even throw this in for ya:

public class JsonModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // Check the value sent in
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult != ValueProviderResult.None)
        {
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);

            // Attempt to convert the input value
            var valueAsString = valueProviderResult.FirstValue;
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject(valueAsString, bindingContext.ModelType);
            if (result != null)
            {
                bindingContext.Result = ModelBindingResult.Success(result);
                return Task.CompletedTask;
            }
        }

        return Task.CompletedTask;
    }
}


问:
Java: two threads printing & receiving user input via Scanner: program doesn't exit after exception is thrown
I have this program with two threads: lessonThread and questionThread. The lesson thread prints Lesson continues, while the question thread every 5 seconds asks Finish lesson? and asks a user for input via Scanner. I have a wait() call in questionThread that throws an exception. In the catch block I use System.exit() to terminate the program, however it doesn't work right away - only after many lesson messages. At the same time, if I go through breakpoints in both thread in a debugger, it System.exit() terminates the program very soon.

```<code>public class LessonNotify {
    private volatile boolean finished;
    private Scanner scanner = new Scanner(System.in);

    private Thread lessonThread;
    private Thread questionThread;

    public static void main(String[] args) {
        LessonNotify lesson = new LessonNotify();
        lesson.lessonThread = lesson.new LessonThread();
        lesson.questionThread = lesson.new QuestionThread();

        lesson.lessonThread.start();
        lesson.questionThread.start();
    }

    class LessonThread extends Thread  {
        @Override
        public void run()  {
            while (!finished)  {
                System.out.println("Lesson continues");
            }
        }
    }

    class QuestionThread extends Thread {
        private Instant sleepStart = Instant.now();
        @Override
        public void run() {
            while (!finished) {
                if (Instant.now().getEpochSecond() - sleepStart.getEpochSecond() >= 5) {
                    try {
                        lessonThread.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                        finished = true;
                        System.exit(0);
                    }

                    System.out.print("Finish a lesson? y/n");

                    String reply = scanner.nextLine().substring(0, 1);
                    switch (reply.toLowerCase()) {
                        case "y":
                            finished = true;
                    }

                    sleepStart = Instant.now();

                    lessonThread.notify();

                }
            }
        }
    }
}
</code>```

答:
That's just how exiting works. The messages printed by the other thread, especially because it has no breaks on the car, are already in various buffers. By using a debugger the thread is frozen or at least runs slower, thus, you don't observe it.

See my other answer. When I said 'this is not how you thread' - there are a billion reasons why, and this is one of the billion.

Body:
I have this program with two threads: lessonThread and questionThread. The lesson thread prints Lesson continues, while the question thread every 5 seconds asks Finish lesson? and asks a user for input via Scanner. I have a wait() call in questionThread that throws an exception. In the catch block I use System.exit() to terminate the program, however it doesn't work right away - only after many lesson messages. At the same time, if I go through breakpoints in both thread in a debugger, it System.exit() terminates the program very soon.

public class LessonNotify {
    private volatile boolean finished;
    private Scanner scanner = new Scanner(System.in);

    private Thread lessonThread;
    private Thread questionThread;

    public static void main(String[] args) {
        LessonNotify lesson = new LessonNotify();
        lesson.lessonThread = lesson.new LessonThread();
        lesson.questionThread = lesson.new QuestionThread();

        lesson.lessonThread.start();
        lesson.questionThread.start();
    }

    class LessonThread extends Thread  {
        @Override
        public void run()  {
            while (!finished)  {
                System.out.println("Lesson continues");
            }
        }
    }

    class QuestionThread extends Thread {
        private Instant sleepStart = Instant.now();
        @Override
        public void run() {
            while (!finished) {
                if (Instant.now().getEpochSecond() - sleepStart.getEpochSecond() >= 5) {
                    try {
                        lessonThread.wait();
                    } catch (Exception e) {
                        e.printStackTrace();
                        finished = true;
                        System.exit(0);
                    }

                    System.out.print("Finish a lesson? y/n");

                    String reply = scanner.nextLine().substring(0, 1);
                    switch (reply.toLowerCase()) {
                        case "y":
                            finished = true;
                    }

                    sleepStart = Instant.now();

                    lessonThread.notify();

                }
            }
        }
    }
}


问:
Wait Until Webpack Dev Server Is Ready
Requirements

I need to run the webpack-dev-server and wait until the server is ready to serve pages.

Solution

```<code>// Start a webpack-dev-server
new WebpackDevServer(webpack(myConfig), {
    publicPath: myConfig.output.publicPath,
    hot: true,
    historyApiFallback: true,
    // It suppress error shown in console, so it has to be set to false.
    quiet: false,
    // It suppress everything except error, so it has to be set to false as well
    // to see success build.
    noInfo: false,
    stats: {
        // Config for minimal console.log mess.
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
    }
}).listen(3000, '0.0.0.0', function(err) {
    if(err) throw new gutil.PluginError('webpack-dev-server', err);
    gutil.log('[webpack-dev-server]', 'http://0.0.0.0:3000/webpack-dev-server/index.html');
    //this is to ensure that end to end test wouldn't start running until the server is ready
    http.get({
        hostname: '0.0.0.0',
        port: 3000,
        path: '/',
        agent: false  // create a new agent just for this one request
    }, (/*res*/) => {
        // Do stuff with response
        done();
    });
});
</code>```

Problem

On Linux a have a wait until the server is ready. On Windows I get an exception because there is no wait and the server is not ready

C:\development\ucms-react>gulp webpack-dev-server [11:03:01] Requiring
  external module babel-register [11:03:07] Using gulpfile
  C:\development\ucms-react\gulpfile.babel.js [11:03:07] Starting
  'webpack-dev-server'... [11:03:07] [webpack-dev-server]
  http://0.0.0.0:3000/webpack-dev-server/index.html error events.js:141
        throw er; // Unhandled 'error' event
        ^

Error: connect EADDRNOTAVAIL 0.0.0.0:3000
      at Object.exports._errnoException (util.js:907:11)
      at exports._exceptionWithHostPort (util.js:930:20)
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)

C:\development\ucms-react>

How can I solve this issue?

答:
Here's another solution (inspired by @CameronTacklind's answer). The setImmediate makes the log output show up below the initial compiler log output.

```<code>const PORT = process.env.PORT || 3000

const compiler = webpack(config)
new WebpackDevServer(compiler).listen(PORT, '0.0.0.0', err => {
    if (err) {
        console.log(err)
    }
})

compiler.hooks.done.tap('done', () => {
    setImmediate(() => {
        console.log()
        console.log(`Running at http://localhost:${PORT}`)
    })
})
</code>```

UPDATE

Here's an alternative version that doesn't require a custom server script—you can just add this to your webpack config options. It also preserves the built-in feature of automatically using a different port if the default one isn't available...of course, if you'd rather specify your port, you don't have to use that part.

```<code>const chalk = require('chalk')
...

module.exports = {
    ....
    devServer: {
        onListening: server => {
            const { port } = server.listeningApp.address()
            server.compiler.hooks.done.tap('done', () => {
                setImmediate(() => {
                    console.log()
                    console.log(
                        chalk.cyan.bold(`Running at http://localhost:${port}`)
                    )
                })
            })
        },
    }
}
</code>```

Title: Wait Until Webpack Dev Server Is Ready

Body:
Requirements

I need to run the webpack-dev-server and wait until the server is ready to serve pages.

Solution

// Start a webpack-dev-server
new WebpackDevServer(webpack(myConfig), {
    publicPath: myConfig.output.publicPath,
    hot: true,
    historyApiFallback: true,
    // It suppress error shown in console, so it has to be set to false.
    quiet: false,
    // It suppress everything except error, so it has to be set to false as well
    // to see success build.
    noInfo: false,
    stats: {
        // Config for minimal console.log mess.
        assets: false,
        colors: true,
        version: false,
        hash: false,
        timings: false,
        chunks: false,
        chunkModules: false
    }
}).listen(3000, '0.0.0.0', function(err) {
    if(err) throw new gutil.PluginError('webpack-dev-server', err);
    gutil.log('[webpack-dev-server]', 'http://0.0.0.0:3000/webpack-dev-server/index.html');
    //this is to ensure that end to end test wouldn't start running until the server is ready
    http.get({
        hostname: '0.0.0.0',
        port: 3000,
        path: '/',
        agent: false  // create a new agent just for this one request
    }, (/*res*/) => {
        // Do stuff with response
        done();
    });
});

Problem

On Linux a have a wait until the server is ready. On Windows I get an exception because there is no wait and the server is not ready

C:\development\ucms-react>gulp webpack-dev-server [11:03:01] Requiring
  external module babel-register [11:03:07] Using gulpfile
  C:\development\ucms-react\gulpfile.babel.js [11:03:07] Starting
  'webpack-dev-server'... [11:03:07] [webpack-dev-server]
  http://0.0.0.0:3000/webpack-dev-server/index.html error events.js:141
        throw er; // Unhandled 'error' event
        ^

Error: connect EADDRNOTAVAIL 0.0.0.0:3000
      at Object.exports._errnoException (util.js:907:11)
      at exports._exceptionWithHostPort (util.js:930:20)
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1077:14)

C:\development\ucms-react>

How can I solve this issue?

Body:
Here's another solution (inspired by @CameronTacklind's answer). The setImmediate makes the log output show up below the initial compiler log output.

const PORT = process.env.PORT || 3000

const compiler = webpack(config)
new WebpackDevServer(compiler).listen(PORT, '0.0.0.0', err => {
    if (err) {
        console.log(err)
    }
})

compiler.hooks.done.tap('done', () => {
    setImmediate(() => {
        console.log()
        console.log(`Running at http://localhost:${PORT}`)
    })
})

UPDATE

Here's an alternative version that doesn't require a custom server script—you can just add this to your webpack config options. It also preserves the built-in feature of automatically using a different port if the default one isn't available...of course, if you'd rather specify your port, you don't have to use that part.

const chalk = require('chalk')
...

module.exports = {
    ....
    devServer: {
        onListening: server => {
            const { port } = server.listeningApp.address()
            server.compiler.hooks.done.tap('done', () => {
                setImmediate(() => {
                    console.log()
                    console.log(
                        chalk.cyan.bold(`Running at http://localhost:${port}`)
                    )
                })
            })
        },
    }
}


问:
Which Path should I use in my website? Related path absolute path?
I am building website for my client. I was wondering which path should I use for my website? which path is more secure? also correct me if I am totally wrong or if you have other reason for safety concerns for website! Thanks in advance.

For example...

```<code><script src="https://example.com/admin/js/myjavascript.js"></script>
or
<script src="/js/myjavascript.js"></script>

<img src="https://swadtiffin.ca/wp-content/uploads/myimg.jpg" alt="Loading...!">
or
<img src="/wp-content/uploads/myimg.jpg" alt="Loading...!">

$http({
  method: 'POST',
  url: '/wp-content/themes/astra-child/php/get_all_food_combos.php',
  data: $.param({ 'data': "test" }),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).then(function (resp) {
  console.log(resp.data); //all items
  });
  }, function (error) {
     console.log(error);
  });

or

$http({
  method: 'POST',
  url: 'https://example.com/wp-content/themes/astra-child/php/get_combos.php',
  data: $.param({ 'data': "test" }),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).then(function (resp) {
  console.log(resp.data); //all items
  });
  }, function (error) {
     console.log(error);
  });
</code>```

答:
Both of your way are OK. Secure is not different. But use in different scenario.

If you prefix  your service with URL.  (https://example.com/wp-content/...php) that mean you can only get data from this URL. And if you have service run in another website you must do in this way.

If you not prefix it will automatically use service in your local path.

Body:
I am building website for my client. I was wondering which path should I use for my website? which path is more secure? also correct me if I am totally wrong or if you have other reason for safety concerns for website! Thanks in advance.

For example...

or

or

$http({
  method: 'POST',
  url: '/wp-content/themes/astra-child/php/get_all_food_combos.php',
  data: $.param({ 'data': "test" }),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).then(function (resp) {
  console.log(resp.data); //all items
  });
  }, function (error) {
     console.log(error);
  });

or

$http({
  method: 'POST',
  url: 'https://example.com/wp-content/themes/astra-child/php/get_combos.php',
  data: $.param({ 'data': "test" }),
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).then(function (resp) {
  console.log(resp.data); //all items
  });
  }, function (error) {
     console.log(error);
  });


问:
Loop over list with and condition
I am trying to write a code for below pseudocode

```<code>for all element in list do
    match and condition
    if all match
       return True
</code>```

for example, List A=[1,2,3,4,5],B=10

What I want is like

```<code>def match():
    for i in range(len(A)):
      if B%A[0]==0 and B%A[1]==0 and B%A[2]==0 and B%A[3]==0 and B%A[4]==0: #Generate all these
        #and condition one by one
        #automatically in this function
          return True
</code>```

How can I do?

NOTE:I am asking about write code match and condition with a loop, not write a remainder

答:
You can use a pythonic one liner

result = all(B % x == 0 for x in A)

Or maybe in a slightly more familiar syntax

```<code>res = True
for x in A:
    if B % x != 0:
        res = False
        break
</code>```

Title: Loop over list with and condition

Body:
I am trying to write a code for below pseudocode

for all element in list do
    match and condition
    if all match
       return True

for example, List A=[1,2,3,4,5],B=10

What I want is like

def match():
    for i in range(len(A)):
      if B%A[0]==0 and B%A[1]==0 and B%A[2]==0 and B%A[3]==0 and B%A[4]==0: #Generate all these
        #and condition one by one
        #automatically in this function
          return True

How can I do?

NOTE:I am asking about write code match and condition with a loop, not write a remainder

Body:
You can use a pythonic one liner

result = all(B % x == 0 for x in A)

Or maybe in a slightly more familiar syntax

res = True
for x in A:
    if B % x != 0:
        res = False
        break


问:
How do I mask an email address between the first and the last character before the @ sign?
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

```<code>var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};
</code>```

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

答:
To answer your question...  javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

```<code>When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)
</code>```

You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...

Body:
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

Body:
To answer your question...  javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)

You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...


问:
How can I generate a random HTML colour in Python?
How can I generate a random HTML colour (#ABABAB, etc) in Python? I tried doing something like

```<code>random.choice('0','1','2',)
</code>```

etc. but it didn't work. Help? Thank you.

答:
```<code>from random import choice

def colour():
    hex_chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
    randomColour = '#'
    for i in range(0, 6):
        randomColour = randomColour + choice(hex_chars)
    return randomColour
</code>```

Body:
How can I generate a random HTML colour (#ABABAB, etc) in Python? I tried doing something like

random.choice('0','1','2',)

etc. but it didn't work. Help? Thank you.


问:
Sql Import wizard imports 1022868890 as 1.02287e+009
I'm trying to import some data from Excel to SQL Server, I have a TEXT column with some numbers in it, some of the numbers go over just fine, and some turn into scientific form.

Column in Excel is "text" type, column in the target sql table is varchar(255)

Here are some examples:

Excel [text]     -> SQL Server [varchar(255)]

0313852230 -> 0313852230

1024869004 -> 1024869004

1022868890 -> 1.02287e+009

1022868899 -> 1.02287e+009

1022868907 -> 1022868907

1030869319 -> 1030869319

1106869726 -> 1106869726

SomeText   -> SomeText

Please help!

SOLUTION: Formatting the column as [Number] with 10 leading zeros worked for me, since all my numbers are 10-digit numbers

答: SOLUTION: Formatting the column as [Number] with 10 leading zeros worked for me, since all my numbers are 10-digit numbers</p>

OwnerDisplayName: rm

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: rm


问:
Using Java for light control
when reading Eckel's Thinking in Java, I found design for controlling Greenhouse. It really struck me, since he was mentioning in comment lines "here put the hardware code for controlling light" and stuff, and I want to know - how would I make such a simple thing, as controlling physical light, or traffic light with Java program?

How would I connect light to PC and power it, through software control?

I believe assembly language with some microcontroller is the way, but I do not intend to learn assembly language yet, so I want to know if there's possibility to do this with Java?

Thanks,
M.

答:
I googled this a couple of months ago. Found something called X10 and this site. Might be a start for finding more information about controlling light etc.

http://x10controller.sourceforge.net/X10Client/index.html
http://www.x10.com/homepage.htm

Title: Using Java for light control


问:
Hide ACF fields when one of them are empty
i use the following code with custom fields:

But the problem is; when did not put any content in one of custom field it need be hide.
the class style of the other effect it, and that is something I don’t want to show.

```<code><div class = "class2">
<? php the_sub_field ('filed2'); ?>
</div>
<div class = "class1">
<? php the_sub_field ('filed1'); ?>
</div>
</code>```

I want hide one of both custom filed when on of them is empty.

How can i hide it?

答:
```<code><?php if (get_sub_field ('filed2') || get_sub_field('filed1'));{ ?>
   <div class = "class2">
    <? php the_sub_field ('filed2'); ?>
  </div>
  <div class = "class1">
    <? php the_sub_field ('filed1'); ?>
  </div>
<?php } ?>
</code>```

You would want to wrap it in an if statement.

You can also do (if you need the conditional logic on a per-field basis):

```<code> <?php if (get_sub_field ('filed2'));{ ?>
      <div class = "class2">
        <? php the_sub_field ('filed2'); ?>
     </div>
 <?php }; if (get_sub_field ('filed1'));{ ?>
      <div class = "class1">
        <? php the_sub_field ('filed1'); ?>
      </div>
<?php }; ?>
</code>```

Body:
i use the following code with custom fields:

But the problem is; when did not put any content in one of custom field it need be hide.
the class style of the other effect it, and that is something I don’t want to show.

<? php the_sub_field ('filed2'); ?>

<? php the_sub_field ('filed1'); ?>

I want hide one of both custom filed when on of them is empty.

How can i hide it?

Body:
<?php if (get_sub_field ('filed2') || get_sub_field('filed1'));{ ?>
   <div class = "class2">
    <? php the_sub_field ('filed2'); ?>
  </div>
  <div class = "class1">
    <? php the_sub_field ('filed1'); ?>
  </div>
<?php } ?>

You would want to wrap it in an if statement.

You can also do (if you need the conditional logic on a per-field basis):

 <?php if (get_sub_field ('filed2'));{ ?>
      <div class = "class2">
        <? php the_sub_field ('filed2'); ?>
     </div>
 <?php }; if (get_sub_field ('filed1'));{ ?>
      <div class = "class1">
        <? php the_sub_field ('filed1'); ?>
      </div>
<?php }; ?>


问:
Bing image search API (cognitive) returns broken links?
I am using Azure cognitive service, more precisely the 'bing image search service'.
I send requests to fetch images in relation to a specific keyword.

For this, I make HTTP REST requests to the right azure endpoint:

'https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=MYKEYWORD'

It works well for a lot of requests and results.

However, in some images in the json response of the service, the field 'contentUrl' gives me a broken link to the website hosting the image (404 or 403 on some different wordpress sites for example).

Therefore, my program which tried to download the image thanks to the 'contentUrl' link crashes (or has to throw at least an exception).

I guess it is because the website changed (by removing the image they were hosting) and bing didn't update its database (or the crawler didn't have time to do so).

Hence I don't know what to do :'(

Any help / advice ?

答:
Yes, you are right, the contentUrl could be outdated cache removal.

By default, Bing returns cached content, if available. To prevent Bing
  from returning cached content, set the Pragma header to no-cache (for
  example, Pragma: no-cache).

You could check the Pragma header in this doc: Headers.


问:
looking for usage example of dataflow client for c# (nuget) - running job by template
I have a working code to load data to bigtable by dataflow-template by http request.I want to change it to work with the nuget client library for c#, but I can find any example, and the reference is not so helpfull... can someone give me any reference how should I use this client?

my existing code is like that

```<code>using (var client = new HttpClient())
        {

            var obj = new requestFormat
            {
                jobName = fileName,
                parameters = new parameters
                {
                    bigtableInstanceId = "ariel",
                    bigtableProjectId = cloudProjectId,
                    bigtableTableId = "ariel",
                    inputFilePattern = $"gs://{bucketName}/{fileName}.avro"
                }
            };

            var objStr = JsonConvert.SerializeObject(obj);

            var content = new StringContent(objStr, Encoding.UTF8, "application/json");
            var response = client.PostAsync("https://dataflow.googleapis.com/v1b3/projects/proj/templates:launch?gcsPath=gs://dataflow-templates/latest/GCS_Avro_to_Cloud_Bigtable", content).Result;

            var responseString = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(responseString);

        }
</code>```

答:
I succeeded by </p>

```<code>        GoogleCredential credential = GoogleCredential.GetApplicationDefault();
        credential = credential.CreateScoped(new List<string>() { "https://www.googleapis.com/auth/compute" });
        var dataflowService = new DataflowService(new Google.Apis.Services.BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
        });

        var launchTemplateParameters = new LaunchTemplateParameters();
        launchTemplateParameters.JobName = fileName;
        launchTemplateParameters.Parameters = new Dictionary<string, string>() {
            { "bigtableInstanceId", "arielh" },
            { "bigtableProjectId", cloudProjectId },
            { "bigtableTableId", "ariel" },
            { "inputFilePattern", $"gs://{bucketName}/{fileName}.avro" }
        };
        var locationResources = dataflowService.Projects.Locations;
        var launchRequest = locationResources.Templates.Launch(launchTemplateParameters, cloudProjectId, location);
        launchRequest.GcsPath = "gs://dataflow-templates/latest/GCS_Avro_to_Cloud_Bigtable";
        var launchTemplateResponse = launchRequest.Execute();
        var jobId = launchTemplateResponse.Job.Id;
        var getRequest = locationResources.Jobs.Get(cloudProjectId, location, jobId);
        var timer = new Timer(2000);
        timer.Elapsed += (sender, e) =>
        {
            var jobStatus = getRequest.Execute();
            var currentState = jobStatus.CurrentState;
            if (currentState != "JOB_STATE_STOPPED" && currentState != "JOB_STATE_RUNNING")
            {
                if (currentState == "JOB_STATE_DONE")
                {
                    timer.Stop();
                    Console.WriteLine("job done");
                }
                else
                {
                    throw new Exception($"job {jobId} not finished successfully. current state: {currentState}");
                }
            }
            else
            {
                Console.WriteLine("job is running");
            }
        };
</code>```

Body:
I have a working code to load data to bigtable by dataflow-template by http request.I want to change it to work with the nuget client library for c#, but I can find any example, and the reference is not so helpfull... can someone give me any reference how should I use this client?

my existing code is like that

using (var client = new HttpClient())
        {

            var obj = new requestFormat
            {
                jobName = fileName,
                parameters = new parameters
                {
                    bigtableInstanceId = "ariel",
                    bigtableProjectId = cloudProjectId,
                    bigtableTableId = "ariel",
                    inputFilePattern = $"gs://{bucketName}/{fileName}.avro"
                }
            };

            var objStr = JsonConvert.SerializeObject(obj);

            var content = new StringContent(objStr, Encoding.UTF8, "application/json");
            var response = client.PostAsync("https://dataflow.googleapis.com/v1b3/projects/proj/templates:launch?gcsPath=gs://dataflow-templates/latest/GCS_Avro_to_Cloud_Bigtable", content).Result;

            var responseString = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(responseString);

        }

Body:
I succeeded by

        GoogleCredential credential = GoogleCredential.GetApplicationDefault();
        credential = credential.CreateScoped(new List<string>() { "https://www.googleapis.com/auth/compute" });
        var dataflowService = new DataflowService(new Google.Apis.Services.BaseClientService.Initializer()
        {
            HttpClientInitializer = credential
        });

        var launchTemplateParameters = new LaunchTemplateParameters();
        launchTemplateParameters.JobName = fileName;
        launchTemplateParameters.Parameters = new Dictionary<string, string>() {
            { "bigtableInstanceId", "arielh" },
            { "bigtableProjectId", cloudProjectId },
            { "bigtableTableId", "ariel" },
            { "inputFilePattern", $"gs://{bucketName}/{fileName}.avro" }
        };
        var locationResources = dataflowService.Projects.Locations;
        var launchRequest = locationResources.Templates.Launch(launchTemplateParameters, cloudProjectId, location);
        launchRequest.GcsPath = "gs://dataflow-templates/latest/GCS_Avro_to_Cloud_Bigtable";
        var launchTemplateResponse = launchRequest.Execute();
        var jobId = launchTemplateResponse.Job.Id;
        var getRequest = locationResources.Jobs.Get(cloudProjectId, location, jobId);
        var timer = new Timer(2000);
        timer.Elapsed += (sender, e) =>
        {
            var jobStatus = getRequest.Execute();
            var currentState = jobStatus.CurrentState;
            if (currentState != "JOB_STATE_STOPPED" && currentState != "JOB_STATE_RUNNING")
            {
                if (currentState == "JOB_STATE_DONE")
                {
                    timer.Stop();
                    Console.WriteLine("job done");
                }
                else
                {
                    throw new Exception($"job {jobId} not finished successfully. current state: {currentState}");
                }
            }
            else
            {
                Console.WriteLine("job is running");
            }
        };


问:
Numpy: apply function to every (or subset of) diagonal
I'd like to apply a function (namely np.var, but a general method would be great) to every diagonal of an array.  My arrays are square.
I can do this with:

```<code>offset_list = np.arange(-1 * len(arr) + 1, len(arr))
diag_var_list = [np.var(np.diagonal(arr, k)) for k in offset_list]
</code>```

If I want a subset of the diagonals I can change offset_list.

But using list comprehension seems inefficient since I'll be doing this on many large arrays.
Is there a better way?

答:
You can use the following idea. If major, minor = A.strides then setting strides of A to major + minor, minor (this should be done carefully to avoid stepping outside of array boundaries) you get array with each column as diagonal. This way with something like A.sum(axis=0) you can calculate sum of diagonals. For means you can use the same but multiply to certain values like A.shape[0] / [1, 2, ... A.shape[0], ... 2, 1] to fix the change in lengths of diagonals. For variance you can use that variance = <(x - <x>)**2> = <x**2> - <x>**2.

```<code>import numpy as np
def rot45(A):
    """
    >>> A = np.triu(np.arange(25).reshape(5, 5), 1)
    >>> print(A)
    [[ 0  1  2  3  4]
     [ 0  0  7  8  9]
     [ 0  0  0 13 14]
     [ 0  0  0  0 19]
     [ 0  0  0  0  0]]
    >>> print(rot45(A))
    [[ 1  2  3  4]
     [ 7  8  9  0]
     [13 14  0  0]
     [19  0  0  0]]
    """
    major, minor = A.strides
    strides = major + minor, minor
    shape = A.shape[0] - 1, A.shape[1]
    return np.lib.stride_tricks.as_strided(A, shape, strides)[:, 1:]

def apply_diag(A, func):
    """
    >>> A = np.arange(25).reshape(5, 5)
    >>> print(A)
    [[ 0  1  2  3  4]
     [ 5  6  7  8  9]
     [10 11 12 13 14]
     [15 16 17 18 19]
     [20 21 22 23 24]]
    >>> offset_list = np.arange(-1 * len(A) + 1, len(A))
    >>> diag_var_list = [np.sum(np.diagonal(A, k)) for k in offset_list]
    >>> diag_var_list
    [20, 36, 48, 56, 60, 40, 24, 12, 4]
    >>> print(apply_diag(A, np.sum))
    [20, 36, 48, 56, 60, 40, 24, 12, 4]
    """
    U = np.triu(A, 1)
    U = rot45(U)
    D = np.tril(A, -1).T.copy()
    D = rot45(D)
    return func(D, axis=0)[::-1].tolist() + [func(np.diag(A))] + func(U, axis=0)[::-1].tolist()[::-1]

def using_numpy(A):
    """
    >>> A = np.arange(25).reshape(5, 5)
    >>> print(A)
    [[ 0  1  2  3  4]
     [ 5  6  7  8  9]
     [10 11 12 13 14]
     [15 16 17 18 19]
     [20 21 22 23 24]]
    >>> offset_list = np.arange(-1 * len(A) + 1, len(A))
    >>> diag_var_list = [np.var(np.diagonal(A, k)) for k in offset_list]
    >>> diag_var_list
    [0.0, 9.0, 24.0, 45.0, 72.0, 45.0, 24.0, 9.0, 0.0]
    >>> print(using_numpy(A))
    [ 0.  9. 24. 45. 72. 45. 24.  9.  0.]
    """
    multiply = (A.shape[0] - 1) / np.r_[1:A.shape[0], A.shape[0] - 1, A.shape[0] - 1:0:-1]
    return multiply * apply_diag(A ** 2, np.mean) - (multiply * apply_diag(A, np.mean))**2

def list_comp(A, func):
    """
    >>> A = np.arange(25).reshape(5, 5)
    >>> list_comp(A, np.sum)
    [20, 36, 48, 56, 60, 40, 24, 12, 4]
    """
    offset_list = np.arange(-1 * len(A) + 1, len(A))
    return [func(np.diagonal(A, k)) for k in offset_list]
</code>```

It seems like there is 10 times speed up for (100, 100) size matrices but for bigger ones the speed difference drop lower.

```<code>In [9]: A = np.random.randn(100, 100)

In [10]: %timeit using_numpy(A)
761 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [11]: %timeit list_comp(A, np.var)
9.57 ms ± 19.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [12]: A = np.random.randn(1000, 1000)

In [13]: %timeit using_numpy(A)
37.4 ms ± 125 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [14]: %timeit list_comp(A, np.var)
112 ms ± 927 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Body:
I'd like to apply a function (namely np.var, but a general method would be great) to every diagonal of an array.  My arrays are square.
I can do this with:

offset_list = np.arange(-1 * len(arr) + 1, len(arr))
diag_var_list = [np.var(np.diagonal(arr, k)) for k in offset_list]

If I want a subset of the diagonals I can change offset_list.

But using list comprehension seems inefficient since I'll be doing this on many large arrays.
Is there a better way?

Body:
You can use the following idea. If major, minor = A.strides then setting strides of A to major + minor, minor (this should be done carefully to avoid stepping outside of array boundaries) you get array with each column as diagonal. This way with something like A.sum(axis=0) you can calculate sum of diagonals. For means you can use the same but multiply to certain values like A.shape[0] / [1, 2, ... A.shape[0], ... 2, 1] to fix the change in lengths of diagonals. For variance you can use that variance = <(x - <x>)**2> = <x**2> - <x>**2.

import numpy as np
def rot45(A):
    """
    >>> A = np.triu(np.arange(25).reshape(5, 5), 1)
    >>> print(A)
    [[ 0  1  2  3  4]
     [ 0  0  7  8  9]
     [ 0  0  0 13 14]
     [ 0  0  0  0 19]
     [ 0  0  0  0  0]]
    >>> print(rot45(A))
    [[ 1  2  3  4]
     [ 7  8  9  0]
     [13 14  0  0]
     [19  0  0  0]]
    """
    major, minor = A.strides
    strides = major + minor, minor
    shape = A.shape[0] - 1, A.shape[1]
    return np.lib.stride_tricks.as_strided(A, shape, strides)[:, 1:]

def apply_diag(A, func):
    """
    >>> A = np.arange(25).reshape(5, 5)
    >>> print(A)
    [[ 0  1  2  3  4]
     [ 5  6  7  8  9]
     [10 11 12 13 14]
     [15 16 17 18 19]
     [20 21 22 23 24]]
    >>> offset_list = np.arange(-1 * len(A) + 1, len(A))
    >>> diag_var_list = [np.sum(np.diagonal(A, k)) for k in offset_list]
    >>> diag_var_list
    [20, 36, 48, 56, 60, 40, 24, 12, 4]
    >>> print(apply_diag(A, np.sum))
    [20, 36, 48, 56, 60, 40, 24, 12, 4]
    """
    U = np.triu(A, 1)
    U = rot45(U)
    D = np.tril(A, -1).T.copy()
    D = rot45(D)
    return func(D, axis=0)[::-1].tolist() + [func(np.diag(A))] + func(U, axis=0)[::-1].tolist()[::-1]

def using_numpy(A):
    """
    >>> A = np.arange(25).reshape(5, 5)
    >>> print(A)
    [[ 0  1  2  3  4]
     [ 5  6  7  8  9]
     [10 11 12 13 14]
     [15 16 17 18 19]
     [20 21 22 23 24]]
    >>> offset_list = np.arange(-1 * len(A) + 1, len(A))
    >>> diag_var_list = [np.var(np.diagonal(A, k)) for k in offset_list]
    >>> diag_var_list
    [0.0, 9.0, 24.0, 45.0, 72.0, 45.0, 24.0, 9.0, 0.0]
    >>> print(using_numpy(A))
    [ 0.  9. 24. 45. 72. 45. 24.  9.  0.]
    """
    multiply = (A.shape[0] - 1) / np.r_[1:A.shape[0], A.shape[0] - 1, A.shape[0] - 1:0:-1]
    return multiply * apply_diag(A ** 2, np.mean) - (multiply * apply_diag(A, np.mean))**2

def list_comp(A, func):
    """
    >>> A = np.arange(25).reshape(5, 5)
    >>> list_comp(A, np.sum)
    [20, 36, 48, 56, 60, 40, 24, 12, 4]
    """
    offset_list = np.arange(-1 * len(A) + 1, len(A))
    return [func(np.diagonal(A, k)) for k in offset_list]

It seems like there is 10 times speed up for (100, 100) size matrices but for bigger ones the speed difference drop lower.

In [9]: A = np.random.randn(100, 100)

In [10]: %timeit using_numpy(A)
761 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [11]: %timeit list_comp(A, np.var)
9.57 ms ± 19.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [12]: A = np.random.randn(1000, 1000)

In [13]: %timeit using_numpy(A)
37.4 ms ± 125 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [14]: %timeit list_comp(A, np.var)
112 ms ± 927 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


问:
Python SKLearn: How to Get Feature Names After OneHotEncoder?
I would like to get the feature names of a data set after it has been transformed by SKLearn OneHotEncoder.

In active_features_ attribute in OneHotEncoder one can see a very good explanation how the attributes n_values_, feature_indices_ and active_features_ get filled after transform() was executed.

My question is:

For e.g. DataFrame based input data:

```<code>data = pd.DataFrame({"a": [0, 1, 2,0], "b": [0,1,4, 5], "c":[0,1,4, 5]}).as_matrix()
</code>```

How does the code look like to get from the original feature names a, b and c to a list of the transformed feature names
(like e.g:

a-0,a-1, a-2, b-0, b-1, b-2, b-3, c-0, c-1, c-2, c-3

or

a-0,a-1, a-2, b-0, b-1, b-2, b-3, b-4, b-5, b-6, b-7, b-8

or anything that helps to see the assignment of encoded columns to the original columns).

Background: I would like to see the feature importances of some of the algorithms to get a feeling for which feature have the most effect on the algorithm used.

答: OneHotEncoder now has a method get_feature_names.  You can use input_features=data.columns to match to the training data.

Body:
I would like to get the feature names of a data set after it has been transformed by SKLearn OneHotEncoder.

In active_features_ attribute in OneHotEncoder one can see a very good explanation how the attributes n_values_, feature_indices_ and active_features_ get filled after transform() was executed.

My question is:

For e.g. DataFrame based input data:

data = pd.DataFrame({"a": [0, 1, 2,0], "b": [0,1,4, 5], "c":[0,1,4, 5]}).as_matrix()

How does the code look like to get from the original feature names a, b and c to a list of the transformed feature names
(like e.g:

a-0,a-1, a-2, b-0, b-1, b-2, b-3, c-0, c-1, c-2, c-3

or

a-0,a-1, a-2, b-0, b-1, b-2, b-3, b-4, b-5, b-6, b-7, b-8

or anything that helps to see the assignment of encoded columns to the original columns).

Background: I would like to see the feature importances of some of the algorithms to get a feeling for which feature have the most effect on the algorithm used.


问:
Android Profiling is unavailable for the selected process, but advanced profiling is enabled
I am developing an Android app with multiple modules. The app uses ProGuard, compileSdkVersion is set to 27 in all modules, and when I tried to enable Advanced Profiling I continue to get a message saying "Advanced profiling is unavailable for the selected process".

Solutions I've tried after searching other questions about the topic:

Enable Advanced Profiling (obviously) for the app as well as the default Run Configurations

Disable ProGuard in all modules using minifyEnabled false

Update Studio version to 3.1.3 and Gradle to 4.4

Rebuild project after the above changes

Am I missing something? Is there anything else I can do to enable Advanced Profiling?

答:
In your build.gradle file turn on debuggable flag (debuggable true).

For eg :

```<code>buildTypes {
        debug {
            debuggable true
            buildConfigField "Boolean", "DEBUG_MODE", "true"
        }
    }
</code>```

Body:
In your build.gradle file turn on debuggable flag (debuggable true).

For eg :

buildTypes {
        debug {
            debuggable true
            buildConfigField "Boolean", "DEBUG_MODE", "true"
        }
    }


问:
Python- Why does it say password denied even when I enter a password that should work?
```<code>
userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):

    if userpass[i].isupper():
        uppercounter=uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].islower():
        lowercounter=lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")
            print("Password Accepted")
    else:
        print('Password Denied')
        raise SystemExit(0)

</code>```

<p>I’m trying to make a program for a password that must contain one uppercase letter, one lowercase letter, and one number. But the if statements don’t seem to be working properly and whenever I enter a password like “Py11”, it says password denied. </p>

答:
Because your logic is wrong.
So first, you're entering the Py11 password and it enters the first if statement.

Your loop takes first value is P from Py11. When it goes to second if statement, it immediately goes to else statement of second if statement because the value is still P.

I tried not to modify your code so much but you could try this way:

```<code>userpass = input(
    'Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter = 0
lowercounter = 0
numbercounter = 0
for i in range(len(userpass)):
    print(userpass[i])
    if userpass[i].isupper():
        uppercounter = uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    elif userpass[i].islower():
        lowercounter = lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    elif userpass[i].isnumeric():
        numbercounter = numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")

if uppercounter <= 0 or lowercounter <= 0 or numbercounter <= 0:
    print('Password Denied')
    raise SystemExit(0)
else:
    print("Password Accepted")

</code>```

Body:
userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):

    if userpass[i].isupper():
        uppercounter=uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].islower():
        lowercounter=lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")
            print("Password Accepted")
    else:
        print('Password Denied')
        raise SystemExit(0)

I’m trying to make a program for a password that must contain one uppercase letter, one lowercase letter, and one number. But the if statements don’t seem to be working properly and whenever I enter a password like “Py11”, it says password denied.

Body:
Because your logic is wrong.
So first, you're entering the Py11 password and it enters the first if statement.

Your loop takes first value is P from Py11. When it goes to second if statement, it immediately goes to else statement of second if statement because the value is still P.

I tried not to modify your code so much but you could try this way:

userpass = input(
    'Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter = 0
lowercounter = 0
numbercounter = 0
for i in range(len(userpass)):
    print(userpass[i])
    if userpass[i].isupper():
        uppercounter = uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    elif userpass[i].islower():
        lowercounter = lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    elif userpass[i].isnumeric():
        numbercounter = numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")

if uppercounter <= 0 or lowercounter <= 0 or numbercounter <= 0:
    print('Password Denied')
    raise SystemExit(0)
else:
    print("Password Accepted")


问:
Know active window by using x11-api and Mono/C#
I'm trying to use X11-api with Mono and C# on Ubuntu.
I have a SIGSEGV when I'm trying to know active window.

Import:

```<code>[DllImport("libX11")]
public static extern void XGetInputFocus(IntPtr display, IntPtr focus_return, int revert_to_return);

[DllImport("libX11")]
public static extern IntPtr XOpenDisplay(string display_name);
</code>```

And using:

```<code>IntPtr rootWind = XOpenDisplay(null);
IntPtr wind;
int ret = 0;

XGetInputFocus(rootWind, wind, ret); //SIGSEGV there
</code>```

I've tried to use pointers, references and some more, but there's one result.
Some other api-functions works normally.
What`s wrong?

答:
Try this:</p>

```<code>[DllImport("libX11")]
public static extern void XGetInputFocus(IntPtr display, ref IntPtr focus_return, ref int revert_to_return);

IntPtr rootWind = XOpenDisplay(null);
IntPtr wind;
int ret = 0;
XGetInputFocus(rootWind, ref wind, ref ret);
</code>```

Body:
I'm trying to use X11-api with Mono and C# on Ubuntu.
I have a SIGSEGV when I'm trying to know active window.

Import:

[DllImport("libX11")]
public static extern void XGetInputFocus(IntPtr display, IntPtr focus_return, int revert_to_return);

[DllImport("libX11")]
public static extern IntPtr XOpenDisplay(string display_name);

And using:

IntPtr rootWind = XOpenDisplay(null);
IntPtr wind;
int ret = 0;

XGetInputFocus(rootWind, wind, ret); //SIGSEGV there

I've tried to use pointers, references and some more, but there's one result.
Some other api-functions works normally.
What`s wrong?

Body:
Try this:

[DllImport("libX11")]
public static extern void XGetInputFocus(IntPtr display, ref IntPtr focus_return, ref int revert_to_return);

IntPtr rootWind = XOpenDisplay(null);
IntPtr wind;
int ret = 0;
XGetInputFocus(rootWind, ref wind, ref ret);


问:
Axios post returns 401 and logs user out, but only on OSX & iOS
I have a Vue app using Vue router and I suddenly started getting a 401 on an axios.post /wp-json/jwt-auth/v1/and it only seems to be happening on OS X and iOS.

Thoughts on where to direct my debug hunt?

The error is:

```<code>{
  "code": "rest_forbidden",
  "message": "Sorry, you are not allowed to do that.",
  "data": {
    "status": 401
  }
}
</code>```

I post, it immediately fails with a 401, but only on Macs.

localClient config:

```<code>import axios from "axios";
import environment from "@/environments/environment";
import state from "../store";
import router from "../router";

const userData = JSON.parse(localStorage.getItem("userData"));

let instance = {};

if (userData) {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL,
    headers: { Authorization: `Bearer ${userData.token}` }
  });
} else {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL
  });
}

instance.interceptors.request.use(
  config => {
    state.commit("setNetworkStatus", true);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    state.commit("setNetworkStatus", false);
    return response;
  },
  error => {
    if ([401, 403].includes(error.response.status)) {
      console.log(error);
      state.commit("delUserData");
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default {
  get(path) {
    return instance.get(instance.defaults.baseURL + path);
  },
  post(path, params) {
    console.log(instance.defaults.baseURL + path, params);
    return instance.post(instance.defaults.baseURL + path, params);
  },
  put(path, params) {
    return instance.put(instance.defaults.baseURL + path, params);
  },
  delete(path, params) {
    return instance.delete(instance.defaults.baseURL + path, params);
  }
};

</code>```

interceptor request success before response 401 failure:

```<code>interceptor request success=
{url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer", method: "post", data: {…}, headers: {…}, baseURL: "https://panel.site.art/wp-json", …}
adapter: ƒ (t)
baseURL: "https://panel.site.art/wp-json"
data: "{"location_id":"rec140ttKVWJCDr8v","items":["recg1W9lQuLLRm8VS"]}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer"
validateStatus: ƒ (t)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object
</code>```

答:
I finally figured this out by adding a billion console logs to the whole flow. What was happening is the login flow stores the user data (with token) in localStorage and Vuex store upon login. However, the way the local axios client was set up (I didn't build it) the axios instance that is used for the post was getting created WITHOUT a token, even though the token exists in state and localStorage. With a hard page refresh the axios instance is recreated with token.

So, I made the axios get, post, put, delete exports check the localStorage every time.

It's ugly as all get out, but it works. If anyone knows how to refactor this to be smaller, let me know.

```<code>import axios from "axios";
import environment from "@/environments/environment";
import state from "../store";
import router from "../router";

export default {
  get(path) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.get(instance.defaults.baseURL + path);
  },
  post(path, params) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.post(instance.defaults.baseURL + path, params);
  },
  put(path, params) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.put(instance.defaults.baseURL + path, params);
  },
  delete(path, params) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.delete(instance.defaults.baseURL + path, params);
  }
};

</code>```

Body:
I have a Vue app using Vue router and I suddenly started getting a 401 on an axios.post /wp-json/jwt-auth/v1/and it only seems to be happening on OS X and iOS.

Thoughts on where to direct my debug hunt?

The error is:

{
  "code": "rest_forbidden",
  "message": "Sorry, you are not allowed to do that.",
  "data": {
    "status": 401
  }
}

I post, it immediately fails with a 401, but only on Macs.

localClient config:

import axios from "axios";
import environment from "@/environments/environment";
import state from "../store";
import router from "../router";

const userData = JSON.parse(localStorage.getItem("userData"));

let instance = {};

if (userData) {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL,
    headers: { Authorization: `Bearer ${userData.token}` }
  });
} else {
  instance = axios.create({
    baseURL: environment.CUSTOM_BASE_URL
  });
}

instance.interceptors.request.use(
  config => {
    state.commit("setNetworkStatus", true);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

instance.interceptors.response.use(
  response => {
    state.commit("setNetworkStatus", false);
    return response;
  },
  error => {
    if ([401, 403].includes(error.response.status)) {
      console.log(error);
      state.commit("delUserData");
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default {
  get(path) {
    return instance.get(instance.defaults.baseURL + path);
  },
  post(path, params) {
    console.log(instance.defaults.baseURL + path, params);
    return instance.post(instance.defaults.baseURL + path, params);
  },
  put(path, params) {
    return instance.put(instance.defaults.baseURL + path, params);
  },
  delete(path, params) {
    return instance.delete(instance.defaults.baseURL + path, params);
  }
};

interceptor request success before response 401 failure:

interceptor request success=
{url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer", method: "post", data: {…}, headers: {…}, baseURL: "https://panel.site.art/wp-json", …}
adapter: ƒ (t)
baseURL: "https://panel.site.art/wp-json"
data: "{"location_id":"rec140ttKVWJCDr8v","items":["recg1W9lQuLLRm8VS"]}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf-8"
__proto__: Object
maxContentLength: -1
method: "post"
timeout: 0
transformRequest: [ƒ]
transformResponse: [ƒ]
url: "https://panel.site.art/wp-json/jwt-auth/v1/site/transfer"
validateStatus: ƒ (t)
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object

Body:
I finally figured this out by adding a billion console logs to the whole flow. What was happening is the login flow stores the user data (with token) in localStorage and Vuex store upon login. However, the way the local axios client was set up (I didn't build it) the axios instance that is used for the post was getting created WITHOUT a token, even though the token exists in state and localStorage. With a hard page refresh the axios instance is recreated with token.

So, I made the axios get, post, put, delete exports check the localStorage every time.

It's ugly as all get out, but it works. If anyone knows how to refactor this to be smaller, let me know.

import axios from "axios";
import environment from "@/environments/environment";
import state from "../store";
import router from "../router";

export default {
  get(path) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.get(instance.defaults.baseURL + path);
  },
  post(path, params) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.post(instance.defaults.baseURL + path, params);
  },
  put(path, params) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.put(instance.defaults.baseURL + path, params);
  },
  delete(path, params) {
    const userData = JSON.parse(localStorage.getItem("userData"));

    let instance = {};

    if (userData) {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL,
        headers: { Authorization: `Bearer ${userData.token}` }
      });
    } else {
      instance = axios.create({
        baseURL: environment.CUSTOM_BASE_URL
      });
    }

    instance.interceptors.request.use(
      config => {
        state.commit("setNetworkStatus", true);
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );

    instance.interceptors.response.use(
      response => {
        state.commit("setNetworkStatus", false);
        return response;
      },
      error => {
        if ([401, 403].includes(error.response.status)) {
          state.commit("delUserData");
          router.push("/login");
        }
        return Promise.reject(error);
      }
    );
    return instance.delete(instance.defaults.baseURL + path, params);
  }
};


问:
CS50 caesar part 1. What does return 1 do in the code below?
Why is the return 1 necessary in the code below? Is this to stop the loop from 'looping' after '1' cycle since it will go ON forever if the Boolean expression is false?

```<code>while (argc != 2 || isnumber(argv[1]) == false)
{
    printf("Usage: .caesar key\n");
    **return 1;**
}
</code>```

Can you explain this step by step?

答:
The return 1 is necessary as if you provide the wrong number of command line arguments, it will return 1 to indicate a failure, which is to stop the program. You actually do not need the while loop, you can actually do

```<code>if (argc != 2 || isnumber(argv[1]) == false)
{
  printf("Usage: .caesar key\n");
  return 1;
}
</code>```

You can also use other numbers bigger than 0 for failure and return 0 is for success.

Body:
Why is the return 1 necessary in the code below? Is this to stop the loop from 'looping' after '1' cycle since it will go ON forever if the Boolean expression is false?

while (argc != 2 || isnumber(argv[1]) == false)
{
    printf("Usage: .caesar key\n");
    **return 1;**
}

Can you explain this step by step?

Body:
The return 1 is necessary as if you provide the wrong number of command line arguments, it will return 1 to indicate a failure, which is to stop the program. You actually do not need the while loop, you can actually do

if (argc != 2 || isnumber(argv[1]) == false)
{
  printf("Usage: .caesar key\n");
  return 1;
}

You can also use other numbers bigger than 0 for failure and return 0 is for success.