问:
How to Select an item from Dropdown Menu using while Loop in Php Mysql
How do I select a particular item from the following drop-down code using while loop in php ?

I am able to populate the drop-down,but unable to select a particular item from the drop-down. Please Help, if you can. Thanks.

```<code><div class="form-group">
    <select name="submit" for="no_id">
    <?php
        $query = "SELECT * FROM crap";
        $select_dropdown = mysqli_query($conn, $query);
        #function confirm stores in functions.php
        confirm($select_dropdown);
        while($row=mysqli_fetch_assoc($select_dropdown)){
            $keyas_id= $row['keyas_id'];
            $valueas_title =$row['valueas_title'];
            echo "<option value=$keyas_id>  $valueas_title </option>";
        }
    ?>
    </select>
</div>
</code>```

答:
You can simply add if condition within option to compare whether keyas_id is equal to selected_id and if it is equal then you can select that like below:

```<code><div class="form-group">
<select name="submit" for="no_id">
<?php
    $query = "SELECT * FROM crap";
    $select_dropdown = mysqli_query($conn, $query);
    #function confirm stores in functions.php
    confirm($select_dropdown);
    $selectedId = 'Your selected ID';
    while($row=mysqli_fetch_assoc($select_dropdown)){
        $keyas_id= $row['keyas_id'];
        $valueas_title =$row['valueas_title'];
        echo "<option if($keyas_id==$selectedId) { selected='selected' } value=$keyas_id>  $valueas_title </option>";
    }
?>
</select>
</div>
</code>```

Body:
How do I select a particular item from the following drop-down code using while loop in php ?

I am able to populate the drop-down,but unable to select a particular item from the drop-down. Please Help, if you can. Thanks.

    <select name="submit" for="no_id">
    <?php
        $query = "SELECT * FROM crap";
        $select_dropdown = mysqli_query($conn, $query);
        #function confirm stores in functions.php
        confirm($select_dropdown);
        while($row=mysqli_fetch_assoc($select_dropdown)){
            $keyas_id= $row['keyas_id'];
            $valueas_title =$row['valueas_title'];
            echo "<option value=$keyas_id>  $valueas_title </option>";
        }
    ?>
    </select>

Body:
You can simply add if condition within option to compare whether keyas_id is equal to selected_id and if it is equal then you can select that like below:

<div class="form-group">
<select name="submit" for="no_id">
<?php
    $query = "SELECT * FROM crap";
    $select_dropdown = mysqli_query($conn, $query);
    #function confirm stores in functions.php
    confirm($select_dropdown);
    $selectedId = 'Your selected ID';
    while($row=mysqli_fetch_assoc($select_dropdown)){
        $keyas_id= $row['keyas_id'];
        $valueas_title =$row['valueas_title'];
        echo "<option if($keyas_id==$selectedId) { selected='selected' } value=$keyas_id>  $valueas_title </option>";
    }
?>
</select>
</div>


来源: stackexchange

问:
Linux script for which needs to input password automatically and runs background (No expect and send)
I am writing a script which is intended to run every day. Script also consists of a command where I need to input my password lets say abcd every time it execute. Is there any way that I can input password automatically when it ask for "Password:"
Thanks</p>

答:
use xdotool If not installed then first install this tool in your system using CLI as

```<code>apt-get install xdotool
</code>```

here is the simple usage

```<code>xdotool key Ctrl+Alt+t  # for opening termianl
xdotool key Ctrl+Super+Up #super
xdotool type "su" #typing su for root user
xdotool key KP_Enter #pressing enter key
</code>```

check your keyboard short cut compatibilities. I hope helps.

ContentLicense: CC BY-SA 3.0

Body:
use xdotool If not installed then first install this tool in your system using CLI as

apt-get install xdotool

here is the simple usage

xdotool key Ctrl+Alt+t  # for opening termianl
xdotool key Ctrl+Super+Up #super
xdotool type "su" #typing su for root user
xdotool key KP_Enter #pressing enter key

check your keyboard short cut compatibilities. I hope helps.


问:
Wix change exe installer icon
Well, I wrote an add-on to excel and created a msi installer for it using wix toolset. The problem is that I would like to change the installer icon, but from what I read msi installer icons can not be changed and I wanted to ask you whether it is possible to change the installer from msi to some other (eg on exe) and then change the installer icon?

[Update]

I've already change msi file to exe using wix bootstrap, but still i don't know how could i change this icon.

Thanks for all the tips / help.

This problem is not duplicate of Change exe icon based on define C#

my problem is not a duplicate of the post that was indicated, because it is a wix project and the given solution is for wpf, winforms projects.

In my project, there is no csproj file, only wixproj, which does not even have the <ApplicationIcon> tag.

Project properties are also different because there is no context in the build tab.

答:
You cannot change the icon displayed by Windows for *.msi file.

For bundle exe's use

```<code><Bundle ... IconSourceFile='path\to\product.ico'>
</code>```

This will also change the icon in the "Add/Remove Programs" (which is probably good).

Title: Wix change exe installer icon

Body:
You cannot change the icon displayed by Windows for *.msi file.

For bundle exe's use

<Bundle ... IconSourceFile='path\to\product.ico'>

This will also change the icon in the "Add/Remove Programs" (which is probably good).


问:
Remove duplicates Objects from List in Java
I know this kind of question is asked in stackoverflow lots of time before. But my issue is little bit different and I could not find any similar scenario, so posting this question here

Problem:
I need to remove duplicate objects from ArrayList. Structure of my arrayList is as below

```<code>dataList.add(new ObjectClass("a","b"));
dataList.add(new ObjectClass("c","n"));
dataList.add(new ObjectClass("b","a")); // should be counted as duplicate
dataList.add(new ObjectClass("z","x"));
</code>```

I need to remove objects from above list such as, it treats combination of "a,b" and "b,a" as duplicates and remove any of those duplicate

My solution:
step 1) Override equals method in DataClass class

```<code>class DataClass {
      String source;
      String destination;

      DataClass(String src, String dest) {
        this.source = src;
        this.destination = dest;
      }

      // getter setter for source and destination variables

    @Override
    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }
</code>```

step 2) method to remove duplicates

```<code>public List<DataClass> removeDuplicates(List<DataClass> dataList) {
            List<DataClass> resultList = new ArrayList<DataClass>();

            // Convert array list to Linked list
            LinkedList<DataClass> linkedList = new LinkedList<DataClass>();
            for(DataClass obj: dataList) {
                linkedList.add(obj);
            }

            // Iterate through linked list and remove if values are duplicates
            for(int i = 0; i<linkedList.size();i++) {
              for(int j = i+1;j<linkedList.size();j++) {
                if(linkedList.get(j).equals(linkedList.get(i))) {
                    linkedList.remove();
                }
              }
            }
            resultList.addAll(linkedList);
            return resultList;
        }
</code>```

I am still looking for any better optimized solution, if there is any. Thanks in advance

Update with solution
: my equals method was needed to correct some comparison logic. So here is my updated ObjectClass instead of DataClass including correct overridden equals method

```<code>public class ObjectClass {
    String i;
    String j;
    public  ObjectClass(String i, String j) {
        this.i = i;
        this.j = j;
    }
    // getters setters
    // override hashcode

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;

        if((i.equals(other.getJ()) || i.equals(other.getI()))
            && (j.equals(other.getI()) || j.equals(other.getJ()))) {
            return true;
        } else return false;
    }
}
</code>```

2) After fixing equals method I tried below implementation in removeDuplicate method as Janos mentioned and it is working fine as expected

```<code>    for(ObjectClass obj: dataList) {
        if(!resultList.contains(obj))
            resultList.add(obj);
    }
</code>```

Thank you very much

答:
There are several problems here:

```<code>class DataClass {
      String source;
      String destination;

      // ...

    @Override
    public boolean equals(Object obj) {
        // ...
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }
</code>```

The equals method casts the other object to ObjectClass.
It should cast to the same class where this method is defined: DataClass.

The equals method compares i and j variables,
but they are not defined anywhere within the class.
There's source and destination.

The equals method will return true when this.i is the same as other.j and this.j is the same as other.i, and return false otherwise. In other words, (a, b) will be equal to (b, a). But it will not be equal to itself. That's very strange, and probably not what you intended.

The removeDuplicates method is overcomplicated.
For example converting an array list to a linked list is unnecessary.
Here's a much simpler algorithm:

For each value in the source list

If the value does not exist in the result list, add it to the result list

That's it.

```<code>List<DataClass> result = new ArrayList<>();

for (DataClass item : dataList) {
    if (!result.contains(item)) {
        result.add(item);
    }
}
return result;
</code>```

This assumes that the implementation of the equals method is fixed.
Otherwise the result.contains step will not work correctly.

Also note that result.contains performs a linear search:
it checks every item until it finds a match.
You could improve performance by using a set.

Body:
I know this kind of question is asked in stackoverflow lots of time before. But my issue is little bit different and I could not find any similar scenario, so posting this question here

Problem:
I need to remove duplicate objects from ArrayList. Structure of my arrayList is as below

dataList.add(new ObjectClass("a","b"));
dataList.add(new ObjectClass("c","n"));
dataList.add(new ObjectClass("b","a")); // should be counted as duplicate
dataList.add(new ObjectClass("z","x"));

I need to remove objects from above list such as, it treats combination of "a,b" and "b,a" as duplicates and remove any of those duplicate

My solution:
step 1) Override equals method in DataClass class

class DataClass {
      String source;
      String destination;

      DataClass(String src, String dest) {
        this.source = src;
        this.destination = dest;
      }

      // getter setter for source and destination variables

    @Override
    public boolean equals(Object obj) {
        System.out.println("inside equals");
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }

step 2) method to remove duplicates

public List<DataClass> removeDuplicates(List<DataClass> dataList) {
            List<DataClass> resultList = new ArrayList<DataClass>();

            // Convert array list to Linked list
            LinkedList<DataClass> linkedList = new LinkedList<DataClass>();
            for(DataClass obj: dataList) {
                linkedList.add(obj);
            }

            // Iterate through linked list and remove if values are duplicates
            for(int i = 0; i<linkedList.size();i++) {
              for(int j = i+1;j<linkedList.size();j++) {
                if(linkedList.get(j).equals(linkedList.get(i))) {
                    linkedList.remove();
                }
              }
            }
            resultList.addAll(linkedList);
            return resultList;
        }

I am still looking for any better optimized solution, if there is any. Thanks in advance

Update with solution
: my equals method was needed to correct some comparison logic. So here is my updated ObjectClass instead of DataClass including correct overridden equals method

public class ObjectClass {
    String i;
    String j;
    public  ObjectClass(String i, String j) {
        this.i = i;
        this.j = j;
    }
    // getters setters
    // override hashcode

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ObjectClass other = (ObjectClass) obj;

        if((i.equals(other.getJ()) || i.equals(other.getI()))
            && (j.equals(other.getI()) || j.equals(other.getJ()))) {
            return true;
        } else return false;
    }
}

2) After fixing equals method I tried below implementation in removeDuplicate method as Janos mentioned and it is working fine as expected

    for(ObjectClass obj: dataList) {
        if(!resultList.contains(obj))
            resultList.add(obj);
    }

Thank you very much

Body:
There are several problems here:

class DataClass {
      String source;
      String destination;

      // ...

    @Override
    public boolean equals(Object obj) {
        // ...
        ObjectClass other = (ObjectClass) obj;
        if(i.equals(other.getJ())
            && j.equals(other.getI())) {
            return true;
        } else return false;
    }

The equals method casts the other object to ObjectClass.
It should cast to the same class where this method is defined: DataClass.

The equals method compares i and j variables,
but they are not defined anywhere within the class.
There's source and destination.

The equals method will return true when this.i is the same as other.j and this.j is the same as other.i, and return false otherwise. In other words, (a, b) will be equal to (b, a). But it will not be equal to itself. That's very strange, and probably not what you intended.

The removeDuplicates method is overcomplicated.
For example converting an array list to a linked list is unnecessary.
Here's a much simpler algorithm:

For each value in the source list

If the value does not exist in the result list, add it to the result list

That's it.

List<DataClass> result = new ArrayList<>();

for (DataClass item : dataList) {
    if (!result.contains(item)) {
        result.add(item);
    }
}
return result;

This assumes that the implementation of the equals method is fixed.
Otherwise the result.contains step will not work correctly.

Also note that result.contains performs a linear search:
it checks every item until it finds a match.
You could improve performance by using a set.


问:
Javascript: Group data by dates and fill in the days in between
I have a event data array of objects with just the end and start date for each event.

```<code>let listOfEvents = [{
  "end": Date 2017-12-09T11:12:00.000Z,
  "start": Date 2017-12-14T03:12:00.000Z,
  "title": "Event One"
},{
  "end": Date 2017-11-10T11:12:00.000Z,
  "start": Date 2017-11-12T03:12:00.000Z,
  "title": "Event Two"
}]
</code>```

This is what I want the final output to be

```<code>    let listOfEvents = [{
      "date": Date 2017-12-09T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-12-10T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-11T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-12T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-13T03:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-14T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-11-10T11:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-11T03:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-12T03:12:00.000Z,
      "title": "Event Two"
    }]
</code>```

This is what I have currently,

```<code>let newEvents = [];
listOfEvents.forEach(function (item) {
        newEvents.push({
            date: item.start,
            title: item.title
        })
    });
</code>```

How would I add logic to fill in the day and add a day for each new entry to the end date then continue on the loop? I can include momentjs if needed.

答:
You can use array#reduce and compare the dates and keep adding each new day to result array till your end date is less than start date.

let listOfEvents = [{ "end": "2017-12-09T11:12:00.000Z", "start": "2017-12-14T03:12:00.000Z", "title": "Event One" },{ "end": "2017-11-10T11:12:00.000Z", "start": "2017-11-12T03:12:00.000Z", "title": "Event Two" }];

var result = listOfEvents.reduce((r, {
  end,
  start,
  title
}) => {
  end = new Date(end);
  start = new Date(start);

  while (end < start) {
    r.push({
      'date': new Date(end),
      title
    });
    end.setDate(end.getDate() + 1);
  }
  if (Math.abs(start.getTime() - end.getTime()) < 1000 * 3600 * 24) {
    r.push({
      'date': new Date(start),
      title
    });
  }

  return r;
}, []);
console.log(result);```

Body:
I have a event data array of objects with just the end and start date for each event.

let listOfEvents = [{
  "end": Date 2017-12-09T11:12:00.000Z,
  "start": Date 2017-12-14T03:12:00.000Z,
  "title": "Event One"
},{
  "end": Date 2017-11-10T11:12:00.000Z,
  "start": Date 2017-11-12T03:12:00.000Z,
  "title": "Event Two"
}]

This is what I want the final output to be

    let listOfEvents = [{
      "date": Date 2017-12-09T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-12-10T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-11T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-12T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-13T03:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-14T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-11-10T11:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-11T03:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-12T03:12:00.000Z,
      "title": "Event Two"
    }]

This is what I have currently,

let newEvents = [];
listOfEvents.forEach(function (item) {
        newEvents.push({
            date: item.start,
            title: item.title
        })
    });

How would I add logic to fill in the day and add a day for each new entry to the end date then continue on the loop? I can include momentjs if needed.


问:
Display image from JSON/API in React using JSX
I'm a React noob and I'm making an API request to retrieve JSON from a movie API and then displaying information about the movies, including the movie poster, in my component. I was able to retrieve and display text, but I am having trouble displaying images using JSX and the URL of the database.

I've assigned the images to post.poster_path and I'm attempting to concatenate the rest of the URL to the JSX.

```<code><img src={"https://image.tmdb.org/t/p/w300/"+post.poster_path} alt="Movie Poster"/>
</code>```

This doesn't work.

poster_path contains the image, I have verfied this in React tools. How do I properly concatenate the rest of the URL to post.poster_path?

答:
If

post.poster_path = 'image.png'

and the whole url is

https://image.tmdb.org/t/p/w300/image.png"

for your image then the img tag will be as follows

```<code><img src={`https://image.tmdb.org/t/p/w300/${post.poster_path}`} alt="Movie Poster"/>
</code>```

In JSX if you have a value in variable and need to concat with a string you use tick `

```<code>eg. {`string ${variableName}`}
</code>```

and if post.poster_path has the whole path then:

```<code><img src={post.poster_path} alt="Movie Poster"/>
</code>```

Body:
I'm a React noob and I'm making an API request to retrieve JSON from a movie API and then displaying information about the movies, including the movie poster, in my component. I was able to retrieve and display text, but I am having trouble displaying images using JSX and the URL of the database.

I've assigned the images to post.poster_path and I'm attempting to concatenate the rest of the URL to the JSX.

This doesn't work.

poster_path contains the image, I have verfied this in React tools. How do I properly concatenate the rest of the URL to post.poster_path?

Body:
If

post.poster_path = 'image.png'

and the whole url is

https://image.tmdb.org/t/p/w300/image.png"

for your image then the img tag will be as follows

<img src={`https://image.tmdb.org/t/p/w300/${post.poster_path}`} alt="Movie Poster"/>

In JSX if you have a value in variable and need to concat with a string you use tick `

eg. {`string ${variableName}`}

and if post.poster_path has the whole path then:

<img src={post.poster_path} alt="Movie Poster"/>


问:
Project Euler 18
Hey, been working at Project Euler, and this one is giving me some problems

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3

7 4

2 4 6

8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

...

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

here's the algorithm I've used to solve it

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Problem18
{
    class Program
    {
        static void Main(string[] args)
        {
            string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
            string[] rows = triangle.Split('\n');
            int currindex = 1;
            int total = int.Parse(rows[0]);
            Console.WriteLine(rows[0]);
            for (int i = 1; i < rows.Length; i++)
            {
                string[] array1 = rows[i].Split(' ');
                if (array1.Length > 1)
                {
                    if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
                    {
                        Console.WriteLine(array1[currindex - 1]);
                        total += int.Parse(array1[currindex - 1]);
                    }
                    else
                    {
                        Console.WriteLine(array1[currindex]);
                        total += int.Parse(array1[currindex]);
                        currindex++;
                    }
                }
            }
            Console.WriteLine("Total: " + total);
            Console.ReadKey();
        }
    }
}
</code>```

now whenever i run it, it comes up with 1064, only 10 less then the solution -- 1074

i haven't found any problems with the algorithm and I did the problem by hand and also came up with 1064, anyone know if the solution is wrong, i'm interpreting the question wrong, or if there's just a flaw in the algorithm?

答:
Your problem is that your algorithm is a greedy algorithm, always finding local maxima. Unfortunately that causes it to miss higher numbers down below because they are directly below lower numbers. For example, if the triangle were only 3 levels, your algorithm would pick 75 + 95 + 47 = 217, while the correct answer is 75 + 64 + 82 = 221.

The correct algorithm will either try every path and choose the one with the highest total, or compute paths from the bottom up (which allows you to avoid trying every one, thus being much faster). I should add that working from the bottom-up is not only much faster (O(n^2) instead of O(2^n)!), but also much easier to write (I did it in about 3 lines of code).

ContentLicense: CC BY-SA 2.5

Title: Project Euler 18

Body:
Hey, been working at Project Euler, and this one is giving me some problems

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3

7 4

2 4 6

8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

...

NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; it cannot be solved by brute force, and requires a clever method! ;o)

here's the algorithm I've used to solve it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Problem18
{
    class Program
    {
        static void Main(string[] args)
        {
            string triangle = @"75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23";
            string[] rows = triangle.Split('\n');
            int currindex = 1;
            int total = int.Parse(rows[0]);
            Console.WriteLine(rows[0]);
            for (int i = 1; i < rows.Length; i++)
            {
                string[] array1 = rows[i].Split(' ');
                if (array1.Length > 1)
                {
                    if (int.Parse(array1[currindex - 1]) > int.Parse(array1[currindex]))
                    {
                        Console.WriteLine(array1[currindex - 1]);
                        total += int.Parse(array1[currindex - 1]);
                    }
                    else
                    {
                        Console.WriteLine(array1[currindex]);
                        total += int.Parse(array1[currindex]);
                        currindex++;
                    }
                }
            }
            Console.WriteLine("Total: " + total);
            Console.ReadKey();
        }
    }
}

now whenever i run it, it comes up with 1064, only 10 less then the solution -- 1074

i haven't found any problems with the algorithm and I did the problem by hand and also came up with 1064, anyone know if the solution is wrong, i'm interpreting the question wrong, or if there's just a flaw in the algorithm?


问:
How do I check my email is available in database or not
I wrote one model that is having email field. I added some emails to it by admin. What I need is when I type any email that should check with my database email if exist it should show email is already there:

models.py #in my database already some data is there

```<code>class Friend(models.Model):
    email = models.EmailField(max_length=100)

    def __str__(self):
        return self.email
</code>```

forms.py

```<code>class FriendForm(forms.ModelForm):
    class Meta:
        model = Friend
        fields = ['email']
</code>```

views.py

```<code>def check(request):
    form = FriendForm(request.POST or None)
    if form.is_valid():
        form = Friend.objects.filter(**form.cleaned_data)
    context = {
        'form': form
    }
    return render(request, "one.html", context)
</code>```

I imported every thing. When I am trying this code it is directly rendering to one.html. What I need is it should check if email is there in database then only it should render.

答:
```<code>class Friend(models.Model):
     email = models.EmailField(max_length=100,unique=True,error_messages={'error':'The Email already exists'})
</code>```

<p>you can change your model to this. </p>

```<code>if form.is_valid():
    form = Friend.objects.filter(**form.cleaned_data)
else:
    redirect('to_some_page')
</code>```

Body:
I wrote one model that is having email field. I added some emails to it by admin. What I need is when I type any email that should check with my database email if exist it should show email is already there:

models.py #in my database already some data is there

class Friend(models.Model):
    email = models.EmailField(max_length=100)

    def __str__(self):
        return self.email

forms.py

class FriendForm(forms.ModelForm):
    class Meta:
        model = Friend
        fields = ['email']

views.py

def check(request):
    form = FriendForm(request.POST or None)
    if form.is_valid():
        form = Friend.objects.filter(**form.cleaned_data)
    context = {
        'form': form
    }
    return render(request, "one.html", context)

I imported every thing. When I am trying this code it is directly rendering to one.html. What I need is it should check if email is there in database then only it should render.

Body:
class Friend(models.Model):
     email = models.EmailField(max_length=100,unique=True,error_messages={'error':'The Email already exists'})

you can change your model to this.

if form.is_valid():
    form = Friend.objects.filter(**form.cleaned_data)
else:
    redirect('to_some_page')


问:
How to scale point size and color at the same time in ggvis?
Considering a data.frame like this:

```<code>df <- data.frame(t = rep(seq(from=as.POSIXct('00:15:00',format='%H:%M:%S'),
                             to=as.POSIXct('24:00:00',format='%H:%M:%S'),by='15 min'),times=2),
                     y = c(rnorm(96,10,10),rnorm(96,40,5)),
                     group = factor(rep(1:2,each=96)),
                     type = factor(rep(1:3,each=64)))
</code>```

Using ggvis, I want to generate a point-line plot in which the line is grouped by group. The size of points with type==3 should be 100 while the size of points withtype==1 and type==2 are all 50. The colour of the points should be green, blue and red corresponding to type1,type2 and type3. Here is my ggvis code:

```<code>df <- data.frame(df,id=1:nrow(df))

all_values <- function(x) {
  if(is.null(x)) return(NULL)
  row <- df[df$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "<br />")
}

ggvis(data=df,x=~t,y=~y,stroke=~group) %>%
  layer_points(fill=~type,size=~type, key:=~id, fillOpacity := 0.5,
               fillOpacity.hover := 0.8,size.hover := 500) %>%
  scale_nominal("size",domain = c(1,2,3), range = c(50,50,100)) %>%
  scale_nominal("fill",domain = c(1,2,3), range = c('green','blue','red')) %>%
  layer_lines() %>%
  add_tooltip(all_values,'click') %>%
  add_legend(scales=c("fill","size"), properties = legend_props(legend = list(y = 150))) %>%
  set_options(duration = 0) %>%
  add_axis(type="x",format="%H:%M")
</code>```

I get the error of Error: length(x) not less than or equal to 2.
Why this happened and how can I fix it?

答: It turns out that scale_nominal("size",domain = c(1,2,3), range = c(50,50,100)) should be replaced by scale_nominal("size",domain = c(1,2,3), range = c('50','50','100')).

Body:
Considering a data.frame like this:

df <- data.frame(t = rep(seq(from=as.POSIXct('00:15:00',format='%H:%M:%S'),
                             to=as.POSIXct('24:00:00',format='%H:%M:%S'),by='15 min'),times=2),
                     y = c(rnorm(96,10,10),rnorm(96,40,5)),
                     group = factor(rep(1:2,each=96)),
                     type = factor(rep(1:3,each=64)))

Using ggvis, I want to generate a point-line plot in which the line is grouped by group. The size of points with type==3 should be 100 while the size of points withtype==1 and type==2 are all 50. The colour of the points should be green, blue and red corresponding to type1,type2 and type3. Here is my ggvis code:

df <- data.frame(df,id=1:nrow(df))

all_values <- function(x) {
  if(is.null(x)) return(NULL)
  row <- df[df$id == x$id, ]
  paste0(names(row), ": ", format(row), collapse = "
")
}

ggvis(data=df,x=~t,y=~y,stroke=~group) %>%
  layer_points(fill=~type,size=~type, key:=~id, fillOpacity := 0.5,
               fillOpacity.hover := 0.8,size.hover := 500) %>%
  scale_nominal("size",domain = c(1,2,3), range = c(50,50,100)) %>%
  scale_nominal("fill",domain = c(1,2,3), range = c('green','blue','red')) %>%
  layer_lines() %>%
  add_tooltip(all_values,'click') %>%
  add_legend(scales=c("fill","size"), properties = legend_props(legend = list(y = 150))) %>%
  set_options(duration = 0) %>%
  add_axis(type="x",format="%H:%M")

I get the error of Error: length(x) not less than or equal to 2.
Why this happened and how can I fix it?


问:
compile c++ code using makefile dynamically
It is about makefile and I wonder if makefile can compile cpp files dynamically.

Suppose I have main.cpp, a.cpp, b.cpp, and c.cpp files.(probably d.cpp, e.cpp and more can be added)

main.cpp file has main() function and a, b and c have their own functions.

Sometimes I only want to compile main.cpp, a.cpp and b.cpp files and link them.

But sometimes compile main.cpp, b.cpp and c.cpp files and link.
No rules for what files I want to choose to compile.

What I think is like

make a b

make b c

make a c

or

make a b c

then only the file name specified can be compiled and link with main.cpp file.

Is there a good way for this to be done?

Thank you.

答:
There is a simple solution: make variables that you can pass on the command line. They take precedence over the definitions in the Makefile.

```<code>$ cat Makefile
SRCS = $(filter-out main,$(patsubst %.cpp,%,$(wildcard *.cpp)))

main: main.o $(patsubst %,%.o,$(SRCS))
    $(CXX) -o $@ $^

clean:
    rm -f $(wildcard *.o) main
</code>```

Then, if you want to link only a and b:

```<code>$ make SRCS="a b"
c++    -c -o main.o main.cpp
c++    -c -o a.o a.cpp
c++    -c -o b.o b.cpp
c++ -o main main.o a.o b.o
</code>```

If you want to link only c and d:

```<code>$ make clean
rm -f a.o b.o main.o main
$ make SRCS="c d"
c++    -c -o main.o main.cpp
c++    -c -o c.o c.cpp
c++    -c -o d.o d.cpp
c++ -o main main.o c.o d.o
</code>```

And the default:

```<code>$ make clean
rm -f c.o d.o main.o main
$ make
c++    -c -o main.o main.cpp
c++    -c -o a.o a.cpp
c++    -c -o b.o b.cpp
c++    -c -o c.o c.cpp
c++    -c -o d.o d.cpp
c++ -o main main.o a.o b.o c.o d.o
</code>```

If the default does not make sense (e.g. because methods are defined in several source files), change the default value of SRCS in the Makefile:

```<code>SRCS = a b
</code>```

Note: do not mix up make variables, which definition appears after the make command on the command line: make ... VAR=VALUE ... and the environment variables that you can pass to the make process: VAR=VALUE make .... There are relations between the two but they are completely different things.

Body:
There is a simple solution: make variables that you can pass on the command line. They take precedence over the definitions in the Makefile.

$ cat Makefile
SRCS = $(filter-out main,$(patsubst %.cpp,%,$(wildcard *.cpp)))

main: main.o $(patsubst %,%.o,$(SRCS))
    $(CXX) -o $@ $^

clean:
    rm -f $(wildcard *.o) main

Then, if you want to link only a and b:

$ make SRCS="a b"
c++    -c -o main.o main.cpp
c++    -c -o a.o a.cpp
c++    -c -o b.o b.cpp
c++ -o main main.o a.o b.o

If you want to link only c and d:

$ make clean
rm -f a.o b.o main.o main
$ make SRCS="c d"
c++    -c -o main.o main.cpp
c++    -c -o c.o c.cpp
c++    -c -o d.o d.cpp
c++ -o main main.o c.o d.o

And the default:

$ make clean
rm -f c.o d.o main.o main
$ make
c++    -c -o main.o main.cpp
c++    -c -o a.o a.cpp
c++    -c -o b.o b.cpp
c++    -c -o c.o c.cpp
c++    -c -o d.o d.cpp
c++ -o main main.o a.o b.o c.o d.o

If the default does not make sense (e.g. because methods are defined in several source files), change the default value of SRCS in the Makefile:

SRCS = a b

Note: do not mix up make variables, which definition appears after the make command on the command line: make ... VAR=VALUE ... and the environment variables that you can pass to the make process: VAR=VALUE make .... There are relations between the two but they are completely different things.


问:
Can you write a concept for ContiguousIterator?
I know there is concept for ContiguousIterator in words specification sense, but I wonder if it can be written using C++20/C++17 Concepts TS syntax.

My problem with this is that unlike RandomAccessIterator ContiguousIterator  requires not just some operations like it+123 to work, but depends on runtime result of that operation.

答: Your problem is currently unsolvable. The committee is considering what to do about deducing contiguous memory access. The flub is that iterator_category is not a trait (although it resides in iterator_traits); It is an ad-hoc type. It cannot be subtyped without breaking existing code. (Beginner mistake, eh what?) The Committee has recognized the mess.  This recent discussion tells all -> How to deduce contiguous memory from iterator</p>


问:
java.io.IOException: Cannot run program adb.exe CreateProcess error=5, Access is denied
I am trying to run code in android studio gets following Error:

java.io.IOException: Cannot run program
  "C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools\adb.exe":
  CreateProcess error=5, Access is denied

What will be the cause.
Also while creating AVD getting this Error:

java.io.IOException: Cannot run program
  "C:\Users\Admin\AppData\Local\Android\Sdk\emulator\emulator-check.exe":
  CreateProcess error=5, Access is denied

答:
It's a Windows Security issue. You need to give yourself the proper permissions to run ADB.

Using Windows Explorer, navigate to :

```<code>C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools\adb.exe
</code>```

1) Right click on the adb.exe icon and select Properties;

2) In the Properties window, select the Security tab;

3) Select your user name and give yourself full control;

4) Click Apply

Why did you have to do this when ADB was working before, you ask? Because you just updated the Android SDK and the new version of ADB overwrote the old version which had the proper permissions.

Body:
It's a Windows Security issue. You need to give yourself the proper permissions to run ADB.

Using Windows Explorer, navigate to :

C:\Users\Admin\AppData\Local\Android\Sdk\platform-tools\adb.exe

1) Right click on the adb.exe icon and select Properties;

2) In the Properties window, select the Security tab;

3) Select your user name and give yourself full control;

4) Click Apply

Why did you have to do this when ADB was working before, you ask? Because you just updated the Android SDK and the new version of ADB overwrote the old version which had the proper permissions.


问:
How do I extract images from a MMS sent using Twilio into a Azure Blob Storage using an Azure Logic app?
In my question on getting text messages into Azure
I was able to get the message of an SMS into Azure Table Store.

In the case where the text message contains images and thus has been sent as a MMS I want to download the images into Azure Blob Storage.

Twilo has  a guide on how to download and receive images

But I am not sure how to make use of this with a Logic App

I tried studying this Twilio guide and cloned the code from GitHub.
Confusingly the DownloadMmsImages is in the same solution as a BlockSpamCalls project. I was unclear about the relationship between the 2 projects.

I tried adding a Twilio GetMessage action however the only property that I am prompted to put in the Message SID is Body.

The (slightly obfuscated ) request body JSON schema is

```<code>{
  "body": {
    "$content": "VG9Db3VudHJ etc",
    "$content-type": "application/json",
    "$formdata": [
      {
        "key": "ToCountry",
        "value": "AU"
      },
      {
        "key": "ToState",
        "value": ""
      },
      {
        "key": "SmsMessageSid",
        "value": "SMeda21902 etc"
      },
      {
        "key": "NumMedia",
        "value": "0"
      },
      {
        "key": "ToCity",
        "value": ""
      },
      {
        "key": "FromZip",
        "value": ""
      },
      {
        "key": "SmsSid",
        "value": "SMeda2 etc"
      },
      {
        "key": "FromState",
        "value": ""
      },
      {
        "key": "SmsStatus",
        "value": "received"
      },
      {
        "key": "FromCity",
        "value": ""
      },
      {
        "key": "Body",
        "value": "Tskez7"
      },
      {
        "key": "FromCountry",
        "value": "AU"
      },
      {
        "key": "To",
        "value": "+61 etc"
      },
      {
        "key": "ToZip",
        "value": ""
      },
      {
        "key": "NumSegments",
        "value": "1"
      },
      {
        "key": "MessageSid",
        "value": "SMeda2 etc"
      },
      {
        "key": "AccountSid",
        "value": "AC7aa etc"
      },
      {
        "key": "From",
        "value": "+61 etc"
      },
      {
        "key": "ApiVersion",
        "value": "2010-04-01"
      }
    ]
  },
  "headers": {
    "Accept": "*/*",
    "Cache-Control": "max-age=259200",
    "Connection": "close",
    "Content-Length": "381",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "etc.logic.azure.com:443",
    "User-Agent": "TwilioProxy/1.1",
    "X-Twilio-Signature": "sQf etc"
  }
}
</code>```

答:
DISCLAIMER I apologize in advance if something in this answer does not quite work. I do not have an account with Twilio and am unable to test the solution end-to-end. Please, think of it as a draft that is supposed to demonstrate the main steps and key details required to achieve the desired results.

Getting the message SID

When you try to retrieve a message (or the message's media), you indeed need to provide the SID/SIDs of the message and/or the media, which are basically their identifiers. I assume, this instance of Logic App is receiving the SID(s) as a part of the incoming HttpRequest trigger.

For example, you may require the consumer of the Logic App to provide the message SID in the URL of an HTTP GET request, as shown below.

```<code>{
  "kind": "Http",
  "inputs": {
    "schema": {},
    "method": "GET",
    "relativePath": "message/{mms_message_sid}"
  }
}
</code>```

Then, you will be able to refer to this SID in the further steps of your Logic App.

```<code>{
  "inputs": {
    "host": {
      "connection": {
        "name": "@parameters('$connections')['twilio']['connectionId']"
      }
    },
    "method": "get",
    "path": "/Messages/@{encodeURIComponent(triggerOutputs()['relativePathParameters']['mms_message_sid'])}.json",
    "authentication": "@parameters('$authentication')"
  }
}
</code>```

Retrieving the Message

I briefly looked at the Twilio connector and let me recommend you to not use it because it's going to complicate your Logic App a lot.

Instead, you can use the Get Media API via Http connector. You will need to construct a URL of the following form: https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages/{mms_message_sid}/Media.json

You should then receive a response which contains the message's media_list with content_type and the uri you can use to download the actual content of the MMS.

```<code>{
  "first_page_uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media.json?PageSize=50&Page=0",
  "media_list":[
  {
    "sid":"ME85ebf7e12cb821f84b319340424dcb02",
    "account_sid":"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "parent_sid":"MM800f449d0399ed014aae2bcc0cc2f2ec",
    "content_type":"image/png",
    "date_created":"Wed, 25 Sep 2013 22:47:18 +0000",
    "date_updated":"Wed, 25 Sep 2013 22:47:19 +0000",
    "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media/ME85ebf7e12cb821f84b319340424dcb02.json"
  },
  {
    "sid":"ME8d8f717e2d6e5383055b3cd150ac5f54",
    "account_sid":"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "parent_sid":"MM800f449d0399ed014aae2bcc0cc2f2ec",
    "content_type":"image/png",
    "date_created":"Wed, 25 Sep 2013 22:47:18 +0000",
    "date_updated":"Wed, 25 Sep 2013 22:47:19 +0000",
    "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media/ME8d8f717e2d6e5383055b3cd150ac5f54.json"
  }
  ],
  "previous_page_uri":null,
  "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media.json?PageSize=50&Page=0",
  "page_size":50,
  "next_page_uri":null,
  "page":0
}
</code>```

Parse the response JSON

Since the response body is a JSON document expressed as a string, we won't be able to iterate media_list array, unless we jump through some hoops.

Just add a parse JSON step, which uses the body of the previous step (HTTP) as Content. For the schema provide the following document:

```<code>{
  "inputs": {
    "content": "@body('HTTP')",
    "schema": {
      "type": "object",
      "properties": {
        "first_page_uri": {
          "type": "string"
        },
        "media_list": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "sid": {
                "type": "string"
              },
              "account_sid": {
                "type": "string"
              },
              "parent_sid": {
                "type": "string"
              },
              "content_type": {
                "type": "string"
              },
              "date_created": {
                "type": "string"
              },
              "date_updated": {
                "type": "string"
              },
              "uri": {
                "type": "string"
              }
            },
            "required": [
              "sid",
              "account_sid",
              "parent_sid",
              "content_type",
              "date_created",
              "date_updated",
              "uri"
            ]
          }
        },
        "previous_page_uri": {},
        "uri": {
          "type": "string"
        },
        "page_size": {
          "type": "number"
        },
        "next_page_uri": {},
        "page": {
          "type": "number"
        }
      }
    }
  }
}
</code>```

Iterate through `media_list`

Now the things are relatively easier. You add a For Each step that targets media_list from the previous step.

For each media we need to make an API call that actually retrieves its binary contents. You may want to specify media type related HTTP headers. Play around that and see what works.

Save into Azure Blob Storage

I will not provide any details here because you said, you already know how to do that for the SMS. Just make sure you add the necessary step(s) right after the HTTP2 (inside the For Each step).

Hope, it helps. Logic Apps is NOT "easy peasy integration squeeze".

Body:
In my question on getting text messages into Azure
I was able to get the message of an SMS into Azure Table Store.

In the case where the text message contains images and thus has been sent as a MMS I want to download the images into Azure Blob Storage.

Twilo has  a guide on how to download and receive images

But I am not sure how to make use of this with a Logic App

I tried studying this Twilio guide and cloned the code from GitHub.
Confusingly the DownloadMmsImages is in the same solution as a BlockSpamCalls project. I was unclear about the relationship between the 2 projects.

I tried adding a Twilio GetMessage action however the only property that I am prompted to put in the Message SID is Body.

The (slightly obfuscated ) request body JSON schema is

{
  "body": {
    "$content": "VG9Db3VudHJ etc",
    "$content-type": "application/json",
    "$formdata": [
      {
        "key": "ToCountry",
        "value": "AU"
      },
      {
        "key": "ToState",
        "value": ""
      },
      {
        "key": "SmsMessageSid",
        "value": "SMeda21902 etc"
      },
      {
        "key": "NumMedia",
        "value": "0"
      },
      {
        "key": "ToCity",
        "value": ""
      },
      {
        "key": "FromZip",
        "value": ""
      },
      {
        "key": "SmsSid",
        "value": "SMeda2 etc"
      },
      {
        "key": "FromState",
        "value": ""
      },
      {
        "key": "SmsStatus",
        "value": "received"
      },
      {
        "key": "FromCity",
        "value": ""
      },
      {
        "key": "Body",
        "value": "Tskez7"
      },
      {
        "key": "FromCountry",
        "value": "AU"
      },
      {
        "key": "To",
        "value": "+61 etc"
      },
      {
        "key": "ToZip",
        "value": ""
      },
      {
        "key": "NumSegments",
        "value": "1"
      },
      {
        "key": "MessageSid",
        "value": "SMeda2 etc"
      },
      {
        "key": "AccountSid",
        "value": "AC7aa etc"
      },
      {
        "key": "From",
        "value": "+61 etc"
      },
      {
        "key": "ApiVersion",
        "value": "2010-04-01"
      }
    ]
  },
  "headers": {
    "Accept": "*/*",
    "Cache-Control": "max-age=259200",
    "Connection": "close",
    "Content-Length": "381",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "etc.logic.azure.com:443",
    "User-Agent": "TwilioProxy/1.1",
    "X-Twilio-Signature": "sQf etc"
  }
}

Body:
DISCLAIMER I apologize in advance if something in this answer does not quite work. I do not have an account with Twilio and am unable to test the solution end-to-end. Please, think of it as a draft that is supposed to demonstrate the main steps and key details required to achieve the desired results.

Getting the message SID

When you try to retrieve a message (or the message's media), you indeed need to provide the SID/SIDs of the message and/or the media, which are basically their identifiers. I assume, this instance of Logic App is receiving the SID(s) as a part of the incoming HttpRequest trigger.

For example, you may require the consumer of the Logic App to provide the message SID in the URL of an HTTP GET request, as shown below.

{
  "kind": "Http",
  "inputs": {
    "schema": {},
    "method": "GET",
    "relativePath": "message/{mms_message_sid}"
  }
}

Then, you will be able to refer to this SID in the further steps of your Logic App.

{
  "inputs": {
    "host": {
      "connection": {
        "name": "@parameters('$connections')['twilio']['connectionId']"
      }
    },
    "method": "get",
    "path": "/Messages/@{encodeURIComponent(triggerOutputs()['relativePathParameters']['mms_message_sid'])}.json",
    "authentication": "@parameters('$authentication')"
  }
}

Retrieving the Message

I briefly looked at the Twilio connector and let me recommend you to not use it because it's going to complicate your Logic App a lot.

Instead, you can use the Get Media API via Http connector. You will need to construct a URL of the following form: https://api.twilio.com/2010-04-01/Accounts/{account_sid}/Messages/{mms_message_sid}/Media.json

You should then receive a response which contains the message's media_list with content_type and the uri you can use to download the actual content of the MMS.

{
  "first_page_uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media.json?PageSize=50&Page=0",
  "media_list":[
  {
    "sid":"ME85ebf7e12cb821f84b319340424dcb02",
    "account_sid":"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "parent_sid":"MM800f449d0399ed014aae2bcc0cc2f2ec",
    "content_type":"image/png",
    "date_created":"Wed, 25 Sep 2013 22:47:18 +0000",
    "date_updated":"Wed, 25 Sep 2013 22:47:19 +0000",
    "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media/ME85ebf7e12cb821f84b319340424dcb02.json"
  },
  {
    "sid":"ME8d8f717e2d6e5383055b3cd150ac5f54",
    "account_sid":"ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "parent_sid":"MM800f449d0399ed014aae2bcc0cc2f2ec",
    "content_type":"image/png",
    "date_created":"Wed, 25 Sep 2013 22:47:18 +0000",
    "date_updated":"Wed, 25 Sep 2013 22:47:19 +0000",
    "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media/ME8d8f717e2d6e5383055b3cd150ac5f54.json"
  }
  ],
  "previous_page_uri":null,
  "uri":"/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Messages/MM800f449d0399ed014aae2bcc0cc2f2ec/Media.json?PageSize=50&Page=0",
  "page_size":50,
  "next_page_uri":null,
  "page":0
}

Parse the response JSON

Since the response body is a JSON document expressed as a string, we won't be able to iterate media_list array, unless we jump through some hoops.

Just add a parse JSON step, which uses the body of the previous step (HTTP) as Content. For the schema provide the following document:

{
  "inputs": {
    "content": "@body('HTTP')",
    "schema": {
      "type": "object",
      "properties": {
        "first_page_uri": {
          "type": "string"
        },
        "media_list": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "sid": {
                "type": "string"
              },
              "account_sid": {
                "type": "string"
              },
              "parent_sid": {
                "type": "string"
              },
              "content_type": {
                "type": "string"
              },
              "date_created": {
                "type": "string"
              },
              "date_updated": {
                "type": "string"
              },
              "uri": {
                "type": "string"
              }
            },
            "required": [
              "sid",
              "account_sid",
              "parent_sid",
              "content_type",
              "date_created",
              "date_updated",
              "uri"
            ]
          }
        },
        "previous_page_uri": {},
        "uri": {
          "type": "string"
        },
        "page_size": {
          "type": "number"
        },
        "next_page_uri": {},
        "page": {
          "type": "number"
        }
      }
    }
  }
}

Iterate through `media_list`

Now the things are relatively easier. You add a For Each step that targets media_list from the previous step.

For each media we need to make an API call that actually retrieves its binary contents. You may want to specify media type related HTTP headers. Play around that and see what works.

Save into Azure Blob Storage

I will not provide any details here because you said, you already know how to do that for the SMS. Just make sure you add the necessary step(s) right after the HTTP2 (inside the For Each step).

Hope, it helps. Logic Apps is NOT "easy peasy integration squeeze".


问:
Can WSO2IS log SSO session data for measuring specific website usage activity?

I'm trying to accomplish logging of session data in Identity Server for users who access websites/resources that are integrated with Identity Server SSO. Is there an easy way to do this? I saw the log4j.properties file in ../repository/conf, however it doesn't provide what I'm looking for. Let me know if anyone needs further clarification.

答:
There is a predefined Session Data Publisher (DASSessionDataPublisherImpl)[1] that is used by Identity Server Analytics to analyse session data. You can use that to retrieve data.

[1]https://docs.wso2.com/display/IS530/Prerequisites+to+Publish+Statistics#PrerequisitestoPublishStatistics-EnablinganalyticsforIdentityServer

Or else try WSO2 Identity Server Analytics.
https://docs.wso2.com/display/IS530/Analytics


问:
How to get number of index's a element is away from a certain element in jQuery?
Suppose I have the following HTML code:

// post the jquery code here...```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="perspectiveSlider__main">
  <div class="perspectiveSlider__slidesContainer">
    <div class="perspectiveSlider__item item-left-faded">
      <img src="img/slide-1.jpg" alt="">
    </div>
    <div class="perspectiveSlider__item item-left">
      <img src="img/slide-2.png" alt="">
    </div>
    <div class="perspectiveSlider__item item-center">
      <img src="img/slide-3.png" alt="">
    </div>
    <div class="perspectiveSlider__item item-right">
      <img src="img/slide-5.jpg" alt="">
    </div>
    <div class="perspectiveSlider__item item-right-faded">
      <img src="img/slide-6.jpg" alt="">
    </div>
  </div>
</div></code>```

As you can see perspectiveSlider__item are 5 siblings of each other and each also has a unique class, now how do I find the number of index's .item-left-faded is away from item-center ?

I know jQuery provides a next() and prev() functions and also index() function but is there something that I can create that will work like a ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement() ?

In the above case .item-left-faded is away from item-center by 2 index's , How do i achieve this functionality ?

答:
```<code>console.log($('.item-right-faded').index()-$('.item-center').index());
</code>```

Read the doc :- https://api.jquery.com/index/

Body:
Suppose I have the following HTML code:

// post the jquery code here...

As you can see perspectiveSlider__item are 5 siblings of each other and each also has a unique class, now how do I find the number of index's .item-left-faded is away from item-center ?

I know jQuery provides a next() and prev() functions and also index() function but is there something that I can create that will work like a ProvideMeTheIndexTheSelectedElementIsAwayFromTheTargetedElement() ?

In the above case .item-left-faded is away from item-center by 2 index's , How do i achieve this functionality ?

Body:
console.log($('.item-right-faded').index()-$('.item-center').index());

Read the doc :- https://api.jquery.com/index/


问:
concatenate a string from R variables
With names(mtcars) we get:

```<code> [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
</code>```

I want to programmaically construct a string to pass to as an argument to another function, this is what I want it to look like:

structField("mpg", "double"), structField("cyl", "double"),structField("disp", "double")...

With what I know, I could come up with this:   a = vector("character", ncol(mtcars))

Create a vector a and give it names from mtcars and use the names in for loop

```<code>names(a) = names(mtcars)

for(i in names(mtcars)) a[i] = unquote(paste0("structField","(", '"',i,'"', ",", '"', "double", '"', ")"))
</code>```

This last for statement creates the following vector:

                               mpg                                cyl
 "structField(\"mpg\",\"double\")"  "structField(\"cyl\",\"double\")"
                              disp                                 hp
"structField(\"disp\",\"double\")"   "structField(\"hp\",\"double\")"
                              drat                                 wt
"structField(\"drat\",\"double\")"   "structField(\"wt\",\"double\")"
                              qsec                                 vs
"structField(\"qsec\",\"double\")"   "structField(\"vs\",\"double\")"
                                am                               gear
  "structField(\"am\",\"double\")" "structField(\"gear\",\"double\")"
                              carb
"structField(\"carb\",\"double\")"

How to I modify the for statement so that \ is not introduced before each ".

My idea is to use paste(a, collapse = ",") to get the final string that looks like:
"structField(\"mpg\",\"double\"),structField(\"cyl\",\"double\"),structField(\"disp\",\"double\"),..., albeit without the \, but is there a more efficient to do this?

Thanks.

答:
Use this:

```<code>sapply(names(mtcars), function(x)paste0("structField(","'",x,"'",",","'" ,typeof(mtcars[[x]]),"'",")"))
</code>```

Output:

```<code>> sapply(names(mtcars), function(x)paste0("structField(","'",x,"'",",","'" ,typeof(mtcars[[x]]),"'",")"))
                           mpg                            cyl
 "structField('mpg','double')"  "structField('cyl','double')"
                          disp                             hp
"structField('disp','double')"   "structField('hp','double')"
                          drat                             wt
"structField('drat','double')"   "structField('wt','double')"
                          qsec                             vs
"structField('qsec','double')"   "structField('vs','double')"
                            am                           gear
  "structField('am','double')" "structField('gear','double')"
                          carb
"structField('carb','double')"
</code>```

Title: concatenate a string from R variables

Body:
With names(mtcars) we get:

 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"

I want to programmaically construct a string to pass to as an argument to another function, this is what I want it to look like:

structField("mpg", "double"), structField("cyl", "double"),structField("disp", "double")...

With what I know, I could come up with this:   a = vector("character", ncol(mtcars))

Create a vector a and give it names from mtcars and use the names in for loop

names(a) = names(mtcars)

for(i in names(mtcars)) a[i] = unquote(paste0("structField","(", '"',i,'"', ",", '"', "double", '"', ")"))

This last for statement creates the following vector:

                               mpg                                cyl
 "structField(\"mpg\",\"double\")"  "structField(\"cyl\",\"double\")"
                              disp                                 hp
"structField(\"disp\",\"double\")"   "structField(\"hp\",\"double\")"
                              drat                                 wt
"structField(\"drat\",\"double\")"   "structField(\"wt\",\"double\")"
                              qsec                                 vs
"structField(\"qsec\",\"double\")"   "structField(\"vs\",\"double\")"
                                am                               gear
  "structField(\"am\",\"double\")" "structField(\"gear\",\"double\")"
                              carb
"structField(\"carb\",\"double\")"

How to I modify the for statement so that \ is not introduced before each ".

My idea is to use paste(a, collapse = ",") to get the final string that looks like:
"structField(\"mpg\",\"double\"),structField(\"cyl\",\"double\"),structField(\"disp\",\"double\"),..., albeit without the \, but is there a more efficient to do this?

Thanks.

Body:
Use this:

sapply(names(mtcars), function(x)paste0("structField(","'",x,"'",",","'" ,typeof(mtcars[[x]]),"'",")"))

Output:

> sapply(names(mtcars), function(x)paste0("structField(","'",x,"'",",","'" ,typeof(mtcars[[x]]),"'",")"))
                           mpg                            cyl
 "structField('mpg','double')"  "structField('cyl','double')"
                          disp                             hp
"structField('disp','double')"   "structField('hp','double')"
                          drat                             wt
"structField('drat','double')"   "structField('wt','double')"
                          qsec                             vs
"structField('qsec','double')"   "structField('vs','double')"
                            am                           gear
  "structField('am','double')" "structField('gear','double')"
                          carb
"structField('carb','double')"


问:
How can I use Angular interpolation to insert a dynamic URL into an elements style?
I am trying to use interpolation to generate background images for my element using variables from the ngFor.

Here's what I currently have, which renders perfectly:

```<code>  <ion-item-group *ngFor="let game of games">
  <ion-card padding style="background: url('./assets/imgs/Body Harvest (USA).png')">
    <h2>{{game.name}}</h2>
  </ion-card>
  </ion-item-group>
</code>```

game object looks like this:

```<code>  {
    "Id": 30,
    "name": "Body Harvest",
    "genres": "Action/Adventure/3D shooter",
    "date": "30-Sep-98",
    "images": "Body Harvest (USA).png",
    "developer": "DMA Design",
    "publisher": "Midway",
    "description": "A video game released for the Nintendo 64.",
    "players": 1
  },
</code>```

I am looking for a way to inject the URL using something like this:

```<code><ion-item-group *ngFor="let game of games">
<ion-card padding style="background: url('./assets/imgs/{{games.images}}')">
   <h2>{{game.name}}</h2>
</ion-card>
</ion-item-group>
</code>```

I think part of the issue is that 'game.images' is returned with double quotes.

答:
You can do this using the Following

```<code><div style="height:200px" [ngStyle]="{background: 'url(https://pbs.twimg.com/profile_images/839721704163155970/'+games+')'}">
    Hello
</div>
</code>```

Component

```<code>games = "LI_TRk1z_400x400.jpg";

<div [ngStyle]="{background: 'url(/img/' + image + ')'"></div>
</code>```

Working Example

Body:
I am trying to use interpolation to generate background images for my element using variables from the ngFor.

Here's what I currently have, which renders perfectly:

  <ion-item-group *ngFor="let game of games">
  <ion-card padding style="background: url('./assets/imgs/Body Harvest (USA).png')">

{{game.name}}

  </ion-card>
  </ion-item-group>

game object looks like this:

  {
    "Id": 30,
    "name": "Body Harvest",
    "genres": "Action/Adventure/3D shooter",
    "date": "30-Sep-98",
    "images": "Body Harvest (USA).png",
    "developer": "DMA Design",
    "publisher": "Midway",
    "description": "A video game released for the Nintendo 64.",
    "players": 1
  },

I am looking for a way to inject the URL using something like this:

<ion-item-group *ngFor="let game of games">
<ion-card padding style="background: url('./assets/imgs/{{games.images}}')">

{{game.name}}

</ion-card>
</ion-item-group>

I think part of the issue is that 'game.images' is returned with double quotes.

Body:
You can do this using the Following

<div style="height:200px" [ngStyle]="{background: 'url(https://pbs.twimg.com/profile_images/839721704163155970/'+games+')'}">
    Hello
</div>

Component

games = "LI_TRk1z_400x400.jpg";

<div [ngStyle]="{background: 'url(/img/' + image + ')'"></div>

Working Example


问:
ASP.NET MVC Adding records to related multiple tables from single view
I'm very new to MVC so i apologize if i haven't explained my requirement properly/haven't used correct terminology.

I have a simple database with item and detail entities. They have a one-to-many relationship so Item has many Details.

I'd like to add records to both these tables from a single view.

So far my understanding is that if i add a create action for 'item' it will get an 'item' object in the HTTPPost request. So does that mean i have to create a separate action/view for details?

Or is 'partial-view' what i should use here? Can someone please give me an example. Really appreciate it. Thanks.

答:
It sounds like you're using strongly typed views, and taking advantage of some MVC magic that auto-populates that type in action. I haven't used MVC3 yet, but in MVC2, you'd probably use UpdateModel to auto-populate your type from the formcollection. Whether MVC is doing some magic for your or not, you will always be sending information from your view to your controller (either POSTing or GETting with a url string) - you'll always be able to access the url string, or forms collection for the raw values.

That being said, you probably want to create a ViewModel - that is a model that fits the needs of your view. In your case it is just a compound model. This ViewModel, is just a plain class. It should be as easy as exposing each of your types as a property of this new class. If you do that, you'll  don't forget to prefix your class/properties right, like:
Model.Item.SomeProperty, Model.Detail.SomeOtherProperty
If you don't, MVC probably won't be able to map values coming back correctly.

That should get you the data you need in your controller - then you just have to insert into the database.


问:
Undo set-branches on git remote
I've currently set up my git remote to restrict which branches are fetched:

```<code>git remote set-branches myOrigin myBranch
</code>```

This adds the proper entries to .git/config:

```<code>[remote "myOrigin"]
    fetch = +refs/heads/myBranch:refs/remotes/myOrigin/myBranch
</code>```

Now I want to undo this, and go back to the default configuration:

```<code>[remote "myOrigin"]
    fetch = +refs/heads/*:refs/remotes/myOrigin/*
</code>```

How can I do this without manually modifying my .git/config? Is there a git command I can run?

答:
Simply use quoted star:</p>

```<code>git remote set-branches myOrigin '*'
</code>```

Title: Undo set-branches on git remote

Body:
I've currently set up my git remote to restrict which branches are fetched:

git remote set-branches myOrigin myBranch

This adds the proper entries to .git/config:

[remote "myOrigin"]
    fetch = +refs/heads/myBranch:refs/remotes/myOrigin/myBranch

Now I want to undo this, and go back to the default configuration:

[remote "myOrigin"]
    fetch = +refs/heads/*:refs/remotes/myOrigin/*

How can I do this without manually modifying my .git/config? Is there a git command I can run?

Body:
Simply use quoted star:

git remote set-branches myOrigin '*'


问:
Not able to unmarshal xml file using JAXB
I have done the following

Created a XML file by myself.

Converted it to XSD using online tool

Copied the generated POJOs in my project

And tried creating Object using JAXB unmarshaller

Step 1: XML I created

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<corpsSymbol>
    <section sectionname="ARMOUR">
        <SIDCvalue sidcname="ArmdRegt" sidc="SFGPUCA----FING"></SIDCvalue>
        <SIDCvalue sidcname="ArmdRegtHQ" sidc="SFGPUCA---AFING"></SIDCvalue>
    </section>
    <section sectionname="ENGINEERS">
        <SIDCvalue sidcname="EngineersCompany" sidc="SFGPUCE----EING"></SIDCvalue>
        <SIDCvalue sidcname="EngineersCompanyHQ" sidc="SFGPUCE---AEING"></SIDCvalue>
    </section>
</corpsSymbol>
</code>```

Step 2: Converted it to XSD

```<code><xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="SIDCvalue">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute type="xs:string" name="sidcname" use="optional"/>
          <xs:attribute type="xs:string" name="sidc" use="optional"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
  <xs:element name="section">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="SIDCvalue" maxOccurs="unbounded" minOccurs="0"/>
      </xs:sequence>
      <xs:attribute type="xs:string" name="sectionname" use="optional"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="corpsSymbol">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="section" maxOccurs="unbounded" minOccurs="0"/>
      </xs:sequence>
      <xs:attribute type="xs:string" name="name"/>
    </xs:complexType>
  </xs:element>
</xs:schema>
</code>```

Step 3: Following POJOs are created (Removed the comment)

CorpsSymbol

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "section"
})
@XmlRootElement(name = "corpsSymbol")
public class CorpsSymbol {

    protected List<Section> section;
    @XmlAttribute(name = "name")
    protected String name;

    public List<Section> getSection() {
        if (section == null) {
            section = new ArrayList<Section>();
        }
        return this.section;
    }
    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

}
</code>```

Section

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "sidCvalue"
})
@XmlRootElement(name = "section")
public class Section {

    @XmlElement(name = "SIDCvalue")
    protected List<SIDCvalue> sidCvalue;
    @XmlAttribute(name = "sectionname")
    protected String sectionname;

    public List<SIDCvalue> getSIDCvalue() {
        if (sidCvalue == null) {
            sidCvalue = new ArrayList<SIDCvalue>();
        }
        return this.sidCvalue;
    }
    public String getSectionname() {
        return sectionname;
    }

    public void setSectionname(String value) {
        this.sectionname = value;
    }

}
</code>```

SIDCvalue

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "value"
})
@XmlRootElement(name = "SIDCvalue")
public class SIDCvalue {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "sidcname")
    protected String sidcname;
    @XmlAttribute(name = "sidc")
    protected String sidc;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getSidcname() {
        return sidcname;
    }

    public void setSidcname(String value) {
        this.sidcname = value;
    }

    public String getSidc() {
        return sidc;
    }

    public void setSidc(String value) {
        this.sidc = value;
    }
}
</code>```

Step 4: Trying to unmarshal

```<code>File file = new File("//main//resources//tacticalSymbols.xml");
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(CorpsSymbol.class);

            Unmarshaller unmarshaller = context.createUnmarshaller();

            CorpsSymbol symbols = (CorpsSymbol) unmarshaller.unmarshal(file);

            System.out.println(symbols.getName());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
</code>```

Here, the unmarshalling is giving an exception
javax.xml.bind.UnmarshalException
 - with linked exception:
[java.net.UnknownHostException: main]
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)

I am not able to understand, where exactly is the problem.

答:
Have you checked to make sure that the problem isn't in the file path? Namely this line:

```<code>File file = new File("//main//resources//tacticalSymbols.xml");
</code>```

Try this instead

```<code>File file = new File("tacticalSymbols.xml");
</code>```

Body:
I have done the following

Created a XML file by myself.

Converted it to XSD using online tool

Copied the generated POJOs in my project

And tried creating Object using JAXB unmarshaller

Step 1: XML I created

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<corpsSymbol>

        <SIDCvalue sidcname="ArmdRegt" sidc="SFGPUCA----FING"></SIDCvalue>
        <SIDCvalue sidcname="ArmdRegtHQ" sidc="SFGPUCA---AFING"></SIDCvalue>

        <SIDCvalue sidcname="EngineersCompany" sidc="SFGPUCE----EING"></SIDCvalue>
        <SIDCvalue sidcname="EngineersCompanyHQ" sidc="SFGPUCE---AEING"></SIDCvalue>

</corpsSymbol>

Step 2: Converted it to XSD

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="SIDCvalue">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:string">
          <xs:attribute type="xs:string" name="sidcname" use="optional"/>
          <xs:attribute type="xs:string" name="sidc" use="optional"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
  <xs:element name="section">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="SIDCvalue" maxOccurs="unbounded" minOccurs="0"/>
      </xs:sequence>
      <xs:attribute type="xs:string" name="sectionname" use="optional"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="corpsSymbol">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="section" maxOccurs="unbounded" minOccurs="0"/>
      </xs:sequence>
      <xs:attribute type="xs:string" name="name"/>
    </xs:complexType>
  </xs:element>
</xs:schema>

Step 3: Following POJOs are created (Removed the comment)

CorpsSymbol

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "section"
})
@XmlRootElement(name = "corpsSymbol")
public class CorpsSymbol {

    protected List
 section;
    @XmlAttribute(name = "name")
    protected String name;

    public List
 getSection() {
        if (section == null) {
            section = new ArrayList
();
        }
        return this.section;
    }
    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

}

Section

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "sidCvalue"
})
@XmlRootElement(name = "section")
public class Section {

    @XmlElement(name = "SIDCvalue")
    protected List<SIDCvalue> sidCvalue;
    @XmlAttribute(name = "sectionname")
    protected String sectionname;

    public List<SIDCvalue> getSIDCvalue() {
        if (sidCvalue == null) {
            sidCvalue = new ArrayList<SIDCvalue>();
        }
        return this.sidCvalue;
    }
    public String getSectionname() {
        return sectionname;
    }

    public void setSectionname(String value) {
        this.sectionname = value;
    }

}

SIDCvalue

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "value"
})
@XmlRootElement(name = "SIDCvalue")
public class SIDCvalue {

    @XmlValue
    protected String value;
    @XmlAttribute(name = "sidcname")
    protected String sidcname;
    @XmlAttribute(name = "sidc")
    protected String sidc;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getSidcname() {
        return sidcname;
    }

    public void setSidcname(String value) {
        this.sidcname = value;
    }

    public String getSidc() {
        return sidc;
    }

    public void setSidc(String value) {
        this.sidc = value;
    }
}

Step 4: Trying to unmarshal

File file = new File("//main//resources//tacticalSymbols.xml");
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(CorpsSymbol.class);

            Unmarshaller unmarshaller = context.createUnmarshaller();

            CorpsSymbol symbols = (CorpsSymbol) unmarshaller.unmarshal(file);

            System.out.println(symbols.getName());
        } catch (JAXBException e) {
            e.printStackTrace();
        }

Here, the unmarshalling is giving an exception
javax.xml.bind.UnmarshalException
 - with linked exception:
[java.net.UnknownHostException: main]
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:246)
    at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)

I am not able to understand, where exactly is the problem.

Body:
Have you checked to make sure that the problem isn't in the file path? Namely this line:

File file = new File("//main//resources//tacticalSymbols.xml");

Try this instead

File file = new File("tacticalSymbols.xml");


问:
MPI INT Arrays in C
I'm creating a program that utilities MPI to determine the dotproduct of large matrices. I am having trouble determining how to send and receive the data through MPI_Send & MPI_Recv.

I have an array int* vector of size nrc that I would like to send and receive

```<code>MPI_Send(vector,nrc,MPI_INT,MASTER,123,MPI_COMM_WORLD);
MPI_Recv(vector, nrc, MPI_INT, i, 123, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
</code>```

I'm running a test of nrc=4, where Master is receiving vectors from 3 slaves. However the results are garbage.

```<code>vector [ 255992420  255992420  255992420  255992420 ]
vector [ -260683762  -260683762  -260683762  -260683762 ]
vector [ 2018561464  2018561464  2018561464  2018561464 ]
</code>```

答:
I found the problem, it wasn't in the send recv functions, they work as intended.

The problem was in the matrix init function that populates the matricies.

Originally I had these init functions inside of the if id==master and if id==slave blocks, which set the id to 0,1,2 etc.

When I moved them out of the master slave blocks the id no longer was 0,1,2, it was garbage. So when initializing the matrices using the id, they became garbage as well.

Title: MPI INT Arrays in C

Body:
I'm creating a program that utilities MPI to determine the dotproduct of large matrices. I am having trouble determining how to send and receive the data through MPI_Send & MPI_Recv.

I have an array int* vector of size nrc that I would like to send and receive

MPI_Send(vector,nrc,MPI_INT,MASTER,123,MPI_COMM_WORLD);
MPI_Recv(vector, nrc, MPI_INT, i, 123, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

I'm running a test of nrc=4, where Master is receiving vectors from 3 slaves. However the results are garbage.

vector [ 255992420  255992420  255992420  255992420 ]
vector [ -260683762  -260683762  -260683762  -260683762 ]
vector [ 2018561464  2018561464  2018561464  2018561464 ]


问:
React multi-select selected value undefined
I'm using this component to make a react multi-select. When I use a normal select if works perfectly. I have the following code.

```<code>handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
    return (
      <Select
        name="form-field-name"
        value={this.state.selectedOption.value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }
</code>```

But when I add, multi={true} it gives undefined in the console. What am I doing wrong? Is there anything else to be added to the attributes?

Plus the value inside the select box doesn't change. Here is an example- https://jsfiddle.net/69z2wepo/94309/

答: My guess is that selectedOption will be an array in case of multi={true}. So of cause selectedOption.label will be undefined. But something like selectedOption[0].label should work.

Body:
I'm using this component to make a react multi-select. When I use a normal select if works perfectly. I have the following code.

handleChange = (selectedOption) => {
    this.setState({ selectedOption });
    console.log(`Selected: ${selectedOption.label}`);
  }
  render() {
    return (
      <Select
        name="form-field-name"
        value={this.state.selectedOption.value}
        onChange={this.handleChange}
        options={[
          { value: 'one', label: 'One' },
          { value: 'two', label: 'Two' },
        ]}
      />
    );
  }

But when I add, multi={true} it gives undefined in the console. What am I doing wrong? Is there anything else to be added to the attributes?

Plus the value inside the select box doesn't change. Here is an example- https://jsfiddle.net/69z2wepo/94309/


问:
Unable to change image for the button in swift 3?
In my code for checkmark I used button to change images for selected and unselected but unable to implement if I click on it's changing to unchecked but again selecting button it's unable to change to check image can anyone help me how to resolve this ?</p>

```<code>var checkedImage = UIImage(named: "check")! as UIImage
var uncheckedImage = UIImage(named: "uncheck")! as UIImage
var isChecked: Bool = true
var checkMarkSelected = 0

checkMarkButton.addTarget(self, action: #selector(checkMarkAction(button:)), for: .touchUpInside)

func checkMarkAction(button : UIButton) {
        if isChecked == true {
            checkMarkButton.setImage(checkedImage, for: .selected)
            isChecked = false
            checkMarkSelected = 1
        }
        else {
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            isChecked = true
            checkMarkSelected = 0
        }
    }
</code>```

答:
```<code>Step 1: Select your CheckUIButton and set Image “Uncheck” (state config must be Default in attribute inspector)
Step 2: In attribute inspector change state config to Selected and set image “Check”
Step 3: Put following code in your UIButton action.

@IBAction func checkclick(_ sender: UIButton) {

        sender.isSelected = !sender.isSelected

    }
</code>```

Body:
In my code for checkmark I used button to change images for selected and unselected but unable to implement if I click on it's changing to unchecked but again selecting button it's unable to change to check image can anyone help me how to resolve this ?

var checkedImage = UIImage(named: "check")! as UIImage
var uncheckedImage = UIImage(named: "uncheck")! as UIImage
var isChecked: Bool = true
var checkMarkSelected = 0

checkMarkButton.addTarget(self, action: #selector(checkMarkAction(button:)), for: .touchUpInside)

func checkMarkAction(button : UIButton) {
        if isChecked == true {
            checkMarkButton.setImage(checkedImage, for: .selected)
            isChecked = false
            checkMarkSelected = 1
        }
        else {
            checkMarkButton.setImage(uncheckedImage, for: .normal)
            isChecked = true
            checkMarkSelected = 0
        }
    }


问:
How can I find the sum of two numbers which are in String variables?
In this code fragment, I can't sum a and b:

```<code>String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,a+b);
</code>```

Since a and b are defined as String, this code will concatenate the strings and output 10+20=1020.

How can I get it to instead sum a and b and output 10+20=30?

Body:
In this code fragment, I can't sum a and b:

String a = "10";
String b = "20";
JOptionPane.showMessageDialog(null,a+b);

Since a and b are defined as String, this code will concatenate the strings and output 10+20=1020.

How can I get it to instead sum a and b and output 10+20=30?

Body:
use BigInteger class to perform largely in length string addition operation.

BigInteger big = new BigInteger("77777777777777777777888888888888888888888888888856666666666666666666666666666666");
        BigInteger big1 = new BigInteger("99999999999999995455555555555555556");
        BigInteger big3 =   big.add(big1);


问:
TIC TCP Conn Failed when running Swift project on my phone
I am new to Swift. I built a simple application which works fine on the simulator. I am running the same on my device (iPhone 6s with iOS 11.0.2) and it's failing to connect to server.

getting these errors:

```<code>2017-10-26 18:16:02.489134-0400 myproj[1451:206438] TIC TCP Conn Failed [1:0x1c0176800]: 1:61 Err(61)
2017-10-26 18:16:02.489771-0400 myproj[1451:206438] Task <0C30ADDC-4A0E-4815-A701-2EF0A7CF5F04>.<1> HTTP load failed (error code: -1004 [1:61])
2017-10-26 18:16:02.490293-0400 myproj[1451:206440] Task <0C30ADDC-4A0E-4815-A701-2EF0A7CF5F04>.<1> finished with error - code: -1004
</code>```

Please help me understand this error.

EDIT:

Here is the code making that call to the server:

```<code>func postRequest(postData: NSDictionary, postHeaders: NSDictionary, endPoint: String,
                 onComplete: @escaping ((NSDictionary)->Void), callbackParams: NSDictionary = NSMutableDictionary()) {
    let url:URL = baseUrl.appendingPathComponent(endPoint)
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    var paramString = ""
    for (key, value) in postData{
        paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
    }

    request.allHTTPHeaderFields = postHeaders as? [String : String]
    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in
        guard let _:Data = data, let _:URLResponse = response  , error == nil else {
            return}
        let json: Any?
        do {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch {
            return
        }
        var serverResponse = json as? NSDictionary
        DispatchQueue.main.async{
            for (key, value) in serverResponse!{
                callbackParams.setValue(value, forKey: key as! String)
            }
            onComplete(callbackParams)
        }
    })
    task.resume()
}
</code>```

EDIT:

Thanks!

答:
In my case i'm not changes the Local host IP address.

```<code>Example : @"http://Localhost/Host name/index.pnp/apiname?";
</code>```

initially i'm used above URL, so i'm got the same error...

Later i changed in to Localhost to 190.177.0.22

```<code>Example : @"http://190.177.0.22/Host name/index.pnp/apiname?";
</code>```

Body:
I am new to Swift. I built a simple application which works fine on the simulator. I am running the same on my device (iPhone 6s with iOS 11.0.2) and it's failing to connect to server.

getting these errors:

2017-10-26 18:16:02.489134-0400 myproj[1451:206438] TIC TCP Conn Failed [1:0x1c0176800]: 1:61 Err(61)
2017-10-26 18:16:02.489771-0400 myproj[1451:206438] Task <0C30ADDC-4A0E-4815-A701-2EF0A7CF5F04>.<1> HTTP load failed (error code: -1004 [1:61])
2017-10-26 18:16:02.490293-0400 myproj[1451:206440] Task <0C30ADDC-4A0E-4815-A701-2EF0A7CF5F04>.<1> finished with error - code: -1004

Please help me understand this error.

EDIT:

Here is the code making that call to the server:

func postRequest(postData: NSDictionary, postHeaders: NSDictionary, endPoint: String,
                 onComplete: @escaping ((NSDictionary)->Void), callbackParams: NSDictionary = NSMutableDictionary()) {
    let url:URL = baseUrl.appendingPathComponent(endPoint)
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url)
    request.httpMethod = "POST"
    request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
    var paramString = ""
    for (key, value) in postData{
        paramString = paramString + (key as! String) + "=" + (value as! String) + "&"
    }

    request.allHTTPHeaderFields = postHeaders as? [String : String]
    request.httpBody = paramString.data(using: String.Encoding.utf8)

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (data, response, error) in
        guard let _:Data = data, let _:URLResponse = response  , error == nil else {
            return}
        let json: Any?
        do {
            json = try JSONSerialization.jsonObject(with: data!, options: [])
        }
        catch {
            return
        }
        var serverResponse = json as? NSDictionary
        DispatchQueue.main.async{
            for (key, value) in serverResponse!{
                callbackParams.setValue(value, forKey: key as! String)
            }
            onComplete(callbackParams)
        }
    })
    task.resume()
}

EDIT:

Thanks!

Body:
In my case i'm not changes the Local host IP address.

Example : @"http://Localhost/Host name/index.pnp/apiname?";

initially i'm used above URL, so i'm got the same error...

Later i changed in to Localhost to 190.177.0.22

Example : @"http://190.177.0.22/Host name/index.pnp/apiname?";


问:
Javascript: Group data by dates and fill in the days in between
I have a event data array of objects with just the end and start date for each event.

```<code>let listOfEvents = [{
  "end": Date 2017-12-09T11:12:00.000Z,
  "start": Date 2017-12-14T03:12:00.000Z,
  "title": "Event One"
},{
  "end": Date 2017-11-10T11:12:00.000Z,
  "start": Date 2017-11-12T03:12:00.000Z,
  "title": "Event Two"
}]
</code>```

This is what I want the final output to be

```<code>    let listOfEvents = [{
      "date": Date 2017-12-09T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-12-10T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-11T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-12T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-13T03:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-14T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-11-10T11:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-11T03:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-12T03:12:00.000Z,
      "title": "Event Two"
    }]
</code>```

This is what I have currently,

```<code>let newEvents = [];
listOfEvents.forEach(function (item) {
        newEvents.push({
            date: item.start,
            title: item.title
        })
    });
</code>```

How would I add logic to fill in the day and add a day for each new entry to the end date then continue on the loop? I can include momentjs if needed.

答:
You can extract the function that creates a range based on a given input, and then reduce the events into a new array

Note that with the data given, start and end properties seem to have been inverted, and the given question doesn't say if it should purely compare on date or on datetime. Where @Hassans answer adds an item to the dataset when ready, I specifically ignored this as I believe this is up to specification

const extractDateRange = ( range, transform ) => {
  let results = [];
  // note that start and end date seem to be up side down in the question
  let curDate = new Date(range.end);
  let endDate = new Date(range.start);
  while (curDate <= endDate) {
    results.push( transform( new Date(curDate), range ) );
    curDate.setDate( curDate.getDate() + 1 ); // / add 1 day
  }
  return results;
};

let listOfEvents = [{
  "end": '2017-12-09T11:12:00.000Z',
  "start": '2017-12-14T03:12:00.000Z',
  "title": "Event One"
},{
  "end": '2017-11-10T11:12:00.000Z',
  "start": '2017-11-12T03:12:00.000Z',
  "title": "Event Two"
}];

let allEvents = listOfEvents.reduce( (current, item) => current.concat(
  extractDateRange( item, ( date, props ) => ({
    title: props.title,
    date
  }) ) )
, []);

console.log( allEvents );```

Body:
I have a event data array of objects with just the end and start date for each event.

let listOfEvents = [{
  "end": Date 2017-12-09T11:12:00.000Z,
  "start": Date 2017-12-14T03:12:00.000Z,
  "title": "Event One"
},{
  "end": Date 2017-11-10T11:12:00.000Z,
  "start": Date 2017-11-12T03:12:00.000Z,
  "title": "Event Two"
}]

This is what I want the final output to be

    let listOfEvents = [{
      "date": Date 2017-12-09T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-12-10T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-11T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-12T11:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-13T03:12:00.000Z,
      "title": "Event One"
    }{
      "date": Date 2017-12-14T11:12:00.000Z,
      "title": "Event One"
    },{
      "date": Date 2017-11-10T11:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-11T03:12:00.000Z,
      "title": "Event Two"
    },{
      "date": Date 2017-11-12T03:12:00.000Z,
      "title": "Event Two"
    }]

This is what I have currently,

let newEvents = [];
listOfEvents.forEach(function (item) {
        newEvents.push({
            date: item.start,
            title: item.title
        })
    });

How would I add logic to fill in the day and add a day for each new entry to the end date then continue on the loop? I can include momentjs if needed.