问:
How can I play a .wav file in python 3.6?
Currently, I'm making a program using python 3.6, and I've been trying to make a sound effect occur after pressing a button. I found something from a different question asked, found here. Down below is my code.

```<code>from tkinter import *

window = Tk()
c = Canvas(window, height=100, width=100, bg='blue')
c.pack()

with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3
Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
    data = base64.b64encode(f.read())

def playSound():
    sound = winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY)

def sound(event):
    global sound
    if event.keysym == 'Up':
        playSound()
c.pack('<Key>', sound)
</code>```

Then I got this error message:

```<code> RESTART: C:\Users\lenonvo\AppData\Local\Programs\Python\Python36\Python 3
Files\Python 3.6.3\Test2.py
Traceback (most recent call last):
  File "C:\Users\lenonvo\AppData\Local\Programs\Python\Python36\Python 3
Files\Python 3.6.3\Test2.py", line 7, in <module>
    with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python
3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
FileNotFoundError: [Errno 2] No such file or directory:
'Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3
Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav'
</code>```

Any suggestions?

Also, I am not an advanced python coder, so if your answer could be simplistic, it would be very much appreciated. =]

Now one problem is fixed, thanks to Patrick Artner, but now this error message comes up:

```<code>    data = base64.b64decode(f.read())
NameError: name 'base64' is not defined
</code>```

答:
This:

```<code>with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3  Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
</code>```

is a relative path to where your prog runs.

Use

```<code>with open('C:/Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
          ^^^^
</code>```

Body:
Currently, I'm making a program using python 3.6, and I've been trying to make a sound effect occur after pressing a button. I found something from a different question asked, found here. Down below is my code.

from tkinter import *

window = Tk()
c = Canvas(window, height=100, width=100, bg='blue')
c.pack()

with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3
Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
    data = base64.b64encode(f.read())

def playSound():
    sound = winsound.PlaySound(base64.b64decode(data), winsound.SND_MEMORY)

def sound(event):
    global sound
    if event.keysym == 'Up':
        playSound()
c.pack('<Key>', sound)

Then I got this error message:

 RESTART: C:\Users\lenonvo\AppData\Local\Programs\Python\Python36\Python 3
Files\Python 3.6.3\Test2.py
Traceback (most recent call last):
  File "C:\Users\lenonvo\AppData\Local\Programs\Python\Python36\Python 3
Files\Python 3.6.3\Test2.py", line 7, in <module>
    with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python
3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
FileNotFoundError: [Errno 2] No such file or directory:
'Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3
Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav'

Any suggestions?

Also, I am not an advanced python coder, so if your answer could be simplistic, it would be very much appreciated. =]

Now one problem is fixed, thanks to Patrick Artner, but now this error message comes up:

    data = base64.b64decode(f.read())
NameError: name 'base64' is not defined

Body:
This:

with open('Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3  Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:

is a relative path to where your prog runs.

Use

with open('C:/Users/lenonvo/AppData/Local/Programs/Python/Python 3.6/Python 3 Files/Python [3.6.3]/Sounds/Blook Game/Attack.wav','rb') as f:
          ^^^^


来源: stackexchange

问:
Haskell: Retrieve nth value from type which is a tuple
I am trying to access some data inside a type from an imported package.

The type is declared (by the package authors) as so:

```<code>newtype MultiBalanceReport =
  MultiBalanceReport ([DateSpan]
                     ,[MultiBalanceReportRow]
                     ,MultiBalanceReportTotals
                     )
</code>```

And I'm trying to extract the first list in the type with a function like so:

```<code>getDates :: MultiBalanceReport -> [DateSpan]
getDates (date,_,_) = date
</code>```

But when I use the function, the compiler complains that the types aren't the same:

```<code>• Couldn't match expected type ‘MultiBalanceReport’
              with actual type ‘([DateSpan], t7, t8)’
</code>```

I feel like the compiler just doesn't know the inner details of the MultiBalanceReport type? Am I not importing the package which defines the type correctly?

I'm new to Haskell, so sorry if I'm using the wrong nomenclature to try to describe my problem.

答:
You're really close. You're pattern matching on a tuple type, but the actual value you have is a MultiBalanceReport which contains a tuple.

```<code>getDates :: MultiBalanceReport -> [DateSpan]
getDates (MultiBalanceReport (date,_,_)) = date
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to access some data inside a type from an imported package.

The type is declared (by the package authors) as so:

newtype MultiBalanceReport =
  MultiBalanceReport ([DateSpan]
                     ,[MultiBalanceReportRow]
                     ,MultiBalanceReportTotals
                     )

And I'm trying to extract the first list in the type with a function like so:

getDates :: MultiBalanceReport -> [DateSpan]
getDates (date,_,_) = date

But when I use the function, the compiler complains that the types aren't the same:

• Couldn't match expected type ‘MultiBalanceReport’
              with actual type ‘([DateSpan], t7, t8)’

I feel like the compiler just doesn't know the inner details of the MultiBalanceReport type? Am I not importing the package which defines the type correctly?

I'm new to Haskell, so sorry if I'm using the wrong nomenclature to try to describe my problem.

Body:
You're really close. You're pattern matching on a tuple type, but the actual value you have is a MultiBalanceReport which contains a tuple.

getDates :: MultiBalanceReport -> [DateSpan]
getDates (MultiBalanceReport (date,_,_)) = date


问:
Ionic Ajax / CORS issue after build
I am using ionic 3 and write some provider code to get result from api endpoint that is place in some https server for example https://apiserver/api/endpoint/article is my end point. my provider code is below.

```<code>// provider class function
load(){

    if(this.data){
      return Promise.resolve(this.data);
    }

    let headers = new HttpHeaders()
      .set("Access-Control-Allow-Origin", "*")
      .set('Access-Control-Allow-Methods', 'GET, POST')
      .set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    return new Promise(resolve => {
      this.http.get('/api/endpoint/article',{headers})
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        },err => {
          console.log(err);
        });
    });
  }

// ionic.config.json
{
  "name": "app",
  "app_id": "app_id",
  "type": "ionic-angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "https://apiserver/api"
    }
  ]
}
</code>```

load() returns me data which i show in my app, This work PERFECTLY in my  localhost, Ionic DevApp, Ionic View also when debugging through Ios/xcode emulator.

but when i install my app to mobile phone it does not return any data and show me blank page.

I have debug it whole bet didn't find any reason about this behavior. may be CORS ?

答:
When you build app you need to use the real endpoint. Ionic proxy works only for debugging (ie. when you use ionic cordova run ios -l).

So, this

```<code>this.http.get('/api/endpoint/article',{headers})
</code>```

becomes

```<code>this.http.get('https://apiserver/api/endpoint/article',{headers})
</code>```

Title: Ionic Ajax / CORS issue after build

Body:
I am using ionic 3 and write some provider code to get result from api endpoint that is place in some https server for example https://apiserver/api/endpoint/article is my end point. my provider code is below.

// provider class function
load(){

    if(this.data){
      return Promise.resolve(this.data);
    }

    let headers = new HttpHeaders()
      .set("Access-Control-Allow-Origin", "*")
      .set('Access-Control-Allow-Methods', 'GET, POST')
      .set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

    return new Promise(resolve => {
      this.http.get('/api/endpoint/article',{headers})
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        },err => {
          console.log(err);
        });
    });
  }

// ionic.config.json
{
  "name": "app",
  "app_id": "app_id",
  "type": "ionic-angular",
  "integrations": {
    "cordova": {}
  },
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "https://apiserver/api"
    }
  ]
}

load() returns me data which i show in my app, This work PERFECTLY in my  localhost, Ionic DevApp, Ionic View also when debugging through Ios/xcode emulator.

but when i install my app to mobile phone it does not return any data and show me blank page.

I have debug it whole bet didn't find any reason about this behavior. may be CORS ?

Body:
When you build app you need to use the real endpoint. Ionic proxy works only for debugging (ie. when you use ionic cordova run ios -l).

So, this

this.http.get('/api/endpoint/article',{headers})

becomes

this.http.get('https://apiserver/api/endpoint/article',{headers})


问:
how to Modify CUDA kernel code to OpenCL for matrix multiplication using tiling approach?
I recently started to work with OpenCl and i trying to change my CUDA code that does the tiled matrix multiplication to OpenCl. I have done some change but i am not sure if i am doing correct. I don't know what would be the blockIdx, threadIdx, __syncthreads, Ashare and Bshare in opencl.
I will be more than happy if any one can help me.

My CUDA Kernel code for tiled matrix multiplication:

```<code>#define TILE_WIDTH 16
__global__ void matrixMulKernel(float* A, float* B, float* C, int width) {
 __shared__ float Ashare[TILE_WIDTH][TILE_WIDTH];
 __shared__ float Bshare[TILE_WIDTH][TILE_WIDTH];
 int bx = blockIdx.x, by = blockIdx.y;
 int tx = threadIdx.x, ty = threadIdx.y;
 //calculate the row and column for this element of the matrix
 int row = by * TILE_WIDTH + ty;
 int col = bx * TILE_WIDTH + tx;
 float result = 0;
 //loop over the A and B tiles required to compute the C element
 for (int m = 0; m < width / TILE_WIDTH; m++) {
 //collectively load the A and B tiles into shared memory
 Ashare[ty][tx] = A[(row * width) + (m * TILE_WIDTH) + tx];
 Bshare[ty][tx] = B[(((m * TILE_WIDTH) + ty) * width) + col];
 __syncthreads(); //wait for all the shared memory to be loaded

 for (int k = 0; k < TILE_WIDTH; k++) {
 result += A[ty][k] * B[k][tx];
 }
 __syncthreads();
 }
     C[(row * width) + col] = result;
}
</code>```

答:
although you have __local__ it should be __local

the translations for threadIdx.x, blockIdx.x, etc. are given here

as already indicated, the translation for __syncthreads() is given here

there are some other errors in your kernel code, for example you use width but have defined A_width and B_width only,  also, in your multiply loop you are using A[][] and B[][] but it should be Ashare[][] and Bshare[][]

here's a fully-worked example showing the changes and fixes:

```<code>$ cat t5.cpp
#include <CL/opencl.h>
#include <stdio.h>
#include <stdlib.h>

#define TILE_WIDTH 16
#define DS 1024

const char source[] =
"__kernel void matrix_multiply(__global float *A, __global float *B,"
" __global float *C, int width)"
"{"
"   __local float Ashare[TILE_WIDTH][TILE_WIDTH];"
"   __local float Bshare[TILE_WIDTH][TILE_WIDTH];"
"   int bx = get_group_id(0);"
"   int by = get_group_id(1);"
"   int tx = get_local_id(0);"
"   int ty = get_local_id(1);"
"   int row = by * TILE_WIDTH + ty;"
"   int col = bx * TILE_WIDTH + tx;"
"   float result = 0;"
"   for (int m = 0; m < width / TILE_WIDTH; m++) {"
"     Ashare[ty][tx] = A[(row * width) + (m * TILE_WIDTH) + tx];"
"     Bshare[ty][tx] = B[(((m * TILE_WIDTH) + ty) * width) + col];"
"     barrier(CLK_LOCAL_MEM_FENCE); "
"       for (int k = 0; k < TILE_WIDTH; k++) {"
"         result += Ashare[ty][k] * Bshare[k][tx];"
"       }"
"     barrier(CLK_LOCAL_MEM_FENCE); "
"   }"
"   C[(row * width) + col] = result;"
"};"

;

int main(int argc, char *argv[])
{
  cl_platform_id platform;
  cl_device_id device;
  cl_context context;
  cl_command_queue queue1, queue2;
  cl_program program;
  cl_mem mem1, mem2, mem3;
  cl_kernel kernel;
  cl_int err;

  err = clGetPlatformIDs(1, &platform, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  context = clCreateContext(NULL, 1, &device, NULL, NULL, NULL);
  queue1 = clCreateCommandQueue(context, device, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, NULL);

  const char *sources[1] = {source};
  program = clCreateProgramWithSource(context, 1, sources, NULL, &err);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clBuildProgram(program, 1, &device, "-D TILE_WIDTH=16", NULL, NULL);
  if (err == CL_BUILD_PROGRAM_FAILURE) {
    // Determine the size of the log
    size_t log_size;
    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);

    // Allocate memory for the log
    char *log = (char *) malloc(log_size);

    // Get the log
    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size, log, NULL);

    // Print the log
    printf("%s\n", log);
  }

  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  mem1 = clCreateBuffer(context, CL_MEM_READ_WRITE, DS*DS*sizeof(float), NULL, NULL);
  mem2 = clCreateBuffer(context, CL_MEM_READ_WRITE, DS*DS*sizeof(float), NULL, NULL);
  mem3 = clCreateBuffer(context, CL_MEM_READ_WRITE, DS*DS*sizeof(float), NULL, NULL);
  float *hdata = new float[DS*DS];
  for (int i = 0; i < DS*DS; i++) hdata[i] = 1;
  kernel = clCreateKernel(program, "matrix_multiply", &err);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  const size_t gwork_size[2] = {DS,DS};
  const size_t lwork_size[2] = {TILE_WIDTH,TILE_WIDTH};
  int msize = DS;
  err = clSetKernelArg(kernel, 0, sizeof(mem1), &mem1);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clSetKernelArg(kernel, 1, sizeof(mem2), &mem2);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clSetKernelArg(kernel, 2, sizeof(mem3), &mem3);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clSetKernelArg(kernel, 3, sizeof(msize), &msize);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}

  err = clEnqueueWriteBuffer(queue1, mem1, CL_TRUE, 0, DS*DS*sizeof(float), hdata, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clEnqueueWriteBuffer(queue1, mem2, CL_TRUE, 0, DS*DS*sizeof(float), hdata, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clEnqueueNDRangeKernel(queue1, kernel, 2, NULL, gwork_size, lwork_size, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clEnqueueReadBuffer(queue1, mem3, CL_TRUE, 0, DS*DS*sizeof(float), hdata, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  for (int i = 0; i < DS*DS; i++)
    if (hdata[i] != DS) {printf("error at %d, was %f, should be %f\n", i, hdata[i], (float)DS); return 1;}
  printf("success!\n");
  return 0;
}
$ g++ -I/usr/local/cuda/include t5.cpp -o t5 -lOpenCL
$ ./t5
success!
$
</code>```

convenient build log printer picked up from here.

Body:
I recently started to work with OpenCl and i trying to change my CUDA code that does the tiled matrix multiplication to OpenCl. I have done some change but i am not sure if i am doing correct. I don't know what would be the blockIdx, threadIdx, __syncthreads, Ashare and Bshare in opencl.
I will be more than happy if any one can help me.

My CUDA Kernel code for tiled matrix multiplication:

#define TILE_WIDTH 16
__global__ void matrixMulKernel(float* A, float* B, float* C, int width) {
 __shared__ float Ashare[TILE_WIDTH][TILE_WIDTH];
 __shared__ float Bshare[TILE_WIDTH][TILE_WIDTH];
 int bx = blockIdx.x, by = blockIdx.y;
 int tx = threadIdx.x, ty = threadIdx.y;
 //calculate the row and column for this element of the matrix
 int row = by * TILE_WIDTH + ty;
 int col = bx * TILE_WIDTH + tx;
 float result = 0;
 //loop over the A and B tiles required to compute the C element
 for (int m = 0; m < width / TILE_WIDTH; m++) {
 //collectively load the A and B tiles into shared memory
 Ashare[ty][tx] = A[(row * width) + (m * TILE_WIDTH) + tx];
 Bshare[ty][tx] = B[(((m * TILE_WIDTH) + ty) * width) + col];
 __syncthreads(); //wait for all the shared memory to be loaded

 for (int k = 0; k < TILE_WIDTH; k++) {
 result += A[ty][k] * B[k][tx];
 }
 __syncthreads();
 }
     C[(row * width) + col] = result;
}

Body:
although you have __local__ it should be __local

the translations for threadIdx.x, blockIdx.x, etc. are given here

as already indicated, the translation for __syncthreads() is given here

there are some other errors in your kernel code, for example you use width but have defined A_width and B_width only,  also, in your multiply loop you are using A[][] and B[][] but it should be Ashare[][] and Bshare[][]

here's a fully-worked example showing the changes and fixes:

$ cat t5.cpp
#include <CL/opencl.h>
#include <stdio.h>
#include <stdlib.h>

#define TILE_WIDTH 16
#define DS 1024

const char source[] =
"__kernel void matrix_multiply(__global float *A, __global float *B,"
" __global float *C, int width)"
"{"
"   __local float Ashare[TILE_WIDTH][TILE_WIDTH];"
"   __local float Bshare[TILE_WIDTH][TILE_WIDTH];"
"   int bx = get_group_id(0);"
"   int by = get_group_id(1);"
"   int tx = get_local_id(0);"
"   int ty = get_local_id(1);"
"   int row = by * TILE_WIDTH + ty;"
"   int col = bx * TILE_WIDTH + tx;"
"   float result = 0;"
"   for (int m = 0; m < width / TILE_WIDTH; m++) {"
"     Ashare[ty][tx] = A[(row * width) + (m * TILE_WIDTH) + tx];"
"     Bshare[ty][tx] = B[(((m * TILE_WIDTH) + ty) * width) + col];"
"     barrier(CLK_LOCAL_MEM_FENCE); "
"       for (int k = 0; k < TILE_WIDTH; k++) {"
"         result += Ashare[ty][k] * Bshare[k][tx];"
"       }"
"     barrier(CLK_LOCAL_MEM_FENCE); "
"   }"
"   C[(row * width) + col] = result;"
"};"

;

int main(int argc, char *argv[])
{
  cl_platform_id platform;
  cl_device_id device;
  cl_context context;
  cl_command_queue queue1, queue2;
  cl_program program;
  cl_mem mem1, mem2, mem3;
  cl_kernel kernel;
  cl_int err;

  err = clGetPlatformIDs(1, &platform, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  context = clCreateContext(NULL, 1, &device, NULL, NULL, NULL);
  queue1 = clCreateCommandQueue(context, device, CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, NULL);

  const char *sources[1] = {source};
  program = clCreateProgramWithSource(context, 1, sources, NULL, &err);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clBuildProgram(program, 1, &device, "-D TILE_WIDTH=16", NULL, NULL);
  if (err == CL_BUILD_PROGRAM_FAILURE) {
    // Determine the size of the log
    size_t log_size;
    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 0, NULL, &log_size);

    // Allocate memory for the log
    char *log = (char *) malloc(log_size);

    // Get the log
    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, log_size, log, NULL);

    // Print the log
    printf("%s\n", log);
  }

  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  mem1 = clCreateBuffer(context, CL_MEM_READ_WRITE, DS*DS*sizeof(float), NULL, NULL);
  mem2 = clCreateBuffer(context, CL_MEM_READ_WRITE, DS*DS*sizeof(float), NULL, NULL);
  mem3 = clCreateBuffer(context, CL_MEM_READ_WRITE, DS*DS*sizeof(float), NULL, NULL);
  float *hdata = new float[DS*DS];
  for (int i = 0; i < DS*DS; i++) hdata[i] = 1;
  kernel = clCreateKernel(program, "matrix_multiply", &err);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  const size_t gwork_size[2] = {DS,DS};
  const size_t lwork_size[2] = {TILE_WIDTH,TILE_WIDTH};
  int msize = DS;
  err = clSetKernelArg(kernel, 0, sizeof(mem1), &mem1);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clSetKernelArg(kernel, 1, sizeof(mem2), &mem2);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clSetKernelArg(kernel, 2, sizeof(mem3), &mem3);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clSetKernelArg(kernel, 3, sizeof(msize), &msize);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}

  err = clEnqueueWriteBuffer(queue1, mem1, CL_TRUE, 0, DS*DS*sizeof(float), hdata, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clEnqueueWriteBuffer(queue1, mem2, CL_TRUE, 0, DS*DS*sizeof(float), hdata, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clEnqueueNDRangeKernel(queue1, kernel, 2, NULL, gwork_size, lwork_size, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  err = clEnqueueReadBuffer(queue1, mem3, CL_TRUE, 0, DS*DS*sizeof(float), hdata, 0, NULL, NULL);
  if (err != CL_SUCCESS) {printf("%d: %d\n", __LINE__, err); return -1;}
  for (int i = 0; i < DS*DS; i++)
    if (hdata[i] != DS) {printf("error at %d, was %f, should be %f\n", i, hdata[i], (float)DS); return 1;}
  printf("success!\n");
  return 0;
}
$ g++ -I/usr/local/cuda/include t5.cpp -o t5 -lOpenCL
$ ./t5
success!
$

convenient build log printer picked up from here.


答:
A newtype is a data type with a constructor, so you need to unwrap the tuple out of the constructor MultiBalanceReport first:

```<code>getDates :: MultiBalanceReport -> [DateSpan]
getDates <b>(MultiBalanceReport</b> (date,_,_)<b>)</b> = date</code>```

Title: Haskell: Retrieve nth value from type which is a tuple

Body:
A newtype is a data type with a constructor, so you need to unwrap the tuple out of the constructor MultiBalanceReport first:

getDates :: MultiBalanceReport -> [DateSpan]
getDates (MultiBalanceReport (date,_,_)) = date


问:
Create table mysql
I'am new to mysql and i want to know what KEY (not primary key) means in the query below :

```<code>    CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL default '',
  `username` varchar(150) NOT NULL default '',
  `email` varchar(100) NOT NULL default '',
  `password` varchar(100) NOT NULL default '',
  `activation` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`),
  KEY `idx_name` (`name`),
  KEY `username` (`username`),
  KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=65 ;
</code>```

also this line ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=65 ;

答:
KEY is normally a synonym for INDEX.

```<code>ENGINE=MyISAM
</code>```

It means the storage engine for your table. There are two types of storage engines in MySQL: transactional and non-transactional. The default engine is InnoDB as of MySQL 5.5.5 ( MyISAM before 5.5.5).

```<code>DEFAULT CHARSET=utf8
</code>```

Character set support that enables you to store data using a variety of character sets.

```<code>AUTO_INCREMENT=65
</code>```

It means currently the value of auto_increment is 65 for primary key id.

More information:-
https://dev.mysql.com/doc/refman/5.7/en/create-table.html

Title: Create table mysql

Body:
I'am new to mysql and i want to know what KEY (not primary key) means in the query below :

    CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL default '',
  `username` varchar(150) NOT NULL default '',
  `email` varchar(100) NOT NULL default '',
  `password` varchar(100) NOT NULL default '',
  `activation` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`),
  KEY `idx_name` (`name`),
  KEY `username` (`username`),
  KEY `email` (`email`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=65 ;

also this line ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=65 ;

Body:
KEY is normally a synonym for INDEX.

ENGINE=MyISAM

It means the storage engine for your table. There are two types of storage engines in MySQL: transactional and non-transactional. The default engine is InnoDB as of MySQL 5.5.5 ( MyISAM before 5.5.5).

DEFAULT CHARSET=utf8

Character set support that enables you to store data using a variety of character sets.

AUTO_INCREMENT=65

It means currently the value of auto_increment is 65 for primary key id.

More information:-
https://dev.mysql.com/doc/refman/5.7/en/create-table.html


问:
With List<KeyValuePair<int, int>>, to make 1 in 4 of the values equal 1
I have a List< KeyValuePair < int,int >>. (I chose this over a dictionary since multiple keys will be the same (though consecutive keys won't be the same); and because I want to output them in the order input).

All the keys are equal to a randNum between 1-5 (inclusive). (The keys don't really matter in relation to my problem).

All the values are the default, 0.

I want to change 1 in 4 of the values to equal 1 (the others still equal 0). The position of the value=1 in each range of 4 is randomly chosen.

An example output of what I want, printing the KVPs in the list:

```<code>[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]
</code>```

So, in groups of 4, the values would be: 0100 | 0001 | 0010.

Here's what I've tried to do so far:
(the sequence is already set up with all the keys)

```<code>List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();

// Populate keys in sequence with random numbers 1-5
// ...

public static void SetSequenceValues()
{
    Random randNum = new Random();
    bool allValuesSet = false;

    // count is the max (non-inclusive) in each range of 4
    // i.e. first loop is 1-4
    // then count += 4
    // second loop is 5-8, etc.
    int count = 5;

    while (allValuesSet == false)
    {
        int randPos = randNum.Next(count - 4, count);

        // If changing the first key in the range,
        // the desired key index = count-4
        if (randPos == count - 4)
        {
            var oldKVP = sequence[count - 4];
            sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count -3)
        {
            var oldKVP = sequence[count - 3];
            sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 2)
        {
            var oldKVP = sequence[count - 2];
            sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 1)
        {
            var oldKVP = sequence[count - 1];
            sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }

        // Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
        count += 4;

        if (count >= sequence.Count)
            allValuesSet = true;
    }
}
</code>```

Currently, the output is kind of close-ish, but, occasionally there'll be a couple of 1s in each group. Also, I think it may be using groups of 5 rather than 4? Though that doesn't seem to entirely be it either.

答:
As far as what's broken with the code you posted I think you have an off by 1 issue somewhere. It looks like you index into the array starting at [1] when the first key should be [0]. Try setting count to 4 initially instead of 5.

```<code>...
int count = 4;

while (allValuesSet == false)
{
...
</code>```

I would recommend trying to use loops and variables in place of hard coded if conditions. You have the right idea but you don't need to check the value of the index, you can just use it in place. So you can collapse the following to make it a lot more readable. You could replace all of

```<code>    // If changing the first key in the range,
    // the desired key index = count-4
    if (randPos == count - 4)
    {
        var oldKVP = sequence[count - 4];
        sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
    else if (randPos == count -3)
    {
        var oldKVP = sequence[count - 3];
        sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
    else if (randPos == count - 2)
    {
        var oldKVP = sequence[count - 2];
        sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
    else if (randPos == count - 1)
    {
        var oldKVP = sequence[count - 1];
        sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
</code>```

With

```<code>var oldKVP = sequence[randPos];
sequence[randPos] = new KeyValuePair<int, int>(oldKVP.Key, 1);
</code>```

To do what you want to do in a more generalized fashion I would do as below

```<code>using System;
using System.Collections.Generic;

namespace KvpSequence
{
    class Program
    {
        const int numberOfSequences = 4; // each sequence is a set of 4 ints between 1 and 5
        static void Main(string[] args)
        {
            List<KeyValuePair<int, int>> sequence = new List<KeyValuePair<int, int>>(numberOfSequences * 4);
            Random rand = new Random();

            for (int i = 0; i < numberOfSequences; ++i) {
                var indexToSet = rand.Next(0, 4);
                for (int j = 0; j < 4; ++j)
                    sequence.Add(new KeyValuePair<int, int>(rand.Next(1, 6), j == indexToSet ? 1 : 0));
            }

            foreach (var kvp in sequence)
                Console.WriteLine(kvp);
        }
    }
}
</code>```

Body:
I have a List< KeyValuePair < int,int >>. (I chose this over a dictionary since multiple keys will be the same (though consecutive keys won't be the same); and because I want to output them in the order input).

All the keys are equal to a randNum between 1-5 (inclusive). (The keys don't really matter in relation to my problem).

All the values are the default, 0.

I want to change 1 in 4 of the values to equal 1 (the others still equal 0). The position of the value=1 in each range of 4 is randomly chosen.

An example output of what I want, printing the KVPs in the list:

[5,0]
[3,1]
[2,0]
[5,0]
[1,0]
[4,0]
[2,0]
[3,1]
[1,0]
[5,0]
[4,1]
[2,0]

So, in groups of 4, the values would be: 0100 | 0001 | 0010.

Here's what I've tried to do so far:
(the sequence is already set up with all the keys)

List<KeyValuePair<int,int>> sequence = new List<KeyValuePair<int,int>>();

// Populate keys in sequence with random numbers 1-5
// ...

public static void SetSequenceValues()
{
    Random randNum = new Random();
    bool allValuesSet = false;

    // count is the max (non-inclusive) in each range of 4
    // i.e. first loop is 1-4
    // then count += 4
    // second loop is 5-8, etc.
    int count = 5;

    while (allValuesSet == false)
    {
        int randPos = randNum.Next(count - 4, count);

        // If changing the first key in the range,
        // the desired key index = count-4
        if (randPos == count - 4)
        {
            var oldKVP = sequence[count - 4];
            sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count -3)
        {
            var oldKVP = sequence[count - 3];
            sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 2)
        {
            var oldKVP = sequence[count - 2];
            sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }
        else if (randPos == count - 1)
        {
            var oldKVP = sequence[count - 1];
            sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
        }

        // Increase count by 4, so on the next loop, e.g. the range looked at will be 4-8 (not including 8, i.e. 4-7)
        count += 4;

        if (count >= sequence.Count)
            allValuesSet = true;
    }
}

Currently, the output is kind of close-ish, but, occasionally there'll be a couple of 1s in each group. Also, I think it may be using groups of 5 rather than 4? Though that doesn't seem to entirely be it either.

Body:
As far as what's broken with the code you posted I think you have an off by 1 issue somewhere. It looks like you index into the array starting at [1] when the first key should be [0]. Try setting count to 4 initially instead of 5.

...
int count = 4;

while (allValuesSet == false)
{
...

I would recommend trying to use loops and variables in place of hard coded if conditions. You have the right idea but you don't need to check the value of the index, you can just use it in place. So you can collapse the following to make it a lot more readable. You could replace all of

    // If changing the first key in the range,
    // the desired key index = count-4
    if (randPos == count - 4)
    {
        var oldKVP = sequence[count - 4];
        sequence[count - 4] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
    else if (randPos == count -3)
    {
        var oldKVP = sequence[count - 3];
        sequence[count -3] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
    else if (randPos == count - 2)
    {
        var oldKVP = sequence[count - 2];
        sequence[count - 2] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }
    else if (randPos == count - 1)
    {
        var oldKVP = sequence[count - 1];
        sequence[count - 1] = new KeyValuePair<int, int>(oldKVP.Key, 1);
    }

With

var oldKVP = sequence[randPos];
sequence[randPos] = new KeyValuePair<int, int>(oldKVP.Key, 1);

To do what you want to do in a more generalized fashion I would do as below

using System;
using System.Collections.Generic;

namespace KvpSequence
{
    class Program
    {
        const int numberOfSequences = 4; // each sequence is a set of 4 ints between 1 and 5
        static void Main(string[] args)
        {
            List<KeyValuePair<int, int>> sequence = new List<KeyValuePair<int, int>>(numberOfSequences * 4);
            Random rand = new Random();

            for (int i = 0; i < numberOfSequences; ++i) {
                var indexToSet = rand.Next(0, 4);
                for (int j = 0; j < 4; ++j)
                    sequence.Add(new KeyValuePair<int, int>(rand.Next(1, 6), j == indexToSet ? 1 : 0));
            }

            foreach (var kvp in sequence)
                Console.WriteLine(kvp);
        }
    }
}


问:
Cannot declare class 'TestCommandRun', because the name is already in use
I am using laravel 5.4.

I am using php artisan list, but get the following error:

```<code>C:\Users\admin\Desktop\Coding Projects\demo_laravel>php artisan list
PHP Fatal error:  Cannot declare class TestCommandRun, because the name is already in use in C:\Users\admin\Desktop\Coding Projects\demo_laravel\app\Console\Commands\TestCommandRun.php on line 109
PHP Stack trace:
PHP   1. {main}() C:\Users\admin\Desktop\Coding Projects\demo_laravel\artisan:0
PHP   2. App\Console\Kernel->handle() C:\Users\admin\Desktop\Coding Projects\demo_laravel\artisan:37
PHP   3. App\Console\Kernel->getArtisan() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:121
PHP   4. Illuminate\Console\Application->resolveCommands() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:317
PHP   5. Illuminate\Console\Application->resolve() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Console\Application.php:242
PHP   6. Illuminate\Foundation\Application->make() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Console\Application.php:228
PHP   7. Illuminate\Foundation\Application->make() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:732
PHP   8. Illuminate\Foundation\Application->resolve() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:586
PHP   9. Illuminate\Foundation\Application->build() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:631
PHP  10. ReflectionClass->__construct() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
PHP  11. spl_autoload_call() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
PHP  12. Composer\Autoload\ClassLoader->loadClass() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
PHP  13. Composer\Autoload\includeFile() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\composer\ClassLoader.php:322

In TestCommandRun.php line 109:

  Cannot declare class TestCommandRun, because the name is already in use
</code>```

My Command has the right name:

```<code>class TestCommandRun extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'TestCommandRun:run';
</code>```

Within my Kernel.php I have added it to $commands section:

```<code>protected $commands = [
    '\App\Console\Commands\TestCommandRun',
];
</code>```

Any suggestions why I get the above error message?

答:
Looks like you have two commands with the same class name TestCommandRun. So, you need to delete one.

Also it's a good idea to run composer du command after that.

Body:
I am using laravel 5.4.

I am using php artisan list, but get the following error:

C:\Users\admin\Desktop\Coding Projects\demo_laravel>php artisan list
PHP Fatal error:  Cannot declare class TestCommandRun, because the name is already in use in C:\Users\admin\Desktop\Coding Projects\demo_laravel\app\Console\Commands\TestCommandRun.php on line 109
PHP Stack trace:
PHP   1. {main}() C:\Users\admin\Desktop\Coding Projects\demo_laravel\artisan:0
PHP   2. App\Console\Kernel->handle() C:\Users\admin\Desktop\Coding Projects\demo_laravel\artisan:37
PHP   3. App\Console\Kernel->getArtisan() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:121
PHP   4. Illuminate\Console\Application->resolveCommands() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:317
PHP   5. Illuminate\Console\Application->resolve() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Console\Application.php:242
PHP   6. Illuminate\Foundation\Application->make() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Console\Application.php:228
PHP   7. Illuminate\Foundation\Application->make() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Foundation\Application.php:732
PHP   8. Illuminate\Foundation\Application->resolve() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:586
PHP   9. Illuminate\Foundation\Application->build() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:631
PHP  10. ReflectionClass->__construct() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
PHP  11. spl_autoload_call() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
PHP  12. Composer\Autoload\ClassLoader->loadClass() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:752
PHP  13. Composer\Autoload\includeFile() C:\Users\admin\Desktop\Coding Projects\demo_laravel\vendor\composer\ClassLoader.php:322

In TestCommandRun.php line 109:

  Cannot declare class TestCommandRun, because the name is already in use

My Command has the right name:

class TestCommandRun extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'TestCommandRun:run';

Within my Kernel.php I have added it to $commands section:

protected $commands = [
    '\App\Console\Commands\TestCommandRun',
];

Any suggestions why I get the above error message?


问:
How could the test_and_set() instruction still work on a multiprocessor?
Dear stack overflow community,

I'm reading Operating System Concepts (2012) by Silberschatz, Galvin and Gagne, it says "if two test_and_set() instructions are executed simultaneously (each on a different CPU), they will be executed sequentially in some arbitrary order." on page 210, I cannot understand why two such institutions will be executed sequentially even on a multiprocessor. What if each instruction is executed on a different processor? To the best of my knowledge, these two institutions be executed simultaneously.

My understanding of the atomicity of instructions and the multiprocessor stays at a quite superficial level, so I may take the problem for granted. Could anyone help me out here?

答:
The whole point of test-and-set is that one processor will execute it first, and then the other processor will execute it, and they will not do it simultaneously.

To achieve this, there will be some communication between both processors. Basically, one processor will load the cache line including the memory location from memory, and tell the other processor that it can't have that cache line until both test and set are finished.


问:
How to Fix Permissions on Home-brew on MacOS High Sierra
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

```<code>$ brew link python
</code>```

After entering that the same error message appears:

```permission denied @ dir_s_mkdir - /usr/local/lib```

I have tried to do:

```<code>$ sudo chown -R $(whoami) /usr/local
</code>```

And I get an error message that reads:

chown: /usr/local: Operation not permitted

答: Uninstalling and doing a clean install of homebrew will fix the issue.</p>

ContentLicense: CC BY-SA 4.0

Body:
When I tried to install python onto homebrew it downloaded it and then an error message popped up at the end that stopped it from completing. When I try to do it again it asks me to do:

$ brew link python

After entering that the same error message appears:

permission denied @ dir_s_mkdir - /usr/local/lib

I have tried to do:

$ sudo chown -R $(whoami) /usr/local

And I get an error message that reads:

chown: /usr/local: Operation not permitted


问:
Given a matrix which only contains 0 and 1, and each row of the matrix is sorted, please find which row contains the most 1s

Given a matrix which only contains 0 and 1, and each row of the matrix is sorted, please find which row contains the most 1s. For a M*N matrix, O(M+N) time complexity is required, and O(1) space complexity is required.

Example

Input:

000000011111

000011111111

000000111111

000000000111

000000011111

000011111111

Output:

As row 2 and row 6 both contain 8 1s, the output is [2,8],[6,8].

I came up a solution:

```<code>public List<List<Integer>> mostOnes(int[][] a) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    for (int j = 0; j < a[0].length; j++) {
        for (int i = 0; i < a.length; i++) {
            if (a[i][j] == 1) {
                List<Integer> res = new ArrayList<>();
                res.add(i + 1);
                res.add(a[0].length - j);
                result.add(res);
            }
        }
        if (result.size() != 0) break;
    }
    return result;
}
</code>```

However, it is not O(M+N). Does anyone have other solutions?

答:
Please check my O(m + n) implementation. The code is written in C, but easily you can convert it to Java.

```<code>int FindRow(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    int i = 0, j = n - 1, mx = 0;
    while (i < m && j >= 0) {
        while (j >= 0 && mat[i][j] == 1) --j;
        mx = max(mx, n - j - 1);
        ++i;
    }
    return mx;
}
</code>```

I have started with first row and last column. When I get first 0, I move to next row. We should check only remaining columns at most.

Body:
Given a matrix which only contains 0 and 1, and each row of the matrix is sorted, please find which row contains the most 1s. For a M*N matrix, O(M+N) time complexity is required, and O(1) space complexity is required.

Example

Input:

000000011111

000011111111

000000111111

000000000111

000000011111

000011111111

Output:

As row 2 and row 6 both contain 8 1s, the output is [2,8],[6,8].

I came up a solution:

public List<List<Integer>> mostOnes(int[][] a) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    for (int j = 0; j < a[0].length; j++) {
        for (int i = 0; i < a.length; i++) {
            if (a[i][j] == 1) {
                List<Integer> res = new ArrayList<>();
                res.add(i + 1);
                res.add(a[0].length - j);
                result.add(res);
            }
        }
        if (result.size() != 0) break;
    }
    return result;
}

However, it is not O(M+N). Does anyone have other solutions?

Body:
Please check my O(m + n) implementation. The code is written in C, but easily you can convert it to Java.

int FindRow(vector<vector<int>>& mat) {
    int m = mat.size(), n = mat[0].size();
    int i = 0, j = n - 1, mx = 0;
    while (i < m && j >= 0) {
        while (j >= 0 && mat[i][j] == 1) --j;
        mx = max(mx, n - j - 1);
        ++i;
    }
    return mx;
}

I have started with first row and last column. When I get first 0, I move to next row. We should check only remaining columns at most.


问:
Which patterns to use - how to design
All,

I am the process of applying design thinking to everyday problems. on the process, i need some help on the following. Assume a car renting company such as hertz is needing an application, along with regular data, they need the ability to offer customers offers based on certain criteria.

Criteria are

All listed holidays (not weekends) - get 10% off on hire price

Labor day alone get 15% off on hire price

if taking > 3 days for listed holidays - 20 % off

if taking >3 days on labor day - 25% off

etc - more will come

Now I can think of decorators to start off such as

```<code>IVehicleBase
{
 Props: Make, Model, HirePrice, HireTimePeriodinDays
}
</code>```

Concrete classes:

```<code>public class FordExplorer : VehicleBase
{
    public override string Make
    {
        get { return "Ford"; }
    }

    public override string Model
    {
        get { return "Explorer"; }
    }

    public override double HirePrice
    {
        get { return 450; }
    }

    public override int HireTimePeriodinDays
    {
        get { return 1; }
    }
}
</code>```

Similarly for many other classes (cars).

now how do i decorate the special offers ?

I Can think of a vehicleDecoratorBase, but if the offer is specific to just the holidays then fine (make two concrete implementations for labor / other listed holidays), but we have holidays combined with hireDate which is a domain property of car.

I hope I am making sense here. Any advices pls ?

Cheers

答:
I would say the rentals, prices, special offers etc. do not belong to the vehicle: these are separate abstraction(s). Especially so as the kinds of offers you list above do not seem to be linked to a specific vehicle model, only to calendar days / length of rental etc.

So don't try to add these as decorators to the vehicle. Instead, create a separate class (hierarchy) to deal with them.

Note that based on your description you have two use cases:

the rental agent needs to be able to enumerate all existing offers to the customer like "if you start your rental next Monday, you will get a 10% discount due to this offer, alternatively if you start on Tuesday but extend the rental to 3 days you will get 20% off" etc.

the (estimated) price of a concrete rental needs to be calculated taking into account all applicable discounts.

So on the one hand you should store an instance of each valid offer in a collection, which allows the agent to list them one by one, along with a textual description. (Note that as the offers are most likely stateless, you can have a single shared instance of each.)

OTOH you need functionality for each offer to decide whether it is applicable for a given concrete rental. This can be implemented within the individual offer classes, then invoked polymorphically by e.g. an offer selector (a special kind of factory), which iterates over the collection of offers and selects the ones for the given rentals (nice, you can immediately reuse the collection of offers for a different purpose!). The applicable offers then in fact operate on the collection of rental charges (i.e. not necessarily directly on the rental object itself), modifying / removing charges as applicable.

As a side note, if you represent each vehicle model with a separate derived class of IVehicleBase, you would have an awful lot of derived classes in real life, and moreover you would need to add new ones regularly as new models come out and get incorporated into the fleet. And requiring a code change whenever a new vehicle model appears is a maintenance headache in the long run. Of course, if this is just an experimental / toy project, maintenance may not be an issue.

ContentLicense: CC BY-SA 2.5

Title: Which patterns to use - how to design

Body:
All,

I am the process of applying design thinking to everyday problems. on the process, i need some help on the following. Assume a car renting company such as hertz is needing an application, along with regular data, they need the ability to offer customers offers based on certain criteria.

Criteria are

All listed holidays (not weekends) - get 10% off on hire price

Labor day alone get 15% off on hire price

if taking > 3 days for listed holidays - 20 % off

if taking >3 days on labor day - 25% off

etc - more will come

Now I can think of decorators to start off such as

IVehicleBase
{
 Props: Make, Model, HirePrice, HireTimePeriodinDays
}

Concrete classes:

public class FordExplorer : VehicleBase
{
    public override string Make
    {
        get { return "Ford"; }
    }

    public override string Model
    {
        get { return "Explorer"; }
    }

    public override double HirePrice
    {
        get { return 450; }
    }

    public override int HireTimePeriodinDays
    {
        get { return 1; }
    }
}

Similarly for many other classes (cars).

now how do i decorate the special offers ?

I Can think of a vehicleDecoratorBase, but if the offer is specific to just the holidays then fine (make two concrete implementations for labor / other listed holidays), but we have holidays combined with hireDate which is a domain property of car.

I hope I am making sense here. Any advices pls ?

Cheers


问:
Change home directory for R
Somehow, my home and library directories in R got changed to a cloud location, which is messing up a bunch of paths, and now, I can't seem to change it back. When I type path.expand("~") in R, I get back "C:/Users/MyName/OneDrive/Documents", but I was expecting to get "C:/Users/MyName/Documents".

When I try .libPaths(), I get "C:/Users/MyName/OneDrive/Documents/R/win-library/3.4" and "C:/Program Files/R/R-3.4.3/library", but I only want the latter.

I have tried uninstalling and reinstalling both R and RStudio (thus now working with the most-recent versions of each), but the cloud path persists. I have seen posts elsewhere on SO about setting things in the .Rprofile file, but I don't think that's the right option, especially since the .Rprofile file would then have to be in a cloud location, which I don't want.

I have looked at my environment variables in the control panel (I'm on Windows 10) and looked at PATH, but there's nothing there that specifies the cloud directory, so I don't know where it's coming from.

How do I permanently change my home directory and also make sure that .libPaths is pointing to only the actual library directory?

答:
This is based on your windows environment variable HOME.  You need to reset HOME to the path that you want "C:/Users/MyName/Documents"

If you want to do that from within R, you can use:

```<code>Sys.setenv(HOME="C:/Users/MyName/Documents")
</code>```

This change would not be permanent. If you wish to avoid doing this every time you run R, you could put the above statement in your .Rprofile file. There is a nice article on setting up your .Rprofile in the RStudio support

Title: Change home directory for R

Body:
This is based on your windows environment variable HOME.  You need to reset HOME to the path that you want "C:/Users/MyName/Documents"

If you want to do that from within R, you can use:

Sys.setenv(HOME="C:/Users/MyName/Documents")

This change would not be permanent. If you wish to avoid doing this every time you run R, you could put the above statement in your .Rprofile file. There is a nice article on setting up your .Rprofile in the RStudio support


问:
jQuery hover is too slow
Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.

How to fix it? (the white holes)

I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.

Any help appreciated :)

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('

');

  }

  var tile = $(".tile");

  tile.hover (
    function() { //hover-in
      $(this).css("background-color","red");
    },
    function() { //hover-out

    }
   );

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}</code>```

```

答:
With your design one way would be to iterate over the first to your current hovered element and fill it, which would lead no spaces. That said you may want to consider using the HTML5 Canvas and drawing a rectangle from 0 to your mouse position, which will perform significantly faster.

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('

');

  }

  var tile = $(".tile");

  tile.hover (
    function() { //hover-in
      var self = this;
      $("#line").children().each(function(){
        $(this).css("background-color","red");
        if(this == self) return false;
      });
    },
    function() { //hover-out

    }
   );

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}</code>```

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

<hr>

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

<p>Below is an example doing the same task but using the HTML 5 Canvas:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$("#line").mousemove(function(e){
  var canvas = $(this)[0];
  var ctx = canvas.getContext("2d");
  var rect = canvas.getBoundingClientRect()
  var x = e.clientX - rect.left;
  ctx.fillStyle="red";
  ctx.fillRect(0, 0, x, canvas.height);
});</code>```

#line{ background-color: #ddd; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="line" width=500 height=50 ></canvas></code>```

Title: jQuery hover is too slow

Body:
Please run the snippet and drag you mouse over the bar to make it red.
If you drag the mouse very slowly, you will fill it red, but if you move it fast, there will be white holes in it.

How to fix it? (the white holes)

I want to make a bar divided into 500 parts and if you hover it, it becomes red and being able to drag fast and fill it without holes.

Any help appreciated :)

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('

');

  }

  var tile = $(".tile");

  tile.hover (
    function() { //hover-in
      $(this).css("background-color","red");
    },
    function() { //hover-out

    }
   );

});

#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}

Body:
With your design one way would be to iterate over the first to your current hovered element and fill it, which would lead no spaces. That said you may want to consider using the HTML5 Canvas and drawing a rectangle from 0 to your mouse position, which will perform significantly faster.

$(function() {

  var line = $("#line");

  for ( var i = 0; i < 500; i++) {

    line.append('<div class="tile" id="t'+(i+1)+'"></div>');

  }

  var tile = $(".tile");

  tile.hover (
    function() { //hover-in
      var self = this;
      $("#line").children().each(function(){
        $(this).css("background-color","red");
        if(this == self) return false;
      });
    },
    function() { //hover-out

    }
   );

});

#line{
  height: 50px;
  background-color: #000;
  width: 500px;
}
.tile {
  height: 50px;
  float: left;
  background-color: #ddd;
  width: 1px;
}

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<div id="line"></div>

Edit

Below is an example doing the same task but using the HTML 5 Canvas:

$("#line").mousemove(function(e){
  var canvas = $(this)[0];
  var ctx = canvas.getContext("2d");
  var rect = canvas.getBoundingClientRect()
  var x = e.clientX - rect.left;
  ctx.fillStyle="red";
  ctx.fillRect(0, 0, x, canvas.height);
});

#line{ background-color: #ddd; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="line" width=500 height=50 ></canvas>


问:
How to get dictionary inside list and retrive specific values
I want to get dictionaries inside list and get specific values from them.

here is list that contain actual data:

```<code>[[{'confidence': 0.9655525279517, 'type': 'value', 'value': 'firefox'}],

[{'confidence': 0.97317936846366, 'type': 'value', 'value': 'open'}],

[{'confidence': 0.98969319754083, 'value': 'app'}]]
</code>```

what i want is:
get value from every dictionary like:

```<code> value :'firefox'

 value : 'open'

 value : 'app'
</code>```

How i can accomplish this?

答:
```<code>Mylist = [[{'confidence': 0.9655525279517, 'type': 'value', 'value': 'firefox'}], [{'confidence': 0.97317936846366, 'type': 'value', 'value': 'open'}], [{'confidence': 0.98969319754083, 'value': 'app'}]]

for i in range(len(Mylist)):
    Values = Mylist[i][0]['value']
    print(Values)
</code>```

<p>in this way you can accomplish it </p>

Body:
I want to get dictionaries inside list and get specific values from them.

here is list that contain actual data:

[[{'confidence': 0.9655525279517, 'type': 'value', 'value': 'firefox'}],

[{'confidence': 0.97317936846366, 'type': 'value', 'value': 'open'}],

[{'confidence': 0.98969319754083, 'value': 'app'}]]

what i want is:
get value from every dictionary like:

 value :'firefox'

 value : 'open'

 value : 'app'

How i can accomplish this?

Body:
Mylist = [[{'confidence': 0.9655525279517, 'type': 'value', 'value': 'firefox'}], [{'confidence': 0.97317936846366, 'type': 'value', 'value': 'open'}], [{'confidence': 0.98969319754083, 'value': 'app'}]]

for i in range(len(Mylist)):
    Values = Mylist[i][0]['value']
    print(Values)

in this way you can accomplish it


问:
Feed Aggregator in Rails which can grab image
Im newbie. What Feed Aggregator available in Rails which can grab one image (largest image) from the source URL?</p>

答:
You could:

parse the feed with SimpleRSS

get the picture's url

store the image with the method described here (using paperclip):

Save image from URL by paperclip


问:
Laravel get last inserted data
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

```<code>    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }
</code>```

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

答:
Im still not entirely sure about what you are asking. If it is okay to make new queries something like this:

```<code>$country->refresh();
</code>```

Would reload the current model from the database and any already loaded relationships fresh from the database.

```<code>$country->id;
$country->created_at;
$firstBox = $country->boxes->first();
$firstBox->id;
$firstBox->created_at;
</code>```

It seems you would prefer to not have any more queries happen, that is okay as well. As long as there are no default values that your database would set that you need you can actually add these records to the relationship instead of reloading the relationship.

Say you have your country and you loaded that relationship:

```<code> $country->load('boxes');
 // or maybe because of eager loading
 $country = Country::where(...)->with('boxes')->first();

 ...
 foreach ( something ) {
     $dimention = new BoxDimentions;
     ...
     $dimention->save();
     $country->boxes->add($dimention);
 }

 return $country;
</code>```

$country->boxes would have all the items you had loaded before and all the new records.

If you only want the new ones, you can just set the relationship as the collection of the new ones.

```<code>$country->setRelation('boxes', $country->newCollection());

foreach ( something ) {
    ...
    $country->boxes->add($dimention);
}
</code>```

Now $country->boxes is just those new ones.

Title: Laravel get last inserted data

Body:
Please find the code below, Here I am trying to create master record and based on the id I am adding related data.

    $country = new Country;

    $country->name = $request->post('country-name');
    $country->xyz  = $request->post('xyz');

    if($country->save()) {
        $n = count($request->post('bname'));

        for ($i = 0; $i < $n; $i++) {
            $dimention = new BoxDimentions;

            $dimention->name = $request->post('bname')[$i];
            $dimention->xyz  = $request->post('xyz')[$i];
            $dimention->cid  = $country->id;

            $dimention->save();
        }
    }

Is there any inbuilt laravel function I can use to get all the information about country & BoxDimentions(including id, date time stamp etc) after the operation?

I have created a relation in the Country Model class "boxes" which will return all the box information. I know I can fetch the data using another query with the last created country id. I dont want to go for another query because I believe we have all the data is in our hand.

Body:
Im still not entirely sure about what you are asking. If it is okay to make new queries something like this:

$country->refresh();

Would reload the current model from the database and any already loaded relationships fresh from the database.

$country->id;
$country->created_at;
$firstBox = $country->boxes->first();
$firstBox->id;
$firstBox->created_at;

It seems you would prefer to not have any more queries happen, that is okay as well. As long as there are no default values that your database would set that you need you can actually add these records to the relationship instead of reloading the relationship.

Say you have your country and you loaded that relationship:

 $country->load('boxes');
 // or maybe because of eager loading
 $country = Country::where(...)->with('boxes')->first();

 ...
 foreach ( something ) {
     $dimention = new BoxDimentions;
     ...
     $dimention->save();
     $country->boxes->add($dimention);
 }

 return $country;

$country->boxes would have all the items you had loaded before and all the new records.

If you only want the new ones, you can just set the relationship as the collection of the new ones.

$country->setRelation('boxes', $country->newCollection());

foreach ( something ) {
    ...
    $country->boxes->add($dimention);
}

Now $country->boxes is just those new ones.


问:
Create tibble with all possible models
I have created a loop which creates all possible model combinations for a given data set. There are 63 possible models and I need to put them into a tibble with model number, subset of explanatory variables, model formula, and outcome (specifically r-squared value). </p>

```<code>Cols <- names(finalprojectdata3)
Cols <- Cols[! Cols %in% 'debt']
n <- length(Cols)

id <- unlist(
  lapply(1:n,
         function(i)combn(1:n, i, simplify = FALSE)
         ),
  recursive = FALSE)

Formulas <- sapply(id, function(i)
  paste('debt~', paste(Cols[i],collapse="+")))

models <- lapply(Formulas, function(i)
summary(lm(as.formula(i), data = finalprojectdata3)))

models
</code>```

<p>The output is a the summaries for each model but I need it in a easy to read tibble. </p>

答:
It's not perfectly clear how you want your output, but here's a suggested path, following tidyr nested objects.

Make some fake data, following your methodology above:

```<code>dat <- mtcars[,1:5]
Cols <- names(dat)
Cols <- Cols[! Cols %in% 'mpg']
n <- length(Cols)

id <- unlist(
  lapply(1:n,
         function(i)combn(1:n, i, simplify = FALSE)
         ),
  recursive = FALSE)
str(id)
# List of 15
#  $ : int 1
#  $ : int 2
#  $ : int 3
#  $ : int 4
#  $ : int [1:2] 1 2
#  $ : int [1:2] 1 3
#  $ : int [1:2] 1 4
#  $ : int [1:2] 2 3
#  $ : int [1:2] 2 4
#  $ : int [1:2] 3 4
#  $ : int [1:3] 1 2 3
#  $ : int [1:3] 1 2 4
#  $ : int [1:3] 1 3 4
#  $ : int [1:3] 2 3 4
#  $ : int [1:4] 1 2 3 4

Formulas <- sapply(id, function(i)
  paste('mpg ~', paste(Cols[i], collapse=" + ")))
head(Formulas)
# [1] "mpg ~ cyl"        "mpg ~ disp"       "mpg ~ hp"         "mpg ~ drat"
# [5] "mpg ~ cyl + disp" "mpg ~ cyl + hp"
</code>```

This is where I diverge from your path.

```<code>library(dplyr)
library(tidyr)
library(purrr)

x <- data_frame(Formulas) %>%
  mutate(
    lms = map(Formulas, ~ lm(as.formula(.), data = dat)),
    summaries = map(lms, ~ summary(.)),
    coefs = map(summaries, ~ as.data.frame(coef(.)))
  )
x
# # A tibble: 15 × 4
#                        Formulas      lms        summaries                coefs
#                           <chr>   <list>           <list>               <list>
# 1                     mpg ~ cyl <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 2                    mpg ~ disp <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 3                      mpg ~ hp <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 4                    mpg ~ drat <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 5              mpg ~ cyl + disp <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 6                mpg ~ cyl + hp <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 7              mpg ~ cyl + drat <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 8               mpg ~ disp + hp <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 9             mpg ~ disp + drat <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 10              mpg ~ hp + drat <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 11        mpg ~ cyl + disp + hp <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 12      mpg ~ cyl + disp + drat <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 13        mpg ~ cyl + hp + drat <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 14       mpg ~ disp + hp + drat <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 15 mpg ~ cyl + disp + hp + drat <S3: lm> <S3: summary.lm> <data.frame [5 × 4]>
</code>```

I did this piece-wise, keeping the models and the summaries, primarily for demonstration and in case you re-use lm (perhaps for predict). If you know you never need to keep the raw lm output, you could combine them into a single function call.

I believe you are asking for a data.frame of the coefficients, in which case:

```<code>x$summaries[[1]]
# Call:
# lm(formula = as.formula(.), data = dat)
# Residuals:
#     Min      1Q  Median      3Q     Max
# -4.9814 -2.1185  0.2217  1.0717  7.5186
# Coefficients:
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)  37.8846     2.0738   18.27  < 2e-16 ***
# cyl          -2.8758     0.3224   -8.92 6.11e-10 ***
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Residual standard error: 3.206 on 30 degrees of freedom
# Multiple R-squared:  0.7262,  Adjusted R-squared:  0.7171
# F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10
coef(x$summaries[[1]])
#             Estimate Std. Error   t value     Pr(>|t|)
# (Intercept) 37.88458  2.0738436 18.267808 8.369155e-18
# cyl         -2.87579  0.3224089 -8.919699 6.112687e-10
</code>```

Unfortunately, if you try to combine all of these coefficient summaries into a single data.frame, the row names are lost in dplyr::bind_rows:

```<code>bind_rows(map(x$summaries[1:2], ~ as.data.frame(coef(.))))
#      Estimate  Std. Error   t value     Pr(>|t|)
# 1 37.88457649 2.073843606 18.267808 8.369155e-18
# 2 -2.87579014 0.322408883 -8.919699 6.112687e-10
# 3 29.59985476 1.229719515 24.070411 3.576586e-21
# 4 -0.04121512 0.004711833 -8.747152 9.380327e-10
</code>```

One could always use base R, though you are lacking the "which model" component:

```<code>do.call(rbind.data.frame, map(x$summaries[1:2], ~ as.data.frame(coef(.))))
#                 Estimate  Std. Error   t value     Pr(>|t|)
# (Intercept)  37.88457649 2.073843606 18.267808 8.369155e-18
# cyl          -2.87579014 0.322408883 -8.919699 6.112687e-10
# (Intercept)1 29.59985476 1.229719515 24.070411 3.576586e-21
# disp         -0.04121512 0.004711833 -8.747152 9.380327e-1
</code>```

We can re-introduce that by using tibble::rownames_to_column in the original pipeline:

```<code>x <- data_frame(Formulas) %>%
  mutate(
    lms = map(Formulas, ~ lm(as.formula(.), data = dat)),
    summaries = map(lms, ~ summary(.)),
    coefs = map(summaries, ~ tibble::rownames_to_column(as.data.frame(coef(.))))
  )
select(x, Formulas, coefs) %>% unnest()
# # A tibble: 47 × 6
#            Formulas     rowname    Estimate `Std. Error` `t value`   `Pr(>|t|)`
#               <chr>       <chr>       <dbl>        <dbl>     <dbl>        <dbl>
# 1         mpg ~ cyl (Intercept) 37.88457649  2.073843606 18.267808 8.369155e-18
# 2         mpg ~ cyl         cyl -2.87579014  0.322408883 -8.919699 6.112687e-10
# 3        mpg ~ disp (Intercept) 29.59985476  1.229719515 24.070411 3.576586e-21
# 4        mpg ~ disp        disp -0.04121512  0.004711833 -8.747152 9.380327e-10
# 5          mpg ~ hp (Intercept) 30.09886054  1.633920950 18.421246 6.642736e-18
# 6          mpg ~ hp          hp -0.06822828  0.010119304 -6.742389 1.787835e-07
# 7        mpg ~ drat (Intercept) -7.52461844  5.476662574 -1.373942 1.796391e-01
# 8        mpg ~ drat        drat  7.67823260  1.506705108  5.096042 1.776240e-05
# 9  mpg ~ cyl + disp (Intercept) 34.66099474  2.547003876 13.608536 4.022869e-14
# 10 mpg ~ cyl + disp         cyl -1.58727681  0.711844271 -2.229809 3.366495e-02
# # ... with 37 more rows
</code>```

Title: Create tibble with all possible models

Body:
I have created a loop which creates all possible model combinations for a given data set. There are 63 possible models and I need to put them into a tibble with model number, subset of explanatory variables, model formula, and outcome (specifically r-squared value).

Cols <- names(finalprojectdata3)
Cols <- Cols[! Cols %in% 'debt']
n <- length(Cols)

id <- unlist(
  lapply(1:n,
         function(i)combn(1:n, i, simplify = FALSE)
         ),
  recursive = FALSE)

Formulas <- sapply(id, function(i)
  paste('debt~', paste(Cols[i],collapse="+")))

models <- lapply(Formulas, function(i)
summary(lm(as.formula(i), data = finalprojectdata3)))

models

The output is a the summaries for each model but I need it in a easy to read tibble.

Body:
It's not perfectly clear how you want your output, but here's a suggested path, following tidyr nested objects.

Make some fake data, following your methodology above:

dat <- mtcars[,1:5]
Cols <- names(dat)
Cols <- Cols[! Cols %in% 'mpg']
n <- length(Cols)

id <- unlist(
  lapply(1:n,
         function(i)combn(1:n, i, simplify = FALSE)
         ),
  recursive = FALSE)
str(id)
# List of 15
#  $ : int 1
#  $ : int 2
#  $ : int 3
#  $ : int 4
#  $ : int [1:2] 1 2
#  $ : int [1:2] 1 3
#  $ : int [1:2] 1 4
#  $ : int [1:2] 2 3
#  $ : int [1:2] 2 4
#  $ : int [1:2] 3 4
#  $ : int [1:3] 1 2 3
#  $ : int [1:3] 1 2 4
#  $ : int [1:3] 1 3 4
#  $ : int [1:3] 2 3 4
#  $ : int [1:4] 1 2 3 4

Formulas <- sapply(id, function(i)
  paste('mpg ~', paste(Cols[i], collapse=" + ")))
head(Formulas)
# [1] "mpg ~ cyl"        "mpg ~ disp"       "mpg ~ hp"         "mpg ~ drat"
# [5] "mpg ~ cyl + disp" "mpg ~ cyl + hp"

This is where I diverge from your path.

library(dplyr)
library(tidyr)
library(purrr)

x <- data_frame(Formulas) %>%
  mutate(
    lms = map(Formulas, ~ lm(as.formula(.), data = dat)),
    summaries = map(lms, ~ summary(.)),
    coefs = map(summaries, ~ as.data.frame(coef(.)))
  )
x
# # A tibble: 15 × 4
#                        Formulas      lms        summaries                coefs
#                           <chr>   <list>           <list>               <list>
# 1                     mpg ~ cyl <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 2                    mpg ~ disp <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 3                      mpg ~ hp <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 4                    mpg ~ drat <S3: lm> <S3: summary.lm> <data.frame [2 × 4]>
# 5              mpg ~ cyl + disp <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 6                mpg ~ cyl + hp <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 7              mpg ~ cyl + drat <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 8               mpg ~ disp + hp <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 9             mpg ~ disp + drat <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 10              mpg ~ hp + drat <S3: lm> <S3: summary.lm> <data.frame [3 × 4]>
# 11        mpg ~ cyl + disp + hp <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 12      mpg ~ cyl + disp + drat <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 13        mpg ~ cyl + hp + drat <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 14       mpg ~ disp + hp + drat <S3: lm> <S3: summary.lm> <data.frame [4 × 4]>
# 15 mpg ~ cyl + disp + hp + drat <S3: lm> <S3: summary.lm> <data.frame [5 × 4]>

I did this piece-wise, keeping the models and the summaries, primarily for demonstration and in case you re-use lm (perhaps for predict). If you know you never need to keep the raw lm output, you could combine them into a single function call.

I believe you are asking for a data.frame of the coefficients, in which case:

x$summaries[[1]]
# Call:
# lm(formula = as.formula(.), data = dat)
# Residuals:
#     Min      1Q  Median      3Q     Max
# -4.9814 -2.1185  0.2217  1.0717  7.5186
# Coefficients:
#             Estimate Std. Error t value Pr(>|t|)
# (Intercept)  37.8846     2.0738   18.27  < 2e-16 ***
# cyl          -2.8758     0.3224   -8.92 6.11e-10 ***
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
# Residual standard error: 3.206 on 30 degrees of freedom
# Multiple R-squared:  0.7262,  Adjusted R-squared:  0.7171
# F-statistic: 79.56 on 1 and 30 DF,  p-value: 6.113e-10
coef(x$summaries[[1]])
#             Estimate Std. Error   t value     Pr(>|t|)
# (Intercept) 37.88458  2.0738436 18.267808 8.369155e-18
# cyl         -2.87579  0.3224089 -8.919699 6.112687e-10

Unfortunately, if you try to combine all of these coefficient summaries into a single data.frame, the row names are lost in dplyr::bind_rows:

bind_rows(map(x$summaries[1:2], ~ as.data.frame(coef(.))))
#      Estimate  Std. Error   t value     Pr(>|t|)
# 1 37.88457649 2.073843606 18.267808 8.369155e-18
# 2 -2.87579014 0.322408883 -8.919699 6.112687e-10
# 3 29.59985476 1.229719515 24.070411 3.576586e-21
# 4 -0.04121512 0.004711833 -8.747152 9.380327e-10

One could always use base R, though you are lacking the "which model" component:

do.call(rbind.data.frame, map(x$summaries[1:2], ~ as.data.frame(coef(.))))
#                 Estimate  Std. Error   t value     Pr(>|t|)
# (Intercept)  37.88457649 2.073843606 18.267808 8.369155e-18
# cyl          -2.87579014 0.322408883 -8.919699 6.112687e-10
# (Intercept)1 29.59985476 1.229719515 24.070411 3.576586e-21
# disp         -0.04121512 0.004711833 -8.747152 9.380327e-1

We can re-introduce that by using tibble::rownames_to_column in the original pipeline:

x <- data_frame(Formulas) %>%
  mutate(
    lms = map(Formulas, ~ lm(as.formula(.), data = dat)),
    summaries = map(lms, ~ summary(.)),
    coefs = map(summaries, ~ tibble::rownames_to_column(as.data.frame(coef(.))))
  )
select(x, Formulas, coefs) %>% unnest()
# # A tibble: 47 × 6
#            Formulas     rowname    Estimate `Std. Error` `t value`   `Pr(>|t|)`
#               <chr>       <chr>       <dbl>        <dbl>     <dbl>        <dbl>
# 1         mpg ~ cyl (Intercept) 37.88457649  2.073843606 18.267808 8.369155e-18
# 2         mpg ~ cyl         cyl -2.87579014  0.322408883 -8.919699 6.112687e-10
# 3        mpg ~ disp (Intercept) 29.59985476  1.229719515 24.070411 3.576586e-21
# 4        mpg ~ disp        disp -0.04121512  0.004711833 -8.747152 9.380327e-10
# 5          mpg ~ hp (Intercept) 30.09886054  1.633920950 18.421246 6.642736e-18
# 6          mpg ~ hp          hp -0.06822828  0.010119304 -6.742389 1.787835e-07
# 7        mpg ~ drat (Intercept) -7.52461844  5.476662574 -1.373942 1.796391e-01
# 8        mpg ~ drat        drat  7.67823260  1.506705108  5.096042 1.776240e-05
# 9  mpg ~ cyl + disp (Intercept) 34.66099474  2.547003876 13.608536 4.022869e-14
# 10 mpg ~ cyl + disp         cyl -1.58727681  0.711844271 -2.229809 3.366495e-02
# # ... with 37 more rows


问:
Replacing all words except one - regex perl
i try to have a regular expresion which will change "dir1/dir2/" to "dir1/dir3/"
only if dir2 is not tmp, and if it is tmp ,I want it not to change and stay "dir1/tmp".

I think I need a lookahead regex but I cant manage.

答: You could use if statement before applying the s////.... check using m// if tmp is not there and then replace.</p>


问:
Networkx doesn't parse all the network edges from file
I have a file with 3 columns. The first and second column show the edges and the third column is the sign(weight) of the edge. The file has 450 lines, so i thought that i must have 450 edges.
Im parsing the edges with networkx with the following code:

```<code>G = nx.read_edgelist('myfile.txt', delimiter='\t', nodetype=int, data=(('sign', int),))
</code>```

and the i print the number of graph edges with the following code:

```<code>n1 = nx.number_of_nodes(G)
n2 = nx.number_of_edges(G)
print("nodes: ", n1)
print("edges: ", n2)
</code>```

and the result is less edges than 450. Why im getting this result? Is there any problem with parsing?

答:
It's hard to be certain because you don't provide a Minimal, Complete, and Verifiable example, but I think the most likely explanation is that the same edge is added twice (perhaps with the node order switched).

By default networkx uses an undirected graph.  So a u-v edge and a v-u edge are the same thing.  If you try to add an already existing edge, it simply does nothing. Similarly edges from a node to itself are not allowed.  To use some other graph type, you need to set the create_using option for read_edgelist.

Body:
I have a file with 3 columns. The first and second column show the edges and the third column is the sign(weight) of the edge. The file has 450 lines, so i thought that i must have 450 edges.
Im parsing the edges with networkx with the following code:

G = nx.read_edgelist('myfile.txt', delimiter='\t', nodetype=int, data=(('sign', int),))

and the i print the number of graph edges with the following code:

n1 = nx.number_of_nodes(G)
n2 = nx.number_of_edges(G)
print("nodes: ", n1)
print("edges: ", n2)

and the result is less edges than 450. Why im getting this result? Is there any problem with parsing?


问:
r - subsetting dataframe creates factors
I have a huge data frame (call it huge) I would like to split up in two by row number. Though, I notice that the way I'd do it makes the resulting subsets large factors instead of data frames.

```<code>list1 <- huge[c(1:8175),]
list2 <- huge[c(8176:nrow(huge),]

class(list1)
[1] "factor"
</code>```

Can someone explain to me why it is like that, and how do I prevent that?

答:
It is likely that you subset a one-column data frame. Considering the following example.

```<code># Create an example data frame
dt <- data.frame(a = 1:5, b = letters[1:5])
dt

#   a b
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d
# 5 5 e

str(dt)

# 'data.frame': 5 obs. of  2 variables:
#  $ a: int  1 2 3 4 5
#  $ b: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5

# Subset the data frame
list1 <- dt[1:2, ]
list2 <- dt[3:nrow(dt), ]

class(list1)
# [1] "data.frame"
</code>```

The code to subset dt works well. However, when I created a one-column data frame from dt and subset it, you can see that the output automatically becomes a vector.

```<code># Create a one-column data frame
dt2 <- dt[, 2, drop = FALSE]

# Subset the data frame
list3 <- dt2[1:2, ]
list4 <- dt2[3:nrow(dt2), ]

class(list3)
# [1] "factor"
list3
# [1] a b
# Levels: a b c d e
</code>```

The solution would be add drop = FALSE when subsetting the data frame to keep the output as a data frame.

```<code># Subset the data frame
list5 <- dt2[1:2, , drop = FALSE]
class(list5)
# [1] "data.frame"
</code>```

Body:
I have a huge data frame (call it huge) I would like to split up in two by row number. Though, I notice that the way I'd do it makes the resulting subsets large factors instead of data frames.

list1 <- huge[c(1:8175),]
list2 <- huge[c(8176:nrow(huge),]

class(list1)
[1] "factor"

Can someone explain to me why it is like that, and how do I prevent that?

Body:
It is likely that you subset a one-column data frame. Considering the following example.

# Create an example data frame
dt <- data.frame(a = 1:5, b = letters[1:5])
dt

#   a b
# 1 1 a
# 2 2 b
# 3 3 c
# 4 4 d
# 5 5 e

str(dt)

# 'data.frame': 5 obs. of  2 variables:
#  $ a: int  1 2 3 4 5
#  $ b: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5

# Subset the data frame
list1 <- dt[1:2, ]
list2 <- dt[3:nrow(dt), ]

class(list1)
# [1] "data.frame"

The code to subset dt works well. However, when I created a one-column data frame from dt and subset it, you can see that the output automatically becomes a vector.

# Create a one-column data frame
dt2 <- dt[, 2, drop = FALSE]

# Subset the data frame
list3 <- dt2[1:2, ]
list4 <- dt2[3:nrow(dt2), ]

class(list3)
# [1] "factor"
list3
# [1] a b
# Levels: a b c d e

The solution would be add drop = FALSE when subsetting the data frame to keep the output as a data frame.

# Subset the data frame
list5 <- dt2[1:2, , drop = FALSE]
class(list5)
# [1] "data.frame"


问:
ASP.NET Core Posting Array Object JSON
I'm trying to post an array of Object in my view to my controller but params are null i saw that for just a simple object I need to put [FromBody] in my controller action.

Here is my JSON:

{
  "monJour": [
    {
      "openTime": "04:00",
      "closedTime": "21:30",
      "id": "0"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "1"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "2"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "3"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "4"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "5"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "6"
    }
  ]
}
```

<p>Here is my Ajax Request :</p>

```function SendAllDay() {
    var mesJours = {};
    var monJour = [];
    mesJours.monJour = monJour;

    var senddata ='';

    $('div[id^="Conteneur"]').each(function () {
        var idDiv = $(this).attr("id");
        var jour = idDiv.substr(9, idDiv.length - 9);
        var opentps = $("#O" + jour).val();
        var closetps = $("#C" + jour).val();
        var monid = $("#id" + jour).val();

        monJour = {
            openTime: opentps,
            closedTime: closetps,
            id: monid
        }

        mesJours.monJour.push(monJour);
    });

    $.ajax({
        url: '@Url.Action("ReceiveAll")',
        dataType: 'json',
        type: 'POST',
        //data: JSON.stringify(monJours),
        data: JSON.stringify(mesJours),
        contentType:'application/json',
        success: function (response) {
            console.log('ok');
            //window.location.reload();
        },
        error: function (response) {
            console.log('error');
            //alert(response)
            //window.location.reload();
        }
    });
}
```

<p>Here is my Action:</p>

```[HttpPost]
public void ReceiveAll([FromBody]ReceiveTime [] rt) { }
```

<p>Here is my Class:</p>

```public class ReceiveTime
{
    public string openTime { get; set; }
    public string closedTime { get; set; }
    public string id { get; set; }
}
```

Any help is appreciated :)

答:
Instead of using ReceiveTime[] rt, it might be better to model the data according to the same structure that you POST. For example, you could create a class that looks like this:

```<code>public class MesJours
{
    public ReceiveTime[] MonJour { get; set; }
}
</code>```

I don't know if MesJours makes sense as a class name (I don't speak French), but the idea is still clear - You can name the class whatever you like.

Given this, you could update your controller like this:

```<code>[HttpPost]
public void ReceiveAll([FromBody] MesJours mesJours)
{
    // Access monJour via mesJours.
    var rt = mesJours.MonJour;
}
</code>```

This would satisfy the ASP.NET MVC Model Binder and should give you the data you've POSTed. This also has the added benefit of easily accommodating any additional properties you might want to POST.

Title: ASP.NET Core Posting Array Object JSON

Body:
I'm trying to post an array of Object in my view to my controller but params are null i saw that for just a simple object I need to put [FromBody] in my controller action.

Here is my JSON:

{
  "monJour": [
    {
      "openTime": "04:00",
      "closedTime": "21:30",
      "id": "0"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "1"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "2"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "3"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "4"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "5"
    },
    {
      "openTime": "08:00",
      "closedTime": "17:30",
      "id": "6"
    }
  ]
}

Here is my Ajax Request :

function SendAllDay() {
    var mesJours = {};
    var monJour = [];
    mesJours.monJour = monJour;

    var senddata ='';

    $('div[id^="Conteneur"]').each(function () {
        var idDiv = $(this).attr("id");
        var jour = idDiv.substr(9, idDiv.length - 9);
        var opentps = $("#O" + jour).val();
        var closetps = $("#C" + jour).val();
        var monid = $("#id" + jour).val();

        monJour = {
            openTime: opentps,
            closedTime: closetps,
            id: monid
        }

        mesJours.monJour.push(monJour);
    });

    $.ajax({
        url: '@Url.Action("ReceiveAll")',
        dataType: 'json',
        type: 'POST',
        //data: JSON.stringify(monJours),
        data: JSON.stringify(mesJours),
        contentType:'application/json',
        success: function (response) {
            console.log('ok');
            //window.location.reload();
        },
        error: function (response) {
            console.log('error');
            //alert(response)
            //window.location.reload();
        }
    });
}

Here is my Action:

[HttpPost]
public void ReceiveAll([FromBody]ReceiveTime [] rt) { }

Here is my Class:

public class ReceiveTime
{
    public string openTime { get; set; }
    public string closedTime { get; set; }
    public string id { get; set; }
}

Any help is appreciated :)

Body:
Instead of using ReceiveTime[] rt, it might be better to model the data according to the same structure that you POST. For example, you could create a class that looks like this:

public class MesJours
{
    public ReceiveTime[] MonJour { get; set; }
}

I don't know if MesJours makes sense as a class name (I don't speak French), but the idea is still clear - You can name the class whatever you like.

Given this, you could update your controller like this:

[HttpPost]
public void ReceiveAll([FromBody] MesJours mesJours)
{
    // Access monJour via mesJours.
    var rt = mesJours.MonJour;
}

This would satisfy the ASP.NET MVC Model Binder and should give you the data you've POSTed. This also has the added benefit of easily accommodating any additional properties you might want to POST.


问:
How can I find my Apple Developer Team id and Team Agent Apple ID?
I am trying to transfer an app.  I am having troubles finding my team agent apple id and my team id.  I have found it before and I have searched for 30 min without any luck now that i need it.

The person trying to transfer the app to me gets to view in this image and I don't know where to find this info.

答:
If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.

Applications -> Utilities -> Keychain Access.

Under the 'login' Keychain, go into the 'Certificates' category.

Scroll to find your development or distribution certificate. They will read:

iPhone Distribution: Team Name (certificate id)

or

iPhone Developer: Team Name (certificate id)

Simply double-click on the item, and the

"Organizational Unit"

is the "Team ID"

Note that this is the only way to find your

"Personal team" ID

You can not find the "Personal team" ID on the Apple web interface.

For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.