问:
node js store returned API key as variable
I am new to node and am trying to using A node.js library for the Pardot API

This I pass my userKey, email and password to pardot, this returns my api_key.

I am using the following code to authenticate, then when I run my node server I can see the api_key being passed back.

how do I then store that api_key as a variable to then use to post data to the API?

my node code

```<code>var nodePardot = require('node-pardot');

// Create client using email, password and user_key
nodePardot.PardotAPI({
    userKey: 'kyujk',
    email: 'uu.uuy@uu.co.uk',
    password: 'uit.09',
    DEBUG: true
}, function(err, client) {
    // Authentication completed
    console.log('Authentication completed');

    // gets api key
    var api_key = api_key;
    console.log('key',api_key);
});
</code>```

my console output

```<code>[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server started! At http://localhost:8080
Initializing node-pardot in DEBUG mode
params {"email":"bhyuyten.jj@jyj.co.uk","password":"tyjt.09","user_key":"yjty76","format":"json"}
uri https://pi.pardot.com/api/login/version/3?email=ss.jyj%s.co.uk&password=tyjt.09&user_key=yjty76&api_key=&format=json
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}
Authentication completed
key undefined
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}

var nodePardot = require('node-pardot');

    // Create client using email, password and user_key
    nodePardot.PardotAPI({
        userKey: 'fdgr',
        email: 'rg.gg@gg.co.uk',
        password: 'dfherg',
        DEBUG: true
    }, function(err, client) {
        // Authentication completed
        console.log('Authentication completed');

        // gets api key
        var api_key = api_key;
        console.log('key',api_key);
    });
</code>```

答:
It seems like you're trying to assign the value of an undeclared variable to itself in

```<code>var api_key = api_key;
</code>```

You should be assigning it the value in the response, i.e.

```<code>var api_key = client.api_key;
</code>```

Body:
I am new to node and am trying to using A node.js library for the Pardot API

This I pass my userKey, email and password to pardot, this returns my api_key.

I am using the following code to authenticate, then when I run my node server I can see the api_key being passed back.

how do I then store that api_key as a variable to then use to post data to the API?

my node code

var nodePardot = require('node-pardot');

// Create client using email, password and user_key
nodePardot.PardotAPI({
    userKey: 'kyujk',
    email: 'uu.uuy@uu.co.uk',
    password: 'uit.09',
    DEBUG: true
}, function(err, client) {
    // Authentication completed
    console.log('Authentication completed');

    // gets api key
    var api_key = api_key;
    console.log('key',api_key);
});

my console output

[nodemon] restarting due to changes...
[nodemon] starting `node index.js`
Server started! At http://localhost:8080
Initializing node-pardot in DEBUG mode
params {"email":"bhyuyten.jj@jyj.co.uk","password":"tyjt.09","user_key":"yjty76","format":"json"}
uri https://pi.pardot.com/api/login/version/3?email=ss.jyj%s.co.uk&password=tyjt.09&user_key=yjty76&api_key=&format=json
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}
Authentication completed
key undefined
parsedResponse {"@attributes":{"stat":"ok","version":1},"api_key":"878074492492dhjjk67u","version":4}

var nodePardot = require('node-pardot');

    // Create client using email, password and user_key
    nodePardot.PardotAPI({
        userKey: 'fdgr',
        email: 'rg.gg@gg.co.uk',
        password: 'dfherg',
        DEBUG: true
    }, function(err, client) {
        // Authentication completed
        console.log('Authentication completed');

        // gets api key
        var api_key = api_key;
        console.log('key',api_key);
    });

Body:
It seems like you're trying to assign the value of an undeclared variable to itself in

var api_key = api_key;

You should be assigning it the value in the response, i.e.

var api_key = client.api_key;


来源: stackexchange

问:
Can you create dictionaries with just a single function?
As a total beginner I'm quite proud of this function. Although I believe there's probably an easier, more pythonic way of doing the exact same thing:

```<code>Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def RawDict(keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    return zip(dictKeys, dictValues)

GenDict = dict(RawDict(Genes, Mutations))

print(GenDict)
</code>```

The function above is a rather overcomplicated (I think) way of putting several values (mutations) within keys (genes). However I was wondering if I could tweak this so I could get a dictionary by just doing this:

```<code>dict(GenDict, Genes, Mutations)

print(GenDict)
</code>```

My struggle involves that when I use dict within the function, this won't work:

```<code>Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def fullDict(dictName, keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    dictName = dict(RawDict(Genes, Mutations))

fullDict(GenDict, Genes, Mutations)

print(GenDict)
</code>```

The above just won't work as GenDict is not defined.

答:
I am assuming that you want the "Gen"s to be stored by the numerical value that it contains.

```<code>Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']
the_dict = {i:[] for i in Genes}

for i in Mutations:
    new_val = i.split(".")

   the_dict[new_val[0]].append(i)

print(the_dict)
</code>```

Output:

```<code>{'Gen2': ['Gen2.A'], 'Gen3': ['Gen3.A', 'Gen3.B', 'Gen3.C'], 'Gen1': ['Gen1.A', 'Gen1.B']}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
As a total beginner I'm quite proud of this function. Although I believe there's probably an easier, more pythonic way of doing the exact same thing:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def RawDict(keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    return zip(dictKeys, dictValues)

GenDict = dict(RawDict(Genes, Mutations))

print(GenDict)

The function above is a rather overcomplicated (I think) way of putting several values (mutations) within keys (genes). However I was wondering if I could tweak this so I could get a dictionary by just doing this:

dict(GenDict, Genes, Mutations)

print(GenDict)

My struggle involves that when I use dict within the function, this won't work:

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']

def fullDict(dictName, keys, values):
    dictKeys = []
    dictValues = []
    for key in keys:
        keyVal = []
        for value in values:
            if value.find(key) == -1:
                pass
            else:
                keyVal.append(value)
        dictKeys.append(key)
        dictValues.append(keyVal)
    dictName = dict(RawDict(Genes, Mutations))

fullDict(GenDict, Genes, Mutations)

print(GenDict)

The above just won't work as GenDict is not defined.

Body:
I am assuming that you want the "Gen"s to be stored by the numerical value that it contains.

Genes = ['Gen1', 'Gen2', 'Gen3']
Mutations = ['Gen1.A', 'Gen1.B', 'Gen2.A', 'Gen3.A', 'Gen3.B', 'Gen3.C']
the_dict = {i:[] for i in Genes}

for i in Mutations:
    new_val = i.split(".")

   the_dict[new_val[0]].append(i)

print(the_dict)

Output:

{'Gen2': ['Gen2.A'], 'Gen3': ['Gen3.A', 'Gen3.B', 'Gen3.C'], 'Gen1': ['Gen1.A', 'Gen1.B']}


问:
Merge two observables when Obs B depends on Obs A
I have two repository classes, repository A a List of Competitions as an Observable>.

My Competition class has a countryId.

I also have a repository B, which returns either a List of countries as an Observable> or a single country by Id as a Observable

I want to retrieve my list of competitions, and somehow merge it with their respective countries by returning a CountryCompetition class consisting of:

```<code>class CountryCompetition {
    public Country country;
    public Competition competition;
}
</code>```

This means combinining my competitionService.getCompetitions() with countryService.getCountry(competition.id), but I am not sure how to achieve this; merge or zip take an observable, and I dont have the ID of each country "yet".

```<code> mCompetitionService.getCompetitions(wrapSearch(constraint))
                .flatMap(new Func1<List<Competition>, Observable<Competition>>() {
                    @Override
                    public Observable<Competition> call(List<Competition> competitions) {
                        return Observable.from(competitions);
                    }
                })

                .map(new Func1<Competition, CountryCompetition>() {
                    @Override
                    public CountryCompetition call(Competition competition) {
                        CountryCompetition c = new CountryCompetition();
                        c.setCompetition(competition);
//Here i would like to set the Country as well, but mCountryService.getCountryById(competition.getCountryId()) returns another observable.
                        return c;
                    }
                })
                .toList()
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(mSchedulerProvider.ui())
                .subscribe(subscriber);
</code>```

答:
If I understand your problem correctly, you have two lists and you want to basically merge them. You may found my solution useful:

Model classes (for sake of simplicity constructors are not included):

```<code>class Country {
    String name;
    String id;
}

class Competition {
    String name;
    String countryId;
}

class CountryCompetition {
    public Country country;
    public Competition competition;
}
</code>```

Dummy data which follows your source Observable's definitions:

```<code>public Observable<List<Competition>> getCompetitions() {
    ArrayList<Competition> competitions = new ArrayList<>();
    competitions.add(new Competition("First", "id_0"));
    competitions.add(new Competition("Second", "id_1"));
    competitions.add(new Competition("Third", "id_1"));
    competitions.add(new Competition("Fourth", "id_2"));
    competitions.add(new Competition("Fifth", "id_3"));

    return Observable.just(competitions);
}

public Observable<List<Country>> getCountries() {
    ArrayList<Country> competitions = new ArrayList<>();
    competitions.add(new Country("Germany", "id_0"));
    competitions.add(new Country("Czech Republic", "id_1"));
    competitions.add(new Country("Slovakia", "id_2"));
    competitions.add(new Country("Poland", "id_3"));

    return Observable.just(competitions);
}
</code>```

And finally merge logic. I hope you're familiar with lambdas:

```<code>public void fun() {
    Observable.zip( // (1)
            getCompetitions(),
            getCountries(),
            Pair::create)
            .flatMap(pair -> getCompetitionsWithCountries(pair.first, pair.second)) // (2)
            .subscribeOn(Schedulers.immediate())
            .observeOn(Schedulers.immediate())
            .subscribe(countryCompetitions -> {
                for (CountryCompetition countryCompetition : countryCompetitions) {
                    System.out.print(countryCompetition.toString()); // (6)
                }
            });
}

public Observable<List<CountryCompetition>> getCompetitionsWithCountries(List<Competition> competitions, List<Country> countries) {
    return Observable.from(competitions) // (3)
            .map(competition -> {
                Country country = searchForCountry(countries, competition.countryId); // (4)
                return new CountryCompetition(country, competition);
            })
            .toList(); // (5)
}

public Country searchForCountry(List<Country> countries, String countryId) {
    for (Country country : countries) {
        if (country.id.equals(countryId)) {
            return country;
        }
    }

    throw new RuntimeException("Country not found");
}
</code>```

Explanation of interesting parts. :

zip() operator takes two observables and produces Pair of it's results. In this case, pair of two lists.

flatMap() operator takes this pair and returns new observable of type Observable<List<CountryCompetition>>

from() operator takes list of Competitions and emits every single Competition item separately to Rx chain.

Now we have single competition and list of countries, so we search for Country object based on countryId. Now we have both Competition and Country objects and we can map() them to new CountryCompetition object.

Pack all emitted CountryCompetition items back to the list.

Print results. Type of the object countryCompetitions is List<CountryCompetition>

Body:
I have two repository classes, repository A a List of Competitions as an Observable>.

My Competition class has a countryId.

I also have a repository B, which returns either a List of countries as an Observable> or a single country by Id as a Observable

I want to retrieve my list of competitions, and somehow merge it with their respective countries by returning a CountryCompetition class consisting of:

class CountryCompetition {
    public Country country;
    public Competition competition;
}

This means combinining my competitionService.getCompetitions() with countryService.getCountry(competition.id), but I am not sure how to achieve this; merge or zip take an observable, and I dont have the ID of each country "yet".

 mCompetitionService.getCompetitions(wrapSearch(constraint))
                .flatMap(new Func1<List<Competition>, Observable<Competition>>() {
                    @Override
                    public Observable<Competition> call(List<Competition> competitions) {
                        return Observable.from(competitions);
                    }
                })

                .map(new Func1<Competition, CountryCompetition>() {
                    @Override
                    public CountryCompetition call(Competition competition) {
                        CountryCompetition c = new CountryCompetition();
                        c.setCompetition(competition);
//Here i would like to set the Country as well, but mCountryService.getCountryById(competition.getCountryId()) returns another observable.
                        return c;
                    }
                })
                .toList()
                .subscribeOn(mSchedulerProvider.io())
                .observeOn(mSchedulerProvider.ui())
                .subscribe(subscriber);

Body:
If I understand your problem correctly, you have two lists and you want to basically merge them. You may found my solution useful:

Model classes (for sake of simplicity constructors are not included):

class Country {
    String name;
    String id;
}

class Competition {
    String name;
    String countryId;
}

class CountryCompetition {
    public Country country;
    public Competition competition;
}

Dummy data which follows your source Observable's definitions:

public Observable<List<Competition>> getCompetitions() {
    ArrayList<Competition> competitions = new ArrayList<>();
    competitions.add(new Competition("First", "id_0"));
    competitions.add(new Competition("Second", "id_1"));
    competitions.add(new Competition("Third", "id_1"));
    competitions.add(new Competition("Fourth", "id_2"));
    competitions.add(new Competition("Fifth", "id_3"));

    return Observable.just(competitions);
}

public Observable<List<Country>> getCountries() {
    ArrayList<Country> competitions = new ArrayList<>();
    competitions.add(new Country("Germany", "id_0"));
    competitions.add(new Country("Czech Republic", "id_1"));
    competitions.add(new Country("Slovakia", "id_2"));
    competitions.add(new Country("Poland", "id_3"));

    return Observable.just(competitions);
}

And finally merge logic. I hope you're familiar with lambdas:

public void fun() {
    Observable.zip( // (1)
            getCompetitions(),
            getCountries(),
            Pair::create)
            .flatMap(pair -> getCompetitionsWithCountries(pair.first, pair.second)) // (2)
            .subscribeOn(Schedulers.immediate())
            .observeOn(Schedulers.immediate())
            .subscribe(countryCompetitions -> {
                for (CountryCompetition countryCompetition : countryCompetitions) {
                    System.out.print(countryCompetition.toString()); // (6)
                }
            });
}

public Observable<List<CountryCompetition>> getCompetitionsWithCountries(List<Competition> competitions, List<Country> countries) {
    return Observable.from(competitions) // (3)
            .map(competition -> {
                Country country = searchForCountry(countries, competition.countryId); // (4)
                return new CountryCompetition(country, competition);
            })
            .toList(); // (5)
}

public Country searchForCountry(List<Country> countries, String countryId) {
    for (Country country : countries) {
        if (country.id.equals(countryId)) {
            return country;
        }
    }

    throw new RuntimeException("Country not found");
}

Explanation of interesting parts. :

zip() operator takes two observables and produces Pair of it's results. In this case, pair of two lists.

flatMap() operator takes this pair and returns new observable of type Observable<List<CountryCompetition>>

from() operator takes list of Competitions and emits every single Competition item separately to Rx chain.

Now we have single competition and list of countries, so we search for Country object based on countryId. Now we have both Competition and Country objects and we can map() them to new CountryCompetition object.

Pack all emitted CountryCompetition items back to the list.

Print results. Type of the object countryCompetitions is List<CountryCompetition>


问:
Read Multiple Byte Arrays from File
How can I read multiple byte arrays from a file?  These byte arrays are images and have the potential to be large.

This is how I'm adding them to the file:

```<code> using (var stream = new FileStream(tempFile, FileMode.Append))
      {
        //convertedImage = one byte array
        stream.Write(convertedImage, 0, convertedImage.Length);
      }
</code>```

So, now they're in tempFile and I don't know how to retrieve them as individual arrays.  Ideally, I'd like to get them as an IEnumerable<byte[]>.  Is there a way to split these, maybe?

答:
When you read back how do you get the number of bytes per image/byte array to read?

You will need to store the length too (i.e. first 4 bytes = encoded 32 bit int byte count, followed by the data bytes.)

To read back, read the first four bytes, un-encode it back to an int, and then read that number of bytes, repeat until eof.

Title: Read Multiple Byte Arrays from File

Body:
How can I read multiple byte arrays from a file?  These byte arrays are images and have the potential to be large.

This is how I'm adding them to the file:

 using (var stream = new FileStream(tempFile, FileMode.Append))
      {
        //convertedImage = one byte array
        stream.Write(convertedImage, 0, convertedImage.Length);
      }

So, now they're in tempFile and I don't know how to retrieve them as individual arrays.  Ideally, I'd like to get them as an IEnumerable<byte[]>.  Is there a way to split these, maybe?


问:
Trying to make my 2D character double jump - it's not working and I don't know why?
I'm making a 2D platformer. Here's my code so far. The character jumps only when touching the ground as it should - but the code for double jumping doesn't work. Any help is appreciated. I'm new at scripting and I don't understand what I did wrong?</p>

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

public class PlayerController : MonoBehaviour {

    public float speed = 12f, jumpHeight = 30f;
    Rigidbody2D playerBody;
    Transform playerTrans, tagGround;
    bool isGrounded = false;
    public LayerMask playerMask;
    public float maxJumps = 2;
    public float jumpsLeft = 2;

    // Use this for initialization
    void Start ()
    {
        playerBody = this.GetComponent<Rigidbody2D>();
        playerTrans = this.transform;
        tagGround = GameObject.Find(this.name + "/tag_Ground").transform;

    }

    // Update is called once per frame
    public void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast(playerTrans.position, tagGround.position, playerMask);
        Move();
        Jump();
        DoubleJump();

    }

    private void Move()
    {
        float move = Input.GetAxisRaw("Horizontal") * speed;
        playerBody.velocity = new Vector2(move, playerBody.velocity.y);
    }

    private void Jump()

    {
        if (isGrounded)
        {

            if (Input.GetButtonDown("Jump"))
            {
                playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);

            }

        }

    }
    private void DoubleJump()
    {
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0)
        {
            Jump();
            jumpsLeft--;
        }

        if (isGrounded)
        {
            jumpsLeft = maxJumps;
        }
    }
}
</code>```

答:
Your code doesn't make much sense. You should handle your jumping in one method and handle it something like this:

```<code>private void HandleJump()
{
    if(isGrounded) {
        jumpsLeft = maxJumps;
    }

    if(Input.GetButtonDown("Jump") && jumpsLeft > 0) {
        playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
        jumpsLeft--;
    }
}
</code>```

This way you can make triple jumps or however many jumps you want.

Body:
I'm making a 2D platformer. Here's my code so far. The character jumps only when touching the ground as it should - but the code for double jumping doesn't work. Any help is appreciated. I'm new at scripting and I don't understand what I did wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float speed = 12f, jumpHeight = 30f;
    Rigidbody2D playerBody;
    Transform playerTrans, tagGround;
    bool isGrounded = false;
    public LayerMask playerMask;
    public float maxJumps = 2;
    public float jumpsLeft = 2;

    // Use this for initialization
    void Start ()
    {
        playerBody = this.GetComponent<Rigidbody2D>();
        playerTrans = this.transform;
        tagGround = GameObject.Find(this.name + "/tag_Ground").transform;

    }

    // Update is called once per frame
    public void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast(playerTrans.position, tagGround.position, playerMask);
        Move();
        Jump();
        DoubleJump();

    }

    private void Move()
    {
        float move = Input.GetAxisRaw("Horizontal") * speed;
        playerBody.velocity = new Vector2(move, playerBody.velocity.y);
    }

    private void Jump()

    {
        if (isGrounded)
        {

            if (Input.GetButtonDown("Jump"))
            {
                playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);

            }

        }

    }
    private void DoubleJump()
    {
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0)
        {
            Jump();
            jumpsLeft--;
        }

        if (isGrounded)
        {
            jumpsLeft = maxJumps;
        }
    }
}

Body:
Your code doesn't make much sense. You should handle your jumping in one method and handle it something like this:

private void HandleJump()
{
    if(isGrounded) {
        jumpsLeft = maxJumps;
    }

    if(Input.GetButtonDown("Jump") && jumpsLeft > 0) {
        playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
        jumpsLeft--;
    }
}

This way you can make triple jumps or however many jumps you want.


问:
Working with linked list + struct C
Here is the linked list and the struct:

```<code>#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
struct Frame
{
    char *name;
    unsigned int duration;
    char *path;  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;
</code>```

And here's my function:

```<code>link_t* createFrame(char name[], int duration, char path[]){
frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
temp->duration = duration;

strncpy(temp->name, name,MAX_NAME_SIZE);
strncpy(temp->path, path,MAX_PATH_SIZE);
link_t* newFrame = (link_t*)malloc(sizeof(link_t));

newFrame->frame = temp;
return newFrame;
}
</code>```

The problem is that the function stop working in the line "strncpy(temp->name)..", the weird thing is that the temp->duration is working but it doesn't work with strings. Error: "Unhandled exception at 0x0F744645 (msvcr120d.dll)"

答:
You didn't allocate memory for your name, now they point to unknown location and is undefined behaviour.

```<code>temp->name = malloc((MAX_NAME_SIZE + 1) * sizeof(*temp->name));
temp->path = malloc((MAX_PATH_SIZE + 1) * sizeof(*temp->path));
temp->name[MAX_NAME_SIZE] = 0; //Manually add null termination
temp->name[MAX_PATH_SIZE] = 0; //Manually add null termination
strncpy(temp->name, name,MAX_NAME_SIZE);
</code>```

Now, memory is allocated for name and path and you are able to copy data for name and path.

Or, if you want, you can define your structure like this:

```<code>struct Frame {
    char name[MAX_NAME_SIZE + 1];
    unsigned int duration;
    char path[MAX_PATH_SIZE + 1];
};
</code>```

Then you won't need to call malloc for name and path separatelly as memory will be allocated on first malloc for structure already.

Title: Working with linked list + struct C

Body:
Here is the linked list and the struct:

#define MAX_PATH_SIZE (256)
#define MAX_NAME_SIZE (50)
struct Frame
{
    char *name;
    unsigned int duration;
    char *path;  // may change to FILE*
};

typedef struct Frame frame_t;
struct Link
{
    frame_t *frame;
    struct Link *next;
};

typedef struct Link link_t;

And here's my function:

link_t* createFrame(char name[], int duration, char path[]){
frame_t * temp = (frame_t*)malloc(sizeof(frame_t));
temp->duration = duration;

strncpy(temp->name, name,MAX_NAME_SIZE);
strncpy(temp->path, path,MAX_PATH_SIZE);
link_t* newFrame = (link_t*)malloc(sizeof(link_t));

newFrame->frame = temp;
return newFrame;
}

The problem is that the function stop working in the line "strncpy(temp->name)..", the weird thing is that the temp->duration is working but it doesn't work with strings. Error: "Unhandled exception at 0x0F744645 (msvcr120d.dll)"

Body:
You didn't allocate memory for your name, now they point to unknown location and is undefined behaviour.

temp->name = malloc((MAX_NAME_SIZE + 1) * sizeof(*temp->name));
temp->path = malloc((MAX_PATH_SIZE + 1) * sizeof(*temp->path));
temp->name[MAX_NAME_SIZE] = 0; //Manually add null termination
temp->name[MAX_PATH_SIZE] = 0; //Manually add null termination
strncpy(temp->name, name,MAX_NAME_SIZE);

Now, memory is allocated for name and path and you are able to copy data for name and path.

Or, if you want, you can define your structure like this:

struct Frame {
    char name[MAX_NAME_SIZE + 1];
    unsigned int duration;
    char path[MAX_PATH_SIZE + 1];
};

Then you won't need to call malloc for name and path separatelly as memory will be allocated on first malloc for structure already.


问:
Can I use localStorage to create a permanent database?
I'm currently learning about hybrid app development on my own. I need to create a local database on the phone in order to save some information, however, I don't know much about storage.

I've seen HTML5 Local Storage (https://www.w3schools.com/html/html5_webstorage.asp), and it's easy and confortable to apply, but I don't know if this kind of storage will be permanent on a hybrid app when the phone turns off or when the app closes.

Can you, please, help me with this doubt?

Thank you!

答: I recently started using Realm. I find it very useful and pretty easy to use. It's a local database that persists until you uninstall the app.</p>


问:
Getting mysql_affected_rows() expects parameter 1 to be resource, boolean given - Yet query inserts into database succesfully - What gives?
This problem has me stumped.  I get this error even though the when I check the database in phpmyadmin the query successfully inserts into the database.  So I know the query goes through and is not false.  What I'm trying to do is register a user, and if there is a result returned - return that to be checked true or false i.e. if result exist then continue.  The code in my class;

```<code>class registerUser {

    function register($email,$password) {
        $query = "insert into users(email,password) values('".$email."','".$password."')";
        $result = mysql_query($query) or die("Could not enter the user into the database".mysql_error());

        return mysql_affected_rows($result);
    }

    function checkPasswords($password1,$password2) {
        if($password1 == $password2) {
            return true;
        }
        else {
            return false;
        }
    }
}
</code>```

The file that uses the class:

```<code>include('../data/connection.php');
include('../data/registerUser.php');

$connect = new connection();
$connect->connect($con, $db);
$register = new registerUser();
$checkPass = $register->checkPasswords($_POST['regpass'],$_POST['confirm']);

if($checkPass) {
    $reg = $register->register($_POST['regemail'],$_POST['regpass']);
        if($reg) {
            session_start();
            $_SESSION['id'] = $_POST['email'];
            $connect->close($con);
            header("Location:dashboard.php");
        } else  {
           // Failure - message
            echo "Registration not successful, contact Administrator";
        }
} else {
    echo "Passwords do not match";
}
</code>```

It seems like it never gets past the register function in registerUser and executes the die message in the mysql_query, yet the insert is successful when checked in phpMyAdmin.  What am I doing wrong?  Any help much appreciated!!

答: Try to pass the connection variable like mysqli_affected_rows($conn);    here $conn is my connection variable</p>

Body:
This problem has me stumped.  I get this error even though the when I check the database in phpmyadmin the query successfully inserts into the database.  So I know the query goes through and is not false.  What I'm trying to do is register a user, and if there is a result returned - return that to be checked true or false i.e. if result exist then continue.  The code in my class;

class registerUser {

    function register($email,$password) {
        $query = "insert into users(email,password) values('".$email."','".$password."')";
        $result = mysql_query($query) or die("Could not enter the user into the database".mysql_error());

        return mysql_affected_rows($result);
    }

    function checkPasswords($password1,$password2) {
        if($password1 == $password2) {
            return true;
        }
        else {
            return false;
        }
    }
}

The file that uses the class:

include('../data/connection.php');
include('../data/registerUser.php');

$connect = new connection();
$connect->connect($con, $db);
$register = new registerUser();
$checkPass = $register->checkPasswords($_POST['regpass'],$_POST['confirm']);

if($checkPass) {
    $reg = $register->register($_POST['regemail'],$_POST['regpass']);
        if($reg) {
            session_start();
            $_SESSION['id'] = $_POST['email'];
            $connect->close($con);
            header("Location:dashboard.php");
        } else  {
           // Failure - message
            echo "Registration not successful, contact Administrator";
        }
} else {
    echo "Passwords do not match";
}

It seems like it never gets past the register function in registerUser and executes the die message in the mysql_query, yet the insert is successful when checked in phpMyAdmin.  What am I doing wrong?  Any help much appreciated!!


问:
MVC Model Binding Complex Type to Action Parameter
I'm binding a list of customers into a customer search results page using the model binding of MVC3, and using Razor to render all the customers in a foreach loop.  My question is how then to send back the customer object to the action to save me having to fetch the details again.

Below is my action method signature:

```<code>public ActionResult BasketAddCustomer(Customer customer)
</code>```

The Customer object is quite large, ie. lots of fields

Below is a cut down version of the view which renders each customer and has the button to select each one.

```<code>@model WebUI.Models.SearchModel
@foreach (var customer in Model.Customers)
    {
                <h5>@customer.FirstName @customer.LastName</h5>
                <button onclick="window.location.href = '@Url.Action("BasketAddCustomer", "Cust", customer)';">Select customer</button>
    }
</code>```

The problem with this is that the customer that is passed into the action seems to come through as being full of nulls.

The html that is rendered by the @URL.Action is below and looks like a good start but only has some of the customer fields, not all.  Is the Customer just too complex for being broken down this way? Is there a better way to do it?

```<code><button onclick="window.location.href =
'/Test/Cust/BasketAddCustomer?BirthDate=01%2F01%2F0001%2000%3A00%3A00&PrimaryEmailFlag=False&PrimaryEmailDate=01%2F01%2F0001%2000%3A00%3A00&PrimaryEmailID=0&PrimaryPhoneFlag=False&PrimaryPhoneDate=01%2F01%2F0001%2000%3A00%3A00&PrimaryPhoneID=0&WifiConnected=False';" >Select customer</button>
</code>```

答:
As per my knowledge with @url.action  we can only send route values and couldn't send the object itself.

Kindly refer this link: https://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper.action(v=vs.118).aspx

So for your problem, you can send any unique value to the controller action as a route parameter in url.helper and get the entire object from the database using linq query in action  .

Note : if your requirement says that , you should send the object only, then you can put all the controls inside the form in the view and  send it as post method.

Hope above information was helpful.

Thanks

Karthik

Body:
I'm binding a list of customers into a customer search results page using the model binding of MVC3, and using Razor to render all the customers in a foreach loop.  My question is how then to send back the customer object to the action to save me having to fetch the details again.

Below is my action method signature:

public ActionResult BasketAddCustomer(Customer customer)

The Customer object is quite large, ie. lots of fields

Below is a cut down version of the view which renders each customer and has the button to select each one.

@model WebUI.Models.SearchModel
@foreach (var customer in Model.Customers)
    {

@customer.FirstName @customer.LastName

                <button onclick="window.location.href = '@Url.Action("BasketAddCustomer", "Cust", customer)';">Select customer</button>
    }

The problem with this is that the customer that is passed into the action seems to come through as being full of nulls.

The html that is rendered by the @URL.Action is below and looks like a good start but only has some of the customer fields, not all.  Is the Customer just too complex for being broken down this way? Is there a better way to do it?

<button onclick="window.location.href =
'/Test/Cust/BasketAddCustomer?BirthDate=01%2F01%2F0001%2000%3A00%3A00&PrimaryEmailFlag=False&PrimaryEmailDate=01%2F01%2F0001%2000%3A00%3A00&PrimaryEmailID=0&PrimaryPhoneFlag=False&PrimaryPhoneDate=01%2F01%2F0001%2000%3A00%3A00&PrimaryPhoneID=0&WifiConnected=False';" >Select customer</button>


问:
Troubleshooting R mapper script on Amazon Elastic MapReduce - Results not as expected
I am trying to use Amazon Elastic Map Reduce to run a series of simulations of several million cases. This is an Rscript streaming job with no reducer. I am using the Identity Reducer in my EMR call --reducer org.apache.hadoop.mapred.lib.IdentityReducer.

The script file works fine when tested and run locally from the command line on a Linux box when passing one line of string manually echo "1,2443,2442,1,5" | ./mapper.R and I get the one line of results that I am expecting. However, when I tested my simulation using about 10,000 cases (lines) from the input file on EMR, I only got output for a dozen lines or so out of 10k input lines. I've tried several times and I cannot figure out why. The Hadoop job runs fine without any errors. It seems like input lines are being skipped, or perhaps something is happening with the Identity reducer. The results are correct for the cases where there is output.

My input file is a csv with the following data format, a series of five integers separated by commas:

```<code>1,2443,2442,1,5
2,2743,4712,99,8
3,2443,861,282,3177
etc...
</code>```

Here is my R script for mapper.R

```<code>#! /usr/bin/env Rscript

# Define Functions
trimWhiteSpace <- function(line) gsub("(^ +)|( +$)", "", line)
splitIntoWords <- function(line) unlist(strsplit(line, "[[:space:]]+"))
# function to read in the relevant data from needed data files
get.data <- function(casename) {
    list <- lapply(casename, function(x) {
        read.csv(file = paste("./inputdata/",x, ".csv", sep = ""),
                 header = TRUE,
        stringsAsFactors = FALSE)})
    return(data.frame(list))
}

con <- file("stdin")
line <- readLines(con, n = 1, warn = FALSE)
line <- trimWhiteSpace(line)
values <- unlist(strsplit(line, ","))
lv <- length(values)
cases <- as.numeric(values[2:lv])
simid <- paste("sim", values[1], ":", sep = "")
l <- length(cases)                      # for indexing

## create a vector for the case names
names.vector <- paste("case", cases, sep = ".")

## read in metadata and necessary data columns using get.data function
metadata <- read.csv(file = "./inputdata/metadata.csv", header = TRUE,
                     stringsAsFactors = FALSE)
d <- cbind(metadata[,1:3], get.data(names.vector))

## Calculations that use df d and produce a string called 'output'
## in the form of "id: value1 value2 value3 ..." to be used at a
## later time for agregation.

cat(output, "\n")
close(con)
</code>```

The (generalized) EMR call for this simulation is:

```<code>ruby elastic-mapreduce --create --stream --input s3n://bucket/project/input.txt --output s3n://bucket/project/output --mapper s3n://bucket/project/mapper.R --reducer org.apache.hadoop.mapred.lib.IdentityReducer --cache-archive s3n://bucket/project/inputdata.tar.gz#inputdata --name Simulation --num-instances 2
</code>```

If anyone has any insights as to why I might be experiencing these issues, I am open to suggestions, as well as any changes/optimization to the R script.

My other option is to turn the script into a function and run a parallelized apply using R multicore packages, but I haven't tried it yet. I'd like to get this working on EMR. I used JD Long's and Pete Skomoroch's R/EMR examples as a basis for creating the script.

答:
Nothing obvious jumps out. However, can you run the job using a simple input file of only 10 lines? Make sure these 10 lines are scenarios which did not run in your big test case. Try this to eliminate the possibility that your inputs are causing the R script to not produce an answer.

Debugging EMR jobs is a skill of its own.

EDIT:

This is a total fishing expedition, but fire up a EMR interactive pig session using the AWS GUI. "Interactive pig" sessions stay up and running so you can ssh into them. You could also do this from the command line tools, but it's a little easier from the GUI since, hopefully, you only need to do this once. Then ssh into the cluster, transfer over your test case infile your cachefiles and your mapper and then run this:

cat infile.txt | yourMapper.R  > outfile.txt

This is just to test if your mapper can parse the infile in the EMR environment with no Hadoop bits in the way.

EDIT 2:

I'm leaving the above text there for posterity but the real issue is your script never goes back to stdin to pick up more data. Thus you get one run for each mapper then it ends. If you run the above one liner you will only get out one result, not a result for each line in infile.txt. If you had run the cat test even on your local machine the error should pop out!

So let's look at Pete's word count in R example:

```<code>#! /usr/bin/env Rscript

trimWhiteSpace <- function(line) gsub("(^ +)|( +$)", "", line)
splitIntoWords <- function(line) unlist(strsplit(line, "[[:space:]]+"))

## **** could wo with a single readLines or in blocks
con <- file("stdin", open = "r")
while (length(line <- readLines(con, n = 1, warn = FALSE)) > 0) {
    line <- trimWhiteSpace(line)
    words <- splitIntoWords(line)
    ## **** can be done as cat(paste(words, "\t1\n", sep=""), sep="")
    for (w in words)
        cat(w, "\t1\n", sep="")
}
close(con)
</code>```

The piece your script is missing is this bit:

```<code> while (length(line <- readLines(con, n = 1, warn = FALSE)) > 0) {
        #do your dance
        #do your dance quick
        #come on everybody tell me what's the word
        #word up
    }
</code>```

you should, naturally, replace the lyrics of Cameo's Word Up! with your actual logic.

Keep in mind that proper debugging music makes the process less painful:

http://www.youtube.com/watch?v=MZjAantupsA

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use Amazon Elastic Map Reduce to run a series of simulations of several million cases. This is an Rscript streaming job with no reducer. I am using the Identity Reducer in my EMR call --reducer org.apache.hadoop.mapred.lib.IdentityReducer.

The script file works fine when tested and run locally from the command line on a Linux box when passing one line of string manually echo "1,2443,2442,1,5" | ./mapper.R and I get the one line of results that I am expecting. However, when I tested my simulation using about 10,000 cases (lines) from the input file on EMR, I only got output for a dozen lines or so out of 10k input lines. I've tried several times and I cannot figure out why. The Hadoop job runs fine without any errors. It seems like input lines are being skipped, or perhaps something is happening with the Identity reducer. The results are correct for the cases where there is output.

My input file is a csv with the following data format, a series of five integers separated by commas:

1,2443,2442,1,5
2,2743,4712,99,8
3,2443,861,282,3177
etc...

Here is my R script for mapper.R

#! /usr/bin/env Rscript

# Define Functions
trimWhiteSpace <- function(line) gsub("(^ +)|( +$)", "", line)
splitIntoWords <- function(line) unlist(strsplit(line, "[[:space:]]+"))
# function to read in the relevant data from needed data files
get.data <- function(casename) {
    list <- lapply(casename, function(x) {
        read.csv(file = paste("./inputdata/",x, ".csv", sep = ""),
                 header = TRUE,
        stringsAsFactors = FALSE)})
    return(data.frame(list))
}

con <- file("stdin")
line <- readLines(con, n = 1, warn = FALSE)
line <- trimWhiteSpace(line)
values <- unlist(strsplit(line, ","))
lv <- length(values)
cases <- as.numeric(values[2:lv])
simid <- paste("sim", values[1], ":", sep = "")
l <- length(cases)                      # for indexing

## create a vector for the case names
names.vector <- paste("case", cases, sep = ".")

## read in metadata and necessary data columns using get.data function
metadata <- read.csv(file = "./inputdata/metadata.csv", header = TRUE,
                     stringsAsFactors = FALSE)
d <- cbind(metadata[,1:3], get.data(names.vector))

## Calculations that use df d and produce a string called 'output'
## in the form of "id: value1 value2 value3 ..." to be used at a
## later time for agregation.

cat(output, "\n")
close(con)

The (generalized) EMR call for this simulation is:

ruby elastic-mapreduce --create --stream --input s3n://bucket/project/input.txt --output s3n://bucket/project/output --mapper s3n://bucket/project/mapper.R --reducer org.apache.hadoop.mapred.lib.IdentityReducer --cache-archive s3n://bucket/project/inputdata.tar.gz#inputdata --name Simulation --num-instances 2

If anyone has any insights as to why I might be experiencing these issues, I am open to suggestions, as well as any changes/optimization to the R script.

My other option is to turn the script into a function and run a parallelized apply using R multicore packages, but I haven't tried it yet. I'd like to get this working on EMR. I used JD Long's and Pete Skomoroch's R/EMR examples as a basis for creating the script.

Body:
Nothing obvious jumps out. However, can you run the job using a simple input file of only 10 lines? Make sure these 10 lines are scenarios which did not run in your big test case. Try this to eliminate the possibility that your inputs are causing the R script to not produce an answer.

Debugging EMR jobs is a skill of its own.

EDIT:

This is a total fishing expedition, but fire up a EMR interactive pig session using the AWS GUI. "Interactive pig" sessions stay up and running so you can ssh into them. You could also do this from the command line tools, but it's a little easier from the GUI since, hopefully, you only need to do this once. Then ssh into the cluster, transfer over your test case infile your cachefiles and your mapper and then run this:

cat infile.txt | yourMapper.R  > outfile.txt

This is just to test if your mapper can parse the infile in the EMR environment with no Hadoop bits in the way.

EDIT 2:

I'm leaving the above text there for posterity but the real issue is your script never goes back to stdin to pick up more data. Thus you get one run for each mapper then it ends. If you run the above one liner you will only get out one result, not a result for each line in infile.txt. If you had run the cat test even on your local machine the error should pop out!

So let's look at Pete's word count in R example:

#! /usr/bin/env Rscript

trimWhiteSpace <- function(line) gsub("(^ +)|( +$)", "", line)
splitIntoWords <- function(line) unlist(strsplit(line, "[[:space:]]+"))

## **** could wo with a single readLines or in blocks
con <- file("stdin", open = "r")
while (length(line <- readLines(con, n = 1, warn = FALSE)) > 0) {
    line <- trimWhiteSpace(line)
    words <- splitIntoWords(line)
    ## **** can be done as cat(paste(words, "\t1\n", sep=""), sep="")
    for (w in words)
        cat(w, "\t1\n", sep="")
}
close(con)

The piece your script is missing is this bit:

 while (length(line <- readLines(con, n = 1, warn = FALSE)) > 0) {
        #do your dance
        #do your dance quick
        #come on everybody tell me what's the word
        #word up
    }

you should, naturally, replace the lyrics of Cameo's Word Up! with your actual logic.

Keep in mind that proper debugging music makes the process less painful:

http://www.youtube.com/watch?v=MZjAantupsA


问:
Writing Python bindings for C++ code that use OpenCV
I'm trying to write a python wrapper for some C++ code that make use of OpenCV but I'm having difficulties returning the result, which is a OpenCV C++ Mat object, to the python interpreter.

I've looked at OpenCV's source and found the file cv2.cpp which has conversions functions to perform conversions to and fro between PyObject* and OpenCV's Mat. I made use of those conversions functions but got a segmentation fault when I tried to use them.

I basically need some suggestions/sample code/online references on how to interface python and C++ code that make use of OpenCV, specifically with the ability to return OpenCV's C++ Mat to the python interpreter or perhaps suggestions on how/where to start investigating the cause of the segmentation fault.

Currently I'm using Boost Python to wrap the code.

Thanks in advance to any replies.

The relevant code:

```<code>// This is the function that is giving the segmentation fault.
PyObject* ABC::doSomething(PyObject* image)
{
    Mat m;
    pyopencv_to(image, m);  // This line gives segmentation fault.

    // Some code to create cppObj from CPP library that uses OpenCV
    cv::Mat processedImage = cppObj->align(m);

    return pyopencv_from(processedImage);
}
</code>```

The conversion functions taken from OpenCV's source follows. The conversion code gives segmentation fault at the commented line with "if (!PyArray_Check(o)) ...".

```<code>static int pyopencv_to(const PyObject* o, Mat& m, const char* name = "<unknown>", bool allowND=true)
{
    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }

    if( !PyArray_Check(o) ) // Segmentation fault inside PyArray_Check(o)
    {
        failmsg("%s is not a numpy array", name);
        return false;
    }

    int typenum = PyArray_TYPE(o);
    int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S :
               typenum == NPY_INT || typenum == NPY_LONG ? CV_32S :
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;

    if( type < 0 )
    {
        failmsg("%s data type = %d is not supported", name, typenum);
        return false;
    }

    int ndims = PyArray_NDIM(o);
    if(ndims >= CV_MAX_DIM)
    {
        failmsg("%s dimensionality (=%d) is too high", name, ndims);
        return false;
    }

    int size[CV_MAX_DIM+1];
    size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(o);
    const npy_intp* _strides = PyArray_STRIDES(o);
    bool transposed = false;

    for(int i = 0; i < ndims; i++)
    {
        size[i] = (int)_sizes[i];
        step[i] = (size_t)_strides[i];
    }

    if( ndims == 0 || step[ndims-1] > elemsize ) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if( ndims >= 2 && step[0] < step[1] )
    {
        std::swap(size[0], size[1]);
        std::swap(step[0], step[1]);
        transposed = true;
    }

    if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] )
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if( ndims > 2 && !allowND )
    {
        failmsg("%s has more than 2 dimensions", name);
        return false;
    }

    m = Mat(ndims, size, type, PyArray_DATA(o), step);

    if( m.data )
    {
        m.refcount = refcountFromPyObject(o);
        m.addref(); // protect the original numpy array from deallocation
                    // (since Mat destructor will decrement the reference counter)
    };
    m.allocator = &g_numpyAllocator;

    if( transposed )
    {
        Mat tmp;
        tmp.allocator = &g_numpyAllocator;
        transpose(m, tmp);
        m = tmp;
    }
    return true;
}

static PyObject* pyopencv_from(const Mat& m)
{
    if( !m.data )
        Py_RETURN_NONE;
    Mat temp, *p = (Mat*)&m;
    if(!p->refcount || p->allocator != &g_numpyAllocator)
    {
        temp.allocator = &g_numpyAllocator;
        m.copyTo(temp);
        p = &temp;
    }
    p->addref();
    return pyObjectFromRefcount(p->refcount);
}
</code>```

My python test program:

```<code>import pysomemodule # My python wrapped library.
import cv2

def main():
    myobj = pysomemodule.ABC("faces.train") # Create python object. This works.
    image = cv2.imread('61.jpg')
    processedImage = myobj.doSomething(image)
    cv2.imshow("test", processedImage)
    cv2.waitKey()

if __name__ == "__main__":
    main()
</code>```

答:
One option is to implement your code directly into modules/python/src2/cv2.cpp as a custom branch of the python bindings. </p>

<p>'OpenCV build system will bundle it into single "cv2". Examples of contributed modules are here.' https://github.com/opencv/opencv/issues/8872#issuecomment-307136942</p>

Body:
I'm trying to write a python wrapper for some C++ code that make use of OpenCV but I'm having difficulties returning the result, which is a OpenCV C++ Mat object, to the python interpreter.

I've looked at OpenCV's source and found the file cv2.cpp which has conversions functions to perform conversions to and fro between PyObject* and OpenCV's Mat. I made use of those conversions functions but got a segmentation fault when I tried to use them.

I basically need some suggestions/sample code/online references on how to interface python and C++ code that make use of OpenCV, specifically with the ability to return OpenCV's C++ Mat to the python interpreter or perhaps suggestions on how/where to start investigating the cause of the segmentation fault.

Currently I'm using Boost Python to wrap the code.

Thanks in advance to any replies.

The relevant code:

// This is the function that is giving the segmentation fault.
PyObject* ABC::doSomething(PyObject* image)
{
    Mat m;
    pyopencv_to(image, m);  // This line gives segmentation fault.

    // Some code to create cppObj from CPP library that uses OpenCV
    cv::Mat processedImage = cppObj->align(m);

    return pyopencv_from(processedImage);
}

The conversion functions taken from OpenCV's source follows. The conversion code gives segmentation fault at the commented line with "if (!PyArray_Check(o)) ...".

static int pyopencv_to(const PyObject* o, Mat& m, const char* name = "<unknown>", bool allowND=true)
{
    if(!o || o == Py_None)
    {
        if( !m.data )
            m.allocator = &g_numpyAllocator;
        return true;
    }

    if( !PyArray_Check(o) ) // Segmentation fault inside PyArray_Check(o)
    {
        failmsg("%s is not a numpy array", name);
        return false;
    }

    int typenum = PyArray_TYPE(o);
    int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S :
               typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S :
               typenum == NPY_INT || typenum == NPY_LONG ? CV_32S :
               typenum == NPY_FLOAT ? CV_32F :
               typenum == NPY_DOUBLE ? CV_64F : -1;

    if( type < 0 )
    {
        failmsg("%s data type = %d is not supported", name, typenum);
        return false;
    }

    int ndims = PyArray_NDIM(o);
    if(ndims >= CV_MAX_DIM)
    {
        failmsg("%s dimensionality (=%d) is too high", name, ndims);
        return false;
    }

    int size[CV_MAX_DIM+1];
    size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type);
    const npy_intp* _sizes = PyArray_DIMS(o);
    const npy_intp* _strides = PyArray_STRIDES(o);
    bool transposed = false;

    for(int i = 0; i < ndims; i++)
    {
        size[i] = (int)_sizes[i];
        step[i] = (size_t)_strides[i];
    }

    if( ndims == 0 || step[ndims-1] > elemsize ) {
        size[ndims] = 1;
        step[ndims] = elemsize;
        ndims++;
    }

    if( ndims >= 2 && step[0] < step[1] )
    {
        std::swap(size[0], size[1]);
        std::swap(step[0], step[1]);
        transposed = true;
    }

    if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] )
    {
        ndims--;
        type |= CV_MAKETYPE(0, size[2]);
    }

    if( ndims > 2 && !allowND )
    {
        failmsg("%s has more than 2 dimensions", name);
        return false;
    }

    m = Mat(ndims, size, type, PyArray_DATA(o), step);

    if( m.data )
    {
        m.refcount = refcountFromPyObject(o);
        m.addref(); // protect the original numpy array from deallocation
                    // (since Mat destructor will decrement the reference counter)
    };
    m.allocator = &g_numpyAllocator;

    if( transposed )
    {
        Mat tmp;
        tmp.allocator = &g_numpyAllocator;
        transpose(m, tmp);
        m = tmp;
    }
    return true;
}

static PyObject* pyopencv_from(const Mat& m)
{
    if( !m.data )
        Py_RETURN_NONE;
    Mat temp, *p = (Mat*)&m;
    if(!p->refcount || p->allocator != &g_numpyAllocator)
    {
        temp.allocator = &g_numpyAllocator;
        m.copyTo(temp);
        p = &temp;
    }
    p->addref();
    return pyObjectFromRefcount(p->refcount);
}

My python test program:

import pysomemodule # My python wrapped library.
import cv2

def main():
    myobj = pysomemodule.ABC("faces.train") # Create python object. This works.
    image = cv2.imread('61.jpg')
    processedImage = myobj.doSomething(image)
    cv2.imshow("test", processedImage)
    cv2.waitKey()

if __name__ == "__main__":
    main()

Body:
One option is to implement your code directly into modules/python/src2/cv2.cpp as a custom branch of the python bindings.

'OpenCV build system will bundle it into single "cv2". Examples of contributed modules are here.' https://github.com/opencv/opencv/issues/8872#issuecomment-307136942


问:
VBA - calculate and print answer for many rows
I am still new to vba and am writing a macro to calculate the time between two dates in two columns using dateDiff then print the difference in the cell next to it. i would also like do use a do until empty

Column A holds the start date
Column B holds the end date
Column C will hold the answer

i have some useful code but most of it is written to understand the goal of the macro and needs changed.

```<code>Range("A2").Select
Do Until IsEmpty(ActiveCell)
 For i = 2 To 25
  date1 = ["A" & i]
  date2 = ["B" & i]
  answer = DateDiff("n", date1, date2)
  "C" & i = answer
 next i
Loop
</code>```

I appreciate any help!

答:
Without knowing the details of the format for dating, and assuming contiguous data, I would recommend the following:

```<code>Dim LR as Long
LR=Cells(.Rows.Count, "A").End(xlUp).Row
Sheets("NAME").Range("C1:C"&LR).Formula="=B1-A1"
</code>```

Hopefully that helps!

Edited per Scott's comment.

Body:
I am still new to vba and am writing a macro to calculate the time between two dates in two columns using dateDiff then print the difference in the cell next to it. i would also like do use a do until empty

Column A holds the start date
Column B holds the end date
Column C will hold the answer

i have some useful code but most of it is written to understand the goal of the macro and needs changed.

Range("A2").Select
Do Until IsEmpty(ActiveCell)
 For i = 2 To 25
  date1 = ["A" & i]
  date2 = ["B" & i]
  answer = DateDiff("n", date1, date2)
  "C" & i = answer
 next i
Loop

I appreciate any help!

Body:
Without knowing the details of the format for dating, and assuming contiguous data, I would recommend the following:

Dim LR as Long
LR=Cells(.Rows.Count, "A").End(xlUp).Row
Sheets("NAME").Range("C1:C"&LR).Formula="=B1-A1"

Hopefully that helps!

Edited per Scott's comment.


问:
TYPO3 Extension not visible on secondary language
I have a website which uses a TYPO3 extension called "Headerslider". This extension works flawlessly on my default language settings on the Front-End (German) for my site. But if I change the sitelanguage on the Front-End to "English", the extension is not visible anymore. I've changed the images for the English site and configured it like it was on the German one, but it's still not visible. The initial installation of the extension contained following steps:

Choose from which source your jQuery comes from (I chose Google as host)

Create a marker in Templatesetup

Insert Marker in HTML - Template

This steps should also work for the English version of my Website, because the German and English version share the same template, aren't they?

答:
I do not know if it's still relevant or not, but I faced the same problem.
(All my carelessness) check the visibility of the block for a specific language</p>


答:
Unless you can work out the number of bytes taken by each individual array from the content of these bytes themselves, you need to store the number of images and their individual lengths into the file.

There are many ways to do it: you could write lengths of the individual arrays preceding each byte array, or you could write a "header" describing the rest of the content before writing the "payload" data to the file.

Header may look as follows:

```<code>Byte offset    Description
-----------  -------------------
0000...0003 - Number of files, N
0004...000C - Length of file 1
000D...0014 - Length of file 2
...
XXXX...XXXX - Length of file N
XXXX...XXXX - Content of file 1
XXXX...XXXX - Content of file 2
...
XXXX...XXXX - Content of file N
</code>```

You can use BitConverter methods to produce byte arrays to be written to the header, or you could use BinaryWriter.

Title: Read Multiple Byte Arrays from File

Body:
Unless you can work out the number of bytes taken by each individual array from the content of these bytes themselves, you need to store the number of images and their individual lengths into the file.

There are many ways to do it: you could write lengths of the individual arrays preceding each byte array, or you could write a "header" describing the rest of the content before writing the "payload" data to the file.

Header may look as follows:

Byte offset    Description
-----------  -------------------
0000...0003 - Number of files, N
0004...000C - Length of file 1
000D...0014 - Length of file 2
...
XXXX...XXXX - Length of file N
XXXX...XXXX - Content of file 1
XXXX...XXXX - Content of file 2
...
XXXX...XXXX - Content of file N

You can use BitConverter methods to produce byte arrays to be written to the header, or you could use BinaryWriter.


问:
Use an integer in a pandas dataframe column to extract a specific value from a list inside another column
I have a dataframe with a list inside a column, and another column with a specific integer value for that row. I want to use this integer value to extract a specific value from the list inside the other column:

df:

```<code>    list                                         val
1   ['mohamed', 'adam', 'paul', 'dave']           3
2   ['dave', 'fred']                              0
3   ['john', 'dave', 'jane']                      1
4   ['dave']                                      0
</code>```

this was created by:

```<code>df = df.loc[df['unsplit_list'].str.contains('dave')]
df['list'] = df['unsplit_list'].str.split('|')
df['val'] = df['list'].apply(lambda lst: [i for i, x in enumerate(lst) if 'dave' in x][0])
df['val'] = df['val'].astype(int)
</code>```

when i try to obtain the value for dave out of my list, it comes up with an error:

```<code>df['list'].str[df['val']]

>>
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

however if i did:

```<code>df['list'].str[df[1]]
</code>```

then i would be able to obtain the value in the list using this integer. How can I get this value i want out?

答:
```<code>df['name'] = [row[0][row[1]] for ix, row in df.iterrows()]
</code>```

Body:
I have a dataframe with a list inside a column, and another column with a specific integer value for that row. I want to use this integer value to extract a specific value from the list inside the other column:

df:

    list                                         val
1   ['mohamed', 'adam', 'paul', 'dave']           3
2   ['dave', 'fred']                              0
3   ['john', 'dave', 'jane']                      1
4   ['dave']                                      0

this was created by:

df = df.loc[df['unsplit_list'].str.contains('dave')]
df['list'] = df['unsplit_list'].str.split('|')
df['val'] = df['list'].apply(lambda lst: [i for i, x in enumerate(lst) if 'dave' in x][0])
df['val'] = df['val'].astype(int)

when i try to obtain the value for dave out of my list, it comes up with an error:

df['list'].str[df['val']]

>>
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

however if i did:

df['list'].str[df[1]]

then i would be able to obtain the value in the list using this integer. How can I get this value i want out?


问:
How to remove content that is added automatically to body in exchange web service api
firstly I create appointment via exchange web services, then When I look at this appointment body  on microsoft outlook , the body include content as follow. But I don't add  this content as programatically. How to remove this content ?

```<code>When: Friday, June 09, 2017 10:00 AM-10:30 AM. UTC

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

Also I set Message body for appintment as follow;

```<code>MessageBody messageBody = new MessageBody();
messageBody.setBodyType(BodyType.Text);
messageBody.setText("MY TEXT");
appointment.setBody(messageBody);
</code>```

答:
This behavior is by default.

You can do a work-around by saving the invitations to the Drafts folder instead of sending them, then retrieve them and remove the extra text.
Then use UpdateItems to save them to the SentItems folder.

Body:
firstly I create appointment via exchange web services, then When I look at this appointment body  on microsoft outlook , the body include content as follow. But I don't add  this content as programatically. How to remove this content ?

When: Friday, June 09, 2017 10:00 AM-10:30 AM. UTC

*~*~*~*~*~*~*~*~*~*

Also I set Message body for appintment as follow;

MessageBody messageBody = new MessageBody();
messageBody.setBodyType(BodyType.Text);
messageBody.setText("MY TEXT");
appointment.setBody(messageBody);


问:
reducing list based on fuzzy values in python
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

```<code>    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones
</code>```

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

答:
Assuming that this is a list of audio tones, you probably want to use a fraction such as 1.059 to determine the range to assign to a group, rather than hard-coding a number like 2.0.

```<code>def average_tones(tones):
    threshold = 1.059
    average = 0
    count = 0
    for tone in sorted(tones):
        if count != 0 and tone >= average*threshold:
            yield average
            count = 0
        average = (average * count + tone) / (count + 1)
        count += 1
    if count != 0:
        yield average
</code>```

Body:
I have a list that contains groups of nearly identical numeric values. i.e. (1004.523, 1004.575, 1004.475, 791.385, 791.298, 791.301, 791.305, 791.299)

What I am trying to do is read through the list and find all the 1004.5 +- values aggregate them and find the average value. then continue on and find all the 791.0 +- values and do the same to them.

I do not know how many individual values there will be in each "group" nor do I know how many groups there will be.

The result I am looking for is another list which would contain the average values of each of the groups. So in the example my result would be (1004.524, 791.3176)

The code I'm currently using is very Kludgey and it seems there should be a much better way to do it.

As you can see I have to repeat code twice once in the else and once at the end of the if since the last set of numbers does not trigger the else. Plus at the completion of the if I need to add the last value.

If I use the len(tones) rather that len(tones)-i I get an out of range error.

Any thoughts or suggestions would be appreciated. Thanks for your help.

Ed

    toneLen = len(tones) -1
    for i in range(0, toneLen):
        if abs(tones[i]-tones[i+1]) <= 2.0:
            tmpTones.append(tones[i])
        else:
            freq = mean(tmpTones)
            newTones.append(freq)
            tmpTones = []
    tmpTones.append(tones[i+1])
    freq = mean(tmpTones)
    newTones.append(freq)
    tones = newTones

UPDATE:
First I wanted to thank everyone who submitted suggestions. The response was very quick and helpful. I should have probably included some more info which I am doing below. Thanks so much for your help.

Second , a quick explanation of what I am trying to do. Our local Fire Department is looking for a way to track dispatches for departments close to them. For the most part they use two tone sequential paging i.e. 1000Hz followed by 500Hz.

So I am using numpy fft to find the tone frequency. Since the accuracy of the tone appears to be about +- 2 Hz, I compare the calculated frequency to a list of known paging tones and pick the closest match. After all the tones have been matched to the paging tones I look for matches to departments of interest.

One thing I did not know when I started this that in any given dispatch the same tone can be repeated several times, so the order of the tones is important. An example:
707.3, 339.6, 707.3, 569.1, 447.2, 569.1 would be a typical dispatch. I then look to see if any of the tone pairs are ones I'm interested in if so I display a message

Thanks again for all your help.

Ed

Body:
Assuming that this is a list of audio tones, you probably want to use a fraction such as 1.059 to determine the range to assign to a group, rather than hard-coding a number like 2.0.

def average_tones(tones):
    threshold = 1.059
    average = 0
    count = 0
    for tone in sorted(tones):
        if count != 0 and tone >= average*threshold:
            yield average
            count = 0
        average = (average * count + tone) / (count + 1)
        count += 1
    if count != 0:
        yield average


问:
Compare two List<Object[]> efficiently in Java
I have two List<Object[]> and I need to compare the values inside that and create a final list with just unique values.

Ex:

```<code>List<Object[]> list1 has n rows of object list with 5 columns
  [[val1,val2,val3,val4,val5],[val1_,val2_,val3_,val4_,val5_]]

List<Object[]> list2 has n rows of Object list with 4 columns
  [[val3_,val4_,val5_,val6_],[val2,val3,val4,val5]]
</code>```

The composition of second to fifth column of elements in Object array in the list1 might match with the elements in Object array in the list2. When all those columns matches, that should not be repeated in the new List. Or, instead of using a new list, I can just update the contents in list1 itself. If list2 has something unique that list1 does not have, I shall add it to the list. Unfortunately, the output of my program will only result in List<Object[]>. Could someone please tell me how I can make this comparison done efficiently?

答:
Arrays don't have an equals or hashcode method, but Lists do, so you can use a List as the key to a HashMap.

Write a method to generate a List<Object> to use as a key:

for your 5-element list, it'll be new ArrayList(array).subList(1,array.length)

for your 4-element list, it'll be new ArrayList(array)

Then:

```<code>Map map = new HashMap<List<Object>, Object[]>();
for(array : fourColumnArrays) {
     map.put( keyForFourElements(array), array);
}
for(array : fiveColumnArrays) {
     map.put( keyForFiveColumnArrays(array), array);
}
</code>```

map now contains the arrays you need.

Body:
I have two List<Object[]> and I need to compare the values inside that and create a final list with just unique values.

Ex:

List<Object[]> list1 has n rows of object list with 5 columns
  [[val1,val2,val3,val4,val5],[val1_,val2_,val3_,val4_,val5_]]

List<Object[]> list2 has n rows of Object list with 4 columns
  [[val3_,val4_,val5_,val6_],[val2,val3,val4,val5]]

The composition of second to fifth column of elements in Object array in the list1 might match with the elements in Object array in the list2. When all those columns matches, that should not be repeated in the new List. Or, instead of using a new list, I can just update the contents in list1 itself. If list2 has something unique that list1 does not have, I shall add it to the list. Unfortunately, the output of my program will only result in List<Object[]>. Could someone please tell me how I can make this comparison done efficiently?

Body:
Arrays don't have an equals or hashcode method, but Lists do, so you can use a List as the key to a HashMap.

Write a method to generate a List<Object> to use as a key:

for your 5-element list, it'll be new ArrayList(array).subList(1,array.length)

for your 4-element list, it'll be new ArrayList(array)

Then:

Map map = new HashMap<List<Object>, Object[]>();
for(array : fourColumnArrays) {
     map.put( keyForFourElements(array), array);
}
for(array : fiveColumnArrays) {
     map.put( keyForFiveColumnArrays(array), array);
}

map now contains the arrays you need.


问:
Invalid argument during changing ownership
I want to change ownership of file. I made this command as root:

```<code>chown test:test make_import.py
</code>```

I recieved this error:

```<code>chown: changing ownership of ‘make_import.py’: Invalid argument
</code>```

I couldn't find clear solution in web.
Thanks for any hint.

答: Most likely this file is on a remote/mounted filesystem. Can you check that with either "df" or "mount" command? If it is remote filesystem then possibly the mount options disallow changing the file.</p>

Body:
I want to change ownership of file. I made this command as root:

chown test:test make_import.py

I recieved this error:

chown: changing ownership of ‘make_import.py’: Invalid argument

I couldn't find clear solution in web.
Thanks for any hint.


问:
Android - Delete item from custom ListView
Does anyone know how to delete an item from a custom ListView? I'm currently working on an Android bar code scanner that stores a scanned item name into an inventory, together with its price. I also want it to be removed when the user clicks on it (but it doesn't works).

This is my code, which might seem messy because I'm still a beginner in Android.

XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.aurora.android_barcode_scanner.Inventory"
    android:focusableInTouchMode="false"
    android:clickable="false"
    android:focusable="false">

    <ListView
        android:id="@+id/listView"
        android:layout_width="365dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="10dp"
        tools:layout_editor_absoluteY="8dp"
        android:focusableInTouchMode="false"
        android:clickable="false"
        android:focusable="false"/>
</android.support.constraint.ConstraintLayout>
</code>```

Implementation:

```<code>public void display() {
    ShoppingListAdapter adapter = new ShoppingListAdapter(this,
        R.layout.adapter_view_layout, shoppingList);
    lv = (ListView) findViewById(R.id.listView);

    lv.setAdapter(adapter);
}

@Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Remove this item?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            shoppingList.remove(position);

            display();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}
</code>```

Adapter:

```<code>public class ShoppingListAdapter extends ArrayAdapter<Product> {

    private static final String TAG = "ShoppingListAdapter";

    private Context mContext;
    int mResource;

    public ShoppingListAdapter(Context context, int resource, ArrayList<Product> objects)
    {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        String name = getItem(position).getName();
        double price = getItem(position).getPrice();
        String convertPrice = Double.toString(price);

        Product product = new Product(name, price);

        LayoutInflater inflater  = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);

        TextView productName = (TextView)
        convertView.findViewById(R.id.textView1);
        TextView productPrice = (TextView)
        convertView.findViewById(R.id.textView2);

        productName.setText(name);
        productPrice.setText(convertPrice);

        return convertView;
    }

}
</code>```

答:
Make your adapter a field in the activity class

like so :

```<code>public class MainActivity extends AppCompatActivity {

    private ShoppingListAdapter mAdapter;
</code>```

and inside your onCreate method create the shoppingList and the adapter instances
And then start adding and removing items from the list and whenever you want to apply your changes in the ListView call mAdapter.notifyDataSetChanged()

like so :

```<code>builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        shoppingList.remove(position);
        mAdapter.notifyDataSetChanged();
    }
});
</code>```

Body:
Does anyone know how to delete an item from a custom ListView? I'm currently working on an Android bar code scanner that stores a scanned item name into an inventory, together with its price. I also want it to be removed when the user clicks on it (but it doesn't works).

This is my code, which might seem messy because I'm still a beginner in Android.

XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="in.aurora.android_barcode_scanner.Inventory"
    android:focusableInTouchMode="false"
    android:clickable="false"
    android:focusable="false">

    <ListView
        android:id="@+id/listView"
        android:layout_width="365dp"
        android:layout_height="495dp"
        tools:layout_editor_absoluteX="10dp"
        tools:layout_editor_absoluteY="8dp"
        android:focusableInTouchMode="false"
        android:clickable="false"
        android:focusable="false"/>
</android.support.constraint.ConstraintLayout>

Implementation:

public void display() {
    ShoppingListAdapter adapter = new ShoppingListAdapter(this,
        R.layout.adapter_view_layout, shoppingList);
    lv = (ListView) findViewById(R.id.listView);

    lv.setAdapter(adapter);
}

@Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Remove this item?");
    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            shoppingList.remove(position);

            display();
        }
    });
    builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    builder.show();
}

Adapter:

public class ShoppingListAdapter extends ArrayAdapter<Product> {

    private static final String TAG = "ShoppingListAdapter";

    private Context mContext;
    int mResource;

    public ShoppingListAdapter(Context context, int resource, ArrayList<Product> objects)
    {
        super(context, resource, objects);
        mContext = context;
        mResource = resource;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        String name = getItem(position).getName();
        double price = getItem(position).getPrice();
        String convertPrice = Double.toString(price);

        Product product = new Product(name, price);

        LayoutInflater inflater  = LayoutInflater.from(mContext);
        convertView = inflater.inflate(mResource, parent, false);

        TextView productName = (TextView)
        convertView.findViewById(R.id.textView1);
        TextView productPrice = (TextView)
        convertView.findViewById(R.id.textView2);

        productName.setText(name);
        productPrice.setText(convertPrice);

        return convertView;
    }

}

Body:
Make your adapter a field in the activity class

like so :

public class MainActivity extends AppCompatActivity {

    private ShoppingListAdapter mAdapter;

and inside your onCreate method create the shoppingList and the adapter instances
And then start adding and removing items from the list and whenever you want to apply your changes in the ListView call mAdapter.notifyDataSetChanged()

like so :

builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        shoppingList.remove(position);
        mAdapter.notifyDataSetChanged();
    }
});


问:
Testing a PHP script on a local computer
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

```<code><form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted: <br/>
    Name:<input type="text" name="name" /> <br/><br/>
    Company: <input type="text" name="company"/> <br/><br/>
    Phone: <input type="text" name="phone" /> <br/><br/>
    Email: <input type="text" name="email" /> <br/><br/>

    <input type="submit" name="Submit" value="Submit" />
</form>
</code>```

The following is the code for the php script:

```<code><table>
<tr><th>Field Name</th><th>Value(s)</th></tr>

<?php
if (empty($_POST)) {
print "<p>No data was submitted.</p>";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "<tr><td><code>$key</code></td><td>";
    foreach ($_POST['extras'] as $value) {
            print "<i>$value</i><br />";
            }
            print "</td></tr>";
    } else {
    print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
    }
} else {

print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
}
 }
}
?>
</table>
</body>
</html>
</code>```

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

答:
On first glance, it looks like you're trying to place variables, but you're putting the variables inside of a string.

So this:

```<code>print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";
</code>```

Should be something like:

```<code>print "<tr><td><code>" . $key . "</code></td><td><i>" . $value . "</i></td></tr>\n";
</code>```

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

Body:
New to PHP and web development in general. I am trying to get information from an HTML form to appear in a table on another web page after clicking submit. So I installed Apache and then PHP on my local PC and expected to be able to test a PHP script locally however it does not return the information I was expecting.
The following is the code for the form:

<form method="post" action="showform.php">

Please fill out the following form if you would like to be contacted:

    Name:<input type="text" name="name" />

    Company: <input type="text" name="company"/>

    Phone: <input type="text" name="phone" />

    Email: <input type="text" name="email" />

    <input type="submit" name="Submit" value="Submit" />
</form>

The following is the code for the php script:

Field Name	Value(s)

<?php
if (empty($_POST)) {
print "
No data was submitted.
";
 } else {

foreach ($_POST as $key => $value) {
if (get_magic_quotes_gpc()) $value=stripslashes($value);
if ($key=='extras') {

if (is_array($_POST['extras']) ){
    print "
$key	";
    foreach ($_POST['extras'] as $value) {
            print "$value
";
            }
            print "
";
    } else {
    print "
$key	$value
\n";
    }
} else {

print "
$key	$value
\n";
}
 }
}
?>

I know it works when used on the internet but how come it doesn't work locally. I have checked that apache and php are installed correctly. What could be the issue?
The current result is a table with $key and $value in the places where the correct values should be, in other words in the table cells.
Thanks for your help.

UPDATE: Now working though WAMPSERVER- thanks to all who helped!

Body:
On first glance, it looks like you're trying to place variables, but you're putting the variables inside of a string.

So this:

print "<tr><td><code>$key</code></td><td><i>$value</i></td></tr>\n";

Should be something like:

print "<tr><td><code>" . $key . "</code></td><td><i>" . $value . "</i></td></tr>\n";


问:
Does TensorFlow allow definition of variables with undefined size?
Does TensorFlow allow definition of variables with undefined size? For example I can easily define a placeholder with None values in shape - this means that these values can be specified at run time, after the graph is built. But shapes of variables must be supplied before construction of the graph. Is the previous statement true? If it is, why is it so?

答:
Take a look at the tensorflow docs on tf.Variable.

The keyword argument validate_shape:

If False, allows the variable to be initialized with a value of unknown shape. If True, the default, the shape of initial_value must be known.

So setting this to False would allow you to initialize the variable with a value of unknown shape.


问:
angular form how to show changed save button text?
I use angular 1 form to show changed save button text.
The button text should be the follow:

(disabled) save - when initial

(enable) save - when edited or re-edit after saved

(enable) saved - click save button

How can I use a simple method to resolve it?

sample JSFiddle here or the follow code

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
 $scope.buttonText = 'save';

 $scope.save = function (myForm) {
   myForm.$setPristine();
    $scope.buttonText = 'saved';
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  <form name="myForm">

    <input type="text" ng-model="text1" name="text1">
    <input type="text" ng-model="text2" name="text2">

    <button ng-click="save(myForm)" ng-disabled="myForm.$pristine">
     {{buttonText}}
    </button>

  </form>
</div>
</body></code>```

答:
You could attach a watch to the form model object and set the text back to 'Save'?

Asides from that you already have it with the initial value and setting to Saved when button is clicked

```<code>$scope.$watch("myFormData", function(){
  // text is 'Save'
}, true);
</code>```

For the following to work, put all your form data in an object variable.

I.e.

```<code>myFormData = {};

myFormData.text1 = "hi"
</code>```

So you can change the ng-model binding to a viewmodel - which is good practice anyway!

Body:
I use angular 1 form to show changed save button text.
The button text should be the follow:

(disabled) save - when initial

(enable) save - when edited or re-edit after saved

(enable) saved - click save button

How can I use a simple method to resolve it?

sample JSFiddle here or the follow code

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
 $scope.buttonText = 'save';

 $scope.save = function (myForm) {
   myForm.$setPristine();
    $scope.buttonText = 'saved';
  }
});

  <form name="myForm">

    <input type="text" ng-model="text1" name="text1">
    <input type="text" ng-model="text2" name="text2">

    <button ng-click="save(myForm)" ng-disabled="myForm.$pristine">
     {{buttonText}}
    </button>

  </form>

Body:
You could attach a watch to the form model object and set the text back to 'Save'?

Asides from that you already have it with the initial value and setting to Saved when button is clicked

$scope.$watch("myFormData", function(){
  // text is 'Save'
}, true);

For the following to work, put all your form data in an object variable.

I.e.

myFormData = {};

myFormData.text1 = "hi"

So you can change the ng-model binding to a viewmodel - which is good practice anyway!


问:
Hoisting causing issues in jQuery
I am declaring the global variable isValid to true initially. Then when I navigate across tabs, I submit the form and upon submit, the value of isValid is changed to false. However, the first time I navigate, it alerts a value of true rather than false. For some reason, the submit function is being invoked after the alert statement. What can I do so that it is invoked before the alert statement?

```<code>var isValid = true;

$('form').on('submit', function(e)) {
    e.preventDefault();
    // rest of the code
    isValid = false;
}

$(document).on('hide.bs.tab', '.nav-pills a', function()) {
    $('form').submit();
    alert(isValid);
}
</code>```

答: The submit handler is getting called asynchronously, so the order may be non-deterministic. You could put the alert call in your handler, or consider using something like jQuery deferred.promise() to control the flow of calls.</p>

Title: Hoisting causing issues in jQuery

Body:
I am declaring the global variable isValid to true initially. Then when I navigate across tabs, I submit the form and upon submit, the value of isValid is changed to false. However, the first time I navigate, it alerts a value of true rather than false. For some reason, the submit function is being invoked after the alert statement. What can I do so that it is invoked before the alert statement?

var isValid = true;

$('form').on('submit', function(e)) {
    e.preventDefault();
    // rest of the code
    isValid = false;
}

$(document).on('hide.bs.tab', '.nav-pills a', function()) {
    $('form').submit();
    alert(isValid);
}


问:
Can I connect the KAA server with an Active Directory group for authentication & authorisation?
When different app SDKs are contacting the KAA server, I want to send a AD user from the SDKs which should be authenticated & authorized at the KAA server level.  Is that doable?</p>

答: Yes, Kaa provides ability to use one of existing or custom Credential Service(s). See Custom implementation of Credential Service documentation page for more details.</p>


问:
Calculate Font Size to Fit Frame - Core Text - NSAttributedString - iOS
I have some text which I am drawing into a fixed frame via an NSAttributedString (code below). At the moment I am hard coding the text size to 16. My question is, is there a way to calculate the best fit size for the text for the given frame ?</p>

```<code>- (void)drawText:(CGContextRef)contextP startX:(float)x startY:(float)
y withText:(NSString *)standString
{
    CGContextTranslateCTM(contextP, 0, (bottom-top)*2);
    CGContextScaleCTM(contextP, 1.0, -1.0);

    CGRect frameText = CGRectMake(1, 0, (right-left)*2, (bottom-top)*2);

    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:standString];
    [attrString addAttribute:NSFontAttributeName
                      value:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]
                      range:NSMakeRange(0, attrString.length)];

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attrString));
    struct CGPath * p = CGPathCreateMutable();
    CGPathAddRect(p, NULL, frameText);
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), p, NULL);

    CTFrameDraw(frame, contextP);
}
</code>```

答:
I like the approach given by @holtwick, but found that it would sometimes overestimate what would fit.  I created a tweak that seems to work well in my tests. Tip: Don't forget to test with really wide letters like "WWW" or even "௵௵௵"</p>

```<code>func idealFontSize(for text: String, font: UIFont, width: CGFloat) -> CGFloat {
    let baseFontSize = CGFloat(256)
    let textSize = text.size(attributes: [NSFontAttributeName: font.withSize(baseFontSize)])
    let ratio = width / textSize.width

    let ballparkSize = baseFontSize * ratio
    let stoppingSize = ballparkSize / CGFloat(2) // We don't want to loop forever, if we've already come down to 50% of the ballpark size give up
    var idealSize = ballparkSize
    while (idealSize > stoppingSize && text.size(attributes: [NSFontAttributeName: font.withSize(idealSize)]).width > width) {
        // We subtract 0.5 because sometimes ballparkSize is an overestimate of a size that will fit
        idealSize -= 0.5
    }

    return idealSize
}
</code>```

Body:
I have some text which I am drawing into a fixed frame via an NSAttributedString (code below). At the moment I am hard coding the text size to 16. My question is, is there a way to calculate the best fit size for the text for the given frame ?

- (void)drawText:(CGContextRef)contextP startX:(float)x startY:(float)
y withText:(NSString *)standString
{
    CGContextTranslateCTM(contextP, 0, (bottom-top)*2);
    CGContextScaleCTM(contextP, 1.0, -1.0);

    CGRect frameText = CGRectMake(1, 0, (right-left)*2, (bottom-top)*2);

    NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:standString];
    [attrString addAttribute:NSFontAttributeName
                      value:[UIFont fontWithName:@"Helvetica-Bold" size:16.0]
                      range:NSMakeRange(0, attrString.length)];

    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)(attrString));
    struct CGPath * p = CGPathCreateMutable();
    CGPathAddRect(p, NULL, frameText);
    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0,0), p, NULL);

    CTFrameDraw(frame, contextP);
}

Body:
I like the approach given by @holtwick, but found that it would sometimes overestimate what would fit.  I created a tweak that seems to work well in my tests. Tip: Don't forget to test with really wide letters like "WWW" or even "௵௵௵"

func idealFontSize(for text: String, font: UIFont, width: CGFloat) -> CGFloat {
    let baseFontSize = CGFloat(256)
    let textSize = text.size(attributes: [NSFontAttributeName: font.withSize(baseFontSize)])
    let ratio = width / textSize.width

    let ballparkSize = baseFontSize * ratio
    let stoppingSize = ballparkSize / CGFloat(2) // We don't want to loop forever, if we've already come down to 50% of the ballpark size give up
    var idealSize = ballparkSize
    while (idealSize > stoppingSize && text.size(attributes: [NSFontAttributeName: font.withSize(idealSize)]).width > width) {
        // We subtract 0.5 because sometimes ballparkSize is an overestimate of a size that will fit
        idealSize -= 0.5
    }

    return idealSize
}