问:
Mongoose Bulk upsert not working
Hi i am new to nodejs and mongoose. Just trying to update mongo data with bulk inserts with following methods.

```<code>"use strict";
var mongo = require('../models/tracking_mongo');
var Schema = mongo.trackingMasterMongoosePoc.Schema;
//create a schema
var userwise_tracking_events = new Schema({
    activities      : {},
    summary         : {},
    userId          : Number,
    counter         : Number,
    created         : Date,
    modified        : Date
});

let collection = 'userwise_tracking_events';

let UserwiseTrackingEvents = mongo.trackingMasterConnPoc.model(collection, userwise_tracking_events);

UserwiseTrackingEvents.updateCollectionStream = function(condition, params, options, callback){
    var Bulk = UserwiseTrackingEvents.collection.initializeUnorderedBulkOp();
    Bulk.find(condition).upsert().update(params);
    Bulk.execute(callback);
};

module.exports = UserwiseTrackingEvents;
</code>```

Upper code works fine but this didn't solved my problem for using bulk inserts.

Then i just made a change by making the bulk variable global.

```<code>"use strict";
var mongo = require('../models/tracking_mongo');
var Schema = mongo.trackingMasterMongoosePoc.Schema;
//create a schema
var userwise_tracking_events = new Schema({
    activities      : {},
    summary         : {},
    userId          : Number,
    counter         : Number,
    created         : Date,
    modified        : Date
});

let collection = 'userwise_tracking_events';

let UserwiseTrackingEvents = mongo.trackingMasterConnPoc.model(collection, userwise_tracking_events);
var Bulk = UserwiseTrackingEvents.collection.initializeUnorderedBulkOp();
UserwiseTrackingEvents.updateCollectionStream = function(condition, params, options, callback){
    Bulk.find(condition).upsert().update(params);
    Bulk.execute(callback);
};

module.exports = UserwiseTrackingEvents;
</code>```

Now getting the error find of undefined is not a function.

When i checked

console.log(UserwiseTrackingEvents.collection);

Gave me result with NativeCollection.collection is null.

Do let me know what i am doing wrong.

I have another methods to work on this but i specifically want what i am doing wrong in this question.

Thanks :)

答: I would venture to say that your declaration of Bulk is not outside of any function declaration when moved out of the function call.  Thus when the exposed function is called , Bulk was not initialized.</p>

Title: Mongoose Bulk upsert not working

Body:
Hi i am new to nodejs and mongoose. Just trying to update mongo data with bulk inserts with following methods.

"use strict";
var mongo = require('../models/tracking_mongo');
var Schema = mongo.trackingMasterMongoosePoc.Schema;
//create a schema
var userwise_tracking_events = new Schema({
    activities      : {},
    summary         : {},
    userId          : Number,
    counter         : Number,
    created         : Date,
    modified        : Date
});

let collection = 'userwise_tracking_events';

let UserwiseTrackingEvents = mongo.trackingMasterConnPoc.model(collection, userwise_tracking_events);

UserwiseTrackingEvents.updateCollectionStream = function(condition, params, options, callback){
    var Bulk = UserwiseTrackingEvents.collection.initializeUnorderedBulkOp();
    Bulk.find(condition).upsert().update(params);
    Bulk.execute(callback);
};

module.exports = UserwiseTrackingEvents;

Upper code works fine but this didn't solved my problem for using bulk inserts.

Then i just made a change by making the bulk variable global.

"use strict";
var mongo = require('../models/tracking_mongo');
var Schema = mongo.trackingMasterMongoosePoc.Schema;
//create a schema
var userwise_tracking_events = new Schema({
    activities      : {},
    summary         : {},
    userId          : Number,
    counter         : Number,
    created         : Date,
    modified        : Date
});

let collection = 'userwise_tracking_events';

let UserwiseTrackingEvents = mongo.trackingMasterConnPoc.model(collection, userwise_tracking_events);
var Bulk = UserwiseTrackingEvents.collection.initializeUnorderedBulkOp();
UserwiseTrackingEvents.updateCollectionStream = function(condition, params, options, callback){
    Bulk.find(condition).upsert().update(params);
    Bulk.execute(callback);
};

module.exports = UserwiseTrackingEvents;

Now getting the error find of undefined is not a function.

When i checked

console.log(UserwiseTrackingEvents.collection);

Gave me result with NativeCollection.collection is null.

Do let me know what i am doing wrong.

I have another methods to work on this but i specifically want what i am doing wrong in this question.

Thanks :)


来源: stackexchange

问:
Conversion of SSL certificate from .pfx to .key
What is the use of -nodes in the command to convert .pfx to .pem?

Can I use

```<code>openssl pkcs12 -in keyStore.pfx -out keyStore.key -nodes
</code>```

答:
Per the OpenSSL documentation :

-nodes : don't encrypt the private keys at all.

Yes, you can use this command but what are you trying to do ? From the title, I'm understanding that you want to convert a certificate from pfx to pem format, is that right ?

ContentLicense: CC BY-SA 3.0

Body:
What is the use of -nodes in the command to convert .pfx to .pem?

Can I use

openssl pkcs12 -in keyStore.pfx -out keyStore.key -nodes


问:
XMPP Room Creation Denied (403)
I am trying to create a chatroom in XMPP (cloned from ChatSecure which is not letting me create my chatroom.This is the response I get while creating a chat room. </p>

```<code><presence xmlns="jabber:client" from="16d8ecb3-ce47-42cb-90aa-cbd9eade37ac@conference.myServer/92313456778@myServer" to="92313456778@myServer/phone" type="error"><x xmlns="http://jabber.org/protocol/muc"/><x xmlns="vcard-temp:x:update"><photo>f0858329475df2054ad8e8ac8674e7b4f25aedcd</photo></x><c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="https://github.com/robbiehanson/XMPPFramework" ver="yE4evQDERI5tsQRBmzG1547iiAU="/><error code="403" type="auth"><forbidden xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/><text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">Room creation is denied by service policy</text></error></presence>
</code>```

答:
Well, in the response I see from="16d8ecb3-ce47-42cb-90aa-cbd9eade37ac@conference.myServer/92313456778@myServer".  That's why I asked you for what did you sent out.

I guess you set the full JID (92313456778@myServer) as nickname for the room, which includes an @, and I think it's not allowed.

Let's assume:

user = user123

host = myServer

resource = myDevice

mucService = conference.myServer

roomName = myRoom

nickname = johndoe (Do not include @)

In your request, from and to should be:

from = user123@myServer/myDevice

to = room@conference.myServer/johndoe

Title: XMPP Room Creation Denied (403)

Body:
I am trying to create a chatroom in XMPP (cloned from ChatSecure which is not letting me create my chatroom.This is the response I get while creating a chat room.

<presence xmlns="jabber:client" from="16d8ecb3-ce47-42cb-90aa-cbd9eade37ac@conference.myServer/92313456778@myServer" to="92313456778@myServer/phone" type="error"><x xmlns="http://jabber.org/protocol/muc"/><x xmlns="vcard-temp:x:update"><photo>f0858329475df2054ad8e8ac8674e7b4f25aedcd</photo></x><c xmlns="http://jabber.org/protocol/caps" hash="sha-1" node="https://github.com/robbiehanson/XMPPFramework" ver="yE4evQDERI5tsQRBmzG1547iiAU="/><error code="403" type="auth"><forbidden xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/><text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">Room creation is denied by service policy</text></error></presence>


问:
IEnumerable filtration inside sql rather than memory?
I have seen lot of posts talking about IEnumerable that it applies filtration in the memory and not in SQL server like IQueryable.

But,

I have table having 20 records out of only one has Id = '12345'.

When i do

```<code>IEnumerable<Customer> customer = _context.Customer.where(x => x.Id== '12345');
</code>```

It returns 1 row and not of 20 rows.
Why?

My understanding is it would return 20 rows initially, later on when i do

```<code>var result = customers.ToList();
</code>```

It will return 1 record.

答:
At this time, you do the where on your IQueryable interface. (Remember that the right side of = is earlier executed then the left side)

```<code>IEnumerable<Customer> customer = _context.Customer.Where(x => x.Id == 12345);
</code>```

What you have read is something like that:

```<code>IEnumerable<Customer> customers = _context.Customer
IEnumerable<Customer> clientFiltered = customers.Where(x => x.Id == 12345);
</code>```

If you want to do this as oneliner:

```<code>_context.Customer.AsEnumerable().Where(x => x.Id == 12345);
</code>```

Note, in the later 2 cases, you have first casted it to IEnumerable, then do a more specific Where.

Body:
I have seen lot of posts talking about IEnumerable that it applies filtration in the memory and not in SQL server like IQueryable.

But,

I have table having 20 records out of only one has Id = '12345'.

When i do

IEnumerable<Customer> customer = _context.Customer.where(x => x.Id== '12345');

It returns 1 row and not of 20 rows.
Why?

My understanding is it would return 20 rows initially, later on when i do

var result = customers.ToList();

It will return 1 record.

Body:
At this time, you do the where on your IQueryable interface. (Remember that the right side of = is earlier executed then the left side)

IEnumerable<Customer> customer = _context.Customer.Where(x => x.Id == 12345);

What you have read is something like that:

IEnumerable<Customer> customers = _context.Customer
IEnumerable<Customer> clientFiltered = customers.Where(x => x.Id == 12345);

If you want to do this as oneliner:

_context.Customer.AsEnumerable().Where(x => x.Id == 12345);

Note, in the later 2 cases, you have first casted it to IEnumerable, then do a more specific Where.


问:
Why do Magento configurable products have a SKU
I am about to create about 300 products (not many but enough).  Most of them are configurable so I will be entering a bunch of info then putting it together.  Each simple product that makes up a config product has its own sku, so why would a configurable product need a sku?</p>

答: A valid question, I suppose they did it for consistency.  I think it's a good point that a stock keep unit is a thing, and a configurable product is not a thing .. yet SKU is the one piece of information that is kept constant in say.. importing and exporting.  I guess they did it for uniqueness rather than to be technically correct.  Virtual products wouldn't need skus either, but they are a unit in your system, so they have them.   Is there a technical side to your question, or is it purely philosophical? </p>

ContentLicense: CC BY-SA 2.5


问:
Explain the use of a bit vector for determining if all characters are unique
I am confused about how a bit vector would work to do this (not too familiar with bit vectors). Here is the code given. Could someone please walk me through this?

```<code>public static boolean isUniqueChars(String str) {
    int checker = 0;
    for (int i = 0; i < str.length(); ++i) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}
</code>```

Particularly, what is the checker doing?

Body:
I am confused about how a bit vector would work to do this (not too familiar with bit vectors). Here is the code given. Could someone please walk me through this?

public static boolean isUniqueChars(String str) {
    int checker = 0;
    for (int i = 0; i < str.length(); ++i) {
        int val = str.charAt(i) - 'a';
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}

Particularly, what is the checker doing?

Body:
Lets break down the code line by line.

int checker = 0; We are initiating a checker which will help us find duplicate values.

int val = str.charAt(i) - 'a'; We are getting the ASCII value of the character at the 'i'th position of the string and subtracting it with the ASCII value of 'a'. Since the assumption is that the string is lower characters only, the number of characters in limited to 26. Hece, the value of 'val' will always be >= 0.

if ((checker & (1 << val)) > 0) return false;

checker |= (1 << val);

Now this is the tricky part. Lets us consider an example with string "abcda". This should ideally return false.

For loop iteration 1:

Checker: 00000000000000000000000000000000

val: 97-97 = 0

1 << 0:  00000000000000000000000000000001

checker & (1 << val): 00000000000000000000000000000000 is not > 0

Hence checker: 00000000000000000000000000000001

For loop iteration 2:

Checker: 00000000000000000000000000000001

val: 98-97 = 1

1 << 1:  00000000000000000000000000000010

checker & (1 << val): 00000000000000000000000000000000 is not > 0

Hence checker: 00000000000000000000000000000011

For loop iteration 3:

Checker: 00000000000000000000000000000011

val: 99-97 = 2

1 << 2:  00000000000000000000000000000100

checker & (1 << val): 00000000000000000000000000000000 is not > 0

Hence checker: 00000000000000000000000000000111

For loop iteration 4:

Checker: 00000000000000000000000000000111

val: 100-97 = 3

1 << 3:  00000000000000000000000000001000

checker & (1 << val): 00000000000000000000000000000000 is not > 0

Hence checker: 00000000000000000000000000001111

For loop iteration 5:

Checker: 00000000000000000000000000001111

val: 97-97 = 0

1 << 0:  00000000000000000000000000000001

checker & (1 << val): 00000000000000000000000000000001 is > 0

Hence return false.

ContentLicense: CC BY-SA 4.0


问:
Return type required/ Cannot return a value from a method with a void result type
Im a beginner, can you tell me what am i doing wrong? Why can't i use those methods properly?

IDE shows: Return type required/ Cannot return a value from a method with a void result type

`        public class Human

```<code>{
    public int Age = 0;
    public int Weight = 0;
    public int Height = 0;
    private String name = "";
    boolean isMale;
}

public getAge()
{
    return Age;
}
public getWeight()
{
    return Weight;
}
public getHeight()
{
    return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean
isMale)
{

}      `
</code>```

答:
Great job so far, you're just missing the return type statements for your methods.  Your methods should be written as follows:

```<code>class Human {
    private int Age = 0;
    private int Weight = 0;
    private int Height = 0;
    private String name = "";
    private boolean isMale;

    public int getAge() {
        return Age;
    }

    public int getWeight() {
        return Weight;
    }

    public int getHeight() {
        return Height;
    }

    public Human(int Age, int Weight, int Height, String name, boolean isMale) {
        this.Age = Age;
        this.Weight = Weight;
        this.Height = Height;
        this.name = name;
        this.isMale = isMale;

        //returns nothing
    }
}
</code>```

Notice that each method has some sort of return type.  Since getAge() returns Age (which you have specified above as type int), you need to explicitly put in the method declaration statement that you are returning an int.  Same holds true if you were to return a String or a Boolean, etc.

The last method (Human()), however, is a constructor function that gets called when you instantiate a new Human object:

```<code>Human myHuman = new Human(31, 155, 68, "Bob", true);
</code>```

Notice how in the codeblock above, I am passing values in the order that I have them in the constructor function and the constructor function sets the attributes of the object based on what is being passed.  The big takeaway here, per your question, is that it does not return anything (with the exception of a new object...discussion for another time).

Generally speaking, if you are not returning anything, put void in the return type.  Just as you do in the Main function.

Last thing that I would like to point out, is the use of public vs. private for your attributes and methods.  Generally speaking, you would set your attributes to private and then make your public get/set methods to return or alter these attributes.  Just something to look out for in the future.

Hope that helps!  Feel free to message me if you have another question or need some clarification.

Body:
Im a beginner, can you tell me what am i doing wrong? Why can't i use those methods properly?

IDE shows: Return type required/ Cannot return a value from a method with a void result type

`        public class Human

{
    public int Age = 0;
    public int Weight = 0;
    public int Height = 0;
    private String name = "";
    boolean isMale;
}

public getAge()
{
    return Age;
}
public getWeight()
{
    return Weight;
}
public getHeight()
{
    return Height;
}
public Human(int Age, int Weight, int Height, String name, boolean
isMale)
{

}      `

Body:
Great job so far, you're just missing the return type statements for your methods.  Your methods should be written as follows:

class Human {
    private int Age = 0;
    private int Weight = 0;
    private int Height = 0;
    private String name = "";
    private boolean isMale;

    public int getAge() {
        return Age;
    }

    public int getWeight() {
        return Weight;
    }

    public int getHeight() {
        return Height;
    }

    public Human(int Age, int Weight, int Height, String name, boolean isMale) {
        this.Age = Age;
        this.Weight = Weight;
        this.Height = Height;
        this.name = name;
        this.isMale = isMale;

        //returns nothing
    }
}

Notice that each method has some sort of return type.  Since getAge() returns Age (which you have specified above as type int), you need to explicitly put in the method declaration statement that you are returning an int.  Same holds true if you were to return a String or a Boolean, etc.

The last method (Human()), however, is a constructor function that gets called when you instantiate a new Human object:

Human myHuman = new Human(31, 155, 68, "Bob", true);

Notice how in the codeblock above, I am passing values in the order that I have them in the constructor function and the constructor function sets the attributes of the object based on what is being passed.  The big takeaway here, per your question, is that it does not return anything (with the exception of a new object...discussion for another time).

Generally speaking, if you are not returning anything, put void in the return type.  Just as you do in the Main function.

Last thing that I would like to point out, is the use of public vs. private for your attributes and methods.  Generally speaking, you would set your attributes to private and then make your public get/set methods to return or alter these attributes.  Just something to look out for in the future.

Hope that helps!  Feel free to message me if you have another question or need some clarification.


问:
using opus in linphone
i would like to use opus codec in my linphone  application

but i have a few questions , if someone with opus codec knowledge could help me out would appreciate

OPUS.  Does this codec compress as well as package the data?

What is the output data structure from OPUS?

Is the output data streaming or packets?

What does the audio sampling scheme look like?
             and….

Within the audio sampling scheme, what are the values for silence?

Within the audio sampling scheme, what are the values for speech?

thx in advance

答:
I see you asked this on the mailing list too, but I'll answer here. I'm not sure what you mean in some the questions, but here's a start. You've tagged your post as relating to Android; I mostly know about the reference C implementation, so if you're asking about the java interface available to Android applications this won't be much help.

OPUS. Does this codec compress as well as package the data?

The Opus codec compressed pcm audio data into packets. There's internal structure, but the codec requires a transport layer like RTP to keep track of the boundaries between compressed packets.

What is the output data structure from OPUS?

The reference encoder accepts a given duration of pcm audio data an fills in a given buffer with compressed data up to a maximum requested size. See opus_encode() and opus_encode_float() in the encoder documentation for details.

Is the output data streaming or packets?

Opus produces a sequence of packets.

What does the audio sampling scheme look like? and….

The reference encoder accepts interleaved mono, stereo, or surround pcm audio data with either 16-bit signed integer or floating point samples at 8, 12, 16, 24, or 48 kHz.

Within the audio sampling scheme, what are the values for silence?

Zero pcm values are silence. As a perceptual codec Opus will try to encode low-level noise if there is no other signal. There is also support for special zero-data compressed packets for sending silence or handling discontinuous transmission.

Within the audio sampling scheme, what are the values for speech?

I'm not sure what you're asking here. Speech is treated the same as music, and will sound equally normal down to 64 kbps. The codec can maintain transparency for speech down to much lower bitrates than for music (something like 24 kbps for mono) and is intelligible down to 6 kbps for narrowband speech.

Title: using opus in linphone


问:
How to change the class of elements that have matching content
I have:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
<div class="foo">qux</div>
</code>```

And I would like all the elements that contain the same content as the one with a class of "bar" to also have a class of "bar" like so:

```<code><div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
<div class="foo">qux</div>
</code>```

But I can't just search for "baz" because that content is subject to change. Instead I have to figure out what's in the lone "bar" div then find the others that match it and change their class to "bar" too.

I've managed to get the content of the first "bar" element into a variable:

```<code>var = body.css(".bar").first.inner_text
</code>```

But nothing I've tried from there as far as finding the matching content and replacing the class has worked.

答:
I'd do something like this:

```<code>require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
EOT

target_text = doc.at('.bar').text # => "baz"
doc.search("//div[text()='#{target_text}']").each do |div|
  div['class'] = 'bar'
end
</code>```

Which results in:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
</body></html>
</code>```

There's nothing that says we can't mix CSS and XPath selectors. XPath has more capabilities, but it is visually noisy, so I use CSS when I can and XPath when I have to.

XPath makes it easy to search all nodes for text, so it's a good choice for that task.

Body:
I have:

baz

qux

qux

baz

qux

baz

qux

And I would like all the elements that contain the same content as the one with a class of "bar" to also have a class of "bar" like so:

baz

qux

qux

baz

qux

baz

qux

But I can't just search for "baz" because that content is subject to change. Instead I have to figure out what's in the lone "bar" div then find the others that match it and change their class to "bar" too.

I've managed to get the content of the first "bar" element into a variable:

var = body.css(".bar").first.inner_text

But nothing I've tried from there as far as finding the matching content and replacing the class has worked.

Body:
I'd do something like this:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="foo">baz</div>
EOT

target_text = doc.at('.bar').text # => "baz"
doc.search("//div[text()='#{target_text}']").each do |div|
  div['class'] = 'bar'
end

Which results in:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<div class="bar">baz</div>
<div class="foo">qux</div>
<div class="bar">baz</div>
</body></html>

There's nothing that says we can't mix CSS and XPath selectors. XPath has more capabilities, but it is visually noisy, so I use CSS when I can and XPath when I have to.

XPath makes it easy to search all nodes for text, so it's a good choice for that task.


问:
Kill all detached screen sessions
When I execute screen -ls, I see the following. How can I kill all the detached sessions?

There are screens on:
        84918.ttys002.ros-mbp   (Detached)
        84944.ttys008.ros-mbp   (Detached)
        84970.ttys013.ros-mbp   (Attached)
        84998.ttys002.ros-mbp   (Detached)
        85024.ttys002.ros-mbp   (Detached)
5 Sockets in /var/folders/86/062qtcyx2rxbnmn8mtpkyghs0r0r_z/T/.screen.
```

答:
If the screens are dead, use:</p>

```<code>screen -wipe
</code>```

Title: Kill all detached screen sessions

Body:
If the screens are dead, use:

screen -wipe


问:
move records from one table to another
I have two tables - posts and parchive with the same structure, and want to move records from one table to the other.

id column is primary key - autoincrement.

```<code>insert into posts select * from parchive where id...
</code>```

Error:

Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '70' for key 'PRIMARY'...

Second try:

```<code>insert into posts select date, title, subtitle, intro, story, img, tags,...
</code>```

Everything is selected except id.

Error:

Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count

Any help?

答:
From my comment above. If you are only going to insert data into particular fields, then you must specify those fields after the table:

```<code>insert into posts (date, title, subtitle, intro, story, img, tags,...) select date, title, subtitle, intro, story, img, tags,...
</code>```

I think it might worth exploring why you are getting a duplicate unique key error though when inserting the ID. If your ID is autogenerated in your main table, it would make sense to not autogenerate in your archive table so the id's match up.

Title: move records from one table to another

Body:
I have two tables - posts and parchive with the same structure, and want to move records from one table to the other.

id column is primary key - autoincrement.

insert into posts select * from parchive where id...

Error:

Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '70' for key 'PRIMARY'...

Second try:

insert into posts select date, title, subtitle, intro, story, img, tags,...

Everything is selected except id.

Error:

Uncaught PDOException: SQLSTATE[21S01]: Insert value list does not match column list: 1136 Column count doesn't match value count

Any help?

Body:
From my comment above. If you are only going to insert data into particular fields, then you must specify those fields after the table:

insert into posts (date, title, subtitle, intro, story, img, tags,...) select date, title, subtitle, intro, story, img, tags,...

I think it might worth exploring why you are getting a duplicate unique key error though when inserting the ID. If your ID is autogenerated in your main table, it would make sense to not autogenerate in your archive table so the id's match up.


问:
Gdal_calc fails with nan output
I want to do some raster calculations with gdal_calc from the command line, but keep getting empty rasters filled with nan.

For example when I replace values in a raster:

```<code>gdal_calc.py -A input.tif --outfile=output.tif --calc="10*(A==0)+20*(A==1)"
</code>```

In this example values equal to 0 should be replaced by 10 and values equal to 1 should be replaced by 20. Is my syntax wrong?

答:
Based on this: https://gis.stackexchange.com/questions/116473/reclassify-rasters-using-gdal-and-python

you should try:

```<code>gdal_calc.py -A C:temp\raster.tif --outfile=result.tiff --calc="10*(A==0)" --calc="20*(A==1)"
</code>```

Title: Gdal_calc fails with nan output

Body:
I want to do some raster calculations with gdal_calc from the command line, but keep getting empty rasters filled with nan.

For example when I replace values in a raster:

gdal_calc.py -A input.tif --outfile=output.tif --calc="10*(A==0)+20*(A==1)"

In this example values equal to 0 should be replaced by 10 and values equal to 1 should be replaced by 20. Is my syntax wrong?

Body:
Based on this: https://gis.stackexchange.com/questions/116473/reclassify-rasters-using-gdal-and-python

you should try:

gdal_calc.py -A C:temp\raster.tif --outfile=result.tiff --calc="10*(A==0)" --calc="20*(A==1)"


问:
Authentication filter in Web API 2
I created a simple custom authentication filter in Web API 2, which look like this.

```<code>public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        string authToken = context.Request.Headers.GetValues("CustomAuthHeader").FirstOrDefault();
        if (string.IsNullOrEmpty(authToken))
        {
            context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
        }

        return Task.FromResult(0);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        return Task.FromResult(0);
    }
</code>```

I have below question on this-

1). AuthenticateAsync is for implementing the core authentication logic but what is the use of ChallengeAsync in real life. If possible please explain with a example.

2). Why its returning Task. Will it create a new thread at back end every time (Wherever apply). If it create a new thread every time, when this thread will be killed?

3). What is the role of Task.FromResult(0)

Thank you!

答:
ChallengeAsync is used to add authentication challenges to the response, if needed. Typically it is used in case of 401 Unauthorized to provide information about authentication required by server.

Methods return task to support asynchronous execution and chaining.

Methods contain no really asynchronous methods that's why they return dummy already completed task to satisfy implemented interface.

I guess this article should help you a lot.

Title: Authentication filter in Web API 2

Body:
I created a simple custom authentication filter in Web API 2, which look like this.

public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    {
        string authToken = context.Request.Headers.GetValues("CustomAuthHeader").FirstOrDefault();
        if (string.IsNullOrEmpty(authToken))
        {
            context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
        }

        return Task.FromResult(0);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    {
        return Task.FromResult(0);
    }

I have below question on this-

1). AuthenticateAsync is for implementing the core authentication logic but what is the use of ChallengeAsync in real life. If possible please explain with a example.

2). Why its returning Task. Will it create a new thread at back end every time (Wherever apply). If it create a new thread every time, when this thread will be killed?

3). What is the role of Task.FromResult(0)

Thank you!


问:
Aggregating based on "near" row values
I have a very messy dataframe (webscraped) that unfortunately has many double and even triple entries in it. Most of the dataframe looks like this:

```<code>> df1<-data.frame(var1=c("a","a","b","b","c","c","d","d"),var2=c("right.a",NA,"right.b",NA,"right.c",NA,"right.d",NA),var3=c("correct.a","correct.a","correct.b","correct.b","correct.c","correct.c","correct.d","correct.d"))
> df1
  var1    var2      var3
1    a right.a correct.a
2    a    <NA> correct.a
3    b right.b correct.b
4    b    <NA> correct.b
5    c right.c correct.c
6    c    <NA> correct.c
7    d right.d correct.d
8    d    <NA> correct.d
</code>```

"var1"  is my ID variable that I need to use to aggregate. My goal is to have a dataframe that looks like this:

```<code>  var1    var2      var3
1    a right.a correct.a
2    b right.b correct.b
3    c right.c correct.c
4    d right.d correct.d
</code>```

However, the main problem is, that not the whole dataframe looks like this. In fact, I have other parts that look like this:

```<code>> df2<-data.frame(var1=c("e","e","e","f","f","g","g","g"),var2=c(NA,NA,"right.e",NA,NA,NA,"right.g",NA),var3=c("correct.e","correct.e",NA,"correct.f",NA,"correct.g","correct.g",NA))
> df2
  var1    var2      var3
1    e    <NA> correct.e
2    e    <NA> correct.e
3    e right.e      <NA>
4    f    <NA> correct.f
5    f    <NA>      <NA>
6    g    <NA> correct.g
7    g right.g   wrong.g
8    g    <NA>      <NA>
</code>```

And other variations. In the end, every ID should have one row with the correct and right var2 and var3 in it. At this point, I get lost: My var1 is not unique. However, I know that duplicate IDs that "belong" together are grouped in the dataframe (as seen in my examples); e.g. there might be another "a" in row 4102 and 4103.

What I think would be the way to go is using aggregate with var1 as ID,but in addition telling R that aggregate should just check +-2 rows of var1 when doing so. Any ideas how to code this?

Thanks!

答:
If var2 and var3 have only one unique value for each level of var1, then:

```<code>library(dplyr)

df = rbind(df1,df2)

df %>% group_by(var1) %>%
  summarise_all(funs(.[!is.na(.)][1]))
</code>```

```<code>   var1    var2      var3
1     a right.a correct.a
2     b right.b correct.b
3     c right.c correct.c
4     d right.d correct.d
5     e right.e correct.e
6     f    <NA> correct.f
7     g right.g correct.g
</code>```

Title: Aggregating based on "near" row values

Body:
I have a very messy dataframe (webscraped) that unfortunately has many double and even triple entries in it. Most of the dataframe looks like this:

> df1<-data.frame(var1=c("a","a","b","b","c","c","d","d"),var2=c("right.a",NA,"right.b",NA,"right.c",NA,"right.d",NA),var3=c("correct.a","correct.a","correct.b","correct.b","correct.c","correct.c","correct.d","correct.d"))
> df1
  var1    var2      var3
1    a right.a correct.a
2    a    <NA> correct.a
3    b right.b correct.b
4    b    <NA> correct.b
5    c right.c correct.c
6    c    <NA> correct.c
7    d right.d correct.d
8    d    <NA> correct.d

"var1"  is my ID variable that I need to use to aggregate. My goal is to have a dataframe that looks like this:

  var1    var2      var3
1    a right.a correct.a
2    b right.b correct.b
3    c right.c correct.c
4    d right.d correct.d

However, the main problem is, that not the whole dataframe looks like this. In fact, I have other parts that look like this:

> df2<-data.frame(var1=c("e","e","e","f","f","g","g","g"),var2=c(NA,NA,"right.e",NA,NA,NA,"right.g",NA),var3=c("correct.e","correct.e",NA,"correct.f",NA,"correct.g","correct.g",NA))
> df2
  var1    var2      var3
1    e    <NA> correct.e
2    e    <NA> correct.e
3    e right.e      <NA>
4    f    <NA> correct.f
5    f    <NA>      <NA>
6    g    <NA> correct.g
7    g right.g   wrong.g
8    g    <NA>      <NA>

And other variations. In the end, every ID should have one row with the correct and right var2 and var3 in it. At this point, I get lost: My var1 is not unique. However, I know that duplicate IDs that "belong" together are grouped in the dataframe (as seen in my examples); e.g. there might be another "a" in row 4102 and 4103.

What I think would be the way to go is using aggregate with var1 as ID,but in addition telling R that aggregate should just check +-2 rows of var1 when doing so. Any ideas how to code this?

Thanks!

Body:
If var2 and var3 have only one unique value for each level of var1, then:

library(dplyr)

df = rbind(df1,df2)

df %>% group_by(var1) %>%
  summarise_all(funs(.[!is.na(.)][1]))

   var1    var2      var3
1     a right.a correct.a
2     b right.b correct.b
3     c right.c correct.c
4     d right.d correct.d
5     e right.e correct.e
6     f    <NA> correct.f
7     g right.g correct.g


问:
Position TextBox in Chart in Excel to the top / left -4
I have a chart in excel. Inside this chart there is a textbox. I want to position this textbox to the upper left corner of the chart.

When I do this manually and read out the properties .Top and .Left I get -4 as a response.

If I try setting these two properties to -4 the textbox goes to positions 0 and not -4.
Why cant I position the texbox to the upper left corner of the chart?
Is here some outer margin of the textbox or an inner margin of the chart / chartarea?

Here is some code to test it with any chart, in which you inserted a textbox:

```<code>Sub TextBoxPositionUpperLeftCorner()
    Dim cho As ChartObject
    Dim sh As Shape

    For Each cho In ActiveSheet.ChartObjects
        For Each sh In cho.Chart.Shapes

            'reading out the position
            Debug.Print "Top: " & sh.Top
            Debug.Print "Left: " & sh.Left

            'setting the position
            sh.Top = -4
            sh.Left = -4

        Next
    Next
End Sub
</code>```

答:
Seems like you can't set Top/Left to negative numbers.

But you can increment the position to achieve that:

```<code>Sub TextBoxPositionUpperLeftCorner()
Dim cho As ChartObject
Dim sh As Shape

For Each cho In ActiveSheet.ChartObjects
    For Each sh In cho.Chart.Shapes

        'reading out the position
        Debug.Print "Top: " & sh.Top
        Debug.Print "Left: " & sh.Left

        sh.IncrementTop -(sh.Top + 4)
        sh.IncrementLeft -(sh.Left + 4)

         'reading out the position
        Debug.Print "Top: " & sh.Top
        Debug.Print "Left: " & sh.Left

    Next
Next
</code>```

EDIT: after a little more testing, the most negative you can go even with this approach is -4/-4.

Body:
I have a chart in excel. Inside this chart there is a textbox. I want to position this textbox to the upper left corner of the chart.

When I do this manually and read out the properties .Top and .Left I get -4 as a response.

If I try setting these two properties to -4 the textbox goes to positions 0 and not -4.
Why cant I position the texbox to the upper left corner of the chart?
Is here some outer margin of the textbox or an inner margin of the chart / chartarea?

Here is some code to test it with any chart, in which you inserted a textbox:

Sub TextBoxPositionUpperLeftCorner()
    Dim cho As ChartObject
    Dim sh As Shape

    For Each cho In ActiveSheet.ChartObjects
        For Each sh In cho.Chart.Shapes

            'reading out the position
            Debug.Print "Top: " & sh.Top
            Debug.Print "Left: " & sh.Left

            'setting the position
            sh.Top = -4
            sh.Left = -4

        Next
    Next
End Sub

Body:
Seems like you can't set Top/Left to negative numbers.

But you can increment the position to achieve that:

Sub TextBoxPositionUpperLeftCorner()
Dim cho As ChartObject
Dim sh As Shape

For Each cho In ActiveSheet.ChartObjects
    For Each sh In cho.Chart.Shapes

        'reading out the position
        Debug.Print "Top: " & sh.Top
        Debug.Print "Left: " & sh.Left

        sh.IncrementTop -(sh.Top + 4)
        sh.IncrementLeft -(sh.Left + 4)

         'reading out the position
        Debug.Print "Top: " & sh.Top
        Debug.Print "Left: " & sh.Left

    Next
Next

EDIT: after a little more testing, the most negative you can go even with this approach is -4/-4.


问:
Number of fields in a structure
I'm new in abap development .
Actually, I'm looking for the Number of fields of a table or structure

any suggestion please

答:
@lausek answered correctly. But for release 730 or lower, you'll need to adapt to something like this:</p>

```<code>data ls_mara type mara.
data lo_structdescr type ref to cl_abap_structdescr.
data lv_count type i.

lo_structdescr ?= cl_abap_datadescr=>describe_by_data( ls_mara ).
lv_count = lines( lo_structdescr->components ).
write lv_count.
</code>```

Title: Number of fields in a structure

Body:
@lausek answered correctly. But for release 730 or lower, you'll need to adapt to something like this:

data ls_mara type mara.
data lo_structdescr type ref to cl_abap_structdescr.
data lv_count type i.

lo_structdescr ?= cl_abap_datadescr=>describe_by_data( ls_mara ).
lv_count = lines( lo_structdescr->components ).
write lv_count.


问:
Convert C# dictionary with delegate values to its VB.NET equivalent
I require some help to understand how can I translate this kind of dictionary entries that uses a delegate as value, from C# to VB.NET:

```<code>using LookupT =
    System.Collections.Generic.KeyValuePair<string, System.Func<BBCodeNode, bool, string>>;

public delegate string HtmlRendererCallback(BBCodeNode Node,
                                            bool ThrowOnError,
                                            object LookupTable);

static readonly LookupT[] convertLookup =
    new Dictionary<string, HtmlRendererCallback>
    {
        { "b", DirectConvert }
    }.ToArray();

public static string DirectConvert(BBCodeNode Node,
                                   bool ThrowOnError,
                                   object LookupTable)
{
    //...
}
</code>```

What I tried is this translation below which will not work, the debugger marks the function name as error in the dictionary entry ( {"b", DirectConvert()} ) asking me to pass the proper arguments to the DirectConvert function:

```<code>Imports LookupT =
    System.Collections.Generic.KeyValuePair(Of String, System.Func(Of BBCodeNode, Boolean, String))

Public Delegate Function HtmlRendererCallback(node As BBCodeNode,
                                              throwOnError As Boolean,
                                              lookupTable As Object) As String

Shared ReadOnly convertLookup As LookupT() =
    New Dictionary(Of String, HtmlRendererCallback)() From
        {
            {"b", DirectConvert()}
        }.ToArray()

Public Shared Function DirectConvert(node As BBCodeNode,
                                     throwOnError As Boolean,
                                     lookupTable As Object) As String
' ...
End sub
</code>```

...however, in the C# code if I'm not wrong it seems like it is not specifying at all any argument to the function, so... it is confusing me.

答:
Could you please try this:</p>

```<code>    Public Delegate Function HtmlRendererCallback(ByVal node As BBCodeNode, ByVal throwOnError As Boolean, ByVal lookupTable As Object) As String
    Shared convertMeth As HtmlRendererCallback = AddressOf DirectConvert
    Shared ReadOnly convertLookup As ILookup(Of String, HtmlRendererCallback) = New Dictionary(Of String, HtmlRendererCallback)() From {
        {"b", convertMeth},
        {"c", convertMeth},
        {"d", convertMeth}
    }

    Public Shared Function DirectConvert(ByVal node As BBCodeNode, ByVal throwOnError As Boolean, ByVal lookupTable As Object) As String
        DirectConvert = ""
    End Function
</code>```

Body:
I require some help to understand how can I translate this kind of dictionary entries that uses a delegate as value, from C# to VB.NET:

using LookupT =
    System.Collections.Generic.KeyValuePair<string, System.Func<BBCodeNode, bool, string>>;

public delegate string HtmlRendererCallback(BBCodeNode Node,
                                            bool ThrowOnError,
                                            object LookupTable);

static readonly LookupT[] convertLookup =
    new Dictionary<string, HtmlRendererCallback>
    {
        { "b", DirectConvert }
    }.ToArray();

public static string DirectConvert(BBCodeNode Node,
                                   bool ThrowOnError,
                                   object LookupTable)
{
    //...
}

What I tried is this translation below which will not work, the debugger marks the function name as error in the dictionary entry ( {"b", DirectConvert()} ) asking me to pass the proper arguments to the DirectConvert function:

Imports LookupT =
    System.Collections.Generic.KeyValuePair(Of String, System.Func(Of BBCodeNode, Boolean, String))

Public Delegate Function HtmlRendererCallback(node As BBCodeNode,
                                              throwOnError As Boolean,
                                              lookupTable As Object) As String

Shared ReadOnly convertLookup As LookupT() =
    New Dictionary(Of String, HtmlRendererCallback)() From
        {
            {"b", DirectConvert()}
        }.ToArray()

Public Shared Function DirectConvert(node As BBCodeNode,
                                     throwOnError As Boolean,
                                     lookupTable As Object) As String
' ...
End sub

...however, in the C# code if I'm not wrong it seems like it is not specifying at all any argument to the function, so... it is confusing me.

Body:
Could you please try this:

    Public Delegate Function HtmlRendererCallback(ByVal node As BBCodeNode, ByVal throwOnError As Boolean, ByVal lookupTable As Object) As String
    Shared convertMeth As HtmlRendererCallback = AddressOf DirectConvert
    Shared ReadOnly convertLookup As ILookup(Of String, HtmlRendererCallback) = New Dictionary(Of String, HtmlRendererCallback)() From {
        {"b", convertMeth},
        {"c", convertMeth},
        {"d", convertMeth}
    }

    Public Shared Function DirectConvert(ByVal node As BBCodeNode, ByVal throwOnError As Boolean, ByVal lookupTable As Object) As String
        DirectConvert = ""
    End Function


问:
jQuery reset star-rating.js
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

```<code> $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }
</code>```

Please help on how to reset these stars to zero or null.

Here is the full code.

```<code> $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});
</code>```

答:
I'm not familiar with the plugin, but looking at the link you provided, can't you just update the text inside of the element to reflect an empty or zero rating? Something like:</p>

```<code>$("#btn-reset").on('click', function() {
     $('#starrating').text('0/5').star_rating();
}
</code>```

Title: jQuery reset star-rating.js

Body:
I am using this plugin https://danielupshaw.com/jquery-star-rating/

I want to reset my form. But how can I reset these stars??

 $("#btn-reset").on('click', function() {
  //some other inputs reset
  $('#starrating').star_rating.remove();
  $('#starrating').star_rating.reload();
 }

Please help on how to reset these stars to zero or null.

Here is the full code.

 $("#btn-reset").on('click', function() {
   $('#starrating').star_rating.reload();
});
  jQuery(function($) {
    $('#starrating').star_rating({
        click: function(clicked_rating, event) {
            event.preventDefault();
            $('input[name=\'rating\']').val(clicked_rating);
            this.rating(clicked_rating);
        }
    });
});

Body:
I'm not familiar with the plugin, but looking at the link you provided, can't you just update the text inside of the element to reflect an empty or zero rating? Something like:

$("#btn-reset").on('click', function() {
     $('#starrating').text('0/5').star_rating();
}


问:
C# Reading String inside a binary file
I have some problems to understand how reading files from different format than the text format. I know that inside a given file there are some information as string. I managed to write the hex code to a text file which is helping me a lot for another function of the process, because I know that after some combinations of hex codes there might be string writed in the file.

For instance, I have this batch of hex codes.
00 39 AF 32 DD 24 BA 09 07 06 03 DB
I know that when the hex codes are equal to AF 32 the next information should be the string. For instance: "Invoice Number 223232"

Any help or reference will be appreciated.

Kind regards,

```<code>static void Main(string[] args)
   {
      StreamWriter writer = new StreamWriter("output.txt", true);
      FileStream fs = new FileStream("File", FileMode.Open);
      int hexIn;
      String hex;
      for (int i = 0; (hexIn = fs.ReadByte()) != -1; i++)
      {
         writer.Write(hexIn + " ");
         hex = string.Format("{0:X2}", hexIn);
         writer.Write(hex + " ");
      }
  }
</code>```

答:
The sample code you have looks like you are trying to read a binary file, not a hex-encoded text file.

If the source file is binary (which is ideal), you would read it byte-by-byte, and run through a state machine to know when to expect a string.  You would have to know how long the string is.  In the sample below I am assuming a null-terminated C-style string.  For pascal style strings you would read a length prefix, or for fixed width just keep track of the expected number of character.

```<code>bool done = false;
int state = 0;
StringBuilder result = new StringBuilder();
while (!done) {
   int byteValue = fs.ReadByte();
   if (bytesValue == -1)
      done = true;
   else {
      switch (state) {
         case 0: //looking for 0xAF
            if (byteValue == 0xAF)
               state = 1;
            break;
        case 1: //looking for 0x32
            if (byteValue == 0x32)
                state = 2;
            else
                state = 0;
            break;
        case 2: //start reading string
            if (byteValue == 0) {//end of C-style string
                //Do something with result.ToString()
                result.Clear();
                state = 0;  //go back to looking for more strings
            } else {
                result.Append((char)byteValue); //assuming 8-bit ASCII string
            }
            break;
      }
   }
}
</code>```

If you are reading a hex-encoded text file, it would be more difficult, as you would have to read hex nibbles at a time and reconstruct the bytes, but the state machine approach would be similar.

Title: C# Reading String inside a binary file

Body:
I have some problems to understand how reading files from different format than the text format. I know that inside a given file there are some information as string. I managed to write the hex code to a text file which is helping me a lot for another function of the process, because I know that after some combinations of hex codes there might be string writed in the file.

For instance, I have this batch of hex codes.
00 39 AF 32 DD 24 BA 09 07 06 03 DB
I know that when the hex codes are equal to AF 32 the next information should be the string. For instance: "Invoice Number 223232"

Any help or reference will be appreciated.

Kind regards,

static void Main(string[] args)
   {
      StreamWriter writer = new StreamWriter("output.txt", true);
      FileStream fs = new FileStream("File", FileMode.Open);
      int hexIn;
      String hex;
      for (int i = 0; (hexIn = fs.ReadByte()) != -1; i++)
      {
         writer.Write(hexIn + " ");
         hex = string.Format("{0:X2}", hexIn);
         writer.Write(hex + " ");
      }
  }

Body:
The sample code you have looks like you are trying to read a binary file, not a hex-encoded text file.

If the source file is binary (which is ideal), you would read it byte-by-byte, and run through a state machine to know when to expect a string.  You would have to know how long the string is.  In the sample below I am assuming a null-terminated C-style string.  For pascal style strings you would read a length prefix, or for fixed width just keep track of the expected number of character.

bool done = false;
int state = 0;
StringBuilder result = new StringBuilder();
while (!done) {
   int byteValue = fs.ReadByte();
   if (bytesValue == -1)
      done = true;
   else {
      switch (state) {
         case 0: //looking for 0xAF
            if (byteValue == 0xAF)
               state = 1;
            break;
        case 1: //looking for 0x32
            if (byteValue == 0x32)
                state = 2;
            else
                state = 0;
            break;
        case 2: //start reading string
            if (byteValue == 0) {//end of C-style string
                //Do something with result.ToString()
                result.Clear();
                state = 0;  //go back to looking for more strings
            } else {
                result.Append((char)byteValue); //assuming 8-bit ASCII string
            }
            break;
      }
   }
}

If you are reading a hex-encoded text file, it would be more difficult, as you would have to read hex nibbles at a time and reconstruct the bytes, but the state machine approach would be similar.


问:
Why does gprof significantly underestimate the program's running time?
I have this program that takes 2.34 seconds to run, and gprof says it only takes 1.18 seconds. I've read answers elsewhere suggesting that gprof can get it wrong if e.g the program is I/O bound, but this program clearly isn't.

This also happens for a useful program I'm trying to profile. It's not specific to this trivial test case.

(Also in this case gprof says that main() takes more than 100% of the program's running time, which is a pretty stupid bug but not really causing problems for me.)

```<code>$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.
</code>```

答:
First of all, profiling a program that completes in 2.3 seconds is a little bit ludicrous.  You really need a long-running program to get a good measurement of program hot spots, etc.  But I digress...

To answer your first question, time (the command-line utility) times the execution of the whole process (including the profiling instrumentation itself).  When you enable profiling in your build, the program writes a gmon.out file containing execution times etc. each time you run the program.  That is, the hard work of profiling is done each time you run the program.  The profiling instrumentation tries hard to separate out its own impact on the time accounting, and in this case, it seems that the profiling itself accounted for 2.34 - 1.18 = 1.16s of the runtime (as reported by time).  The gprof program itself essentially just analyzes and reformats the runtime statistics stored in the gmon.out program.  To be clear about this, the real profiling happens during your program's run, not during the gprof run.

Finally, the gprof output answers your second question directly.  It samples your program's execution at 1/100 sec. intervals and gives credit for that whole 0.01 s to whatever happened to be executing during the sample.  If your program doesn't take an exact multiple of 0.01 seconds to execute, you'll get numbers that don't add up to 100%.  Again, it must be emphasized that profiling a program that runs this quickly is quite error prone, and this apparent bug would certainly be mitigated by a longer sampling interval (i.e. runtime).  Also, gprof's accounting for its own overhead is imperfect, which might further contribute to the seemingly ludicrous 101.33% number.

It's a statistical process, and it's not perfect.  You have to interpret the results with a grain of salt.

Good luck!

Body:
I have this program that takes 2.34 seconds to run, and gprof says it only takes 1.18 seconds. I've read answers elsewhere suggesting that gprof can get it wrong if e.g the program is I/O bound, but this program clearly isn't.

This also happens for a useful program I'm trying to profile. It's not specific to this trivial test case.

(Also in this case gprof says that main() takes more than 100% of the program's running time, which is a pretty stupid bug but not really causing problems for me.)

$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls  Ts/call  Ts/call  name
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.


问:
Select rows from a data frame based on values in a vector
I have data similar to this:

```<code>dt <- structure(list(fct = structure(c(1L, 2L, 3L, 4L, 3L, 4L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 3L, 4L), .Label = c("a", "b", "c", "d"), class = "factor"), X = c(2L, 4L, 3L, 2L, 5L, 4L, 7L, 2L, 9L, 1L, 4L, 2L, 5L, 4L, 2L)), .Names = c("fct", "X"), class = "data.frame", row.names = c(NA, -15L))
</code>```

I want to select rows from this data frame based on the values in the fct variable. For example, if I wish to select rows containing either "a" or "c" I can do this:

```<code>dt[dt$fct == 'a' | dt$fct == 'c', ]
</code>```

which yields

```<code>1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4
</code>```

as expected. But my actual data is more complex and I actually want to select rows based on the values in a vector such as

```<code>vc <- c('a', 'c')
</code>```

So I tried

```<code>dt[dt$fct == vc, ]
</code>```

but of course that doesn't work. I know I could code something to loop through the vector and pull out the rows needed and append them to a new dataframe, but I was hoping there was a more elegant way.

So how can I filter/subset my data based on the contents of the vector vc?

答:
Another option would be to use a keyed data.table:

```<code>library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]
</code>```

which results in:

```<code>   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4
</code>```

What this does:

setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.

Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

```<code>setDT(dt)[J(vc), on=.(fct)]
</code>```

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

```<code>setDT(dt, key = 'fct')[J(vc), nomatch = 0]
</code>```

or:

```<code>setDT(dt)[J(vc), on=.(fct), nomatch = 0]
</code>```

Body:
I have data similar to this:

dt <- structure(list(fct = structure(c(1L, 2L, 3L, 4L, 3L, 4L, 1L, 2L, 3L, 1L, 2L, 3L, 2L, 3L, 4L), .Label = c("a", "b", "c", "d"), class = "factor"), X = c(2L, 4L, 3L, 2L, 5L, 4L, 7L, 2L, 9L, 1L, 4L, 2L, 5L, 4L, 2L)), .Names = c("fct", "X"), class = "data.frame", row.names = c(NA, -15L))

I want to select rows from this data frame based on the values in the fct variable. For example, if I wish to select rows containing either "a" or "c" I can do this:

dt[dt$fct == 'a' | dt$fct == 'c', ]

which yields

1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

as expected. But my actual data is more complex and I actually want to select rows based on the values in a vector such as

vc <- c('a', 'c')

So I tried

dt[dt$fct == vc, ]

but of course that doesn't work. I know I could code something to loop through the vector and pull out the rows needed and append them to a new dataframe, but I was hoping there was a more elegant way.

So how can I filter/subset my data based on the contents of the vector vc?

Body:
Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.

Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]


问:
DrawableLeft in center with text
I can't center my drawableLeft icon.

I can easily put icon on the left of text, but if I set gravity to center, then only text is centered, but no icon.

```<code><Button
    android:id="@+id/patient_list_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/patientList"
    android:drawableLeft="@drawable/ic_icon_two_heads"
    android:layout_marginBottom="15dp"
    style="@style/darkBlueButtonWithImage"/>
</code>```

This is what I want:

This is what I have:

```<code><style name="darkBlueButtonWithImage">
    <item name="android:drawablePadding">10dp</item>
    <item name="android:textColor">@color/white</item>
    <item name="android:paddingLeft">10dp</item>
    <item name="android:background">@drawable/radius_dark_blue_button</item>
    <item name="android:gravity">center_vertical|left</item>
    <item name="android:drawableTint">@color/white</item> <!-- has to be set in activity.java -->
</style>
</code>```

How can I achieve this?

答:
a) Increase "paddingLeft" value and shrink or remove "drawablePadding" in your case, adjust the value to a proper one; for example:

```<code>android:paddingLeft="50dp"
android:gravity="center_vertical|left"
</code>```

b) Use a custom view.

Title: DrawableLeft in center with text

Body:
I can't center my drawableLeft icon.

I can easily put icon on the left of text, but if I set gravity to center, then only text is centered, but no icon.

<Button
    android:id="@+id/patient_list_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/patientList"
    android:drawableLeft="@drawable/ic_icon_two_heads"
    android:layout_marginBottom="15dp"
    style="@style/darkBlueButtonWithImage"/>

This is what I want:

This is what I have:

How can I achieve this?

Body:
a) Increase "paddingLeft" value and shrink or remove "drawablePadding" in your case, adjust the value to a proper one; for example:

android:paddingLeft="50dp"
android:gravity="center_vertical|left"

b) Use a custom view.


问:
Update a List of KeyValue pair
I have a WPF application where I need to implement this concept:

There is a combobox and a datagrid. The combobox holds a list of sellers, and the datagrid holds the rates of items they sell.

I want something like this:

```<code>client -> null

item    |   rate
--------------------
itemA   |   0.00
itemB   |   0.00
itemC   |   0.00
</code>```

When none of the client (seller) is selected, all the rates of items default to 0.00.

Now, let's say I choose a client by name of clientA, who does not sell ItemB. Then, the display should reflect this.

```<code>client -> clientA

item    |   rate
--------------------
itemA   |   5.00
itemB   |   0.00
itemC   |   8.00
</code>```

Basically, it should show 0.00 instead of null for the items a client does not sell.

This is actually the work of a Dictionary, or in case of WPF, an ObservableDictionary.

But, I am using Caliburn, and I would like to solve it by using BindableCollection.

So, I have something similar to this:

```<code>if (SelectedReferenceClient == null)
{
    Rates = new BindableCollection<KeyValuePair<string, decimal>>(itemrepository.FindWhere(c => true).Select(c => new KeyValuePair<string, decimal>(key: c.Name, value: 0)));;
} //retrieve all items and put value to zero.

    var SelectedClientRates = new List<KeyValuePair<string, decimal>>(raterepository.FindWhere(c => c.Client == SelectedClient).Select(c => new KeyValuePair<string, decimal>(key: c.ItemName, value: c.Rate)));
    //get rates of items they sell

    foreach (var a in SelectedClientRates)
    {
        var b = Rates.FirstOrDefault(c => c.key == a.key);
        b.value = a.value;
    }//update the values in BindingCollection
</code>```

This might work, but it's noisy and it's kludgy. Is there any LINQ way to do this? As LINQ abhors side effects, my first thought was that it wasnt possible.

But, if I want to stick to BindableCollection and not use ObservableDictionary, is there any better way to do this?

答:
See sample code below</p>

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

namespace ConsoleApplication49
{
    class Program
    {

        static void Main(string[] args)
        {
            string SelectedClient = "";
            List<RateRepository> raterepository = new List<RateRepository>();
            Dictionary<string, decimal> SelectedClientRates = raterepository.Where(c => c.Client == SelectedClient)
                .GroupBy(x => x.ItemName, y => y.Rate)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
    public class RateRepository
    {
        public string Client { get; set; }
        public string ItemName { get; set; }
        public decimal Rate { get; set; }
    }

}
</code>```

Title: Update a List of KeyValue pair

Body:
I have a WPF application where I need to implement this concept:

There is a combobox and a datagrid. The combobox holds a list of sellers, and the datagrid holds the rates of items they sell.

I want something like this:

client -> null

item    |   rate
--------------------
itemA   |   0.00
itemB   |   0.00
itemC   |   0.00

When none of the client (seller) is selected, all the rates of items default to 0.00.

Now, let's say I choose a client by name of clientA, who does not sell ItemB. Then, the display should reflect this.

client -> clientA

item    |   rate
--------------------
itemA   |   5.00
itemB   |   0.00
itemC   |   8.00

Basically, it should show 0.00 instead of null for the items a client does not sell.

This is actually the work of a Dictionary, or in case of WPF, an ObservableDictionary.

But, I am using Caliburn, and I would like to solve it by using BindableCollection.

So, I have something similar to this:

if (SelectedReferenceClient == null)
{
    Rates = new BindableCollection<KeyValuePair<string, decimal>>(itemrepository.FindWhere(c => true).Select(c => new KeyValuePair<string, decimal>(key: c.Name, value: 0)));;
} //retrieve all items and put value to zero.

    var SelectedClientRates = new List<KeyValuePair<string, decimal>>(raterepository.FindWhere(c => c.Client == SelectedClient).Select(c => new KeyValuePair<string, decimal>(key: c.ItemName, value: c.Rate)));
    //get rates of items they sell

    foreach (var a in SelectedClientRates)
    {
        var b = Rates.FirstOrDefault(c => c.key == a.key);
        b.value = a.value;
    }//update the values in BindingCollection

This might work, but it's noisy and it's kludgy. Is there any LINQ way to do this? As LINQ abhors side effects, my first thought was that it wasnt possible.

But, if I want to stick to BindableCollection and not use ObservableDictionary, is there any better way to do this?

Body:
See sample code below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication49
{
    class Program
    {

        static void Main(string[] args)
        {
            string SelectedClient = "";
            List<RateRepository> raterepository = new List<RateRepository>();
            Dictionary<string, decimal> SelectedClientRates = raterepository.Where(c => c.Client == SelectedClient)
                .GroupBy(x => x.ItemName, y => y.Rate)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
    public class RateRepository
    {
        public string Client { get; set; }
        public string ItemName { get; set; }
        public decimal Rate { get; set; }
    }

}


问:
Can I see all files from a specific commit?
I can use git ls-files to see all files in the project that are tracked by git.

Can I use this command to see all files that were present in some specific commit? I mean not those files that were changed at the moment of the commit, but the whole files tree like how it works with git ls-files?

答:
This is much simpler than the temporary index method, but the output format differs depending on options:</p>

```<code>git ls-tree --name-only -r <commit>
</code>```

Body:
This is much simpler than the temporary index method, but the output format differs depending on options:

git ls-tree --name-only -r <commit>


问:
Export and import DataFrames to Access file (.mdb)
I have 7 tables which I want to read from an Access file (.mdb), then I need to change the values using pandas DataFrame, and then save them again in a new Access file. Do you have any suggestion on how to do that?
I am relatively new in python, and any support is highly appreciated.</p>

答:
I think you should check this.

https://pypi.python.org/pypi/pyodbc/

Also, to read data from Access Table, try something like this.

```<code># -*- coding: utf-8 -*-
import pypyodbc
pypyodbc.lowercase = False
conn = pypyodbc.connect(
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
    r"Dbq=C:\Users\Public\Database1.accdb;")
cur = conn.cursor()
cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures");
while True:
    row = cur.fetchone()
    if row is None:
        break
    print(u"Creature with ID {0} is {1} ({2})".format(
        row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP")))
cur.close()
conn.close()
</code>```

Or . . . just use VBA, if you are already using Access.

```<code>Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True
</code>```

This could be an options too . . .

```<code>strPath = "V:\Reports\Worklist_Summary.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryEscByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryCreatedByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryClosedByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryCreatedByUsers", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qrySummaries", strPath
</code>```

Or . . . run some VBA scripts . . .

```<code>Option Compare Database
Option Explicit
Private Sub Command2_Click()
  Dim strFile As String
  Dim varItem As Variant

    strFile = InputBox("Designate the path and file name to export to...", "Export")

    If (strFile = vbNullString) Then Exit Sub

    For Each varItem In Me.List0.ItemsSelected
        DoCmd.TransferSpreadsheet transferType:=acExport, _
                                  spreadsheetType:=acSpreadsheetTypeExcel9, _
                                  tableName:=Me.List0.ItemData(varItem), _
                                  fileName:=strFile
    Next

    MsgBox "Process complete.", vbOKOnly, "Export"
End Sub
Private Sub Form_Open(Cancel As Integer)
  Dim strTables As String
  Dim tdf As TableDef

    For Each tdf In CurrentDb.TableDefs
        If (Left(tdf.Name, 4) <> "MSys") Then
            strTables = strTables & tdf.Name & ","
        End If
    Next
    strTables = Left(strTables, Len(strTables) - 1)

    Me.List0.RowSource = strTables
End Sub
</code>```

When all data is exported, do your transformations, and load (back to Access or another destination).

I'll bet you don't even need the export step.  You can probably do everything you need to do in Access, all y itself.

Body:
I think you should check this.

https://pypi.python.org/pypi/pyodbc/

Also, to read data from Access Table, try something like this.

# -*- coding: utf-8 -*-
import pypyodbc
pypyodbc.lowercase = False
conn = pypyodbc.connect(
    r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
    r"Dbq=C:\Users\Public\Database1.accdb;")
cur = conn.cursor()
cur.execute("SELECT CreatureID, Name_EN, Name_JP FROM Creatures");
while True:
    row = cur.fetchone()
    if row is None:
        break
    print(u"Creature with ID {0} is {1} ({2})".format(
        row.get("CreatureID"), row.get("Name_EN"), row.get("Name_JP")))
cur.close()
conn.close()

Or . . . just use VBA, if you are already using Access.

Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True

This could be an options too . . .

strPath = "V:\Reports\Worklist_Summary.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryEscByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryCreatedByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryClosedByDate", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qryCreatedByUsers", strPath
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, "qrySummaries", strPath

Or . . . run some VBA scripts . . .

Option Compare Database
Option Explicit
Private Sub Command2_Click()
  Dim strFile As String
  Dim varItem As Variant

    strFile = InputBox("Designate the path and file name to export to...", "Export")

    If (strFile = vbNullString) Then Exit Sub

    For Each varItem In Me.List0.ItemsSelected
        DoCmd.TransferSpreadsheet transferType:=acExport, _
                                  spreadsheetType:=acSpreadsheetTypeExcel9, _
                                  tableName:=Me.List0.ItemData(varItem), _
                                  fileName:=strFile
    Next

    MsgBox "Process complete.", vbOKOnly, "Export"
End Sub
Private Sub Form_Open(Cancel As Integer)
  Dim strTables As String
  Dim tdf As TableDef

    For Each tdf In CurrentDb.TableDefs
        If (Left(tdf.Name, 4) <> "MSys") Then
            strTables = strTables & tdf.Name & ","
        End If
    Next
    strTables = Left(strTables, Len(strTables) - 1)

    Me.List0.RowSource = strTables
End Sub

When all data is exported, do your transformations, and load (back to Access or another destination).

I'll bet you don't even need the export step.  You can probably do everything you need to do in Access, all y itself.


问:
Swift - Function in other view controller is not being called (protocol / delegate)
I'm trying to call the function updateProgress from a LoadingDataHelper object but my delegate is not being called. I think the problem is that this LoadingDataHelper is not connected to the LoadingDataViewController (I mean like when you're having a UIView and a viewController).

LoadingDataHelper

```<code>protocol LoadingNewDataDelegate: class {
    func updateProgress(progress : Float)
}

class LoadingDataHelper: NSObject {
    var delegate: LoadingNewDataDelegate?
    static let shared = LoadingDataHelper() // shared instance

    func loginUser() {
    //more code
        updateProgressInViewController()
    //more code
    }

    func updateProgressInViewController() {
        delegate?.updateProgress(0.3)
    }

}
</code>```

LoadingDataViewController

```<code>class LoadingDataViewController: UIViewController, LoadingNewDataDelegate {

let loadingDataHelper: LoadingDataHelper = LoadingDataHelper()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadingDataHelper.delegate = self
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        if (NSUserDefaults.standardUserDefaults().boolForKey("approvedTermsOfUse")) {
            self.updateProgress(0.1)
            LoadingDataHelper.shared.loginUser()
        } else {
            self.askForTerms()
        }
    }

    func updateProgress(progress : Float) {
        self.progressBar.setProgress(progress, animated: true)
        self.progressBar.setNeedsDisplay()
    }
}
</code>```

Is there a way to solve this?

答:
There is some wrong in above codeL:
In LoadingDataViewController, you are creating static property for LoadingDataHelper class and setting delegate to that class. But you are call "loginUser" using direct call.

You need to change like below:

```<code>class LoadingDataViewController: UIViewController, LoadingNewDataDelegate {
**//Change to shared initialisation of object//**
let loadingDataHelper: LoadingDataHelper = LoadingDataHelper.shared

    override func viewDidLoad() {
        super.viewDidLoad()
        loadingDataHelper.delegate = self
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        if (NSUserDefaults.standardUserDefaults().boolForKey("approvedTermsOfUse")) {
            self.updateProgress(0.1)
           **//Call using static object instead of new instance or direct call//**
            loadingDataHelper.loginUser()
        } else {
            self.askForTerms()
        }
    }

    func updateProgress(progress : Float) {
        self.progressBar.setProgress(progress, animated: true)
        self.progressBar.setNeedsDisplay()
    }
}
</code>```

This will make your controller to get delegate call back.

Body:
I'm trying to call the function updateProgress from a LoadingDataHelper object but my delegate is not being called. I think the problem is that this LoadingDataHelper is not connected to the LoadingDataViewController (I mean like when you're having a UIView and a viewController).

LoadingDataHelper

protocol LoadingNewDataDelegate: class {
    func updateProgress(progress : Float)
}

class LoadingDataHelper: NSObject {
    var delegate: LoadingNewDataDelegate?
    static let shared = LoadingDataHelper() // shared instance

    func loginUser() {
    //more code
        updateProgressInViewController()
    //more code
    }

    func updateProgressInViewController() {
        delegate?.updateProgress(0.3)
    }

}

LoadingDataViewController

class LoadingDataViewController: UIViewController, LoadingNewDataDelegate {

let loadingDataHelper: LoadingDataHelper = LoadingDataHelper()

    override func viewDidLoad() {
        super.viewDidLoad()
        loadingDataHelper.delegate = self
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        if (NSUserDefaults.standardUserDefaults().boolForKey("approvedTermsOfUse")) {
            self.updateProgress(0.1)
            LoadingDataHelper.shared.loginUser()
        } else {
            self.askForTerms()
        }
    }

    func updateProgress(progress : Float) {
        self.progressBar.setProgress(progress, animated: true)
        self.progressBar.setNeedsDisplay()
    }
}

Is there a way to solve this?

Body:
There is some wrong in above codeL:
In LoadingDataViewController, you are creating static property for LoadingDataHelper class and setting delegate to that class. But you are call "loginUser" using direct call.

You need to change like below:

class LoadingDataViewController: UIViewController, LoadingNewDataDelegate {
**//Change to shared initialisation of object//**
let loadingDataHelper: LoadingDataHelper = LoadingDataHelper.shared

    override func viewDidLoad() {
        super.viewDidLoad()
        loadingDataHelper.delegate = self
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        if (NSUserDefaults.standardUserDefaults().boolForKey("approvedTermsOfUse")) {
            self.updateProgress(0.1)
           **//Call using static object instead of new instance or direct call//**
            loadingDataHelper.loginUser()
        } else {
            self.askForTerms()
        }
    }

    func updateProgress(progress : Float) {
        self.progressBar.setProgress(progress, animated: true)
        self.progressBar.setNeedsDisplay()
    }
}

This will make your controller to get delegate call back.


问:
Python trigonometric calculations in degrees
I am converting a MATLAB program to Python for a project. I am facing some major issues with converting MATLAB's sind() syntax to Python. I'm using

```<code>numpy.sin(numpy.radians())
</code>```

but some of the results in Python compared to Matlab are displaying tremendous variations. Is there an easier way to tell Python in degrees instead of radians?

答:
In Octave, sind is:

```<code>function y = sind (x)
  ...
  I = x / 180;
  y = sin (I .* pi);
  y(I == fix (I) & isfinite (I)) = 0;
endfunction
</code>```

np.radians (np.deg2rad) is, according to a note x * pi / 180.

So for most values np.sin(np.radians(x)) should be the same as sind(x).  There might be some variation off at the limits of floating point precision.  Also I'm not sure what that last line is supposed to be doing.

```<code>In [327]: np.sin(np.radians(0))
Out[327]: 0.0
In [328]: np.sin(np.radians(90))
Out[328]: 1.0
In [329]: np.sin(np.radians(180))
Out[329]: 1.2246467991473532e-16

>> sind(0)
ans = 0
>> sind(90)
ans =  1
>> sind(180)
ans = 0
</code>```

The Octave docs add: Returns zero for elements where 'X/180' is an integer.

So yes there may be differences, but 1e-16 is not a tremendous difference.

I can replicate sind with:

```<code>def sind(x):
    I = x/180.
    y = np.sin(I * np.pi)
    mask = (I == np.trunc(I)) & np.isfinite(I)
    y[mask] = 0
    return y

In [356]: x=np.array([0,90,180,359,360])
In [357]: np.sin(np.radians(x))
Out[357]:
array([  0.00000000e+00,   1.00000000e+00,   1.22464680e-16,
        -1.74524064e-02,  -2.44929360e-16])
In [358]: sind(x)
Out[358]: array([ 0.        ,  1.        ,  0.        , -0.01745241,  0.        ])

>> x=[0,90,180,359, 360]
x =
     0    90   180   359   360
>> sind(x)
ans =
   0.00000   1.00000   0.00000  -0.01745   0.00000
</code>```

Body:
I am converting a MATLAB program to Python for a project. I am facing some major issues with converting MATLAB's sind() syntax to Python. I'm using

numpy.sin(numpy.radians())

but some of the results in Python compared to Matlab are displaying tremendous variations. Is there an easier way to tell Python in degrees instead of radians?

Body:
In Octave, sind is:

function y = sind (x)
  ...
  I = x / 180;
  y = sin (I .* pi);
  y(I == fix (I) & isfinite (I)) = 0;
endfunction

np.radians (np.deg2rad) is, according to a note x * pi / 180.

So for most values np.sin(np.radians(x)) should be the same as sind(x).  There might be some variation off at the limits of floating point precision.  Also I'm not sure what that last line is supposed to be doing.

In [327]: np.sin(np.radians(0))
Out[327]: 0.0
In [328]: np.sin(np.radians(90))
Out[328]: 1.0
In [329]: np.sin(np.radians(180))
Out[329]: 1.2246467991473532e-16

>> sind(0)
ans = 0
>> sind(90)
ans =  1
>> sind(180)
ans = 0

The Octave docs add: Returns zero for elements where 'X/180' is an integer.

So yes there may be differences, but 1e-16 is not a tremendous difference.

I can replicate sind with:

def sind(x):
    I = x/180.
    y = np.sin(I * np.pi)
    mask = (I == np.trunc(I)) & np.isfinite(I)
    y[mask] = 0
    return y

In [356]: x=np.array([0,90,180,359,360])
In [357]: np.sin(np.radians(x))
Out[357]:
array([  0.00000000e+00,   1.00000000e+00,   1.22464680e-16,
        -1.74524064e-02,  -2.44929360e-16])
In [358]: sind(x)
Out[358]: array([ 0.        ,  1.        ,  0.        , -0.01745241,  0.        ])

>> x=[0,90,180,359, 360]
x =
     0    90   180   359   360
>> sind(x)
ans =
   0.00000   1.00000   0.00000  -0.01745   0.00000


问:
How to add jsonobject in to jsonarray which i want
I can do only add jsonobj and json obj like in the left hand side in this picture

but if i want to add data like right hand side  what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}
</code>```

答:
You can use following code to try it.</p>

```<code>JSONArray ja = new JSONArray();
ja.put(dataToSend);
</code>```

Body:
I can do only add jsonobj and json obj like in the left hand side in this picture

but if i want to add data like right hand side  what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}

Body:
You can use following code to try it.

JSONArray ja = new JSONArray();
ja.put(dataToSend);