问:
Zip subfolders using ZipOutputStream
ZipOutputStream only zips files in a folder. I want to zip subfolders also. How can I achieve this?

答: This article by C# MVP Peter Bromberg may solve your problem: Zip / Unzip folders and files with C#. It has complete code and a sample project.</p>

Title: Zip subfolders using ZipOutputStream


来源: stackexchange

问:
How to perform two results with a single $('#id').on('change', function);
I have let's say sets of div:

```<code><body>
<div id="div1" style="display: block">
    <p> paragraph here </p>``
    <img>
    <table></table>
</div>

<div id="div2" style="display: none">
    <p> paragraph here </p>
    <img>
    <table></table>
</div>
</code>```

I surrounded each contents with div.

Now I have two radio buttons:

```<code><label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block">
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block">
</code>```

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

```<code>$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);
</code>```

but here, when I tried the second button:

```<code>$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');
</code>```

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

答:
Came up with this condensed change handler for both of them.

$('#button1, #button2').on('change', function(e) {
  var $divs = $('#div1, #div2');
  var targets = {
    button1: "#div1",
    button2: "#div2"
  };

  //get the div id by the button id
  $divs.not(targets[e.target.id]).hide();
  $divs.filter(targets[e.target.id]).css('display', e.target.value);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" style="display: block">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2" style="display: none">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block" checked>
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block"></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have let's say sets of div:

 paragraph here
``

 paragraph here

I surrounded each contents with div.

Now I have two radio buttons:

 Button1
<input id="button1" name="button" type="radio" value="block">
 Button2
<input id="button2" name="button" type="radio" value="block">

Now what I want to do is to hide the current div and display the second div in place of the first div using .css().
The method I have now is:

$('#button1').on('change', function1);
function function1() {
    let change1 = $('#button1').val();
        $('#div1').css('display', change1);

but here, when I tried the second button:

$('#button2').on('change',function2);
function function2() {
    let change2 = $('#button2').val();
        $('#div2').css('display', change2);
        $('#div1').css('display', 'none');

but it doesn't work, it can only execute one or the other but not both of them. Anyone knows the problem?
Thank you.

Body:
Came up with this condensed change handler for both of them.

$('#button1, #button2').on('change', function(e) {
  var $divs = $('#div1, #div2');
  var targets = {
    button1: "#div1",
    button2: "#div2"
  };

  //get the div id by the button id
  $divs.not(targets[e.target.id]).hide();
  $divs.filter(targets[e.target.id]).css('display', e.target.value);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" style="display: block">
  <p> paragraph here 1</p>
  <img>
  <table></table>
</div>

<div id="div2" style="display: none">
  <p> paragraph here 2</p>
  <img>
  <table></table>
</div>

<label for="button1"> Button1 </label>
<input id="button1" name="button" type="radio" value="block" checked>
<label for="button2"> Button2</label>
<input id="button2" name="button" type="radio" value="block">


问:
How to combine values of objects with common key in JavaScript?
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

```<code>let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];
</code>```

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

```<code>let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]
</code>```

答:
I think this is what you are looking for. This is merging the two datasets, adding values from the second item that don't exist in the first.

There are a number of comments in there so you can follow along with the data as it is worked on.

let sourceData = [
    {
        "metric": "Approved",
        "rounded_counts": [
            { "2017-11-16 15:10:00": 3 },
            { "2017-11-16 15:11:00": 5 }
        ]
    },
    {
        "metric": "Approved",
        "rounded_counts": [
            { "2017-11-16 15:10:00": 28 },
            { "2017-11-16 15:11:00": 28 },
            { "2017-11-16 15:12:00": 29 }
        ]
    },
    {
        "metric": "Quarantine",
        "rounded_counts": [
            { "2017-11-16 15:10:00": 1 },
            { "2017-11-16 15:11:00": 2 }
        ]
    }
];

let chartData = []; // our combined output Dataset

// map over the sourceData one item at a time.
sourceData.map((item) => {
    let d = chartData.find(data => data.metric == item.metric);
    if ( d ) { // if an existing item exists
        //console.log("item exists"); console.log(d);

        // create a new array of the existing items
        rounded_counts = d.rounded_counts;

        // iterate all the rounded_counts in the current item
        item.rounded_counts.map((count) => {

            let key = Object.keys(count)[0]; // get the key for the current object, this would be the datetime
            // console.log("key: " + key);

            // check for any existing items with the same key (datetime)
            let additional = rounded_counts.find(data => Object.keys(data)[0] == key);
            // console.log(additional); // print the additional item raw

            if (additional) {
                // console.log(additional[Object.keys(additional)]); // print the additional items value, this is the value we will add to the existing item with the same "metric" and same value
                let Z = (count[key] + additional[Object.keys(additional)]); // add our 2 values together
                // console.log(Z);  // print this new value
                let newObj = {}; newObj[key] = Z; // create a new Object with the new value and existing key
                rounded_counts[rounded_counts.findIndex(data => Object.keys(data)[0] == key)] = newObj; // update the existing rounded_count item with our new object
            } else {
                rounded_counts.push(count);
            }
        });

        // set the exists items rounded_counts to our new array
        d.rounded_counts = rounded_counts;

    } else {
        chartData.push(item);
    }
});

// print the dataset so we can inspect the results
console.log(chartData);```

Body:
I'm trying to merge some items in a JSON array, based on one of the keys. I want to group by the 'metric', and then I need to look at all the time/value data in 'rounded_counts', and if the times are the same, the values need to be added together. Here is the source data:

let sourceData = [
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 3 },
      { "2017-11-16 15:11:00": 5 }
    ]
  },
  {
    "metric": "Approved",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 28 },
      { "2017-11-16 15:11:00": 28 }
    ]
  },
  {
    "metric": "Quarantine",
    "rounded_counts": [
      { "2017-11-16 15:10:00": 1 },
      { "2017-11-16 15:11:00": 2 }
    ]
  }
];

and here is the desired output required for the Highcharts graphing library - notice how the 2 metrics called 'Approved' have had their values merged

Underscore, and/or ES6 can be used - Thanks in advance!

let chartData = [
  {
    "name": "Approved",
    "data": [
      [ "2017-11-16 15:10:00", 30 ],
      [ "2017-11-16 15:11:00", 33 ]
    ]
  },
  {
    "name": "Quarantine",
    "data": [
      [ "2017-11-16 15:10:00", 1 ],
      [ "2017-11-16 15:11:00", 2 ]
    ]
  }
]


问:
Get usb device on provisioning from user input in vagrant
I build a vagrant file with a provisioning script. The goal ist to build a complete linux system  for a embedded device inside the vm and write it to a sdcard in the hosts memory card reader. I would like to ask the user for the device with the sdcard.
I know i could just write a image back to the shared vagrant folder. But i would like to have a solution i could just run vagrant up, go for lunch and have the sdcard ready when i get back.
Anybody got an idea ? Would be nice if it would be a real cross platform solution. </p>

答: You can query the hostusb devices using vboxmanage and the Vagrantfile is just ruby, so you could probably do a shell call within the Vagrantfile to get the devices and then evaluate the user selected device and put the USB device ID in the virtualbox syntax as additional arguments that get lazy loaded before the actual vagrant portion of the Vagrantfile runs.</p>


问:
Can WebSockets replace AJAX when it comes to Database requests?
This may seem like an extremely dumb question, but I am currently switching my Website from using the EventSource Polling constructor to the WebSocket standard which is implemented in Node.js.

Originally, all backend on my website was handled with PHP. With the introduction of Node.js, I am trying to switch as much as I can without going outside of the "standard". By standard, I meaning that typically I see WebSocket implementations that send small data, and receive small data back vs. performing database queries and then sending large amounts of data back to the client.

Can WebSockets replace AJAX when it comes to Database requests?

Let's consider a small hello world program in PHP/JavaScript (AJAX) vs Node.js/JavaScript (WebSockets)

    PHP/JavaScript (AJAX)

```<code>// HelloWorld.php with Laravel in the Backend

Table::update([ 'column' => $_POST['message'] ]);
echo $_POST['message'];
</code>```

Ajax.js with a custom ajax function

```<code>Global.request("HelloWorld.php").post({
     message: "Hello World"
}).then(message => alert(message));
</code>```

    Node.js/JavaScript (WebSockets)

```<code>// skip all the server setup
server.on('connection', function () {
     server.on('message', function (message) {
         sqlConnection.query("UPDATE `table` SET `column` = ?", [message], function () {
              server.send(message);
         });
     });
});
</code>```

WebSocket.js:

```<code>let socket = new WebSocket('ws://example.com');

socket.onmessage = function (message) {
    alert(message)
}
socket.send("Hello World");
</code>```

They both essentially do the same thing, in a slightly different way. Now, in this scale it would not make sense to use WebSockets. Though an example, imagine it scaled up to a point where Node.js is processing bigger queries and sending lots of data to the client. Is this acceptable?

答:
Yes, theoretically, you could trigger a db query with websockets. Both HTTP and Websockets are built on TCP which do the job of transferring data of being a the bridge between network requests and responses.

The bigger issue is that Websockets were intended to lessen burden of opening/closing network ports, which you would have to do for ajax. This comes with several application-level benefits including real-time media streaming.

So what's the benefit of sticking with HTTP if you don't have a specific use case for web sockets? That HTTP is built has a robust ecosystem of tools - HTTP is largely plug & play. Think of stuff like security and standardization. Web sockets is a relatively new technology and hasn't developed this same ecosystem.

Body:
This may seem like an extremely dumb question, but I am currently switching my Website from using the EventSource Polling constructor to the WebSocket standard which is implemented in Node.js.

Originally, all backend on my website was handled with PHP. With the introduction of Node.js, I am trying to switch as much as I can without going outside of the "standard". By standard, I meaning that typically I see WebSocket implementations that send small data, and receive small data back vs. performing database queries and then sending large amounts of data back to the client.

Can WebSockets replace AJAX when it comes to Database requests?

Let's consider a small hello world program in PHP/JavaScript (AJAX) vs Node.js/JavaScript (WebSockets)

    PHP/JavaScript (AJAX)

// HelloWorld.php with Laravel in the Backend

Table::update([ 'column' => $_POST['message'] ]);
echo $_POST['message'];

Ajax.js with a custom ajax function

Global.request("HelloWorld.php").post({
     message: "Hello World"
}).then(message => alert(message));

    Node.js/JavaScript (WebSockets)

// skip all the server setup
server.on('connection', function () {
     server.on('message', function (message) {
         sqlConnection.query("UPDATE `table` SET `column` = ?", [message], function () {
              server.send(message);
         });
     });
});

WebSocket.js:

let socket = new WebSocket('ws://example.com');

socket.onmessage = function (message) {
    alert(message)
}
socket.send("Hello World");

They both essentially do the same thing, in a slightly different way. Now, in this scale it would not make sense to use WebSockets. Though an example, imagine it scaled up to a point where Node.js is processing bigger queries and sending lots of data to the client. Is this acceptable?


问:
Disabled binding not working for checkboxes generated with *ngFor
I have a list of objects that I want to bind to for checkboxes. The problem I'm having is that all of my checkboxes will be disabled when I only want to disable specific ones in the list. What is the proper way to setup the *ngfor and checkbox? Here I'm using the PrimeNg checkbox but if you know for a regular checkbox that would be a helpful stepping stone.

component.ts has this:

```<code> this.options = [
            { name: "A", checked: true, disabled: true },
            { name: "B", checked: false, disabled: false },
            { name: "C", checked: false, disabled: false },
        ];
</code>```

component.html:

```<code><div class="form-group row">
    <span *ngFor="let test of options; let i=index" class="col-sm-4">
        <p-checkbox binary="true" [(ngModel)]="test.checked" label="{{test.name}}"
            [ngModelOptions]="{standalone: true}" disabled="{{test.disabled}}"></p-checkbox>
    </span>
</div>
</code>```

答:
change how you set disabled</p>

```<code>// this will always set a disabled attribute. Problem is, as soon as the attribute exists,
//  the browser disables the input. As a result, all your inputs are disabled
disabled="{{test.disabled}}"

// this binds to the DOM property, not the element attribute. When the property is false
// the browser removes the attribute from the DOM and the input is enabled
[disabled]="test.disabled"
</code>```

Body:
I have a list of objects that I want to bind to for checkboxes. The problem I'm having is that all of my checkboxes will be disabled when I only want to disable specific ones in the list. What is the proper way to setup the *ngfor and checkbox? Here I'm using the PrimeNg checkbox but if you know for a regular checkbox that would be a helpful stepping stone.

component.ts has this:

 this.options = [
            { name: "A", checked: true, disabled: true },
            { name: "B", checked: false, disabled: false },
            { name: "C", checked: false, disabled: false },
        ];

component.html:

Body:
change how you set disabled

// this will always set a disabled attribute. Problem is, as soon as the attribute exists,
//  the browser disables the input. As a result, all your inputs are disabled
disabled="{{test.disabled}}"

// this binds to the DOM property, not the element attribute. When the property is false
// the browser removes the attribute from the DOM and the input is enabled
[disabled]="test.disabled"


问:
GsonBuilder setPrettyPrinting doesn't print pretty
I'm using the following code (found on this webpage) and the Gson library (2.8.2) to format JSON code with pretty printing.

```<code>import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonExample {
    public static void main(String[] args) {
      String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String json = gson.toJson(jsonData);

      System.out.println(json);
    }
}
</code>```

This is the expected result:

```<code>{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}
</code>```

Unfortunately "pretty printing" doesn't work at all and I get everything in one line:

```<code>{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}"
</code>```

Any ideas what I'm doing wrong?

答:
You have to parse the JSON, and then call gson.toJson() on the resulting parsed JSON.

```<code>JsonElement jsonElement = new JsonParser().parse(jsonData);
String json = gson.toJson(jsonElement);
</code>```

Your current code is just telling GSON to convert some String into JSON, and the result of that is the same String.

Body:
I'm using the following code (found on this webpage) and the Gson library (2.8.2) to format JSON code with pretty printing.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonExample {
    public static void main(String[] args) {
      String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String json = gson.toJson(jsonData);

      System.out.println(json);
    }
}

This is the expected result:

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

Unfortunately "pretty printing" doesn't work at all and I get everything in one line:

{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}"

Any ideas what I'm doing wrong?

Body:
You have to parse the JSON, and then call gson.toJson() on the resulting parsed JSON.

JsonElement jsonElement = new JsonParser().parse(jsonData);
String json = gson.toJson(jsonElement);

Your current code is just telling GSON to convert some String into JSON, and the result of that is the same String.


问:
How do I add csv file data into a dictionary
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

```<code>ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30
</code>```

For example if I called the ID: "12345" it would display - Italy, 100, 80

答:
Your question is quite vague, but making a dict is pretty easy.

```<code>d={
  '12345' : ['Italy',100,80],
 ....#add more as needed
}
</code>```

Now d['12345'] will return that list with the info in it. Not sure what else you need...

Body:
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30

For example if I called the ID: "12345" it would display - Italy, 100, 80

Body:
Your question is quite vague, but making a dict is pretty easy.

d={
  '12345' : ['Italy',100,80],
 ....#add more as needed
}

Now d['12345'] will return that list with the info in it. Not sure what else you need...


问:
Python create cookies and then load a page with the cookies

I would like to access a web page from a python program.
I have to set up cookies to load the page.

I used the httplib2 library, but I didn't find how add my own cookie

```<code>resp_headers, content = h.request("http://www.theURL.com", "GET")
</code>```

How can I create cookies with the right name and value, add it to the function and then load the page?

Thanks

答:
You can also use just urllib2 library

```<code>        import urllib2

        opener = urllib2.build_opener()
        opener.addheaders.append(('Cookie', 'cookie1=value1;cookie2=value2'))
        f = opener.open("http://www.example.com/")
        the_page_html = f.read()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would like to access a web page from a python program.
I have to set up cookies to load the page.

I used the httplib2 library, but I didn't find how add my own cookie

resp_headers, content = h.request("http://www.theURL.com", "GET")

How can I create cookies with the right name and value, add it to the function and then load the page?

Thanks

Body:
You can also use just urllib2 library

        import urllib2

        opener = urllib2.build_opener()
        opener.addheaders.append(('Cookie', 'cookie1=value1;cookie2=value2'))
        f = opener.open("http://www.example.com/")
        the_page_html = f.read()


问:
Filtering the Array Object by Matching SubObject values
I have an array of objects:

```<code>sampledata = [{
    "id": 1,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 1"
    },
    "energy": -145.9,
    "pv": 83.72
}, {
    "id2": 2,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 2"
    },
    "energy": -145.9,
    "pv": 83.72
}];
</code>```

I want to get some of the object's attributes if that object's parameter value matches a given input.

I have tried:

```<code>let x={Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}
return this.sampledata.filter(data=> data['parameter']===x)
</code>```

Based on the matching parameter object I want to return energy and pv attribute from the array object.
Result:

```<code>{
 "energy": -145.9,
  "pv": 83.72
}
</code>```

Can anyone suggest how I can filter my data?

答:
Use Array#every to iterate the keys of x, and check if all x values equal the same values of parameter. After filtering the object, map the array's objects to the required format:

const data = [{"id":1,"parameter":{"Num_Of_Floors":"2","East":"10","Window_Type":"Window Type 1"},"energy":-145.9,"pv":83.72},{"id2":2,"parameter":{"Num_Of_Floors":"2","East":"10","Window_Type":"Window Type 2"},"energy":-145.9,"pv":83.72}];

const x = {Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"};

const result = data.filter(({ parameter }) =>
  Object.keys(x).every((key) => x[key] === parameter[key]))
  .map(({ energy, pv }) => ({ energy, pv }));

console.log(result);```

Body:
I have an array of objects:

sampledata = [{
    "id": 1,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 1"
    },
    "energy": -145.9,
    "pv": 83.72
}, {
    "id2": 2,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 2"
    },
    "energy": -145.9,
    "pv": 83.72
}];

I want to get some of the object's attributes if that object's parameter value matches a given input.

I have tried:

let x={Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}
return this.sampledata.filter(data=> data['parameter']===x)

Based on the matching parameter object I want to return energy and pv attribute from the array object.
Result:

{
 "energy": -145.9,
  "pv": 83.72
}

Can anyone suggest how I can filter my data?


问:
Target custom attributes using jQuery
I am using a slider (Slick Slider) and I am trying to target individual slides.

Here is an example of the things it spits into the divs.

```<code><div class="slick-slide" data-slick-index="1" aria-hidden="true" tabindex="-1" role="option" aria-describedby="slick-slide01"></div>
<div class="slick-slide" data-slick-index="2" aria-hidden="true" tabindex="-1" role="option" aria-describedby="slick-slide02"></div>
</code>```

I want to target each div using jQuery so I can add a class to it. I think the attribute I want to target is aria-describedby

I've tried doing this:

jQuery("[aria-describedby='slick-slide01']").addClass("newClass"); but it doesn't seem to work.

I can't use nth child selectors because I have Slick set to infinite loop and nth child on this doesn't always select the right div. What can I try next?

答:
As you can see, there is no problem with your code. You just have both divs empty, so it just looks like there is no change...

jQuery("[aria-describedby='slick-slide01']").addClass("newClass");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.newClass {
  background-color: red;
}</code>```

AAA

AAA
```

ContentLicense: CC BY-SA 4.0

Title: Target custom attributes using jQuery

Body:
I am using a slider (Slick Slider) and I am trying to target individual slides.

Here is an example of the things it spits into the divs.

I want to target each div using jQuery so I can add a class to it. I think the attribute I want to target is aria-describedby

I've tried doing this:

jQuery("[aria-describedby='slick-slide01']").addClass("newClass"); but it doesn't seem to work.

I can't use nth child selectors because I have Slick set to infinite loop and nth child on this doesn't always select the right div. What can I try next?

Body:
As you can see, there is no problem with your code. You just have both divs empty, so it just looks like there is no change...

jQuery("[aria-describedby='slick-slide01']").addClass("newClass");

.newClass {
  background-color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slick-slide" data-slick-index="1" aria-hidden="true" tabindex="-1" role="option" aria-describedby="slick-slide01">AAA</div>
<div class="slick-slide" data-slick-index="2" aria-hidden="true" tabindex="-1" role="option" aria-describedby="slick-slide02">AAA</div>


问:
Handling temporary changes (not to be committed) in Git
Often while working on a branch I need to introduce some "temporary" changes (such as additional debugging info, or a change which lets me better observe the thing i'm actually working on).

About these "temporary" changes:

I want them in my working copy of my branch, because they help me to work on the actual change,

I don't want them committed to the branch, because the branch is going to be merged into master some time and they're not production code.

Currently I just keep them as unstaged and I skip them manually when staging every commit. However I can't stay with this solution because:

All the time I have to remember which files I need to skip,

Someday I'm going to end up with 2 changes in one file, one being temporary, one to be committed, and it's going to be really troublesome.

How should I deal with it?

gitignore is obviously out of the question because I don't want to ignore the whole files and I'm still interested in changes from other committers (I need to rebase the branch to master from time to time).

答:
To avoid cluttering up your staging area as you're creating a feature, commit your debug changes with a bright blinking warning that they should not make it into the final merge:

```<code>#warning - DEBUG ONLY - DO NOT MERGE

print(debugInfo)

#warning - DEBUG ONLY - DO NOT MERGE
</code>```

When you're ready to merge the branch, if you've forgotten about them, these changes will be caught by you or someone else in the code review of your pull request.

You'll then have different ways to remove the debug commits:

revert the specific debug commits. This will retain their history in the branch.

cherry-pick the good commits. This will remove the debug commits entirely.

Something more complicated such as rebase -interactive to remove the commits in-place.

Body:
To avoid cluttering up your staging area as you're creating a feature, commit your debug changes with a bright blinking warning that they should not make it into the final merge:

#warning - DEBUG ONLY - DO NOT MERGE

print(debugInfo)

#warning - DEBUG ONLY - DO NOT MERGE

When you're ready to merge the branch, if you've forgotten about them, these changes will be caught by you or someone else in the code review of your pull request.

You'll then have different ways to remove the debug commits:

revert the specific debug commits. This will retain their history in the branch.

cherry-pick the good commits. This will remove the debug commits entirely.

Something more complicated such as rebase -interactive to remove the commits in-place.


问:
How do I connect GitHub to Shopify?
I've used Beanstalk and Tower in the past for version control, however, is there a way to connect Shopify to GitHub?

Ideally, I'd like to have a copy of my Shopify theme on my desktop to work on, then when I'm ready to push the changes, I'll use the GitHub Desktop app to push to Shopify.

How do I go about connecting Shopify and GitHub together?

Cheers

答:
I think that you need a Premium Shopify account , but anyways if you have 1 I recommend you to use this : https://zapier.com/zapbook/github/shopify/ !
It explains you step by step on how to do it!</p>

Title: How do I connect GitHub to Shopify?


问:
Split divs diagonally and responsively
I need to build the following screenshot, and I can't figure out how to do the angles responsively:

https://imgur.com/a/e9IJV

I tried using pseudo classes to add diagonal edges to a solid-color div.
But this design requires two images side-by-side so that won't work there. Also, the slants have to stay on the same angle through different sections with variable heights. I can't use clip-path because I need to support IE.

Here is my feeble attempt:
https://codepen.io/lsterling03/pen/zPEgaq

As you can see, I am having trouble! Is this design possible? Do you have any advice on how to approach this? Will it require javascript?

UPDATE

I have made a little progress. Here is an updated pen:
https://codepen.io/lsterling03/pen/GOOqmo

I can't get the slant right on the last section, which needs a variable height and width. I tried using javascript, but I don't have the right calculations:

```<code>        $(".slant").css('width', $('.main').width() * 0.5 - 100);
        $(".slant").css('border-top-width', $('.main').height());
</code>```

I also haven't figured out how to do two images in a row yet.

Does anyone have suggestions to fix either of the above issues?

答:
And, here is another example that you can start to investigate some more: CodePen</p>

```<code>body {
  background-color: #00bcd4;
}

div { box-sizing:border-box; }

.row {
  overflow: hidden;
  position: relative;
  width: 100%;
}

.image {
  background: url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg) center center no-repeat #eee;
  background-size: cover;
  height: 400px;
  width: 50%;
  float: right;
}

.image2{
  background: url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg) center center no-repeat #eee;
  background-size: cover;
  height: 400px;
  width: 64.5%;
  float: left;
  -webkit-clip-path: polygon(0 0, 100% 0, 78% 100%, 0% 100%);
  clip-path: polygon(0 0, 100% 0, 78% 100%, 0% 100%);
}

.image3{
  background: url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg) top left no-repeat #eee;
  background-size: cover;
  height: 400px;
  width: 50%;
  float: left;
  -webkit-clip-path: polygon(28% 0, 100% 0, 100% 100%, 0% 100%);
  clip-path: polygon(28% 0, 100% 0, 100% 100%, 0% 100%);
  position: absolute;
  right: 0;
}

.text {
  background-color: #eee;
  padding: 30px;
  position: relative;
  width: 50%;
  float: left;
  height: 400px;
}

.text > div {
  position: relative;
  z-index: 1;
}

.text2 {
  height: 400px;
  width: 50%;
  float: left;
  background: #fff;
  padding: 30px
}

.corner:after {
  transition: all .3s ease;
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
  position: absolute;
  display: block;
  content: "";
  top: 0;
}

.corner-right:after {
  border-left: 150px solid #eee;
  border-top: 400px solid transparent;
  border-right: 270px solid transparent;
}

.corner-left:after {
  border-right: 150px solid #eee;
  border-top: 400px solid transparent;
  border-left: 270px solid transparent;
  right: 50%;
}
</code>```

Title: Split divs diagonally and responsively

Body:
I need to build the following screenshot, and I can't figure out how to do the angles responsively:

https://imgur.com/a/e9IJV

I tried using pseudo classes to add diagonal edges to a solid-color div.
But this design requires two images side-by-side so that won't work there. Also, the slants have to stay on the same angle through different sections with variable heights. I can't use clip-path because I need to support IE.

Here is my feeble attempt:
https://codepen.io/lsterling03/pen/zPEgaq

As you can see, I am having trouble! Is this design possible? Do you have any advice on how to approach this? Will it require javascript?

UPDATE

I have made a little progress. Here is an updated pen:
https://codepen.io/lsterling03/pen/GOOqmo

I can't get the slant right on the last section, which needs a variable height and width. I tried using javascript, but I don't have the right calculations:

        $(".slant").css('width', $('.main').width() * 0.5 - 100);
        $(".slant").css('border-top-width', $('.main').height());

I also haven't figured out how to do two images in a row yet.

Does anyone have suggestions to fix either of the above issues?

Body:
And, here is another example that you can start to investigate some more: CodePen

body {
  background-color: #00bcd4;
}

div { box-sizing:border-box; }

.row {
  overflow: hidden;
  position: relative;
  width: 100%;
}

.image {
  background: url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg) center center no-repeat #eee;
  background-size: cover;
  height: 400px;
  width: 50%;
  float: right;
}

.image2{
  background: url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg) center center no-repeat #eee;
  background-size: cover;
  height: 400px;
  width: 64.5%;
  float: left;
  -webkit-clip-path: polygon(0 0, 100% 0, 78% 100%, 0% 100%);
  clip-path: polygon(0 0, 100% 0, 78% 100%, 0% 100%);
}

.image3{
  background: url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg) top left no-repeat #eee;
  background-size: cover;
  height: 400px;
  width: 50%;
  float: left;
  -webkit-clip-path: polygon(28% 0, 100% 0, 100% 100%, 0% 100%);
  clip-path: polygon(28% 0, 100% 0, 100% 100%, 0% 100%);
  position: absolute;
  right: 0;
}

.text {
  background-color: #eee;
  padding: 30px;
  position: relative;
  width: 50%;
  float: left;
  height: 400px;
}

.text > div {
  position: relative;
  z-index: 1;
}

.text2 {
  height: 400px;
  width: 50%;
  float: left;
  background: #fff;
  padding: 30px
}

.corner:after {
  transition: all .3s ease;
  -webkit-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
  position: absolute;
  display: block;
  content: "";
  top: 0;
}

.corner-right:after {
  border-left: 150px solid #eee;
  border-top: 400px solid transparent;
  border-right: 270px solid transparent;
}

.corner-left:after {
  border-right: 150px solid #eee;
  border-top: 400px solid transparent;
  border-left: 270px solid transparent;
  right: 50%;
}


问:
How can I erase my data from textarea using javascript?
How can i erase my data from textarea using javascript ?

This code:

```<code><textarea class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>
</code>```

答:
Try giving the textarea an ID</p>

```<code><textarea id="edit-text" class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >aldkasdklad al;kd al;kd la;ksd al;kd l;aksl;dkal;skdl aksdl  </textarea>

document.getElementById("edit-text").value = '';
</code>```

Body:
How can i erase my data from textarea using javascript ?

This code:

<textarea class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >يمكنك إضافة أكثر من بريد إلكتروني. أضف "," بين كل إدخال</textarea>

Body:
Try giving the textarea an ID

<textarea id="edit-text" class="mails" tabindex="1" onfocus="this.className='writing'" onblur="this.className='mails'" onkeypress="this.className='writing'" >aldkasdklad al;kd al;kd la;ksd al;kd l;aksl;dkal;skdl aksdl  </textarea>

document.getElementById("edit-text").value = '';


问:
PostgreSQL: Why psql can't connect to server?
I typed psql and I get this:

```<code>psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
</code>```

I used sudo netstat -nlp | grep 5432 to see the status but nothing showed.
And I searched online, somebody told me to modify pg_hba.conf but I can't locate this file. And I also tried this command sudo ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432. It can't work.

答:
I have encountered a similar issue a couple of times. Normally I just do a fresh installation of PostgreSQL following this tutorial and that solves the problem at the expense of losing data.

I was determined on getting real fix today. Restarting PostgreSQL resolved it on ubuntu. sudo /etc/init.d/postgresql restart

Body:
I typed psql and I get this:

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I used sudo netstat -nlp | grep 5432 to see the status but nothing showed.
And I searched online, somebody told me to modify pg_hba.conf but I can't locate this file. And I also tried this command sudo ln -s /tmp/.s.PGSQL.5432 /var/run/postgresql/.s.PGSQL.5432. It can't work.


问:
Add properties to a complex datatype dynamically
I am working on a class with some properties like below in C#

```<code>public class SummaryDto
    {
        public string Name { get; set; }
        public string  GenericName { get; set; }
        public int Data2012 { get; set; }
        public int Data2013 { get; set; }
        public int Data2014 { get; set; }
        public int Data2015 { get; set; }
        public int Data2016 { get; set; }
        public int Data2017 { get; set; }

    }
</code>```

In the above class the properties Data2012, Data2013 and so on should be added dynamically based on the data in another object which just contains years in it.
May I know a good way to do it?

答:
It sounds like what you want is something like a Dictionary<K, V>.  For example:

```<code>public Dictionary<int, int> Data { get; set; }
</code>```

(And, of course, initialize it to something in the constructor.)

Then to "add a new year" you'd simply add it to the dictionary:

```<code>someObj.Data.Add(2017, someIntValue);
</code>```

Basically, any time you have variables with an incrementing counter in their names, you probably want something like an array, list, dictionary, etc. instead.

Body:
I am working on a class with some properties like below in C#

public class SummaryDto
    {
        public string Name { get; set; }
        public string  GenericName { get; set; }
        public int Data2012 { get; set; }
        public int Data2013 { get; set; }
        public int Data2014 { get; set; }
        public int Data2015 { get; set; }
        public int Data2016 { get; set; }
        public int Data2017 { get; set; }

    }

In the above class the properties Data2012, Data2013 and so on should be added dynamically based on the data in another object which just contains years in it.
May I know a good way to do it?

Body:
It sounds like what you want is something like a Dictionary<K, V>.  For example:

public Dictionary<int, int> Data { get; set; }

(And, of course, initialize it to something in the constructor.)

Then to "add a new year" you'd simply add it to the dictionary:

someObj.Data.Add(2017, someIntValue);

Basically, any time you have variables with an incrementing counter in their names, you probably want something like an array, list, dictionary, etc. instead.


问:
Problems with constant iterators
I'm trying write a tempate function which takes a sequence (by 2 iterators) and calculates the number of permutations of this sequence, in which there are no consecutive identical elements.
Thats what i did

```<code>    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/
</code>```

This code not working if i pass const iterators. What should I change to make it work with const iterators?

答:
This code not working if i pass const iterators. What should I change to make it work with const iterators?

You can't: std::next_permutation() modify the values so is incompatible with const iterators.

-- EDIT --

The OP ask

How can i implement this function in right way?

I suggest you to follows the suggestion from Jarod42: works over a copy.

I propose something as follows

```<code>template <class Container>
size_t count_perm (Container c)  // note: c is a copy
{
    if ( c.cbegin() == c.cend() )
        return 1;

    size_t count = 0U;

    std::sort(c.begin(), c.end());

    if (std::adjacent_find(c.cbegin(), c.cend()) != c.cend()))
     {
       std::size_t ui = c.size();

       for ( count = ui ; --ui > 1 ; count *= ui )
        ;

       // count now is c.size() ! (factorial of)
     }
    else
     {
       while (std::next_permutation(c.begin(), c.end()))
          if (std::adjacent_find(c.cbegin(), c.cend()) != c.cend())
             ++count;
     }

    return count; // remember this return!
}
</code>```

Title: Problems with constant iterators

Body:
I'm trying write a tempate function which takes a sequence (by 2 iterators) and calculates the number of permutations of this sequence, in which there are no consecutive identical elements.
Thats what i did

    template<class Iterator>
    size_t count_perm(Iterator p, Iterator q)
    {
        if (p == q)
            return 1;
        size_t count = 0;
        while(std::next_permutation(p, q)){
              if(std::adjacent_find(p,q) != q)
              ++count;
        }
    }
/*Example

std::array<int, 3> a1 = {1,2,3};
size_t c1 = count_perm(a1.begin(), a1.end()); // 6

std::array<int, 5> a2 = {1,2,3,4,4};
size_t c2 = count_perm(a2.begin(), a2.end()); // 36*/

This code not working if i pass const iterators. What should I change to make it work with const iterators?

Body:
This code not working if i pass const iterators. What should I change to make it work with const iterators?

You can't: std::next_permutation() modify the values so is incompatible with const iterators.

-- EDIT --

The OP ask

How can i implement this function in right way?

I suggest you to follows the suggestion from Jarod42: works over a copy.

I propose something as follows

template <class Container>
size_t count_perm (Container c)  // note: c is a copy
{
    if ( c.cbegin() == c.cend() )
        return 1;

    size_t count = 0U;

    std::sort(c.begin(), c.end());

    if (std::adjacent_find(c.cbegin(), c.cend()) != c.cend()))
     {
       std::size_t ui = c.size();

       for ( count = ui ; --ui > 1 ; count *= ui )
        ;

       // count now is c.size() ! (factorial of)
     }
    else
     {
       while (std::next_permutation(c.begin(), c.end()))
          if (std::adjacent_find(c.cbegin(), c.cend()) != c.cend())
             ++count;
     }

    return count; // remember this return!
}


问:
Pandas DataFrame slicing with iteration
I would like to perform some action on sliced DataFrame with multiple slice indexes. The pattern is df.iloc[0:24] , df.iloc[24:48], df.iloc[48:72] and so on with step 24 as you get it. How I can iterate it without to set it manually every time. More like df.iloc[x:z] and each iteration x=0, z=24 and next iteration with 24 step, x will be 24 and z=48 and so on.
Thanks in advance,
Hristo.</p>

答:
for loop iteration

```<code>for i in range(0, len(df), 24):
    slc = df.iloc[i : i + 24]
</code>```

groupby

```<code>df.groupby(df.index // 24 * 24).apply(your_function)
</code>```

Title: Pandas DataFrame slicing with iteration

Body:
for loop iteration

for i in range(0, len(df), 24):
    slc = df.iloc[i : i + 24]

groupby

df.groupby(df.index // 24 * 24).apply(your_function)


答:
Use a dictionary instead:

```<code>public class SummaryDto
{
    public string Name { get; set; }
    public string  GenericName { get; set; }
    public Dictionary<int, int> Data { get; } = new Dictionary<int, int>();
}
</code>```

Then set the data like this:

```<code>summaryDto.Data[2017] = 1;
</code>```

And read it like this:

```<code>int value = summaryDto.Data[2017];
</code>```

Or if you are not sure there is an entry for that year:

```<code>if (summaryDto.Data.TryGetValue(2017, out int value))
{
    // use value
}
</code>```

Title: Add properties to a complex datatype dynamically

Body:
Use a dictionary instead:

public class SummaryDto
{
    public string Name { get; set; }
    public string  GenericName { get; set; }
    public Dictionary<int, int> Data { get; } = new Dictionary<int, int>();
}

Then set the data like this:

summaryDto.Data[2017] = 1;

And read it like this:

int value = summaryDto.Data[2017];

Or if you are not sure there is an entry for that year:

if (summaryDto.Data.TryGetValue(2017, out int value))
{
    // use value
}


问:
android detect Samsung Galaxy S8 navigation bar hide or show programmatically
On some devices such as Samsung S8, navigation bar can be hide or show, that's a question in some condition.
Samsung S8's navigation bar can be hide or show by click left bottom button

I didn't find straight way to determine even if in the Android sources code.

And I google some issues, such as A good solution to check for navigation bar  , but it doesn't help.

Any help is very appreciated.

答:
Use this method, worked for me. Make sure the view has been rendered first to make sure that getHeight() doesn't return 0. Also make sure that the rootView you are using is meant to take up the whole screen.</p>

```<code>public static boolean hasNavBar (Activity activity, View rootView) {
    if (activity == null || rootView == null)
        return true;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        return true;

    Display d = activity.getWindowManager().getDefaultDisplay();
    DisplayMetrics realDisplayMetrics = new DisplayMetrics();
    d.getRealMetrics(realDisplayMetrics);

    int viewHeight = rootView.getHeight();
    if (viewHeight == 0)
        return true;

    int realHeight = realDisplayMetrics.heightPixels;
    return realHeight != viewHeight;
}
</code>```

Body:
Use this method, worked for me. Make sure the view has been rendered first to make sure that getHeight() doesn't return 0. Also make sure that the rootView you are using is meant to take up the whole screen.

public static boolean hasNavBar (Activity activity, View rootView) {
    if (activity == null || rootView == null)
        return true;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1)
        return true;

    Display d = activity.getWindowManager().getDefaultDisplay();
    DisplayMetrics realDisplayMetrics = new DisplayMetrics();
    d.getRealMetrics(realDisplayMetrics);

    int viewHeight = rootView.getHeight();
    if (viewHeight == 0)
        return true;

    int realHeight = realDisplayMetrics.heightPixels;
    return realHeight != viewHeight;
}


问:
$(document).scrollTop() always returns 0
I'm simply trying to do something once the scroll position of the page reaches a certain height. However scrollTop() is returning 0 or null no matter how far down I scroll. This is the help function I'm using to check the scrollTop() value:

```<code>$('body').click(function(){
    var scrollPost = $(document).scrollTop();
    alert(scrollPost);
});
</code>```

I've tried attaching scrollTop() to $('body'), $('html') and of course $(window), but nothing changes.

Any ideas?

答:
Removing height: 100%; from html and body tags can resolve the issue.

The reason is that you might have set 100% as value of height property of html and body elements. If you set the height property of html and body elements to 100%, they get height equal to document’s height.

Body:
I'm simply trying to do something once the scroll position of the page reaches a certain height. However scrollTop() is returning 0 or null no matter how far down I scroll. This is the help function I'm using to check the scrollTop() value:

$('body').click(function(){
    var scrollPost = $(document).scrollTop();
    alert(scrollPost);
});

I've tried attaching scrollTop() to $('body'), $('html') and of course $(window), but nothing changes.

Any ideas?


答:
```<code>public class SummaryDto
{
    public string Name {get; set;};
    public string GenericName {get; set; }
    public Dictionary<int,int> Data {get; } = new Dictionry<int,int>();
}
</code>```

And add data for a year like

```<code>void SetYear(int year, int n)
{
    var s = new SummaryDto();
    s.Data[year] = n;
}
</code>```

If you don't want a list because you have some restriction on how data is returned, wrap the list in its own class:

```<code>class YearData
{
    List<int, int> _data = new List<int, int>();

    public int GetYearData(int year)
    {
        AssertYearValid(year);
        return _data[year];
    }

    public void SetYearData(int year, int number)
    {
        AssertYearValid(year);
        AssertYearNumberValid(number);
        _data[year] = number;
    }

    private void AssertYearValid(int year)
    {
        if (year < 1900 || year > 2900)
        {
            throw new ArgumentException("Year is not valid.");
        }
    }
}

public class SummaryDto
{
    public string Name {get; set;};
    public string GenericName {get; set; }
    public YearData Data {get; } = new YearData();
}
</code>```

and set with

```<code>var s = new SummaryDto();
s.SetYearData(2001, 100);
</code>```

Body:
public class SummaryDto
{
    public string Name {get; set;};
    public string GenericName {get; set; }
    public Dictionary<int,int> Data {get; } = new Dictionry<int,int>();
}

And add data for a year like

void SetYear(int year, int n)
{
    var s = new SummaryDto();
    s.Data[year] = n;
}

If you don't want a list because you have some restriction on how data is returned, wrap the list in its own class:

class YearData
{
    List<int, int> _data = new List<int, int>();

    public int GetYearData(int year)
    {
        AssertYearValid(year);
        return _data[year];
    }

    public void SetYearData(int year, int number)
    {
        AssertYearValid(year);
        AssertYearNumberValid(number);
        _data[year] = number;
    }

    private void AssertYearValid(int year)
    {
        if (year < 1900 || year > 2900)
        {
            throw new ArgumentException("Year is not valid.");
        }
    }
}

public class SummaryDto
{
    public string Name {get; set;};
    public string GenericName {get; set; }
    public YearData Data {get; } = new YearData();
}

and set with

var s = new SummaryDto();
s.SetYearData(2001, 100);


问:
Dynamically assigning object keys results in last key being contained with double quotes
I've created a CSV parser and have run into an interesting situation. When the onLoad function is hit, the last key of my object row is double quoted. I'm looking for an explanation of why. Anyone know?

Comments contains sample values

```<code>const results = [];
const lines = reader.result.split('\n');
//lines = ["accountId,nickname,rando", "test-arn,test-nickname,test-rando"]
const keys = lines[0].split(',');
//keys = ["accountId", "nickname", "rando"]

forEach((line) => {
    // line = "test-arn, test-nickname, test-rando"
    const values = line.split(',');
    // values = ["test-arn", "test-nickname", "test-rando"]
    const row = {};

    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        row[key] = values[i];
    }

    //row = { accountId: "test-arn", nickname="test-nickname", "rando": "test-rando"}
    results.push(row);
}, lines);
</code>```

You can see that the key rando inside row is surrounded by double quotes

```<code>row = {
    accountId: "test-arn",
    nickname: "test-nickname",
    "rando": "test-rando",
}
</code>```

Sample CSV

```<code>accountId,nickname,rando^M
test-arn,test-nickname,test-rando^M
</code>```

Full Function

```<code>const parseCsv = ({ file, before, onSuccess, onError }) => {
    before();
    const reader = new FileReader();

    reader.readAsText(file);
    reader.onload = () => {
        const results = [];
        const lines = reader.result.split('\n');
        const keys = lines[0].split(',');

        forEach((line) => {
            const values = line.split(',');
            const row = {};

            for (let i = 0; i < keys.length; i++) {
                let key = keys[i];
                row[key] = values[i];
            }
            results.push(row);
        }, lines);

        onSuccess(results);
    };

    reader.onError = (error) => {
        onError(error);
    };
};
</code>```

答:
I've found that there is a return character being left in the last key.

In the console:

```<code>keys
>(3) ["accountId", "nickname", "rando"]
JSON.strigify(keys)
>"["accountId","nickname","rando\r"]"
</code>```

Resolution is to remove the return character

```<code>const results = [];
const lines = reader.result.split('\n');
const header = lines.shift().replace(/(\r\n|\n|\r)/gm, ''); //Remove newline characters
const keys = header.split(',');

forEach((line) => {
    const values = line.replace(/(\r\n|\n|\r)/gm, '').split(',');
    const row = {};

    for (let i = 0; i < keys.length; i++) {
        row[keys[i]] = values[i];
    }

    results.push(row);
}, lines);

onSuccess(results);
</code>```

Body:
I've created a CSV parser and have run into an interesting situation. When the onLoad function is hit, the last key of my object row is double quoted. I'm looking for an explanation of why. Anyone know?

Comments contains sample values

const results = [];
const lines = reader.result.split('\n');
//lines = ["accountId,nickname,rando", "test-arn,test-nickname,test-rando"]
const keys = lines[0].split(',');
//keys = ["accountId", "nickname", "rando"]

forEach((line) => {
    // line = "test-arn, test-nickname, test-rando"
    const values = line.split(',');
    // values = ["test-arn", "test-nickname", "test-rando"]
    const row = {};

    for (let i = 0; i < keys.length; i++) {
        let key = keys[i];
        row[key] = values[i];
    }

    //row = { accountId: "test-arn", nickname="test-nickname", "rando": "test-rando"}
    results.push(row);
}, lines);

You can see that the key rando inside row is surrounded by double quotes

row = {
    accountId: "test-arn",
    nickname: "test-nickname",
    "rando": "test-rando",
}

Sample CSV

accountId,nickname,rando^M
test-arn,test-nickname,test-rando^M

Full Function

const parseCsv = ({ file, before, onSuccess, onError }) => {
    before();
    const reader = new FileReader();

    reader.readAsText(file);
    reader.onload = () => {
        const results = [];
        const lines = reader.result.split('\n');
        const keys = lines[0].split(',');

        forEach((line) => {
            const values = line.split(',');
            const row = {};

            for (let i = 0; i < keys.length; i++) {
                let key = keys[i];
                row[key] = values[i];
            }
            results.push(row);
        }, lines);

        onSuccess(results);
    };

    reader.onError = (error) => {
        onError(error);
    };
};

Body:
I've found that there is a return character being left in the last key.

In the console:

keys
>(3) ["accountId", "nickname", "rando"]
JSON.strigify(keys)
>"["accountId","nickname","rando\r"]"

Resolution is to remove the return character

const results = [];
const lines = reader.result.split('\n');
const header = lines.shift().replace(/(\r\n|\n|\r)/gm, ''); //Remove newline characters
const keys = header.split(',');

forEach((line) => {
    const values = line.replace(/(\r\n|\n|\r)/gm, '').split(',');
    const row = {};

    for (let i = 0; i < keys.length; i++) {
        row[keys[i]] = values[i];
    }

    results.push(row);
}, lines);

onSuccess(results);


问:
Background color does not cover entire -element when hovered
I am currently coding a navigation bar where when the links are hovered, the background-color of the -element changes. Currently, the background-color in the navigation bar's dropdown menu does not cover the entire "box".

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: black;
}

ul li {
  display: inline-block;
  position: relative;
  background-color: black;
}

ul li a {
  display: block;
  color: white;
  text-decoration: none;
  text-align: center;
  margin: -left:0;
  padding: 15px 25px;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

ul li a:hover {
  background-color: #333;
}

ul li ul#dropdowncontent {
  display: inline-block;
  position: absolute;
  text-align: center;
  min-width: 100%;
  font-size: 70%;
  z-index: 999;
  width: 90px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Produkter
    <ul id="dropdowncontent">
      <li>Moderkort</li>
      <li>Processorer</li>
      <li>Hårddiskar</li>
      <li>Grafikkort</li>
    </ul>
  </li>
  <li>Butiker</li>
  <li>Kontakt</li>
  <li>Vanliga frågor</li>
</ul></code>```

You can also take a look at the code in this Jsfiddle: https://jsfiddle.net/fdvcmnx6/

答:
Set your dropdown list items to display: block.

```<code>#dropdowncontent li {
    display: block;
}
</code>```

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: black;
}

ul li {
  display: inline-block;
  position: relative;
  background-color: black;
}

ul li a {
  display: block;
  color: white;
  text-decoration: none;
  text-align: center;
  margin: -left:0;
  padding: 15px 25px;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

ul li a:hover {
  background-color: #333;
}

ul li ul#dropdowncontent {
  display: inline-block;
  position: absolute;
  text-align: center;
  min-width: 100%;
  font-size: 70%;
  z-index: 999;
  width: 90px;
}

/* Additional */

#dropdowncontent li {
    display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Produkter
    <ul id="dropdowncontent">
      <li>Moderkort</li>
      <li>Processorer</li>
      <li>Hårddiskar</li>
      <li>Grafikkort</li>
    </ul>
  </li>
  <li>Butiker</li>
  <li>Kontakt</li>
  <li>Vanliga frågor</li>
</ul></code>```

Title: Background color does not cover entire <a>-element when hovered

Body:
I am currently coding a navigation bar where when the links are hovered, the background-color of the -element changes. Currently, the background-color in the navigation bar's dropdown menu does not cover the entire "box".

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: black;
}

ul li {
  display: inline-block;
  position: relative;
  background-color: black;
}

ul li a {
  display: block;
  color: white;
  text-decoration: none;
  text-align: center;
  margin: -left:0;
  padding: 15px 25px;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

ul li a:hover {
  background-color: #333;
}

ul li ul#dropdowncontent {
  display: inline-block;
  position: absolute;
  text-align: center;
  min-width: 100%;
  font-size: 70%;
  z-index: 999;
  width: 90px;
}

Produkter

Moderkort

Processorer

Hårddiskar

Grafikkort

Butiker

Kontakt

Vanliga frågor

You can also take a look at the code in this Jsfiddle: https://jsfiddle.net/fdvcmnx6/

Body:
Set your dropdown list items to display: block.

#dropdowncontent li {
    display: block;
}

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: black;
}

ul li {
  display: inline-block;
  position: relative;
  background-color: black;
}

ul li a {
  display: block;
  color: white;
  text-decoration: none;
  text-align: center;
  margin: -left:0;
  padding: 15px 25px;
  -webkit-transition-duration: 0.4s;
  transition-duration: 0.4s;
}

ul li a:hover {
  background-color: #333;
}

ul li ul#dropdowncontent {
  display: inline-block;
  position: absolute;
  text-align: center;
  min-width: 100%;
  font-size: 70%;
  z-index: 999;
  width: 90px;
}

/* Additional */

#dropdowncontent li {
    display: block;
}

<ul>
  <li><a href="#">Produkter</a>
    <ul id="dropdowncontent">
      <li><a href="#">Moderkort</a></li>
      <li><a href="#">Processorer</a></li>
      <li><a href="#">Hårddiskar</a></li>
      <li><a href="#">Grafikkort</a></li>
    </ul>
  </li>
  <li><a href="#">Butiker</a></li>
  <li><a href="#">Kontakt</a></li>
  <li><a href="#">Vanliga frågor</a></li>
</ul>


问:
R Find all replies to a user's tweets from their follower list
I'm trying to find out the number of replies for all given tweets by a user. This is not something avaiable directly from Twitter's API. I've decided to only go after replies from a user's followers, to help distill down the data generated and as a good approximation (I believe msot of the replies to a tweet will come directly from that users followers.

I believe I've come a long way already, I jsut need help with the final section. I'm struggling to make the function I've created run over all the followers.

I'd rather this solution be in R over Python, although I know this exists and will be an option. I've also put in the twitter tag for Donald Trump; I'm not trying to do it for him and know that his huge following will make this a challenge. I want a generic version useable for whichever user is inputted.

```<code>library(rtweet)
library(plyr)
library(dplyr)

##set name of tweeter to look at (this can be changed)
targettwittername <- "realDonaldTrump"

##get this tweeter's timeline
tmls <- get_timeline(targettwittername, n=3200, retryonratelimit=TRUE)
##get their user id
targettwitteruserid <- as.numeric(select(lookup_users(targettwittername), user_id))
##get ids of their tweets
tweetids <- select(tmls, status_id)
tweetids <- transform(tweetids, status_id_num=as.numeric(status_id))

##get list of followers (who are most likely to reply)
targetfollowers <- data.frame(get_followers(targettwittername))

##clean up follower list to exclude those that have never tweeted and restricted access
user_lookup <- lookup_users(targetfollowers)
users_with_tweets_and_unprotected <- filter(user_lookup, statuses_count != 0)
users_with_tweets_and_unprotected <- select(filter(users_with_tweets_and_unprotected, protected != "TRUE"), user_id)

targetfollowers <- filter(targetfollowers, user_id %in% users_with_tweets_and_unprotected$user_id)

##custom function to search all followers timelines one by one
getfollowersreplies <- function(x){
  follower <- as.numeric(x[1])
  followertl <- data.frame(get_timeline(follower, n=3200, retryonratelimit=TRUE))
  followertl <- filter(followertl, in_reply_to_status_user_id == targettwitteruserid)
  followertl <- transform(followertl, reply_to_status_id_num=as.numeric(in_reply_to_status_status_id))
  join <- inner_join(followertl, tweetids, by=c("reply_to_status_id_num"="status_id_num"))
  replycounts <- data.frame(
                  join %>%
                    group_by(user_id, reply_to_status_id_num) %>%
                    summarise(n=n())
                  )
  return(replycounts)
}

tweet_replies <- do.call("rbind", lapply(targetfollowers$user_id, getfollowersreplies))
</code>```

答:
The biggest obstacle would be the time it takes to collect up to 3,200 of the most recent tweets posted by more than 42 million followers of @realDonaldTrump.

```<code>> djt <- lookup_users(targettwittername)
> djt[, c("screen_name", "followers_count", "friends_count", "statuses_count")]
# A tibble: 1 x 4
      screen_name followers_count friends_count statuses_count
            <chr>           <int>         <int>          <int>
1 realDonaldTrump        42793758            45          36398
</code>```

Twitter limits the number of follower user IDs collected to 75,000 every 15 minutes.

```<code>flw <- get_followers("realDonaldTrump", n = 75000)
> flw
# A tibble: 75,000 x 1
              user_id
                <chr>
 1          928808378
 2 926186565231136768
 3 931237514253426688
 4 930584682701475842
 5 902580952165216256
 6 931236663950372864
 7 931237367024820224
 8 922140807024578560
 9 931235142047211520
10 931235653412708352
# ... with 74,990 more rows
</code>```

Assuming you have a reliable internet connection and time, then you can use the following code to get all 42 million follower IDs.

```<code>flw <- get_followers(
  "realDonaldTrump", n = 42793758, retryonratelimit = TRUE
)
</code>```

Then you'd probably want to construct a for loop that uses get_timeline() and handles API rate limits. In the example code below, I've made the loop sleep until the rate limit reset after every 56 calls.

```<code>flw_tml <- vector("list", length(flw$user_id))
for (i in seq_along(flw$user_id)) {
  flw_tml[[i]] <- get_timeline(
    flw$user_id[i], n = 3200
  )
  if (i %% 56 == 0L) {
    rl <- rate_limit("get_timeline")
    Sys.sleep(as.numeric(rl$reset, "secs"))
  }
  cat(i, " ")
}
</code>```

As you can see, this would take a really long time. You'd be better off trying to collect all the replies in the past 6-9 days. The code below gets up to 5 million replies to Trump's tweets from the past 9 days. Warning: if there are actually that many replies (I honestly have no idea) available from the past 9 days, this search would take just under three days to finish.

```<code>at_rdt <- search_tweets(
  "to:realdonaldtrump",
  n = 5e6,
   retryonratelimit = TRUE
)
</code>```

Body:
I'm trying to find out the number of replies for all given tweets by a user. This is not something avaiable directly from Twitter's API. I've decided to only go after replies from a user's followers, to help distill down the data generated and as a good approximation (I believe msot of the replies to a tweet will come directly from that users followers.

I believe I've come a long way already, I jsut need help with the final section. I'm struggling to make the function I've created run over all the followers.

I'd rather this solution be in R over Python, although I know this exists and will be an option. I've also put in the twitter tag for Donald Trump; I'm not trying to do it for him and know that his huge following will make this a challenge. I want a generic version useable for whichever user is inputted.

library(rtweet)
library(plyr)
library(dplyr)

##set name of tweeter to look at (this can be changed)
targettwittername <- "realDonaldTrump"

##get this tweeter's timeline
tmls <- get_timeline(targettwittername, n=3200, retryonratelimit=TRUE)
##get their user id
targettwitteruserid <- as.numeric(select(lookup_users(targettwittername), user_id))
##get ids of their tweets
tweetids <- select(tmls, status_id)
tweetids <- transform(tweetids, status_id_num=as.numeric(status_id))

##get list of followers (who are most likely to reply)
targetfollowers <- data.frame(get_followers(targettwittername))

##clean up follower list to exclude those that have never tweeted and restricted access
user_lookup <- lookup_users(targetfollowers)
users_with_tweets_and_unprotected <- filter(user_lookup, statuses_count != 0)
users_with_tweets_and_unprotected <- select(filter(users_with_tweets_and_unprotected, protected != "TRUE"), user_id)

targetfollowers <- filter(targetfollowers, user_id %in% users_with_tweets_and_unprotected$user_id)

##custom function to search all followers timelines one by one
getfollowersreplies <- function(x){
  follower <- as.numeric(x[1])
  followertl <- data.frame(get_timeline(follower, n=3200, retryonratelimit=TRUE))
  followertl <- filter(followertl, in_reply_to_status_user_id == targettwitteruserid)
  followertl <- transform(followertl, reply_to_status_id_num=as.numeric(in_reply_to_status_status_id))
  join <- inner_join(followertl, tweetids, by=c("reply_to_status_id_num"="status_id_num"))
  replycounts <- data.frame(
                  join %>%
                    group_by(user_id, reply_to_status_id_num) %>%
                    summarise(n=n())
                  )
  return(replycounts)
}

tweet_replies <- do.call("rbind", lapply(targetfollowers$user_id, getfollowersreplies))

Body:
The biggest obstacle would be the time it takes to collect up to 3,200 of the most recent tweets posted by more than 42 million followers of @realDonaldTrump.

> djt <- lookup_users(targettwittername)
> djt[, c("screen_name", "followers_count", "friends_count", "statuses_count")]
# A tibble: 1 x 4
      screen_name followers_count friends_count statuses_count
            <chr>           <int>         <int>          <int>
1 realDonaldTrump        42793758            45          36398

Twitter limits the number of follower user IDs collected to 75,000 every 15 minutes.

flw <- get_followers("realDonaldTrump", n = 75000)
> flw
# A tibble: 75,000 x 1
              user_id
                <chr>
 1          928808378
 2 926186565231136768
 3 931237514253426688
 4 930584682701475842
 5 902580952165216256
 6 931236663950372864
 7 931237367024820224
 8 922140807024578560
 9 931235142047211520
10 931235653412708352
# ... with 74,990 more rows

Assuming you have a reliable internet connection and time, then you can use the following code to get all 42 million follower IDs.

flw <- get_followers(
  "realDonaldTrump", n = 42793758, retryonratelimit = TRUE
)

Then you'd probably want to construct a for loop that uses get_timeline() and handles API rate limits. In the example code below, I've made the loop sleep until the rate limit reset after every 56 calls.

flw_tml <- vector("list", length(flw$user_id))
for (i in seq_along(flw$user_id)) {
  flw_tml[[i]] <- get_timeline(
    flw$user_id[i], n = 3200
  )
  if (i %% 56 == 0L) {
    rl <- rate_limit("get_timeline")
    Sys.sleep(as.numeric(rl$reset, "secs"))
  }
  cat(i, " ")
}

As you can see, this would take a really long time. You'd be better off trying to collect all the replies in the past 6-9 days. The code below gets up to 5 million replies to Trump's tweets from the past 9 days. Warning: if there are actually that many replies (I honestly have no idea) available from the past 9 days, this search would take just under three days to finish.

at_rdt <- search_tweets(
  "to:realdonaldtrump",
  n = 5e6,
   retryonratelimit = TRUE
)


问:
Is there a 'SHOW CREATE TABLE' for another query
I know SHOW CREATE TABLE gives you the script in order to create a table based on an existing table but I would like to get the script for the return of a query.

Example : I have lots of really long and complex queries, but now I would like to create tables for what these queries fetch.

Is there a way to do this?

答:
To get the creation script, you can put the results of your query into a temporary table, then use SHOW CREATE TABLE:

```<code>CREATE TEMPORARY TABLE query1 AS
    SELECT * FROM YourQuery
    LIMIT 0; --Add LIMIT 0 to avoid putting all the data into the table TY Bill Karwin

SHOW CREATE TABLE query1;
</code>```

If you can access the end destination for the table (and you want the results included), you can skip a step and just use CREATE..SELECT:

```<code>CREATE TABLE permanent1 AS
    SELECT * FROM YourQuery;
</code>```

Body:
To get the creation script, you can put the results of your query into a temporary table, then use SHOW CREATE TABLE:

CREATE TEMPORARY TABLE query1 AS
    SELECT * FROM YourQuery
    LIMIT 0; --Add LIMIT 0 to avoid putting all the data into the table TY Bill Karwin

SHOW CREATE TABLE query1;

If you can access the end destination for the table (and you want the results included), you can skip a step and just use CREATE..SELECT:

CREATE TABLE permanent1 AS
    SELECT * FROM YourQuery;


问:
How do I add csv file data into a dictionary
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

```<code>ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30
</code>```

For example if I called the ID: "12345" it would display - Italy, 100, 80

答:
First let's create the file:

```<code>with open("test.csv", "w") as f:
        f.write("""\
ID,Tour,Start,End
12345,Italy,100,80
13579,China,50,30
24680,France,50,30""")
</code>```

If you are going to work with Python and tables I recommend pandas. Here is a one-liner:

```<code>import pandas as pd

d = pd.read_csv("test.csv",sep=",").set_index('ID').to_dict(orient='i')
</code>```

d returns

```<code>{12345: {'End': 80, 'Start': 100, 'Tour': 'Italy'},
 13579: {'End': 30, 'Start': 50, 'Tour': 'China'},
 24680: {'End': 30, 'Start': 50, 'Tour': 'France'}}
</code>```

Or maybe:

```<code>import pandas as pd

df = pd.read_csv("test.csv",sep=",").set_index('ID')
d = dict(zip(df.index,df.values.tolist()))
</code>```

d returns

```<code>{12345: ['Italy', 100, 80],
 13579: ['China', 50, 30],
 24680: ['France', 50, 30]}
</code>```

Body:
me very new in programming, how do I make a dictionary that calls the Tour ID and displays the given info.(Tour, Start, End)

Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30

For example if I called the ID: "12345" it would display - Italy, 100, 80

Body:
First let's create the file:

with open("test.csv", "w") as f:
        f.write("""\
ID,Tour,Start,End
12345,Italy,100,80
13579,China,50,30
24680,France,50,30""")

If you are going to work with Python and tables I recommend pandas. Here is a one-liner:

import pandas as pd

d = pd.read_csv("test.csv",sep=",").set_index('ID').to_dict(orient='i')

d returns

{12345: {'End': 80, 'Start': 100, 'Tour': 'Italy'},
 13579: {'End': 30, 'Start': 50, 'Tour': 'China'},
 24680: {'End': 30, 'Start': 50, 'Tour': 'France'}}

Or maybe:

import pandas as pd

df = pd.read_csv("test.csv",sep=",").set_index('ID')
d = dict(zip(df.index,df.values.tolist()))

d returns

{12345: ['Italy', 100, 80],
 13579: ['China', 50, 30],
 24680: ['France', 50, 30]}


问:
GsonBuilder setPrettyPrinting doesn't print pretty
I'm using the following code (found on this webpage) and the Gson library (2.8.2) to format JSON code with pretty printing.

```<code>import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonExample {
    public static void main(String[] args) {
      String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String json = gson.toJson(jsonData);

      System.out.println(json);
    }
}
</code>```

This is the expected result:

```<code>{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}
</code>```

Unfortunately "pretty printing" doesn't work at all and I get everything in one line:

```<code>{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}"
</code>```

Any ideas what I'm doing wrong?

答:
nickb made my day! :-)

The correct code must look like this:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;

public class GsonExample {
    public static void main(String[] args) {
        String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";
        JsonElement jsonElement = new JsonParser().parse(jsonData);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(jsonElement);

        System.out.println(json);
    }
}
```
<p>Output:</p>
<pre class="lang-json prettyprint-override"><code>{
    "name": "mkyong",
    "age": 35,
    "position": "Founder",
    "salary": 10000,
    "skills": [
        "java",
        "python",
        "shell"
    ]
}
</code>```

Body:
I'm using the following code (found on this webpage) and the Gson library (2.8.2) to format JSON code with pretty printing.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonExample {
    public static void main(String[] args) {
      String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";

      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String json = gson.toJson(jsonData);

      System.out.println(json);
    }
}

This is the expected result:

{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

Unfortunately "pretty printing" doesn't work at all and I get everything in one line:

{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}"

Any ideas what I'm doing wrong?

Body:
nickb made my day! :-)

The correct code must look like this:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParser;
import com.google.gson.JsonElement;

public class GsonExample {
    public static void main(String[] args) {
        String jsonData = "{\"name\":\"mkyong\",\"age\":35,\"position\":\"Founder\",\"salary\":10000,\"skills\":[\"java\",\"python\",\"shell\"]}";
        JsonElement jsonElement = new JsonParser().parse(jsonData);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(jsonElement);

        System.out.println(json);
    }
}

Output:

{
    "name": "mkyong",
    "age": 35,
    "position": "Founder",
    "salary": 10000,
    "skills": [
        "java",
        "python",
        "shell"
    ]
}


问:
Accessing GAE log files using Google Cloud Logging (Python)
We have a running Google App Engine (GAE) service for which we would like to download the logs for archival on our server.

The GAE has a Service Account, the Credentials for which have been downloaded as a JSON file to our server. The following code, run on our server, attempts to create a client for the logging service:

```<code>from google.cloud import logging
client = logging.Client.from_service_account_json('credentials.json')
</code>```

with the result:

```<code>ValueError: Service account info was not in the expected format, missing fields token_uri, client_email.
</code>```

The error message is quite clear, but what is not clear is why the fields are expected in a JSON file that was created for this purpose? Are we using the credentials from the wrong type of Service account?

答:
You need to get the service account file that contains the private key credentials, it's basically a different file from the one you have.
You can get it, or get a new one by going to https://console.developers.google.com/iam-admin/iam/ then select your project, then select "Service accounts" and create a new one as role "viewer" for the project for example (or use one that already exists and click "create new key")

The "key" is a json or p12 file that will be downloaded when you create the account (or use "create new key" there) which contains the correct fields and credentials that will work for your code.

Example structure of the downloaded "key" file (when selecting JSON):

```<code>{
  "type": "service_account",
  "project_id": "zeta-handler-9999",
  "private_key_id": "123456789deedbeaf",
  "private_key": "-----BEGIN PRIVATE KEY-----\nREDACTED REDACTED...-----END PRIVATE KEY-----\n",
  "client_email": "projectname-service-account@zeta-handler-9999.iam.gserviceaccount.com",
  "client_id": "12345678909999",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/projectname-service-account%40zeta-handler-9999.iam.gserviceaccount.com"
}
</code>```

Example code to use that "key" file (python):

```<code>#!/usr/bin/env python
import google.auth
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('downloaded_key.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive.metadata.readonly'])
</code>```

Body:
We have a running Google App Engine (GAE) service for which we would like to download the logs for archival on our server.

The GAE has a Service Account, the Credentials for which have been downloaded as a JSON file to our server. The following code, run on our server, attempts to create a client for the logging service:

from google.cloud import logging
client = logging.Client.from_service_account_json('credentials.json')

with the result:

ValueError: Service account info was not in the expected format, missing fields token_uri, client_email.

The error message is quite clear, but what is not clear is why the fields are expected in a JSON file that was created for this purpose? Are we using the credentials from the wrong type of Service account?

Body:
You need to get the service account file that contains the private key credentials, it's basically a different file from the one you have.
You can get it, or get a new one by going to https://console.developers.google.com/iam-admin/iam/ then select your project, then select "Service accounts" and create a new one as role "viewer" for the project for example (or use one that already exists and click "create new key")

The "key" is a json or p12 file that will be downloaded when you create the account (or use "create new key" there) which contains the correct fields and credentials that will work for your code.

Example structure of the downloaded "key" file (when selecting JSON):

{
  "type": "service_account",
  "project_id": "zeta-handler-9999",
  "private_key_id": "123456789deedbeaf",
  "private_key": "-----BEGIN PRIVATE KEY-----\nREDACTED REDACTED...-----END PRIVATE KEY-----\n",
  "client_email": "projectname-service-account@zeta-handler-9999.iam.gserviceaccount.com",
  "client_id": "12345678909999",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/projectname-service-account%40zeta-handler-9999.iam.gserviceaccount.com"
}

Example code to use that "key" file (python):

#!/usr/bin/env python
import google.auth
from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('downloaded_key.json')
scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive.metadata.readonly'])


问:
Filtering the Array Object by Matching SubObject values
I have an array of objects:

```<code>sampledata = [{
    "id": 1,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 1"
    },
    "energy": -145.9,
    "pv": 83.72
}, {
    "id2": 2,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 2"
    },
    "energy": -145.9,
    "pv": 83.72
}];
</code>```

I want to get some of the object's attributes if that object's parameter value matches a given input.

I have tried:

```<code>let x={Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}
return this.sampledata.filter(data=> data['parameter']===x)
</code>```

Based on the matching parameter object I want to return energy and pv attribute from the array object.
Result:

```<code>{
 "energy": -145.9,
  "pv": 83.72
}
</code>```

Can anyone suggest how I can filter my data?

答:
Inside the filter method,use array#every to compare each value of sampedata and x and then use array#map to get pv and energy

const sampledata = [{ "id": 1, "parameter": { "Num_Of_Floors":"2", "East":"10", "Window_Type":"Window Type 1" }, "energy": -145.9, "pv": 83.72 }, { "id2": 2, "parameter": { "Num_Of_Floors":"2", "East":"10", "Window_Type":"Window Type 2" }, "energy": -145.9, "pv": 83.72
}];

let x= { Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}

var result = sampledata
              .filter(obj => Object
                .keys(obj.parameter)
                .every(k => obj.parameter[k] === x[k]))
              .map(({energy,pv}) => ({energy,pv}));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array of objects:

sampledata = [{
    "id": 1,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 1"
    },
    "energy": -145.9,
    "pv": 83.72
}, {
    "id2": 2,
    "parameter": {
        "Num_Of_Floors":"2",
        "East":"10",
        "Window_Type":"Window Type 2"
    },
    "energy": -145.9,
    "pv": 83.72
}];

I want to get some of the object's attributes if that object's parameter value matches a given input.

I have tried:

let x={Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}
return this.sampledata.filter(data=> data['parameter']===x)

Based on the matching parameter object I want to return energy and pv attribute from the array object.
Result:

{
 "energy": -145.9,
  "pv": 83.72
}

Can anyone suggest how I can filter my data?

Body:
Inside the filter method,use array#every to compare each value of sampedata and x and then use array#map to get pv and energy

const sampledata = [{ "id": 1, "parameter": { "Num_Of_Floors":"2", "East":"10", "Window_Type":"Window Type 1" }, "energy": -145.9, "pv": 83.72 }, { "id2": 2, "parameter": { "Num_Of_Floors":"2", "East":"10", "Window_Type":"Window Type 2" }, "energy": -145.9, "pv": 83.72
}];

let x= { Num_Of_Floors: "2", East: "10", Window_Type: "Window Type 1"}

var result = sampledata
              .filter(obj => Object
                .keys(obj.parameter)
                .every(k => obj.parameter[k] === x[k]))
              .map(({energy,pv}) => ({energy,pv}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Rails: Validate Unique Pairs
I have a model called Users. I want two Users to be associated with my Conversation model, but I want the pairs of users (User1, User2) to be unique. For example, If user1 is 5 and user2 is 6, there cannot be a pair where user1 is 6 and user2 is 5.

I already made sure the two users are not the same/there are no User1 and User2 combinations are identical

```<code>validates :user1_id, uniqueness: { scope: :user2_id}
</code>```

but How do do I make sure that if there is a conversation with User1 and User2, there cannot be a convo with User2 and User1? Also, how can I also make sure User1 and User2 are not the same? (ie, Invalid if User1 is 6 and User2 is also 6)

答:
I would suggest a custom validation method:

```<code>validate :validate_users_are_unique

private

def validate_users_are_unique
  if self.class.where(user1_id: user1_id, user2_id: user2_id)
               .or(self.class.where(user1_id: user2_id, user2_id: user1_id))
               .exists?
    errors.add(:base, 'User 1 and User 2 combination exists!')
  end
end
</code>```

Another option might be to sort the user ids and to ensure that user1_id is always the smaller of the two. Then the default Rails' uniqueness validation can be used. And the uniqueness can be ensured at the database level by adding a unique index:

```<code># in the model
before_validation :sort_user_ids
validates :user1_id, uniqueness: { scope: :user2_id }

private

def sort_user_ids
  self.user1_id, self.user2_id = [user1_id, user2_id].sort
end

# in a migration
add_index :table_name, [:user1_id, :user2_id], unique: true
</code>```

Title: Rails: Validate Unique Pairs

Body:
I have a model called Users. I want two Users to be associated with my Conversation model, but I want the pairs of users (User1, User2) to be unique. For example, If user1 is 5 and user2 is 6, there cannot be a pair where user1 is 6 and user2 is 5.

I already made sure the two users are not the same/there are no User1 and User2 combinations are identical

validates :user1_id, uniqueness: { scope: :user2_id}

but How do do I make sure that if there is a conversation with User1 and User2, there cannot be a convo with User2 and User1? Also, how can I also make sure User1 and User2 are not the same? (ie, Invalid if User1 is 6 and User2 is also 6)

Body:
I would suggest a custom validation method:

validate :validate_users_are_unique

private

def validate_users_are_unique
  if self.class.where(user1_id: user1_id, user2_id: user2_id)
               .or(self.class.where(user1_id: user2_id, user2_id: user1_id))
               .exists?
    errors.add(:base, 'User 1 and User 2 combination exists!')
  end
end

Another option might be to sort the user ids and to ensure that user1_id is always the smaller of the two. Then the default Rails' uniqueness validation can be used. And the uniqueness can be ensured at the database level by adding a unique index:

# in the model
before_validation :sort_user_ids
validates :user1_id, uniqueness: { scope: :user2_id }

private

def sort_user_ids
  self.user1_id, self.user2_id = [user1_id, user2_id].sort
end

# in a migration
add_index :table_name, [:user1_id, :user2_id], unique: true


问:
MS Access SQL - Count of Records that are Currently Open During a Workweek
I have a record set that contains

```<code> unique ID
 open date
 closed date
</code>```

I want a query to find the count of record that were active during each workweek (52 workweeks in each year).  The data spans several years so the workweeks would not be unique, repeating from 1-52 each year.

Some pseudo-Code would look like:

```<code> CountIf( ((OpenDate >= Workweek) & (ClosedDate >= WorkWeek))
         OR ((OpenDate >= Workweek) & IsNull(ClosedDate)) )
</code>```

The end result would be a table with the Years, Workweeks, and Count of Active records for that year/workweek.

I have a query that gives me Opened in a workweek:

```<code>SELECT Year([TABLE].[OpenedDate]) AS [Year], DatePart('ww',TABLE.[OpenedDate])
AS [Work Week], Count(TABLE.[ID]) AS [Count Of IDs Opened]
FROM TABLE
GROUP BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate])
ORDER BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate]);
</code>```

And a similar one for Closed but I just can't wrap my head around how to get Active during each Workweek.

Edited to add:

Example Data:

```<code>No  Opened Date Closed Date
1   20-Apr-15   23-Apr-15
2   22-Apr-15   04-May-15
3   27-Apr-15   01-May-15
4   29-Apr-15   04-May-15
5   29-Apr-15   05-Jun-15
6   04-May-15   20-May-15
7   04-May-15   07-May-15
8   05-May-15   20-May-15
9   05-May-15   20-May-15
10  06-May-15   20-May-15
11  06-May-15   20-May-15
12  06-May-15   20-May-15
13  07-May-15   20-May-15
14  11-May-15   26-May-15
15  11-May-15   26-May-15
16  13-May-15   26-May-15
17  18-May-15   26-May-15
18  20-May-15   01-Jun-15
19  21-May-15   03-Jun-15
20  12-Oct-15   07-Jul-16
21  02-Nov-15   26-Jul-17
22  06-Nov-15   30-Nov-15
23  09-Nov-15   26-Jul-17
24  08-Feb-17   05-May-17
25  13-Feb-17
26  13-Feb-17   14-Aug-17
27  07-Mar-17   17-Mar-17
</code>```

答:
So it took some time but I solved my own problem with a combination of solutions posted here.
I made table with 4 columns:

```<code>tbl_WorkWeeks
 cYear
 cWorkWeek
 FirstDay
 LastDay
</code>```

I populated it with years from 2010-2030, workweeks 1-52 (or 53 as needed), the first day of the given work week and the last day of the given work week.

I then ran this query:

```<code>SELECT tbl_WorkWeeks.cYear, tbl_WorkWeeks.cWorkweek,
    tbl_WorkWeeks.FirstDay, tbl_WorkWeeks.LastDay,
    Sum(
        IIf(
            (
                ([tbl_MyDataTable].[OpenedDate] <= [tbl_WorkWeeks].[LastDay])
            AND (
                (([tbl_MyDataTable].[ClosedDate] >= [tbl_WorkWeeks].[FirstDay])
                 OR
                 ([tbl_MyDataTable].[ClosedDate] Is Null))
                )
            )
        ,1,0)
    ) AS [Active RecordID]
 FROM tbl_WorkWeeks, tbl_MyDataTable
 WHERE [tbl_MyDataTable].[RecordID] Is Not Null AND [tbl_WorkWeeks].[FirstDay] <= Now()
 GROUP BY tbl_WorkWeeks.cYear, tbl_WorkWeeks.cWorkweek, tbl_WorkWeeks.FirstDay, tbl_WorkWeeks.LastDay
 ORDER BY tbl_WorkWeeks.cYear, tbl_WorkWeeks.cWorkweek;
</code>```

Thanks everyone for your help.

Body:
I have a record set that contains

 unique ID
 open date
 closed date

I want a query to find the count of record that were active during each workweek (52 workweeks in each year).  The data spans several years so the workweeks would not be unique, repeating from 1-52 each year.

Some pseudo-Code would look like:

 CountIf( ((OpenDate >= Workweek) & (ClosedDate >= WorkWeek))
         OR ((OpenDate >= Workweek) & IsNull(ClosedDate)) )

The end result would be a table with the Years, Workweeks, and Count of Active records for that year/workweek.

I have a query that gives me Opened in a workweek:

SELECT Year([TABLE].[OpenedDate]) AS [Year], DatePart('ww',TABLE.[OpenedDate])
AS [Work Week], Count(TABLE.[ID]) AS [Count Of IDs Opened]
FROM TABLE
GROUP BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate])
ORDER BY Year([TABLE].[OpenedDate]), DatePart('ww',TABLE.[OpenedDate]);

And a similar one for Closed but I just can't wrap my head around how to get Active during each Workweek.

Edited to add:

Example Data:

No  Opened Date Closed Date
1   20-Apr-15   23-Apr-15
2   22-Apr-15   04-May-15
3   27-Apr-15   01-May-15
4   29-Apr-15   04-May-15
5   29-Apr-15   05-Jun-15
6   04-May-15   20-May-15
7   04-May-15   07-May-15
8   05-May-15   20-May-15
9   05-May-15   20-May-15
10  06-May-15   20-May-15
11  06-May-15   20-May-15
12  06-May-15   20-May-15
13  07-May-15   20-May-15
14  11-May-15   26-May-15
15  11-May-15   26-May-15
16  13-May-15   26-May-15
17  18-May-15   26-May-15
18  20-May-15   01-Jun-15
19  21-May-15   03-Jun-15
20  12-Oct-15   07-Jul-16
21  02-Nov-15   26-Jul-17
22  06-Nov-15   30-Nov-15
23  09-Nov-15   26-Jul-17
24  08-Feb-17   05-May-17
25  13-Feb-17
26  13-Feb-17   14-Aug-17
27  07-Mar-17   17-Mar-17

Body:
So it took some time but I solved my own problem with a combination of solutions posted here.
I made table with 4 columns:

tbl_WorkWeeks
 cYear
 cWorkWeek
 FirstDay
 LastDay

I populated it with years from 2010-2030, workweeks 1-52 (or 53 as needed), the first day of the given work week and the last day of the given work week.

I then ran this query:

SELECT tbl_WorkWeeks.cYear, tbl_WorkWeeks.cWorkweek,
    tbl_WorkWeeks.FirstDay, tbl_WorkWeeks.LastDay,
    Sum(
        IIf(
            (
                ([tbl_MyDataTable].[OpenedDate] <= [tbl_WorkWeeks].[LastDay])
            AND (
                (([tbl_MyDataTable].[ClosedDate] >= [tbl_WorkWeeks].[FirstDay])
                 OR
                 ([tbl_MyDataTable].[ClosedDate] Is Null))
                )
            )
        ,1,0)
    ) AS [Active RecordID]
 FROM tbl_WorkWeeks, tbl_MyDataTable
 WHERE [tbl_MyDataTable].[RecordID] Is Not Null AND [tbl_WorkWeeks].[FirstDay] <= Now()
 GROUP BY tbl_WorkWeeks.cYear, tbl_WorkWeeks.cWorkweek, tbl_WorkWeeks.FirstDay, tbl_WorkWeeks.LastDay
 ORDER BY tbl_WorkWeeks.cYear, tbl_WorkWeeks.cWorkweek;

Thanks everyone for your help.


问:
Calculate Time Remaining
What's a good algorithm for determining the remaining time for something to complete?  I know how many total lines there are, and how many have completed already, how should I estimate the time remaining?</p>

答:
Generally, you know three things at any point in time while processing:

How many units/chunks/items have been processed up to that point in time (A).

How long it has taken to process those items (B).

The number of remaining items (C).

Given those items, the estimate (unless the time to process an item is constant) of the remaining time will be

B * C / A

OwnerDisplayName: Aaron Smith

Title: Calculate Time Remaining

OwnerDisplayName: casperOne