问:
Unix - Writing a line from a file to a char* var, then saving it in integers
Question: I have a file, called ATM1, and it is filled with strings, for example(this is the format for everyline): O ilan 123 456 Which means - O stands for open account, ilan is username, 123 is password, and 456 is initial amount in my bank account.

After opening the file, iterating with a while loop while(((ret_in = read (in1, &buffer1, BUF_SIZE)) > 0)), I want to get the line's details and store them in the appropriate variables. for example the first char will be stored in a variable called letter or msg[0] whatever is more convenient for you, then there is a space and then username, then password, and optional stuff like balance, or maybe another account id (for transfer money purposes).

Every ATM machine should be a thread, it has its own file, for now it is just one file "ATM1" because I want it to work in the beginning for at least one file.

Current Problem:
Segmentation fault in the OpenFile function. I'm still not able to store the line's values in the appropriate variables and called the switch statement for opening account, etc.

Here is the current code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>

#define BUF_SIZE  8192
sem_t log;

void OpenNewAccount(int acc,int pw,int amount){

}

struct Account{
    int  number;
    int  password;
    int  balance;
};

//*Opens file for every ATM
void* openFile(void* args){
  //To add later: while(true) { sleep(100); do next file's line }
  //Open file
  int* aargs = args;

  int acc;
  int pw;
  int amount;
  int target_acc;

  int ret_in, in1,file;
  char buffer1[BUF_SIZE];

  int count = 0;
  int i = 0;
  char fn[5] = "ATM1";

  char* msg;
 file = open(fn,O_RDONLY|O_CREAT,0644);

while(((ret_in = read (file, &buffer1, BUF_SIZE)) > 0))
  {
   for(i; i<ret_in; i++)
    {
     if(buffer1[i]!='\n')
      msg[i] = buffer1[i];
    /* else{
      if(count == 0){
       count++;
       break;
      }
      else
      {
       count = i + 1;
       break;
      }
     }
*/
    }
}
    printf("%s", msg); //TEST: check msg
    //Here we translate the message
/*
  //Here we call the relevant function of the msg
   switch (msg[count - 1]){
   case 'O': OpenNewAccount(acc,pw,amount);
   case 'D': Deposit(acc,pw,amount);
   case 'W': Withdrawl(acc,pw,amount);
   case 'B': Balance(acc,pw);
   case 'Q': CloseAccount(acc,pw);
   case 'T': Transfer(acc,pw,target_acc,amount);

 }
*/

}

//*finish: Update log.txt and lock it
void WriteLog(char* msg){
 int file;
 char logName[8] = "log.txt";
 sem_wait(&log);
 file = open(logName,O_WRONLY|O_CREAT,0644);
 strcat(msg,"\n");
 write(file,&msg,strlen(msg));
 close(file);
 sem_post(&log);
}

int main(void)
{
int i,n,a;
sem_init(&log, 0, 1);
printf("Please enter the number of ATMs you want: \n");
scanf("%d", &n);

int bank; //bank with n ATMs
pthread_t thread[3];
printf("test\n"); //TEST: check msg
for(i = 0; i < 3; i++)
pthread_create ( &thread[i] , NULL , openFile , &i);

scanf("%d",&a);
}
</code>```

答:
Well, for one, you use i as an array index without ever initializing it. That could easily cause a SEGFAULT. </p>

<p>But honestly this whole thing is a mess. Your function names don't do what they say they do. You appear to be thrashing around almost randomly. I suggest you rethink your design from the beginning. Go through the "top down" design process you should have learned and figure out how to factor your code. Only then should you proceed. </p>

Body:
Question: I have a file, called ATM1, and it is filled with strings, for example(this is the format for everyline): O ilan 123 456 Which means - O stands for open account, ilan is username, 123 is password, and 456 is initial amount in my bank account.

After opening the file, iterating with a while loop while(((ret_in = read (in1, &buffer1, BUF_SIZE)) > 0)), I want to get the line's details and store them in the appropriate variables. for example the first char will be stored in a variable called letter or msg[0] whatever is more convenient for you, then there is a space and then username, then password, and optional stuff like balance, or maybe another account id (for transfer money purposes).

Every ATM machine should be a thread, it has its own file, for now it is just one file "ATM1" because I want it to work in the beginning for at least one file.

Current Problem:
Segmentation fault in the OpenFile function. I'm still not able to store the line's values in the appropriate variables and called the switch statement for opening account, etc.

Here is the current code:

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>

#define BUF_SIZE  8192
sem_t log;

void OpenNewAccount(int acc,int pw,int amount){

}

struct Account{
    int  number;
    int  password;
    int  balance;
};

//*Opens file for every ATM
void* openFile(void* args){
  //To add later: while(true) { sleep(100); do next file's line }
  //Open file
  int* aargs = args;

  int acc;
  int pw;
  int amount;
  int target_acc;

  int ret_in, in1,file;
  char buffer1[BUF_SIZE];

  int count = 0;
  int i = 0;
  char fn[5] = "ATM1";

  char* msg;
 file = open(fn,O_RDONLY|O_CREAT,0644);

while(((ret_in = read (file, &buffer1, BUF_SIZE)) > 0))
  {
   for(i; i<ret_in; i++)
    {
     if(buffer1[i]!='\n')
      msg[i] = buffer1[i];
    /* else{
      if(count == 0){
       count++;
       break;
      }
      else
      {
       count = i + 1;
       break;
      }
     }
*/
    }
}
    printf("%s", msg); //TEST: check msg
    //Here we translate the message
/*
  //Here we call the relevant function of the msg
   switch (msg[count - 1]){
   case 'O': OpenNewAccount(acc,pw,amount);
   case 'D': Deposit(acc,pw,amount);
   case 'W': Withdrawl(acc,pw,amount);
   case 'B': Balance(acc,pw);
   case 'Q': CloseAccount(acc,pw);
   case 'T': Transfer(acc,pw,target_acc,amount);

 }
*/

}

//*finish: Update log.txt and lock it
void WriteLog(char* msg){
 int file;
 char logName[8] = "log.txt";
 sem_wait(&log);
 file = open(logName,O_WRONLY|O_CREAT,0644);
 strcat(msg,"\n");
 write(file,&msg,strlen(msg));
 close(file);
 sem_post(&log);
}

int main(void)
{
int i,n,a;
sem_init(&log, 0, 1);
printf("Please enter the number of ATMs you want: \n");
scanf("%d", &n);

int bank; //bank with n ATMs
pthread_t thread[3];
printf("test\n"); //TEST: check msg
for(i = 0; i < 3; i++)
pthread_create ( &thread[i] , NULL , openFile , &i);

scanf("%d",&a);
}

Body:
Well, for one, you use i as an array index without ever initializing it. That could easily cause a SEGFAULT.

But honestly this whole thing is a mess. Your function names don't do what they say they do. You appear to be thrashing around almost randomly. I suggest you rethink your design from the beginning. Go through the "top down" design process you should have learned and figure out how to factor your code. Only then should you proceed.


来源: stackexchange

问:
unable to resolve getter method
I'm learning java as a beginner and I'm trying to create a program that calculates your future age as an exercise.

I have the following issue:

Error:(14, 64) java: cannot find symbol
symbol:   method getYear()
location: class ageProgram

I can't seem to get my getter methods eventho they are declared public.

ageProgram.java:

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

public class ageProgram {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter your birth year");
        int yearBirth = keyboard.nextInt();
        System.out.println("enter a (future) year");
        int yearTo = keyboard.nextInt();

        ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);

        if (yearBirth > yearTo) {
            System.out.println("You will be born in %s years", getYear());
        } else {
            System.out.println("You are %s years old", getYear());
        }
    }
}
</code>```

ageCalculator.java:

```<code>public class ageCalculator {
        public ageCalculator(int yearBirth, int yearTo) {
            if (yearBirth > yearTo) {
                int year = (yearBirth - yearTo);
                year = year.toString();
            } else {
                int year = (yearTo - yearBirth);
                year = year.toString();
            }
        }
        public String getYear() {
            return year;
        }
        }
</code>```

I'm not sure what I am doing wrong... I tried to check for solutions at similar / other questions on stackoverflow but nothing seems to work.

Thanks for the help!

答:
try this

ageProgram.java

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

public class ageProgram {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter your birth year");
        int yearBirth = keyboard.nextInt();
        System.out.println("enter a (future) year");
        int yearTo = keyboard.nextInt();

        ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);

        if (yearBirth > yearTo) {
            System.out.format("You will be born in %s years", agecalculator.getYear());
        } else {
            System.out.format("You are %s years old", agecalculator.getYear());
        }
    }
}
</code>```

ageCalculator.java

```<code>public class ageCalculator {
    String yearText;
    public ageCalculator(int yearBirth, int yearTo) {
        if (yearBirth > yearTo) {
            int year = (yearBirth - yearTo);
            yearText = String.valueOf(year);
        } else {
            int year = (yearTo - yearBirth);
            yearText = String.valueOf(year);
        }
    }
    public String getYear() {
        return yearText;
    }
}
</code>```

if you don't understand it, i can explain

edit: i didn't get it at first but the above answer is also correct. you should use agecalculater.getYear() to call the method
edit: you should start a class name with a capital letter. and you can use

```<code>yearText = String.valueOf(yearBirth - yearTo);
</code>```

instead of

```<code>int year = (yearTo - yearBirth);
yearText = String.valueOf(year);
</code>```

ContentLicense: CC BY-SA 3.0

Title: unable to resolve getter method

Body:
I'm learning java as a beginner and I'm trying to create a program that calculates your future age as an exercise.

I have the following issue:

Error:(14, 64) java: cannot find symbol
symbol:   method getYear()
location: class ageProgram

I can't seem to get my getter methods eventho they are declared public.

ageProgram.java:

import java.util.Scanner;

public class ageProgram {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter your birth year");
        int yearBirth = keyboard.nextInt();
        System.out.println("enter a (future) year");
        int yearTo = keyboard.nextInt();

        ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);

        if (yearBirth > yearTo) {
            System.out.println("You will be born in %s years", getYear());
        } else {
            System.out.println("You are %s years old", getYear());
        }
    }
}

ageCalculator.java:

public class ageCalculator {
        public ageCalculator(int yearBirth, int yearTo) {
            if (yearBirth > yearTo) {
                int year = (yearBirth - yearTo);
                year = year.toString();
            } else {
                int year = (yearTo - yearBirth);
                year = year.toString();
            }
        }
        public String getYear() {
            return year;
        }
        }

I'm not sure what I am doing wrong... I tried to check for solutions at similar / other questions on stackoverflow but nothing seems to work.

Thanks for the help!

Body:
try this

ageProgram.java

import java.util.Scanner;

public class ageProgram {
    public static void main(String[]args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("enter your birth year");
        int yearBirth = keyboard.nextInt();
        System.out.println("enter a (future) year");
        int yearTo = keyboard.nextInt();

        ageCalculator agecalculator = new ageCalculator(yearBirth, yearTo);

        if (yearBirth > yearTo) {
            System.out.format("You will be born in %s years", agecalculator.getYear());
        } else {
            System.out.format("You are %s years old", agecalculator.getYear());
        }
    }
}

ageCalculator.java

public class ageCalculator {
    String yearText;
    public ageCalculator(int yearBirth, int yearTo) {
        if (yearBirth > yearTo) {
            int year = (yearBirth - yearTo);
            yearText = String.valueOf(year);
        } else {
            int year = (yearTo - yearBirth);
            yearText = String.valueOf(year);
        }
    }
    public String getYear() {
        return yearText;
    }
}

if you don't understand it, i can explain

edit: i didn't get it at first but the above answer is also correct. you should use agecalculater.getYear() to call the method
edit: you should start a class name with a capital letter. and you can use

yearText = String.valueOf(yearBirth - yearTo);

instead of

int year = (yearTo - yearBirth);
yearText = String.valueOf(year);


问:
Angular 2 Reactive Form Error - TypeError: this.form.get is not a function
I am using Angular 2 RC 5 with following:

esnext

webpack

reactive form

I have built a simple test form and I am getting following error in the browser console:

```<code>zone.js:461Unhandled Promise rejection: EXCEPTION: Error in ./FormComponent class FormComponent - inline template:4:25
ORIGINAL EXCEPTION: TypeError: this.form.get is not a function
ORIGINAL STACKTRACE:
TypeError: this.form.get is not a function
    at FormGroupDirective.addControl (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:35832:31)
    at FormControlName.ngOnChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:35650:33)
    at DebugAppView._View_FormComponent0.detectChangesInternal (FormComponent.ngfactory.js:230:55)
    at DebugAppView.AppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18565:15)
    at DebugAppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18671:45)
    at DebugAppView.AppView.detectViewChildrenChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18591:20)
    at DebugAppView._View_FormComponent_Host0.detectChangesInternal (FormComponent.ngfactory.js:31:8)
    at DebugAppView.AppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18565:15)
    at DebugAppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18671:45)
    at ViewRef_.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:16397:66)
</code>```

Here is my code:

form.component.js

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

import template from './form.component.html'

@Component({
    selector: 'load-form',
    template: template
})
export class FormComponent {
    carriers = [];
    stations = [];
    loadForm = {};

    constructor(formBuilder : FormBuilder) {
        this.formBuilder = formBuilder;

        this.loadForm = this.formBuilder.group({
            carrierId: '',
            carrierStationId: ''
        });

        console.log("constructor")
    }

    ngOnInit() {
        console.log("ngOnInit")
    }

    saveLoad(data) {
        console.log(data);
    }
}
</code>```

form.component.html

```<code><form [formGroup]="loadForm" (ngSubmit)="saveLoad(loadForm.value)">
  <div>
    <label>Carrier</label>
    <div>
      <input type="text" formControlName="carrierId">
    </div>
  </div>

  <div>
    <label>Station</label>
    <div>
      <input type="text" formControlName="carrierStationId">
    </div>
  </div>

  <div>
    <button type="submit" >[+] Add Load</button>
  </div>
</form>
</code>```

Has anyone know what is going to here? I stuck on this for days now.

The full code can be found here:

https://github.com/tahseen/angular2-reactive-form-webpack-esnext

And the live example with error can be seen here:

https://tahseen.github.io/angular2-reactive-form-webpack-esnext/

答:
Right. I encountered a similar problem, however, with respect the latest of Angular 2 at this point of writing, I placed the routes in a separate typescript file. And then, in the app.module.ts added the following line:

RouterModule.forRoot(APP_ROUTES) to the list of imports @NgModules, where APP_ROUTES is the array of path routes(imported). And note that you have to place the aforementioned line before the ReactiveFormsModule import.

Body:
I am using Angular 2 RC 5 with following:

esnext

webpack

reactive form

I have built a simple test form and I am getting following error in the browser console:

zone.js:461Unhandled Promise rejection: EXCEPTION: Error in ./FormComponent class FormComponent - inline template:4:25
ORIGINAL EXCEPTION: TypeError: this.form.get is not a function
ORIGINAL STACKTRACE:
TypeError: this.form.get is not a function
    at FormGroupDirective.addControl (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:35832:31)
    at FormControlName.ngOnChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:35650:33)
    at DebugAppView._View_FormComponent0.detectChangesInternal (FormComponent.ngfactory.js:230:55)
    at DebugAppView.AppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18565:15)
    at DebugAppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18671:45)
    at DebugAppView.AppView.detectViewChildrenChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18591:20)
    at DebugAppView._View_FormComponent_Host0.detectChangesInternal (FormComponent.ngfactory.js:31:8)
    at DebugAppView.AppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18565:15)
    at DebugAppView.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:18671:45)
    at ViewRef_.detectChanges (https://tahseen.github.io/angular2-reactive-form-webpack-esnext/loads.bundle.js:16397:66)

Here is my code:

form.component.js

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

import template from './form.component.html'

@Component({
    selector: 'load-form',
    template: template
})
export class FormComponent {
    carriers = [];
    stations = [];
    loadForm = {};

    constructor(formBuilder : FormBuilder) {
        this.formBuilder = formBuilder;

        this.loadForm = this.formBuilder.group({
            carrierId: '',
            carrierStationId: ''
        });

        console.log("constructor")
    }

    ngOnInit() {
        console.log("ngOnInit")
    }

    saveLoad(data) {
        console.log(data);
    }
}

form.component.html

<form [formGroup]="loadForm" (ngSubmit)="saveLoad(loadForm.value)">

    Carrier

      <input type="text" formControlName="carrierId">

    Station

      <input type="text" formControlName="carrierStationId">

    <button type="submit" >[+] Add Load</button>

</form>

Has anyone know what is going to here? I stuck on this for days now.

The full code can be found here:

https://github.com/tahseen/angular2-reactive-form-webpack-esnext

And the live example with error can be seen here:

https://tahseen.github.io/angular2-reactive-form-webpack-esnext/


问:
Selenium - How to import all settings from an existing Firefox profile
Why am I doing this:

I need to automate a website that requires client-side SSL certificates. I understand this to be an option which cannot be specified using fp.set_preference(). I am not in control of the server I am connecting to thus I cannot change the security setup.

What have I tried

I have created a separate Firefox profile which has the required 'client-side password protected SSL certificates' set up, select one certificate automaticaly and some manual proxy settings (SOCKS 5). After much googling I have set my code as follows:

```<code>from selenium import webdriver
url = 'https://www.paininneck.co.uk'
fp = webdriver.FirefoxProfile(r"""C:\Users\
<user>\AppData\Local\Mozilla\Firefox\Profiles\<Firefox>""")
driver = webdriver.Firefox(fp)
driver.get(url)
</code>```

The Problem:

The browser does open, however, it is still using the default profile. None of the settings I have changed in the other profile has copied across. The profile specified in my code is still working with selecting it through the Firefox UI.

I am hoping I missed something simple and all this time googling has not been in vain! I am reluctant to change to default settings, however after tweaking the default profile to see if the settings would copy over it is apparent that they don't and Selenium is making a clean copy each time.

Kind regards

Rich

Versions:

```<code>Python==3.6.1,
Selenium==3.4.3,
Firefox==53
gecko driver==v0.16.1
OS==Windows(Its for work dont judge me!)
</code>```

答:
Using Selenium 3.4.x, Python 3.6.1 along with geckodriver v0.16.1 & Mozilla Firefox 53.0, you can use the existing Firefox profile through the following steps:

Locate the Firefox Profile directory on your windows box. For e.g. my Firefox Profile "debanjan" was located at C:\\Users\\AtechM_03\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles by the name w8iy627a.debanjan.

Next, you have to specify the absolute path of the Firefox Profile directory when you initiate the webdriver.

Here is the working code which opens an existing Firefox Profile 'debanjan' on my Windows machine:

It is to be noted that the current Selenium-Python binding is unstable with geckodriver and looks to be Architecture specific. You can find the github discussion and merge here. So you may additionally need to pass the absolute path of the firefox binary while initializing the webdriver

```<code>from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

profile = webdriver.FirefoxProfile('C:\\Users\\AtechM_03\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\w8iy627a.debanjan')
binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')

driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
url = 'https://www.paininneck.co.uk'
driver.get(url)
</code>```

Body:
Why am I doing this:

I need to automate a website that requires client-side SSL certificates. I understand this to be an option which cannot be specified using fp.set_preference(). I am not in control of the server I am connecting to thus I cannot change the security setup.

What have I tried

I have created a separate Firefox profile which has the required 'client-side password protected SSL certificates' set up, select one certificate automaticaly and some manual proxy settings (SOCKS 5). After much googling I have set my code as follows:

from selenium import webdriver
url = 'https://www.paininneck.co.uk'
fp = webdriver.FirefoxProfile(r"""C:\Users\
<user>\AppData\Local\Mozilla\Firefox\Profiles\<Firefox>""")
driver = webdriver.Firefox(fp)
driver.get(url)

The Problem:

The browser does open, however, it is still using the default profile. None of the settings I have changed in the other profile has copied across. The profile specified in my code is still working with selecting it through the Firefox UI.

I am hoping I missed something simple and all this time googling has not been in vain! I am reluctant to change to default settings, however after tweaking the default profile to see if the settings would copy over it is apparent that they don't and Selenium is making a clean copy each time.

Kind regards

Rich

Versions:

Python==3.6.1,
Selenium==3.4.3,
Firefox==53
gecko driver==v0.16.1
OS==Windows(Its for work dont judge me!)

Body:
Using Selenium 3.4.x, Python 3.6.1 along with geckodriver v0.16.1 & Mozilla Firefox 53.0, you can use the existing Firefox profile through the following steps:

Locate the Firefox Profile directory on your windows box. For e.g. my Firefox Profile "debanjan" was located at C:\\Users\\AtechM_03\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles by the name w8iy627a.debanjan.

Next, you have to specify the absolute path of the Firefox Profile directory when you initiate the webdriver.

Here is the working code which opens an existing Firefox Profile 'debanjan' on my Windows machine:

It is to be noted that the current Selenium-Python binding is unstable with geckodriver and looks to be Architecture specific. You can find the github discussion and merge here. So you may additionally need to pass the absolute path of the firefox binary while initializing the webdriver

from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

profile = webdriver.FirefoxProfile('C:\\Users\\AtechM_03\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\w8iy627a.debanjan')
binary = FirefoxBinary('C:\\Program Files\\Mozilla Firefox\\firefox.exe')

driver = webdriver.Firefox(firefox_profile=profile, firefox_binary=binary, executable_path="C:\\Utility\\BrowserDrivers\\geckodriver.exe")
url = 'https://www.paininneck.co.uk'
driver.get(url)

ContentLicense: CC BY-SA 4.0


问:
dbml generates ISingleResult<object> from my stored procedure when I want a collection
I've created a stored procedure which I've dragged on to my dbml file expecting it to create a method that will return a collection of objects. However it only gives me a method returning an ISingleResult.

My stored proc creates a table variable, populates it with data and then selects all from that table.

Any idea what I'm doing wrong? I can post code if that would be helpful.

Edit. Here's the generated code from the dbml

```<code>[Function(Name="dbo.gr_RecentActions")]
public ISingleResult<Action> gr_RecentActions([Parameter(Name="UserID", DbType="UniqueIdentifier")] System.Nullable<System.Guid> userID)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), userID);
    return ((ISingleResult<Action>)(result.ReturnValue));
}
</code>```

Here's a section of the stored procedure. It's pretty much this straightforward.

```<code>    ALTER PROCEDURE [dbo].[gr_RecentActions]
@UserID UNIQUEIDENTIFIER
AS
BEGIN

DECLARE @RecentActions AS TABLE (UserId UNIQUEIDENTIFIER, UserID1 UNIQUEIDENTIFIER, Name VARCHAR(500), GiftID UNIQUEIDENTIFIER, ActionType VARCHAR(20), ActionDate DATETIME)

DECLARE @Friends AS Table (Userid UNIQUEIDENTIFIER)

INSERT INTO @Friends (Userid)
    (SUBQUERY...)

INSERT INTO @RecentActions (UserId, UserId1, Name, GiftID, ActionType, ActionDate)
    SELECT userid, NULL, Name, g.GiftId, 'GiftAdded', DateCreated FROM Gift g
    WHERE UserId IN
        (select UserId from @Friends)

/* SNIP.... SIMILAR CODE TO ABOVE */

SELECT * FROM @RecentActions ORDER BY ActionDate DESC
</code>```

答:
ISingleResult<T> inherits IEnumerable<T>. It is a collection.

It's a single result as opposed to a multiple result, as in multiple result sets:

```<code>SELECT *
FROM Table1

SELECT *
FROM Table2
</code>```

A stored procedure like that would not return ISingleResult<T>.

ContentLicense: CC BY-SA 2.5

Body:
I've created a stored procedure which I've dragged on to my dbml file expecting it to create a method that will return a collection of objects. However it only gives me a method returning an ISingleResult.

My stored proc creates a table variable, populates it with data and then selects all from that table.

Any idea what I'm doing wrong? I can post code if that would be helpful.

Edit. Here's the generated code from the dbml

[Function(Name="dbo.gr_RecentActions")]
public ISingleResult<Action> gr_RecentActions([Parameter(Name="UserID", DbType="UniqueIdentifier")] System.Nullable<System.Guid> userID)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), userID);
    return ((ISingleResult<Action>)(result.ReturnValue));
}

Here's a section of the stored procedure. It's pretty much this straightforward.

    ALTER PROCEDURE [dbo].[gr_RecentActions]
@UserID UNIQUEIDENTIFIER
AS
BEGIN

DECLARE @RecentActions AS TABLE (UserId UNIQUEIDENTIFIER, UserID1 UNIQUEIDENTIFIER, Name VARCHAR(500), GiftID UNIQUEIDENTIFIER, ActionType VARCHAR(20), ActionDate DATETIME)

DECLARE @Friends AS Table (Userid UNIQUEIDENTIFIER)

INSERT INTO @Friends (Userid)
    (SUBQUERY...)

INSERT INTO @RecentActions (UserId, UserId1, Name, GiftID, ActionType, ActionDate)
    SELECT userid, NULL, Name, g.GiftId, 'GiftAdded', DateCreated FROM Gift g
    WHERE UserId IN
        (select UserId from @Friends)

/* SNIP.... SIMILAR CODE TO ABOVE */

SELECT * FROM @RecentActions ORDER BY ActionDate DESC

Body:
ISingleResult<T> inherits IEnumerable<T>. It is a collection.

It's a single result as opposed to a multiple result, as in multiple result sets:

SELECT *
FROM Table1

SELECT *
FROM Table2

A stored procedure like that would not return ISingleResult<T>.


问:
Powerbuilder 11.5 - Cannot install Database Interfaces
I uninstalled and tried to re-install PB 11.5.1. I am using Windows 10 and before the uninstall the PB was working OK (I have installed it on Windows 8.1 and then updated to Windows 10 but it was working OK).

The installation of the PB was fine but when I launch PB, I get an error:

```<code>No Database interfaces are installed.
</code>```

I try but I cannot get the Database Interfaces to install.

I get an error :

```<code>Note:PkgMgr has been deprecated. Please update your scripts to use DISM.exe to install.
</code>```

Any help appreciated

答: No luck. Fortunately my Windows Previous Version option worked!</p>

Body:
I uninstalled and tried to re-install PB 11.5.1. I am using Windows 10 and before the uninstall the PB was working OK (I have installed it on Windows 8.1 and then updated to Windows 10 but it was working OK).

The installation of the PB was fine but when I launch PB, I get an error:

No Database interfaces are installed.

I try but I cannot get the Database Interfaces to install.

I get an error :

Note:PkgMgr has been deprecated. Please update your scripts to use DISM.exe to install.

Any help appreciated


问:
Pandas : plot data frame object with marker?
This is my pandas DataFrame.

```<code>   value  action
0      1       0
1      2       1
2      3       1
3      4       1
4      3       0
5      2       1
6      5       0
</code>```

What I want to do is mark value as o if action=0, x if action=1.

So, the plot marker should be like this:
o x x x o x o

But have no idea how to do this...

Need your helps. Thanks.

答:
You can plot the filtered dataframe. I.e., you can create two dataframes, one for action 0 and one for action 1. Then plot each individually.

```<code>import pandas as pd

df = pd.DataFrame({"value":[1,2,3,4,3,2,5], "action":[0,1,1,1,0,1,0]})
df0 = df[df["action"] == 0]
df1 = df[df["action"] == 1]

ax = df.reset_index().plot(x = "index", y="value", legend=False, color="gray", zorder=0)
df0.reset_index().plot(x = "index", y="value",kind="scatter", marker="o", ax=ax)
df1.reset_index().plot(x = "index", y="value",kind="scatter",  marker="x", ax=ax)
</code>```

Body:
This is my pandas DataFrame.

   value  action
0      1       0
1      2       1
2      3       1
3      4       1
4      3       0
5      2       1
6      5       0

What I want to do is mark value as o if action=0, x if action=1.

So, the plot marker should be like this:
o x x x o x o

But have no idea how to do this...

Need your helps. Thanks.

Body:
You can plot the filtered dataframe. I.e., you can create two dataframes, one for action 0 and one for action 1. Then plot each individually.

import pandas as pd

df = pd.DataFrame({"value":[1,2,3,4,3,2,5], "action":[0,1,1,1,0,1,0]})
df0 = df[df["action"] == 0]
df1 = df[df["action"] == 1]

ax = df.reset_index().plot(x = "index", y="value", legend=False, color="gray", zorder=0)
df0.reset_index().plot(x = "index", y="value",kind="scatter", marker="o", ax=ax)
df1.reset_index().plot(x = "index", y="value",kind="scatter",  marker="x", ax=ax)


问:
Is scipy.misc.imread safe/efficient to run from multiple threads?
I have set up a producer/consumer model using python Queues. In one producer I'm reading images using scipy.misc.imread.

Reading images in one thread is not fast enough, it takes ~0.2s per image to read. About 20MB/sec reading from an SSD.

I tried adding another identical thread using python's threading module. However the time spent in scipy.misc.imread increased by approximately double, causing the 2 threads to read images approximately as fast as the 1 did.

I'm sure my SSD can handle 40MB/sec throughput, even with random reads. A dd write test shows 800MB+/sec write speeds.

I am left wondering if scipy.misc.imread runs as a critical region among threads? Would I expect multiprocessing to avoid the problem?

答:
scipy.misc.imread is safe from multiple threads, but each call locks the global interpreter, so performance won't benefit from multithreading.

It works well from multiprocessing, no unexpected issues.


问:
BeautifulSoup: Extracting figures and captions from JATS XML
I would like to get the images and it's descriptions from JATS XML. In my example I use http://journal.frontiersin.org/article/10.3389/fpls.2011.00008/xml/nlm

The figures are formatted like this:

```<code><fig id="F1" position="float">
<label>Figure 1</label>
<caption><p><bold>Pathways of DSB misrepair...</p></caption>
<graphic xlink:href="fpls-02-00008-g001.tif"/>
</fig>
</code>```

I would like to get both the contents of
...
 and <graphic xlink:href="..."/> of every figure.

So my idea was to use the css selectors of BeautifoulSoup and strip the html tags when printing:

```<code>#!/usr/bin/python

from bs4 import BeautifulSoup
import urllib.request

content = urllib.request.urlopen('file:///tmp/fpls-02-00008.xml').read()
soup = BeautifulSoup(content, 'xml')

##<fig><caption>XXX</caption></fig>
caption = soup.select("fig caption")

##<fig><graphic xlink:href="YYY"/></fig>
graphic = soup.select("fig graphic")

for a in caption:
    print(a.get_text().strip())

#print(b.get_text()) doesn't work
for b in graphic:
    print(b)

#separator = "|"
#print(separator.join([caption, graphic]))
</code>```

Getting just the captions or just the graphics works, but because of inconsistencies in the sources I need get it both at once. The result should not be

caption A

caption B

graphic A

graphic B

but rather

caption A, graphic A

caption B, graphic B

How do I achieve this? Thanks in advance!

答:
You could select fig element first, then select caption and graphic in same loop.

```<code>fig = soup.select("fig")
for e in fig:
    print(e.select('caption')[0].get_text().strip())
    print(e.select('graphic')[0]['xlink:href'])
</code>```

output:

```<code>Pathways of DSB misrepair via single-strand annealing(SSA) or via synthesis-dependent strand annealing (SDSA). (A) Deletion via exonucleolytic 5′-end resection, SSA at complementary overhang sequences, resection of the non-aligned ends, and ligation of break-ends. (B) Insertion into a DSB by break-end invasion and elongationalong an ectopic and partially homologous (vertical bars) template.(C) Re-synthesis of break-ends after invasion into a homologous template double-strand without (gene conversion) or with exchange of flanking regions due to appropriate resolution of Holiday junctions (greenarrow heads).
fpls-02-00008-g001.tif
Schematic models of replication and chromosome labeling patterns after BIR at proximal DSB ends in S and G2. (A) BIR through conservative replication of a one ended DSB during S phase. The DSB appears when the replication fork arrives at a single-strand break (arrow head). Conservative replication occurs via recurrent strand invasion (or via unidirectional fork migration) without resolution of the Holiday junction(s) using the parental double strand as a template. The result after EdU incorporation is an asymmetrically unlabeled terminal chromatid region. (B) BIR during G2 phase, through conservative replication at the proximal end of a DSB (arrow head) via recurrent strand invasion and/or via unidirectional fork migration without resolution of the Holiday junction(s) using the undamaged sister double helix as a template. The result after EdU incorporation is an asymmetrically labeled terminal chromatid region. (C) BIR during G2 phase through semiconservative replication achieved by resolution of the Holiday junction (green arrow head) after invasion of the elongating break-end into the template double strand. The result after EdU incorporation is a symmetrically labeled distal chromatid region. Full lines unlabeled; broken lines labeled by EdU. The distal fragment of the broken double helix in (B,C) gets lost.
fpls-02-00008-g002.tif
Metaphase chromosomes of the field bean. (A) Chromatid-type aberrations after bleomycin treatment. Left cell: isochromatid break (arrow head), the centric, and the acentric chromatid fragments are surrounded by black dots, the homologous undamaged chromosome is surrounded by white dots. Middle cell: symmetric reciprocal chromatid translocation (arrow) and two terminal chromatid breaks (arrow heads). The latter with the broken fragment either switched to the opposite site of the undamaged sister chromatid (left) or being at least 90° apart from the other break-end as in case of the broken secondary constriction (right). Right cell: interstitial deletion (arrow), the deleted fragment remains attached to the undamaged sister chromatid, the chromosome involved is surrounded by black dots. (B) Interstitial asymmetric chromatid labeling (arrows) after bleomycin treatment in the presence of EdU during S phase. (C) Interstitial asymmetric chromatid labeling (arrows) after bleomycin treatment in the presence of EdU during G2. The asymmetric signals appear on chromosomes II, IV, V, and VI, respectively, at interstitial heterochromatic regions composed of homologous tandem repeats (Fuchs et al., 1994).
fpls-02-00008-g003.tif
</code>```

Body:
I would like to get the images and it's descriptions from JATS XML. In my example I use http://journal.frontiersin.org/article/10.3389/fpls.2011.00008/xml/nlm

The figures are formatted like this:

<fig id="F1" position="float">
Figure 1

<bold>Pathways of DSB misrepair...

<graphic xlink:href="fpls-02-00008-g001.tif"/>
</fig>

I would like to get both the contents of
...
 and <graphic xlink:href="..."/> of every figure.

So my idea was to use the css selectors of BeautifoulSoup and strip the html tags when printing:

#!/usr/bin/python

from bs4 import BeautifulSoup
import urllib.request

content = urllib.request.urlopen('file:///tmp/fpls-02-00008.xml').read()
soup = BeautifulSoup(content, 'xml')

##<fig>
XXX
</fig>
caption = soup.select("fig caption")

##<fig><graphic xlink:href="YYY"/></fig>
graphic = soup.select("fig graphic")

for a in caption:
    print(a.get_text().strip())

#print(b.get_text()) doesn't work
for b in graphic:
    print(b)

#separator = "|"
#print(separator.join([caption, graphic]))

Getting just the captions or just the graphics works, but because of inconsistencies in the sources I need get it both at once. The result should not be

caption A

caption B

graphic A

graphic B

but rather

caption A, graphic A

caption B, graphic B

How do I achieve this? Thanks in advance!

Body:
You could select fig element first, then select caption and graphic in same loop.

fig = soup.select("fig")
for e in fig:
    print(e.select('caption')[0].get_text().strip())
    print(e.select('graphic')[0]['xlink:href'])

output:

Pathways of DSB misrepair via single-strand annealing(SSA) or via synthesis-dependent strand annealing (SDSA). (A) Deletion via exonucleolytic 5′-end resection, SSA at complementary overhang sequences, resection of the non-aligned ends, and ligation of break-ends. (B) Insertion into a DSB by break-end invasion and elongationalong an ectopic and partially homologous (vertical bars) template.(C) Re-synthesis of break-ends after invasion into a homologous template double-strand without (gene conversion) or with exchange of flanking regions due to appropriate resolution of Holiday junctions (greenarrow heads).
fpls-02-00008-g001.tif
Schematic models of replication and chromosome labeling patterns after BIR at proximal DSB ends in S and G2. (A) BIR through conservative replication of a one ended DSB during S phase. The DSB appears when the replication fork arrives at a single-strand break (arrow head). Conservative replication occurs via recurrent strand invasion (or via unidirectional fork migration) without resolution of the Holiday junction(s) using the parental double strand as a template. The result after EdU incorporation is an asymmetrically unlabeled terminal chromatid region. (B) BIR during G2 phase, through conservative replication at the proximal end of a DSB (arrow head) via recurrent strand invasion and/or via unidirectional fork migration without resolution of the Holiday junction(s) using the undamaged sister double helix as a template. The result after EdU incorporation is an asymmetrically labeled terminal chromatid region. (C) BIR during G2 phase through semiconservative replication achieved by resolution of the Holiday junction (green arrow head) after invasion of the elongating break-end into the template double strand. The result after EdU incorporation is a symmetrically labeled distal chromatid region. Full lines unlabeled; broken lines labeled by EdU. The distal fragment of the broken double helix in (B,C) gets lost.
fpls-02-00008-g002.tif
Metaphase chromosomes of the field bean. (A) Chromatid-type aberrations after bleomycin treatment. Left cell: isochromatid break (arrow head), the centric, and the acentric chromatid fragments are surrounded by black dots, the homologous undamaged chromosome is surrounded by white dots. Middle cell: symmetric reciprocal chromatid translocation (arrow) and two terminal chromatid breaks (arrow heads). The latter with the broken fragment either switched to the opposite site of the undamaged sister chromatid (left) or being at least 90° apart from the other break-end as in case of the broken secondary constriction (right). Right cell: interstitial deletion (arrow), the deleted fragment remains attached to the undamaged sister chromatid, the chromosome involved is surrounded by black dots. (B) Interstitial asymmetric chromatid labeling (arrows) after bleomycin treatment in the presence of EdU during S phase. (C) Interstitial asymmetric chromatid labeling (arrows) after bleomycin treatment in the presence of EdU during G2. The asymmetric signals appear on chromosomes II, IV, V, and VI, respectively, at interstitial heterochromatic regions composed of homologous tandem repeats (Fuchs et al., 1994).
fpls-02-00008-g003.tif


问:
How to import the electron ipcRenderer in a react / webpack 2 setup
using a electron, react (es6 / jsx), sass, pouchdb and webpack 2 setup. I fail to import or require ipcRenderer to make communication between main and renderer process possible. My setup can be found here: https://github.com/wende60/timeTracker

Any hints how to get the ipcRenderer into a react component?

Cheers, jo

答:
I had the same problem. This solved that issue for me:

Add in the webpack.config.js:

```<code>const webpack = require("webpack");

module.exports = {
    plugins: [
        new webpack.ExternalsPlugin('commonjs', [
            'electron'
        ])
    ]
    ...
}
</code>```

Then you can use it with

```<code>import {ipcRenderer} from "electron";
</code>```

Body:
I had the same problem. This solved that issue for me:

Add in the webpack.config.js:

const webpack = require("webpack");

module.exports = {
    plugins: [
        new webpack.ExternalsPlugin('commonjs', [
            'electron'
        ])
    ]
    ...
}

Then you can use it with

import {ipcRenderer} from "electron";


问:
in python is there a better way to apply a list of functions to a dictionary
Is there a better way to iteratively apply a list of functions to a dictionary? Here is an example of what I want to do.  But this uses recursion.

```<code>def func1(h: dict):
    h['foo']=10
    return(h)

def func2(h: dict):
    h['bar']=100
    return(h)

def func3(h: dict):
    h['baz']=h['foo']+h['bar']
    return(h)

func3(func2(func1({'firstElement':'good'})))
</code>```

Produces expected output:

```<code>{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

I want to provide the functions as a array and produce the same output.  Here is what I have tried and works:

```<code>def recApply(flist, h=None):
    """
    Helper Apply the list of functions iteratively over the dictionary passed
    :obj: function list each will be applied to the dictionary sequentially.
    """
    #if no dictionary passed, then set the dictionary.
    if(h == None):
        h = {}

    #iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
    for f in flist:
        h = f(h)

    return(h)

flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})
</code>```

This produces the desired output:

```<code>{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

Is there a way to do this that is more readable, removes the recApply function and hopefully minimizes dictionary copies?

答:
You could also use reduce (or functools.reduce in Python 3) with the starting dictionary as the initializer parameter:

```<code>>>> from functools import reduce  # Python 3
>>> reduce(lambda (x, f): f(x), (func1, func2, func3), {'firstElement':'good'})
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

This will apply the functions one after the other to the initializer or the result of the previous function.

You could also combine this with functools.partial to create a chained function that can then be applied to different input dictionaries:

```<code>>>> from functools import partial
>>> chain = partial(reduce, lambda (x, f): f(x), (func1, func2, func3))
>>> chain({'firstElement':'good'})
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

And you could generalize that further, making it a partial of a partial function...

```<code>>>> chainer = partial(partial, reduce, lambda (x, f): f(x))
>>> chain = chainer((func1, func2, func3))
>>> chain({'firstElement':'good'})
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}
</code>```

Body:
Is there a better way to iteratively apply a list of functions to a dictionary? Here is an example of what I want to do.  But this uses recursion.

def func1(h: dict):
    h['foo']=10
    return(h)

def func2(h: dict):
    h['bar']=100
    return(h)

def func3(h: dict):
    h['baz']=h['foo']+h['bar']
    return(h)

func3(func2(func1({'firstElement':'good'})))

Produces expected output:

{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

I want to provide the functions as a array and produce the same output.  Here is what I have tried and works:

def recApply(flist, h=None):
    """
    Helper Apply the list of functions iteratively over the dictionary passed
    :obj: function list each will be applied to the dictionary sequentially.
    """
    #if no dictionary passed, then set the dictionary.
    if(h == None):
        h = {}

    #iteratively call functions with dictionary as a passed parameter and returning a derived dictionary
    for f in flist:
        h = f(h)

    return(h)

flist = [func1,func2,func3]
recApply(flist,{'firstElement':'good'})

This produces the desired output:

{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

Is there a way to do this that is more readable, removes the recApply function and hopefully minimizes dictionary copies?

Body:
You could also use reduce (or functools.reduce in Python 3) with the starting dictionary as the initializer parameter:

>>> from functools import reduce  # Python 3
>>> reduce(lambda (x, f): f(x), (func1, func2, func3), {'firstElement':'good'})
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

This will apply the functions one after the other to the initializer or the result of the previous function.

You could also combine this with functools.partial to create a chained function that can then be applied to different input dictionaries:

>>> from functools import partial
>>> chain = partial(reduce, lambda (x, f): f(x), (func1, func2, func3))
>>> chain({'firstElement':'good'})
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}

And you could generalize that further, making it a partial of a partial function...

>>> chainer = partial(partial, reduce, lambda (x, f): f(x))
>>> chain = chainer((func1, func2, func3))
>>> chain({'firstElement':'good'})
{'bar': 100, 'baz': 110, 'firstElement': 'good', 'foo': 10}


问:
basic clang: sprintf resets int counter to 0
Consider the following:

```<code>int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);
</code>```

then later

```<code>fileNo++; // fileNo equals 1 now
</code>```

Then if you call this again:

```<code>sprintf(outfile, "%03d.jpg", fileNo);
</code>```

fileNo now equals 0 again.

The goal here is to keep a counter in fileNo, and then pass that value to sprintf in order to set a filename. Is there an easier way to convert a counter to a string value? Or am I just missing a step that might prevent the fileNo from being reset to zero?

I've been digging into malloc, but it isn't really clear when that is necessary. Help?

(I'm not new to programming, but new to C.)

Update

This is a very simple program. There are no reassignments. When I step into the debugger, fileNo is reset to 0 immediately after the sprintf line is executed.

...

```<code>static int fileNo = 0;
char outfile[7];
sprintf(outfile, "%03d.jpg", fileNo);
</code>```

...

```<code> while(fread(buffer, 1, 512, inptr) == 512)
 {
    // 0xff 0xd8 0xff
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
    {
        if (!found1stJPG)
        {
            found1stJPG = true;

        } else {
            fileNo++;
            fclose(outptr);
            sprintf(outfile, "%03d.jpg", fileNo); // fileNo is 1 before this executes
            printf("outfile: %s,\n", outfile); // in the debugger fileNo is now 0
        }
</code>```

答:
You have the following:

```<code>char somecharvariable;
char outfile[7];
int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);
</code>```

Oops. The string null terminator wrote over fileno. outfile should be length 8. If you allow fileNo to exceed 999 your code will crash anyway.

Putting the static flag on fileNo does not fix the problem. It merely relocates the problem to some other variable.

Body:
Consider the following:

int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);

then later

fileNo++; // fileNo equals 1 now

Then if you call this again:

sprintf(outfile, "%03d.jpg", fileNo);

fileNo now equals 0 again.

The goal here is to keep a counter in fileNo, and then pass that value to sprintf in order to set a filename. Is there an easier way to convert a counter to a string value? Or am I just missing a step that might prevent the fileNo from being reset to zero?

I've been digging into malloc, but it isn't really clear when that is necessary. Help?

(I'm not new to programming, but new to C.)

Update

This is a very simple program. There are no reassignments. When I step into the debugger, fileNo is reset to 0 immediately after the sprintf line is executed.

...

static int fileNo = 0;
char outfile[7];
sprintf(outfile, "%03d.jpg", fileNo);

...

 while(fread(buffer, 1, 512, inptr) == 512)
 {
    // 0xff 0xd8 0xff
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
    {
        if (!found1stJPG)
        {
            found1stJPG = true;

        } else {
            fileNo++;
            fclose(outptr);
            sprintf(outfile, "%03d.jpg", fileNo); // fileNo is 1 before this executes
            printf("outfile: %s,\n", outfile); // in the debugger fileNo is now 0
        }

Body:
You have the following:

char somecharvariable;
char outfile[7];
int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);

Oops. The string null terminator wrote over fileno. outfile should be length 8. If you allow fileNo to exceed 999 your code will crash anyway.

Putting the static flag on fileNo does not fix the problem. It merely relocates the problem to some other variable.


问:
re.findall() not returning all matches
```<code>      import re
      text = 'fruits to be sold are apple orange and peach'
      x = re.findall(r'fruits.*(apple|orange|peach).*',text,re.I)
      print(x)
</code>```

The objective of the code is to return a list, containing names of the fruits in the sentence after the word 'fruits'.

so the expected result should be like

```<code>['apple','orange','peach']
</code>```

but instead am getting only the last match in the sentence.i.e peach.
Could someone help me out where did I go wrong ?

答:
You could replace your regexp by the simpler</p>

```<code>x = re.findall(r'(apple|orange|peach)',text,re.I)
</code>```

Title: re.findall() not returning all matches

Body:
      import re
      text = 'fruits to be sold are apple orange and peach'
      x = re.findall(r'fruits.*(apple|orange|peach).*',text,re.I)
      print(x)

The objective of the code is to return a list, containing names of the fruits in the sentence after the word 'fruits'.

so the expected result should be like

['apple','orange','peach']

but instead am getting only the last match in the sentence.i.e peach.
Could someone help me out where did I go wrong ?

Body:
You could replace your regexp by the simpler

x = re.findall(r'(apple|orange|peach)',text,re.I)


问:
Why does an image captured using camera intent gets rotated on some devices on Android?
I'm capturing an image and setting it to image view.

```<code>public void captureImage() {

    Intent intentCamera = new Intent("android.media.action.IMAGE_CAPTURE");
    File filePhoto = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
    imageUri = Uri.fromFile(filePhoto);
    MyApplicationGlobal.imageUri = imageUri.getPath();
    intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intentCamera, TAKE_PICTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentFromCamera) {
    super.onActivityResult(requestCode, resultCode, intentFromCamera);

    if (resultCode == RESULT_OK && requestCode == TAKE_PICTURE) {

        if (intentFromCamera != null) {
            Bundle extras = intentFromCamera.getExtras();
            if (extras.containsKey("data")) {
                bitmap = (Bitmap) extras.get("data");
            }
            else {
                bitmap = getBitmapFromUri();
            }
        }
        else {
            bitmap = getBitmapFromUri();
        }
        // imageView.setImageBitmap(bitmap);
        imageView.setImageURI(imageUri);
    }
    else {
    }
}

public Bitmap getBitmapFromUri() {

    getContentResolver().notifyChange(imageUri, null);
    ContentResolver cr = getContentResolver();
    Bitmap bitmap;

    try {
        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
        return bitmap;
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
</code>```

But the problem is, the image on some devices every time it gets rotated. For example, on a Samsung device it works good, but on a Sony Xperia the image gets rotated by 90 degrees and on Toshiba Thrive (tablet) by 180 degrees.

答:
So first thing, you sholuld know that since Android 7.0 we have to use FileProvider and something called ContentUri, otherwise you will get an annoying error trying to invoke your Intent. This is sample code:

```<code>Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriFromPath(context, "[Your path to save image]"));
startActivityForResult(intent, CAPTURE_IMAGE_RESULT);
</code>```

Method getUriFromPath(Context, String) basis on user version of Android create FileUri (file://...) or ContentUri (content://...) and there it is:

```<code>public Uri getUriFromPath(Context context, String destination) {
    File file =  new File(destination);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    } else {
        return Uri.fromFile(file);
    }
}
</code>```

After onActivityResult you can catch that uri where image is saved by camera, but now you have to detect camera rotation, here we will use moddified @Jason Robinson answer:

First we need to create ExifInterface based on Uri

```<code>@Nullable
public ExifInterface getExifInterface(Context context, Uri uri) {
    try {
        String path = uri.toString();
        if (path.startsWith("file://")) {
            return new ExifInterface(path);
        }
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (path.startsWith("content://")) {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);
                return new ExifInterface(inputStream);
            }
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
</code>```

Above code can be simplified, but i want to show everything. So from FileUri we can create ExifInterface based on String path, but from ContentUri we can't, Android doesn't support that.

In that case we have to use other constructor based on InputStream. Remember this constructor isn't available by default, you have to add additional library:

```<code>compile "com.android.support:exifinterface:XX.X.X"
</code>```

Now we can use getExifInterface method to get our angle:

```<code>public float getExifAngle(Context context, Uri uri) {
    try {
        ExifInterface exifInterface = getExifInterface(context, uri);
        if(exifInterface == null) {
            return -1f;
        }

        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return 90f;
            case ExifInterface.ORIENTATION_ROTATE_180:
                return 180f;
            case ExifInterface.ORIENTATION_ROTATE_270:
                return 270f;
            case ExifInterface.ORIENTATION_NORMAL:
                return 0f;
            case ExifInterface.ORIENTATION_UNDEFINED:
                return -1f;
            default:
                return -1f;
        }
    }
    catch (Exception e) {
        e.printStackTrace();
        return -1f;
    }
}
</code>```

Now you have Angle to properly rotate you image.

Body:
I'm capturing an image and setting it to image view.

public void captureImage() {

    Intent intentCamera = new Intent("android.media.action.IMAGE_CAPTURE");
    File filePhoto = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
    imageUri = Uri.fromFile(filePhoto);
    MyApplicationGlobal.imageUri = imageUri.getPath();
    intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    startActivityForResult(intentCamera, TAKE_PICTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intentFromCamera) {
    super.onActivityResult(requestCode, resultCode, intentFromCamera);

    if (resultCode == RESULT_OK && requestCode == TAKE_PICTURE) {

        if (intentFromCamera != null) {
            Bundle extras = intentFromCamera.getExtras();
            if (extras.containsKey("data")) {
                bitmap = (Bitmap) extras.get("data");
            }
            else {
                bitmap = getBitmapFromUri();
            }
        }
        else {
            bitmap = getBitmapFromUri();
        }
        // imageView.setImageBitmap(bitmap);
        imageView.setImageURI(imageUri);
    }
    else {
    }
}

public Bitmap getBitmapFromUri() {

    getContentResolver().notifyChange(imageUri, null);
    ContentResolver cr = getContentResolver();
    Bitmap bitmap;

    try {
        bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, imageUri);
        return bitmap;
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

But the problem is, the image on some devices every time it gets rotated. For example, on a Samsung device it works good, but on a Sony Xperia the image gets rotated by 90 degrees and on Toshiba Thrive (tablet) by 180 degrees.

Body:
So first thing, you sholuld know that since Android 7.0 we have to use FileProvider and something called ContentUri, otherwise you will get an annoying error trying to invoke your Intent. This is sample code:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getUriFromPath(context, "[Your path to save image]"));
startActivityForResult(intent, CAPTURE_IMAGE_RESULT);

Method getUriFromPath(Context, String) basis on user version of Android create FileUri (file://...) or ContentUri (content://...) and there it is:

public Uri getUriFromPath(Context context, String destination) {
    File file =  new File(destination);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    } else {
        return Uri.fromFile(file);
    }
}

After onActivityResult you can catch that uri where image is saved by camera, but now you have to detect camera rotation, here we will use moddified @Jason Robinson answer:

First we need to create ExifInterface based on Uri

@Nullable
public ExifInterface getExifInterface(Context context, Uri uri) {
    try {
        String path = uri.toString();
        if (path.startsWith("file://")) {
            return new ExifInterface(path);
        }
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (path.startsWith("content://")) {
                InputStream inputStream = context.getContentResolver().openInputStream(uri);
                return new ExifInterface(inputStream);
            }
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Above code can be simplified, but i want to show everything. So from FileUri we can create ExifInterface based on String path, but from ContentUri we can't, Android doesn't support that.

In that case we have to use other constructor based on InputStream. Remember this constructor isn't available by default, you have to add additional library:

compile "com.android.support:exifinterface:XX.X.X"

Now we can use getExifInterface method to get our angle:

public float getExifAngle(Context context, Uri uri) {
    try {
        ExifInterface exifInterface = getExifInterface(context, uri);
        if(exifInterface == null) {
            return -1f;
        }

        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED);

        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                return 90f;
            case ExifInterface.ORIENTATION_ROTATE_180:
                return 180f;
            case ExifInterface.ORIENTATION_ROTATE_270:
                return 270f;
            case ExifInterface.ORIENTATION_NORMAL:
                return 0f;
            case ExifInterface.ORIENTATION_UNDEFINED:
                return -1f;
            default:
                return -1f;
        }
    }
    catch (Exception e) {
        e.printStackTrace();
        return -1f;
    }
}

Now you have Angle to properly rotate you image.


问:
DTLS handshake fail on ipv6
I have a demo code of dtls, it works well with ipv4. but after I modified it for ipv6, it  fails at handshake stage.
The server code like this:

```<code>SSL_load_error_strings();
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(DTLSv1_server_method());
if(SSL_CTX_use_certificate_chain_file(ctx, "path/to/crt") !=1)
    ERR_print_errors_fp(stderr);

if(SSL_CTX_use_PrivateKey_file(ctx, "path/to/key", SSL_FILETYPE_PEM) != 1)
    ERR_print_errors_fp(stderr);

SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_cert);
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);
SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);
SSL_CTX_set_cipher_list(ctx, "ALL:NULL:eNULL:aNULL");

int fd = socket(AF_INET6, SOCK_DGRAM, 0);
struct sockaddr_in6 server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin6_family = AF_INET6;
server_addr.sin6_port = htons(MYPORT);
server_addr.sin6_addr = in6addr_any;
int flag = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0)
    perror("server reuse addr");

#ifdef SO_REUSEPORT
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) < 0)
    perror("server reuse port");
#endif
if(bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
    perror("bind server fd");

BIO *bio = BIO_new_dgram(fd, BIO_NOCLOSE);
SSL *ssl = SSL_new(ctx);
SSL_set_bio(ssl, bio, bio);

/* Enable cookie exchange */
SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);

fprintf(stderr, "Wait for incoming connections\n");
struct sockaddr_in6 client_addr;
while(1){
    int ret = DTLSv1_listen(ssl, &client_addr);
    if(ret < 0){
        ERR_print_errors_fp(stderr);
    }
    if(ret > 0)
        break;
}
fprintf(stderr, "Handle client connection\n");
int client_fd = socket(client_addr.sin6_family, SOCK_DGRAM, 0);
if (setsockopt(client_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0)
    perror("reuse addr");

#ifdef SO_REUSEPORT
if (setsockopt(client_fd, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) < 0)
    perror("reuse port");
#endif
if(bind(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
    perror("bind client fd");
if(connect(client_fd, (struct sockaddr *)&client_addr, sizeof(client_addr)))
    perror("connect client");
BIO *cbio = SSL_get_rbio(ssl);
BIO_set_fd(cbio, client_fd, BIO_NOCLOSE);
BIO_ctrl(cbio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &client_addr);
fprintf(stderr, "waiting SSL_accept\n");
if(SSL_accept(ssl)!=1){
    ERR_print_errors_fp(stderr);
}
fprintf(stderr, "SSL_accept completed\n");
</code>```

and the client code is:

```<code>SSL_load_error_strings();
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(DTLSv1_client_method());
SSL_CTX_set_read_ahead(ctx, 1);

union {
    struct sockaddr_storage ss;
    struct sockaddr_in6 s6;
    struct sockaddr_in s4;
} server_addr;
int fd;
memset(&server_addr, 0, sizeof(server_addr));
if(inet_pton(AF_INET, argv[1], &server_addr.s4.sin_addr) == 1){
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    server_addr.s4.sin_family = AF_INET;
    server_addr.s4.sin_port = htons(MYPORT);
}else if(inet_pton(AF_INET6, argv[1], &server_addr.s6.sin6_addr) ==1){
    fd = socket(AF_INET6, SOCK_DGRAM, 0);
    server_addr.s6.sin6_family = AF_INET6;
    server_addr.s6.sin6_port = htons(MYPORT);
}else{
    fprintf(stderr, "Wrong ip format\n");
    return 1;
}
if(connect(fd, (struct sockaddr*)&server_addr, sizeof(server_addr)))
    perror("connect");
BIO *bio = BIO_new_dgram(fd, BIO_NOCLOSE);
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &server_addr);
SSL *ssl = SSL_new(ctx);
SSL_set_bio(ssl, bio, bio);
fprintf(stderr, "waiting SSL_connect\n");
if(SSL_connect(ssl)!=1)
    ERR_print_errors_fp(stderr);
fprintf(stderr, "SSL connected\n");
</code>```

It seems no return in SSL_accept and SSL_connect.
I modified the code by changing sockaddr_in to sockaddr_in6 only.
The openssl version is: 1.0.2h on linux

Also I caught the packages with wireshark:

Can somebody tell me what's wrong with the code ?

答:
I add

```<code>BIO_ctrl_set_connected(bio, 0, &client_addr);
</code>```

after DTLSv1_listen in server side solved this problem.

Title: DTLS handshake fail on ipv6

Body:
I have a demo code of dtls, it works well with ipv4. but after I modified it for ipv6, it  fails at handshake stage.
The server code like this:

SSL_load_error_strings();
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(DTLSv1_server_method());
if(SSL_CTX_use_certificate_chain_file(ctx, "path/to/crt") !=1)
    ERR_print_errors_fp(stderr);

if(SSL_CTX_use_PrivateKey_file(ctx, "path/to/key", SSL_FILETYPE_PEM) != 1)
    ERR_print_errors_fp(stderr);

SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_cert);
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);
SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);
SSL_CTX_set_cipher_list(ctx, "ALL:NULL:eNULL:aNULL");

int fd = socket(AF_INET6, SOCK_DGRAM, 0);
struct sockaddr_in6 server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin6_family = AF_INET6;
server_addr.sin6_port = htons(MYPORT);
server_addr.sin6_addr = in6addr_any;
int flag = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0)
    perror("server reuse addr");

#ifdef SO_REUSEPORT
if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) < 0)
    perror("server reuse port");
#endif
if(bind(fd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
    perror("bind server fd");

BIO *bio = BIO_new_dgram(fd, BIO_NOCLOSE);
SSL *ssl = SSL_new(ctx);
SSL_set_bio(ssl, bio, bio);

/* Enable cookie exchange */
SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);

fprintf(stderr, "Wait for incoming connections\n");
struct sockaddr_in6 client_addr;
while(1){
    int ret = DTLSv1_listen(ssl, &client_addr);
    if(ret < 0){
        ERR_print_errors_fp(stderr);
    }
    if(ret > 0)
        break;
}
fprintf(stderr, "Handle client connection\n");
int client_fd = socket(client_addr.sin6_family, SOCK_DGRAM, 0);
if (setsockopt(client_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0)
    perror("reuse addr");

#ifdef SO_REUSEPORT
if (setsockopt(client_fd, SOL_SOCKET, SO_REUSEPORT, &flag, sizeof(flag)) < 0)
    perror("reuse port");
#endif
if(bind(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)))
    perror("bind client fd");
if(connect(client_fd, (struct sockaddr *)&client_addr, sizeof(client_addr)))
    perror("connect client");
BIO *cbio = SSL_get_rbio(ssl);
BIO_set_fd(cbio, client_fd, BIO_NOCLOSE);
BIO_ctrl(cbio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &client_addr);
fprintf(stderr, "waiting SSL_accept\n");
if(SSL_accept(ssl)!=1){
    ERR_print_errors_fp(stderr);
}
fprintf(stderr, "SSL_accept completed\n");

and the client code is:

SSL_load_error_strings();
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(DTLSv1_client_method());
SSL_CTX_set_read_ahead(ctx, 1);

union {
    struct sockaddr_storage ss;
    struct sockaddr_in6 s6;
    struct sockaddr_in s4;
} server_addr;
int fd;
memset(&server_addr, 0, sizeof(server_addr));
if(inet_pton(AF_INET, argv[1], &server_addr.s4.sin_addr) == 1){
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    server_addr.s4.sin_family = AF_INET;
    server_addr.s4.sin_port = htons(MYPORT);
}else if(inet_pton(AF_INET6, argv[1], &server_addr.s6.sin6_addr) ==1){
    fd = socket(AF_INET6, SOCK_DGRAM, 0);
    server_addr.s6.sin6_family = AF_INET6;
    server_addr.s6.sin6_port = htons(MYPORT);
}else{
    fprintf(stderr, "Wrong ip format\n");
    return 1;
}
if(connect(fd, (struct sockaddr*)&server_addr, sizeof(server_addr)))
    perror("connect");
BIO *bio = BIO_new_dgram(fd, BIO_NOCLOSE);
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &server_addr);
SSL *ssl = SSL_new(ctx);
SSL_set_bio(ssl, bio, bio);
fprintf(stderr, "waiting SSL_connect\n");
if(SSL_connect(ssl)!=1)
    ERR_print_errors_fp(stderr);
fprintf(stderr, "SSL connected\n");

It seems no return in SSL_accept and SSL_connect.
I modified the code by changing sockaddr_in to sockaddr_in6 only.
The openssl version is: 1.0.2h on linux

Also I caught the packages with wireshark:

Can somebody tell me what's wrong with the code ?

Body:
I add

BIO_ctrl_set_connected(bio, 0, &client_addr);

after DTLSv1_listen in server side solved this problem.


问:
Prompt dialog in JavaScript runs before the code written earlier
Why the prompt dialog in JavaScript runs before the code written earlier?
For example
It seems to me in this code the "main-heading" should be shown at first then for loop and only after that prompt dialogue?</p>

```<code><h1 id="main-heading">Hello World!!!</h1>
<script>
  var friends= ["Olya", "Dima", "Dan", "Dennis", "Sasha" ];
  for ( var r= 0, rmax= friends.length; r < rmax; r++ ) {
    $("body").append("<p>" + friends[r] + "</p>");
    console.log('friends[r]', friends[r]);
  }
  var newHeading= prompt("Enter NEW Heading");
  $("#main-heading").text(newHeading);
</script>
</code>```

答:
The body tag is not closed yet, so it cannot be rendered/painted.
You might want to wait to loading the content, by adding your code to a callback, that runs after the html had been rendered. With jQuery, its really easy to accomplish using jQuery ready:

```<code>$(function(){
    //Everything is loaded, let's manipulate the body
});
</code>```

Body:
Why the prompt dialog in JavaScript runs before the code written earlier?
For example
It seems to me in this code the "main-heading" should be shown at first then for loop and only after that prompt dialogue?

Hello World!!!

Body:
The body tag is not closed yet, so it cannot be rendered/painted.
You might want to wait to loading the content, by adding your code to a callback, that runs after the html had been rendered. With jQuery, its really easy to accomplish using jQuery ready:

$(function(){
    //Everything is loaded, let's manipulate the body
});


问:
echo environment variable with docker run
Can anybody explain why this doesn't work:

```<code># docker run -ti --rm golang echo $GOPATH

# docker run -ti --rm golang echo \$GOPATH
$GOPATH
</code>```

when this works:

```<code># docker run -ti --rm golang bash -c "echo \$GOPATH"
/go
</code>```

答:
1) docker run -ti --rm golang echo $GOPATH

```<code>docker run -ti golang echo $GOPATH
/Users/me/go
</code>```

I removed the --rm flag to be able to inspect the container. Then, I did docker inspect container-id:

```<code>"Env": [
    "no_proxy=*.local, 169.254/16",
    "PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "GOLANG_VERSION=1.8.1",
    "GOPATH=/go"
],
"Cmd": [
    "echo",
    "/Users/me/go"
],
</code>```

$GOPATH is expanded before the container starts. It's expanded by your shell, indeed before the docker command is called.

2) docker run -ti --rm golang echo \$GOPATH

```<code>docker run -ti golang echo \$GOPATH
$GOPATH
</code>```

docker inspect container-id:

```<code>"Env": [
    "no_proxy=*.local, 169.254/16",
    "PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "GOLANG_VERSION=1.8.1",
    "GOPATH=/go"
],
"Cmd": [
    "echo",
    "$GOPATH"
],
</code>```

Here the $GOPATH is a literal string and doesn't get expanded by the shell because you escaped the $, then echo receives the literal var name instead of its value.

3) docker run -ti --rm golang bash -c "echo \$GOPATH"

```<code>docker run -ti golang bash -c "echo \$GOPATH"
/go
</code>```

docker inspect container-id:

```<code>"Env": [
    "no_proxy=*.local, 169.254/16",
    "PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "GOLANG_VERSION=1.8.1",
    "GOPATH=/go"
],
"Cmd": [
    "bash",
    "-c",
    "echo $GOPATH"
],
</code>```

Here, your shell runs docker with no variable expansion too, due to the \$, but there is another shell that will catch it and expand it: bash will do that but inside the container this time, where the GOPATH is provided by docker as environment variable defined in the golang image (GOPATH=/go). See the Dockerfile where that is defined.

Body:
Can anybody explain why this doesn't work:

# docker run -ti --rm golang echo $GOPATH

# docker run -ti --rm golang echo \$GOPATH
$GOPATH

when this works:

# docker run -ti --rm golang bash -c "echo \$GOPATH"
/go

Body:
1) docker run -ti --rm golang echo $GOPATH

docker run -ti golang echo $GOPATH
/Users/me/go

I removed the --rm flag to be able to inspect the container. Then, I did docker inspect container-id:

"Env": [
    "no_proxy=*.local, 169.254/16",
    "PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "GOLANG_VERSION=1.8.1",
    "GOPATH=/go"
],
"Cmd": [
    "echo",
    "/Users/me/go"
],

$GOPATH is expanded before the container starts. It's expanded by your shell, indeed before the docker command is called.

2) docker run -ti --rm golang echo \$GOPATH

docker run -ti golang echo \$GOPATH
$GOPATH

docker inspect container-id:

"Env": [
    "no_proxy=*.local, 169.254/16",
    "PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "GOLANG_VERSION=1.8.1",
    "GOPATH=/go"
],
"Cmd": [
    "echo",
    "$GOPATH"
],

Here the $GOPATH is a literal string and doesn't get expanded by the shell because you escaped the $, then echo receives the literal var name instead of its value.

3) docker run -ti --rm golang bash -c "echo \$GOPATH"

docker run -ti golang bash -c "echo \$GOPATH"
/go

docker inspect container-id:

"Env": [
    "no_proxy=*.local, 169.254/16",
    "PATH=/go/bin:/usr/local/go/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
    "GOLANG_VERSION=1.8.1",
    "GOPATH=/go"
],
"Cmd": [
    "bash",
    "-c",
    "echo $GOPATH"
],

Here, your shell runs docker with no variable expansion too, due to the \$, but there is another shell that will catch it and expand it: bash will do that but inside the container this time, where the GOPATH is provided by docker as environment variable defined in the golang image (GOPATH=/go). See the Dockerfile where that is defined.


问:
How do I find out if my application is running on x86 or x64 Windows?
I want to know, at run time, whether I'm running on 32 bit or 64 bit windows.  The OSVERSIONINFOEX structure tells me the major and minor version, but I'm guessing I need the build numbers.  Anyone know what they are?</p>

答:
I use WMI.

select * from Win32_OperatingSystem

Get the first instance, and then select the Version attribute. For WinXP, it returns 5.1.2600.

OwnerDisplayName: hatcat

LastEditorDisplayName: Roger Lipscombe

OwnerDisplayName: jsawruk


问:
Error in MySQL Query. Check if row exist, update or insert
The following query should check if the row exists, if it does, update, if it doesn't, insert.

```<code>String sql = "IF EXISTS (SELECT * FROM 'mocha' WHERE uuid = " + uuid + ")" +
        "BEGIN" +
            "UPDATE 'mocha'" +
            "SET join_message = " + message +
            "WHERE uuid ="  + uuid +
        "END" +
        "ELSE" +
        "BEGIN" +
            "INSERT INTO 'mocha' (uuid, join_message, quit_message)" +
            "VALUES ('"  + uuid + ", " + message + " + "" + "')" +
        "END";
</code>```

I was hoping to be able to do this in one query instead of two, Here's the entire method:

```<code>public void setMessage(UUID uuid, String message) {
    String sql = "IF EXISTS (SELECT * FROM 'mocha' WHERE uuid = " + uuid + ")" +
            "BEGIN" +
                "UPDATE 'mocha'" +
                "SET join_message = " + message +
                "WHERE uuid ="  + uuid +
            "END" +
            "ELSE" +
            "BEGIN" +
                "INSERT INTO 'mocha' (uuid, join_message, quit_message)" +
                "VALUES ('"  + uuid + ", " + message + ", ''" + "')" +
            "END";
    BukkitRunnable r = new BukkitRunnable() {
        @Override
        public void run() {
            System.out.println("Join message was set.");
            try {
                Statement statement = connection.createStatement();
                statement.executeUpdate(sql);
            } catch(SQLException e) {
                e.printStackTrace();
            }
        }
    };

    r.runTaskAsynchronously(instance);
}
</code>```

However I'm getting the following error:

```<code>    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''mocha' WHERE uuid = 0f9f822c-d7e6-4000-ac05-6ebc17b82f1d)BEGINUPDATE 'mocha'SET' at line 1
[10:18:52 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[10:18:52 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
[10:18:52 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
[10:18:52 WARN]:        at java.lang.reflect.Constructor.newInstance(Unknown Source)
[10:18:52 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
[10:18:52 WARN]:        at com.mysql.jdbc.Util.getInstance(Util.java:408)
[10:18:52 WARN]:        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
[10:18:52 WARN]:        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
[10:18:52 WARN]:        at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1540)
[10:18:52 WARN]:        at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2595)
[10:18:52 WARN]:        at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1468)
[10:18:52 WARN]:        at me.Latte.Models.MochaModel$2.run(MochaModel.java:68)
[10:18:52 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.scheduler.CraftTask.run(CraftTask.java:71)
[10:18:52 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:52)
[10:18:52 WARN]:        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
[10:18:52 WARN]:        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
[10:18:52 WARN]:        at java.lang.Thread.run(Unknown Source)
</code>```

What am I doing wrong?

答:
Yeah, you are using single quotes instead of backtique around your table name mocha. So your query

```<code>INSERT INTO 'mocha'
</code>```

should be

```<code>INSERT INTO `mocha`
</code>```

Body:
The following query should check if the row exists, if it does, update, if it doesn't, insert.

String sql = "IF EXISTS (SELECT * FROM 'mocha' WHERE uuid = " + uuid + ")" +
        "BEGIN" +
            "UPDATE 'mocha'" +
            "SET join_message = " + message +
            "WHERE uuid ="  + uuid +
        "END" +
        "ELSE" +
        "BEGIN" +
            "INSERT INTO 'mocha' (uuid, join_message, quit_message)" +
            "VALUES ('"  + uuid + ", " + message + " + "" + "')" +
        "END";

I was hoping to be able to do this in one query instead of two, Here's the entire method:

public void setMessage(UUID uuid, String message) {
    String sql = "IF EXISTS (SELECT * FROM 'mocha' WHERE uuid = " + uuid + ")" +
            "BEGIN" +
                "UPDATE 'mocha'" +
                "SET join_message = " + message +
                "WHERE uuid ="  + uuid +
            "END" +
            "ELSE" +
            "BEGIN" +
                "INSERT INTO 'mocha' (uuid, join_message, quit_message)" +
                "VALUES ('"  + uuid + ", " + message + ", ''" + "')" +
            "END";
    BukkitRunnable r = new BukkitRunnable() {
        @Override
        public void run() {
            System.out.println("Join message was set.");
            try {
                Statement statement = connection.createStatement();
                statement.executeUpdate(sql);
            } catch(SQLException e) {
                e.printStackTrace();
            }
        }
    };

    r.runTaskAsynchronously(instance);
}

However I'm getting the following error:

    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''mocha' WHERE uuid = 0f9f822c-d7e6-4000-ac05-6ebc17b82f1d)BEGINUPDATE 'mocha'SET' at line 1
[10:18:52 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
[10:18:52 WARN]:        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
[10:18:52 WARN]:        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
[10:18:52 WARN]:        at java.lang.reflect.Constructor.newInstance(Unknown Source)
[10:18:52 WARN]:        at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
[10:18:52 WARN]:        at com.mysql.jdbc.Util.getInstance(Util.java:408)
[10:18:52 WARN]:        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
[10:18:52 WARN]:        at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
[10:18:52 WARN]:        at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
[10:18:52 WARN]:        at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1540)
[10:18:52 WARN]:        at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2595)
[10:18:52 WARN]:        at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1468)
[10:18:52 WARN]:        at me.Latte.Models.MochaModel$2.run(MochaModel.java:68)
[10:18:52 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.scheduler.CraftTask.run(CraftTask.java:71)
[10:18:52 WARN]:        at org.bukkit.craftbukkit.v1_11_R1.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:52)
[10:18:52 WARN]:        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
[10:18:52 WARN]:        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
[10:18:52 WARN]:        at java.lang.Thread.run(Unknown Source)

What am I doing wrong?

Body:
Yeah, you are using single quotes instead of backtique around your table name mocha. So your query

INSERT INTO 'mocha'

should be

INSERT INTO `mocha`


问:
Splitting strings into text and number?
Let’s say I have this string 'foo1bar2xyz'

I know the indexes for the digits in it {'1': 3, '2': 7}

I want to form substrings of the parent string which don’t have the numbers. How would I get substrings of a string removing particular indexes?

Which in the above case which would be ['foo', 'bar', 'xyz']

Have tried this so far

```<code>def iterate_string(og_string, start, stop):
    if start == 0:
        return og_string[:stop]
    else:
        return og_string[start+1:stop]

def ret_string(S):
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()}
    digit_positions = list(digit_dict.values())
    # return digit_positions
    substrings = []
    start_index = 0
    for position in digit_positions:
        p = iterate_string(S, start_index, position)
        substrings.append(p)
        start_index = position

    return substrings

print ret_string('foo1bar2xyz')
</code>```

But this returns ['foo', 'bar']

Relevant SO questions

答:
Try this:</p>

```<code>l = re.compile("[0-9]").split(s)
</code>```

Title: Splitting strings into text and number?

Body:
Let’s say I have this string 'foo1bar2xyz'

I know the indexes for the digits in it {'1': 3, '2': 7}

I want to form substrings of the parent string which don’t have the numbers. How would I get substrings of a string removing particular indexes?

Which in the above case which would be ['foo', 'bar', 'xyz']

Have tried this so far

def iterate_string(og_string, start, stop):
    if start == 0:
        return og_string[:stop]
    else:
        return og_string[start+1:stop]

def ret_string(S):
    digit_dict = {c:i for i,c in enumerate(S) if c.isdigit()}
    digit_positions = list(digit_dict.values())
    # return digit_positions
    substrings = []
    start_index = 0
    for position in digit_positions:
        p = iterate_string(S, start_index, position)
        substrings.append(p)
        start_index = position

    return substrings

print ret_string('foo1bar2xyz')

But this returns ['foo', 'bar']

Relevant SO questions

Body:
Try this:

l = re.compile("[0-9]").split(s)


问:
Regex match equation strings
Hi I'm trying to make a regex for matching simple math equations strings such as:

```<code>565+9^4/22*5
</code>```

I want to only allow to following arthemithic operators: +, -, *, /, ^, %

and the equation has no set length, it can be as long as it the user wants it to be.

I tried using something like:

\d+[+\-*\/^%]\d+

That matches for example:

2*3+3+3

But it doesn't match:

2*3+3

答:
You need to repeat matches for a "number and operator" combination. So you are looking for:</p>

```<code>(\d+[+\-*\/^%])*(\d+)
</code>```

Title: Regex match equation strings

Body:
Hi I'm trying to make a regex for matching simple math equations strings such as:

565+9^4/22*5

I want to only allow to following arthemithic operators: +, -, *, /, ^, %

and the equation has no set length, it can be as long as it the user wants it to be.

I tried using something like:

\d+[+\-*\/^%]\d+

That matches for example:

2*3+3+3

But it doesn't match:

2*3+3

Body:
You need to repeat matches for a "number and operator" combination. So you are looking for:

(\d+[+\-*\/^%])*(\d+)


问:
How to update redux state further down the tree
For a given reducer, my redux state tree typically looks something like this:

```<code>{
  someField: 'some value',
  // ... more fields
  metadata: {
    pending: false,
    fetched: true,
  }
}
</code>```

Typically, when I do an async request, I fire a SOME_ACTION_REQUEST action, which sets the metadata.pending property to true. It's reset to false again when the matching SOME_ACTION_RESPONSE or SOME_ACTION_ERROR event trickles in later.

However, the way I update the state is a bit verbose:

```<code>case actions.SOME_ACTION_REQUEST: {
  return {
    ...state,
    metadata: { ...state.metadata, pending: true },
  };
}
</code>```

Is there a simpler way of doing this?

Object.assign({}, state, { metadata: { pending: true } }) isn't very readable either.

答:
Yeah, it is actually a downside of Redux, and not only -- if you would use MobX, you'd have the same issue. So, the answer is just to generalize it somehow -- write a reducers factory, which will get constants as arguments, and merge them just once, and reuse it for all async actions.

I've created a library for exactly this issue, so feel free to look at it. Also, just keep in mind that raw Redux is pretty verbose anyway, and try to grasp your domain model in the best way.
Your example will look like that:

```<code>import { createTile } from 'redux-tiles';

const someTile = createTile({
  type: ['some', 'example'],
  fn: ({ api, params }) => api.get('/some/request', params),
});

dispatch(actions.some.example(params));
selectors.some.example(state)); // { isPending: true, error: null, data: null }
</code>```

Data from the last selector will be updated automatically after response will be gotten -- so no need to write such stuff manually.

Another problem is nested updates, and you'd have to do the same thing, but with bigger amount of verbosity, which I always tried to solve. But, of course, it is a pretty simple library, which tries only to cover simple use-cases -- for complex ones, I definitely recommend you to try something custom-tailored.

Body:
For a given reducer, my redux state tree typically looks something like this:

{
  someField: 'some value',
  // ... more fields
  metadata: {
    pending: false,
    fetched: true,
  }
}

Typically, when I do an async request, I fire a SOME_ACTION_REQUEST action, which sets the metadata.pending property to true. It's reset to false again when the matching SOME_ACTION_RESPONSE or SOME_ACTION_ERROR event trickles in later.

However, the way I update the state is a bit verbose:

case actions.SOME_ACTION_REQUEST: {
  return {
    ...state,
    metadata: { ...state.metadata, pending: true },
  };
}

Is there a simpler way of doing this?

Object.assign({}, state, { metadata: { pending: true } }) isn't very readable either.

Body:
Yeah, it is actually a downside of Redux, and not only -- if you would use MobX, you'd have the same issue. So, the answer is just to generalize it somehow -- write a reducers factory, which will get constants as arguments, and merge them just once, and reuse it for all async actions.

I've created a library for exactly this issue, so feel free to look at it. Also, just keep in mind that raw Redux is pretty verbose anyway, and try to grasp your domain model in the best way.
Your example will look like that:

import { createTile } from 'redux-tiles';

const someTile = createTile({
  type: ['some', 'example'],
  fn: ({ api, params }) => api.get('/some/request', params),
});

dispatch(actions.some.example(params));
selectors.some.example(state)); // { isPending: true, error: null, data: null }

Data from the last selector will be updated automatically after response will be gotten -- so no need to write such stuff manually.

Another problem is nested updates, and you'd have to do the same thing, but with bigger amount of verbosity, which I always tried to solve. But, of course, it is a pretty simple library, which tries only to cover simple use-cases -- for complex ones, I definitely recommend you to try something custom-tailored.


问:
Manhattan distance generalization
For a research I'm working on I'm trying to find a satisfying heuristic that is based on Manhattan distance which can work with any problem and domain as an input. Which is also known as domain-independent heuristic.
For now, I know how to apply Manhattan distance on a grid based problems.
Can someone give a tip how to generalize it to work on every domain and problem and not just grid based problems?</p>

答:
The generalization of Manhattan distance is simple.  It is a metric which defines the distance between two multi-dimensional points as the sum of the distances along each dimension:

```<code>md(A, B) = dist(a1, b1) + dist(a2, b2) + . . .
</code>```

The distances along each dimension are assumed to be simple to calculate.  For numbers, the distance is the absolute value of the difference between the values.

This can be extended to other domains as well.  For instance, the distance between two strings could be taken as the Levenshtein distance -- and that would prove to be an interesting metric in conjunction with other dimensions.

Title: Manhattan distance generalization

Body:
The generalization of Manhattan distance is simple.  It is a metric which defines the distance between two multi-dimensional points as the sum of the distances along each dimension:

md(A, B) = dist(a1, b1) + dist(a2, b2) + . . .

The distances along each dimension are assumed to be simple to calculate.  For numbers, the distance is the absolute value of the difference between the values.

This can be extended to other domains as well.  For instance, the distance between two strings could be taken as the Levenshtein distance -- and that would prove to be an interesting metric in conjunction with other dimensions.