问:
Python modifying CSV data
I have a file which looks like this(i.e random combination of 2 /3 consecutive rows) :

```<code>String A
String B
String C
<Blank Row>
String D
String E
<Blank Row>
String F
String G
String H
<Blank Row>
String I
String J
String K
<Blank Row>
String L
String M
</code>```

I want the output file to remove the middle row when there are 3 consecutive rows and transpose the 2 remaining row. IN case there are only 2 rows, they should be transposed. The final result should look like this.

```<code>String A,String C
String D,String E
String F,String H
String I,String K
String L,String M
</code>```

Any pointers how to get this done?

答:
You can use groupby and count from itertools module along with list comprehension.

This answer is a little hacky, but do the trick. See the comments for better understanding the logic behind.

I'm assuming that your input, is the input you gave in a file called my_input_file and your output file is called output_file:

```<code>from itertools import groupby, count

# Read the file and split by the space between Value and its number
# Leave the case where the empty string '' exists without splitting its spaces
with open("my_input_file", 'r') as f:
    data = (k.split() if k != '' else k  for k in f.read().splitlines())

# Group the fields splitted, which are lists, in data
# And separate them by the field where the string 'Blank' exists
sub = [list(v) for _, v in groupby(data, lambda x: isinstance(x, list))]

final = []
for elm in sub:
    # if the lenght of the grouped elements is > 1
    if len(elm) >1:
        # Convert the number of the values into an int
        # For further calculations
        dd = map(lambda x: [x[0], int(x[1])], elm)

        # Group the consecutive numbers of elem
        for _,v in groupby(dd , lambda x,y=count(): x[1] - next(y)):
            # If there is a consecutive numbers
            bb = list(v)
            if len(bb) >1:
                # Conveert them into strings. Then, append the first and the final one to the final list
                final.append(' '.join(map(str, bb[0])) + ',' + ' '.join(map(str, bb[-1])))

            # If there is'nt any consecutif numbers. Append the element to the final list
            else:
                final.append(" ".join(map(str, bb[0])))

# create the output file
with open("output_file", 'a') as f:
    for k in final:
        f.write(k + '\n')
</code>```

This code will output a file which contain:

```<code>Value 1,Value 3
Value 4,Value 5
Value 6,Value 8
Value 9,Value 11
Value 12,Value 13
</code>```

Test this code and leave your feedbacks if you have any, or maybe, please report bugs if you found any of them.

Edit:

According to your last edit.

If your input file is:

```<code>What Test
Makes No Sense
is This

My name
Is Sample 123

Your Name
is ABC 2134

What is you
technical question don't know
name?
</code>```

The trick, is so simple. You can do something like this, using only groupby from itertools module:

```<code>from itertools import groupby

with open("my_input_file", 'r') as f:
    data = f.read().splitlines()

final = [list(v) for _, v in groupby(data, lambda x: x != '')]

with open("ouput_file", 'a') as f:
    for k in final:
        if k != ['']:
            f.write(k[0] + ',' + k[-1] + '\n')
</code>```

And, your output file will be:

```<code>What Test ,is This
My name ,Is Sample 123
Your Name ,is ABC 2134
What is you ,name?
</code>```

Title: Python modifying CSV data

Body:
I have a file which looks like this(i.e random combination of 2 /3 consecutive rows) :

String A
String B
String C
<Blank Row>
String D
String E
<Blank Row>
String F
String G
String H
<Blank Row>
String I
String J
String K
<Blank Row>
String L
String M

I want the output file to remove the middle row when there are 3 consecutive rows and transpose the 2 remaining row. IN case there are only 2 rows, they should be transposed. The final result should look like this.

String A,String C
String D,String E
String F,String H
String I,String K
String L,String M

Any pointers how to get this done?

Body:
You can use groupby and count from itertools module along with list comprehension.

This answer is a little hacky, but do the trick. See the comments for better understanding the logic behind.

I'm assuming that your input, is the input you gave in a file called my_input_file and your output file is called output_file:

from itertools import groupby, count

# Read the file and split by the space between Value and its number
# Leave the case where the empty string '' exists without splitting its spaces
with open("my_input_file", 'r') as f:
    data = (k.split() if k != '' else k  for k in f.read().splitlines())

# Group the fields splitted, which are lists, in data
# And separate them by the field where the string 'Blank' exists
sub = [list(v) for _, v in groupby(data, lambda x: isinstance(x, list))]

final = []
for elm in sub:
    # if the lenght of the grouped elements is > 1
    if len(elm) >1:
        # Convert the number of the values into an int
        # For further calculations
        dd = map(lambda x: [x[0], int(x[1])], elm)

        # Group the consecutive numbers of elem
        for _,v in groupby(dd , lambda x,y=count(): x[1] - next(y)):
            # If there is a consecutive numbers
            bb = list(v)
            if len(bb) >1:
                # Conveert them into strings. Then, append the first and the final one to the final list
                final.append(' '.join(map(str, bb[0])) + ',' + ' '.join(map(str, bb[-1])))

            # If there is'nt any consecutif numbers. Append the element to the final list
            else:
                final.append(" ".join(map(str, bb[0])))

# create the output file
with open("output_file", 'a') as f:
    for k in final:
        f.write(k + '\n')

This code will output a file which contain:

Value 1,Value 3
Value 4,Value 5
Value 6,Value 8
Value 9,Value 11
Value 12,Value 13

Test this code and leave your feedbacks if you have any, or maybe, please report bugs if you found any of them.

Edit:

According to your last edit.

If your input file is:

What Test
Makes No Sense
is This

My name
Is Sample 123

Your Name
is ABC 2134

What is you
technical question don't know
name?

The trick, is so simple. You can do something like this, using only groupby from itertools module:

from itertools import groupby

with open("my_input_file", 'r') as f:
    data = f.read().splitlines()

final = [list(v) for _, v in groupby(data, lambda x: x != '')]

with open("ouput_file", 'a') as f:
    for k in final:
        if k != ['']:
            f.write(k[0] + ',' + k[-1] + '\n')

And, your output file will be:

What Test ,is This
My name ,Is Sample 123
Your Name ,is ABC 2134
What is you ,name?


来源: stackexchange

问:
How to "transfer" UIImageView between view
when you click "Share" in my app you'll show an ActionSheet like this:

Take photo

Select photo from Library

Cancel

You tap "Take photo" and you'll see an ImagePicker, with "presentModalViewController".
You take a photo and you select "OK" in the ImagePicker.
Here, I want the photo just taken in a new view with other label. Like this:

(new view)
Little photo (just taken)
- Label 1 (ex. Title of photo)
- Label 2 (ex. Location of photo)

and a button "Share" for sharing your photo and its infos.

How can I do this? I'm stopped after take the photo. How can I send my photo (in a imageview) to another view?

Thanks

答:
Some one already suggested for that by using appDelegate.

you can do in other way too.

just declare some variable like imagePath and imageTitle in the 2nd view controller. and set property to them like

```<code>@property (nonatomic,retain) NSString *imagePath;
</code>```

And then in the 1st view controller access those variables like

```<code>secondViewControllerObj.imagePath = @"Give Image Path Here";
</code>```

then you can access the imagePath in the 2nd View Controller as self.imagePath

Regards,

Satya

ContentLicense: CC BY-SA 2.5

Body:
Some one already suggested for that by using appDelegate.

you can do in other way too.

just declare some variable like imagePath and imageTitle in the 2nd view controller. and set property to them like

@property (nonatomic,retain) NSString *imagePath;

And then in the 1st view controller access those variables like

secondViewControllerObj.imagePath = @"Give Image Path Here";

then you can access the imagePath in the 2nd View Controller as self.imagePath

Regards,

Satya


问:
Format string in ICS Fle (Set font for ICS file)
I am Creating ICS file fromC# WPF application and using the following code to generate ICS file.

```<code>StreamWriter writer;
writer = new StreamWriter(filePath);
writer.WriteLine("BEGIN:VCALENDAR");
writer.WriteLine("VERSION:2.0");
writer.WriteLine("PRODID:MyApp");
writer.WriteLine("CALSCALE:GREGORIAN");
writer.WriteLine("METHOD:PUBLISH");
writer.WriteLine("BEGIN:VEVENT");
string startDateTime = Convert.ToDateTime(appointmentDetails.StartDate).ToString("yyyyMMdd'T'HHmmss");
string endDateTime = Convert.ToDateTime(appointmentDetails.EndDate).ToString("yyyyMMdd'T'HHmmss");

writer.WriteLine("DTSTART:" + startDateTime);
writer.WriteLine("DTEND:" + endDateTime);
writer.WriteLine(@"DESCRIPTION:" + appointmentDetails.Body);
writer.WriteLine("SUMMARY:" + appointmentDetails.Subject);
writer.WriteLine("END:VEVENT");
writer.WriteLine("END:VCALENDAR");
writer.Close();
</code>```

But I have some problems while fromating the description.I think when I add \n for new line ,it creates a problem.
I need to format my string like this.

```<code>------------------
Header1
-----------------
bOdy1
contents
---------------
</code>```

I am using the following line to create a dotted line.

```<code>result += new String('-', characterLength) + "\\n";
</code>```

But the out put showing one line instead of dotted line.I think “\n” creates the problem.when I add some space after the new line escape character I can see the problem solved.Is there any better/alternate solution for this?

Some string in the description showing in different font style.How can Make it unique?

How can I set the font for this ICs file from the C#?

Please suggest.

答:
Format description...</p>

```<code>    str.AppendLine(String.Format("DESCRIPTION:{0}", description));
    str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", description));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am Creating ICS file fromC# WPF application and using the following code to generate ICS file.

StreamWriter writer;
writer = new StreamWriter(filePath);
writer.WriteLine("BEGIN:VCALENDAR");
writer.WriteLine("VERSION:2.0");
writer.WriteLine("PRODID:MyApp");
writer.WriteLine("CALSCALE:GREGORIAN");
writer.WriteLine("METHOD:PUBLISH");
writer.WriteLine("BEGIN:VEVENT");
string startDateTime = Convert.ToDateTime(appointmentDetails.StartDate).ToString("yyyyMMdd'T'HHmmss");
string endDateTime = Convert.ToDateTime(appointmentDetails.EndDate).ToString("yyyyMMdd'T'HHmmss");

writer.WriteLine("DTSTART:" + startDateTime);
writer.WriteLine("DTEND:" + endDateTime);
writer.WriteLine(@"DESCRIPTION:" + appointmentDetails.Body);
writer.WriteLine("SUMMARY:" + appointmentDetails.Subject);
writer.WriteLine("END:VEVENT");
writer.WriteLine("END:VCALENDAR");
writer.Close();

But I have some problems while fromating the description.I think when I add \n for new line ,it creates a problem.
I need to format my string like this.

------------------
Header1
-----------------
bOdy1
contents
---------------

I am using the following line to create a dotted line.

result += new String('-', characterLength) + "\\n";

But the out put showing one line instead of dotted line.I think “\n” creates the problem.when I add some space after the new line escape character I can see the problem solved.Is there any better/alternate solution for this?

Some string in the description showing in different font style.How can Make it unique?

How can I set the font for this ICs file from the C#?

Please suggest.

Body:
Format description...

    str.AppendLine(String.Format("DESCRIPTION:{0}", description));
    str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", description));


问:
How to ensure that a logged in employee can only view his sales record but Admin can view all?
I'm learning asp.net, I have created simple web application for storing sales record using a form, employee record, I'm wondering how I can make sure no employee can view sales data of any other employee and make changes to them but Admin or employee manager can view all of their records?

using a simple Model for now:

```<code>{
public ApplicationUser Employee{ get; set; }
public int EmpId { get; set; }
public int Id { get; set; }
public string Po { get; set; }
public long So { get; set; }
}
</code>```

答:
You have to check the role of user and based on that you query the result
here see sample code:

```<code>           var TheUser = db.MyUsersContext.FirstOrDefault(u => u.UserName.Equals(TrimedUser, StringComparison.CurrentCultureIgnoreCase));
        if (TheUser != null)
        {
            var TheRoles =
                 from r in db.MyRoleContext
                 where TheUser.RoleId == r.Id
                 select r.RoleName;
            if (TheRoles != null)
            {
                return TheRoles.ToArray();
            }
            else
            {
                return new string[] { };
            }
        }
        else
        {
            return new string[] { "Viewer" };
        }
</code>```

and based on return values you can query database

Body:
I'm learning asp.net, I have created simple web application for storing sales record using a form, employee record, I'm wondering how I can make sure no employee can view sales data of any other employee and make changes to them but Admin or employee manager can view all of their records?

using a simple Model for now:

{
public ApplicationUser Employee{ get; set; }
public int EmpId { get; set; }
public int Id { get; set; }
public string Po { get; set; }
public long So { get; set; }
}

Body:
You have to check the role of user and based on that you query the result
here see sample code:

           var TheUser = db.MyUsersContext.FirstOrDefault(u => u.UserName.Equals(TrimedUser, StringComparison.CurrentCultureIgnoreCase));
        if (TheUser != null)
        {
            var TheRoles =
                 from r in db.MyRoleContext
                 where TheUser.RoleId == r.Id
                 select r.RoleName;
            if (TheRoles != null)
            {
                return TheRoles.ToArray();
            }
            else
            {
                return new string[] { };
            }
        }
        else
        {
            return new string[] { "Viewer" };
        }

and based on return values you can query database


问:
Image pasting works on localhost but not on server address
I am having some trouble in pasting images in CKEditor.

I am able to paste images when I use localhost. Please refer the image.
Picture using LocalHost

On the other hand, when I use server address instead of localhost, it shows errors. Ctrl+V won't paste the image from clipboard ether. Please refer the image.
Picture using server address

Note that I am logged into the same server and it only works on IE.

Can someone please point me to the correct direction?

Thank you very much in advance.

Regards,

答:
I guess, problem is that Internet explorer has different security setting depends on what connection are you using.

Open Internet Explorer, select the "gear" Tools button , and then select Internet
  options. Select the Security tab and customize your security zone
  settings in these ways:

To change settings for any security zone, select the zone icon, and
  then move the slider to the security level that you want. To create
  your own security settings for a zone, select the zone icon, and then
  select Custom level and choose the settings that you want. To restore
  all security levels to their original settings, select the Reset all
  zones to default level button.

https://support.microsoft.com/en-us/help/17479/windows-internet-explorer-11-change-security-privacy-settings


问:
Node JS: variable usage between modules
I have two modules to represent my problem/confusion:

f2.js:

```<code>var user;

var getName = function(userName) {
    user = userName;
    return user;
};

module.exports.getName = getName;
module.exports.user = user;
</code>```

f1.js:

```<code>var userName = require('./f2.js');
console.log(userName.getName("myName"));

// I need below to return "myName" too - how?
console.log(userName.user);
</code>```

When I run f1.js, I get these:

```<code>myName
undefined
</code>```

What am I missing in terms of scoping or perhaps asynchronous coding? Logically, I know getName function will always run in front so how can I read 'user' variable in other modules as set with that pre-run function? I eventually want to expand this with express and use it as site login

答:
The problem is that exports.user and var user are independent copies. Initially, they hold the same value, but changes to one don't impact the other, similar to with other variables:

```<code>var foo = 'one';
var bar = foo; // copies the value
bar = 'two';
console.log(foo, bar); // "one" "two"
</code>```

To have exports.user always provide var user's value, one option is to define the former as a getter property, returning the latter:

```<code>Object.defineProperty(module.exports, 'user', {
    get: function () {
        return user;
    }
});
</code>```

Or, assign it to the function directly, though other modules will need to call it:

```<code>module.exports.user = function () {
    return user;
};
</code>```

```<code>var userName = require('./f2.js');
// ...
console.log(userName.user());
</code>```

Title: Node JS: variable usage between modules

Body:
I have two modules to represent my problem/confusion:

f2.js:

var user;

var getName = function(userName) {
    user = userName;
    return user;
};

module.exports.getName = getName;
module.exports.user = user;

f1.js:

var userName = require('./f2.js');
console.log(userName.getName("myName"));

// I need below to return "myName" too - how?
console.log(userName.user);

When I run f1.js, I get these:

myName
undefined

What am I missing in terms of scoping or perhaps asynchronous coding? Logically, I know getName function will always run in front so how can I read 'user' variable in other modules as set with that pre-run function? I eventually want to expand this with express and use it as site login

Body:
The problem is that exports.user and var user are independent copies. Initially, they hold the same value, but changes to one don't impact the other, similar to with other variables:

var foo = 'one';
var bar = foo; // copies the value
bar = 'two';
console.log(foo, bar); // "one" "two"

To have exports.user always provide var user's value, one option is to define the former as a getter property, returning the latter:

Object.defineProperty(module.exports, 'user', {
    get: function () {
        return user;
    }
});

Or, assign it to the function directly, though other modules will need to call it:

module.exports.user = function () {
    return user;
};

var userName = require('./f2.js');
// ...
console.log(userName.user());


问:
Android SDK manager won't open
So I installed the android sdk for Windows:

http://developer.android.com/sdk/index.html   (the installation link)

And ran into the path variable problem. So I fixed that by changing "PATH" in enviroment variables to include where my java.exe file is located from the JDK.

But now when I open the android sdk manager, a cmd-like screen just briefly flashes on for half a second then disappears. I have no idea what's going on and how to get this thing working.

答:
Google removed the GUI for SDK starting from version 26. If you're using version 26, try downgrading to version 25. You can still open the SDK from Android Studio.

Source: Is GUI for Android SDK manager gone?

Title: Android SDK manager won't open


问:
How to sort a List/ArrayList?
I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

```<code>List<Double> testList = new ArrayList();

testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);
testList.add(0.71);
testList.add(0.71);
testList.add(0.71);
testList.add(0.92);
testList.add(0.12);
testList.add(0.65);
testList.add(0.34);
testList.add(0.62);
</code>```

The out put should be like this

```<code>0.92
0.9
0.71
0.71
0.71
0.65
0.62
0.54
0.5
0.34
0.2
0.12
0.1
0.1
0.1
</code>```

答:
|*| Sorting an List :

```<code>import java.util.Collections;
</code>```

|=> Sort Asc Order :

```<code>Collections.sort(NamAryVar);
</code>```

|=> Sort Dsc Order :

```<code>Collections.sort(NamAryVar, Collections.reverseOrder());
</code>```

|*| Reverse the order of List :

```<code>Collections.reverse(NamAryVar);
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to sort a List/ArrayList?

Body:
I have a List of doubles in java and I want to sort ArrayList in descending order.

Input ArrayList is as below:

List<Double> testList = new ArrayList();

testList.add(0.5);
testList.add(0.2);
testList.add(0.9);
testList.add(0.1);
testList.add(0.1);
testList.add(0.1);
testList.add(0.54);
testList.add(0.71);
testList.add(0.71);
testList.add(0.71);
testList.add(0.92);
testList.add(0.12);
testList.add(0.65);
testList.add(0.34);
testList.add(0.62);

The out put should be like this

0.92
0.9
0.71
0.71
0.71
0.65
0.62
0.54
0.5
0.34
0.2
0.12
0.1
0.1
0.1

Body:
|*| Sorting an List :

import java.util.Collections;

|=> Sort Asc Order :

Collections.sort(NamAryVar);

|=> Sort Dsc Order :

Collections.sort(NamAryVar, Collections.reverseOrder());

|*| Reverse the order of List :

Collections.reverse(NamAryVar);


问:
what is the actual use of interface in java?

Possible Duplicates:

  Abstract class and Interface class?

  Java: interface / abstract classes / abstract method

In Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?

答:
Java interface
   - provides the data encapsulation which means, implementation of the methods can not be seen. The class which extends this interface must implement all the methods declared in it.

more info: wiki answer


答:
You can use the handy feature of the unnest() function to unnest multiple arrays in parallel.

Do that in a LATERAL join, multiply per resulting row and feed that to an ARRAY constructor:

```<code>SELECT q.query_id, d.doc, qd.prod
FROM   vetor_query          q
CROSS  JOIN vetor_documento d
CROSS  JOIN LATERAL (
   SELECT ARRAY(SELECT x*y FROM unnest(q.pesos, d.pesos) t(x, y)) AS prod
   ) qd;
</code>```

This is assuming all arrays have the same length, else surplus elements are filled with NULL.

Related:

Unnest multiple arrays in parallel

The order in the resulting array corresponds to the original order of elements. But consider:

PostgreSQL unnest() with element number

Title: Product of elements with same index in 2 arrays

Body:
I need to multiply each element of 2 arrays and project a column which is a array and each element is the product result.

Example:

select * from vetor_query;

Returns:

query_id |pesos                                                                                |
---------|----------------------------------------------------------------------------------------------------|
1        |{2.0000,0.4150,2.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |

And the query:

select * from vetor_documento;

Returns:

doc    |pesos                                                                                |
-------|----------------------------------------------------------------------------------------------------|
d1.txt |{3.0000,0.8301,4.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |
d2.txt |{2.0000,0.0000,0.0000,0.0000,2.0000,2.0000,2.0000,2.0000,2.0000,0.0000,0.0000,0.0000,0.0000,0.0000} |
d3.txt |{0.0000,1.0729,0.0000,0.0000,0.0000,0.0000,2.0000,1.0000,0.0000,2.0000,2.0000,0.0000,0.0000,0.0000} |
d4.txt |{0.0000,1.0729,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,5.1699,4.0000,4.0000} |

I need to combine both queries(cross join) and produce as a result array of internal product for each doc and query_id.

My first attempt was this one:

select vq.query_id, vd.doc, unnest(vq.pesos) * unnest(vd.pesos)
from vetor_query vq
cross join vetor_documento vd;

However, it yields this error:

Functions and operators can take at most one set argument

Body:
You can use the handy feature of the unnest() function to unnest multiple arrays in parallel.

Do that in a LATERAL join, multiply per resulting row and feed that to an ARRAY constructor:

SELECT q.query_id, d.doc, qd.prod
FROM   vetor_query          q
CROSS  JOIN vetor_documento d
CROSS  JOIN LATERAL (
   SELECT ARRAY(SELECT x*y FROM unnest(q.pesos, d.pesos) t(x, y)) AS prod
   ) qd;

This is assuming all arrays have the same length, else surplus elements are filled with NULL.

Related:

Unnest multiple arrays in parallel

The order in the resulting array corresponds to the original order of elements. But consider:

PostgreSQL unnest() with element number


问:
How to make an audio play/pause button?
I recently learned about embedding audio in html like below.

```<code> <audio controls>
  <source src="sample.ogg" type="audio/ogg">
  <source src="sample.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</code>```

Which displays something like a rectangle with various options on it like pause/play, download, set volume etc.

But how can I instead of this "audio playing rectangle" have a button that when clicked plays the audio once and on clicking on it while the audio is playing pauses it and on clicking again continuous playing.

答:
Here is a simple example with pure JS. I am using a class on button to know if audio is playing or not, you can use the same class for different UI when button in play/pause state.

Link: https://jsfiddle.net/p4mksfm1/

```<code><audio id="testAudio" hidden src="https://api.twilio.com/cowbell.mp3" type="audio/mpeg">
</audio>

<button id="playAudio">Play</button>

<script type="text/javascript">
document.getElementById("playAudio").addEventListener("click", function(){
    var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }

});
</script>
</code>```

Title: How to make an audio play/pause button?

Body:
I recently learned about embedding audio in html like below.

 <audio controls>
  <source src="sample.ogg" type="audio/ogg">
  <source src="sample.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

Which displays something like a rectangle with various options on it like pause/play, download, set volume etc.

But how can I instead of this "audio playing rectangle" have a button that when clicked plays the audio once and on clicking on it while the audio is playing pauses it and on clicking again continuous playing.

Body:
Here is a simple example with pure JS. I am using a class on button to know if audio is playing or not, you can use the same class for different UI when button in play/pause state.

Link: https://jsfiddle.net/p4mksfm1/

<audio id="testAudio" hidden src="https://api.twilio.com/cowbell.mp3" type="audio/mpeg">
</audio>

<button id="playAudio">Play</button>

<script type="text/javascript">
document.getElementById("playAudio").addEventListener("click", function(){
    var audio = document.getElementById('testAudio');
  if(this.className == 'is-playing'){
    this.className = "";
    this.innerHTML = "Play"
    audio.pause();
  }else{
    this.className = "is-playing";
    this.innerHTML = "Pause";
    audio.play();
  }

});
</script>


问:
divs height and width are not fixed in carousel slider
Visit this link for code snippet https://codepen.io/arunkayathi/pen/dRPYzz

html

```<code><html lang="en">

<head>

    <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

</head>

<body>
    <section id="projects">
        <div class="content-box">
            <div class="content-title wow animated fadeInDown" data-wow-duration="1s" data-wow-delay=".5s">
                <h3>My Projects</h3>
                <div class="content-title-underline"></div>
            </div>
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <div id="my-projects" class="owl-carousel owl-theme">
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTp1-NNfLpNtsFQY25z7A4u9pp2D_vJHTNU70RDupydx4i7BrMKYw" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit Website</a>
                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                                </div>

                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur . </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" target="_blank">visit site</a>

                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQQAOoZwRkgQ3KDjCJ2-GRtjKDc88iUqU6mJva17ym63D2W0XwnYw" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,  </p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#" role="button" target="_blank">Visit site</a>
                                    </div>

                                </div>
                            </div>
                            <div class="project-list">
                                <div class="project-image">
                                    <img src="https://static.pexels.com/photos/33109/fall-autumn-red-season.jpg" class="img-responsive" alt="project-image1">
                                </div>
                                <div class="project-info text-center">
                                    <h5>Project Title</h5>
                                    <p class="project-info-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.</p>
                                    <div class="project-btn">
                                        <a class="btn btn-lg btn-general btn-white" href="#projects" role="button">Visit site</a>
                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <body>
</code>```

css

```<code>    #projects {
    background-color: #f65d52;
    /*    background-color: #2098D1;*/
}

#projects .content-title h3 {
    color: #fff;
}

.project-info {
    padding: 25px 0 25px 0;
    color: #fff;

}

.project-info h5 {

    font-size: 25px;
    font-weight: 700;
}

.project-image img {
    max-width: 480px !important;
    max-height: 480px !important;
    margin: 0 auto;
    object-fit: contain;
}

.project-info-text {
    line-height: 170%;
    letter-spacing: 1px;
    color: #fff !important;
    font-weight: 500;
    width: 70%;
    margin: 0 auto;
}

.project-btn {
    padding-top: 30px;
}
</code>```

js

```<code>$(document).ready(function () {
    $("#my-projects").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 700,
        loop: true,
        autoplayHoverPause: true
    });

});
</code>```

Hello all,

I am having a problem with arranging divs in a carousel slider. As you can see from the above link the  position of project title in each slid is changing.So can somebody help me in fixing the width and height of each divs, so that text and images  will not overflow and in every slide all divs starts at same position instead  of going up or down.

答:
Your images need a fixed height otherwise things will get pushed down or up.
if you can't set a fixed height on the images then I suggest just a fixed position of the project title and description div. Maybe make it absolute of its parent.  </p>

Body:
Visit this link for code snippet https://codepen.io/arunkayathi/pen/dRPYzz

html

    <link href="https://fonts.googleapis.com/css?family=Lato:400,400i,700,700i|Merriweather:300,400,700" rel="stylesheet">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.min.css" />
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet">

My Projects

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Atque minus voluptatibus obcaecati temporibus, eligendi harum in iusto quasi dicta. Sunt tempora magnam eveniet, adipisci modi quos maxime sint expedita repudiandae. Lorem ipsum dolor sit amet, consectetur adipisicing elit.

                                        Visit Website

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas aliquid consequuntur .

                                        visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eius, omnis,

                                        Visit site

Project Title

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint similique earum labore quos quidem ab! Quibusdam fugit consectetur tenetur odit, fuga amet aliquam architecto modi sequi ea, delectus, quisquam atque.

                                        Visit site

css

    #projects {
    background-color: #f65d52;
    /*    background-color: #2098D1;*/
}

#projects .content-title h3 {
    color: #fff;
}

.project-info {
    padding: 25px 0 25px 0;
    color: #fff;

}

.project-info h5 {

    font-size: 25px;
    font-weight: 700;
}

.project-image img {
    max-width: 480px !important;
    max-height: 480px !important;
    margin: 0 auto;
    object-fit: contain;
}

.project-info-text {
    line-height: 170%;
    letter-spacing: 1px;
    color: #fff !important;
    font-weight: 500;
    width: 70%;
    margin: 0 auto;
}

.project-btn {
    padding-top: 30px;
}

js

$(document).ready(function () {
    $("#my-projects").owlCarousel({
        items: 1,
        autoplay: true,
        smartSpeed: 700,
        loop: true,
        autoplayHoverPause: true
    });

});

Hello all,

I am having a problem with arranging divs in a carousel slider. As you can see from the above link the  position of project title in each slid is changing.So can somebody help me in fixing the width and height of each divs, so that text and images  will not overflow and in every slide all divs starts at same position instead  of going up or down.


问:
Google Maps Search Box disappears after going to searched location
I am using a cut-down version of Google Maps with a search box. The first time through the search box displays and allows you to go to the selected location. When at the selected location the search box does not display.

Can anybody enlighten me as to why the search box does not display at the new location.

The javascript link used is:

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
    <script>
</code>```

The body code is:

```<code><body>
    <div id="map-canvas"></div>
    <input id="pac-input" class="controls" type="text" placeholder="Search Box">
</body>
</code>```

The javascript code is:

```<code><script>
    var latLng = new google.maps.LatLng(-33.86428652, 151.20809555);
    var zoom = 14;

    function initialize() {
        var mapOptions = {
            center:     latLng,
            zoom:       zoom,
            mapTypeId:  google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        var input = document.getElementById('pac-input');
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

        var searchBox = new google.maps.places.SearchBox(input);

        google.maps.event.addListener(searchBox, 'places_changed', function() {
            var places = searchBox.getPlaces();

            if (places.length == 0)
                return;

            for (var i = 0; place = places[i]; i++) {
                latLng = place.geometry.location;
            }

            initialize();
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
</script>
</code>```

答:
You can try to use my sample,

It's good solution for finding the location

You just need to change key workd or Drag drop the map for action

var map;
      var service;

   var err = 0;
   var first = true;
   function initMap() {

   var lat = document.getElementById('start_lat').value;
  var lng = document.getElementById('start_lng').value;
  if(lat!='' && lng!='') {
   lat = parseFloat(lat);
   lng= parseFloat(lng);
    var center =   {lat: lat, lng:lng};
    if(first){
     map = new google.maps.Map(document.getElementById('map'), {
      center: center,
       zoom: 14
     });
      infoWindow = new google.maps.InfoWindow();
     service = new google.maps.places.PlacesService(map);
     map.addListener('idle', performSearch);

   }
   else
   {
    map.setCenter(center);
    performSearch();
   }

  }
      }

      function performSearch() {

  var key = document.getElementById('keyword').value;
     var lat = document.getElementById('start_lat').value;
var lng = document.getElementById('start_lng').value;
  if(key!='' && lat!='' && lng!='')
  {
  var request = {
          bounds: map.getBounds(),
    type:[key],
    keyword: key
        };
        service.radarSearch(request, callback);
 }

      }
var arr_place =[];
var arr_pos = [];
function addRow(name, lat, lng, addr)
{
return;
 document.getElementById('con').innerHTML += ('"'+name+','+lat+','+lng+'",
');
}

      function callback(results, status) {
        if (status !== google.maps.places.PlacesServiceStatus.OK) {
        //  console.error(status);
  //  setTimeout(changeCenter,500);
    return;
        }

  for (var i = 0, result; result = results[i]; i++) {

    if(arr_place.indexOf(result.place_id)==-1)
    {
   arr_place.push(result.place_id);
   addMarker(result);
   addRow( result.place_id, result.geometry.location.lat().toFixed(7), result.geometry.location.lng().toFixed(7), '');

  }
  document.getElementById('result').innerHTML=arr_place.length;
        }

      }
   var k=0;
 var cur =0;

 function ClearToResearch()
 {
  cnt = 0;
  arr_pos = [];
  for(var i=0; i<arr_mark.length; i++)
   arr_mark[i].setMap(null);
  arr_mark = [];
  var con = document.getElementById('con');
  while (con.firstChild) {
   con.removeChild(con.firstChild);
  }
  document.getElementById('keyword').value='';
  document.getElementById('result').innerHTML='0';

 }
 var arr_mark = [];
 var infoWindow;
      function addMarker(place) {
   var cur_pos = place.geometry.location;
   arr_pos.push(place);
   var marker;
        arr_mark.push( marker= new google.maps.Marker({
          map: map,
          position: cur_pos
        }));

   google.maps.event.addListener(marker, 'mouseover', function() {
          service.getDetails(place, function(result, status) {
            if (status !== google.maps.places.PlacesServiceStatus.OK) {
              console.error(status);
              return;
            }
            infoWindow.setContent(result.name+'
'+result.formatted_address);
            infoWindow.open(map, marker);
          });
        });

      }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 450px;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
  padding-top:0px;
        padding-left:10px;
  padding-right:10px;
  background-color:rgb(215,215,215);
      }</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Finding location</title>

        Finding location

 <form action="#" submit="performSearch()" >
 Start Lat <input type="text" id="start_lat" onchange="initMap()" value="25.164244">
 Start Lng <input type="text" id="start_lng" onchange="initMap()" value="55.287799">
 Keyword <input type="text" id="keyword" onchange="performSearch()" value="coffee">
  0
 <input type="button" value="Reset" onclick="ClearToResearch()" />

    </form>

```

Body:
You can try to use my sample,

It's good solution for finding the location

You just need to change key workd or Drag drop the map for action

var map;
      var service;

   var err = 0;
   var first = true;
   function initMap() {

   var lat = document.getElementById('start_lat').value;
  var lng = document.getElementById('start_lng').value;
  if(lat!='' && lng!='') {
   lat = parseFloat(lat);
   lng= parseFloat(lng);
    var center =   {lat: lat, lng:lng};
    if(first){
     map = new google.maps.Map(document.getElementById('map'), {
      center: center,
       zoom: 14
     });
      infoWindow = new google.maps.InfoWindow();
     service = new google.maps.places.PlacesService(map);
     map.addListener('idle', performSearch);

   }
   else
   {
    map.setCenter(center);
    performSearch();
   }

  }
      }

      function performSearch() {

  var key = document.getElementById('keyword').value;
     var lat = document.getElementById('start_lat').value;
var lng = document.getElementById('start_lng').value;
  if(key!='' && lat!='' && lng!='')
  {
  var request = {
          bounds: map.getBounds(),
    type:[key],
    keyword: key
        };
        service.radarSearch(request, callback);
 }

      }
var arr_place =[];
var arr_pos = [];
function addRow(name, lat, lng, addr)
{
return;
 document.getElementById('con').innerHTML += ('"'+name+','+lat+','+lng+'",<BR>');
}

      function callback(results, status) {
        if (status !== google.maps.places.PlacesServiceStatus.OK) {
        //  console.error(status);
  //  setTimeout(changeCenter,500);
    return;
        }

  for (var i = 0, result; result = results[i]; i++) {

    if(arr_place.indexOf(result.place_id)==-1)
    {
   arr_place.push(result.place_id);
   addMarker(result);
   addRow( result.place_id, result.geometry.location.lat().toFixed(7), result.geometry.location.lng().toFixed(7), '');

  }
  document.getElementById('result').innerHTML=arr_place.length;
        }

      }
   var k=0;
 var cur =0;

 function ClearToResearch()
 {
  cnt = 0;
  arr_pos = [];
  for(var i=0; i<arr_mark.length; i++)
   arr_mark[i].setMap(null);
  arr_mark = [];
  var con = document.getElementById('con');
  while (con.firstChild) {
   con.removeChild(con.firstChild);
  }
  document.getElementById('keyword').value='';
  document.getElementById('result').innerHTML='0';

 }
 var arr_mark = [];
 var infoWindow;
      function addMarker(place) {
   var cur_pos = place.geometry.location;
   arr_pos.push(place);
   var marker;
        arr_mark.push( marker= new google.maps.Marker({
          map: map,
          position: cur_pos
        }));

   google.maps.event.addListener(marker, 'mouseover', function() {
          service.getDetails(place, function(result, status) {
            if (status !== google.maps.places.PlacesServiceStatus.OK) {
              console.error(status);
              return;
            }
            infoWindow.setContent(result.name+'<BR>'+result.formatted_address);
            infoWindow.open(map, marker);
          });
        });

      }

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 450px;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
  padding-top:0px;
        padding-left:10px;
  padding-right:10px;
  background-color:rgb(215,215,215);
      }

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Finding location</title>

  </head>
  <body>

<div id="container" style="white-space:nowrap">

    <div id="image" style="display:inline;">

    </div>

    <div id="texts" style="display:inline; white-space:nowrap;">
      <span style="vertical-align:middle;">  <font size=6 color=red><u><b>Finding location</b></u></font> </span>
    </div>

</div>
 <form action="#" submit="performSearch()" >
 <font color=brown><b>Start Lat</b></font> <input type="text" id="start_lat" onchange="initMap()" value="25.164244">
 <font color=brown><b>Start Lng</b></font> <input type="text" id="start_lng" onchange="initMap()" value="55.287799">
 <font color=brown><b>Keyword</b></font> <input type="text" id="keyword" onchange="performSearch()" value="coffee">
 <font color=blue><b><span id="result"> 0 </span></b></font>
 <input type="button" value="Reset" onclick="ClearToResearch()" />
 <BR><BR>
    </form>
    <script src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places,visualization" async defer></script>
 <div id="map" style="border:2px solid brown"></div>
 <BR>

 <div id="con">

 </table>

  </body>
</html>


问:
How to write JUnit tests?
I have an assingment that require me to test if a matrix meets a certain requirement, which I have completed, and then test it in a JUnit test, which I don't know how. I have created the folder for the JUnit test but I don't know how to write the test. So far I did the test in the main class.</p>

```<code>public static void main(String[] args) {
    int matrix[][] = {{2,7,6},{9,5,1},{4,3,8}};

    System.out.println(isMagicSquare(matrix));

    // changing one element
    matrix[0][2] = 5;
    System.out.println(isMagicSquare(matrix));
}

public static boolean isMagicSquare(int[][] matrix) {
    // actual code omitted for the sake of simplicity.
}
</code>```

答:
First you create the class that you want to test.

```<code>public class MagicSquare
{
    private int[][] matrix;

    public MagicSquare(int[][] matrix)
    {
        this.matrix = matrix;
    }

    public boolean isValid()
    {
        // validation logic
    }
}
</code>```

Then you create the test class.

```<code>import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class MagicSquareTest
{
    @Test
    public void testMagicSquare1()
    {
        int[][] matrix = { { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } };
        MagicSquare square = new MagicSquare(matrix);
        // this is a valid magic square
        assertTrue(square.isValid());
    }

    @Test
    public void testMagicSquare2()
    {
        int[][] matrix = { { 2, 7, 5 }, { 9, 5, 1 }, { 4, 3, 8 } };
        MagicSquare square = new MagicSquare(matrix);
        // this is an invalid magic square
        assertFalse(square.isValid());
    }
}
</code>```

Finally see the answers to this question on how to run the test cases from the command line.

Title: How to write JUnit tests?

Body:
I have an assingment that require me to test if a matrix meets a certain requirement, which I have completed, and then test it in a JUnit test, which I don't know how. I have created the folder for the JUnit test but I don't know how to write the test. So far I did the test in the main class.

public static void main(String[] args) {
    int matrix[][] = {{2,7,6},{9,5,1},{4,3,8}};

    System.out.println(isMagicSquare(matrix));

    // changing one element
    matrix[0][2] = 5;
    System.out.println(isMagicSquare(matrix));
}

public static boolean isMagicSquare(int[][] matrix) {
    // actual code omitted for the sake of simplicity.
}

Body:
First you create the class that you want to test.

public class MagicSquare
{
    private int[][] matrix;

    public MagicSquare(int[][] matrix)
    {
        this.matrix = matrix;
    }

    public boolean isValid()
    {
        // validation logic
    }
}

Then you create the test class.

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class MagicSquareTest
{
    @Test
    public void testMagicSquare1()
    {
        int[][] matrix = { { 2, 7, 6 }, { 9, 5, 1 }, { 4, 3, 8 } };
        MagicSquare square = new MagicSquare(matrix);
        // this is a valid magic square
        assertTrue(square.isValid());
    }

    @Test
    public void testMagicSquare2()
    {
        int[][] matrix = { { 2, 7, 5 }, { 9, 5, 1 }, { 4, 3, 8 } };
        MagicSquare square = new MagicSquare(matrix);
        // this is an invalid magic square
        assertFalse(square.isValid());
    }
}

Finally see the answers to this question on how to run the test cases from the command line.


问:
In ASP.Net MVC controller, how do I get a method to recognize data from JSON and Form-urlEncoded formats?
I'm trying to use ASP.NET code MVC to handle HTTP POST requests as follows:

```<code>[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId})]
    public int AddRecord(UserRecord record){
        //This even populates the UserId and GroupId fields in record from the route
    }
}
</code>```

The above works for Form-UrlEncoded parameters, but not for JSON.

If I want JSON to work, I need to use the [FromBody] attribute like so:

```<code>[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId})]
    public int AddRecord([FromBody]UserRecord record, int groupId, int userId){
        //this doesn't look in the route to populate info anymore
        record.GroupId = groupId;
        record.UserId = userId;
    }
}
</code>```

How do i get both to work in a single method?

答:
So, this seems really silly, but from experimentation and reading this very informative article, it looks like the only way to do this is with two separate methods.

One for form-urlencoded data

```<code>[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId}/add)]
    public int AddRecord(UserRecord record){
        //This even populates the UserId and GroupId fields in record from     the route
    }
}
</code>```

and one for json:

```<code>[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId}/addJson)]
    public int AddRecordJson([FromBody]UserRecord record, int groupId, int userId){
        //this doesn't look in the route to populate info anymore
        record.GroupId = groupId;
        record.UserId = userId;
    }
}
</code>```

Body:
I'm trying to use ASP.NET code MVC to handle HTTP POST requests as follows:

[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId})]
    public int AddRecord(UserRecord record){
        //This even populates the UserId and GroupId fields in record from the route
    }
}

The above works for Form-UrlEncoded parameters, but not for JSON.

If I want JSON to work, I need to use the [FromBody] attribute like so:

[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId})]
    public int AddRecord([FromBody]UserRecord record, int groupId, int userId){
        //this doesn't look in the route to populate info anymore
        record.GroupId = groupId;
        record.UserId = userId;
    }
}

How do i get both to work in a single method?

Body:
So, this seems really silly, but from experimentation and reading this very informative article, it looks like the only way to do this is with two separate methods.

One for form-urlencoded data

[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId}/add)]
    public int AddRecord(UserRecord record){
        //This even populates the UserId and GroupId fields in record from     the route
    }
}

and one for json:

[Route("coreapi/control")]
public class Control : Controller
{
    [HttpPost(userGroups/{groupId}/users/{userId}/addJson)]
    public int AddRecordJson([FromBody]UserRecord record, int groupId, int userId){
        //this doesn't look in the route to populate info anymore
        record.GroupId = groupId;
        record.UserId = userId;
    }
}


问:
How to add onmouseover attribute to <OPTION></OPTION> in JavaScript?
I'm trying to add onmouseover to the option tag to display the text value. Can someone please help me on this?</p>

```<code>    var opt;

    for (var i = 0; i < response.length; ++i)
    {
        var tempResult=new Array();
        tempResult=response[i].split('|');

        opt = document.createElement("OPTION");
        opt.text = tempResult[1];
        opt.value= tempResult[0];
        opt.title = tempResult[2];
        opt.attributes.add

        matchList.options.add(opt);
    }
</code>```

答:
```<code>for (var i = 0; i < response.length; ++i)
{
    var tempResult=new Array();
    tempResult=response[i].split('|');

    var opt = document.createElement("OPTION");
    opt.text = tempResult[1];
    opt.value= tempResult[0];
    opt.title = tempResult[2];
    opt.setAttribute('onmouseover', `alert("mouseover")`);

    matchList.options.add(opt);
}
</code>```

I would recommend you learn functions and event listeners, instead. It can be much more organized than inline JavaScript.

Body:
I'm trying to add onmouseover to the option tag to display the text value. Can someone please help me on this?

    var opt;

    for (var i = 0; i < response.length; ++i)
    {
        var tempResult=new Array();
        tempResult=response[i].split('|');

        opt = document.createElement("OPTION");
        opt.text = tempResult[1];
        opt.value= tempResult[0];
        opt.title = tempResult[2];
        opt.attributes.add

        matchList.options.add(opt);
    }

Body:
for (var i = 0; i < response.length; ++i)
{
    var tempResult=new Array();
    tempResult=response[i].split('|');

    var opt = document.createElement("OPTION");
    opt.text = tempResult[1];
    opt.value= tempResult[0];
    opt.title = tempResult[2];
    opt.setAttribute('onmouseover', `alert("mouseover")`);

    matchList.options.add(opt);
}

I would recommend you learn functions and event listeners, instead. It can be much more organized than inline JavaScript.


问:
Setting command button visibility in VC++ 6.0?
How can I make the command button in my VC++ 6.0 dialog visible or invisible on load?</p>

答:
Only use</p>

```<code>ShowDlgItem(Your_DLG_ITEM_ID,1); // visible = true
ShowDlgItem(Your_DLG_ITEM_ID,0); // visible = false
</code>```

OwnerDisplayName: abcd

LastEditorDisplayName: EvilTeach

Body:
Only use

ShowDlgItem(Your_DLG_ITEM_ID,1); // visible = true
ShowDlgItem(Your_DLG_ITEM_ID,0); // visible = false


问:
How to prevent text selection from obstructing onMouseMove event?
I'm implementing a "resize handle" to change the width of my left navigation panel. It is a div that receives an onMouseDown() event, calculates the necessary widths and applies them to the right elements in the subsequent calls to onMouseMove(). But I'm having some problems.

1) The article element, to the right of the navigation panel and handle, does not activate the onMouseUp() if I release the mouse there. Is this because the onMouseDown() was activated in other element?

2) If I move the mouse fast to the right, I can't prevent the text in the article from being selected, even calling methods like preventDefault() and stopPropagation().

3) Even if there's no text in the article, the resizing only works if I move the mouse very slowly. If the mouse moves fast over the article element, the resize stops, unless I release the mouse button - in this case the resize goes smoothly (suggesting it was the text-selecting that was stopping the resize, even with no text at all). But if I release the mouse button, the resize should stop (see point 1).

I've seen some solutions using CSS user-select: none, but this would prevent any text from being selected inside article, which is obviously an overkill.

So, how can I make the resizing smooth, without selecting any text, when I move the mouse over any element in my document? (After pressing the button in the right div, of course.)

That's my HTML:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>CSS Template</title>
</head>
<body>
<header>Header</header>
<main>
    <nav id='nav'>
        <div class='navcont' onmousemove='handMm(event)' onmouseup='handMu(event)'>
            <p>nav 1</p>
            <p>nav 2</p>
        </div>
        <div class='handle' onmousedown='handMd(event)' onmousemove='handMm(event)' onmouseup='handMu(event)'>
        </div>
    </nav>
    <article id='article' onmousemove='handMm(event)' onmouseup='handMu(event)'>
    </article>
</main>
<footer>Footer</footer>
</body>
</html>
</code>```

That's my CSS:

```<code>html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#CCC;
    width:auto;
    overflow:auto;
    padding:10px;
    flex-grow:1;
}
nav {
    width:300px;
    height:auto;
    overflow: hidden;
    display:flex;
}
.navcont {
    background:#8C8;
    width:auto;
    flex-grow:1;
}
.handle {
    background:#333;
    right:0px;
    width:30px;
    cursor:col-resize;
}
footer {
    text-align:center;
}
</code>```

That's my Javascript:

```<code>var mx,px,moving=false;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
}
function handMm(e) {
    if (moving) {
        e.preventDefault();
        e.stopPropagation();
        e.cancelBubble = true;
        e.returnValue = false;
        var diff = e.pageX - mx;
        document.getElementById('nav').style.width = (px + diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    moving = false;
}
</code>```

And here is a working example: https://jsfiddle.net/45h7vq7u/

Another example, including Ryan Tsui's answer: https://jsfiddle.net/v1cmk2f6/1/ (the text-selection is gone, but the div still won't move smoothly, but only when moving fast to the right).

答: I don't know how to stop the selection but I can tell you for some help that the event triggered when something is selected is onselect.

Body:
I'm implementing a "resize handle" to change the width of my left navigation panel. It is a div that receives an onMouseDown() event, calculates the necessary widths and applies them to the right elements in the subsequent calls to onMouseMove(). But I'm having some problems.

1) The article element, to the right of the navigation panel and handle, does not activate the onMouseUp() if I release the mouse there. Is this because the onMouseDown() was activated in other element?

2) If I move the mouse fast to the right, I can't prevent the text in the article from being selected, even calling methods like preventDefault() and stopPropagation().

3) Even if there's no text in the article, the resizing only works if I move the mouse very slowly. If the mouse moves fast over the article element, the resize stops, unless I release the mouse button - in this case the resize goes smoothly (suggesting it was the text-selecting that was stopping the resize, even with no text at all). But if I release the mouse button, the resize should stop (see point 1).

I've seen some solutions using CSS user-select: none, but this would prevent any text from being selected inside article, which is obviously an overkill.

So, how can I make the resizing smooth, without selecting any text, when I move the mouse over any element in my document? (After pressing the button in the right div, of course.)

That's my HTML:

<!DOCTYPE html>

<meta charset='UTF-8'>
<title>CSS Template</title>

Header

nav 1

nav 2

Footer

That's my CSS:

html, body {
    height:100%;
    margin:0;
}
body {
    display:flex;
    flex-direction:column;
}
header {
    text-align:center;
}
main {
    flex:1;
    display:flex;
    min-height:0;
}
article {
    background:#CCC;
    width:auto;
    overflow:auto;
    padding:10px;
    flex-grow:1;
}
nav {
    width:300px;
    height:auto;
    overflow: hidden;
    display:flex;
}
.navcont {
    background:#8C8;
    width:auto;
    flex-grow:1;
}
.handle {
    background:#333;
    right:0px;
    width:30px;
    cursor:col-resize;
}
footer {
    text-align:center;
}

That's my Javascript:

var mx,px,moving=false;
function handMd(e) {
    mx = e.pageX;
    px = document.getElementById('nav').clientWidth;
    moving = true;
}
function handMm(e) {
    if (moving) {
        e.preventDefault();
        e.stopPropagation();
        e.cancelBubble = true;
        e.returnValue = false;
        var diff = e.pageX - mx;
        document.getElementById('nav').style.width = (px + diff)+'px';
        document.getElementById('article').style.width = (window.innerWidth-px-diff)+'px';
    }
}
function handMu(e) {
    moving = false;
}

And here is a working example: https://jsfiddle.net/45h7vq7u/

Another example, including Ryan Tsui's answer: https://jsfiddle.net/v1cmk2f6/1/ (the text-selection is gone, but the div still won't move smoothly, but only when moving fast to the right).


问:
Excel double click on a ribbon button to initiate macro
I have a seemingly simple problem in Excel 2013 to which I cannot find an answer. Below I described all the details. Big thanks in advance for any help.

Circumstances surrounding the problem:

I made a "QuickMacro.xlsm" workbook in Excel that contains Macro1.

Secondly I added custom ribbon (through excel tools, not in VSTO) and on that ribbon I added said macro.

Now every time I open an excel workbook I have a quick accces to that macro across all workbooks on my computer (and the workbook with said macro is hidden, so I do not see it and it does not interfere with my work)

My problem: I want Macro1 to initiate only when I double click its icon on the ribbon. Single click ought to do nothing.

My research on the problem: To find an answer I have went through many msdn materials on VSTO add ins and macros tutorials. The problem with former is that I am only a beginner in VSTO, and with latter that I find only "Worksheet_BeforeDoubleClick" events that regard cell activation, not ribbon button activation.

Question: Finally, my question is: how can it be done? Is there a way to do it with Excel only or do I need to start learning advanced VSTO? Also, I would also appreciate any general tips on where to start digging to solve this problem (except msdn sites which I have analyzed extensively). Any books maybe?

Body:
Tested by assigning this to a shape on a worksheet (so your Sub declaration may look different).

Sub MenuAction()

    Static t As Double

    '0.25 sec double-click interval
    If [NOW()] - t > (1 / 24 / 60 / 60 / 4) Then
        t = [NOW()]
        Exit Sub
    End If

    Debug.Print "double-click"
    'run your code here

End Sub

EDIT: a side note on use of [NOW()] vs. Now().  I saw a post saying that these two expressions have different precision and that [NOW()] is more precise.

For example (also included Time for comparison):

Sub Tester()
    Dim i, x

For i = 1 To 10
    'make a delay...
    For x = 1 To 3000#
        DoEvents
    Next x
    Debug.Print Time * 1, Now() * 1, [NOW()] * 1
Next i

End Sub

Output:

 Time                        Now()                       [NOW()]
 0.494270833333333           42891.4942708333            42891.4942753472
 0.494270833333333           42891.4942708333            42891.4942768519
 0.494270833333333           42891.4942708333            42891.4942782407
 0.494270833333333           42891.4942708333            42891.4942795139
 0.494270833333333           42891.4942708333            42891.4942810185
 0.494282407407407           42891.4942824074            42891.4942824074
 0.494282407407407           42891.4942824074            42891.494283912
 0.494282407407407           42891.4942824074            42891.4942851852
 0.494282407407407           42891.4942824074            42891.4942865741
 0.494282407407407           42891.4942824074            42891.4942880787

Interesting!


问:
How to parse AJAX by cURL?
I am trying to parse this url:

https://halykbank.kz/presscenter/novosti
```

<p>The news are loaded by AJAX. In network I found URL, that must show loaded news, but there only </p>

```{"result":false,"hint":"NO_AUTHORIZATION_DATA"}
```

<p>Why I am getting this? Here the URL, that I think must show me loaded news:</p>

<pre class="lang-none prettyprint-override"><code>https://backend.halykbank.kz/struct/category-items?categoryId=199&sort=position%20desc&offset=200&limit=100
</code>```

答:
You must send these header</p>

```<code>Auth-User-Id, Auth-Token, Auth-Time
</code>```

Title: How to parse AJAX by cURL?

Body:
I am trying to parse this url:

https://halykbank.kz/presscenter/novosti

The news are loaded by AJAX. In network I found URL, that must show loaded news, but there only

{"result":false,"hint":"NO_AUTHORIZATION_DATA"}

Why I am getting this? Here the URL, that I think must show me loaded news:

https://backend.halykbank.kz/struct/category-items?categoryId=199&sort=position%20desc&offset=200&limit=100

Body:
You must send these header

Auth-User-Id, Auth-Token, Auth-Time


问:
A better way to do git clone
This is lazy programmer request. I would like to create a shell script automate the following process:

```<code>git clone <remote-repo-url>
cd <cloned-folder>
open <cloned-folder>
</code>```

So the idea here is to clone a URL and then immediately cd into the cloned-folder. The trick here is to identify the cloned-folder from the url pattern.

For now we can assume that url structure is in this pattern .../<cloned-folder>.git i.e. the url.

I am wondering if we can actually do with using awk or some tools like that. The part i am stuck is finding a appropriate regex, I guess.

USE CASE: Here the use case is if you clone a url, you want to be in the repofolder as soon as possible. The is the pre-requirement if you want to run any git command like git log or mate . which we do 99% of the time.

Thanks in advance.

答:
Instead of getting directory name from url, we could just cd into the latest created directory. Here is the corresponding shell script:

```<code>gclcd() {
    git clone --recursive $* && cd "$(ls -t | head -1)"
}
</code>```

Title: A better way to do git clone

Body:
This is lazy programmer request. I would like to create a shell script automate the following process:

git clone <remote-repo-url>
cd <cloned-folder>
open <cloned-folder>

So the idea here is to clone a URL and then immediately cd into the cloned-folder. The trick here is to identify the cloned-folder from the url pattern.

For now we can assume that url structure is in this pattern .../<cloned-folder>.git i.e. the url.

I am wondering if we can actually do with using awk or some tools like that. The part i am stuck is finding a appropriate regex, I guess.

USE CASE: Here the use case is if you clone a url, you want to be in the repofolder as soon as possible. The is the pre-requirement if you want to run any git command like git log or mate . which we do 99% of the time.

Thanks in advance.

Body:
Instead of getting directory name from url, we could just cd into the latest created directory. Here is the corresponding shell script:

gclcd() {
    git clone --recursive $* && cd "$(ls -t | head -1)"
}


问:
How to read both .xsl and .xlsx using POI?
I have tried POI versions
1.poi-src-3.9-20121203 also with
2.poi-bin-3.10-beta2-20130904

But not able to read .xls file
Getting below error
"
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]"

Note:I am able to read .xlsx file.

答:
You need poi-ooxml to read xlsx format too.
Add this Maven dependency

```<code><dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>
</code>```

For xls use

```<code>Workbook  = new HSSFWorkbook(new FileInputStream(new File("fileName")));
</code>```

For xlsx use

```<code>Workbook  = workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
</code>```

If you don't know the file format before reading and sometimes finding .xls or .xlsx file extension may not be always good enough to find the actual file format. In that case do like this

```<code>Workbook workbook;
try {
    workbook = new HSSFWorkbook(new FileInputStream(new File("fileName")));
    System.out.println(" Reading XLS file");
} catch (OfficeXmlFileException e) {
    System.out.println(" Reading XLSX file");
    workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
}
</code>```

Rest is all the same .xls and .xlsx

An easier way to create workbook by autodetecting the input is

```<code>Workbook workbook = WorkbookFactory.create(new File("fileName"));
</code>```

Body:
You need poi-ooxml to read xlsx format too.
Add this Maven dependency

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>

For xls use

Workbook  = new HSSFWorkbook(new FileInputStream(new File("fileName")));

For xlsx use

Workbook  = workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));

If you don't know the file format before reading and sometimes finding .xls or .xlsx file extension may not be always good enough to find the actual file format. In that case do like this

Workbook workbook;
try {
    workbook = new HSSFWorkbook(new FileInputStream(new File("fileName")));
    System.out.println(" Reading XLS file");
} catch (OfficeXmlFileException e) {
    System.out.println(" Reading XLSX file");
    workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
}

Rest is all the same .xls and .xlsx

An easier way to create workbook by autodetecting the input is

Workbook workbook = WorkbookFactory.create(new File("fileName"));


问:
C# Error when initialize a variable in a different public class
I am trying to initialize 2 different variables in a public class but when I initialize the second one, it gets the property (Name in this example) of the first one. After I set the name of the second one. The first variable changes its name property to the second name.
For example, when I execute the code:

```<code>    //Initialization and set of first var
    findLineToolA.Name = "findLineToolA";
    findLineToolB = null;
    //After findLineToolB = new CatFindLineTool();
    findLineToolA.Name = "findLineToolA";
    findLineToolB.Name = "findLineToolA";

    //After findLineToolB.Name = "findLineToolB";
    findLineToolA.Name = "findLineToolB";
    findLineToolB.Name = "findLineToolB";

    public class CatFindLineTool
    {
            private static string _name;

            public string Name
            {
                set
                {
                    _name = value;
                }
                get
                {
                    return _name;
                }
            }
    }
public class CatFindCornerTool
{
    public CatFindLineTool findLineToolA;
    public CatFindLineTool findLineToolB;
    public CatFindCornerTool()
    {
     findLineToolA = new CatFindLineTool();
     findLineToolA.Name = "findLineToolA";
     findLineToolB = new CatFindLineTool();
     findLineToolB.Name = "findLineToolB";
    }
   }
</code>```

I hope someone can help me to figure out why the properties mix up when initialize multiple variables. I guess it is because there is an important concept about C# class that I am ignoring.
Thanks in advance.

答:
Better use Auto-property. You don't have to create a private member for name.

A public property

```<code>public string Name {get;set;}
</code>```

will automatically create the required private property for you internally.

Your issue is already addressed by Jens Meinecke

Body:
I am trying to initialize 2 different variables in a public class but when I initialize the second one, it gets the property (Name in this example) of the first one. After I set the name of the second one. The first variable changes its name property to the second name.
For example, when I execute the code:

    //Initialization and set of first var
    findLineToolA.Name = "findLineToolA";
    findLineToolB = null;
    //After findLineToolB = new CatFindLineTool();
    findLineToolA.Name = "findLineToolA";
    findLineToolB.Name = "findLineToolA";

    //After findLineToolB.Name = "findLineToolB";
    findLineToolA.Name = "findLineToolB";
    findLineToolB.Name = "findLineToolB";

    public class CatFindLineTool
    {
            private static string _name;

            public string Name
            {
                set
                {
                    _name = value;
                }
                get
                {
                    return _name;
                }
            }
    }
public class CatFindCornerTool
{
    public CatFindLineTool findLineToolA;
    public CatFindLineTool findLineToolB;
    public CatFindCornerTool()
    {
     findLineToolA = new CatFindLineTool();
     findLineToolA.Name = "findLineToolA";
     findLineToolB = new CatFindLineTool();
     findLineToolB.Name = "findLineToolB";
    }
   }

I hope someone can help me to figure out why the properties mix up when initialize multiple variables. I guess it is because there is an important concept about C# class that I am ignoring.
Thanks in advance.

Body:
Better use Auto-property. You don't have to create a private member for name.

A public property

public string Name {get;set;}

will automatically create the required private property for you internally.

Your issue is already addressed by Jens Meinecke


问:
Why use the new Android feature plugin over the library plugin?
Android recently came out with a new com.android.feature plugin to be used to split up applications into features for the new Instant apps. It seems to be an architecture they are recommending in general, not just for features you are splitting up for instant apps. You can do some reading about it's usage here.

What I'm failing to understand is what this plugin actually does better / differently than the normal android-library plugin. I ask, because my team is legitimately considering splitting up our code into feature modules, for reasons that have nothing to do with Android instant apps, and I'm not understanding what the benefit to using the com.android.feature plugin is.

答:
Update (as of May 2019): for anyone stumbling on this post, the details below are largely out-of-date now. The feature plugin (com.android.feature) is no longer "new" and is actually now being deprecated in favour of instant-enabled App Bundles. Read more on that in the official blog post.

The new feature plugin (com.android.feature) is actually almost identical to the existing library plugin (com.android.library) in the way it behaves and the way it's used.

The key difference is that the library plugin will always output an Android Archive (AAR) file where the feature plugin is able to output an AAR file when the build targets a regular Android application (via plugin com.android.application) and an APK file for that module when the build targets an Instant App (via plugin com.android.instantapp).

What are the benefits right now? Currently you only need to use the feature plugin to build for Google Play Instant (previously called Android Instant Apps). There are minimal benefits right now to using the feature plugin if you are NOT planning to build for Google Play Instant. One minor benefit might be you can output APKs for each module of your app and could install and test them independently.


问:
cakephp - create new directory inside webroot
I want to create a new directory(folder) inside the webroot so i can create/edit files inside that new folder.

My code is:

```<code>$path = 'files' . DS . 'pathtofolder';// $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) { //this is to verify if created
    echo "Exists";
}
else{
    echo "Doesnt exist";
}
</code>```

 The result is always doesnt exist. And i cant find any created folder inside my cakephp folders.

 I tried to change 'files' for 'webroot' but it doesnt work.

Is this the correct code to create a directory?

答:
There is a direct PHP call to create directories. So, you can use that. I dont know the cakephp version.

```<code>if (!mkdir($structure, 0777, true)) {
    die('Failed to create folders...');
}
</code>```

Also, check if your web-server user www-data has permissions to create directories. Otherwise, on command prompt run this command

```<code>addgroup www-data
</code>```

That will add www-data to enable permissions. You might need to add sudo in some cases to above command if you get permission denied error.

Body:
I want to create a new directory(folder) inside the webroot so i can create/edit files inside that new folder.

My code is:

$path = 'files' . DS . 'pathtofolder';// $folder_name;
$folder = new Folder($path);
if (!is_null($folder->path)) { //this is to verify if created
    echo "Exists";
}
else{
    echo "Doesnt exist";
}

 The result is always doesnt exist. And i cant find any created folder inside my cakephp folders.

 I tried to change 'files' for 'webroot' but it doesnt work.

Is this the correct code to create a directory?

Body:
There is a direct PHP call to create directories. So, you can use that. I dont know the cakephp version.

if (!mkdir($structure, 0777, true)) {
    die('Failed to create folders...');
}

Also, check if your web-server user www-data has permissions to create directories. Otherwise, on command prompt run this command

addgroup www-data

That will add www-data to enable permissions. You might need to add sudo in some cases to above command if you get permission denied error.


问:
Basic automation/looping in R
I have a list of many string values (city codes) inside an R vector:

"BOS", "NYC", "AUS", "DAL", LAX", ....

I would like to feed these individually into a function F(city,date) which returns a data frame, and store the results individually like so:

```<code>bos <- F("BOS", "2016-01-01")
nyc <- F("NYC", "2016-01-01")
aus <- F("AUS", "2016-01-01")
</code>```

and so on. How can I achieve this for a list of many cities without going one by one? I apologize for the basic question, and appreciate your help

答:
We can use Map to apply the getSummariseWeather on a vector of strings ('vec1') and the corresponding 'dates' which go as start_date argument for the function.  Here, we are assuming that the start_date can change.  If it is not changing then as the @thelatemail suggested approach would be enough

```<code>Map(getSummarizedWeather, vec1, start_date = dates)
</code>```

As a reproducible example

```<code>library(weatherData)
Map(getSummarizedWeather, c("CDG", "LHR"), start_date = c("2013-09-30",
       "2012-12-12"), end_date = c("2013-10-01", "2012-12-13"))
#$CDG
#         Date Max_TemperatureC Mean_TemperatureC Min_TemperatureC
#1 2013-09-30               18                16               13
#2 2013-10-01               19                16               13

#$LHR
#        Date Max_TemperatureC Mean_TemperatureC Min_TemperatureC
#1 2012-12-12                0                -2               -4
#2 2012-12-13                1                -1               -3
</code>```

Title: Basic automation/looping in R

Body:
I have a list of many string values (city codes) inside an R vector:

"BOS", "NYC", "AUS", "DAL", LAX", ....

I would like to feed these individually into a function F(city,date) which returns a data frame, and store the results individually like so:

bos <- F("BOS", "2016-01-01")
nyc <- F("NYC", "2016-01-01")
aus <- F("AUS", "2016-01-01")

and so on. How can I achieve this for a list of many cities without going one by one? I apologize for the basic question, and appreciate your help

Body:
We can use Map to apply the getSummariseWeather on a vector of strings ('vec1') and the corresponding 'dates' which go as start_date argument for the function.  Here, we are assuming that the start_date can change.  If it is not changing then as the @thelatemail suggested approach would be enough

Map(getSummarizedWeather, vec1, start_date = dates)

As a reproducible example

library(weatherData)
Map(getSummarizedWeather, c("CDG", "LHR"), start_date = c("2013-09-30",
       "2012-12-12"), end_date = c("2013-10-01", "2012-12-13"))
#$CDG
#         Date Max_TemperatureC Mean_TemperatureC Min_TemperatureC
#1 2013-09-30               18                16               13
#2 2013-10-01               19                16               13

#$LHR
#        Date Max_TemperatureC Mean_TemperatureC Min_TemperatureC
#1 2012-12-12                0                -2               -4
#2 2012-12-13                1                -1               -3


问:
Django ForeignKey object does not get saved when using UpdateView with InlineFormSet
I have a hard time proceeding with a special case. There's an UpdateView which I use in order to serve a standard form (a ModelForm specifically) and an inline formset.

The views.py code looks like this:

```<code>class Contract(LoginRequiredMixin, UpdateView):
    template_name = '/path/to/template.html'
    model = ContractModel
    form_class = ContractModelForm
    success_url = reverse_lazy('contract-list')

    def get_context_data(self, **kwargs):
        context = super(ContractVerificationUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            context['student_form'] = StudentsFormSet(self.request.POST)
        else:
            context['student_form'] = StudentsFormSet(instance=self.object)
        return context

    def form_valid(self, form):
        self.object = form.save(commit=False)
        context = self.get_context_data()
        student_form = context['student_form']
        if student_form.is_valid():
            self.object = form.save()
            student_form.instance = self.object
            student_form.save()
            return HttpResponseRedirect(self.get_success_url())
        else:
            return self.render_to_response(self.get_context_data(form=form))
</code>```

When I open up this update view, the student's assigned on this contract model are all shown as expected, but when I edit something on them (for example I edit a student's name), and I hit the save button, it doesn't get saved. With my debugger I've confirmed that it reaches the line student_form.save(), which should update the object I guess, though it doesn't save itself. What's wrong with this?

It's possible that it's very easy to solve but my mind is really stuck at this point! Any kind of help or suggestions is greatly welcome!

Thank you in advance!

答:
You need to call form.is_valid() before saving.

Edit your view like this,

```<code>def form_valid(self, form):
    self.object = form.save(commit=False)
    context = self.get_context_data()
    student_form = context['student_form']
    if form.is_valid() and student_form.is_valid():
        self.object = form.save()
        student_form.instance = self.object
        student_form.save()
        return HttpResponseRedirect(self.get_success_url())
    else:
        return self.render_to_response(self.get_context_data(form=form))
</code>```

Body:
I have a hard time proceeding with a special case. There's an UpdateView which I use in order to serve a standard form (a ModelForm specifically) and an inline formset.

The views.py code looks like this:

class Contract(LoginRequiredMixin, UpdateView):
    template_name = '/path/to/template.html'
    model = ContractModel
    form_class = ContractModelForm
    success_url = reverse_lazy('contract-list')

    def get_context_data(self, **kwargs):
        context = super(ContractVerificationUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            context['student_form'] = StudentsFormSet(self.request.POST)
        else:
            context['student_form'] = StudentsFormSet(instance=self.object)
        return context

    def form_valid(self, form):
        self.object = form.save(commit=False)
        context = self.get_context_data()
        student_form = context['student_form']
        if student_form.is_valid():
            self.object = form.save()
            student_form.instance = self.object
            student_form.save()
            return HttpResponseRedirect(self.get_success_url())
        else:
            return self.render_to_response(self.get_context_data(form=form))

When I open up this update view, the student's assigned on this contract model are all shown as expected, but when I edit something on them (for example I edit a student's name), and I hit the save button, it doesn't get saved. With my debugger I've confirmed that it reaches the line student_form.save(), which should update the object I guess, though it doesn't save itself. What's wrong with this?

It's possible that it's very easy to solve but my mind is really stuck at this point! Any kind of help or suggestions is greatly welcome!

Thank you in advance!

Body:
You need to call form.is_valid() before saving.

Edit your view like this,

def form_valid(self, form):
    self.object = form.save(commit=False)
    context = self.get_context_data()
    student_form = context['student_form']
    if form.is_valid() and student_form.is_valid():
        self.object = form.save()
        student_form.instance = self.object
        student_form.save()
        return HttpResponseRedirect(self.get_success_url())
    else:
        return self.render_to_response(self.get_context_data(form=form))


问:
lastwritetime is changing while extracting a zipfile in c#?
While extracting a winzip file through code,Lastwritetime is changing in seconds...

Actual file Lastwritetime:4/8/2010 2:29:03PM

After zipping that file using winzip and while extracting that file using the code,actual files Lastwritetime changes to 4/8/2010 2:29:04PM...Is there any fix for this???
Here is my code...

```<code>                Chilkat.Zip zip = new Chilkat.Zip();
                bool unlocked = zip.UnlockComponent("30-day trial");
                if (!unlocked)
                {
                    MessageBox.Show(zip.LastErrorText);
                    return;
                }

                bool success = zip.OpenZip(inputFolderPath);
                if (!success)
                {
                    MessageBox.Show(zip.LastErrorText);
                    return;
                }
                long count = zip.Unzip(outputFolderPath);
                if (count == -1)
                {
                    MessageBox.Show(zip.LastErrorText);
                }
                else
                {
                    MessageBox.Show("Unzipped Successfully!");

                }
</code>```

答: This must be an issue with the zip library itself. try using sharpZiplib, i've used it a couple of times and works like a charm. http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx</p>

Body:
While extracting a winzip file through code,Lastwritetime is changing in seconds...

Actual file Lastwritetime:4/8/2010 2:29:03PM

After zipping that file using winzip and while extracting that file using the code,actual files Lastwritetime changes to 4/8/2010 2:29:04PM...Is there any fix for this???
Here is my code...

                Chilkat.Zip zip = new Chilkat.Zip();
                bool unlocked = zip.UnlockComponent("30-day trial");
                if (!unlocked)
                {
                    MessageBox.Show(zip.LastErrorText);
                    return;
                }

                bool success = zip.OpenZip(inputFolderPath);
                if (!success)
                {
                    MessageBox.Show(zip.LastErrorText);
                    return;
                }
                long count = zip.Unzip(outputFolderPath);
                if (count == -1)
                {
                    MessageBox.Show(zip.LastErrorText);
                }
                else
                {
                    MessageBox.Show("Unzipped Successfully!");

                }


问:
How to download image asynchronously using cache and display in tableviewcell in objective-C?
I am trying to download image asynchronously using cache and display in tableviewcell in objective-C. Image is coming from URL. I have written API calling using NSSession and doing background calling using GCD but in this case image is downloading again again while scrolling. I want to image download only once.

```<code> //------------ using GCD ---------
        if(![imageUrlString isKindOfClass:[NSNull class]]){

                dispatch_async(dispatch_get_global_queue(0,0), ^{
                  NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
                    if ( data == nil )
                        return;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // WARNING: is the cell still using the same data by this point??
                        cell.imageView.image = [UIImage imageWithData: data];
                    });
                });
        }
        //------------ using GCD -----
</code>```

For same cashing is only way? if yes please suggest how can i achieve this.

答:
Try SDWedImage

```<code>[[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:imageurl] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    cell.imageView.image =  image; // if you want resize your image and any other operation can do here.
        }];
</code>```

OR

```<code>[cell.imageView sd_setImageWithURL:[NSURL URLWithString:imageurl]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
</code>```

Body:
I am trying to download image asynchronously using cache and display in tableviewcell in objective-C. Image is coming from URL. I have written API calling using NSSession and doing background calling using GCD but in this case image is downloading again again while scrolling. I want to image download only once.

 //------------ using GCD ---------
        if(![imageUrlString isKindOfClass:[NSNull class]]){

                dispatch_async(dispatch_get_global_queue(0,0), ^{
                  NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]];
                    if ( data == nil )
                        return;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // WARNING: is the cell still using the same data by this point??
                        cell.imageView.image = [UIImage imageWithData: data];
                    });
                });
        }
        //------------ using GCD -----

For same cashing is only way? if yes please suggest how can i achieve this.

Body:
Try SDWedImage

[[SDWebImageManager sharedManager]downloadImageWithURL:[NSURL URLWithString:imageurl] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
    cell.imageView.image =  image; // if you want resize your image and any other operation can do here.
        }];

OR

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:imageurl]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];


问:
Set properties on an array, funky array returned in chrome/node/canary?
From the function below should the array returned from the chrome console be displayed like this?

```<code>[ name: 'Mike', age: 60, role: 'director' ]
</code>```

When I type the array in the chrome console I get an expected syntax error returned. I understand I'm setting properties on an empty array but I thought the array wouldn't be display like this
[ name: 'Mike', age: 60, role: 'director' ]

Is this chrome trying to help me out by telling me the properties?

Entering the function in jsfiddle, firefox and safari returns an empty array but chrome displays the properties on an array.

var object = {
  name: 'Mike',
  age: 60,
  role: 'director'
}
var array = []

function test_reduce(object) {
  return Object.keys(object).reduce(function(array, key) {
    array[key] = object[key]
    return array;
  }, array)
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)

function test_Loop(object) {
  for (var key in object) {
    array[key] = object[key]
  }
  return array;
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)
console.log(test_Loop(object))```
</div>
</div>
</p>

<p>I'm using </p>

```Chrome Version 61.0.3119.0 (Official Build) canary (64-bit)
Chrome Version 58.0.3029.110 (64-bit)
Node.js v7.7.4
Safari Version 10.1.1 (12603.2.4)
Firefox 53.0.3 (64-bit)
```

答:
Arrays are specialized objects. While chrome will let you enter non-numeric keys, many other browsers will behave erratically. Perhaps you are mixing PHP arrays with JavaScript arrays. </p>

<p>PHP arrays are more equivalent to JavaScript objects. JavaScript arrays are more similar to c/java style arrays (technically, it's a linked list). </p>

Body:
From the function below should the array returned from the chrome console be displayed like this?

[ name: 'Mike', age: 60, role: 'director' ]

When I type the array in the chrome console I get an expected syntax error returned. I understand I'm setting properties on an empty array but I thought the array wouldn't be display like this
[ name: 'Mike', age: 60, role: 'director' ]

Is this chrome trying to help me out by telling me the properties?

Entering the function in jsfiddle, firefox and safari returns an empty array but chrome displays the properties on an array.

var object = {
  name: 'Mike',
  age: 60,
  role: 'director'
}
var array = []

function test_reduce(object) {
  return Object.keys(object).reduce(function(array, key) {
    array[key] = object[key]
    return array;
  }, array)
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)

function test_Loop(object) {
  for (var key in object) {
    array[key] = object[key]
  }
  return array;
}

var dummy_1 = test_reduce(object)
console.log(dummy_1)
console.log(test_Loop(object))

I'm using

Chrome Version 61.0.3119.0 (Official Build) canary (64-bit)
Chrome Version 58.0.3029.110 (64-bit)
Node.js v7.7.4
Safari Version 10.1.1 (12603.2.4)
Firefox 53.0.3 (64-bit)

Body:
Arrays are specialized objects. While chrome will let you enter non-numeric keys, many other browsers will behave erratically. Perhaps you are mixing PHP arrays with JavaScript arrays.

PHP arrays are more equivalent to JavaScript objects. JavaScript arrays are more similar to c/java style arrays (technically, it's a linked list).