问:
Redux with Polymer and dom-repeat
I have a problem with nested dom-repeat's and changes deep in arrays.
Using redux I change properties on an array which has a structure like this:

```<code>[{some: 'value', members: [{ id: 13, hobbies: [{id: 33, name:'hobbyname'}]}]}]
</code>```

When for example a hobby is deleted from a member, I see when I have an observer method on this property and console.log the value of the array that it really changed, the hobby is gone.

The DOM does however not change. The structure of that is something like:

```<code><template id="teamslist" is="dom-repeat" items="[[teams]]">
<template is="dom-repeat" items="[[item.members]]" as="member">
<template is="dom-repeat" items="[[member.hobbies]]" as="hobby">
</code>```

I tried notifying the dom-repeat like this but it does not help:

```<code>this.notifyPath('teams[0].members[0].hobbies.length');
</code>```

Calling render() on the dom-repeat (top-level) does not seem to help either:

```<code>this.$.idfordomrepeat.render()
</code>```

What am I doing wrong here..?

答:
In the end it was a problem with the Redux state not being updated where I thought it was (Redux noob...)
When that was fixed the notifyPath wasn't needed, and nor was the render() call.</p>

Title: Redux with Polymer and dom-repeat

Body:
I have a problem with nested dom-repeat's and changes deep in arrays.
Using redux I change properties on an array which has a structure like this:

[{some: 'value', members: [{ id: 13, hobbies: [{id: 33, name:'hobbyname'}]}]}]

When for example a hobby is deleted from a member, I see when I have an observer method on this property and console.log the value of the array that it really changed, the hobby is gone.

The DOM does however not change. The structure of that is something like:

<template id="teamslist" is="dom-repeat" items="[[teams]]">
<template is="dom-repeat" items="[[item.members]]" as="member">
<template is="dom-repeat" items="[[member.hobbies]]" as="hobby">

I tried notifying the dom-repeat like this but it does not help:

this.notifyPath('teams[0].members[0].hobbies.length');

Calling render() on the dom-repeat (top-level) does not seem to help either:

this.$.idfordomrepeat.render()

What am I doing wrong here..?


来源: stackexchange

问:
Why some css font family does not work?
I used those css code

.logo h2 {
  font-family: Pacifico, MyriadPro-Regular, AdobeInvisFont;
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}```

But it does not work. What should I do?

答:
It seems the font is not imported.

You have to import the font to use it.

You can import the font via Google CDN or download the font and have it in your server.

Code to use Google CDN Font

```<code><link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
</code>```

Just include the above code in the  section of your HTML document.

Refer https://fonts.google.com/specimen/Pacifico?selection.family=Pacifico for more options to import the font.

Refer https://fonts.google.com for more info on Google fonts.

Follow the same for all the other fonts you use.

ContentLicense: CC BY-SA 3.0

Title: Why some css font family does not work?

Body:
I used those css code

.logo h2 {
  font-family: Pacifico, MyriadPro-Regular, AdobeInvisFont;
  font-size: 42pt;
  color: rgba(71, 71, 71, 255);
  text-align: left;
}

But it does not work. What should I do?

Body:
It seems the font is not imported.

You have to import the font to use it.

You can import the font via Google CDN or download the font and have it in your server.

Code to use Google CDN Font

<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">

Just include the above code in the  section of your HTML document.

Refer https://fonts.google.com/specimen/Pacifico?selection.family=Pacifico for more options to import the font.

Refer https://fonts.google.com for more info on Google fonts.

Follow the same for all the other fonts you use.


问:
Convert String of anyformat into dd-mm-yy hh:mm:ss in R
I am reading a date value from csv file.So the format will vary according to the date format of csv. How can I convert any date string to dd-mm-yyy  HH:mm:ss ?

EDIT :

The input format are :

```<code>dd/mm/yyyy HH:mm:ss
dd/mm/yyyy
dd-mm-yyyy HH:mm:ss
dd-mm-yyyy

mm-dd-yyyy HH:mm:ss
mm-dd-yyyy
mm/dd/yyyy

yyyy-mm-dd HH:mm:ss
yyyy-mm-dd
</code>```

I need to convert  all these formats to dd-mm-yyyy HH:mm:ss

答:
See the anytime package whose anytime function does just that -- and without requiring a format string:

```<code>> inputs <- c("12/07/2017 10:11:12", "12/07/2017", "12-07-2017 10:11:12",
+             "07-12-2017", "2017-12-07 10:11:12", "2017-12-07")
> library(anytime)
> anytime(inputs)
[1] "2017-12-07 10:11:12 CST" "2017-12-07 00:00:00 CST"
[3] "2017-12-07 10:11:12 CST" "2017-07-12 00:00:00 CDT"
[5] "2017-12-07 10:11:12 CST" "2017-12-07 00:00:00 CST"
>
</code>```

However, your requirement of accepting both d-m-y and m-d-y is not satisfiable.  So you need to make a choice and supply an explicit format here.

In general, I highly recommend avoiding the ambiguity and sticking to y-m-d ISO formats.  As a convenience to stubborn North American habits, anytime and anydata also accept m-d-y ordering but it is dangerous.

Again, only you can tell if 3-4-5 is April 3rd or March 4th, and you need to specify that.

Body:
I am reading a date value from csv file.So the format will vary according to the date format of csv. How can I convert any date string to dd-mm-yyy  HH:mm:ss ?

EDIT :

The input format are :

dd/mm/yyyy HH:mm:ss
dd/mm/yyyy
dd-mm-yyyy HH:mm:ss
dd-mm-yyyy

mm-dd-yyyy HH:mm:ss
mm-dd-yyyy
mm/dd/yyyy

yyyy-mm-dd HH:mm:ss
yyyy-mm-dd

I need to convert  all these formats to dd-mm-yyyy HH:mm:ss

Body:
See the anytime package whose anytime function does just that -- and without requiring a format string:

> inputs <- c("12/07/2017 10:11:12", "12/07/2017", "12-07-2017 10:11:12",
+             "07-12-2017", "2017-12-07 10:11:12", "2017-12-07")
> library(anytime)
> anytime(inputs)
[1] "2017-12-07 10:11:12 CST" "2017-12-07 00:00:00 CST"
[3] "2017-12-07 10:11:12 CST" "2017-07-12 00:00:00 CDT"
[5] "2017-12-07 10:11:12 CST" "2017-12-07 00:00:00 CST"
>

However, your requirement of accepting both d-m-y and m-d-y is not satisfiable.  So you need to make a choice and supply an explicit format here.

In general, I highly recommend avoiding the ambiguity and sticking to y-m-d ISO formats.  As a convenience to stubborn North American habits, anytime and anydata also accept m-d-y ordering but it is dangerous.

Again, only you can tell if 3-4-5 is April 3rd or March 4th, and you need to specify that.


问:
Split column into two new columns in Pandas
I have a dataframe with 4 columns with value like this:

```<code>value_1
over 1 - 42 -> take this ; over 3 - 4
over 3 - 26 -> take this ; over 3 - 45
over 5 - 25 -> take this ; over 2 - 80
</code>```

And I need to make two column from each of them by splitting by ';'.
And when I try this:

```<code>s = df['value_1'].apply(lambda x: x.split(';'))
df['value_left'] = s.apply(lambda x: x[0])
df['value_right'] = s.apply(lambda x: x[1])
</code>```

Or this:

```<code>f['new_value1'] = df['value_1']
df['value_1_right'] = None
df['value_1_right'].update(df.new_band_bandw_1.apply(lambda x: x.str.split(';')[1]
                      if len(x.str.split()) == 2 else None))
</code>```

I got the same error: List index out of range. What is the problem, is it possible that the values are in some kind of list?

Any kind of solution is welcomed. Thanks

答:
You need split:

```<code>df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True)
print (df)

                                  value_1                 value_left  \
0   over 1 - 42 -> take this ; over 3 - 4  over 1 - 42 -> take this
1  over 3 - 26 -> take this ; over 3 - 45  over 3 - 26 -> take this
2  over 5 - 25 -> take this ; over 2 - 80  over 5 - 25 -> take this

    value_right
0    over 3 - 4
1   over 3 - 45
2   over 2 - 80
</code>```

Sample for multiple ; - is possible specify which ; is used for split:

```<code>df = pd.DataFrame({
    'value_1': ['a;r;e','b;r','c;g;t;e']
})
print (df)

   value_1
0    a;r;e
1      b;r
2  c;g;t;e

df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True, n=1)
print (df)
   value_1 value_left value_right
0    a;r;e          a         r;e
1      b;r          b           r
2  c;g;t;e          c       g;t;e
</code>```

Body:
I have a dataframe with 4 columns with value like this:

value_1
over 1 - 42 -> take this ; over 3 - 4
over 3 - 26 -> take this ; over 3 - 45
over 5 - 25 -> take this ; over 2 - 80

And I need to make two column from each of them by splitting by ';'.
And when I try this:

s = df['value_1'].apply(lambda x: x.split(';'))
df['value_left'] = s.apply(lambda x: x[0])
df['value_right'] = s.apply(lambda x: x[1])

Or this:

f['new_value1'] = df['value_1']
df['value_1_right'] = None
df['value_1_right'].update(df.new_band_bandw_1.apply(lambda x: x.str.split(';')[1]
                      if len(x.str.split()) == 2 else None))

I got the same error: List index out of range. What is the problem, is it possible that the values are in some kind of list?

Any kind of solution is welcomed. Thanks

Body:
You need split:

df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True)
print (df)

                                  value_1                 value_left  \
0   over 1 - 42 -> take this ; over 3 - 4  over 1 - 42 -> take this
1  over 3 - 26 -> take this ; over 3 - 45  over 3 - 26 -> take this
2  over 5 - 25 -> take this ; over 2 - 80  over 5 - 25 -> take this

    value_right
0    over 3 - 4
1   over 3 - 45
2   over 2 - 80

Sample for multiple ; - is possible specify which ; is used for split:

df = pd.DataFrame({
    'value_1': ['a;r;e','b;r','c;g;t;e']
})
print (df)

   value_1
0    a;r;e
1      b;r
2  c;g;t;e

df[['value_left','value_right']] = df['value_1'].str.split(';', expand=True, n=1)
print (df)
   value_1 value_left value_right
0    a;r;e          a         r;e
1      b;r          b           r
2  c;g;t;e          c       g;t;e


问:
Orika mapping nested sublist
Consider the below example.

Group.java(GroupDTO.java also has the same properties)

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

public class Group {
    public Group(List<Person> persons) {
        this.persons = persons;
    }

    private List<Person> persons;

    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}
</code>```

Person.java(PersonDTO.java also has the same properties)

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

public class Person {

    public Person(){}
    public Person(List<Name> names, Integer age) {
        this.names = names;
        this.age = age;
    }

    private List<Name> names;
    private Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public List<Name> getNames() {
        return names;
    }

    public void setNames(List<Name> names) {
        this.names = names;
    }
}
</code>```

Name.java(NameDTO.java also has the same properties)

```<code>public class Name {
    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    private String first;
    private String last;

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }
}
</code>```

And when I run the below class I get the following exception.

```<code>import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;

import java.util.LinkedList;
import java.util.List;

public class Mapper {

    public static void main(String[] args) {

        List<Name> names = new LinkedList<Name>();
        names.add(new Name("foo", "bar"));
        names.add(new Name("lorem", "ipsum"));
        List<Person> persons = new LinkedList<Person>();
        persons.add(new Person(names, 30));
        persons.add(new Person(names, 40));
        Group g1 = new Group(persons);

        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        ClassMapBuilder classMapBuilder = mapperFactory.classMap(Group.class, GroupDTO.class);
        classMapBuilder.field("persons{age}", "persons{age}");
        classMapBuilder.field("persons{names{first}}", "persons{names{first}}");
        classMapBuilder.field("persons{names{last}}", "persons{names{last}}");
        classMapBuilder.byDefault().register();

        MapperFacade mapper = mapperFactory.getMapperFacade();
        GroupDTO groupDTO = mapper.map(g1, GroupDTO.class);

        for(Person p:groupDTO.getPersons()){
            System.out.println(p.getAge());
            for(Name n:p.getNames()){
                System.out.println(n.getFirst());
                System.out.println(n.getFirst());
            }
        }

    }
}
</code>```

Exception

```<code>Exception in thread "main" ma.glasnost.orika.MappingException: java.lang.NullPointerException
    at ma.glasnost.orika.impl.generator.MapperGenerator.build(MapperGenerator.java:104)
    at ma.glasnost.orika.impl.DefaultMapperFactory.buildMapper(DefaultMapperFactory.java:1480)
    at ma.glasnost.orika.impl.DefaultMapperFactory.build(DefaultMapperFactory.java:1295)
    at ma.glasnost.orika.impl.DefaultMapperFactory.getMapperFacade(DefaultMapperFactory.java:883)
    at Mapper.main(Mapper.java:28)
Caused by: java.lang.NullPointerException
    at ma.glasnost.orika.impl.generator.specification.MultiOccurrenceToMultiOccurrence.registerClassMaps(MultiOccurrenceToMultiOccurrence.java:397)
    at ma.glasnost.orika.impl.generator.specification.MultiOccurrenceToMultiOccurrence.generateMappingCode(MultiOccurrenceToMultiOccurrence.java:72)
    at ma.glasnost.orika.impl.generator.SourceCodeContext.mapAggregateFields(SourceCodeContext.java:721)
    at ma.glasnost.orika.impl.generator.MapperGenerator.addMapMethod(MapperGenerator.java:182)
    at ma.glasnost.orika.impl.generator.MapperGenerator.build(MapperGenerator.java:70)
    ... 4 more
</code>```

Sorry about the long post. Am trying map fields from inside List<> which is again inside another List<>. What would be the best approach or am I doing something wrong here?

答:
If the field names on both sides are equal, you don't have to register the field mappings, Orika will handle that by itself. This code will do the mapping correctly:

```<code>    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
    ClassMapBuilder classMapBuilder = mapperFactory.classMap(Group.class, GroupDTO.class);
    classMapBuilder.byDefault().register();

    MapperFacade mapper = mapperFactory.getMapperFacade();
    GroupDTO groupDTO = mapper.map(g1, GroupDTO.class);
</code>```

Also, probably just a typo, but the getPersons() from GroupDTO should return PersonDTO, same for getNames() and NameDTO:

```<code>   for(PersonDTO p:groupDTO.getPersons()){
        System.out.println(p.getAge());
        for(NameDTO n:p.getNames()){
            System.out.println(n.getFirst());
            System.out.println(n.getLast());
        }
    }
</code>```

Title: Orika mapping nested sublist

Body:
Consider the below example.

Group.java(GroupDTO.java also has the same properties)

import java.util.List;

public class Group {
    public Group(List<Person> persons) {
        this.persons = persons;
    }

    private List<Person> persons;

    public List<Person> getPersons() {
        return persons;
    }

    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

Person.java(PersonDTO.java also has the same properties)

import java.util.List;

public class Person {

    public Person(){}
    public Person(List<Name> names, Integer age) {
        this.names = names;
        this.age = age;
    }

    private List<Name> names;
    private Integer age;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public List<Name> getNames() {
        return names;
    }

    public void setNames(List<Name> names) {
        this.names = names;
    }
}

Name.java(NameDTO.java also has the same properties)

public class Name {
    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    private String first;
    private String last;

    public String getFirst() {
        return first;
    }

    public void setFirst(String first) {
        this.first = first;
    }

    public String getLast() {
        return last;
    }

    public void setLast(String last) {
        this.last = last;
    }
}

And when I run the below class I get the following exception.

import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import ma.glasnost.orika.metadata.ClassMapBuilder;

import java.util.LinkedList;
import java.util.List;

public class Mapper {

    public static void main(String[] args) {

        List<Name> names = new LinkedList<Name>();
        names.add(new Name("foo", "bar"));
        names.add(new Name("lorem", "ipsum"));
        List<Person> persons = new LinkedList<Person>();
        persons.add(new Person(names, 30));
        persons.add(new Person(names, 40));
        Group g1 = new Group(persons);

        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        ClassMapBuilder classMapBuilder = mapperFactory.classMap(Group.class, GroupDTO.class);
        classMapBuilder.field("persons{age}", "persons{age}");
        classMapBuilder.field("persons{names{first}}", "persons{names{first}}");
        classMapBuilder.field("persons{names{last}}", "persons{names{last}}");
        classMapBuilder.byDefault().register();

        MapperFacade mapper = mapperFactory.getMapperFacade();
        GroupDTO groupDTO = mapper.map(g1, GroupDTO.class);

        for(Person p:groupDTO.getPersons()){
            System.out.println(p.getAge());
            for(Name n:p.getNames()){
                System.out.println(n.getFirst());
                System.out.println(n.getFirst());
            }
        }

    }
}

Exception

Exception in thread "main" ma.glasnost.orika.MappingException: java.lang.NullPointerException
    at ma.glasnost.orika.impl.generator.MapperGenerator.build(MapperGenerator.java:104)
    at ma.glasnost.orika.impl.DefaultMapperFactory.buildMapper(DefaultMapperFactory.java:1480)
    at ma.glasnost.orika.impl.DefaultMapperFactory.build(DefaultMapperFactory.java:1295)
    at ma.glasnost.orika.impl.DefaultMapperFactory.getMapperFacade(DefaultMapperFactory.java:883)
    at Mapper.main(Mapper.java:28)
Caused by: java.lang.NullPointerException
    at ma.glasnost.orika.impl.generator.specification.MultiOccurrenceToMultiOccurrence.registerClassMaps(MultiOccurrenceToMultiOccurrence.java:397)
    at ma.glasnost.orika.impl.generator.specification.MultiOccurrenceToMultiOccurrence.generateMappingCode(MultiOccurrenceToMultiOccurrence.java:72)
    at ma.glasnost.orika.impl.generator.SourceCodeContext.mapAggregateFields(SourceCodeContext.java:721)
    at ma.glasnost.orika.impl.generator.MapperGenerator.addMapMethod(MapperGenerator.java:182)
    at ma.glasnost.orika.impl.generator.MapperGenerator.build(MapperGenerator.java:70)
    ... 4 more

Sorry about the long post. Am trying map fields from inside List<> which is again inside another List<>. What would be the best approach or am I doing something wrong here?

Body:
If the field names on both sides are equal, you don't have to register the field mappings, Orika will handle that by itself. This code will do the mapping correctly:

    MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
    ClassMapBuilder classMapBuilder = mapperFactory.classMap(Group.class, GroupDTO.class);
    classMapBuilder.byDefault().register();

    MapperFacade mapper = mapperFactory.getMapperFacade();
    GroupDTO groupDTO = mapper.map(g1, GroupDTO.class);

Also, probably just a typo, but the getPersons() from GroupDTO should return PersonDTO, same for getNames() and NameDTO:

   for(PersonDTO p:groupDTO.getPersons()){
        System.out.println(p.getAge());
        for(NameDTO n:p.getNames()){
            System.out.println(n.getFirst());
            System.out.println(n.getLast());
        }
    }


问:
Deserialize into an object that extends List<T>
Using

```<code>var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
</code>```

the following deserializes my JSON array correctly:

```<code>public List<PrintJobTranslation> Translations
</code>```

and the following doesn't:

```<code>public PrintJobTranslations Translations
</code>```

with

```<code>public class PrintJobTranslations : List<PrintJobTranslation>
{
    public string GetTranslation(string Key, string defaultValue)
    {
        var translation = this.FirstOrDefault(x => x.Key == Key);
        if (translation == null) return defaultValue;
        return translation.Translation;
    }
}
</code>```

It throws the error:

System.Collections.Generic.Dictionary`2[System.String,System.Object] ist kein Wert des Typs Print.printJob.PrintJobTranslation und kann in dieser generischen Sammlung nicht verwendet werden. Parametername: value

I did not find an exact translation, but should be something like this in English:

System.Collections.Generic.Dictionary`2[System.String,System.Object] is not a value of type Print.printJob.PrintJobTranslation and cannot be used in the generic collection. Parameter name: value

How can I get the JSON to deserialize correctly?

答:
One way to side step this completely would be to not do that - your method looks fine as an "extension method", so it'll work like an instance method, but without actually having to subclass anything:

```<code>public static class PrintJobTranslationExtensions
{
    public static string GetTranslation(
        this List<PrintJobTranslation> list, string Key, string defaultValue)
    {
        var translation = list.FirstOrDefault(x => x.Key == Key);
        if (translation == null) return defaultValue;
        return translation.Translation;
    }
}
</code>```

and just use List<PrintJobTranslation> in your code.

Body:
Using

var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

the following deserializes my JSON array correctly:

public List<PrintJobTranslation> Translations

and the following doesn't:

public PrintJobTranslations Translations

with

public class PrintJobTranslations : List<PrintJobTranslation>
{
    public string GetTranslation(string Key, string defaultValue)
    {
        var translation = this.FirstOrDefault(x => x.Key == Key);
        if (translation == null) return defaultValue;
        return translation.Translation;
    }
}

It throws the error:

System.Collections.Generic.Dictionary`2[System.String,System.Object] ist kein Wert des Typs Print.printJob.PrintJobTranslation und kann in dieser generischen Sammlung nicht verwendet werden. Parametername: value

I did not find an exact translation, but should be something like this in English:

System.Collections.Generic.Dictionary`2[System.String,System.Object] is not a value of type Print.printJob.PrintJobTranslation and cannot be used in the generic collection. Parameter name: value

How can I get the JSON to deserialize correctly?

Body:
One way to side step this completely would be to not do that - your method looks fine as an "extension method", so it'll work like an instance method, but without actually having to subclass anything:

public static class PrintJobTranslationExtensions
{
    public static string GetTranslation(
        this List<PrintJobTranslation> list, string Key, string defaultValue)
    {
        var translation = list.FirstOrDefault(x => x.Key == Key);
        if (translation == null) return defaultValue;
        return translation.Translation;
    }
}

and just use List<PrintJobTranslation> in your code.


问:
OpenCV length of matches in BFMatcher

I am trying to use SIFT on two images and match the keypoints using BFMatcher in OpenCV.

However, the number of matches is not equal to the number of query descriptors. Can someone explain why they are not equal?

According to docs
match() function "Finds the best match for each descriptor from a query set."

```<code>import cv2
import numpy as np

im1 = cv2.imread("trex1.png", cv2.IMREAD_GRAYSCALE)
im2 = cv2.imread("trex2.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(im1, None)
kp2, des2 = sift.detectAndCompute(im2, None)

im_kp1 = np.zeros(im1.shape, dtype=np.uint8)
im_kp2 = np.zeros(im1.shape, dtype=np.uint8)
im_kp1 = cv2.drawKeypoints(im1,kp1,None)
im_kp2 = cv2.drawKeypoints(im2,kp2,None)

bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
matches = bf.match(des1,des2)

print len(des1)
# Result : 78
print len(des2)
# Result : 71
print len(matches)
# Result : 55
</code>```

答:
Because crossCheck=True is removing some of the results.

If you check the docs for the BFMatcher() constructor:

crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent pairs. Such technique usually produces best results with minimal number of outliers when there are enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper.

This reads like it will only affect the knnMatch() method, but the match() methods actually explicitly call knnMatch():

```<code>void DescriptorMatcher::match( InputArray queryDescriptors, std::vector<DMatch>& matches, InputArrayOfArrays masks )
{
    CV_INSTRUMENT_REGION()

    std::vector<std::vector<DMatch> > knnMatches;
    knnMatch( queryDescriptors, knnMatches, 1, masks, true /*compactResult*/ );
    convertMatches( knnMatches, matches );
}
</code>```

If you set crossCheck=False (or just don't specify, it's False by default), then you'll get

```<code>len(query_descriptors) == len(matches)
</code>```

ContentLicense: CC BY-SA 4.0

Title: OpenCV length of matches in BFMatcher

Body:
I am trying to use SIFT on two images and match the keypoints using BFMatcher in OpenCV.

However, the number of matches is not equal to the number of query descriptors. Can someone explain why they are not equal?

According to docs
match() function "Finds the best match for each descriptor from a query set."

import cv2
import numpy as np

im1 = cv2.imread("trex1.png", cv2.IMREAD_GRAYSCALE)
im2 = cv2.imread("trex2.png", cv2.IMREAD_GRAYSCALE)

sift = cv2.xfeatures2d.SIFT_create()
kp1, des1 = sift.detectAndCompute(im1, None)
kp2, des2 = sift.detectAndCompute(im2, None)

im_kp1 = np.zeros(im1.shape, dtype=np.uint8)
im_kp2 = np.zeros(im1.shape, dtype=np.uint8)
im_kp1 = cv2.drawKeypoints(im1,kp1,None)
im_kp2 = cv2.drawKeypoints(im2,kp2,None)

bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True)
matches = bf.match(des1,des2)

print len(des1)
# Result : 78
print len(des2)
# Result : 71
print len(matches)
# Result : 55

Body:
Because crossCheck=True is removing some of the results.

If you check the docs for the BFMatcher() constructor:

crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent pairs. Such technique usually produces best results with minimal number of outliers when there are enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper.

This reads like it will only affect the knnMatch() method, but the match() methods actually explicitly call knnMatch():

void DescriptorMatcher::match( InputArray queryDescriptors, std::vector<DMatch>& matches, InputArrayOfArrays masks )
{
    CV_INSTRUMENT_REGION()

    std::vector<std::vector<DMatch> > knnMatches;
    knnMatch( queryDescriptors, knnMatches, 1, masks, true /*compactResult*/ );
    convertMatches( knnMatches, matches );
}

If you set crossCheck=False (or just don't specify, it's False by default), then you'll get

len(query_descriptors) == len(matches)


问:
R - calculate pairwise orthographic similarity of a list
I need to calculate orthographic similarity (edit/Levenshtein distance) among words in a given corpus.

The R package vwr seems to be able to calculate this:

```<code>coltheart.N(list1, list2)
</code>```

in which the Levenshtein distance is computed pairwise between the matching words of the two word lists.

I was wondering if there was a way to calculate the Levenshtein distance between all possible word combinations of a given word list. Can somebody give me a hint?

答:
You can use the function levenshtein.distance from the package vwr and loop over every single word in the list:

```<code>library(vwr)

wordlist <- list("but", "nut", "rut")

output <- lapply(wordlist, function(x) levenshtein.distance(x, wordlist))

> output
[[1]]
but nut rut
  0   1   1

[[2]]
but nut rut
  1   0   1

[[3]]
but nut rut
  1   1   0
</code>```

There is a warning message about passing a list argument to stringdist, but the results fit, so I'm pretty sure you can ignore it.

Edit:

To assign the words as names for the list items, just use

```<code>names(output) <- wordlist

> output
$but
but nut rut
  0   1   1

$nut
but nut rut
  1   0   1

$rut
but nut rut
  1   1   0
</code>```

Body:
I need to calculate orthographic similarity (edit/Levenshtein distance) among words in a given corpus.

The R package vwr seems to be able to calculate this:

coltheart.N(list1, list2)

in which the Levenshtein distance is computed pairwise between the matching words of the two word lists.

I was wondering if there was a way to calculate the Levenshtein distance between all possible word combinations of a given word list. Can somebody give me a hint?

Body:
You can use the function levenshtein.distance from the package vwr and loop over every single word in the list:

library(vwr)

wordlist <- list("but", "nut", "rut")

output <- lapply(wordlist, function(x) levenshtein.distance(x, wordlist))

> output
[[1]]
but nut rut
  0   1   1

[[2]]
but nut rut
  1   0   1

[[3]]
but nut rut
  1   1   0

There is a warning message about passing a list argument to stringdist, but the results fit, so I'm pretty sure you can ignore it.

Edit:

To assign the words as names for the list items, just use

names(output) <- wordlist

> output
$but
but nut rut
  0   1   1

$nut
but nut rut
  1   0   1

$rut
but nut rut
  1   1   0


问:
How to Include a count(*) as additional result field of a query in LINQ
Given a table of players (users) with several fields. One of this is their rating with respect other players.

I'd like to implement via LINQ following SQL query:

```<code>SELECT p.*,
    (select COUNT(*) from Users where (Rating > p.Rating)) as Rank
FROM Users as p
ORDER BY p.Rating DESC
</code>```

In other words, last field (RANK) should give the rank of each user with respect the others:

```<code>Id  Username  ... Rating     Rank
43  player41  ... 1002,333  0
99  player97  ... 1002      1
202 player200 ... 1002      1
53  player51  ... 1000,667  2
168 player166 ... 1000,667  2
56  player54  ... 1000      3
32  player30  ... 999,342   4
</code>```

This attempt does not work:

```<code>var q = from u in Users
        orderby u.Rating descending
        group u by u.Id into g
        select new
        {
            MyKey = g.Key,
            User = g.First(),
            cnt = Users.Count(uu => uu.Rating > g.First().Rating) + 1
        };
</code>```

Just for your knowledge, note that the table Users is mapped to a EF entity named User with a 'NotMapped' int? field named Rank where I'd like to manually copy the rank:

```<code>class User {
    ...
    [NotMapped]
    public virtual int? Rank { get; internal set; }
}
</code>```

答:
Try this:</p>

```<code> var q = (from u in Users
         select new
        {
           UserId = u.Id,
           UserObj = u,
           Rank = (from u1 in Users where u1.Rating>u.Rating select u1).Count()
        }).ToList();
</code>```

Body:
Given a table of players (users) with several fields. One of this is their rating with respect other players.

I'd like to implement via LINQ following SQL query:

SELECT p.*,
    (select COUNT(*) from Users where (Rating > p.Rating)) as Rank
FROM Users as p
ORDER BY p.Rating DESC

In other words, last field (RANK) should give the rank of each user with respect the others:

Id  Username  ... Rating     Rank
43  player41  ... 1002,333  0
99  player97  ... 1002      1
202 player200 ... 1002      1
53  player51  ... 1000,667  2
168 player166 ... 1000,667  2
56  player54  ... 1000      3
32  player30  ... 999,342   4

This attempt does not work:

var q = from u in Users
        orderby u.Rating descending
        group u by u.Id into g
        select new
        {
            MyKey = g.Key,
            User = g.First(),
            cnt = Users.Count(uu => uu.Rating > g.First().Rating) + 1
        };

Just for your knowledge, note that the table Users is mapped to a EF entity named User with a 'NotMapped' int? field named Rank where I'd like to manually copy the rank:

class User {
    ...
    [NotMapped]
    public virtual int? Rank { get; internal set; }
}

Body:
Try this:

 var q = (from u in Users
         select new
        {
           UserId = u.Id,
           UserObj = u,
           Rank = (from u1 in Users where u1.Rating>u.Rating select u1).Count()
        }).ToList();


问:
How to inject into var in Kotlin?
I try to implement Dagger2 into my Kotlin project but I have problems with the @Inject annotation.

In Java it looks like this and this works fine:

```<code>public class FooActivity extends Activity {

    @Inject
    @Named("accessTokenObservable")
    public Flowable<Optional<AccessToken>> accessTokenObservable;

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        App.getGraph().inject(this);
    }
}
</code>```

But how I have to write the @Inject line in Kotlin?

When I use this one:

```<code>@Inject
@Named("accessTokenObservable")
var accessTokenObservable: Flowable<Optional<AccessToken>>? = null
</code>```

I get this error message:

```<code>Error:Dagger does not support injection into private fields
</code>```

If I use lateinit:

```<code>@Inject
@Named("accessTokenObservable")
lateinit var accessTokenObservable: Flowable<Optional<AccessToken>>
</code>```

I get this error message:

```<code>Error:Flowable<Optional<AccessToken>> cannot be provided without
an @Provides- or @Produces-annotated method.
</code>```

What is the right syntax to inject something in Kotlin?

答:
Do you provide Flowable<Optional<AccessToken>> accessTokenObservable somewhere  in your code?

If not
Error:Flowable<Optional<AccessToken>> cannot be provided without
an @Provides- or @Produces-annotated method. can be produced. Because you are trying to inject object without provide it.
In this case you need to provide in your injector class:

```<code>@Provide
@Named("accessTokenObservable")
fun provideAccessTokenObservable : Flowable<Optional<AccessToken>>{
    return yourAccessTokenObservable
}
</code>```

then you need to inject your object in your activity

```<code>@Inject
@Named("accessTokenObservable")
lateinit var accessTokenObservable: Flowable<Optional<AccessToken>>
</code>```

Title: How to inject into var in Kotlin?

Body:
I try to implement Dagger2 into my Kotlin project but I have problems with the @Inject annotation.

In Java it looks like this and this works fine:

public class FooActivity extends Activity {

    @Inject
    @Named("accessTokenObservable")
    public Flowable<Optional<AccessToken>> accessTokenObservable;

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        App.getGraph().inject(this);
    }
}

But how I have to write the @Inject line in Kotlin?

When I use this one:

@Inject
@Named("accessTokenObservable")
var accessTokenObservable: Flowable<Optional<AccessToken>>? = null

I get this error message:

Error:Dagger does not support injection into private fields

If I use lateinit:

@Inject
@Named("accessTokenObservable")
lateinit var accessTokenObservable: Flowable<Optional<AccessToken>>

I get this error message:

Error:Flowable<Optional<AccessToken>> cannot be provided without
an @Provides- or @Produces-annotated method.

What is the right syntax to inject something in Kotlin?

Body:
Do you provide Flowable<Optional<AccessToken>> accessTokenObservable somewhere  in your code?

If not
Error:Flowable<Optional<AccessToken>> cannot be provided without
an @Provides- or @Produces-annotated method. can be produced. Because you are trying to inject object without provide it.
In this case you need to provide in your injector class:

@Provide
@Named("accessTokenObservable")
fun provideAccessTokenObservable : Flowable<Optional<AccessToken>>{
    return yourAccessTokenObservable
}

then you need to inject your object in your activity

@Inject
@Named("accessTokenObservable")
lateinit var accessTokenObservable: Flowable<Optional<AccessToken>>


问:
Lifetime of a compound literal
6.5.2.5p5 says

If the compound literal occurs outside the body of a function, the
  object has static storage duration; otherwise, it has automatic
  storage duration associated with the enclosing block.

Am I correct to interpret "the enclosing block" here as "the innermost enclosing block"? (Because if it's not the innermost one, which is it?)
Why are gcc and clang behaving as if the lifetime of a literal were its enclosing function?

Example:

```<code>long foo(long*);

void call_foo()
{
    {foo(&(long){42});}
    {foo(&(long){42});}
    {foo(&(long){42});}
    {foo(&(long){42});}
}

//for comparison

void call_foo2()
{
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
}
</code>```

Code generated by gcc/clang at -O3:

```<code>call_foo:
  sub rsp, 40
  mov rdi, rsp
  mov QWORD PTR [rsp], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+16]
  mov QWORD PTR [rsp+16], 42
  call foo
  lea rdi, [rsp+24]
  mov QWORD PTR [rsp+24], 42
  call foo
  add rsp, 40
  ret
call_foo2:
  sub rsp, 24
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  add rsp, 24
  ret
</code>```

答: There does not seem to be any good reason for this. I would just call it a compiler bug.</p>

Title: Lifetime of a compound literal

Body:
6.5.2.5p5 says

If the compound literal occurs outside the body of a function, the
  object has static storage duration; otherwise, it has automatic
  storage duration associated with the enclosing block.

Am I correct to interpret "the enclosing block" here as "the innermost enclosing block"? (Because if it's not the innermost one, which is it?)
Why are gcc and clang behaving as if the lifetime of a literal were its enclosing function?

Example:

long foo(long*);

void call_foo()
{
    {foo(&(long){42});}
    {foo(&(long){42});}
    {foo(&(long){42});}
    {foo(&(long){42});}
}

//for comparison

void call_foo2()
{
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
    {long x=42;foo(&x);}
}

Code generated by gcc/clang at -O3:

call_foo:
  sub rsp, 40
  mov rdi, rsp
  mov QWORD PTR [rsp], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+16]
  mov QWORD PTR [rsp+16], 42
  call foo
  lea rdi, [rsp+24]
  mov QWORD PTR [rsp+24], 42
  call foo
  add rsp, 40
  ret
call_foo2:
  sub rsp, 24
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  lea rdi, [rsp+8]
  mov QWORD PTR [rsp+8], 42
  call foo
  add rsp, 24
  ret


问:
Laravel 5.5 global variable in template from service provider
How can I get info about logged user in service provider? When I use this in my template {{ $test }} always return 0 but i'm 100% sure that im logged in. Or mybe you have better solution?</p>

```<code>use Illuminate\Support\ServiceProvider;
use Auth;
use View;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $user = Auth::user();
        if ($user !== null) {
            $walletsCount = $user->wallets()->count();
        } else {
            $walletsCount = 0;
        }
        View::share('test', $walletsCount);
    }
}
</code>```

答:
It's happening because auth functionality is not initialized yet when Laravel is loading service providers. One way to deal with it is to move the logic to the view:

```<code>{{ auth()->check() ? auth()->user()->wallets()->count() : 0 }}
</code>```

Another way to go is using a view composer with closure:

```<code>public function boot()
{
    view()->composer('*', function($view) {
        $view->with('walletsCount', auth()->check() ? auth()->user()->wallets()->count() : 0);
    });
}
</code>```

Body:
How can I get info about logged user in service provider? When I use this in my template {{ $test }} always return 0 but i'm 100% sure that im logged in. Or mybe you have better solution?

use Illuminate\Support\ServiceProvider;
use Auth;
use View;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $user = Auth::user();
        if ($user !== null) {
            $walletsCount = $user->wallets()->count();
        } else {
            $walletsCount = 0;
        }
        View::share('test', $walletsCount);
    }
}

Body:
It's happening because auth functionality is not initialized yet when Laravel is loading service providers. One way to deal with it is to move the logic to the view:

{{ auth()->check() ? auth()->user()->wallets()->count() : 0 }}

Another way to go is using a view composer with closure:

public function boot()
{
    view()->composer('*', function($view) {
        $view->with('walletsCount', auth()->check() ? auth()->user()->wallets()->count() : 0);
    });
}


问:
Why should I use "Web 2.0"-style URLs?
In short, why use something like http://stackoverflow.com/badges/6/supporter instead of something "simpler" (and subjectively, at that) like http://stackoverflow.com/badges/6/.

Even on my own site I've just been using /post/6/ to reference posts (by IDs, even though I still store a slug.) Instead of /post/6/small-rant-on-urls, and in some cases, they can get even more absurd, much more so than is really necessary.

答:
Well, firstly it should be pointed out that the "Web 2.0 style URLs" are actually part of something called REST.  Those URLs are sometimes called RESTful URLs.   The claimed benefits are:

Provides improved response time and reduced server load due to its support
  for the caching of representations;

Improves server scalability by reducing the need to maintain session
  state. This means that different
  servers can be used to handle
  different requests in a session;

Requires less client-side software to be written than other approaches,
  because a single browser can access
  any application and any resource;

Depends less on vendor software and mechanisms which layer additional
  messaging frameworks on top of HTTP;

Provides equivalent functionality when compared to alternative
  approaches to communication;

Does not require a separate resource discovery mechanism, due to
  the use of hyperlinks in
  representations;

Provides better long-term compatibility and evolvability
  characteristics than RPC. This is due
  to:

The capability of document types such as HTML to evolve without
  breaking backwards- or
  forwards-compatibility; and

The ability of resources to add support for new content types as they
  are defined without dropping or
  reducing support for older content
  types.

OwnerDisplayName: hydrapheetz

ContentLicense: CC BY-SA 2.5

Title: Why should I use "Web 2.0"-style URLs?

OwnerDisplayName: cletus


问:
Rails: How to change the text on the submit button in a Rails Form
i have listed my _form.html.erb file below what i would like to do is change the text on the submit button i know how to do it in html but not shure how to do it in Rails 3</p>

```<code>%= form_for(@faq) do |f| %>
  <% if @faq.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@faq.errors.count, "error") %> prohibited this faq from being saved:</h2>

      <ul>
      <% @faq.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :question %><br />
    <%= f.text_field :question %>
  </div>
  <div class="field">
    <%= f.label :answer %><br />
    <%= f.text_area :answer %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
You can use:

```<code><%= f.submit 'Name of the submit button' %>
</code>```

For questions like this, consider using the available docs either at

Ruby on Rails API website

APIdock Ruby on Rails section (very easy navigation / search)

Sometimes, a google search like the one below helps:

Google: site:api.rubyonrails.org f.submit

Body:
i have listed my _form.html.erb file below what i would like to do is change the text on the submit button i know how to do it in html but not shure how to do it in Rails 3

%= form_for(@faq) do |f| %>
  <% if @faq.errors.any? %>

<%= pluralize(@faq.errors.count, "error") %> prohibited this faq from being saved:

      <% @faq.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :question %>

    <%= f.text_field :question %>

    <%= f.label :answer %>

    <%= f.text_area :answer %>

    <%= f.submit %>

<% end %>

Body:
You can use:

<%= f.submit 'Name of the submit button' %>

For questions like this, consider using the available docs either at

Ruby on Rails API website

APIdock Ruby on Rails section (very easy navigation / search)

Sometimes, a google search like the one below helps:

Google: site:api.rubyonrails.org f.submit


问:
How to easily output x to the power of n as a string
I need to output large numbers like for example 847288609443 as 3⁴⁵. All of my numbers have the form 3^n or 3^n -1. I use the hints from this post. For now my code looks like :

```<code>public static void main(String[] args) throws IOException {
   Map<String,Character> map = new HashMap<>();
   map.put("-", '\u207b');       map.put("5", '\u2075');
   map.put("0", '\u2070');       map.put("6", '\u2076');
   map.put("1", '\u00b9');       map.put("7", '\u2077');
   map.put("2", '\u00b2');       map.put("8", '\u2078');
   map.put("3", '\u00b3');       map.put("9", '\u2079');
   map.put("4", '\u2074');

   for(int i = 1; i< 50; i++){
       String [] s = String.valueOf(i).split("");
       StringBuilder sb = new StringBuilder();
       sb.append("3");
       Stream.of(s).forEach(e->sb.append(map.get(e)));
       System.out.println(sb.toString());
   }
}
</code>```

unicode values are from this wiki page:(https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts)

Is there another way of doing such a conversion instead of spliting the string value of my exponents and appending unicode chars?

答:
I'm going to assume that your code does what you want...

The idea of converting each digit to a unicode superscript and appending to a StringBuilder is fine, but your implementation is not very efficient -- especially in the split.  If that's bothering you, then you can do it like this, which will be a lot faster:

```<code>static final String SUPDIGITS = "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";

public static void main(String[] args) throws IOException {

   StringBuilder sb = new StringBuilder();
   for(int i = 1; i< 50; i++) {
       sb.setLength(0);

       //append digits in reverse order
       int v = i;
       for (;v>0;v/=10) {
           sb.append(SUPDIGITS.charAt(v%10));
       }
       //and then the 3
       sb.append("3");
       //and then reverse it
       sb.reverse();
       System.out.append(sb).println();
   }
}
</code>```

The major difference here is that this version does many fewer memory allocations.

Body:
I need to output large numbers like for example 847288609443 as 3⁴⁵. All of my numbers have the form 3^n or 3^n -1. I use the hints from this post. For now my code looks like :

public static void main(String[] args) throws IOException {
   Map<String,Character> map = new HashMap<>();
   map.put("-", '\u207b');       map.put("5", '\u2075');
   map.put("0", '\u2070');       map.put("6", '\u2076');
   map.put("1", '\u00b9');       map.put("7", '\u2077');
   map.put("2", '\u00b2');       map.put("8", '\u2078');
   map.put("3", '\u00b3');       map.put("9", '\u2079');
   map.put("4", '\u2074');

   for(int i = 1; i< 50; i++){
       String [] s = String.valueOf(i).split("");
       StringBuilder sb = new StringBuilder();
       sb.append("3");
       Stream.of(s).forEach(e->sb.append(map.get(e)));
       System.out.println(sb.toString());
   }
}

unicode values are from this wiki page:(https://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts)

Is there another way of doing such a conversion instead of spliting the string value of my exponents and appending unicode chars?

Body:
I'm going to assume that your code does what you want...

The idea of converting each digit to a unicode superscript and appending to a StringBuilder is fine, but your implementation is not very efficient -- especially in the split.  If that's bothering you, then you can do it like this, which will be a lot faster:

static final String SUPDIGITS = "\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079";

public static void main(String[] args) throws IOException {

   StringBuilder sb = new StringBuilder();
   for(int i = 1; i< 50; i++) {
       sb.setLength(0);

       //append digits in reverse order
       int v = i;
       for (;v>0;v/=10) {
           sb.append(SUPDIGITS.charAt(v%10));
       }
       //and then the 3
       sb.append("3");
       //and then reverse it
       sb.reverse();
       System.out.append(sb).println();
   }
}

The major difference here is that this version does many fewer memory allocations.


答:
You could do something like that:</p>

```<code>private static char[] DIGITS = {
        '\u2070', '\u00b9', '\u00b2', '\u00b3', '\u2074',
        '\u2075', '\u2076', '\u2077', '\u2078', '\u2079'};

public static String toSuperscript(int i) {
    boolean neg = i < 0;
    if (neg) {
        i = -i;
    }
    char[] chars = new char[15];
    int k = chars.length;
    do {
        chars[--k] = DIGITS[i%10];
        i /= 10;
    } while (i > 0);
    if (neg) {
        chars[--k] = '\u207b'; // minus sign
    }
    return new String(chars, k, chars.length-k);
}

public static void main(String[] args) throws IOException {
   for(int i = 1; i< 50; i++){
       System.out.println("3" + toSuperscript(i));
   }
}
</code>```

Title: How to easily output x to the power of n as a string

Body:
You could do something like that:

private static char[] DIGITS = {
        '\u2070', '\u00b9', '\u00b2', '\u00b3', '\u2074',
        '\u2075', '\u2076', '\u2077', '\u2078', '\u2079'};

public static String toSuperscript(int i) {
    boolean neg = i < 0;
    if (neg) {
        i = -i;
    }
    char[] chars = new char[15];
    int k = chars.length;
    do {
        chars[--k] = DIGITS[i%10];
        i /= 10;
    } while (i > 0);
    if (neg) {
        chars[--k] = '\u207b'; // minus sign
    }
    return new String(chars, k, chars.length-k);
}

public static void main(String[] args) throws IOException {
   for(int i = 1; i< 50; i++){
       System.out.println("3" + toSuperscript(i));
   }
}


问:
Get user's current location when they click on button
I am building a web application based on users current location using javascript/jquery. How to get current location of user when he browse my application on all browsers?</p>

答:
you can use geolocation API ..  for more details you can refer this
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation</p>


问:
PHP/Symfony 2 - Fetch data from db, edit it and resend to another server
In my symfony 2 app by using a console command I want to fetch data from database table. Looping through I want to change them a bit (e.g multiply some values) and then send it to database on another server (by curl).

How can I set new names of the columns and assign those data to them? And also how to send it as an .sql file?

Just to give you brief notion here is a raw version of my command:

```<code>class MyCommand extends ContainerAwareCommand
{
      private $input;
      private $output;

      protected function configure()
      {
        // my configs
      }

     protected function execute(InputInterface $input, OutputInterface $output)
      {
       $entityManager = $this->getContainer()->get('doctrine')->getManager('default');

       $queryBuilder = $entityManager->createQueryBuilder();
       $query = $queryBuilder
                -> // my query params

       foreach ($query->iterate() as $e)
      {
       // loop through results of the query in order to create a new DB table
      }

     $this->sendData($output);

      }

}
</code>```

Thank you in advance for any help and advises!

答:
Generate a sql file and send by curl to another server executes it doesn't seems the best approach at all. If someone else sends a malicious sql file to be executed on the server?

Doctrine provides a feature to a connect on multiple databases. Maybe you could use this functionality instead of sending the sql file.

Answering your question, inside your loop statement you could generate the INSERTS/UPDATES sql statements that you need and saving each one inside a text file using a function like fwrite

Take a look for this function here: http://php.net/manual/en/function.fwrite.php

Body:
In my symfony 2 app by using a console command I want to fetch data from database table. Looping through I want to change them a bit (e.g multiply some values) and then send it to database on another server (by curl).

How can I set new names of the columns and assign those data to them? And also how to send it as an .sql file?

Just to give you brief notion here is a raw version of my command:

class MyCommand extends ContainerAwareCommand
{
      private $input;
      private $output;

      protected function configure()
      {
        // my configs
      }

     protected function execute(InputInterface $input, OutputInterface $output)
      {
       $entityManager = $this->getContainer()->get('doctrine')->getManager('default');

       $queryBuilder = $entityManager->createQueryBuilder();
       $query = $queryBuilder
                -> // my query params

       foreach ($query->iterate() as $e)
      {
       // loop through results of the query in order to create a new DB table
      }

     $this->sendData($output);

      }

}

Thank you in advance for any help and advises!


问:
Need to pass array to route and controller
I need to pass array to route and controller from view.

I get the error:

Missing required parameters for [Route: actBook] [URI: bookfromindex/actBook/{id}/{array}].

I have my route defined as:

```<code>Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');
</code>```

My controller function is defined as:

```<code>public function actBook(Request $request, $id, $array){
</code>```

And I call this route in my view using:

```<code><a href="{{ route('actBook', $room->id, $array) }}" class="btn btn-default">დაჯავშნა</a>
</code>```

How do I prevent this error?

答:
Just use serialize($array);

Then pass this array to the route.

Body:
I need to pass array to route and controller from view.

I get the error:

Missing required parameters for [Route: actBook] [URI: bookfromindex/actBook/{id}/{array}].

I have my route defined as:

Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');

My controller function is defined as:

public function actBook(Request $request, $id, $array){

And I call this route in my view using:

id, $array) }}" class="btn btn-default">დაჯავშნა

How do I prevent this error?


问:
Is there a faster method of deleting shapes in Excel
I've successfully added shapes into cells (msoShapeOval) in a pivot table.

I need to clear and recreate these shapes if the pivot / slicer selection changes.

My current method works, but it is slow.

Is there any better method to clear shapes in bulk?
Note: I do know the exact cell range where all these shapes exist.

I've also appied :

```<code>Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
</code>```

Current code:

```<code>  Dim Shp as Shape
  For Each Shp In rng.Parent.Shapes
     If InStrB(Shp.Name, "$") > 0 Then Shp.Delete
  Next
</code>```

答:
It is possible to delete the shapes at once without selecting, with some fine tuning. Let's imagine you want to delete the rectangulars from this:

What you need to do is the following:

loop through all the objects

make an array with all the rectangular's names

delete the objects in the array

Tricky part is the looping through the objects, because you need to increment your array every time, which is not a built-in functionality (like in collection). incrementArray is the function for this.

Furthermore, the first time you increment to the unassigned array, you need to check whether it is allocated (achieved with the IsArrayAllocated function below).

```<code>Option Explicit

Sub TestMe()

    Dim shp             As Shape
    Dim arrOfShapes()   As Variant 'the () are important!

    With ActiveSheet
        For Each shp In .Shapes
            If InStrB(shp.Name, "Rec") > 0 Then
                arrOfShapes = incrementArray(arrOfShapes, shp.Name)
            End If
        Next
        If IsArrayAllocated(arrOfShapes) Then
            Debug.Print .Shapes.Range(arrOfShapes(0)).Name
            .Shapes.Range(arrOfShapes).Delete
        End If
    End With
End Sub
</code>```

The additional functions:

```<code>Public Function incrementArray(arrOfShapes As Variant, nameOfShape As String) As Variant

    Dim cnt         As Long
    Dim arrNew      As Variant

    If IsArrayAllocated(arrOfShapes) Then
        ReDim arrNew(UBound(arrOfShapes) + 1)
        For cnt = LBound(arrOfShapes) To UBound(arrOfShapes)
            arrNew(cnt) = CStr(arrOfShapes(cnt))
        Next cnt
        arrNew(UBound(arrOfShapes) + 1) = CStr(nameOfShape)
    Else
        arrNew = Array(nameOfShape)
    End If

    incrementArray = arrNew

End Function

Function IsArrayAllocated(Arr As Variant) As Boolean
    On Error Resume Next
    IsArrayAllocated = IsArray(Arr) And _
                       Not IsError(LBound(Arr, 1)) And _
                       LBound(Arr, 1) <= UBound(Arr, 1)

End Function
</code>```

Credits to this guy for the finding that the arrOfShapes should be declared with parenthesis (I have spent about 30 minutes researching why I could not pass it correctly) and to CPearson for the IsArrayAllocated().

Body:
I've successfully added shapes into cells (msoShapeOval) in a pivot table.

I need to clear and recreate these shapes if the pivot / slicer selection changes.

My current method works, but it is slow.

Is there any better method to clear shapes in bulk?
Note: I do know the exact cell range where all these shapes exist.

I've also appied :

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

Current code:

  Dim Shp as Shape
  For Each Shp In rng.Parent.Shapes
     If InStrB(Shp.Name, "$") > 0 Then Shp.Delete
  Next

Body:
It is possible to delete the shapes at once without selecting, with some fine tuning. Let's imagine you want to delete the rectangulars from this:

What you need to do is the following:

loop through all the objects

make an array with all the rectangular's names

delete the objects in the array

Tricky part is the looping through the objects, because you need to increment your array every time, which is not a built-in functionality (like in collection). incrementArray is the function for this.

Furthermore, the first time you increment to the unassigned array, you need to check whether it is allocated (achieved with the IsArrayAllocated function below).

Option Explicit

Sub TestMe()

    Dim shp             As Shape
    Dim arrOfShapes()   As Variant 'the () are important!

    With ActiveSheet
        For Each shp In .Shapes
            If InStrB(shp.Name, "Rec") > 0 Then
                arrOfShapes = incrementArray(arrOfShapes, shp.Name)
            End If
        Next
        If IsArrayAllocated(arrOfShapes) Then
            Debug.Print .Shapes.Range(arrOfShapes(0)).Name
            .Shapes.Range(arrOfShapes).Delete
        End If
    End With
End Sub

The additional functions:

Public Function incrementArray(arrOfShapes As Variant, nameOfShape As String) As Variant

    Dim cnt         As Long
    Dim arrNew      As Variant

    If IsArrayAllocated(arrOfShapes) Then
        ReDim arrNew(UBound(arrOfShapes) + 1)
        For cnt = LBound(arrOfShapes) To UBound(arrOfShapes)
            arrNew(cnt) = CStr(arrOfShapes(cnt))
        Next cnt
        arrNew(UBound(arrOfShapes) + 1) = CStr(nameOfShape)
    Else
        arrNew = Array(nameOfShape)
    End If

    incrementArray = arrNew

End Function

Function IsArrayAllocated(Arr As Variant) As Boolean
    On Error Resume Next
    IsArrayAllocated = IsArray(Arr) And _
                       Not IsError(LBound(Arr, 1)) And _
                       LBound(Arr, 1) <= UBound(Arr, 1)

End Function

Credits to this guy for the finding that the arrOfShapes should be declared with parenthesis (I have spent about 30 minutes researching why I could not pass it correctly) and to CPearson for the IsArrayAllocated().


问:
Cannot use datalab - getting error 403 when connecting in browser
I have tried to configure from scratch datalab with the free google cloud trial account.
I followed all steps here:
https://cloud.google.com/datalab/docs/quickstart

When I connect to my browser on localhost:8081, I get the following error:
403 Forbidden

I have tried to delete project, recreate one.
Change VM zone from europe-west to us-west with no luck.
I have also checked other post and made all account editor / owner of my project, same thing.
One thing i noticed is that when I create instance, I cannot choose 'y' when prompted to cache ssh key, and I have to press CTRL+C. Not sure if that makes a difference ? I tried from cmd and powershell, same issue.

```<code>Updating project ssh metadata.../Updated [https://www.googleapis.com/co
Updating project ssh metadata...done.
Waiting for SSH key to propagate.
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 7b:bd:14:9xxxx14:6c:a8
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) ^C^CTerminate batch job (Y/N)? y
Terminate batch job (Y/N)? y
</code>```

Any idea ?

答: Turned out I already had an http process (jabber) on port 8081...</p>

Body:
I have tried to configure from scratch datalab with the free google cloud trial account.
I followed all steps here:
https://cloud.google.com/datalab/docs/quickstart

When I connect to my browser on localhost:8081, I get the following error:
403 Forbidden

I have tried to delete project, recreate one.
Change VM zone from europe-west to us-west with no luck.
I have also checked other post and made all account editor / owner of my project, same thing.
One thing i noticed is that when I create instance, I cannot choose 'y' when prompted to cache ssh key, and I have to press CTRL+C. Not sure if that makes a difference ? I tried from cmd and powershell, same issue.

Updating project ssh metadata.../Updated [https://www.googleapis.com/co
Updating project ssh metadata...done.
Waiting for SSH key to propagate.
The server's host key is not cached in the registry. You
have no guarantee that the server is the computer you
think it is.
The server's rsa2 key fingerprint is:
ssh-rsa 2048 7b:bd:14:9xxxx14:6c:a8
If you trust this host, enter "y" to add the key to
PuTTY's cache and carry on connecting.
If you want to carry on connecting just once, without
adding the key to the cache, enter "n".
If you do not trust this host, press Return to abandon the
connection.
Store key in cache? (y/n) ^C^CTerminate batch job (Y/N)? y
Terminate batch job (Y/N)? y

Any idea ?


问:
jdbc driver to connect oracle from python
Do you know of any library to use a jdbc url to connect oracle using python?
i tried using pyodbc but its slow while retrieving million records.
note: pyodbc uses odbc connections

Thanks in advance
sreeni

答:
Have you tried JayDeBeApi?

The JayDeBeApi module allows you to connect from Python code to
  databases using Java JDBC. It provides a Python DB-API v2.0 to that
  database.


问:
Function Now: Tdatetime for Perpetual Calendar
I am trying to write a function for Tdatetime (but when I open my program, he must show now data)

Below i have a function for TDatetime but I have an error in that:

((((''DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);''))))

```<code>unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Spin, Buttons;

type
  TForm1 = class(TForm)
    edRok: TSpinEdit;
    edMiesiac: TSpinEdit;
    edDzien: TSpinEdit;
    lbRok: TLabel;
    lbMiesiac: TLabel;
    lbDzien: TLabel;
    lbDT: TLabel;
    btnZamknij: TBitBtn;
    procedure edRokChange(Sender: TObject);
    procedure edDzienChange(Sender: TObject);
    procedure DecodeDate(Date: TDateTime);
    function DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
    function GetDzienText(Dt: Byte): String;
    function Now: TDateTime;

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.edRokChange(Sender: TObject);
begin
 case edMiesiac.Value of
  1,3,5,7,8,10,12: edDzien.MaxValue:=31;
  4,6,9,11: edDzien.MaxValue:=30;
 else
  if edRok.Value mod 4=0 then edDzien.MaxValue:=29
  else edDzien.MaxValue:=28;
 end;{case}
 if edDzien.Value>edDzien.MaxValue then
  edDzien.Value:=edDzien.MaxValue;
  edDzienChange(Sender);
end;

procedure TForm1.edDzienChange(Sender: TObject);
begin
 lbDt.Caption:='Dzień tygodnia: '+GetDzienText(DT(eddzien.value, edmiesiac.value, edrok.value));
end;

procedure TForm1.DecodeDate(Date: TDateTime);
var
 Now, Rok, Miesiac, Dzien: Word;
begin
DecodeDate(Now);
DecodeDate(Rok);
DecodeDate(Miesiac);
DecodeDate(Dzien);
edRok.Value:=Rok;
edMiesiac.Value:=Miesiac;
edDzien.Value:=Dzien;
end;

function TForm1.DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
var m,r,w: Byte; {deklaracja zmiennych}
begin
 if Miesiac>2 then m:=miesiac-2
 else
  begin
   m:=miesiac+10;
   rok:=rok-1;
  end;
  r:=rok mod 100;
  w:=rok div 100;
 Result:=((13*m-1) div 5+dzien+r div 4+w div 4+r+5*w) mod 7;
end;

function TForm1.GetDzienText(Dt: Byte): String;
const Dni: array[0..6] of String=
      ('Niedziela','Poniedziałek','Wtorek','Środa',
       'Czwartek','Piątek','Sobota');
begin
 Result:=Dni[dt];
end;

function TForm1.Now: TDateTime;
var
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
  data: TDateTime;

begin
  data := Now;
  DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);
  MessageBox(0,PAnsiChar(Format('Data: %d/%d/%d %d:%d:%d:%d',[rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])), 'Data', MB_ICONINFORMATION);
end;

end.
</code>```

答:
You appear to have an infinite recursion together which will lead to a stack overflow (how fitting that you ask this question here).

You could instead write:

```<code>function TForm1.Now: TDateTime;
var
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
begin
  Result := SysUtils.Now;
  SysUtils.DecodeDate(Result, rok, miesiac, dzien);
  DecodeTime(Result, godzina, minuta, sekunda, milisekunda);
  MessageBox(0,PChar(Format('Data: %d/%d/%d %d:%d:%d:%d',[rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])), 'Data', MB_ICONINFORMATION);
end;
</code>```

I've had to fully qualify Now and DecodeDate because you use the same names in your code. You shouldn't really do that and should choose non-clashing names

I don't really understand your aims and there are clearly many other problems in this code.

Follow the comment trail of another answer I ran the following program:

```<code>program Project1;

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

procedure Main;
var
  dt: TDateTime;
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
begin
  dt := Now;
  DecodeDate(dt, rok, miesiac, dzien);
  DecodeTime(dt, godzina, minuta, sekunda, milisekunda);
  MessageBox(
    0,
    PChar(Format(
      'Data: %d/%d/%d %d:%d:%d:%d',
      [rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])
    ),
    'Data',
    MB_ICONINFORMATION
  );
end;

begin
  Main;
end.
</code>```

while resulted in this output:

If your call to Now and DecodeDate really results in the year 2002, then I can only conclude that the time on your computer is wrong!

Body:
I am trying to write a function for Tdatetime (but when I open my program, he must show now data)

Below i have a function for TDatetime but I have an error in that:

((((''DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);''))))

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Spin, Buttons;

type
  TForm1 = class(TForm)
    edRok: TSpinEdit;
    edMiesiac: TSpinEdit;
    edDzien: TSpinEdit;
    lbRok: TLabel;
    lbMiesiac: TLabel;
    lbDzien: TLabel;
    lbDT: TLabel;
    btnZamknij: TBitBtn;
    procedure edRokChange(Sender: TObject);
    procedure edDzienChange(Sender: TObject);
    procedure DecodeDate(Date: TDateTime);
    function DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
    function GetDzienText(Dt: Byte): String;
    function Now: TDateTime;

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.edRokChange(Sender: TObject);
begin
 case edMiesiac.Value of
  1,3,5,7,8,10,12: edDzien.MaxValue:=31;
  4,6,9,11: edDzien.MaxValue:=30;
 else
  if edRok.Value mod 4=0 then edDzien.MaxValue:=29
  else edDzien.MaxValue:=28;
 end;{case}
 if edDzien.Value>edDzien.MaxValue then
  edDzien.Value:=edDzien.MaxValue;
  edDzienChange(Sender);
end;

procedure TForm1.edDzienChange(Sender: TObject);
begin
 lbDt.Caption:='Dzień tygodnia: '+GetDzienText(DT(eddzien.value, edmiesiac.value, edrok.value));
end;

procedure TForm1.DecodeDate(Date: TDateTime);
var
 Now, Rok, Miesiac, Dzien: Word;
begin
DecodeDate(Now);
DecodeDate(Rok);
DecodeDate(Miesiac);
DecodeDate(Dzien);
edRok.Value:=Rok;
edMiesiac.Value:=Miesiac;
edDzien.Value:=Dzien;
end;

function TForm1.DT(Dzien, Miesiac: Byte; Rok: Integer): Byte;
var m,r,w: Byte; {deklaracja zmiennych}
begin
 if Miesiac>2 then m:=miesiac-2
 else
  begin
   m:=miesiac+10;
   rok:=rok-1;
  end;
  r:=rok mod 100;
  w:=rok div 100;
 Result:=((13*m-1) div 5+dzien+r div 4+w div 4+r+5*w) mod 7;
end;

function TForm1.GetDzienText(Dt: Byte): String;
const Dni: array[0..6] of String=
      ('Niedziela','Poniedziałek','Wtorek','Środa',
       'Czwartek','Piątek','Sobota');
begin
 Result:=Dni[dt];
end;

function TForm1.Now: TDateTime;
var
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
  data: TDateTime;

begin
  data := Now;
  DecodeDateTime(data, rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda);
  MessageBox(0,PAnsiChar(Format('Data: %d/%d/%d %d:%d:%d:%d',[rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])), 'Data', MB_ICONINFORMATION);
end;

end.

Body:
You appear to have an infinite recursion together which will lead to a stack overflow (how fitting that you ask this question here).

You could instead write:

function TForm1.Now: TDateTime;
var
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
begin
  Result := SysUtils.Now;
  SysUtils.DecodeDate(Result, rok, miesiac, dzien);
  DecodeTime(Result, godzina, minuta, sekunda, milisekunda);
  MessageBox(0,PChar(Format('Data: %d/%d/%d %d:%d:%d:%d',[rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])), 'Data', MB_ICONINFORMATION);
end;

I've had to fully qualify Now and DecodeDate because you use the same names in your code. You shouldn't really do that and should choose non-clashing names

I don't really understand your aims and there are clearly many other problems in this code.

Follow the comment trail of another answer I ran the following program:

program Project1;

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

procedure Main;
var
  dt: TDateTime;
  dzien, miesiac, rok: Word;
  godzina, minuta, sekunda, milisekunda: Word;
begin
  dt := Now;
  DecodeDate(dt, rok, miesiac, dzien);
  DecodeTime(dt, godzina, minuta, sekunda, milisekunda);
  MessageBox(
    0,
    PChar(Format(
      'Data: %d/%d/%d %d:%d:%d:%d',
      [rok, miesiac, dzien, godzina, minuta, sekunda, milisekunda])
    ),
    'Data',
    MB_ICONINFORMATION
  );
end;

begin
  Main;
end.

while resulted in this output:

If your call to Now and DecodeDate really results in the year 2002, then I can only conclude that the time on your computer is wrong!


问:
Scroll to an element in a div
I would like my

```<code>div="#course_navigation"
</code>```

in my sidebar with this css:

```<code>.sidebar #course_navigation {
    max-height: 700px !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
}
</code>```

to scroll to this class on page load:

```<code>.learndash-current-menu-item
</code>```

I try this, but nothing happens:

```<code>$('#course_navigation').scrollTo('.learndash-current-menu-item');
</code>```

I have tried many other codes, with no success. Don't know the problem is.

The structure looks like this:

Maybe I was not specific enough, so I repeat:

```<code>#course_navigation
</code>```

is scrollable.

I need #course_navigation scrolled until .learndash-current-menu-item can be seen at the top or center of #course_navigation on page load.

I have this at field of Theme Space before /head:

```<code><script src="code.jquery.com/jquery-1.10.2.js"></script>;
</code>```

I put the script to Space before /body like this:

```<code><script>$('#course_navigation').scrollTo('.learndash-current-menu-item');</script>
</code>```

No succes yet, nothing happens, none of the solution works...

Please help me out here with JS or jquery. The best should be scroll the element to the center of the div.

Thank you in advance!

András

答:
try this code

$('html, body').animate({
  'scrollTop': $("#course_navigation").position().top
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sidebar #course_navigation {
  max-height: 700px !important;
  overflow-y: auto !important;
  overflow-x: hidden !important;
}</code>```

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test test test test test test test

test
```

Title: Scroll to an element in a div

Body:
I would like my

div="#course_navigation"

in my sidebar with this css:

.sidebar #course_navigation {
    max-height: 700px !important;
    overflow-y: auto !important;
    overflow-x: hidden !important;
}

to scroll to this class on page load:

.learndash-current-menu-item

I try this, but nothing happens:

$('#course_navigation').scrollTo('.learndash-current-menu-item');

I have tried many other codes, with no success. Don't know the problem is.

The structure looks like this:

Maybe I was not specific enough, so I repeat:

#course_navigation

is scrollable.

I need #course_navigation scrolled until .learndash-current-menu-item can be seen at the top or center of #course_navigation on page load.

I have this at field of Theme Space before /head:

;

I put the script to Space before /body like this:

No succes yet, nothing happens, none of the solution works...

Please help me out here with JS or jquery. The best should be scroll the element to the center of the div.

Thank you in advance!

András

Body:
try this code

$('html, body').animate({
  'scrollTop': $("#course_navigation").position().top
});

.sidebar #course_navigation {
  max-height: 700px !important;
  overflow-y: auto !important;
  overflow-x: hidden !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="#course_navigation1">
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
  <p>test test test test test test test </p>
</div>
<div id="course_navigation">test</div>


问:
Inserting data into a related database. C#
I've got two tables that i'm trying to insert data into with my C# application. They related with the ID.

I've read afew questions on how to do this but none of them have worked, I've now decided to do them as separate sql queries.

```<code> private void btnSave_Click(object sender, EventArgs e)
        {
            //table 1
            String acctCode = tbAcctCode.Text;
            String address1 = tbAdd1.Text;
            String address2 = tbAdd2.Text;
            String address3 = tbAdd3.Text;
            String balance = tbBalance.Text;
            String yearSales = tbSales.Text;
            String yearCost = tbCost.Text;
            //table 2
            String date = tbDate.Text;
            String transaction = tbTrans.Text;
            String docNum = tbDocNum.Text;
            String grossVal = tbGross.Text;
            String vatVal = tbVat.Text;

            //SQL statement set to Add a new value
            sql = String.Format("INSERT INTO "+ table1 + "(Account_Code,Address1,Address2,Address3,Balance,Sales_Year_To_Date,Cost_Year_To_Date) " +
                                 "VALUES " +
                                 "('{0}'," + "{1}," + "{2}," + "'{3}'," + "'{4}'," + "{5}," + "'{6}');", acctCode, address1, address2, address3, balance, yearSales, yearCost);

            sql2 = String.Format("INSERT INTO " + table2 + "(Date,Transaction_Type,Document_No,Gross_Transaction_Value,Vat_Value) " +
                                 "VALUES " +
                                 "('{0}'," + "'{1}'," + "'{2}'," + "'{3}'," + "'{4}');", date, transaction, docNum, grossVal, vatVal);

            try
            {
                dbConn = new OleDbConnection(conString);
                dbCmd = new OleDbCommand(sql, dbConn);

                dbConn.Open();
                dbCmd.ExecuteNonQuery();
                dbCmd = new OleDbCommand(sql2, dbConn);
                dbCmd.ExecuteNonQuery();
            }
            catch (SqlException E)
            {
                MessageBox.Show(E.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                dbConn.Close();
            }

        }
    }
</code>```

The data is inserted into the first table fine but the problem comes in at the OleDbCommand of the sql2. "It throws a System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'"

I've got a feeling something in my sql syntax is wrong but I can't spot it.

答:
```<code>Try This Would Be Prefect

private void btnSave_Click(object sender, EventArgs e)
{
    //SQL statement set to Add a new value
        sql = String.Format("INSERT INTO " + table1 + "(Account_Code,Address1,Address2,Address3,Balance,Sales_Year_To_Date,Cost_Year_To_Date) " +
                             "VALUES " + (@acctCode, @address1, @address2, @address3, @balance, @yearSales, @yearCost));

        sql2 = String.Format("INSERT INTO " + table2 + "([Date],Transaction_Type,Document_No,Gross_Transaction_Value,Vat_Value)" +
                             "VALUES " + (@date, @transaction, @docNum, @grossVal, @vatVal));

        try
        {
            dbConn = new OleDbConnection(conString);
            cmd = new OleDbCommand(sql, dbConn);

            //table 1
            cmd.Parameters.AddWithValue("@acctCode", tbAcctCode.Text);
            cmd.Parameters.AddWithValue("@address1", tbAdd1.Text);
            cmd.Parameters.AddWithValue("@address2", tbAdd2.Text);
            cmd.Parameters.AddWithValue("@address3", tbAdd3.Text);
            cmd.Parameters.AddWithValue("@balance", tbBalance.Text);
            cmd.Parameters.AddWithValue("@yearSales", tbSales.Text);
            cmd.Parameters.AddWithValue("@yearCost", tbCost.Text);

            dbConn.Open();
            cmd.ExecuteNonQuery();
            cmd = new OleDbCommand(sql2, dbConn);

            //table 2
            cmd.Parameters.AddWithValue("@date", tbDate.Text);
            cmd.Parameters.AddWithValue("@transaction", tbTrans.Text);
            cmd.Parameters.AddWithValue("@docNum", tbDocNum.Text);
            cmd.Parameters.AddWithValue("@grossVal", tbGross.Text);
            cmd.Parameters.AddWithValue("@vatVal", tbVat.Text);

            cmd.ExecuteNonQuery();
        }
        catch (SqlException E)
        {
            MessageBox.Show(E.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        finally
        {
            dbConn.Close();
        }
    }
</code>```

Body:
I've got two tables that i'm trying to insert data into with my C# application. They related with the ID.

I've read afew questions on how to do this but none of them have worked, I've now decided to do them as separate sql queries.

 private void btnSave_Click(object sender, EventArgs e)
        {
            //table 1
            String acctCode = tbAcctCode.Text;
            String address1 = tbAdd1.Text;
            String address2 = tbAdd2.Text;
            String address3 = tbAdd3.Text;
            String balance = tbBalance.Text;
            String yearSales = tbSales.Text;
            String yearCost = tbCost.Text;
            //table 2
            String date = tbDate.Text;
            String transaction = tbTrans.Text;
            String docNum = tbDocNum.Text;
            String grossVal = tbGross.Text;
            String vatVal = tbVat.Text;

            //SQL statement set to Add a new value
            sql = String.Format("INSERT INTO "+ table1 + "(Account_Code,Address1,Address2,Address3,Balance,Sales_Year_To_Date,Cost_Year_To_Date) " +
                                 "VALUES " +
                                 "('{0}'," + "{1}," + "{2}," + "'{3}'," + "'{4}'," + "{5}," + "'{6}');", acctCode, address1, address2, address3, balance, yearSales, yearCost);

            sql2 = String.Format("INSERT INTO " + table2 + "(Date,Transaction_Type,Document_No,Gross_Transaction_Value,Vat_Value) " +
                                 "VALUES " +
                                 "('{0}'," + "'{1}'," + "'{2}'," + "'{3}'," + "'{4}');", date, transaction, docNum, grossVal, vatVal);

            try
            {
                dbConn = new OleDbConnection(conString);
                dbCmd = new OleDbCommand(sql, dbConn);

                dbConn.Open();
                dbCmd.ExecuteNonQuery();
                dbCmd = new OleDbCommand(sql2, dbConn);
                dbCmd.ExecuteNonQuery();
            }
            catch (SqlException E)
            {
                MessageBox.Show(E.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                dbConn.Close();
            }

        }
    }

The data is inserted into the first table fine but the problem comes in at the OleDbCommand of the sql2. "It throws a System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'"

I've got a feeling something in my sql syntax is wrong but I can't spot it.


答:
You can use the geolocation object

Check out this MSDN Geolocation Article, or Mozilla navigator.geolocation Docs

1. Check browser compatibility

```<code>if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}
</code>```

2. Get Current Position

```<code>navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});
</code>```

3. Watch for Changes

```<code>var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});
</code>```

Basic Working Example

var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "
Longitude: " + position.coords.longitude;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p></code>```

Also, have a look at this example on JSFiddle, by MSDN which is slightly more comprehensive.

Note: Geolocation only works on SSL sites with secure context

Browser Support

You also asked for it to work in all browsers. As with most features this isn't really possible. But you can check whether the users browser supports navigator.geolocation, and display an appropriate message if not.

Check out https://caniuse.com/#search=geolocation to see current browser support for geolocation. But in summary, it's supported on:

IE9+

Edge 13+

FF 3.5+

Safari 5.0+

Chrome 5.0+

Opera 11.5, 12.1, 16.6+

iOS Safari 3.2+

Android default browser for OS versions 2.1+

Hope that helps

Title: Get user's current location when they click on button

Body: I am building a web application based on users current location using javascript/jquery. How to get current location of user when he browse my application on all browsers?

Body:
You can use the geolocation object

Check out this MSDN Geolocation Article, or Mozilla navigator.geolocation Docs

1. Check browser compatibility

if ("geolocation" in navigator) {
  /* geolocation is available */
} else {
  /* geolocation IS NOT available */
}

2. Get Current Position

navigator.geolocation.getCurrentPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

3. Watch for Changes

var watchID = navigator.geolocation.watchPosition(function(position) {
  do_something(position.coords.latitude, position.coords.longitude);
});

Basic Working Example

var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

Also, have a look at this example on JSFiddle, by MSDN which is slightly more comprehensive.

Note: Geolocation only works on SSL sites with secure context

Browser Support

You also asked for it to work in all browsers. As with most features this isn't really possible. But you can check whether the users browser supports navigator.geolocation, and display an appropriate message if not.

Check out https://caniuse.com/#search=geolocation to see current browser support for geolocation. But in summary, it's supported on:

IE9+

Edge 13+

FF 3.5+

Safari 5.0+

Chrome 5.0+

Opera 11.5, 12.1, 16.6+

iOS Safari 3.2+

Android default browser for OS versions 2.1+

Hope that helps


问:
Stanford Parser questions
I am writing a project that works with NLP (natural language parser). I am using the stanford parser.

I create a thread pool that takes sentences and run the parser with them.
When I create one thread its all works fine, but when I create more, I get errors.
The "test" procedure is finding words that have some connections.
If I do an synchronized its supposed to work like one thread but still I get errors.
My problem is that I have errors on this code:

```<code>public synchronized String test(String s,LexicalizedParser lp )
{

    if (s.isEmpty()) return "";
    if (s.length()>80) return "";
    System.out.println(s);
    String[] sent = s.split(" ");
 Tree parse = (Tree) lp.apply(Arrays.asList(sent));
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
Collection tdl = gs.typedDependenciesCollapsed();
List list = new ArrayList(tdl);

//for (int i=0;i<list.size();i++)
//System.out.println(list.get(1).toString());

//remove scops and numbers like sbj(screen-4,good-6)->screen good

 Pattern p = Pattern.compile(".*\\((.*?)\\-\\d+,(.*?)\\-\\d+\\).*");

       if (list.size()>2){
    // Split input with the pattern
        Matcher m = p.matcher(list.get(1).toString());
        //check if the result have more than  1 groups
       if (m.find()&& m.groupCount()>1){
           if (m.groupCount()>1)
           {
               System.out.println(list);
 return  m.group(1)+m.group(2);
    }}
}
        return "";

}
</code>```

the errors that I have are:

at blogsOpinions.ParserText.(ParserText.java:47)
    at blogsOpinions.ThreadPoolTest$1.run(ThreadPoolTest.java:50)
    at blogsOpinions.ThreadPool$PooledThread.run(ThreadPoolTest.java:196)
  Recovering using fall through
  strategy: will construct an (X ...)
  tree. Exception in thread
  "PooledThread-21"
  java.lang.ClassCastException:
  java.lang.String cannot be cast to
  edu.stanford.nlp.ling.HasWord

at
  edu.stanford.nlp.parser.lexparser.LexicalizedParser.apply(LexicalizedParser.java:289)
      at blogsOpinions.ParserText.test(ParserText.java:174)
      at blogsOpinions.ParserText.insertDb(ParserText.java:76)
      at blogsOpinions.ParserText.(ParserText.java:47)
      at blogsOpinions.ThreadPoolTest$1.run(ThreadPoolTest.java:50)
      at blogsOpinions.ThreadPool$PooledThread.run(ThreadPoolTest.java:196)

and how can i get the discription of the subject like the screen is very good, and I want to get screen good from the list the I get and not like list.get(1).

答:
You can't call LexicalizedParser.parse on a List of Strings; it expects a list of HasWord objects. It's much easier to call the apply method on your input string. This will also run a proper tokenizer on your input (instead of your simple split on spaces).

To get relations such as subjectness out of the returned Tree, call its dependencies member.

Title: Stanford Parser questions

Body:
I am writing a project that works with NLP (natural language parser). I am using the stanford parser.

I create a thread pool that takes sentences and run the parser with them.
When I create one thread its all works fine, but when I create more, I get errors.
The "test" procedure is finding words that have some connections.
If I do an synchronized its supposed to work like one thread but still I get errors.
My problem is that I have errors on this code:

public synchronized String test(String s,LexicalizedParser lp )
{

    if (s.isEmpty()) return "";
    if (s.length()>80) return "";
    System.out.println(s);
    String[] sent = s.split(" ");
 Tree parse = (Tree) lp.apply(Arrays.asList(sent));
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
GrammaticalStructureFactory gsf = tlp.grammaticalStructureFactory();
GrammaticalStructure gs = gsf.newGrammaticalStructure(parse);
Collection tdl = gs.typedDependenciesCollapsed();
List list = new ArrayList(tdl);

//for (int i=0;i<list.size();i++)
//System.out.println(list.get(1).toString());

//remove scops and numbers like sbj(screen-4,good-6)->screen good

 Pattern p = Pattern.compile(".*\\((.*?)\\-\\d+,(.*?)\\-\\d+\\).*");

       if (list.size()>2){
    // Split input with the pattern
        Matcher m = p.matcher(list.get(1).toString());
        //check if the result have more than  1 groups
       if (m.find()&& m.groupCount()>1){
           if (m.groupCount()>1)
           {
               System.out.println(list);
 return  m.group(1)+m.group(2);
    }}
}
        return "";

}

the errors that I have are:

at blogsOpinions.ParserText.(ParserText.java:47)
    at blogsOpinions.ThreadPoolTest$1.run(ThreadPoolTest.java:50)
    at blogsOpinions.ThreadPool$PooledThread.run(ThreadPoolTest.java:196)
  Recovering using fall through
  strategy: will construct an (X ...)
  tree. Exception in thread
  "PooledThread-21"
  java.lang.ClassCastException:
  java.lang.String cannot be cast to
  edu.stanford.nlp.ling.HasWord

at
  edu.stanford.nlp.parser.lexparser.LexicalizedParser.apply(LexicalizedParser.java:289)
      at blogsOpinions.ParserText.test(ParserText.java:174)
      at blogsOpinions.ParserText.insertDb(ParserText.java:76)
      at blogsOpinions.ParserText.(ParserText.java:47)
      at blogsOpinions.ThreadPoolTest$1.run(ThreadPoolTest.java:50)
      at blogsOpinions.ThreadPool$PooledThread.run(ThreadPoolTest.java:196)

and how can i get the discription of the subject like the screen is very good, and I want to get screen good from the list the I get and not like list.get(1).