问:
Django: text-input instead selection on foreignkey
I want to create a messaging function in ma django app. User should be able to write other users a textmessage.

models.py

```<code>from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ForeignKey(User, null=True)
    contentDescription = models.CharField(max_length=1000, null=True)
</code>```

By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) .

Integer

But with forms.py

```<code>recipient =         forms.IntegerField(    widget=forms.NumberInput , required=False,)
</code>```

I get:

```<code>    Cannot assign "11": "Transport.recipient" must be a "User" instance.
</code>```

ChoiceField and NumberInput

with:

```<code>recipient =          forms.ChoiceField(  widget=forms.NumberInput, required=False,)
</code>```

I get the error message "not valid"

Is it possible to write the foreignkey 'manually' at all?

答:
considering your

models.py -

```<code>from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ManytoMany(User, null=True)
    contentDescription = models.TextField()
</code>```

forms.py

```<code>from .models import Message
from django import forms
from django.contrib.auth.models import User

class MailForm(forms.ModelForm):
     recipient = forms.Charfield()
     class Meta:
           model = Message
           fields = ('contentDescription',)

     def clean_recipient(self):
         user_list = self.cleaned_data.get('recipient')
         # considering you post user_list of usernames as 'username1,username2,username3'
         if user_list is not None:
            user_list = user_list.split(',')
            user_qs = User.objects.filter(username__in=userlist)
         else:
            raise forms.ValidationError('Error in this field')
         return user_qs

def save(self, user_qs):
    self.instance.user = user_qs
    return super().save()
</code>```

in views.py -

```<code>from .forms import MailForm
def your_view(request):
    form = MailForm(request.POST or None)
    if form.is_valid():
       user_qs=form.cleaned_data.get('recipient')
       form.save(user_qs)
       #return render here
    else:
         #create your context here and return render
</code>```

This is not perfect but can give you an idea how to implement. With the details you gave this is the best I can do for now.

Body:
I want to create a messaging function in ma django app. User should be able to write other users a textmessage.

models.py

from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ForeignKey(User, null=True)
    contentDescription = models.CharField(max_length=1000, null=True)

By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) .

Integer

But with forms.py

recipient =         forms.IntegerField(    widget=forms.NumberInput , required=False,)

I get:

    Cannot assign "11": "Transport.recipient" must be a "User" instance.

ChoiceField and NumberInput

with:

recipient =          forms.ChoiceField(  widget=forms.NumberInput, required=False,)

I get the error message "not valid"

Is it possible to write the foreignkey 'manually' at all?

Body:
considering your

models.py -

from django.contrib.auth.models import User
class Message(models.Model):
    recipient   = models.ManytoMany(User, null=True)
    contentDescription = models.TextField()

forms.py

from .models import Message
from django import forms
from django.contrib.auth.models import User

class MailForm(forms.ModelForm):
     recipient = forms.Charfield()
     class Meta:
           model = Message
           fields = ('contentDescription',)

     def clean_recipient(self):
         user_list = self.cleaned_data.get('recipient')
         # considering you post user_list of usernames as 'username1,username2,username3'
         if user_list is not None:
            user_list = user_list.split(',')
            user_qs = User.objects.filter(username__in=userlist)
         else:
            raise forms.ValidationError('Error in this field')
         return user_qs

def save(self, user_qs):
    self.instance.user = user_qs
    return super().save()

in views.py -

from .forms import MailForm
def your_view(request):
    form = MailForm(request.POST or None)
    if form.is_valid():
       user_qs=form.cleaned_data.get('recipient')
       form.save(user_qs)
       #return render here
    else:
         #create your context here and return render

This is not perfect but can give you an idea how to implement. With the details you gave this is the best I can do for now.


来源: stackexchange

问:
embedding ARM assembly in C language
My goal is to implement sorting algorithm using C language.
I have to make a C code that converts into least number of instructions when compiled by gcc -O0(no optimization option) in ARM machine.
So, My idea is to embed quicksort implemented in assembly directly into C code.
I referred to several following documents and tried to implement my goal.
However, I don't know how to put intarray into my assembly function 'QuickSort' as a parameter.

Reference
1.https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Quicksort#ARM_Assembly
2.http://forum.falinux.com/zbxe/index.php?mid=lecture_tip&comment_srl=517498&sort_index=readed_count&order_type=asc&l=fr&page=58&document_srl=567970    (sorry for non-english website)

I'm newbie in assembly.
Please help me..

```<code>#include <stdio.h>
#include <stdint.h>
int Quicksort(uint32_t intarray[]);

asm(
".global Quicksort\n\
Quicksort:\n\
qsort:\n\
    stmfd   sp!,{r4, r6, lr}     \n\
    mov     r6,r2                \n\
qsort_tailcall_entry:\n\
    sub     r7,r6,r1\n\
    cmp     r7,#1\n\
    ldmlefd sp!,{r4,r6,pc}\n\
    ldr     r7,[r0,r1,asl#2]\n\
    add     r2,r1,#1\n\
    mov     r4,r6\n\
partition_loop:\n\
    ldr     r3,[r0, r2, asl #2]\n\
    cmp     r3,r7\n\
    addle   r2,r2, #1\n\
    ble     partition_test\n\
    sub     r4,r4, #1\n\
    ldr     r5,[r0, r4, asl #2]\n\
    str     r5,[r0, r2, asl #2]\n\
    str     r3,[r0, r4, asl #2]\n\
partition_test:\n\
    cmp     r2,r4\n\
    blt     partition_loop\n\
partition_finish:\n\
    sub     r2,r2,#1\n\
    ldr     r3,[r0,r2,asl #2]\n\
    str     r3,[r0,r1,asl #2]\n\
    str     r7,[r0,r2,asl #2]\n\
    bl      qsort\n\
    mov     r1,r4\n\
    b       qsort_tailcall_entry\n\
"
);

int main(void){
    uint32_t intarray[10] = {5,2,5,1,7,5,7,2,3,8};
    Quicksort(intarray);
    return 0;
}
</code>```

答: Since you mentioned that you are compiling with gcc, you could use the gcc asm extension (as the name says, it's a gcc extension and might not be compatible with other compilers). Take a look at basic asm and extended asm. Since you will probably be accessing data from your C code, I advise you to stick with the advanced version which lets you specify memory operands.

ContentLicense: CC BY-SA 3.0

Title: embedding ARM assembly in C language

Body:
My goal is to implement sorting algorithm using C language.
I have to make a C code that converts into least number of instructions when compiled by gcc -O0(no optimization option) in ARM machine.
So, My idea is to embed quicksort implemented in assembly directly into C code.
I referred to several following documents and tried to implement my goal.
However, I don't know how to put intarray into my assembly function 'QuickSort' as a parameter.

Reference
1.https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Quicksort#ARM_Assembly
2.http://forum.falinux.com/zbxe/index.php?mid=lecture_tip&comment_srl=517498&sort_index=readed_count&order_type=asc&l=fr&page=58&document_srl=567970    (sorry for non-english website)

I'm newbie in assembly.
Please help me..

#include <stdio.h>
#include <stdint.h>
int Quicksort(uint32_t intarray[]);

asm(
".global Quicksort\n\
Quicksort:\n\
qsort:\n\
    stmfd   sp!,{r4, r6, lr}     \n\
    mov     r6,r2                \n\
qsort_tailcall_entry:\n\
    sub     r7,r6,r1\n\
    cmp     r7,#1\n\
    ldmlefd sp!,{r4,r6,pc}\n\
    ldr     r7,[r0,r1,asl#2]\n\
    add     r2,r1,#1\n\
    mov     r4,r6\n\
partition_loop:\n\
    ldr     r3,[r0, r2, asl #2]\n\
    cmp     r3,r7\n\
    addle   r2,r2, #1\n\
    ble     partition_test\n\
    sub     r4,r4, #1\n\
    ldr     r5,[r0, r4, asl #2]\n\
    str     r5,[r0, r2, asl #2]\n\
    str     r3,[r0, r4, asl #2]\n\
partition_test:\n\
    cmp     r2,r4\n\
    blt     partition_loop\n\
partition_finish:\n\
    sub     r2,r2,#1\n\
    ldr     r3,[r0,r2,asl #2]\n\
    str     r3,[r0,r1,asl #2]\n\
    str     r7,[r0,r2,asl #2]\n\
    bl      qsort\n\
    mov     r1,r4\n\
    b       qsort_tailcall_entry\n\
"
);

int main(void){
    uint32_t intarray[10] = {5,2,5,1,7,5,7,2,3,8};
    Quicksort(intarray);
    return 0;
}


问:
Stateless Silhouette CookieAuthenticator can't find / deletes cookie
I have a Play app that allows users to log in with social providers, and have authentication set up identically to the Play-Silhouette-Slick seed example. The following code is probably fine, but I included it anyway.

```<code>def authenticate(provider: String): Action[AnyContent] = Action.async { implicit request =>
(socialProviderRegistry.get[SocialProvider](provider) match {
  case Some(provider: SocialProvider with CommonSocialProfileBuilder) =>
    provider.authenticate().flatMap {
      case Left(result) => Future.successful(result) // Redirect user to social provider
      case Right(authInfo) => for {
        profile <- provider.retrieveProfile(authInfo)
        user <- userService.save(profile)
        authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
        authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
        cookie <- silhouette.env.authenticatorService.init(authenticator)
        result <- silhouette.env.authenticatorService.embed(cookie, Redirect(routes.EateriesController.eaterySelection()))
      } yield {
        silhouette.env.eventBus.publish(LoginEvent(user, request))
        println("Just to verify that everything went well")
        result
      }
    }
  case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
}).recover {
  case e: ProviderException =>
    logger.error("Unexpected provider error", e)
    Redirect(routes.SignInController.index()).flashing("error" -> Messages("could.not.authenticate"))
  }
}
</code>```

My problem is that after a user logs in, my application's endpoints fail to detect that the user is logged in. When I get redirected to the page immediately after logging in, I can verify in Firefox that the authenticator cookie is set, but as soon as I navigate to another page in my app then the cookie is no longer present.

I'm guessing my app thinks that the cookie is invalid or something, and then deletes it, but I currently have no clue. Is there some other reason why this could be happening / how should I log my application to narrow down the problem?

答:
I would suggest, that your cookie expired.

You can configure this in CookieAuthenticatorSettings, which has cookieMaxAge set to None, which means the resulting cookie is transient.

Body:
I have a Play app that allows users to log in with social providers, and have authentication set up identically to the Play-Silhouette-Slick seed example. The following code is probably fine, but I included it anyway.

def authenticate(provider: String): Action[AnyContent] = Action.async { implicit request =>
(socialProviderRegistry.get[SocialProvider](provider) match {
  case Some(provider: SocialProvider with CommonSocialProfileBuilder) =>
    provider.authenticate().flatMap {
      case Left(result) => Future.successful(result) // Redirect user to social provider
      case Right(authInfo) => for {
        profile <- provider.retrieveProfile(authInfo)
        user <- userService.save(profile)
        authInfo <- authInfoRepository.save(profile.loginInfo, authInfo)
        authenticator <- silhouette.env.authenticatorService.create(profile.loginInfo)
        cookie <- silhouette.env.authenticatorService.init(authenticator)
        result <- silhouette.env.authenticatorService.embed(cookie, Redirect(routes.EateriesController.eaterySelection()))
      } yield {
        silhouette.env.eventBus.publish(LoginEvent(user, request))
        println("Just to verify that everything went well")
        result
      }
    }
  case _ => Future.failed(new ProviderException(s"Cannot authenticate with unexpected social provider $provider"))
}).recover {
  case e: ProviderException =>
    logger.error("Unexpected provider error", e)
    Redirect(routes.SignInController.index()).flashing("error" -> Messages("could.not.authenticate"))
  }
}

My problem is that after a user logs in, my application's endpoints fail to detect that the user is logged in. When I get redirected to the page immediately after logging in, I can verify in Firefox that the authenticator cookie is set, but as soon as I navigate to another page in my app then the cookie is no longer present.

I'm guessing my app thinks that the cookie is invalid or something, and then deletes it, but I currently have no clue. Is there some other reason why this could be happening / how should I log my application to narrow down the problem?


问:
How to perform a reverse mod?
If I have an equation like (x+c) mod y = z and I need to solve for y, how would I go about doing that?

Apologies if this is more math than programming.

答: No simple formula exists. If a mod n = r then n divides a-r and 0 <= r < n. Candidate n can be found by factoring a - r and finding divisors which are larger than r. Factoring is a much-studied but non-trivial problem. Pick your favorite factoring algorithm. Unless a-r is prime, there won't be a unique solution (unless r is larger than any proper-divisor of a-r).

Title: How to perform a reverse mod?


问:
Build an instance of Gson that can inflate subclasses
I have a list of objects that I need to deserialize into their proper subclasses. I have been able to get this working by building a gson object like below

```<code>    JsonDeserializer<Shape> jdTypes = (json, typeOfT, jsonContext) -> {
        JsonObject jsonObject = json.getAsJsonObject();
        int type = jsonObject.get("type").getAsInt();

        Gson gson = new Gson();

        switch (type){
            case Types.TYPE_CARD:
                return gson.fromJson(json, Card.class);

            case Types.TYPE_BLOCK:
                return gson.fromJson(json, Block.class);

            case Types.TYPE_STRIPE:
                return gson.fromJson(json, Stripe.class);

            //...

        }
    };

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Shape.class, jdTypes);
    builder.create();
</code>```

Although it is working, there has to be a better way of doing it. Currently I am creating an instance of Gson within my GsonBuilder. Yikes.  Is there a way I can use the Gson object I am about to build to deserialize the different sub-types?

答:
No need to reinvent the wheel. Your problem is classic in the scope of Gson, and there is a special RuntimeTypeAdapterFactory that is designed to solve problems of exactly such a kind. For example, if you have something like this:

final class Types {

    private Types() {
    }

    static final int TYPE_CARD = 1;
    static final int TYPE_BLOCK = 2;
    static final int TYPE_STRIPE = 3;

    abstract static class Abstract {

        private Abstract() { }

        static final class Card extends Abstract { }
        static final class Block extends Abstract { }
        static final class Stripe extends Abstract {}

    }

}
```

<p>You can configure and use <code>RuntimeTypeAdapterFactory</code>:</p>

<pre class="lang-java prettyprint-override"><code>private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(
                RuntimeTypeAdapterFactory.of(Types.Abstract.class, "type")
                        .registerSubtype(Types.Abstract.Card.class, String.valueOf(Types.TYPE_CARD))
                        .registerSubtype(Types.Abstract.Block.class, String.valueOf(Types.TYPE_BLOCK))
                        .registerSubtype(Types.Abstract.Stripe.class, String.valueOf(Types.TYPE_STRIPE))
        )
        .create();
</code>```

Then you don't even need anything else:

private static final Type abstractListType = new TypeToken<List<Types.Abstract>>() {
}.getType();

public static void main(final String... args) {
    gson.<List<Types.Abstract>>fromJson("[{\"type\":1},{\"type\":2},{\"type\":3}]", abstractListType)
            .stream()
            .map(Types.Abstract::getClass)
            .forEach(System.out::println);
}
```

Output:

class q43159721.Types$Abstract$Card

  class q43159721.Types$Abstract$Block

  class q43159721.Types$Abstract$Stripe

Body:
I have a list of objects that I need to deserialize into their proper subclasses. I have been able to get this working by building a gson object like below

    JsonDeserializer<Shape> jdTypes = (json, typeOfT, jsonContext) -> {
        JsonObject jsonObject = json.getAsJsonObject();
        int type = jsonObject.get("type").getAsInt();

        Gson gson = new Gson();

        switch (type){
            case Types.TYPE_CARD:
                return gson.fromJson(json, Card.class);

            case Types.TYPE_BLOCK:
                return gson.fromJson(json, Block.class);

            case Types.TYPE_STRIPE:
                return gson.fromJson(json, Stripe.class);

            //...

        }
    };

    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Shape.class, jdTypes);
    builder.create();

Although it is working, there has to be a better way of doing it. Currently I am creating an instance of Gson within my GsonBuilder. Yikes.  Is there a way I can use the Gson object I am about to build to deserialize the different sub-types?

Body:
No need to reinvent the wheel. Your problem is classic in the scope of Gson, and there is a special RuntimeTypeAdapterFactory that is designed to solve problems of exactly such a kind. For example, if you have something like this:

final class Types {

    private Types() {
    }

    static final int TYPE_CARD = 1;
    static final int TYPE_BLOCK = 2;
    static final int TYPE_STRIPE = 3;

    abstract static class Abstract {

        private Abstract() { }

        static final class Card extends Abstract { }
        static final class Block extends Abstract { }
        static final class Stripe extends Abstract {}

    }

}

You can configure and use RuntimeTypeAdapterFactory:

private static final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(
                RuntimeTypeAdapterFactory.of(Types.Abstract.class, "type")
                        .registerSubtype(Types.Abstract.Card.class, String.valueOf(Types.TYPE_CARD))
                        .registerSubtype(Types.Abstract.Block.class, String.valueOf(Types.TYPE_BLOCK))
                        .registerSubtype(Types.Abstract.Stripe.class, String.valueOf(Types.TYPE_STRIPE))
        )
        .create();

Then you don't even need anything else:

private static final Type abstractListType = new TypeToken<List<Types.Abstract>>() {
}.getType();

public static void main(final String... args) {
    gson.<List<Types.Abstract>>fromJson("[{\"type\":1},{\"type\":2},{\"type\":3}]", abstractListType)
            .stream()
            .map(Types.Abstract::getClass)
            .forEach(System.out::println);
}

Output:

class q43159721.Types$Abstract$Card

  class q43159721.Types$Abstract$Block

  class q43159721.Types$Abstract$Stripe


问:
unable remove class inside form-control and add new class bootstrap
I have table with two td's one select country option and another  input text.

```<code>    <tr>
      <td><select name="country" class='form-control country' id="country">
        <option value="">-select country-</option>
        <option value="usa">USA</option>
        <option value="eng">England</option>
        <option value="nzl">New Zealand</option>
      </select></td>
      <td><input type="text" class='form-control country_name'></td>
    </tr>
    <p id="ppl"></p>
</code>```

Here is fiddle https://jsfiddle.net/jvk3/wbzasubL/1/

Based on the country change i need to remove text class and add new class.
For example I have change country to usa  I need remove  text class of country_name with usa_country, if he change country to eng i need remove country_name to eng_country

Here is my jquery code.

```<code>    $(".country").on('change', function(){
  var cty_name = $(this).val();
    $(this).next('td.country_name').removeClass('coutry_name')
    .addClass(çty_name+'_counrty')
    })
</code>```

I have tried many ways but i didn't success.
Thanks for any help

答:
this referes to .country which is not a sibling of .country_name element (your selector is also wrong) thus .next() will never work.

You can use .closest() to traverse up ancestor TD element and then use .next() to target immediately following sibling TD, afterwards use .find() to target INPUT element.

```<code> $(this).closest('td').next('td').find('input').removeClass('coutry_name').addClass(çty_name+'_counrty');
</code>```

OR,

If you have single input, travese up to TR, then use .find()

```<code> $(this).closest('tr').find('input').removeClass('coutry_name').addClass(çty_name+'_counrty');
</code>```

Body:
I have table with two td's one select country option and another  input text.

      <select name="country" class='form-control country' id="country">
        <option value="">-select country-</option>
        <option value="usa">USA</option>
        <option value="eng">England</option>
        <option value="nzl">New Zealand</option>
      </select>
      <input type="text" class='form-control country_name'>

Here is fiddle https://jsfiddle.net/jvk3/wbzasubL/1/

Based on the country change i need to remove text class and add new class.
For example I have change country to usa  I need remove  text class of country_name with usa_country, if he change country to eng i need remove country_name to eng_country

Here is my jquery code.

    $(".country").on('change', function(){
  var cty_name = $(this).val();
    $(this).next('td.country_name').removeClass('coutry_name')
    .addClass(çty_name+'_counrty')
    })

I have tried many ways but i didn't success.
Thanks for any help

Body:
this referes to .country which is not a sibling of .country_name element (your selector is also wrong) thus .next() will never work.

You can use .closest() to traverse up ancestor TD element and then use .next() to target immediately following sibling TD, afterwards use .find() to target INPUT element.

 $(this).closest('td').next('td').find('input').removeClass('coutry_name').addClass(çty_name+'_counrty');

OR,

If you have single input, travese up to TR, then use .find()

 $(this).closest('tr').find('input').removeClass('coutry_name').addClass(çty_name+'_counrty');


问:
AWK: search one column, print list of matches in second column
I have the following TAB delimited file:

```<code>string1 string2 string3 001 string4
string5 string6 string7 002 string8
string9 string10 string11 003 string12
string13 string14 string15 002 string16
</code>```

and I want to use awk to print all items in column 4 and print a list of matches of column 5 next to it
(the number is the identifier)

```<code>001 string4
002 string8, string16
003 string12
</code>```

my current attempt failed:
awk 'BEGIN{FS=OFS="\t"} $4 ~ /^K/ { print $4, print $5 }'

I also do not know how to implement to print me a list in column 2 of the matches.

答:
@tobi:@try:

```<code>awk 'FNR==NR{A[$4]=A[$4]?A[$4]","$NF:$NF;next} ($4 in A){print $4,A[$4];delete A[$4]}'   Input_file  Input_file
</code>```

Checking FNR==NR(this condition will be true when 1st Input_file will be read), so making an array named A whose index is $4 and concatenating it's value with last column to it's own in first read of Input_file, next will leave all next statement. Then looping through in array A with $4 in it, printing the values.

Body:
I have the following TAB delimited file:

string1 string2 string3 001 string4
string5 string6 string7 002 string8
string9 string10 string11 003 string12
string13 string14 string15 002 string16

and I want to use awk to print all items in column 4 and print a list of matches of column 5 next to it
(the number is the identifier)

001 string4
002 string8, string16
003 string12

my current attempt failed:
awk 'BEGIN{FS=OFS="\t"} $4 ~ /^K/ { print $4, print $5 }'

I also do not know how to implement to print me a list in column 2 of the matches.

Body:
@tobi:@try:

awk 'FNR==NR{A[$4]=A[$4]?A[$4]","$NF:$NF;next} ($4 in A){print $4,A[$4];delete A[$4]}'   Input_file  Input_file

Checking FNR==NR(this condition will be true when 1st Input_file will be read), so making an array named A whose index is $4 and concatenating it's value with last column to it's own in first read of Input_file, next will leave all next statement. Then looping through in array A with $4 in it, printing the values.


问:
How do I parse an Excel file that will give me data exactly as it appears visually?
I'm on Rails 5 (Ruby 2.4).  I want to read an .xls doc and I would like to get the data into CSV format, just as it appears in the Excel file.  Someone recommended I use Roo, and so I have

```<code>book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
arr_of_arrs = CSV.parse(text)
</code>```

However what is getting returned is not the same as what I see in the spreadsheet.  For isntance, a cell in the spreadsheet has

```<code>16:45.81
</code>```

and when I get the CSV data from above, what is returned is

```<code>"0.011641319444444444"
</code>```

How do I parse the Excel doc and get exactly what I see?  I don't care if I use Roo to parse or not, just as long as I can get CSV data that is a representation of what I see rather than some weird internal representation.  For reference the file type I was parsing givies this when I run "file name_of_file.xls" ...

```<code>Composite Document File V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: Dwight Schroot, Last Saved By: Dwight Schroot, Name of Creating Application: Microsoft Excel, Create Time/Date: Tue Sep 21 17:05:21 2010, Last Saved Time/Date: Wed Oct 13 16:52:14 2010, Security: 0
</code>```

答:
Your problem seems to be with the way you're parsing (reading) the input file.

roo parses only Excel 2007-2013 (.xlsx) files. From you question, you want to parse .xls, which is a different format.

Like the documentation says, use the roo-xls gem instead.

Body:
I'm on Rails 5 (Ruby 2.4).  I want to read an .xls doc and I would like to get the data into CSV format, just as it appears in the Excel file.  Someone recommended I use Roo, and so I have

book = Roo::Spreadsheet.open(file_location)
sheet = book.sheet(0)
text = sheet.to_csv
arr_of_arrs = CSV.parse(text)

However what is getting returned is not the same as what I see in the spreadsheet.  For isntance, a cell in the spreadsheet has

16:45.81

and when I get the CSV data from above, what is returned is

"0.011641319444444444"

How do I parse the Excel doc and get exactly what I see?  I don't care if I use Roo to parse or not, just as long as I can get CSV data that is a representation of what I see rather than some weird internal representation.  For reference the file type I was parsing givies this when I run "file name_of_file.xls" ...

Composite Document File V2 Document, Little Endian, Os: Windows, Version 5.1, Code page: 1252, Author: Dwight Schroot, Last Saved By: Dwight Schroot, Name of Creating Application: Microsoft Excel, Create Time/Date: Tue Sep 21 17:05:21 2010, Last Saved Time/Date: Wed Oct 13 16:52:14 2010, Security: 0


问:
How often do you find javascript disabled on browsers?
I have started using ajax/jQuery in our websites / application. There are many plugins that support degrading the javascript to browsers that dont have javascript enabled and techniques to support this. What are peoples thoughts on javascript support, we build applications rather than just websites and are looking to just support javascript enabled browsers as a pre-requisite assuming that most people or companies have javascript enabled.
Do you find most people have javascript? do you monitor the percentage of javascript/non-javascript browsers (I guess this can be done with website stats) and what are the numbers regarding this?</p>

答:
I know this is a very old thread, but I thought I'd post this for reference:

According to this website, only 0.4% to 2.4% of users had JS turned off. The first test they ran was with about 13,500 users, which is admittedly small for the interwebs, but it's still quite a large amount of people. This data is from 2009

ContentLicense: CC BY-SA 2.5


问:
Can I use the Amazon fire tablet to test my android react native apps?
I'm looking for the cheapest simplest way to test my react-native apps on a physical device and am looking to buy an android device as my test mule.

The android fire tablet seems to be the cheapest one I can find - but I don't know if it has a bunch of custom Amazon adware that will make testing my custom apps on it difficult or problematic.

Should I be able to test my react-native app builds on Amazon fire just like any other android device - or will does it have customizations that will cause problems?

Do you have any other suggestions for a cheap, pain-free device to buy for android testing.

答: Yes you should be able to run your app. The amazon devices are only an issue if you use google libraries like play services. Just to be safe you can test the compatibility of your app with amazon devices on the following link: https://developer.amazon.com/app-testing-service</p>


问:
Multiple string append together with index
I have multiple string required original string to append different strings. Both of origin string and append string contains 1 int variable Based on my knowledge, both of following code are working but what is the best way to do it or if there is a better way to do it?
or is there any way I can write something like

```<code>newstrg = '{}{}'.format(org%OrgInt, appd%appdInt)
</code>```

first method

```<code>org = "org__%s"
appd = "appd__%s"
orgInt = 1
appdInt = 7
newstrg = org % orgInt + appd % appdInt
print(newstrg)
org__1appd__7
</code>```

Second method

```<code>org = "org__{}"
appd = "appd__{}"
orgInt = 1
appdInt = 7
newstrg = (org + appd).format(orgInt, appdInt)
org__1appd__7
</code>```

答:
Here is another way:</p>

```<code>org_appd = {'org': 1, 'appd': 7}
org = "org__{org}"
appd = "appd__{appd}"

newstrg = (org + appd).format(**org_appd)
</code>```

Body:
I have multiple string required original string to append different strings. Both of origin string and append string contains 1 int variable Based on my knowledge, both of following code are working but what is the best way to do it or if there is a better way to do it?
or is there any way I can write something like

newstrg = '{}{}'.format(org%OrgInt, appd%appdInt)

first method

org = "org__%s"
appd = "appd__%s"
orgInt = 1
appdInt = 7
newstrg = org % orgInt + appd % appdInt
print(newstrg)
org__1appd__7

Second method

org = "org__{}"
appd = "appd__{}"
orgInt = 1
appdInt = 7
newstrg = (org + appd).format(orgInt, appdInt)
org__1appd__7

Body:
Here is another way:

org_appd = {'org': 1, 'appd': 7}
org = "org__{org}"
appd = "appd__{appd}"

newstrg = (org + appd).format(**org_appd)


问:
How to filter columns in dplyr specifying the column with a character object or a vector
I'm creating a function to filter a data frame using the dplyr package.

The name of the column changes and I'm able to specify it using a character object and specifying "one_of" See below:

```<code> ICD=c("ICD.y")

 test<-filter(test1,one_of(ICD)=="9")
</code>```

I'm getting this error:

```<code>Error in filter_impl(.data, quo) : Variable context not set
</code>```

The data frame test1 contains both the variable "ICD.y" and also multiple rows using with a value of 9. I would like to make this filtering by being able to assign the name of the column that I want to filter prior to using the dplyr filter function.

Thank you in advance for your help.

Albit

答:
This can be done with interp from lazyeval

```<code>library(dplyr)
test1 %>%
      filter_(lazyeval::interp(~Col ==9, Col = as.name(ICD)))
</code>```

Body:
I'm creating a function to filter a data frame using the dplyr package.

The name of the column changes and I'm able to specify it using a character object and specifying "one_of" See below:

 ICD=c("ICD.y")

 test<-filter(test1,one_of(ICD)=="9")

I'm getting this error:

Error in filter_impl(.data, quo) : Variable context not set

The data frame test1 contains both the variable "ICD.y" and also multiple rows using with a value of 9. I would like to make this filtering by being able to assign the name of the column that I want to filter prior to using the dplyr filter function.

Thank you in advance for your help.

Albit

Body:
This can be done with interp from lazyeval

library(dplyr)
test1 %>%
      filter_(lazyeval::interp(~Col ==9, Col = as.name(ICD)))


问:
ReadFile on standard input crashes on Windows 7
Trying to read standard input with ReadFile works on Windows 8+ but crashes on Windows 7.

```<code>#include <windows.h>

int main() {
    char c[1];
    HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
    ReadFile(in, c, 1, NULL, NULL);
    return 0;
}
</code>```

produces

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00000000770f5803 in VerifyConsoleIoHandle () from C:\Windows\system32\kernel32.dll
</code>```

on Windows 7

答:
the lpNumberOfBytesRead argument is required, unless the ReadFile will complete asynchronously (the file/device was opened with the correct flags and lpOverlapped is provided)

On Windows 8 and later this parameter is checked for NULL before writing (effectively making it optional) but this is not documented anywhere.

Reading standard input without checking the number of bytes read is a bad idea anyway, since the number of bytes read could be less than requested (or even 0) if input is redirected to a pipe.

Body:
Trying to read standard input with ReadFile works on Windows 8+ but crashes on Windows 7.

#include <windows.h>

int main() {
    char c[1];
    HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
    ReadFile(in, c, 1, NULL, NULL);
    return 0;
}

produces

Program received signal SIGSEGV, Segmentation fault.
0x00000000770f5803 in VerifyConsoleIoHandle () from C:\Windows\system32\kernel32.dll

on Windows 7


问:
Python regex matching Unicode properties
Perl and some other current regex engines support Unicode properties, such as the category, in a regex. E.g. in Perl you can use \p{Ll} to match an arbitrary lower-case letter, or p{Zs} for any space separator. I don't see support for this in either the 2.x nor 3.x lines of Python (with due regrets). Is anybody aware of a good strategy to get a similar effect? Homegrown solutions are welcome.

答: The regex module (an alternative to the standard re module) supports Unicode codepoint properties with the \p{} syntax.


问:
observeSingleEvent(of:with:) fetching old data
Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

```<code>let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )
</code>```

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.

答:
So, my problem had nothing to do with caching or fetching old results. Some of my code logic depended on checking the value of the snapshot parameter that was passed back in the completion handler for observeSingleEvent(of:with:). I wrongly assumed that I could check for a null database value by comparing it with nil; this led to a misinterpretation of results.

The best way to actually check for a null database fetch is by calling the exists() method on a FIRDataSnapshot instance. exists() returns true if the snapshot contains a non-null value.

Body:
Background:

I have an app where new users complete a sign-up form (consisting of a username, email, and a password) to register for an account. When the new user submits the form, the app checks its Firebase Database to see if the username has already been taken. The problem here is that observeSingleEvent(of:with:) is not getting the newest data. When I update the data directly from the Firebase console, the changes are not reflected back in the returned results of observeSingleEvent(of:with:). Even between app restarts, the new data changes are not returned.

The only thing I've seen on the issue is here. A user says not to have persistence enabled when using observeSingleEvent(of:with:). But, I have persistence disabled. Also, I set the keepSynced() on the FIRDatabase instance to false (and I've tried true as well). No luck with either setting.

Here's an example of what I am trying:

let usersDatabaseReference = FIRDatabase.database().reference().child("users")
usersDatabaseReference.keepSynced(false)

// Query the database to see if the username is available
// The user with the username "mark" was removed from the database via the Firebase console
let username = "mark" // This user used to exist in the database (and was previously added through the app).
usersDatabaseReference.child(username).observeSingleEvent(of: .value, with: { (snapshot) in ... } )

The above code block should return the newest data (one where the user "mark" should not exist).

I am wondering if anyone else ran into this problem, or if anyone has possible solutions.

Note: Developing using iOS 10.1 and swift 3.


问:
Skip particular method from showing up in stacktrace
I have been trying to get a reliable way of printing the stack trace at runtime on mobile devices. I came across System.Environment.StackTrace

I am trying something with 3 classes right now:

```<code>public class Test : MonoBehaviour {
    public static void Do() {
        Test3.ActionThing(() => {
            Test2.DoSomethingElse();
        });
    }
}

public class Test2 : MonoBehaviour {
    void Start () {
        Test3.ActionThing(() => {
            Debug.Log("Start execution");
            Test.Do();
        });
    }

    public static void DoSomethingElse(){
        Test3.ActionThing(() => {
            var a = 0;
            a = int.Parse("s1");
        });
    }
}

public class Test3 : MonoBehaviour {
    public static void ActionThing(Action act){
        try{
            if (act != null)
                act();
        }catch(Exception e){
            Debug.LogError("Error occured " + e.Message);
            Debug.LogError("StackTrace was " + Environment.StackTrace);
        }
    }
}
</code>```

I get this stacktrace when the error is thrown

```<code>StackTrace was    at System.Environment.get_StackTrace() in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Environment.cs:line 227
   at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 13
   at Test2.DoSomethingElse() in <ProjectPath>\Test2.cs:line 14
   at Test.<Do>m__0() in <ProjectPath>\Test.cs:line 8
   at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 10
   at Test.Do() in <ProjectPath>\Test.cs:line 7
   at Test2.<Start>m__0() in <ProjectPath>\Test2.cs:line 9
   at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 10
   at Test2.Start() in <ProjectPath>\Test2.cs:line 7
UnityEngine.Debug:LogError(Object)
Test3:ActionThing(Action) (at Assets/Test3.cs:13)
Test2:DoSomethingElse() (at Assets/Test2.cs:14)
Test:<Do>m__0() (at Assets/Test.cs:8)
Test3:ActionThing(Action) (at Assets/Test3.cs:10)
Test:Do() (at Assets/Test.cs:7)
Test2:<Start>m__0() (at Assets/Test2.cs:9)
Test3:ActionThing(Action) (at Assets/Test3.cs:10)
Test2:Start() (at Assets/Test2.cs:7)
</code>```

Obviously, since I want this to be a Debug in the release build, it wont show the internal stack trace, and only the message.

But the problem lies in the stacktrace itself, where it even prints the method at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 10. I want to skip this from showing up in the stack trace.

Any help appreciated, thanks in advance. If the question seems too long, please suggest edits :)

答:
The most straight forward approach is to simply process the Environment.StackTrace string and whipe out the stack frames you don't care about.

```<code> public static void ActionThing(Action act){
    try{
        if (act != null)
            act();
    }catch(Exception e){
        var relevantStackFrames =
            Environment.StackTrace
                .Split('\n')
                .Skip(2)
                .ToArray();
        var relevantStackTrace = string.Join("\n", relevantStackFrames);
        Debug.LogError("Error occured " + e.Message);
        Debug.LogError("StackTrace was " + relevantStackTrace );
    }
}
</code>```

The line where we assign to relevantStackFrames splits the stack trace string into an array of strings, with each element being the line for a corresponding stack frame.  The stack frames for System.Environment.get_StackTrace() and Test3.ActionThing(System.Action act) are the first two elements in this array, and since you don't want them, we use linq's Skip function to exclude them from the collection.  Then we convert the result of the skip operation into an array with ToArray.  So relevantStackFrames is an array of stack frame strings excluding the ones you don't want.

Then we make a string called relevantStackTrace which will contain the string for the whole stack trace.   We just join each element of relevantStackTrace and put the line breaks back with string.Join.

Remember to add using System.Linq so you get access to Skip and ToArray

Body:
I have been trying to get a reliable way of printing the stack trace at runtime on mobile devices. I came across System.Environment.StackTrace

I am trying something with 3 classes right now:

public class Test : MonoBehaviour {
    public static void Do() {
        Test3.ActionThing(() => {
            Test2.DoSomethingElse();
        });
    }
}

public class Test2 : MonoBehaviour {
    void Start () {
        Test3.ActionThing(() => {
            Debug.Log("Start execution");
            Test.Do();
        });
    }

    public static void DoSomethingElse(){
        Test3.ActionThing(() => {
            var a = 0;
            a = int.Parse("s1");
        });
    }
}

public class Test3 : MonoBehaviour {
    public static void ActionThing(Action act){
        try{
            if (act != null)
                act();
        }catch(Exception e){
            Debug.LogError("Error occured " + e.Message);
            Debug.LogError("StackTrace was " + Environment.StackTrace);
        }
    }
}

I get this stacktrace when the error is thrown

StackTrace was    at System.Environment.get_StackTrace() in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System/Environment.cs:line 227
   at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 13
   at Test2.DoSomethingElse() in <ProjectPath>\Test2.cs:line 14
   at Test.<Do>m__0() in <ProjectPath>\Test.cs:line 8
   at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 10
   at Test.Do() in <ProjectPath>\Test.cs:line 7
   at Test2.<Start>m__0() in <ProjectPath>\Test2.cs:line 9
   at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 10
   at Test2.Start() in <ProjectPath>\Test2.cs:line 7
UnityEngine.Debug:LogError(Object)
Test3:ActionThing(Action) (at Assets/Test3.cs:13)
Test2:DoSomethingElse() (at Assets/Test2.cs:14)
Test:<Do>m__0() (at Assets/Test.cs:8)
Test3:ActionThing(Action) (at Assets/Test3.cs:10)
Test:Do() (at Assets/Test.cs:7)
Test2:<Start>m__0() (at Assets/Test2.cs:9)
Test3:ActionThing(Action) (at Assets/Test3.cs:10)
Test2:Start() (at Assets/Test2.cs:7)

Obviously, since I want this to be a Debug in the release build, it wont show the internal stack trace, and only the message.

But the problem lies in the stacktrace itself, where it even prints the method at Test3.ActionThing(System.Action act) in <ProjectPath>\Test3.cs:line 10. I want to skip this from showing up in the stack trace.

Any help appreciated, thanks in advance. If the question seems too long, please suggest edits :)

Body:
The most straight forward approach is to simply process the Environment.StackTrace string and whipe out the stack frames you don't care about.

 public static void ActionThing(Action act){
    try{
        if (act != null)
            act();
    }catch(Exception e){
        var relevantStackFrames =
            Environment.StackTrace
                .Split('\n')
                .Skip(2)
                .ToArray();
        var relevantStackTrace = string.Join("\n", relevantStackFrames);
        Debug.LogError("Error occured " + e.Message);
        Debug.LogError("StackTrace was " + relevantStackTrace );
    }
}

The line where we assign to relevantStackFrames splits the stack trace string into an array of strings, with each element being the line for a corresponding stack frame.  The stack frames for System.Environment.get_StackTrace() and Test3.ActionThing(System.Action act) are the first two elements in this array, and since you don't want them, we use linq's Skip function to exclude them from the collection.  Then we convert the result of the skip operation into an array with ToArray.  So relevantStackFrames is an array of stack frame strings excluding the ones you don't want.

Then we make a string called relevantStackTrace which will contain the string for the whole stack trace.   We just join each element of relevantStackTrace and put the line breaks back with string.Join.

Remember to add using System.Linq so you get access to Skip and ToArray


问:
How to display Total cost of products added in wishlist using yith woocommerce wishlist plugin?
I'm developing E-Commerce website using Wordpress and Woocommerce plugins.
I've installed yith Woocommerce wishlist plugin for user to add product in wishlist, it's display unit product cost, add to cart button and product image.

I want to display Total product cost added in wishlist and for that add to cart button also. Please help.

答:
To display Total product cost with YITH Woocommerce Wishlist plugin, you can do this with Jquery :

```<code>var myArray = $(".wishlist_table .amount"); // Recover all product cost
var result = 0;
for (var i = 0; i<myArray.length; i++) {
    result += parseFloat(myArray[i].childNodes["0"].data); // Make the sum
}

$("#som").text(result); // Place total in a HTML element - my ID is "som" but no matter what it is

$(".remove_from_wishlist").live('click', function(){ // When user remove item with AJAX
    var href = $(this).attr('href'); // Find parent
    href = href.replace(/\D/g,'');
    var arrayTo = $('#yith-wcwl-row-'+href+' .amount').text();
    arrayTo = parseFloat(arrayTo.replace(/\u20ac/g, '')); // u20ac is unicode character for euro sign but works with just 'D' instead
    var recoverTotal = $("#som").text(); // Recover the total
    var result2 = recoverTotal - arrayTo;
    $("#som").text(result2); // Display the final result
});
</code>```

You have to put this code in a shortcode function. It works for me.

ContentLicense: CC BY-SA 4.0

Body:
To display Total product cost with YITH Woocommerce Wishlist plugin, you can do this with Jquery :

var myArray = $(".wishlist_table .amount"); // Recover all product cost
var result = 0;
for (var i = 0; i<myArray.length; i++) {
    result += parseFloat(myArray[i].childNodes["0"].data); // Make the sum
}

$("#som").text(result); // Place total in a HTML element - my ID is "som" but no matter what it is

$(".remove_from_wishlist").live('click', function(){ // When user remove item with AJAX
    var href = $(this).attr('href'); // Find parent
    href = href.replace(/\D/g,'');
    var arrayTo = $('#yith-wcwl-row-'+href+' .amount').text();
    arrayTo = parseFloat(arrayTo.replace(/\u20ac/g, '')); // u20ac is unicode character for euro sign but works with just 'D' instead
    var recoverTotal = $("#som").text(); // Recover the total
    var result2 = recoverTotal - arrayTo;
    $("#som").text(result2); // Display the final result
});

You have to put this code in a shortcode function. It works for me.


问:
I want to write javascript code to get a addition countdown
so basically this the prompt:

Addition countdown

you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.

This is what I have so far:

```<code>var num = Number(prompt("Enter a Number Greater than zero"));

while (num > 0){

    first = num;

    second = num-=1;

    document.write(first +  " +" + second + " +");

    value = first + num;

    document.write(value)
    num--;
}
</code>```

but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)

I'm stuck can someone please help me????!!

答:
You could change the algorithm a bit, because for the first value, you need no plus sign for the output.

var num = Number(prompt("Enter a Number Greater than zero")),
    value = 0;

document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
    document.body.appendChild(document.createTextNode(' + ' + num));
    value += num;
    num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));```

Body:
so basically this the prompt:

Addition countdown

you enter a number and the code should be adding a number while countingdown, for example if the user enter 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55.

This is what I have so far:

var num = Number(prompt("Enter a Number Greater than zero"));

while (num > 0){

    first = num;

    second = num-=1;

    document.write(first +  " +" + second + " +");

    value = first + num;

    document.write(value)
    num--;
}

but I keep on getting something like this:
4 +3 +72 +1 +3 (let's say 4 is the number the user inputs)

I'm stuck can someone please help me????!!


问:
How to configure Presto searches to be case-insensitive?
In my case, Presto connects to a MySQL database which has been configured to be case-insensitive. But any search through Presto seems to be case-sensitive.

Questions:

1) Is there a way to configure Presto searches to be case-insensitive? If not, can something be changed in the Presto-MySQL connector to make the searches case-insensitive?

2) If underlying DB is case-insensitive, shouldn't Presto searches also be case-insensitive? (I presume that Presto only generates the query plan and the actual execution happens on the underlying database)

Example: Consider the below table on MySQL.

```<code>name
____
adam

Alan

select * from table where name like '%a%'
// returns adam, Alan on MySQL
// returns only adam on Presto

select * from table where name = 'Adam'
// returns adam on MySQL
// returns NIL on Presto
</code>```

答:
You have to explicitly ask for case-insensitive comparison by normalizing compared values either to-lower, or to-upper, like this:</p>

```<code>select * from table where lower(name) like '%a%';

select * from table where lower(name) = lower('Adam');
</code>```

Body:
In my case, Presto connects to a MySQL database which has been configured to be case-insensitive. But any search through Presto seems to be case-sensitive.

Questions:

1) Is there a way to configure Presto searches to be case-insensitive? If not, can something be changed in the Presto-MySQL connector to make the searches case-insensitive?

2) If underlying DB is case-insensitive, shouldn't Presto searches also be case-insensitive? (I presume that Presto only generates the query plan and the actual execution happens on the underlying database)

Example: Consider the below table on MySQL.

name
____
adam

Alan

select * from table where name like '%a%'
// returns adam, Alan on MySQL
// returns only adam on Presto

select * from table where name = 'Adam'
// returns adam on MySQL
// returns NIL on Presto

Body:
You have to explicitly ask for case-insensitive comparison by normalizing compared values either to-lower, or to-upper, like this:

select * from table where lower(name) like '%a%';

select * from table where lower(name) = lower('Adam');


问:
How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites
The question is how to format a JavaScript Date as a string stating the time elapsed similar to the way you see times displayed on Stack Overflow.

e.g.

1 minute ago

1 hour ago

1 day ago

1 month ago

1 year ago

答:
```<code>function timeago(date) {
    var seconds = Math.floor((new Date() - date) / 1000);
    if(Math.round(seconds/(60*60*24*365.25)) >= 2) return Math.round(seconds/(60*60*24*365.25)) + " years ago";
    else if(Math.round(seconds/(60*60*24*365.25)) >= 1) return "1 year ago";
    else if(Math.round(seconds/(60*60*24*30.4)) >= 2) return Math.round(seconds/(60*60*24*30.4)) + " months ago";
    else if(Math.round(seconds/(60*60*24*30.4)) >= 1) return "1 month ago";
    else if(Math.round(seconds/(60*60*24*7)) >= 2) return Math.round(seconds/(60*60*24*7)) + " weeks ago";
    else if(Math.round(seconds/(60*60*24*7)) >= 1) return "1 week ago";
    else if(Math.round(seconds/(60*60*24)) >= 2) return Math.round(seconds/(60*60*24)) + " days ago";
    else if(Math.round(seconds/(60*60*24)) >= 1) return "1 day ago";
    else if(Math.round(seconds/(60*60)) >= 2) return Math.round(seconds/(60*60)) + " hours ago";
    else if(Math.round(seconds/(60*60)) >= 1) return "1 hour ago";
    else if(Math.round(seconds/60) >= 2) return Math.round(seconds/60) + " minutes ago";
    else if(Math.round(seconds/60) >= 1) return "1 minute ago";
    else if(seconds >= 2)return seconds + " seconds ago";
    else return seconds + "1 second ago";
}
</code>```


答:
Use Awk as below,

```<code>awk 'BEGIN{FS=OFS="\t"}{unique[$4]=(unique[$4] FS $5); next}END{for (i in unique) print i,unique[i]}' file
</code>```

which produces an output as below. Remember this does not retain the order, assuming it does not matter though.

```<code>002     string8 string16
003     string12
001     string4
</code>```

If you are worried bout having comma separated values as in question, do it as

```<code>awk 'BEGIN{FS=OFS="\t"}{unique[$4]=(unique[$4]?(unique[$4]","$5):($5)); next}END{for (i in unique) print i,unique[i]}' file
</code>```

to produce an output as

```<code>002 string8,string16
003 string12
001 string4
</code>```

The idea is

Since Awk process files one line at a time, hash-map array unique is created with $4 being the index and value being $5

When more than one value of $5 is present per index, the values are appended to the existing value with a , de-limiter added. The ternary operator takes care of that, which works by seeing the array element has a value if so append the new value with , or if empty assign the $5 value directly.

The END clause prints the formed hash-map, key and key-value which will get the value as needed.

Title: AWK: search one column, print list of matches in second column

Body:
Use Awk as below,

awk 'BEGIN{FS=OFS="\t"}{unique[$4]=(unique[$4] FS $5); next}END{for (i in unique) print i,unique[i]}' file

which produces an output as below. Remember this does not retain the order, assuming it does not matter though.

002     string8 string16
003     string12
001     string4

If you are worried bout having comma separated values as in question, do it as

awk 'BEGIN{FS=OFS="\t"}{unique[$4]=(unique[$4]?(unique[$4]","$5):($5)); next}END{for (i in unique) print i,unique[i]}' file

to produce an output as

002 string8,string16
003 string12
001 string4

The idea is

Since Awk process files one line at a time, hash-map array unique is created with $4 being the index and value being $5

When more than one value of $5 is present per index, the values are appended to the existing value with a , de-limiter added. The ternary operator takes care of that, which works by seeing the array element has a value if so append the new value with , or if empty assign the $5 value directly.

The END clause prints the formed hash-map, key and key-value which will get the value as needed.


答:
You can keep total in one variable outside of while loop.

var num = Number(prompt("Enter a Number Greater than zero"));

var total = 0;
while (num > 0) {
  total += num;
  document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
  num--;
}```

Title: I want to write javascript code to get a addition countdown


问:
C++: creating multiple data structures using a for loop
I have a program where I use records of the form:

```<code>// declaring a struct for each record
struct record
{
    int number;             // number of record
    vector<int> content;    // content of record
};
</code>```

Within main I then declare each record:

```<code>record batch_1;         // stores integers from 1 - 64
record batch_2;         // stores integers from 65 - 128
</code>```

Where each batch stores 64 integers from a list of numbers (in this instance from a list of 128 total numbers). I would like to make this program open ended, such that the program is capable of handling any list size (with the constraint of it being a multiple of 64). Therefore, if the list size was 256 I would need four records (batch_1 - batch_4). I am not sure how I can create N-many records, but I am looking for something like this (which is clearly not the solution):

```<code>//creating the batch records
for (int i = 1; i <= (list_size / 64); i++)
{
    record batch_[i];   // each batch stores 64 integers
}
</code>```

How can this be done, and will the scope of something declared within the for loop extend beyond the loop itself? I imagine an array would satisfy the scope requirement, but I am not sure how to implement it.

答:
Like many suggested in the comments why not use a resizable vector provided by the C++ Standard Library: std::vector?

So, instead of having this:

```<code>record batch_1;         // stores integers from 1 - 64
record batch_2;         // stores integers from 65 - 128
.
.
record batch_n          // Stores integers x - y
</code>```

Replace with:

```<code>std::vector<record> batches;

//And to create the the batch records
for (int i = 1; i <= (list_size / 64); i++) {
    record r;
    r.number = i;
    r.content = ....;
    batches.push_back(r);
    // You could also declare a constructor for your record struct to facilitate instantiating it.
}
</code>```

Body:
I have a program where I use records of the form:

// declaring a struct for each record
struct record
{
    int number;             // number of record
    vector<int> content;    // content of record
};

Within main I then declare each record:

record batch_1;         // stores integers from 1 - 64
record batch_2;         // stores integers from 65 - 128

Where each batch stores 64 integers from a list of numbers (in this instance from a list of 128 total numbers). I would like to make this program open ended, such that the program is capable of handling any list size (with the constraint of it being a multiple of 64). Therefore, if the list size was 256 I would need four records (batch_1 - batch_4). I am not sure how I can create N-many records, but I am looking for something like this (which is clearly not the solution):

//creating the batch records
for (int i = 1; i <= (list_size / 64); i++)
{
    record batch_[i];   // each batch stores 64 integers
}

How can this be done, and will the scope of something declared within the for loop extend beyond the loop itself? I imagine an array would satisfy the scope requirement, but I am not sure how to implement it.

Body:
Like many suggested in the comments why not use a resizable vector provided by the C++ Standard Library: std::vector?

So, instead of having this:

record batch_1;         // stores integers from 1 - 64
record batch_2;         // stores integers from 65 - 128
.
.
record batch_n          // Stores integers x - y

Replace with:

std::vector<record> batches;

//And to create the the batch records
for (int i = 1; i <= (list_size / 64); i++) {
    record r;
    r.number = i;
    r.content = ....;
    batches.push_back(r);
    // You could also declare a constructor for your record struct to facilitate instantiating it.
}


问:
How to write if and else statement more elegantly in Swift
I'm having a bit of a brain fart in Swift and I know this code could be written better. Basically what it is, I have two images and I check if a value is over 3 to show an image and hide the other.
currently I have it like this

```<code>let greaterThanThree = value > 3
image1.isHidden = greaterThanThree
image2.isHidden = !greaterThanThree
</code>```

But I feel like there is a more elegant way to write this.

答:
There seems to be a rule here that exactly one of these two views should be visible at all times. If so, I'd create, as part of my view controller's viewDidLoad, an instance of this struct:

```<code>struct AlternateViews {
    let views : [UIView]
    init(_ v1:UIView, _ v2:UIView) {
        views = [v1,v2]
    }
    func hide(first:Bool) {
        views[0].isHidden = first
        views[1].isHidden = !first
    }
}
let alternateViews = AlternateViews(image1, image2)
</code>```

Okay, that's a lot of work to set up initially, but the result is that later you can just say

```<code>self.alternateViews.hide(first: value > 3)
</code>```

The struct is acting as a tiny state machine, making sure that your view controller's views remain in a coherent state. This technique of moving the rules for state into utility structs attached to your view controller is recommended in a WWDC 2016 video and I've been making a lot of use of it ever since.

If you have more pairs of alternating views, just make and maintain more instances of the struct.

(If the rule that I've assumed is not quite the real rule, make a struct that does express the real rule.)

Body:
I'm having a bit of a brain fart in Swift and I know this code could be written better. Basically what it is, I have two images and I check if a value is over 3 to show an image and hide the other.
currently I have it like this

let greaterThanThree = value > 3
image1.isHidden = greaterThanThree
image2.isHidden = !greaterThanThree

But I feel like there is a more elegant way to write this.

Body:
There seems to be a rule here that exactly one of these two views should be visible at all times. If so, I'd create, as part of my view controller's viewDidLoad, an instance of this struct:

struct AlternateViews {
    let views : [UIView]
    init(_ v1:UIView, _ v2:UIView) {
        views = [v1,v2]
    }
    func hide(first:Bool) {
        views[0].isHidden = first
        views[1].isHidden = !first
    }
}
let alternateViews = AlternateViews(image1, image2)

Okay, that's a lot of work to set up initially, but the result is that later you can just say

self.alternateViews.hide(first: value > 3)

The struct is acting as a tiny state machine, making sure that your view controller's views remain in a coherent state. This technique of moving the rules for state into utility structs attached to your view controller is recommended in a WWDC 2016 video and I've been making a lot of use of it ever since.

If you have more pairs of alternating views, just make and maintain more instances of the struct.

(If the rule that I've assumed is not quite the real rule, make a struct that does express the real rule.)


答:
Why don't you try this

```<code>    // code
    vector<record> v(list_size / 64);
    // additinal code goes here
</code>```

Now,you can access your data as follow

```<code>    (v[i].content).at(j);
</code>```

Title: C++: creating multiple data structures using a for loop

Body:
Why don't you try this

    // code
    vector<record> v(list_size / 64);
    // additinal code goes here

Now,you can access your data as follow

    (v[i].content).at(j);


问:
How to pass arguments to functions in React js?

I want to display person's email in the alert window. But, I do not know how to pass email as arguments to displayAlert method. Also, it wont let me use  either. So, I have to assign displayAlert methos to a variable and use it in onClick. I do not know why it wont let me call it directly.

```<code>class People extends React.Component{
render (){
        var handleClick = this.displayAlert;
        var items = this.props.items.map(function(item) {
            return(
                <ul key = {item.id}>
                    <li>
                        <button onClick= {handleClick}>{item.lastName + ', ' + item.firstName}</button>
                    </li>
                </ul>
            )
        });
        return (<div>{items}</div>);
 }

displayAlert (){
    alert('Hi');
}
}

 class PersonList extends React.Component{
     render () {
        return (
    <div>
        <People items={this.props.people}/> /* People is an array of people*/
    </div>
    );
  }
}
</code>```

答:
Using arrow function and babel plugin "transform-class-properties"</p>

```<code>class People extends React.Component {
  render() {
    return (
      <ul>
        { this.props.items.map( (item) => (
          <li key={item.id}>
            <button onClick={this.displayAlert(item)}>
              {item.lastName + ', ' + item.firstName}
            </button>
          </li>
        ))}
      </ul>
    )
  }

  displayAlert = (item) => (event) => {
    // you can access the item object and the event object
    alert('Hi');
  }
}
</code>```

Body:
I want to display person's email in the alert window. But, I do not know how to pass email as arguments to displayAlert method. Also, it wont let me use  either. So, I have to assign displayAlert methos to a variable and use it in onClick. I do not know why it wont let me call it directly.

class People extends React.Component{
render (){
        var handleClick = this.displayAlert;
        var items = this.props.items.map(function(item) {
            return(

                        <button onClick= {handleClick}>{item.lastName + ', ' + item.firstName}</button>

            )
        });
        return (
{items}
);
 }

displayAlert (){
    alert('Hi');
}
}

 class PersonList extends React.Component{
     render () {
        return (

        <People items={this.props.people}/> /* People is an array of people*/

    );
  }
}

Body:
Using arrow function and babel plugin "transform-class-properties"

class People extends React.Component {
  render() {
    return (
      <ul>
        { this.props.items.map( (item) => (
          <li key={item.id}>
            <button onClick={this.displayAlert(item)}>
              {item.lastName + ', ' + item.firstName}
            </button>
          </li>
        ))}
      </ul>
    )
  }

  displayAlert = (item) => (event) => {
    // you can access the item object and the event object
    alert('Hi');
  }
}


问:
Creating Windows service without Visual Studio
So creating a Windows service using Visual Studio is fairly trivial.  My question goes a bit deeper as to what actually makes an executable installable as a service & how to write a service as a straight C application.  I couldn't find a lot of references on this, but I'm presuming there has to be some interface I can implement so my .exe can be installed as a service.</p>

答:
Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).

The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.

ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.

Here are some snippets from a service I wrote a few years ago:

set up as service:

```<code>SERVICE_TABLE_ENTRY ServiceStartTable[] =
{
   { "ServiceName", ServiceMain },
   { 0, 0 }
};

if (!StartServiceCtrlDispatcher(ServiceStartTable))
{
   DWORD err = GetLastError();
   if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
      return false;
}
</code>```

ServiceMain:

```<code>void WINAPI ServiceMain(DWORD, LPTSTR*)
{
    hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0);
</code>```

service handler:

```<code>DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)
{
    switch (ControlCode)
    {
    case SERVICE_CONTROL_INTERROGATE :
        // update OS about our status
    case SERVICE_CONTROL_STOP :
        // shut down service
    }

    return 0;
}
</code>```

OwnerDisplayName: Creighton Hogg

LastEditorDisplayName: Chris Upchurch

Body:
Setting up your executable as a service is part of it, but realistically it's usually handled by whatever installation software you're using. You can use the command line SC tool while testing (or if you don't need an installer).

The important thing is that your program has to call StartServiceCtrlDispatcher() upon startup. This connects your service to the service control manager and sets up a ServiceMain routine which is your services main entry point.

ServiceMain (you can call it whatever you like actually, but it always seems to be ServiceMain) should then call RegisterServiceCtrlHandlerEx() to define a callback routine so that the OS can notify your service when certain events occur.

Here are some snippets from a service I wrote a few years ago:

set up as service:

SERVICE_TABLE_ENTRY ServiceStartTable[] =
{
   { "ServiceName", ServiceMain },
   { 0, 0 }
};

if (!StartServiceCtrlDispatcher(ServiceStartTable))
{
   DWORD err = GetLastError();
   if (err == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT)
      return false;
}

ServiceMain:

void WINAPI ServiceMain(DWORD, LPTSTR*)
{
    hServiceStatus = RegisterServiceCtrlHandlerEx("ServiceName", ServiceHandlerProc, 0);

service handler:

DWORD WINAPI ServiceHandlerProc(DWORD ControlCode, DWORD, void*, void*)
{
    switch (ControlCode)
    {
    case SERVICE_CONTROL_INTERROGATE :
        // update OS about our status
    case SERVICE_CONTROL_STOP :
        // shut down service
    }

    return 0;
}

OwnerDisplayName: Ferruccio


问:
C++: Dynamically loading classes from dlls
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

```<code>//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};
</code>```

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

```<code>//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }
</code>```

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

答: You are re-inventing COM.  Your RefCounted class is IUnknown.  Your abstract class is an interface.  A COM server in a DLL has an entrypoint named DllGetClassObject(), it is a class factory.  There is lots of documentation available from Microsoft on COM, poke around a bit to see how they did it.</p>

OwnerDisplayName: Fire Lancer

Body:
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

LastEditorDisplayName: Fire Lancer

OwnerDisplayName: nobugz


问:
Using a for loop on string values of my array and getting a string value back
Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:

```<code>var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
</code>```

Now here's the for loop I'm using:

```<code>for (i = 0; i < stuff.length; i++) {
  console.log(i);
};
</code>```

All I get in my chrome developer console is 0, 1, 2, 3.

How do I get each string value to show up?

答:
You have to use i as a index of each value inside the stuff array to log it in the console.

var stuff = ["ken", "kenneth", "kenny", "kennayyy"];

for (i = 0; i < stuff.length; i++) {
  console.log(stuff[i]);
};```
</div>
</div>
</p>

<p>Or just use <code>Array#forEach</code> instead of <code>for</code> loop.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
    stuff.forEach(v => console.log(v));</code>```

Body:
Pretty dumb question to ask and clearly shows I'm just getting started but I do have some trouble with this. Here's the array I'm dealing with:

var stuff = ["ken", "kenneth", "kenny", "kennayyy"];

Now here's the for loop I'm using:

for (i = 0; i < stuff.length; i++) {
  console.log(i);
};

All I get in my chrome developer console is 0, 1, 2, 3.

How do I get each string value to show up?

Body:
You have to use i as a index of each value inside the stuff array to log it in the console.

var stuff = ["ken", "kenneth", "kenny", "kennayyy"];

for (i = 0; i < stuff.length; i++) {
  console.log(stuff[i]);
};

Or just use Array#forEach instead of for loop.

var stuff = ["ken", "kenneth", "kenny", "kennayyy"];
    stuff.forEach(v => console.log(v));


答:
```<code>for (i = 0; i < stuff.length; i++)
 console.log(stuff[i]);
</code>```

cheers :)

Title: Using a for loop on string values of my array and getting a string value back

Body:
for (i = 0; i < stuff.length; i++)
 console.log(stuff[i]);

cheers :)


问:
How do I load an OpenSSL ECDSA key into C#?
I need to load an OpenSSL private key into a C# based application.

The commands I used to generate the key are:

```<code>$ openssl ecparam -name prime256v1 -genkey -noout -out eckey.pem
$ openssl ec -in eckey.pem
read EC key
writing EC key
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIMiuwhV+yI0od5E5pSU6ZGuUcflskYD4urONi1g3G7EPoAoGCCqGSM49
AwEHoUQDQgAEe+C/M6u171u5CcL2SQKuFEb+OIEibjw1rx+S5LK4gNNePlDV/bqu
Ofjwc5JDqXA07shbfHNIPUn6Hum7qdiUKg==
-----END EC PRIVATE KEY-----

openssl pkcs8 -topk8 -nocrypt -in eckey.pem -out ec2.pem
cat ec2.pem
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyK7CFX7IjSh3kTml
JTpka5Rx+WyRgPi6s42LWDcbsQ+hRANCAAR74L8zq7XvW7kJwvZJAq4URv44gSJu
PDWvH5LksriA014+UNX9uq45+PBzkkOpcDTuyFt8c0g9Sfoe6bup2JQq
-----END PRIVATE KEY-----
</code>```

The C# code I'm using

```<code>   string privKeyPKCS8 = @"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyK7CFX7IjSh3kTmlJTpka5Rx+WyRgPi6s42LWDcbsQ+hRANCAAR74L8zq7XvW7kJwvZJAq4URv44gSJuPDWvH5LksriA014+UNX9uq45+PBzkkOpcDTuyFt8c0g9Sfoe6bup2JQq";
  byte[] privKeyBytes8 = Convert.FromBase64String(privKeyPKCS8);//Encoding.UTF8.GetBytes(privKeyEcc);

 var pubCNG = CngKey.Import(privKeyBytes, CngKeyBlobFormat.EccPrivateBlob);
</code>```

What is the correct way to load the EC based key into CngKey?

EDIT

The key within the base 64 encoding adheres to the following format:

```<code>ECPrivateKey ::= SEQUENCE {
    version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
    privateKey     OCTET STRING,
    parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
    publicKey  [1] BIT STRING OPTIONAL
}
</code>```

Using the secp256r1 curve and a public key in uncompressed point format.

答:
Your key PEM / ASCII armor (the header, footer and base 64) is encoded using the format described in RFC 5915: Elliptic Curve Private Key Structure. This was first specified by Standards for Efficient Cryptography Group (SECG) which is also where the named curve secp256r1 got it's name from. The curve is supported by Microsoft CNG.

```<code>ECPrivateKey ::= SEQUENCE {
    version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
    privateKey     OCTET STRING,
    parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
    publicKey  [1] BIT STRING OPTIONAL
}
</code>```

You first need to convert this "raw" EC private key structure to a PKCS#8 structure using the command in the (updated) question:

```<code>openssl pkcs8 -topk8 -nocrypt -in eckey.pem -out ec2.pem
</code>```

to get:

```<code>SEQUENCE(3 elem)
  INTEGER 0 # version of PKCS#8 structure
  SEQUENCE (2 elem)
    OBJECT IDENTIFIER 1.2.840.10045.2.1 # it's an EC key)
    OBJECT IDENTIFIER 1.2.840.10045.3.1.7 # it's secp256r1
  OCTET STRING (1 elem) # the key structure
    SEQUENCE (3 elem)
      INTEGER 1 # version
      OCTET STRING (32 byte) # private key value (removed)
      [1] (1 elem)
        BIT STRING (520 bit) # public key value (removed)
</code>```

The resulting structure isn't that different, what you are seeing is actually the same as the initial structure. Except that the PKCS#8 structure has an Object Identifier (OID) for designating the key type and an OID for the curve itself in front while your key has just the OID afterwards as parameter. Both also carry the (optional) public key value in the BIT STRING.

So the decoder recognizes this type and returns the EC private key.

The EccPrivateBlob that you were using requires a Microsoft specific structure. See also my question here. It won't work with the structures mentioned above.

Body:
I need to load an OpenSSL private key into a C# based application.

The commands I used to generate the key are:

$ openssl ecparam -name prime256v1 -genkey -noout -out eckey.pem
$ openssl ec -in eckey.pem
read EC key
writing EC key
-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIMiuwhV+yI0od5E5pSU6ZGuUcflskYD4urONi1g3G7EPoAoGCCqGSM49
AwEHoUQDQgAEe+C/M6u171u5CcL2SQKuFEb+OIEibjw1rx+S5LK4gNNePlDV/bqu
Ofjwc5JDqXA07shbfHNIPUn6Hum7qdiUKg==
-----END EC PRIVATE KEY-----

openssl pkcs8 -topk8 -nocrypt -in eckey.pem -out ec2.pem
cat ec2.pem
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyK7CFX7IjSh3kTml
JTpka5Rx+WyRgPi6s42LWDcbsQ+hRANCAAR74L8zq7XvW7kJwvZJAq4URv44gSJu
PDWvH5LksriA014+UNX9uq45+PBzkkOpcDTuyFt8c0g9Sfoe6bup2JQq
-----END PRIVATE KEY-----

The C# code I'm using

   string privKeyPKCS8 = @"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgyK7CFX7IjSh3kTmlJTpka5Rx+WyRgPi6s42LWDcbsQ+hRANCAAR74L8zq7XvW7kJwvZJAq4URv44gSJuPDWvH5LksriA014+UNX9uq45+PBzkkOpcDTuyFt8c0g9Sfoe6bup2JQq";
  byte[] privKeyBytes8 = Convert.FromBase64String(privKeyPKCS8);//Encoding.UTF8.GetBytes(privKeyEcc);

 var pubCNG = CngKey.Import(privKeyBytes, CngKeyBlobFormat.EccPrivateBlob);

What is the correct way to load the EC based key into CngKey?

EDIT

The key within the base 64 encoding adheres to the following format:

ECPrivateKey ::= SEQUENCE {
    version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
    privateKey     OCTET STRING,
    parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
    publicKey  [1] BIT STRING OPTIONAL
}

Using the secp256r1 curve and a public key in uncompressed point format.

Body:
Your key PEM / ASCII armor (the header, footer and base 64) is encoded using the format described in RFC 5915: Elliptic Curve Private Key Structure. This was first specified by Standards for Efficient Cryptography Group (SECG) which is also where the named curve secp256r1 got it's name from. The curve is supported by Microsoft CNG.

ECPrivateKey ::= SEQUENCE {
    version        INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
    privateKey     OCTET STRING,
    parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
    publicKey  [1] BIT STRING OPTIONAL
}

You first need to convert this "raw" EC private key structure to a PKCS#8 structure using the command in the (updated) question:

openssl pkcs8 -topk8 -nocrypt -in eckey.pem -out ec2.pem

to get:

SEQUENCE(3 elem)
  INTEGER 0 # version of PKCS#8 structure
  SEQUENCE (2 elem)
    OBJECT IDENTIFIER 1.2.840.10045.2.1 # it's an EC key)
    OBJECT IDENTIFIER 1.2.840.10045.3.1.7 # it's secp256r1
  OCTET STRING (1 elem) # the key structure
    SEQUENCE (3 elem)
      INTEGER 1 # version
      OCTET STRING (32 byte) # private key value (removed)
      [1] (1 elem)
        BIT STRING (520 bit) # public key value (removed)

The resulting structure isn't that different, what you are seeing is actually the same as the initial structure. Except that the PKCS#8 structure has an Object Identifier (OID) for designating the key type and an OID for the curve itself in front while your key has just the OID afterwards as parameter. Both also carry the (optional) public key value in the BIT STRING.

So the decoder recognizes this type and returns the EC private key.

The EccPrivateBlob that you were using requires a Microsoft specific structure. See also my question here. It won't work with the structures mentioned above.


问:
NSUserDefaults write to disk?
I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

```<code>// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];
</code>```

and ...

```<code>// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];
</code>```

Can anyone tell me if setObject:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?

答:
The synchronize method is called automatically at periodic intervals. You can also call it directly if you can't wait for the periodic intervals. Apple's documentation gives the example of calling synchronize if your application is about to exit.

See: NSUserDefaults Class Reference

Title: NSUserDefaults write to disk?

Body:
I am writing an index for the currently selected UITabBar to [NSUserDefaults standardUserDefaults] but I am getting the odd situation where the index is not writen to disk. I am using

// TO WRITE
NSNumber *selectedTab = [NSNumber numberWithInt:[tabBarController selectedIndex]];
[[NSUserDefaults standardUserDefaults] setObject:selectedTab forKey:@"selectedTab"];

and ...

// TO READ
NSNumber *selectTab = [[NSUserDefaults standardUserDefaults] objectForKey:@"selectedTab"];
NSLog(@"SelectTab: %@", selectTab);
[tabController setSelectedIndex:[selectTab intValue]];

Can anyone tell me if setObject:forKey: does the actual write to disk, or do I need to force the write using something like synchronize ?


问:
How to unit test a console program that reads input and writes to the console
Let's say I have a simple program like

```<code>using System;

public class Solution
{
    public static void Main(string[] args)
    {
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
        Array.Sort(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}
</code>```

which I want to test in a separate project like

```<code>[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
     string input = "2 1";
     string expectedOutput = "1 2";
     // ... ???
     Assert.AreEqual(expectedOutput, actualOutput);
}
</code>```

Is it possible to do that without actually using the .exe from Solution?

答:
Move the code that does all the work in Main() to its own class and method:

```<code>public static class InputConverter
{
    public static string ConvertInput(string input)
    {
        int[] arr = Array.ConvertAll(input.Split(' '), int.Parse);
        Array.Sort(arr);
        return string.Join(" ", arr);
    }
}
</code>```

Your Main() then becomes:

```<code>public static void Main(string[] args)
{
    var input = Console.ReadLine();
    var output = InputConverter.ConvertInput(input);
    Console.WriteLine(output);
}
</code>```

You can now test ConvertInput() without being dependent by the write and read functions of Console:

```<code>[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
    // Arrange
    var input = "2 1";
    var expectedOutput = "1 2";
    // Act
    var actualOutput = InputConverter.ConvertInput(input);
    // Assert
    Assert.AreEqual(expectedOutput, actualOutput);
}
</code>```

As an aside: the way you are passing in your arguments seems as though you are guaranteeing that the input will always be what you expect it to be. What happens when the user passes in something totally different than string representations of integers? You need to validate the input in InputConverter.ConvertInput() and create appropriate courses of action based on that (throw an Exception, return null, depends on what you're after). You'll then have to unit test those scenarios as well to make sure ConvertInput() performs as expected for all cases.

Body:
Let's say I have a simple program like

using System;

public class Solution
{
    public static void Main(string[] args)
    {
        int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
        Array.Sort(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}

which I want to test in a separate project like

[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
     string input = "2 1";
     string expectedOutput = "1 2";
     // ... ???
     Assert.AreEqual(expectedOutput, actualOutput);
}

Is it possible to do that without actually using the .exe from Solution?

Body:
Move the code that does all the work in Main() to its own class and method:

public static class InputConverter
{
    public static string ConvertInput(string input)
    {
        int[] arr = Array.ConvertAll(input.Split(' '), int.Parse);
        Array.Sort(arr);
        return string.Join(" ", arr);
    }
}

Your Main() then becomes:

public static void Main(string[] args)
{
    var input = Console.ReadLine();
    var output = InputConverter.ConvertInput(input);
    Console.WriteLine(output);
}

You can now test ConvertInput() without being dependent by the write and read functions of Console:

[TestMethod]
public void TwoNumbersDescendingAreSwapped()
{
    // Arrange
    var input = "2 1";
    var expectedOutput = "1 2";
    // Act
    var actualOutput = InputConverter.ConvertInput(input);
    // Assert
    Assert.AreEqual(expectedOutput, actualOutput);
}

As an aside: the way you are passing in your arguments seems as though you are guaranteeing that the input will always be what you expect it to be. What happens when the user passes in something totally different than string representations of integers? You need to validate the input in InputConverter.ConvertInput() and create appropriate courses of action based on that (throw an Exception, return null, depends on what you're after). You'll then have to unit test those scenarios as well to make sure ConvertInput() performs as expected for all cases.


问:
Java Stream Api strings manipulation
I have some list of words List<String> strings I have to make a word out of most frequent letters on each position.

For example for strings = {"qwerty", "qwer" , "ab", "bab"} the result would be "qwer"

Letters that appear once do not count

I came up to idea of creating a list

```<code>List<Map<String, Integer>> list;
</code>```

Its size is equal to the string in strings of maximal size and the map would count number of characters on the position

```<code>IntStream.range(0, strings.stream().max(String::compareTo).get().length())
    .forEachOrdered(i -> {
        strings.stream().forEach(s -> {
            if (s.length()>i){
                Map<String,Integer> temp = list.get(i);
                String character = s.charAt(i) + "";
                Integer value = temp.get(character) == null ? 0 : temp.get(character) + 1;
                temp.put(character, value);
                list.add(i, temp);
            }
        });
    });
</code>```

Have no idea why id doesn't work

答:
Here's another approach:

```<code>import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;

...

strings.stream()
    .flatMap(s -> IntStream.range(0, s.length()).mapToObj(i -> new SimpleEntry<>(i, s.charAt(i))))
    .collect(groupingBy(SimpleEntry::getKey, mapping(SimpleEntry::getValue, groupingBy(identity(), counting()))))
    .entrySet()
    .stream()
    .map(e -> e.getValue().entrySet().stream().max(Map.Entry.comparingByValue()).get())
    .filter(e -> e.getValue() > 1)
    .forEach(System.out::println);
</code>```

which outputs:

```<code>q=2
w=2
e=2
r=2
</code>```

From the stream of strings you create a stream of entries for each character mapped with their respective positions. From there you group them by the position and you group the values so that for each position you have a Map representing the occurences of the different characters at this position.

Then you filter out the values that have a count less than 2 (your 'Letters that appear once do not count' requirement)and finally you get the most frequent letter for each remaining position.

Title: Java Stream Api strings manipulation

Body:
I have some list of words List<String> strings I have to make a word out of most frequent letters on each position.

For example for strings = {"qwerty", "qwer" , "ab", "bab"} the result would be "qwer"

Letters that appear once do not count

I came up to idea of creating a list

List<Map<String, Integer>> list;

Its size is equal to the string in strings of maximal size and the map would count number of characters on the position

IntStream.range(0, strings.stream().max(String::compareTo).get().length())
    .forEachOrdered(i -> {
        strings.stream().forEach(s -> {
            if (s.length()>i){
                Map<String,Integer> temp = list.get(i);
                String character = s.charAt(i) + "";
                Integer value = temp.get(character) == null ? 0 : temp.get(character) + 1;
                temp.put(character, value);
                list.add(i, temp);
            }
        });
    });

Have no idea why id doesn't work

Body:
Here's another approach:

import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;

...

strings.stream()
    .flatMap(s -> IntStream.range(0, s.length()).mapToObj(i -> new SimpleEntry<>(i, s.charAt(i))))
    .collect(groupingBy(SimpleEntry::getKey, mapping(SimpleEntry::getValue, groupingBy(identity(), counting()))))
    .entrySet()
    .stream()
    .map(e -> e.getValue().entrySet().stream().max(Map.Entry.comparingByValue()).get())
    .filter(e -> e.getValue() > 1)
    .forEach(System.out::println);

which outputs:

q=2
w=2
e=2
r=2

From the stream of strings you create a stream of entries for each character mapped with their respective positions. From there you group them by the position and you group the values so that for each position you have a Map representing the occurences of the different characters at this position.

Then you filter out the values that have a count less than 2 (your 'Letters that appear once do not count' requirement)and finally you get the most frequent letter for each remaining position.