问:
Python Multidimensional Array as a single List
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

```<code>[[0, 1], [2, 3]]
</code>```

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

```<code>[0, 1, 2, 3]
</code>```

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

```<code>def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex
</code>```

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

答:
```<code>def getlocation(self, cellindex):
    res = []
    for size in reversed(self.dimensions):
        res.append(cellindex % size)
        cellindex /= size
    return res[::-1]
</code>```

Or, for the full test case

```<code>class ndim:
    def __init__(self):
        self.dimensions=[8,9,10]
        self.numdimensions=3
        self.gridsize=8*9*10

    def getcellindex(self, location):
        cindex = 0
        cdrop = self.gridsize
        for index in xrange(self.numdimensions):
            cdrop /= self.dimensions[index]
            cindex += cdrop * location[index]
        return cindex

    def getlocation(self, cellindex):
        res = []
        for size in reversed(self.dimensions):
            res.append(cellindex % size)
            cellindex /= size
        return res[::-1]

n=ndim()
print n.getcellindex((0,0,0))
print n.getcellindex((0,0,1))
print n.getcellindex((0,1,0))
print n.getcellindex((1,0,0))

print n.getlocation(90)
print n.getlocation(10)
print n.getlocation(1)
print n.getlocation(0)
</code>```

Body:
Sure, you can have nested lists to represent multidimensional arrays, but that seems costly...

[[0, 1], [2, 3]]

Is there some way to "encode" and "decode" the coordinate into a single number, and use that number to lookup the corresponding element?

[0, 1, 2, 3]

This needs to work with n-dimensions, not just two, and the best I could come up with for encoding is:

def getcellindex(self, location):
  cindex = 0
  cdrop = self.gridsize # where self.gridsize is the number of cells
  for index in xrange(self.numdimensions): # where self.numdimensions is the number of dimensions
    # where self.dimensions is a tuple of the different sizes of the corresponding dimension
    cdrop /= self.dimensions[index]
    cindex += cdrop * location[index]
  return cindex

There're probably ways to optimize this, but more importantly, how do I reverse the process?  And, does this function work?

Body:
def getlocation(self, cellindex):
    res = []
    for size in reversed(self.dimensions):
        res.append(cellindex % size)
        cellindex /= size
    return res[::-1]

Or, for the full test case

class ndim:
    def __init__(self):
        self.dimensions=[8,9,10]
        self.numdimensions=3
        self.gridsize=8*9*10

    def getcellindex(self, location):
        cindex = 0
        cdrop = self.gridsize
        for index in xrange(self.numdimensions):
            cdrop /= self.dimensions[index]
            cindex += cdrop * location[index]
        return cindex

    def getlocation(self, cellindex):
        res = []
        for size in reversed(self.dimensions):
            res.append(cellindex % size)
            cellindex /= size
        return res[::-1]

n=ndim()
print n.getcellindex((0,0,0))
print n.getcellindex((0,0,1))
print n.getcellindex((0,1,0))
print n.getcellindex((1,0,0))

print n.getlocation(90)
print n.getlocation(10)
print n.getlocation(1)
print n.getlocation(0)


来源: stackexchange

问:
Using try/catch for files in java
I'm having issues with using try-catch blocks in java. I'm writing a method that reads a user input file and prints it out to the console. This is what I have -

```<code>static Scanner input = new Scanner(System.in);

public static String readingFiles(String fileout) {

    boolean find = false;

    while(!find) {
            try {
                File f = new File(input.nextLine());
                Scanner scan = new Scanner(f);
            } catch (FileNotFoundException e) {
                System.out.println("File Not Found.");

            }
    }
    ArrayList<String> list = new ArrayList<String>();

    while (input.hasNext())
    {
        list.add(input.nextLine());
    }

    String output = list.toString();
    return output;

}
</code>```

It just seems like a mess and I have no idea what to do with it at this point. I had it working a few times, in that it would output what the file said but then if I purposefully entered the wrong file name it would loop "file not found" endlessly and I couldn't figure out how to return the loop to the beginning so the user could input a different file name.

Now it just does nothing even when i enter the correct file name, it returns nothing until i press enter again and it'll return file not found.
I call it using this in my main menu method -

```<code>      case 1:
            System.out.println("You chose Read File. Enter your file name: ");
            System.out.println(Question4.readingFiles(input.nextLine()));

            pressEnter();
            break;
</code>```

edit: I now have this, which works but only prints the first line of my file?

```<code>public static String readingFiles(String fileout) {

    boolean find = false;
    String result = "";
    while (!find) {
        try {
            File read = new File(fileout);
            Scanner check = new Scanner(read);
            result = check.nextLine();
            find = true;
            check.close();
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found. Please try again.");
            break;
        }
    }
    return result;
}
</code>```

答:
```<code>public class readingFiles {

public static String readingFiles(String fileout) {

    try {
        //find a file with the same name as the value of "fileout"
        File f = new File(fileout);
        Scanner scan = new Scanner(f);

        //create a list to hold the file output
        ArrayList<String> list = new ArrayList<String>();

        //loop through the output line by line and add to the list
        while (scan.hasNext())
        {
            list.add(scan.nextLine());
        }

        //convert the list into a String value to pass back to the caller
        String output = list.toString();
        scan.close();
        return output;

    } catch (FileNotFoundException e) {
        //if file is not found, return a value of -1
        System.out.println("File Not Found.");
        return("-1");
    }

}
</code>```

Okay a few things:

Your first while loop is unnecessary. I think you are trying to loop through files in the folder to look for a specific file name. However the Scanner scan = new Scanner(f); line already does this.

The reason your code infinitely prints "File not found." is because you never set the find condition to true to exit the loop.

You never use the fileout value you pass into the method. And your code asks the user for the filename input twice (once in the main method, once in the readingFiles method).

Using a list, then converting to String results in an output of [line1, line2, line3, etc] not sure if this is what you want.

As for why your second attempt prints only the first line, You have removed the while loop which loops through the file reading every line, therefore it only reads one line before stopping.

ContentLicense: CC BY-SA 3.0

Title: Using try/catch for files in java

Body:
I'm having issues with using try-catch blocks in java. I'm writing a method that reads a user input file and prints it out to the console. This is what I have -

static Scanner input = new Scanner(System.in);

public static String readingFiles(String fileout) {

    boolean find = false;

    while(!find) {
            try {
                File f = new File(input.nextLine());
                Scanner scan = new Scanner(f);
            } catch (FileNotFoundException e) {
                System.out.println("File Not Found.");

            }
    }
    ArrayList<String> list = new ArrayList<String>();

    while (input.hasNext())
    {
        list.add(input.nextLine());
    }

    String output = list.toString();
    return output;

}

It just seems like a mess and I have no idea what to do with it at this point. I had it working a few times, in that it would output what the file said but then if I purposefully entered the wrong file name it would loop "file not found" endlessly and I couldn't figure out how to return the loop to the beginning so the user could input a different file name.

Now it just does nothing even when i enter the correct file name, it returns nothing until i press enter again and it'll return file not found.
I call it using this in my main menu method -

      case 1:
            System.out.println("You chose Read File. Enter your file name: ");
            System.out.println(Question4.readingFiles(input.nextLine()));

            pressEnter();
            break;

edit: I now have this, which works but only prints the first line of my file?

public static String readingFiles(String fileout) {

    boolean find = false;
    String result = "";
    while (!find) {
        try {
            File read = new File(fileout);
            Scanner check = new Scanner(read);
            result = check.nextLine();
            find = true;
            check.close();
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found. Please try again.");
            break;
        }
    }
    return result;
}

Body:
public class readingFiles {

public static String readingFiles(String fileout) {

    try {
        //find a file with the same name as the value of "fileout"
        File f = new File(fileout);
        Scanner scan = new Scanner(f);

        //create a list to hold the file output
        ArrayList<String> list = new ArrayList<String>();

        //loop through the output line by line and add to the list
        while (scan.hasNext())
        {
            list.add(scan.nextLine());
        }

        //convert the list into a String value to pass back to the caller
        String output = list.toString();
        scan.close();
        return output;

    } catch (FileNotFoundException e) {
        //if file is not found, return a value of -1
        System.out.println("File Not Found.");
        return("-1");
    }

}

Okay a few things:

Your first while loop is unnecessary. I think you are trying to loop through files in the folder to look for a specific file name. However the Scanner scan = new Scanner(f); line already does this.

The reason your code infinitely prints "File not found." is because you never set the find condition to true to exit the loop.

You never use the fileout value you pass into the method. And your code asks the user for the filename input twice (once in the main method, once in the readingFiles method).

Using a list, then converting to String results in an output of [line1, line2, line3, etc] not sure if this is what you want.

As for why your second attempt prints only the first line, You have removed the while loop which loops through the file reading every line, therefore it only reads one line before stopping.


问:
Jackson/YAML: Parse key-value into class
I my input yaml file, I have the following:

```<code>services:
  postgresql:
    image: "postgres:10"
  redis:
    image: "redis:4"
</code>```

It's easy to parse services field into a Map<String, Service>:

```<code>public class DockerCompose {
    public static class Service {
        private String image;
    }

    private Map<String, Service> services;
}
</code>```

I would like to parse the services field in a List<Service> with the name in the field name in Service as following:

```<code>public class DockerCompose {
    public static class Service {
        private String name;
        private String image;
    }

    private List<Service> services;
}
</code>```

Is this possible?

答:
The easiest option is add custom setter for deserialization and getter for serialization.</p>

```<code>public static class DockerCompose {

    public static class Service {
        @JsonIgnore // for serialization
        private String name;
        private String image;
    }

    @JsonProperty("services") // for derserialization
    public void setServicesMap(Map<String, Service> servicesMap){
        for (Map.Entry<String, Service> entry  :servicesMap.entrySet()) {
            entry.getValue().name = entry.getKey();
            services.add(entry.getValue());
        }
    }

    @JsonProperty("services") // for serialization
    public Map<String, Service> getServicesMap() {
        Map<String, Service> map = new HashMap<>();
        for(Service s: services)
            map.put(s.getName(), s);
        return map;
    }

    @JsonIgnore // for serialization
    private List<Service> services = new ArrayList<>();
}
</code>```

Body:
I my input yaml file, I have the following:

services:
  postgresql:
    image: "postgres:10"
  redis:
    image: "redis:4"

It's easy to parse services field into a Map<String, Service>:

public class DockerCompose {
    public static class Service {
        private String image;
    }

    private Map<String, Service> services;
}

I would like to parse the services field in a List<Service> with the name in the field name in Service as following:

public class DockerCompose {
    public static class Service {
        private String name;
        private String image;
    }

    private List<Service> services;
}

Is this possible?

Body:
The easiest option is add custom setter for deserialization and getter for serialization.

public static class DockerCompose {

    public static class Service {
        @JsonIgnore // for serialization
        private String name;
        private String image;
    }

    @JsonProperty("services") // for derserialization
    public void setServicesMap(Map<String, Service> servicesMap){
        for (Map.Entry<String, Service> entry  :servicesMap.entrySet()) {
            entry.getValue().name = entry.getKey();
            services.add(entry.getValue());
        }
    }

    @JsonProperty("services") // for serialization
    public Map<String, Service> getServicesMap() {
        Map<String, Service> map = new HashMap<>();
        for(Service s: services)
            map.put(s.getName(), s);
        return map;
    }

    @JsonIgnore // for serialization
    private List<Service> services = new ArrayList<>();
}


问:
Can I use the Slack API to set the profile picture?
I am running a Slack team for a gaming community. My users all have avatars in the game and I am already using the Slack API to automatically set their Slack user name to their in-game name, so its easier for people to be recognized.

In addition I would also like to automatically set their profile picture in Slack with their avatar picture from the game. However I could not figure out a way to do it, so my question is can it be done and if yes, how?

My current starting point is the undocumented API method users.profile.set which allows me to set the profile of a user (see below for an example of a user profile). So far I've been able to modify:

first_name

last_name

title

phone

skype

The user profile also contains the URL to the profile picture, but I was so far not able to change it. I tried external URLs, and URLs of images already uploaded on Slack.

Here is a link to my documentation of the "undocumented" Slack API method users.profile.set with all options that I could figure out so far.

Any help would be hugely appreciated.

Update November 2017

In the meantime Slack has added a new API method called users.setPhoto for setting profile photos. However, this new method does not solve this question, because it only works for your own user (or more precisely the user you have an access token for, e.g. you not specify another user ID).

I am looking for a way to change the profile pictures of all users on my Slack team by a Slack app / bot.

Example of a user profile:

```<code>{
id: "U12345678",
team_id: "T12345678",
name: "erik.kalkoken",
deleted: false,
status: null,
color: "9f69e7",
real_name: "Erik Kalkoken",
tz: "America/Chicago",
tz_label: "Central Daylight Time",
tz_offset: 3600,
profile: {
avatar_hash: "XXX",
first_name: "Erik",
last_name: "Kalkoken",
title: "",
phone: "",
skype: "",
image_24: "https://avatars.slack-edge.com/2016-03-19/XXX_24.jpg",
image_32: "https://avatars.slack-edge.com/2016-03-19/XXX_32.jpg",
image_48: "https://avatars.slack-edge.com/2016-03-19/XXX_48.jpg",
image_72: "https://avatars.slack-edge.com/2016-03-19/XXX_72.jpg",
image_192: "https://avatars.slack-edge.com/2016-03-19/XXX_192.jpg",
image_512: "https://avatars.slack-edge.com/2016-03-19/XXX_512.jpg",
image_1024: "https://avatars.slack-edge.com/2016-03-19/XXX_512.jpg",
image_original: "https://avatars.slack-edge.com/2016-03-19/XXX_original.jpg",
real_name: "Erik Kalkoken",
real_name_normalized: "Erik Kalkoken",
email: "test@email.com"
},
is_admin: false,
is_owner: false,
is_primary_owner: false,
is_restricted: false,
is_ultra_restricted: false,
is_bot: false,
has_2fa: false
}
</code>```

答:
I was able to get it to work using Jay Querie's method.
The two difference was I gave the full path and I put the image first.
So in my case:

```<code>curl https://slack.com/api/users.setPhoto -F "image=@C:\Users\name\Pictures\dojocat.jpg" -F "token=xxxx-123-123-123-123"
</code>```

Originally when I was using gitbash to run the curl and it was searching for the image in the directory where my gitbash was installed / being executed. So if I put the dojocat.jpg next to my gitbash executable it would would have found it.

Body:
I am running a Slack team for a gaming community. My users all have avatars in the game and I am already using the Slack API to automatically set their Slack user name to their in-game name, so its easier for people to be recognized.

In addition I would also like to automatically set their profile picture in Slack with their avatar picture from the game. However I could not figure out a way to do it, so my question is can it be done and if yes, how?

My current starting point is the undocumented API method users.profile.set which allows me to set the profile of a user (see below for an example of a user profile). So far I've been able to modify:

first_name

last_name

title

phone

skype

The user profile also contains the URL to the profile picture, but I was so far not able to change it. I tried external URLs, and URLs of images already uploaded on Slack.

Here is a link to my documentation of the "undocumented" Slack API method users.profile.set with all options that I could figure out so far.

Any help would be hugely appreciated.

Update November 2017

In the meantime Slack has added a new API method called users.setPhoto for setting profile photos. However, this new method does not solve this question, because it only works for your own user (or more precisely the user you have an access token for, e.g. you not specify another user ID).

I am looking for a way to change the profile pictures of all users on my Slack team by a Slack app / bot.

Example of a user profile:

{
id: "U12345678",
team_id: "T12345678",
name: "erik.kalkoken",
deleted: false,
status: null,
color: "9f69e7",
real_name: "Erik Kalkoken",
tz: "America/Chicago",
tz_label: "Central Daylight Time",
tz_offset: 3600,
profile: {
avatar_hash: "XXX",
first_name: "Erik",
last_name: "Kalkoken",
title: "",
phone: "",
skype: "",
image_24: "https://avatars.slack-edge.com/2016-03-19/XXX_24.jpg",
image_32: "https://avatars.slack-edge.com/2016-03-19/XXX_32.jpg",
image_48: "https://avatars.slack-edge.com/2016-03-19/XXX_48.jpg",
image_72: "https://avatars.slack-edge.com/2016-03-19/XXX_72.jpg",
image_192: "https://avatars.slack-edge.com/2016-03-19/XXX_192.jpg",
image_512: "https://avatars.slack-edge.com/2016-03-19/XXX_512.jpg",
image_1024: "https://avatars.slack-edge.com/2016-03-19/XXX_512.jpg",
image_original: "https://avatars.slack-edge.com/2016-03-19/XXX_original.jpg",
real_name: "Erik Kalkoken",
real_name_normalized: "Erik Kalkoken",
email: "test@email.com"
},
is_admin: false,
is_owner: false,
is_primary_owner: false,
is_restricted: false,
is_ultra_restricted: false,
is_bot: false,
has_2fa: false
}

Body:
I was able to get it to work using Jay Querie's method.
The two difference was I gave the full path and I put the image first.
So in my case:

curl https://slack.com/api/users.setPhoto -F "image=@C:\Users\name\Pictures\dojocat.jpg" -F "token=xxxx-123-123-123-123"

Originally when I was using gitbash to run the curl and it was searching for the image in the directory where my gitbash was installed / being executed. So if I put the dojocat.jpg next to my gitbash executable it would would have found it.


问:
Getting the values of textboxes in Javascript
I have this html code:

```<code><table border="" cellpadding="3" cellspacing="0" id="mytable">

<tbody><tr><td>Song:</td> <td><input type="text" name="song" maxlength="64" size="48" /> </td></tr>
<tr><td>Artist:</td> <td><input type="text" name="artist" maxlength="16" size="48" /> </td></tr>
</code>```

How do I get the values of "song" and "artist"? I have tried:

```<code>var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);
</code>```

but I keep getting "undefined" even when there is text inside the textbox

答: First, td elements don't have a value attribute, so calling .value on them won't do a thing.  Second, the value is actually on the input element, so you need to do mytable.getElementsByTagName('input') instead.  Even better would be to give your input fields ids and then use getElementById.  This would mean you could alter your HTML without your JS breaking.

Body:
I have this html code:

Song:	 <input type="text" name="song" maxlength="64" size="48" />

Artist:	 <input type="text" name="artist" maxlength="16" size="48" />

How do I get the values of "song" and "artist"? I have tried:

var elTableCells = mytable.getElementsByTagName("td");
alert(elTableCells[2].value);
alert(elTableCells[4].value);

but I keep getting "undefined" even when there is text inside the textbox


问:
within docker run particular ubuntu
I want to use a docker with particular ubuntu version. I have my docker ubuntu images as:

```<code>ubuntu@ubuntu:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              dd6f76d9cc90        10 days ago         122MB
ubuntu              14.04               3aa18c7568fc        10 days ago         188MB
</code>```

Now I want to run a docker with ubuntu 14.04:

```<code>ubuntu@ubuntu:~$ docker run -it ubuntu:14.04
root@0b004c5dc55e:/# uname -a
Linux 0b004c5dc55e 4.10.0-38-generic #42~16.04.1-Ubuntu SMP Tue Oct 10 16:32:20 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
</code>```

When I check it with uname -a I see there is still Ubuntu-16.04.

How can I run exact version of ubuntu within docker?

答:
I think uname reports kernel version, which is shared between the container and the host, and your output is expected.

You might want to look at this link: https://unix.stackexchange.com/questions/343717/centos7-container-on-centos6-uname-command

Also you might want to consider 'cat /etc/system-release'

Title: within docker run particular ubuntu

Body:
I want to use a docker with particular ubuntu version. I have my docker ubuntu images as:

ubuntu@ubuntu:~$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
ubuntu              latest              dd6f76d9cc90        10 days ago         122MB
ubuntu              14.04               3aa18c7568fc        10 days ago         188MB

Now I want to run a docker with ubuntu 14.04:

ubuntu@ubuntu:~$ docker run -it ubuntu:14.04
root@0b004c5dc55e:/# uname -a
Linux 0b004c5dc55e 4.10.0-38-generic #42~16.04.1-Ubuntu SMP Tue Oct 10 16:32:20 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

When I check it with uname -a I see there is still Ubuntu-16.04.

How can I run exact version of ubuntu within docker?


问:
Is there anyway to have a linked list of dimension? like (x, y)?
I'm trying to see if I could have a java linked list of dimensions x, y ( not using hash map and not having x and y as two separate integers)
I'm trying to store each square of a grid in a linked list for example
(0, 1) (0, 2) ..</p>

答:
Yes you can store pairs of x, y in a LinkedList<Point> as follow:

```<code>List<Point> pointList = new LinkedList<>();
pointList.add(new Point(0, 1));
pointList.add(new Point(0, 2));
</code>```

Where Point is pre-defined in java.awt package. It has some useful methods such as public void move(int x, int y) or public void translate(int x, int y) which I think is useful for you.

Hope this helps.

Body:
Yes you can store pairs of x, y in a LinkedList<Point> as follow:

List<Point> pointList = new LinkedList<>();
pointList.add(new Point(0, 1));
pointList.add(new Point(0, 2));

Where Point is pre-defined in java.awt package. It has some useful methods such as public void move(int x, int y) or public void translate(int x, int y) which I think is useful for you.

Hope this helps.


问:
iphone equivalent to android intents for opening other apps
Is there a android intent like functionality available in iphone. Android uses intents to open other applications from the calling app to use functionality already implemented by other apps. i read somewhere that iphone has url schemes but couldnot find more info on this.

thanks.

答:
Try looking at the following answer, has a link to a wiki with most of the known supporting apps
List of iPhone Applications that support openURL:</p>

ContentLicense: CC BY-SA 2.5


问:
How to add a new Y scale in google chart
I've tried a lot of answers in stackoverflow posts, but I'm not able to add another Y scale in my google chart, can someone help me?

This is my current output:

and I need this output:

```<code>//here you can put data in javascript format
//String, int, int
var data = google.visualization.arrayToDataTable([
    ['Week', 'IE/Week',{ role: 'style' }, { role: 'annotation' }, { role: 'style' }, 'IE/Day', { role: 'style' }, { role: 'annotation' }],
    [ week1,  valuer1, '#5A9AD4', valuer1, '#000000', valueDay1, '#ED7D30', valueDay1],
    [ week2,  valuer2, '#5A9AD4', valuer2, '#000000', valueDay2, '#ED7D30', valueDay2],
    [ week3,  valuer3, '#5A9AD4', valuer3, '#000000', valueDay3, '#ED7D30', valueDay3],
    [ week4,  valuer4, '#5A9AD4', valuer4, '#000000', valueDay4, '#ED7D30', valueDay4],
    [ week5,  valuer5, '#5A9AD4', valuer5, '#000000', valueDay5, '#ED7D30', valueDay5]
]);

var options = {
        annotations: {
            textStyle: {
              fontSize: 16,
              bold: true,
              color: 'black'
            }
          },
  title : 'IE Trends Weekly and Daily',
  titleTextStyle: {color: 'black', fontName: 'Arial', fontSize: '18', fontWidth: 'normal'},
  vAxes: { 0: {logScale: false}, 1: {logScale: false}},
  vAxes: { 1: {logScale: false}, 2: {logScale: false}},
  series:{
      titleTextStyle: {color: 'black'},
      0:{targetAxisIndex:0},
      1:{targetAxisIndex:1}
  },
  pointSize:8,
  color: 'black',
  lineWidth: 2,
  hAxis: {title: ''},

  seriesType: 'bars',
  series: {0: {type: 'bar'}, 1: {type: 'line'}}
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
</code>```

答:
You were close. You defined the key "series" twice in options object, overriding the previously defined "targetAxisIndex". Try with the following options: jsfiddle</p>

```<code>//here you can put data in javascript format
//String, int, int
var data = google.visualization.arrayToDataTable([
    ['Week', 'IE/Week',{ role: 'style' }, { role: 'annotation' }, { role: 'style' }, 'IE/Day', { role: 'style' }, { role: 'annotation' }],
    [ week1,  valuer1, '#5A9AD4', valuer1, '#000000', valueDay1, '#ED7D30', valueDay1],
    [ week2,  valuer2, '#5A9AD4', valuer2, '#000000', valueDay2, '#ED7D30', valueDay2],
    [ week3,  valuer3, '#5A9AD4', valuer3, '#000000', valueDay3, '#ED7D30', valueDay3],
    [ week4,  valuer4, '#5A9AD4', valuer4, '#000000', valueDay4, '#ED7D30', valueDay4],
    [ week5,  valuer5, '#5A9AD4', valuer5, '#000000', valueDay5, '#ED7D30', valueDay5]
    ]);

var options = {
  annotations: {
    textStyle: {
      fontSize: 16,
      bold: true,
      color: 'black'
  }
},
title : 'IE Trends Weekly and Daily',
titleTextStyle: {color: 'black', fontName: 'Arial', fontSize: '18', fontWidth: 'normal'},
vAxes: { 0: {logScale: false}, 1: {logScale: false}},
vAxes: { 1: {logScale: false}, 2: {logScale: false}},
series:{
    titleTextStyle: {color: 'black'},
    0: { type: 'bar', targetAxisIndex:0},
    1: { type: 'line', targetAxisIndex:1}
},
pointSize:8,
color: 'black',
lineWidth: 2,
hAxis: {title: ''},

seriesType: 'bars'
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
</code>```

Body:
I've tried a lot of answers in stackoverflow posts, but I'm not able to add another Y scale in my google chart, can someone help me?

This is my current output:

and I need this output:

//here you can put data in javascript format
//String, int, int
var data = google.visualization.arrayToDataTable([
    ['Week', 'IE/Week',{ role: 'style' }, { role: 'annotation' }, { role: 'style' }, 'IE/Day', { role: 'style' }, { role: 'annotation' }],
    [ week1,  valuer1, '#5A9AD4', valuer1, '#000000', valueDay1, '#ED7D30', valueDay1],
    [ week2,  valuer2, '#5A9AD4', valuer2, '#000000', valueDay2, '#ED7D30', valueDay2],
    [ week3,  valuer3, '#5A9AD4', valuer3, '#000000', valueDay3, '#ED7D30', valueDay3],
    [ week4,  valuer4, '#5A9AD4', valuer4, '#000000', valueDay4, '#ED7D30', valueDay4],
    [ week5,  valuer5, '#5A9AD4', valuer5, '#000000', valueDay5, '#ED7D30', valueDay5]
]);

var options = {
        annotations: {
            textStyle: {
              fontSize: 16,
              bold: true,
              color: 'black'
            }
          },
  title : 'IE Trends Weekly and Daily',
  titleTextStyle: {color: 'black', fontName: 'Arial', fontSize: '18', fontWidth: 'normal'},
  vAxes: { 0: {logScale: false}, 1: {logScale: false}},
  vAxes: { 1: {logScale: false}, 2: {logScale: false}},
  series:{
      titleTextStyle: {color: 'black'},
      0:{targetAxisIndex:0},
      1:{targetAxisIndex:1}
  },
  pointSize:8,
  color: 'black',
  lineWidth: 2,
  hAxis: {title: ''},

  seriesType: 'bars',
  series: {0: {type: 'bar'}, 1: {type: 'line'}}
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);

Body:
You were close. You defined the key "series" twice in options object, overriding the previously defined "targetAxisIndex". Try with the following options: jsfiddle

//here you can put data in javascript format
//String, int, int
var data = google.visualization.arrayToDataTable([
    ['Week', 'IE/Week',{ role: 'style' }, { role: 'annotation' }, { role: 'style' }, 'IE/Day', { role: 'style' }, { role: 'annotation' }],
    [ week1,  valuer1, '#5A9AD4', valuer1, '#000000', valueDay1, '#ED7D30', valueDay1],
    [ week2,  valuer2, '#5A9AD4', valuer2, '#000000', valueDay2, '#ED7D30', valueDay2],
    [ week3,  valuer3, '#5A9AD4', valuer3, '#000000', valueDay3, '#ED7D30', valueDay3],
    [ week4,  valuer4, '#5A9AD4', valuer4, '#000000', valueDay4, '#ED7D30', valueDay4],
    [ week5,  valuer5, '#5A9AD4', valuer5, '#000000', valueDay5, '#ED7D30', valueDay5]
    ]);

var options = {
  annotations: {
    textStyle: {
      fontSize: 16,
      bold: true,
      color: 'black'
  }
},
title : 'IE Trends Weekly and Daily',
titleTextStyle: {color: 'black', fontName: 'Arial', fontSize: '18', fontWidth: 'normal'},
vAxes: { 0: {logScale: false}, 1: {logScale: false}},
vAxes: { 1: {logScale: false}, 2: {logScale: false}},
series:{
    titleTextStyle: {color: 'black'},
    0: { type: 'bar', targetAxisIndex:0},
    1: { type: 'line', targetAxisIndex:1}
},
pointSize:8,
color: 'black',
lineWidth: 2,
hAxis: {title: ''},

seriesType: 'bars'
};

var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);


问:
WP plugin commit issue:- svn: E175013: Access to ‘/!svn/me’ forbidden
I did svn checkout plugin code from https://plugins.svn.wordpress.org/my-plugin, made changes in a file and then when I give svn ci -m ‘changes description’ it asks for user name and password. When I give the username and password, I get the following error message:

```<code>svn: E175013: Commit failed (details follow):
svn: E175013: Access to ‘/!svn/me’ forbidden
</code>```

I have checked the URL, username and password and all are correct.

What can I try to resolve this?

答:
Do you have TortoiseSVN installed by any chance? Are you able to view the repository via Repo Browse?

Try using http:// instead of https://

If it's not the username or password, it's usually the URL that's the issue. I'm tempted to say it's the http: protocol instead of https: just based on general observation of what I'm seeing in Google Chrome when trying to view that URL from https: (says that URL doesn't exist on their server).

ContentLicense: CC BY-SA 4.0

Body:
I did svn checkout plugin code from https://plugins.svn.wordpress.org/my-plugin, made changes in a file and then when I give svn ci -m ‘changes description’ it asks for user name and password. When I give the username and password, I get the following error message:

svn: E175013: Commit failed (details follow):
svn: E175013: Access to ‘/!svn/me’ forbidden

I have checked the URL, username and password and all are correct.

What can I try to resolve this?


问:
C++ : prim() in an "if statement"
While studying the C++ programming language by B. Stroustrup, it has been mentioned the existence of the prim() functions which reduces the scope of the declared variable to one single block.

This is an example provided by the book:

```<code>if (double d = prim(true)) {
        left /= d;      break;
}
</code>```

Despite understanding its interest, I cannot figure out how to use it: is it part of a certain library ? Of must I precise the standard because Visual Studio isn't able to recognise the function.

Thanks in advance

答: There is no prim() function in the standard library. It is a user defined function used to demonstrate that the condition in the if statement can be a declaration. The function itself is defined in Section 10.2.1 on page no. 245.

Title: C++ : prim() in an "if statement"

Body:
While studying the C++ programming language by B. Stroustrup, it has been mentioned the existence of the prim() functions which reduces the scope of the declared variable to one single block.

This is an example provided by the book:

if (double d = prim(true)) {
        left /= d;      break;
}

Despite understanding its interest, I cannot figure out how to use it: is it part of a certain library ? Of must I precise the standard because Visual Studio isn't able to recognise the function.

Thanks in advance


问:
Webrtc static library on iOS
I am looking for a way to include Webrtc in my iOS project. My project consists some C code which I am looking for a way to call the Webrtc apis from. I am able to do this in Android using a Makefile and linking the webrtc library. However, I haven't been able to do it on iOS. I tried to build a webrtc.framework but I am not sure how to link it to my C code. Any idea?</p>

答: The WebRTC.framework that gets created by the build script has Objective-C header files. You cannot call Objective-C methods in a C source code (.c) file. You'll need to consume it in an Objective-C (.m) file or Objective C++ (.mm) file.</p>

Title: Webrtc static library on iOS


问:
NSNumber for MPMediaItemPropertyPersistentID to NSString and back again
I'm looping through all the songs from an iPhone's music library using the following code:

```<code>NSArray * songs = [[NSArray alloc] initWithArray:[[MPMediaQuery songsQuery] collections]];

for (MPMediaItemCollection * item in songs){

    NSString * persistentID = [[[item representativeItem] valueForProperty:MPMediaItemPropertyPersistentID] stringValue];
    // Do something with it.
}

[songs release];
</code>```

Pretty basic stuff.

I'm getting the PersistentID as an NSString because I need to write it to an XML file (for transmission over a network to another device). Hence the reason I can't just leave it as an NSNumber.

The other device will then ask for the iPhone to play a track by transmitting the PersistentID back again.

At this point, the iPhone has an NSString of the PersistentID of the track it should play.

It would be combersome to loop through every song again and compare PersistentIDs until I find the track I want, so I'm trying to use the MPMediaPropertyPredicate to have the iPhone search for me.

I'm using the following code for the search:

```<code>MPMediaPropertyPredicate * predicate = [MPMediaPropertyPredicate predicateWithValue:persistentID forProperty:MPMediaItemPropertyPersistentID];

MPMediaQuery * songsQuery = [[MPMediaQuery alloc] init];
[songsQuery addFilterPredicate:predicate];

if ([[songsQuery items] count]){

    MPMediaItem * item = [[songsQuery items] objectAtIndex:0];
    // Play item.
}

[songsQuery release];
</code>```

Where persistentID is the NSString from earlier.

Weirdly, this works for some songs, not for others. i.e, sometimes the items array is not empty, even though I'm passing an NSString, not an NSNumber.

I'm wondering if there's a way to convert my NSString back to the NSNumber it came from, and how I can do that.

UPDATE: I've tried the NSNumberFormatter, I've also tried something like:

```<code>[NSNumber numberWithFloat:[persID floatValue]];
</code>```

I've tried all the standard ways of doing it without prevail.

答:
This is working pretty well, no problems so far:

```<code>unsigned long long ullvalue = strtoull([persistentID UTF8String], NULL, 0);
NSNumber * numberID = [[NSNumber alloc] initWithUnsignedLongLong:ullvalue];

MPMediaPropertyPredicate * predicate = [MPMediaPropertyPredicate predicateWithValue:numberID forProperty:MPMediaItemPropertyPersistentID];
[numberID release];

// And so on.
</code>```

Hope this helps anyone else who ran into this problem.

Body:
I'm looping through all the songs from an iPhone's music library using the following code:

NSArray * songs = [[NSArray alloc] initWithArray:[[MPMediaQuery songsQuery] collections]];

for (MPMediaItemCollection * item in songs){

    NSString * persistentID = [[[item representativeItem] valueForProperty:MPMediaItemPropertyPersistentID] stringValue];
    // Do something with it.
}

[songs release];

Pretty basic stuff.

I'm getting the PersistentID as an NSString because I need to write it to an XML file (for transmission over a network to another device). Hence the reason I can't just leave it as an NSNumber.

The other device will then ask for the iPhone to play a track by transmitting the PersistentID back again.

At this point, the iPhone has an NSString of the PersistentID of the track it should play.

It would be combersome to loop through every song again and compare PersistentIDs until I find the track I want, so I'm trying to use the MPMediaPropertyPredicate to have the iPhone search for me.

I'm using the following code for the search:

MPMediaPropertyPredicate * predicate = [MPMediaPropertyPredicate predicateWithValue:persistentID forProperty:MPMediaItemPropertyPersistentID];

MPMediaQuery * songsQuery = [[MPMediaQuery alloc] init];
[songsQuery addFilterPredicate:predicate];

if ([[songsQuery items] count]){

    MPMediaItem * item = [[songsQuery items] objectAtIndex:0];
    // Play item.
}

[songsQuery release];

Where persistentID is the NSString from earlier.

Weirdly, this works for some songs, not for others. i.e, sometimes the items array is not empty, even though I'm passing an NSString, not an NSNumber.

I'm wondering if there's a way to convert my NSString back to the NSNumber it came from, and how I can do that.

UPDATE: I've tried the NSNumberFormatter, I've also tried something like:

[NSNumber numberWithFloat:[persID floatValue]];

I've tried all the standard ways of doing it without prevail.

Body:
This is working pretty well, no problems so far:

unsigned long long ullvalue = strtoull([persistentID UTF8String], NULL, 0);
NSNumber * numberID = [[NSNumber alloc] initWithUnsignedLongLong:ullvalue];

MPMediaPropertyPredicate * predicate = [MPMediaPropertyPredicate predicateWithValue:numberID forProperty:MPMediaItemPropertyPersistentID];
[numberID release];

// And so on.

Hope this helps anyone else who ran into this problem.


问:
Is it possible to have Travis-ci trigger another repository's build?
I am trying to wrap my head around Travis-ci scripts but I am trying to figure out if what I want is even possible:

Repo #1:
 - my app to be built via travis-ci

Repo #2:
 - contains selenium/nightwatch tests that should run once repo #1 is finished building

So this is the workflow I am aiming for:

a PR in Repo #1 gets merged

Travis-ci builds Repo #1 and completes successfully & deploys

Travis-ci tells Repo #2 to start building

Repo #2 installs the repo which triggers browserstack to begin running the selenium tests

Is this at all possible? I've been researching this for a few days and couldn't find a way to trigger a separate repo to build.

Any help is appreciated.

Thanks!

答:
Possible Duplicate of: Triggering builds of dependent projects in Travis CI

Nevertheless, pasting the answer here: Yes, it is possible to trigger another Travis job after a first one succeeds. You can use the trigger-travis.sh script that is part of the plume-lib library.

The script's documentation tells how to use it -- set an environment variable and add three lines to your .travis.yml file.

You can setup repo#1 and repo#2 using different jobs and use the above approach to trigger downstream job after successfully deployment has completed using job 1


问:
Optimize table in MariaDB for large ibd file
We have a WordPress website using MariaDB where a wp_options table keeps growing due to a rogue plugin writing thousands of records to the table. The issue has not been resolved by the plugin maintainer yet and I keep having to remove these 'transient' (temp) records manually via DELETE statement. The problem is the ibd file keeps growing and now 35GB in size. Once this is resolved, I plan to do an OPTIMIZE TABLE on the table to cleanup. Is that the best approach to reclaim all that space? I assume I'll need as much as 40GB free space to do this and how long should the OPTIMIZE TABLE take? Since this table is used quite a bit by WordPress, it seems it will be best to take the website offline while optimizing to avoid locks. I'll looking for the quickest way to resolve.

At least I think these rogue records are the cause of the table growing. Below is a list of the top 10 type of entries in the table:

```<code>MariaDB [wmnf_www]> SELECT    substr(`wp_options`.`option_name`, 1, 18) AS `option_name`,   count(`wp_options`.`option_value`) AS `cnt` FROM   `wp_options` GROUP BY   substr(`wp_options`.`option_name`, 1, 18) ORDER BY   `cnt` DESC LIMIT 10;
+--------------------+-------+
| option_name        | cnt   |
+--------------------+-------+
| _transient_timeout | 21186 |
| _transient_ee_ssn_ | 12628 |
| _transient_jpp_li_ |   222 |
| _transient_externa |   125 |
| _transient_wc_rela |    63 |
| jpsq_sync-14716436 |    50 |
| wpmf_current_folde |    35 |
| _wc_session_expire |    34 |
| jpsq_sync-14716465 |    29 |
| jpsq_sync-14716417 |    25 |
+--------------------+-------+
10 rows in set (0.17 sec)
</code>```

The _transient_ee_ssn_ and _transient_timeout_ee_ are the issue and keep growing, the only ones in the set above that has grown since last night and was initially found with 800K records. I keep removing the records as the plugin maintainer said was safe. But is this the cause of the ibd file growing?

---UPDATE---
Oddly enough, the issue is not resolved and transient records keep getting generated by the thousands, but this ibd index file has stopped growing for the moment. After steadily growing over the weekend from 20GB to now 39GB, it has not grown in a couple of hours. Perhaps there's a limit or this file was growing for other reasons?

答: I think it would be a better solution to recreate the table using Percona pt-online-schema-change tool. This will recreate the table and move all the data to the new table then drop the old table. This will avoid locking the database for a long time.</p>

Body:
We have a WordPress website using MariaDB where a wp_options table keeps growing due to a rogue plugin writing thousands of records to the table. The issue has not been resolved by the plugin maintainer yet and I keep having to remove these 'transient' (temp) records manually via DELETE statement. The problem is the ibd file keeps growing and now 35GB in size. Once this is resolved, I plan to do an OPTIMIZE TABLE on the table to cleanup. Is that the best approach to reclaim all that space? I assume I'll need as much as 40GB free space to do this and how long should the OPTIMIZE TABLE take? Since this table is used quite a bit by WordPress, it seems it will be best to take the website offline while optimizing to avoid locks. I'll looking for the quickest way to resolve.

At least I think these rogue records are the cause of the table growing. Below is a list of the top 10 type of entries in the table:

MariaDB [wmnf_www]> SELECT    substr(`wp_options`.`option_name`, 1, 18) AS `option_name`,   count(`wp_options`.`option_value`) AS `cnt` FROM   `wp_options` GROUP BY   substr(`wp_options`.`option_name`, 1, 18) ORDER BY   `cnt` DESC LIMIT 10;
+--------------------+-------+
| option_name        | cnt   |
+--------------------+-------+
| _transient_timeout | 21186 |
| _transient_ee_ssn_ | 12628 |
| _transient_jpp_li_ |   222 |
| _transient_externa |   125 |
| _transient_wc_rela |    63 |
| jpsq_sync-14716436 |    50 |
| wpmf_current_folde |    35 |
| _wc_session_expire |    34 |
| jpsq_sync-14716465 |    29 |
| jpsq_sync-14716417 |    25 |
+--------------------+-------+
10 rows in set (0.17 sec)

The _transient_ee_ssn_ and _transient_timeout_ee_ are the issue and keep growing, the only ones in the set above that has grown since last night and was initially found with 800K records. I keep removing the records as the plugin maintainer said was safe. But is this the cause of the ibd file growing?

---UPDATE---
Oddly enough, the issue is not resolved and transient records keep getting generated by the thousands, but this ibd index file has stopped growing for the moment. After steadily growing over the weekend from 20GB to now 39GB, it has not grown in a couple of hours. Perhaps there's a limit or this file was growing for other reasons?


问:
How to filter for multiple criteria in Tableau via Drop Down?
Let's imagine there was the following dataset (arbitrary example):

Mary, female, plays instrument, lives in New York

John, male, plays no instrument, lives in Boston

Dave, male, plays no instrument, lives in Los Angeles

I'd like to create a drop down with the following options:

Segment A

Segment B

When selecting segment A, data should be filtered for those who are female and play an instrument (i.e., highlight New York on a map). When selecting segment B, data should be filtered for those who are male and play no instrument (i.e., highlight Boston and Los Angeles on a map).

How could that be implemented with Tableau?

答:
You can create a calculated field, that has a value based on the logic you need, e.g.

IF [Gender] = 'female' AND [Instrument] = 'plays instrument' then 'Segment1' else 'Segment2' END

and then use this field as a filter.


问:
Why shouldn't you use import all in ES6
So I recently started learning react and noticed that all the documentation has imports that look like else:

```<code>import { Apples, Bananas, Oranges } from 'fruits';
</code>```

But while studying react I found that this syntax works just as well:

```<code>import * as Fruits from 'fruits';
</code>```

My Question: Is there any performance loss or logical conflict with using the import all syntax?

If there is not then I will just keep using that syntax. I would rather be a little more verbose and not have to worry about making sure everything has been imported.

答:
Actually - it depends on the amount of exports from given module.

If you import e.g. Lodash you might not want to import whole library, you should import only these methods which you are going to use in your application:

import { isEmpty, pickBy, orderBy } from 'lodash';

to avoid performance loss and memory waste.

However, if your given module holds just a few methods or basically you are going to use every single export, then you can freely use that shortcut:

import * as Fruits from 'fruits';

Note: I suppose you are using webpack 2, which actually includes three-shaking algorithm which makes minifying the bundle possible.

Title: Why shouldn't you use import all in ES6

Body:
So I recently started learning react and noticed that all the documentation has imports that look like else:

import { Apples, Bananas, Oranges } from 'fruits';

But while studying react I found that this syntax works just as well:

import * as Fruits from 'fruits';

My Question: Is there any performance loss or logical conflict with using the import all syntax?

If there is not then I will just keep using that syntax. I would rather be a little more verbose and not have to worry about making sure everything has been imported.


问:
dropdown not updating from Knockout array
I am updating my Knockout object in Knockout and am verifying via the console that it is getting updated correctly.  But the dropdown is not getting refreshed with the new value.  If I refresh the page manually, the dropdown will be updated.  I think I need to make something observable, but not totally sure.

This is my KO viewmodel:

```<code>var SellerViewModel = function(groups) {
        var self = this;

        self.json = groups;
        self.groups = ko.computed(function() {
            var opts = [];
            for(var key in self.json)
            {
                if(self.json.hasOwnProperty(key))
                {
                    opts.push({Text: self.json[key].majorGroup + " / " + self.json[key].minorGroup, Value: self.json[key].groupId});
                }
            }
            return opts;
        });

        self.addGroup = function(json) {
            var group = JSON.parse(json);
            self.json.push(
                {
                    "ExtensionData":{},
                    "contractId":"10006",
                    "groupId":group.groupID,
                    "imageId":null,
                    "majorGroup":group.majorGroup,
                    "minorGroup":group.minorGroup
                }
            );
            console.log(JSON.stringify(self.json));
        };
</code>```

And my HTML dropdown:

```<code><select data-bind="value: roomID, options: $root.groups, optionsValue: 'Value', optionsText: 'Text', optionsCaption: ' -- select a room --', disable: disableRoom" class="form-control" id="@roomID"></select>
</code>```

And finally, this is how the dropdown gets populated on pageload:

```<code>var groups = @Html.Raw( Json.Encode(ViewBag.GroupDetail.SellerGroup) );
sellerViewModel = new SellerViewModel(groups);
</code>```

Forgot to add one last snippet.  This is how I am adding an additional item into the knockout object, which is supposed to update the dropdown.

```<code>var json = '{"majorGroup" : "' + major + '", "minorGroup" : "' + minor + '", "groupID" : "' + groupID + '" }';
sellerViewModel.addGroup(json);
</code>```

My guess is that self.groups needs to be an observable array.  But I don't know how to do that because I set it equal to ko.computed already.

答:
This is a simple problem, with a simpler solution.

self.json = ko.observableArray(groups);

In order for your computed to fire, it needs to register a "subscription". Right now, you have it tied to just a normal JavaScript variable (by the look of the push() I'm guessing it's an array).

Making self.json an observable array will create this subscription for you.

Body:
I am updating my Knockout object in Knockout and am verifying via the console that it is getting updated correctly.  But the dropdown is not getting refreshed with the new value.  If I refresh the page manually, the dropdown will be updated.  I think I need to make something observable, but not totally sure.

This is my KO viewmodel:

var SellerViewModel = function(groups) {
        var self = this;

        self.json = groups;
        self.groups = ko.computed(function() {
            var opts = [];
            for(var key in self.json)
            {
                if(self.json.hasOwnProperty(key))
                {
                    opts.push({Text: self.json[key].majorGroup + " / " + self.json[key].minorGroup, Value: self.json[key].groupId});
                }
            }
            return opts;
        });

        self.addGroup = function(json) {
            var group = JSON.parse(json);
            self.json.push(
                {
                    "ExtensionData":{},
                    "contractId":"10006",
                    "groupId":group.groupID,
                    "imageId":null,
                    "majorGroup":group.majorGroup,
                    "minorGroup":group.minorGroup
                }
            );
            console.log(JSON.stringify(self.json));
        };

And my HTML dropdown:

<select data-bind="value: roomID, options: $root.groups, optionsValue: 'Value', optionsText: 'Text', optionsCaption: ' -- select a room --', disable: disableRoom" class="form-control" id="@roomID"></select>

And finally, this is how the dropdown gets populated on pageload:

var groups = @Html.Raw( Json.Encode(ViewBag.GroupDetail.SellerGroup) );
sellerViewModel = new SellerViewModel(groups);

Forgot to add one last snippet.  This is how I am adding an additional item into the knockout object, which is supposed to update the dropdown.

var json = '{"majorGroup" : "' + major + '", "minorGroup" : "' + minor + '", "groupID" : "' + groupID + '" }';
sellerViewModel.addGroup(json);

My guess is that self.groups needs to be an observable array.  But I don't know how to do that because I set it equal to ko.computed already.


问:
Match all from beginning to /aaa-bbb-ccc/, excluding /aaa-bbb-ccc/
Consider the following string:

```<code>tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl
</code>```

I have a bunch of strings that have /aaa-bbb-ccc/ in them. I would like to remove any characters that occur before /aaa-bbb-ccc/. The final product of the above, for example, should be /aaa-bbb-ccc/def/ghi/jkl.

My attempt, after some searching:

```<code>x <- "tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl"
sub("^.*[^/aaa-bbb-ccc/]", "", x)
[1] ""
</code>```

答:
You need to use lazy dot matching and wrap the known value with a capturing group to restore with a backreference later:

```<code>x <- "tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl"
sub(".*?(/aaa-bbb-ccc/)", "\\1", x)
## [1] "/aaa-bbb-ccc/def/ghi/jkl"
</code>```

See this R demo.

See regex demo, .*? matches any 0+ chars, as few as possible, and (/aaa-bbb-ccc/) is a capturing group with ID=1 that is reference to with \1 from the replacement pattern.

Note you may also extract that part using regmatches/regexpr:

```<code>x <- "tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl"
regmatches(x, regexpr("/aaa-bbb-ccc/.*", x))
</code>```

See this R demo. .* just grabs any 0+ chars up to the end of the whole character vector.

Body:
Consider the following string:

tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl

I have a bunch of strings that have /aaa-bbb-ccc/ in them. I would like to remove any characters that occur before /aaa-bbb-ccc/. The final product of the above, for example, should be /aaa-bbb-ccc/def/ghi/jkl.

My attempt, after some searching:

x <- "tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl"
sub("^.*[^/aaa-bbb-ccc/]", "", x)
[1] ""

Body:
You need to use lazy dot matching and wrap the known value with a capturing group to restore with a backreference later:

x <- "tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl"
sub(".*?(/aaa-bbb-ccc/)", "\\1", x)
## [1] "/aaa-bbb-ccc/def/ghi/jkl"

See this R demo.

See regex demo, .*? matches any 0+ chars, as few as possible, and (/aaa-bbb-ccc/) is a capturing group with ID=1 that is reference to with \1 from the replacement pattern.

Note you may also extract that part using regmatches/regexpr:

x <- "tempo/blah/blah/aaa-bbb-ccc/def/ghi/jkl"
regmatches(x, regexpr("/aaa-bbb-ccc/.*", x))

See this R demo. .* just grabs any 0+ chars up to the end of the whole character vector.


问:
NPE on plugin.getConfig().set(... , ...);
I've a bug on my Spigot Plugin, a null pointer is return when i try to do /samrandom true/false. This is my code :
Main class:

```<code>package com.vandendaelen.simpleautomessage;

import java.io.File;
import java.util.List;
import java.util.Random;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;

import com.vandendaelen.simpleautomessage.Commands.CommandSamRandom;
import com.vandendaelen.simpleautomessage.Commands.CommandSamTime;

public class SimpleAutoMessage extends JavaPlugin {
    public static final String RANDOM_CONFIG ="Random enabled";
    private int iMessages = 0;

    @Override
    public void onDisable() {
        // TODO Auto-generated method stub
        super.onDisable();
    }

    @Override
    public void onEnable() {
        System.out.println("Waw, an amazing plugin powered by LotuxPunk ! :-)");
        this.getCommand("samtime").setExecutor(new CommandSamTime(this));
        this.getCommand("samrandom").setExecutor(new CommandSamRandom(this, RANDOM_CONFIG));
        createConfig();

        this.getConfig().addDefault(RANDOM_CONFIG, false);
        this.getConfig().options().copyDefaults(true);
        saveConfig();

        //Enable display of messages
        if(getConfig().getBoolean("Enable")) {
            if(getConfig().getBoolean(RANDOM_CONFIG)) {
                messageRandomDisplayer();
            } else {
                messageDisplayer();
            }
        }

    }

    private void createConfig() {
        try {
            if (!getDataFolder().exists()) {
                getDataFolder().mkdirs();
            }
            File file = new File(getDataFolder(), "config.yml");
            if (!file.exists()) {
                getLogger().info("Config.yml not found, creating!");
                saveDefaultConfig();
            } else {
                getLogger().info("Config.yml found, loading!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    ...

}
</code>```

Command class :

```<code>package com.vandendaelen.simpleautomessage.Commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

public class CommandSamRandom implements CommandExecutor {

    private String RANDOM_CONFIG;
    private Plugin plugin;

    public CommandSamRandom(Plugin pl, String r) {
        pl = plugin;
        RANDOM_CONFIG = r;
        //System.out.println(plugin.getConfig().getBoolean(RANDOM_CONFIG));
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player p = (Player)sender;
        if(args[0]!="") {
            Boolean randomEnabled = Boolean.parseBoolean(args[0]);
            if(p.hasPermission("simpleautomessage.setrandom")||p.isOp()) {
                plugin.getConfig().set(RANDOM_CONFIG, randomEnabled);

                if(randomEnabled) {
                    p.sendMessage("§2Random enabled");
                } else {
                    p.sendMessage("§4Random disabled");
                }
                plugin.saveConfig();
                plugin.reloadConfig();
                return true;
            }
        }

        return false;
    }

}
</code>```

Config file :

```<code>#Time between 2 messages (minutes)
Time: 15
#Auto-Messages !
Enable: true

#Broadcast randomly your messages
Random enabled: false

Messages:
  - "A simple string"
  - "Another string"
  - "Don't forget to support/rate LotuxPunk on Curse/Bukkit website !"
</code>```

Result :

```<code>[20:56:05 INFO]: LotuxPunk issued server command: /samrandom true
[20:56:05 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'samrandom' in plugin SimpleAutoMessage v0.5
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
        ...
Caused by: java.lang.NullPointerException
        at com.vandendaelen.simpleautomessage.Commands.CommandSamRandom.onCommand(CommandSamRandom.java:26) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
        ... 15 more
</code>```

Anyone can help me please ? :)

The line 26 is

```<code>plugin.getConfig().set(RANDOM_CONFIG, randomEnabled);
</code>```

答:
Your problem is in the Constructor:

```<code>private Plugin plugin;

public CommandSamRandom(Plugin pl, String r) {
    pl = plugin;
}
</code>```

You assign the value of your not yet initialized field pluginto the parameter pl insterad of the other way round.
It helps to explicitly use this.plugin when you try to access an instance field to make this more obvious.

Body:
I've a bug on my Spigot Plugin, a null pointer is return when i try to do /samrandom true/false. This is my code :
Main class:

package com.vandendaelen.simpleautomessage;

import java.io.File;
import java.util.List;
import java.util.Random;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;

import com.vandendaelen.simpleautomessage.Commands.CommandSamRandom;
import com.vandendaelen.simpleautomessage.Commands.CommandSamTime;

public class SimpleAutoMessage extends JavaPlugin {
    public static final String RANDOM_CONFIG ="Random enabled";
    private int iMessages = 0;

    @Override
    public void onDisable() {
        // TODO Auto-generated method stub
        super.onDisable();
    }

    @Override
    public void onEnable() {
        System.out.println("Waw, an amazing plugin powered by LotuxPunk ! :-)");
        this.getCommand("samtime").setExecutor(new CommandSamTime(this));
        this.getCommand("samrandom").setExecutor(new CommandSamRandom(this, RANDOM_CONFIG));
        createConfig();

        this.getConfig().addDefault(RANDOM_CONFIG, false);
        this.getConfig().options().copyDefaults(true);
        saveConfig();

        //Enable display of messages
        if(getConfig().getBoolean("Enable")) {
            if(getConfig().getBoolean(RANDOM_CONFIG)) {
                messageRandomDisplayer();
            } else {
                messageDisplayer();
            }
        }

    }

    private void createConfig() {
        try {
            if (!getDataFolder().exists()) {
                getDataFolder().mkdirs();
            }
            File file = new File(getDataFolder(), "config.yml");
            if (!file.exists()) {
                getLogger().info("Config.yml not found, creating!");
                saveDefaultConfig();
            } else {
                getLogger().info("Config.yml found, loading!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    ...

}

Command class :

package com.vandendaelen.simpleautomessage.Commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

public class CommandSamRandom implements CommandExecutor {

    private String RANDOM_CONFIG;
    private Plugin plugin;

    public CommandSamRandom(Plugin pl, String r) {
        pl = plugin;
        RANDOM_CONFIG = r;
        //System.out.println(plugin.getConfig().getBoolean(RANDOM_CONFIG));
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player p = (Player)sender;
        if(args[0]!="") {
            Boolean randomEnabled = Boolean.parseBoolean(args[0]);
            if(p.hasPermission("simpleautomessage.setrandom")||p.isOp()) {
                plugin.getConfig().set(RANDOM_CONFIG, randomEnabled);

                if(randomEnabled) {
                    p.sendMessage("§2Random enabled");
                } else {
                    p.sendMessage("§4Random disabled");
                }
                plugin.saveConfig();
                plugin.reloadConfig();
                return true;
            }
        }

        return false;
    }

}

Config file :

#Time between 2 messages (minutes)
Time: 15
#Auto-Messages !
Enable: true

#Broadcast randomly your messages
Random enabled: false

Messages:
  - "A simple string"
  - "Another string"
  - "Don't forget to support/rate LotuxPunk on Curse/Bukkit website !"

Result :

[20:56:05 INFO]: LotuxPunk issued server command: /samrandom true
[20:56:05 ERROR]: null
org.bukkit.command.CommandException: Unhandled exception executing command 'samrandom' in plugin SimpleAutoMessage v0.5
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:141) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
        ...
Caused by: java.lang.NullPointerException
        at com.vandendaelen.simpleautomessage.Commands.CommandSamRandom.onCommand(CommandSamRandom.java:26) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[spigot.jar:git-Spigot-d21162c-61e0c69]
        ... 15 more

Anyone can help me please ? :)

The line 26 is

plugin.getConfig().set(RANDOM_CONFIG, randomEnabled);

Body:
Your problem is in the Constructor:

private Plugin plugin;

public CommandSamRandom(Plugin pl, String r) {
    pl = plugin;
}

You assign the value of your not yet initialized field pluginto the parameter pl insterad of the other way round.
It helps to explicitly use this.plugin when you try to access an instance field to make this more obvious.


问:
CSS3 Keyframe Animation on page load only?
What I have here is a profile button that animates in, and performs a different animation on hover. However the entrance animation repeats when my mouse leaves the element. Is there a way to make sure that an animation is only triggered once per page load?</p>

```<code>.profile {
width: 125px;
height: 125px;
background-image: url(graphics/profile1.jpg);
border-style: solid;
border-color: white;
border-radius: 50%;
margin-left: 80px;
outline: 1px solid transparent;
float: left;
animation: popIn 1s;
}

.profile:hover{
width: 125px;
height: 125px;
border-style: solid;
border-color: red;
box-shadow: 0 0 0 0 rgba(155, 0, 2, 0.6);
border-radius: 50%;
-webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}

@keyframes popIn{
0% {
transform: scale(0.1);
opacity: 0;
}
60% {
transform: scale(1.2);
opacity: 1;
}
100% {
transform: scale(1);
}
}

@-webkit-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-moz-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-ms-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
</code>```

答:
Here is a link to a similar question that might help you out.

Run CSS3 animation only once (at page loading)

Personally I would add an extra class to the div that handles all the entrance animations and then use javascript to remove that class once the cursor moves inside the div. I'll make a js fiddle and show you an example, just give me a few minutes.

Edit for fiddle link: https://jsfiddle.net/0uaktv10/

html:

```<code><div class="profile load-in" style="background: blue; width: 100px; height: 100px;"></div>
</code>```

Css:

```<code>    enter .profile {
width: 125px;
height: 125px;
background-image: url(graphics/profile1.jpg);
border-style: solid;
border-color: white;
border-radius: 50%;
margin-left: 80px;
outline: 1px solid transparent;
float: left;
}

.load-in {
  animation: popIn 1s;
}

.profile:hover{
width: 125px;
height: 125px;
border-style: solid;
border-color: red;
box-shadow: 0 0 0 0 rgba(155, 0, 2, 0.6);
border-radius: 50%;
-webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}
@keyframes popIn{
0% {
transform: scale(0.1);
opacity: 0;
}
60% {
transform: scale(1.2);
opacity: 1;
}
100% {
transform: scale(1);
}
}

@-webkit-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-moz-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-ms-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
</code>```

jQuery:

```<code>$(".profile").hover(function(){
    $(".profile").removeClass("load-in")
})
</code>```

Body:
What I have here is a profile button that animates in, and performs a different animation on hover. However the entrance animation repeats when my mouse leaves the element. Is there a way to make sure that an animation is only triggered once per page load?

.profile {
width: 125px;
height: 125px;
background-image: url(graphics/profile1.jpg);
border-style: solid;
border-color: white;
border-radius: 50%;
margin-left: 80px;
outline: 1px solid transparent;
float: left;
animation: popIn 1s;
}

.profile:hover{
width: 125px;
height: 125px;
border-style: solid;
border-color: red;
box-shadow: 0 0 0 0 rgba(155, 0, 2, 0.6);
border-radius: 50%;
-webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}

@keyframes popIn{
0% {
transform: scale(0.1);
opacity: 0;
}
60% {
transform: scale(1.2);
opacity: 1;
}
100% {
transform: scale(1);
}
}

@-webkit-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-moz-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-ms-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}

Body:
Here is a link to a similar question that might help you out.

Run CSS3 animation only once (at page loading)

Personally I would add an extra class to the div that handles all the entrance animations and then use javascript to remove that class once the cursor moves inside the div. I'll make a js fiddle and show you an example, just give me a few minutes.

Edit for fiddle link: https://jsfiddle.net/0uaktv10/

html:

<div class="profile load-in" style="background: blue; width: 100px; height: 100px;"></div>

Css:

    enter .profile {
width: 125px;
height: 125px;
background-image: url(graphics/profile1.jpg);
border-style: solid;
border-color: white;
border-radius: 50%;
margin-left: 80px;
outline: 1px solid transparent;
float: left;
}

.load-in {
  animation: popIn 1s;
}

.profile:hover{
width: 125px;
height: 125px;
border-style: solid;
border-color: red;
box-shadow: 0 0 0 0 rgba(155, 0, 2, 0.6);
border-radius: 50%;
-webkit-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-moz-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
-ms-animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
animation: pulse 1.25s infinite cubic-bezier(0.66, 0, 0, 1);
}
@keyframes popIn{
0% {
transform: scale(0.1);
opacity: 0;
}
60% {
transform: scale(1.2);
opacity: 1;
}
100% {
transform: scale(1);
}
}

@-webkit-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-moz-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@-ms-keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}
@keyframes pulse {to {box-shadow: 0 0 0 45px rgba(232, 76, 61, 0);}}

jQuery:

$(".profile").hover(function(){
    $(".profile").removeClass("load-in")
})


问:
animate's callback function (complete) executed at start?
I'm using jQuery 1.5.1 This is my code:

```<code>$('.cellcontent').animate({
   left: '-=190'}, {
   easing: alert('start ani'),
   duration: 5000,
   complete: alert('end ani')});
</code>```

I get both alerts before the animation starts!? I want the complete function to start after the animation has ended. Any thoughts?

答:
from the jquery docs:</p>

```<code>$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
   left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });
});
</code>```

Body:
I'm using jQuery 1.5.1 This is my code:

$('.cellcontent').animate({
   left: '-=190'}, {
   easing: alert('start ani'),
   duration: 5000,
   complete: alert('end ani')});

I get both alerts before the animation starts!? I want the complete function to start after the animation has ended. Any thoughts?

Body:
from the jquery docs:

$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
   left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });
});


问:
Sublime Text 3 - Preview in browser [localhost] using sidebar enhancement plugin
I have an issue with Sublime Text 3 where I can't get the side bar enhancement plugin to preview in browser for projects on a localhost web server.

I am not the most privy with Sublime but I like the customisation and flexibility.

I have read a couple of different sites in setting the plugin up but to no avail. Maybe my lack of understanding or maybe I'm just missing something.
Here are some the sites I've looked at for starters:

https://github.com/titoBouzout/SideBarEnhancements#with-absolute-paths

https://github.com/xkeshav/sublime/blob/master/settings.md

https://forum.sublimetext.com/t/view-in-browser-php-file-xampp/18431/2

https://www.hongkiat.com/blog/preview-in-localhost/

I've tried a few variations of the SideBarEnhancements.json script and this is what I've currently landed on using (which doesn't work anyways).

```<code>{
    "/applications/mamp/htdocs":
    {
        "url_testing":"http://localhost",
        "url_production":"http://localhost"
    }
}
</code>```

I'm also trying to use the key bindings, but since I can't even get the right click Open in Browser function to work, well I'm just stuck.

答:
Ok, so it seems that SideBarEnhancements.json file as articulated above does in fact work.

However how it ended up working I'm not entirely sure. In the end I just re-saved the json file and restarted Sublime which made the right click open in browser function of sidebarenhancements plugin work.
Now to fix the key bindings. Will update when possible.

Body:
I have an issue with Sublime Text 3 where I can't get the side bar enhancement plugin to preview in browser for projects on a localhost web server.

I am not the most privy with Sublime but I like the customisation and flexibility.

I have read a couple of different sites in setting the plugin up but to no avail. Maybe my lack of understanding or maybe I'm just missing something.
Here are some the sites I've looked at for starters:

https://github.com/titoBouzout/SideBarEnhancements#with-absolute-paths

https://github.com/xkeshav/sublime/blob/master/settings.md

https://forum.sublimetext.com/t/view-in-browser-php-file-xampp/18431/2

https://www.hongkiat.com/blog/preview-in-localhost/

I've tried a few variations of the SideBarEnhancements.json script and this is what I've currently landed on using (which doesn't work anyways).

{
    "/applications/mamp/htdocs":
    {
        "url_testing":"http://localhost",
        "url_production":"http://localhost"
    }
}

I'm also trying to use the key bindings, but since I can't even get the right click Open in Browser function to work, well I'm just stuck.


问:
NullInjectorError: No provider for MatDialogRef
I can't inject MatDialogRef as it described in documentation: https://material.angular.io/components/dialog/overview

When i'm trying to do it i'v got error:

ERROR Error: StaticInjectorError[MatDialogRef]:
StaticInjectorError[MatDialogRef]:
NullInjectorError: No provider for MatDialogRef!

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import {
 MatInputModule,
 MatDialogModule,
 MatProgressSpinnerModule,
 MatButtonModule,
 MatDialog,
 MatDialogRef
} from '@angular/material';

import { ApiModule } from '../api/api.module';
import { RoutingModule } from '../routing/routing.module';

import { RegistrationComponent } from './components/registration.component';
import { LoginComponent } from './components/login.component';

import { AccountService } from './services/account.service';

@NgModule({
 imports: [
  BrowserModule,
  MatInputModule,
  MatDialogModule,
  MatProgressSpinnerModule,
  MatButtonModule,
  FormsModule,
  RoutingModule,
  ApiModule
 ],
 declarations: [
  RegistrationComponent,
  LoginComponent
 ],
 entryComponents: [
  LoginComponent,
  RegistrationComponent
 ],
 providers: [
  AccountService,
  MatDialog,
  MatDialogRef
 ]
})
export class AccountModule {}```
</div>
</div>
</p>

<p>home.component.ts</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';

import { MatDialog } from '@angular/material';
import { RegistrationComponent } from '../account/components/registration.component';

@Component({
    moduleId: module.id.replace('compiled', 'app'),
    templateUrl: 'home.component.html'
})
export class HomeComponent
{
    constructor(private modalService: MatDialog) {}

    public openModal() : void
    {
        let dialog = this.modalService.open(RegistrationComponent, {});
    }
}</code>```

registration.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialogRef } from '@angular/material/dialog';

import { User } from '../../../models/domain/User';
import { ApiUserService } from '../../api/entity-services/user.service';
import { AuthService } from '../../auth/auth.service';
import { AccountService } from '../services/account.service'

@Component({
 selector: 'registration-component',
 templateUrl: 'app/modules/account/templates/registration.component.html'
})
export class RegistrationComponent
{
 public user :User = new User();

 public errorMessage :string;

 public isLoading :boolean;

 constructor
 (
  private userService :ApiUserService,
  private authService :AuthService,
  private accountService :AccountService,
  private router :Router,
  public dialogRef :MatDialogRef<RegistrationComponent>
 )
 {
  this.isLoading = false;
 }

 public onSubmit(e) :void
 {
  e.preventDefault();
  this.isLoading = true;

  this.userService
   .Create(this.user)
   .subscribe(
    user =>
    {
     this.user.id = user.id;
     this.user.login = user.login;

     this.authService
      .Login(this.user)
      .subscribe(
       token =>
       {
        this.accountService.Load()
         .subscribe(
          account =>
          {
           this.user = account;
           this.isLoading = false;
           this.dialogRef.close();

           let redirectRoute = account.activeScopeId
            ? `/scope/${account.activeScopeId}`
            : '/scope-list/';

           this.router.navigate([redirectRoute]);
          },
          error => this.errorMessage = <any>error
         );
       },
       error => this.errorMessage = <any>error
      );
    },
    error => this.errorMessage = <any>error
   );
 }
}```

答: Thanks to the @Edric, i'v solved the problem by importing MatDialogModule, MatDialog and MatDialogRef from @angular/material/dialog instead of @angular/material

Body:
I can't inject MatDialogRef as it described in documentation: https://material.angular.io/components/dialog/overview

When i'm trying to do it i'v got error:

ERROR Error: StaticInjectorError[MatDialogRef]:
StaticInjectorError[MatDialogRef]:
NullInjectorError: No provider for MatDialogRef!

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import {
 MatInputModule,
 MatDialogModule,
 MatProgressSpinnerModule,
 MatButtonModule,
 MatDialog,
 MatDialogRef
} from '@angular/material';

import { ApiModule } from '../api/api.module';
import { RoutingModule } from '../routing/routing.module';

import { RegistrationComponent } from './components/registration.component';
import { LoginComponent } from './components/login.component';

import { AccountService } from './services/account.service';

@NgModule({
 imports: [
  BrowserModule,
  MatInputModule,
  MatDialogModule,
  MatProgressSpinnerModule,
  MatButtonModule,
  FormsModule,
  RoutingModule,
  ApiModule
 ],
 declarations: [
  RegistrationComponent,
  LoginComponent
 ],
 entryComponents: [
  LoginComponent,
  RegistrationComponent
 ],
 providers: [
  AccountService,
  MatDialog,
  MatDialogRef
 ]
})
export class AccountModule {}

home.component.ts

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

import { MatDialog } from '@angular/material';
import { RegistrationComponent } from '../account/components/registration.component';

@Component({
    moduleId: module.id.replace('compiled', 'app'),
    templateUrl: 'home.component.html'
})
export class HomeComponent
{
    constructor(private modalService: MatDialog) {}

    public openModal() : void
    {
        let dialog = this.modalService.open(RegistrationComponent, {});
    }
}

registration.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialogRef } from '@angular/material/dialog';

import { User } from '../../../models/domain/User';
import { ApiUserService } from '../../api/entity-services/user.service';
import { AuthService } from '../../auth/auth.service';
import { AccountService } from '../services/account.service'

@Component({
 selector: 'registration-component',
 templateUrl: 'app/modules/account/templates/registration.component.html'
})
export class RegistrationComponent
{
 public user :User = new User();

 public errorMessage :string;

 public isLoading :boolean;

 constructor
 (
  private userService :ApiUserService,
  private authService :AuthService,
  private accountService :AccountService,
  private router :Router,
  public dialogRef :MatDialogRef<RegistrationComponent>
 )
 {
  this.isLoading = false;
 }

 public onSubmit(e) :void
 {
  e.preventDefault();
  this.isLoading = true;

  this.userService
   .Create(this.user)
   .subscribe(
    user =>
    {
     this.user.id = user.id;
     this.user.login = user.login;

     this.authService
      .Login(this.user)
      .subscribe(
       token =>
       {
        this.accountService.Load()
         .subscribe(
          account =>
          {
           this.user = account;
           this.isLoading = false;
           this.dialogRef.close();

           let redirectRoute = account.activeScopeId
            ? `/scope/${account.activeScopeId}`
            : '/scope-list/';

           this.router.navigate([redirectRoute]);
          },
          error => this.errorMessage = <any>error
         );
       },
       error => this.errorMessage = <any>error
      );
    },
    error => this.errorMessage = <any>error
   );
 }
}


问:
not getting right data in my backend from client
I am trying to send data to my backend, but when it comes to backend it catches an expception thus returns error message.
  I am assuming this is becuase data format from client side is somehow different than what I expected.

I expcect my backend to receive json string(I have other function that takes jsong string to object later).

What am I doing it wrong? I am aware that I can create modelling class for my data from client in my backend, but I need to work it without them and it shoud work as data are all string from my client
  from client.

client

```<code>  //to backend
  callServer() {
    var data = JSON.stringify(test);
    //dispaly JSON like {"GradeA" : "23", "GradeB" : "45", "GradeC" : "22"}
    console.log(data);
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
                        .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
      })
  }
</code>```

backend

```<code>public class testAPiController : ApiController
{
    private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public string test([FromBody] string body)
    {
        try
        {
            Log.Info(string.Format("data {0}", body));
            //convert to json object
            return json_object;
        }

        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return "error";
        }
    }
}
</code>```

Config

```<code>public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            // Web API configuration and services
            log4net.Config.XmlConfigurator.Configure();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "GET", id = RouteParameter.Optional }
            );

        }
    }
</code>```

Updated1

I don't get any error message, but return my body as null

Updated2

```<code> this.appService.http.post('http://localhost:2717/api/testAPi/test', "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}", {headers: headers})
</code>```

still not working with different format of the body while Postman works with it

答:
Very first your API method is GET method since that's default but from client you are making a POST call. Other than that, the passed data is not getting used anywhere

```<code>public string test([FromBody] string body)
{
</code>```

Body:
I am trying to send data to my backend, but when it comes to backend it catches an expception thus returns error message.
  I am assuming this is becuase data format from client side is somehow different than what I expected.

I expcect my backend to receive json string(I have other function that takes jsong string to object later).

What am I doing it wrong? I am aware that I can create modelling class for my data from client in my backend, but I need to work it without them and it shoud work as data are all string from my client
  from client.

client

  //to backend
  callServer() {
    var data = JSON.stringify(test);
    //dispaly JSON like {"GradeA" : "23", "GradeB" : "45", "GradeC" : "22"}
    console.log(data);
    const headers = new HttpHeaders().set('Content-Type', 'application/json');

    this.appService.http.post('http://localhost:2717/api/testAPi/test', data, {headers: headers})
                        .subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
      })
  }

backend

public class testAPiController : ApiController
{
    private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public string test([FromBody] string body)
    {
        try
        {
            Log.Info(string.Format("data {0}", body));
            //convert to json object
            return json_object;
        }

        catch (Exception ex)
        {
            Log.Error(ex.Message);
            return "error";
        }
    }
}

Config

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            // Web API configuration and services
            log4net.Config.XmlConfigurator.Configure();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "GET", id = RouteParameter.Optional }
            );

        }
    }

Updated1

I don't get any error message, but return my body as null

Updated2

 this.appService.http.post('http://localhost:2717/api/testAPi/test', "{\"GradeA\" : \"23\", \"GradeB\" : \"45\", \"GradeC\" : \"22\"}", {headers: headers})

still not working with different format of the body while Postman works with it

Body:
Very first your API method is GET method since that's default but from client you are making a POST call. Other than that, the passed data is not getting used anywhere

public string test([FromBody] string body)
{


问:
How to use localStorage to change value of variable on .js on a HTML file and have the value be retained when on other HTML file?
I have a JavaScript file with some variables on it and multiple HTML files accessing it, but I want it so that when I change a variable in JavaScript, the value is retained in different HTML files and when I reload the page.

say this is my JavaScript file, lets call it variables.js

```<code>localStorage.setItem("number", 1);

var number = parseInt(localStorage.number);

console.log(number);
</code>```

say this is one of my HTML files

```<code><script src="variables.js">
number;
</script>

<script>
/*I've tried all 3 of these separatetly and together, but the value resets back to 10 when accessed on a different HTML file or when I reload the page*/
number = 2;
localStorage.setItem("number", 2);
localStorage.number = 2;
</script>
</code>```

when I reload the page, the value of the variable resets back to 1 instead of 2

What is the problem here?

答:
The problem is in your first two lines of variables.js:

```<code>localStorage.setItem("number", 1);
var number = parseInt(localStorage.number);
</code>```

Every time variables.js gets loaded (it's called at the top of your HTML file with

Body:
I have a JavaScript file with some variables on it and multiple HTML files accessing it, but I want it so that when I change a variable in JavaScript, the value is retained in different HTML files and when I reload the page.

say this is my JavaScript file, lets call it variables.js

localStorage.setItem("number", 1);

var number = parseInt(localStorage.number);

console.log(number);

say this is one of my HTML files

when I reload the page, the value of the variable resets back to 1 instead of 2

What is the problem here?

Body:
The problem is in your first two lines of variables.js:

localStorage.setItem("number", 1);
var number = parseInt(localStorage.number);

Every time variables.js gets loaded (it's called at the top of your HTML file with <script src="variables.js">), the localStorage is set to 1, and considering number is set after that, the local variable number is also set to 1 (which is later outputted to the page).

Instead of setting number to parseInt(localStorage.number), you're looking to retrieve the value from localStorage with localStorage.getItem("number"), and you're looking to do this before modifying it.

To output one value at first, and then a new value the second time the user sees the page, you can check the value is set with if (localStorage.number). If it is set, you set the new value. If it is not set, you set the original value. You'll also want to check this when outputting the value to the page.

This can be seen in the following (sandboxed) StackSnippet:

// Output whatever is in the storage, *if* it is set
if (localStorage.number) {
  document.getElementById("output").innerHTML = localStorage.getItem("number");
}

// If the number has already been set to 1, set it to 2
if (localStorage.number) {
  localStorage.setItem("number", 2);
}
// Else set it to 1
else {
  localStorage.setItem("number", 1);
}

<div id="output">Not set yet!</div>

And in this JSFiddle snippet.

Hope this helps! :)


问:
Handling Base64 images in ImageMagick
I want to use ImageMagick convert command but using a base64 image:

```<code>convert img1.jpeg -distort barrel 'a b c' img2.jpeg
</code>```

But I do not really know how to do this, because in ImageMagick documentation they suggest to use inline but I am obtaining segmentation fault after:

```<code>convert inline:base64.txt -distort barrel '-0.03 -0.0 -0.3' output
</code>```

答:
This seems to work for me in ImageMagick 6.9.9.23 Q16 Mac OSX:

input:

```<code>convert noseguy.gif inline:b64_noseguy.txt

cat b64_noseguy.txt
</code>```

data:image/gif;base64,R0lGODlhIAAgAPIEAAAAAB6Q/76+vvXes////wAAAAAAAAAAACH5BAEAAAUALAAAAAAgACAAAAOBWLrc/jDKCYG1NBcwegeaxHkeGD4j+Z1OWl4Yu6mAYAu1ebpwL/OEYCDA0YWAQuJqRwsSeEyaRTUwTlxUqjUymmZpmeI3u62Mv+XWmUzBrpeit7YtB1/rpTAefv942UcXVX9+MjNVfheGCl18i4ddjwwpPjEslFKDUWeRGj2fnw0JADs=

```<code>convert 'inline:data:image/gif;base64,R0lGODlhIAAgAPIEAAAAAB6Q/76+vvXes////wAAAAAAAAAAACH5BAEAAAUALAAAAAAgACAAAAOBWLrc/jDKCYG1NBcwegeaxHkeGD4j+Z1OWl4Yu6mAYAu1ebpwL/OEYCDA0YWAQuJqRwsSeEyaRTUwTlxUqjUymmZpmeI3u62Mv+XWmUzBrpeit7YtB1/rpTAefv942UcXVX9+MjNVfheGCl18i4ddjwwpPjEslFKDUWeRGj2fnw0JADs=' b64_nose_guy.png
</code>```

If your ImageMagick version was older than Feb 10, 2015 (about IM 6.9.0.5) then there was a 4096 character limit to inline due to a bug. See http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=26918&p=119520&hilit=inline+base64#p119520

Furthermore, this command to do barrel distortion also works fine:

```<code>convert 'inline:data:image/gif;base64,R0lGODlhIAAgAPIEAAAAAB6Q/76+vvXes////wAAAAAAAAAAACH5BAEAAAUALAAAAAAgACAAAAOBWLrc/jDKCYG1NBcwegeaxHkeGD4j+Z1OWl4Yu6mAYAu1ebpwL/OEYCDA0YWAQuJqRwsSeEyaRTUwTlxUqjUymmZpmeI3u62Mv+XWmUzBrpeit7YtB1/rpTAefv942UcXVX9+MjNVfheGCl18i4ddjwwpPjEslFKDUWeRGj2fnw0JADs=' -distort barrel '-0.03 -0.0 -0.3' b64_nose_guy_barrel.png
</code>```

The barrel result is just a little bit narrower in width than the non-barrel result.

If it does not work for you, perhaps you need to upgrade your version of ImageMagick. You did not say what version and platform you were using

Title: Handling Base64 images in ImageMagick

Body:
I want to use ImageMagick convert command but using a base64 image:

convert img1.jpeg -distort barrel 'a b c' img2.jpeg

But I do not really know how to do this, because in ImageMagick documentation they suggest to use inline but I am obtaining segmentation fault after:

convert inline:base64.txt -distort barrel '-0.03 -0.0 -0.3' output

Body:
This seems to work for me in ImageMagick 6.9.9.23 Q16 Mac OSX:

input:

convert noseguy.gif inline:b64_noseguy.txt

cat b64_noseguy.txt

data:image/gif;base64,R0lGODlhIAAgAPIEAAAAAB6Q/76+vvXes////wAAAAAAAAAAACH5BAEAAAUALAAAAAAgACAAAAOBWLrc/jDKCYG1NBcwegeaxHkeGD4j+Z1OWl4Yu6mAYAu1ebpwL/OEYCDA0YWAQuJqRwsSeEyaRTUwTlxUqjUymmZpmeI3u62Mv+XWmUzBrpeit7YtB1/rpTAefv942UcXVX9+MjNVfheGCl18i4ddjwwpPjEslFKDUWeRGj2fnw0JADs=

convert 'inline:data:image/gif;base64,R0lGODlhIAAgAPIEAAAAAB6Q/76+vvXes////wAAAAAAAAAAACH5BAEAAAUALAAAAAAgACAAAAOBWLrc/jDKCYG1NBcwegeaxHkeGD4j+Z1OWl4Yu6mAYAu1ebpwL/OEYCDA0YWAQuJqRwsSeEyaRTUwTlxUqjUymmZpmeI3u62Mv+XWmUzBrpeit7YtB1/rpTAefv942UcXVX9+MjNVfheGCl18i4ddjwwpPjEslFKDUWeRGj2fnw0JADs=' b64_nose_guy.png

If your ImageMagick version was older than Feb 10, 2015 (about IM 6.9.0.5) then there was a 4096 character limit to inline due to a bug. See http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=26918&p=119520&hilit=inline+base64#p119520

Furthermore, this command to do barrel distortion also works fine:

convert 'inline:data:image/gif;base64,R0lGODlhIAAgAPIEAAAAAB6Q/76+vvXes////wAAAAAAAAAAACH5BAEAAAUALAAAAAAgACAAAAOBWLrc/jDKCYG1NBcwegeaxHkeGD4j+Z1OWl4Yu6mAYAu1ebpwL/OEYCDA0YWAQuJqRwsSeEyaRTUwTlxUqjUymmZpmeI3u62Mv+XWmUzBrpeit7YtB1/rpTAefv942UcXVX9+MjNVfheGCl18i4ddjwwpPjEslFKDUWeRGj2fnw0JADs=' -distort barrel '-0.03 -0.0 -0.3' b64_nose_guy_barrel.png

The barrel result is just a little bit narrower in width than the non-barrel result.

If it does not work for you, perhaps you need to upgrade your version of ImageMagick. You did not say what version and platform you were using