问:
call mono_method(pointer) from c
i have mono code

public static unsafe int* mono_method (int* p)

{

//....

return p;

}

and want to call it from native c

MonoObject *result = mono_runtime_invoke(mono_method, NULL, args, NULL);

I tried out some different pointers, variables in the args flag (should be void**)

but always get SIGSEGV error when i execute the runtime invoke.

My question is:
Is it possible to pass pointers from c to mono via runtime_invoke and how?

best regards.

答:
You may have tested everything except what the documentation says at
http://www.mono-project.com/Embedding_Mono: The params array contains the arguments to the method with the same convention: MonoObject* pointers for object instances and pointers to the value type otherwise.</p>

```<code>void* args[1];
int val = 10;
MonoObject *result;
args [0] = &val;
result = mono_runtime_invoke(mono_method, NULL, args, NULL);
/* result will be a boxed IntPtr since pointer types can't be boxed themselves */
</code>```

Title: call mono_method(pointer) from c

Body:
You may have tested everything except what the documentation says at
http://www.mono-project.com/Embedding_Mono: The params array contains the arguments to the method with the same convention: MonoObject* pointers for object instances and pointers to the value type otherwise.

void* args[1];
int val = 10;
MonoObject *result;
args [0] = &val;
result = mono_runtime_invoke(mono_method, NULL, args, NULL);
/* result will be a boxed IntPtr since pointer types can't be boxed themselves */


来源: stackexchange

问:
var j in forloop undefined but i in previous loop defined
I have the following function below that's returning an error

j is not defined

I'm not sure why this is as i in my first for loop is not returning undefined. If I change the second forloop to for(var j =0.... then it works. Anyone care to explain why this is?

```<code>;(function (window, document, undefined) {
  'use strict';
  var DOMState = document.readyState;
if (DOMState === 'interactive' || DOMState === 'complete') {
      setTimeout(init, 250);
    } else if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', init);
    }
  function init() {
    var links = $('#list_of_recs a');

    for (i=0;i<links.length;i++) {
      var href = links[i].href;
      var campaignCode1 = "?intcam=ON_D_homepage_recently_viewed";
      var newHref = href + campaignCode1;
      links[i].href = newHref;
    }

    var recTotalDevices = $('#list_of_recs .one_image');

    for (j=0;j<recTotalDevices.length;j++) {
      var aLinks = $('#list_of_recs a')[j];
      var link = aLinks.href;
      var newLink = link.replace("upg-","");
      var newLinknew = newLink.replace("additional-line","");
      aLinks.href = newLinknew;
    }

  }
})(window, document);
</code>```

答:
JavaScript strict mode prevents using variables that have not been declared. You have not declared j so that is why you are getting an error.

As to why you are not getting an error for i, this is most likely because some other code in your page has declared a global i variable.

You should be declaring both.

ContentLicense: CC BY-SA 3.0

Body:
I have the following function below that's returning an error

j is not defined

I'm not sure why this is as i in my first for loop is not returning undefined. If I change the second forloop to for(var j =0.... then it works. Anyone care to explain why this is?

;(function (window, document, undefined) {
  'use strict';
  var DOMState = document.readyState;
if (DOMState === 'interactive' || DOMState === 'complete') {
      setTimeout(init, 250);
    } else if (document.addEventListener) {
      document.addEventListener('DOMContentLoaded', init);
    }
  function init() {
    var links = $('#list_of_recs a');

    for (i=0;i<links.length;i++) {
      var href = links[i].href;
      var campaignCode1 = "?intcam=ON_D_homepage_recently_viewed";
      var newHref = href + campaignCode1;
      links[i].href = newHref;
    }

    var recTotalDevices = $('#list_of_recs .one_image');

    for (j=0;j<recTotalDevices.length;j++) {
      var aLinks = $('#list_of_recs a')[j];
      var link = aLinks.href;
      var newLink = link.replace("upg-","");
      var newLinknew = newLink.replace("additional-line","");
      aLinks.href = newLinknew;
    }

  }
})(window, document);


问:
Allow Indian and US phone numbers in Laravel 5.4
I want to allow only some specific types of phone number format.
Ex:

xxx-xxx-xxxx

+91-xxxxxxxxxx.

I don't know what will be the regular expression for this.
I refered some sites and got this

```<code>/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/
</code>```

which works for 1st one but not worked for +91 format.

Basically, I want to allow India and US numbers only.

2nd Question:

I want a regular expression which will allow +, -, (, ), and the numbers i.e. 0-9 .

答:
are u looking for something like ^(\d{3}-\d{3}-\d{4}|\+91 \d{10})

example

both numbers are placed in group one this way if u work with groups

edit:

are u looking for one like this? this allows the sets of numbers to be seperated with everything exept a letter or a number
(\d{3}[^\d\w]\d{3}[^\d\w]\d{4}|\+91[^\d\w]\d{10})

example

Body:
I want to allow only some specific types of phone number format.
Ex:

xxx-xxx-xxxx

+91-xxxxxxxxxx.

I don't know what will be the regular expression for this.
I refered some sites and got this

/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/

which works for 1st one but not worked for +91 format.

Basically, I want to allow India and US numbers only.

2nd Question:

I want a regular expression which will allow +, -, (, ), and the numbers i.e. 0-9 .


问:
Check checkboxlist Items as value in querystring in asp.net
I want to mark checkboxlist item selected if it's value found in QueryString. e.g.

www.abcd.com/pproducts.aspx?price=1001-2000|2001-5000|5001-10000.

In this url I am filtering products with 3 different price range. Now I have checkboxlist which contains this prices like below

1001-2000

2001-5000

5001-10000

above-10000

so now I want to it should get selected 1001-2000, 2001-5000, 5001-10000

From below code I am redirecting page & making url

```<code>private void priceRange_SelectedIndexChanged(object sender, EventArgs e)
{
    string selectedPriceRange = priceRange.SelectedValue.ToString;
    foreach (ListItem chk in priceRange.Items) {
        if (selectedPriceRange.Contains(chk.Value)) {
            chk.Selected = true;
        }
    }

    Response.Redirect((Request.Url.AbsoluteUri) + "?price=" + selectedPriceRange);
}
</code>```

答:
```<code>string price = Request.QueryString["price"];
string[] priceList = price.Split('|');
foreach (string p in priceList)
{
    if (chkList.Items.FindByText(p) != null)
    {
          chkList.Items.FindByText(p).Selected = true;
    }
}
</code>```

Above code will select each checkbox as per the value passed in query sting.

Body:
I want to mark checkboxlist item selected if it's value found in QueryString. e.g.

www.abcd.com/pproducts.aspx?price=1001-2000|2001-5000|5001-10000.

In this url I am filtering products with 3 different price range. Now I have checkboxlist which contains this prices like below

1001-2000

2001-5000

5001-10000

above-10000

so now I want to it should get selected 1001-2000, 2001-5000, 5001-10000

From below code I am redirecting page & making url

private void priceRange_SelectedIndexChanged(object sender, EventArgs e)
{
    string selectedPriceRange = priceRange.SelectedValue.ToString;
    foreach (ListItem chk in priceRange.Items) {
        if (selectedPriceRange.Contains(chk.Value)) {
            chk.Selected = true;
        }
    }

    Response.Redirect((Request.Url.AbsoluteUri) + "?price=" + selectedPriceRange);
}

Body:
string price = Request.QueryString["price"];
string[] priceList = price.Split('|');
foreach (string p in priceList)
{
    if (chkList.Items.FindByText(p) != null)
    {
          chkList.Items.FindByText(p).Selected = true;
    }
}

Above code will select each checkbox as per the value passed in query sting.


问:
Django Delete an object via Post request
I want to delete an object via clicking on a glyphicon wrapped in a form.
To do this, my function looks like this:

```<code>def deleteHabit(request, id):
    print('deleteHabit')
    habit_to_delete = get_object_or_404(Habit, id=id)
    print(habit_to_delete)

    if (request.method == 'POST'):
         form = HabitForm(instance=habit_to_delete)
         if form.is_valid(): # checks CSRF
              print('delete') # normally habit_to_delete.delete()
         return redirect('renderOverview') # wherever to go after deleting
    else:
         # Not Working
         return render(request, 'overview/habit_delete_confirm', args)
</code>```

My understanding of Post and Get is the 'Post' condition does roughly the deleting part and the 'Get' condition renders a confirmation page for example to confirm the deletion. However, the object will be deleted, but by clicking the form it redirects to success_url and does not show a confirmation page. What's wrong on the code snippet above?

答:
Sry for answering this question so late, but I'm very busy atm. Another reason why I did'nt answer was that your answer is not the answer I was looking for. You can handle a CRUD operation either by a function (see above) or with a generic view (as you suggested).
My function above was not correctly in more than one cases, but in question case, I did not get confirmation page, which means, I didn't get the 'GET REQUEST'. So, my mistake was not the function, but rather the correct url mapping.

Independently I'm using a DeleteView for now.

in views.py:

```<code>class HabitDeleteView(DeleteView):
    model = Habit
    success_url = reverse_lazy('display_habits')
</code>```

in urls.py:

```<code>  url(r'^habit/(?P<pk>\d+)/delete$', habits_views.HabitDeleteView.as_view(), name='delete_habit'),
</code>```

in template I'm using this:

```<code>    <a href="{% url 'delete_habit' habit.pk %}">
    <span class="glyphicon glyphicon-trash custom-trash-habit-detail"></span>
    </a>
</code>```

Body:
I want to delete an object via clicking on a glyphicon wrapped in a form.
To do this, my function looks like this:

def deleteHabit(request, id):
    print('deleteHabit')
    habit_to_delete = get_object_or_404(Habit, id=id)
    print(habit_to_delete)

    if (request.method == 'POST'):
         form = HabitForm(instance=habit_to_delete)
         if form.is_valid(): # checks CSRF
              print('delete') # normally habit_to_delete.delete()
         return redirect('renderOverview') # wherever to go after deleting
    else:
         # Not Working
         return render(request, 'overview/habit_delete_confirm', args)

My understanding of Post and Get is the 'Post' condition does roughly the deleting part and the 'Get' condition renders a confirmation page for example to confirm the deletion. However, the object will be deleted, but by clicking the form it redirects to success_url and does not show a confirmation page. What's wrong on the code snippet above?

Body:
Sry for answering this question so late, but I'm very busy atm. Another reason why I did'nt answer was that your answer is not the answer I was looking for. You can handle a CRUD operation either by a function (see above) or with a generic view (as you suggested).
My function above was not correctly in more than one cases, but in question case, I did not get confirmation page, which means, I didn't get the 'GET REQUEST'. So, my mistake was not the function, but rather the correct url mapping.

Independently I'm using a DeleteView for now.

in views.py:

class HabitDeleteView(DeleteView):
    model = Habit
    success_url = reverse_lazy('display_habits')

in urls.py:

  url(r'^habit/(?P<pk>\d+)/delete$', habits_views.HabitDeleteView.as_view(), name='delete_habit'),

in template I'm using this:

    <a href="{% url 'delete_habit' habit.pk %}">
    <span class="glyphicon glyphicon-trash custom-trash-habit-detail"></span>
    </a>


问:
How would I go about making this error message appear when form field is not right?
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

```<code>if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}
</code>```

In the form, I have a span class like so:

```<code><span class="error">'.$error.'</span>
</code>```

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!

答:
Yep, I think You have two methods to do that, as already explained above...

When the form is submitted to the same page (itself) using *$_SERVER['PHP_SELF']*, you can check weather each posted field is empty using empty() function. Then if they are not filled then set the variable $error and then use echo $error; at the span of error... If no any error you can assign the default message at the $error instead of the error... It should do what you need...

You can use AJAX and send a request to the page and set the error message. Then the page is not fully refreshed as it was before, but only the element you wanted to refresh. This is fast, but in most of the cases, first method is preferred, unless AJAX is a need..

What exactly you want to do? If you specify what's your actual need, it is possible to provide some sample code... (First method is already discussed)

Thank You.
ADynaMic

ContentLicense: CC BY-SA 2.5

Body:
I have an if statement and I already have it working so if certain fields are not filled in it will not send. I then have an else, and I put it like so:

if(isset($_POST['submit'])) {
    if (!empty($name) && (!empty($email) || !empty($phone))) {
    mail( "EMAIL@hotmail.com", "Monthly Specials Email",
    "Name: $name
     Email: $email
     Phone Number: $phone
     Comment: $comment", "From: $email" );

    $error = "";

   } else {
    $error = "Please fill in the required fields.";
   }
}

In the form, I have a span class like so:

'.$error.'

I have it so the action of the form is set to blank so it will stay on the same page when sent, and all of the functions are in the same page as the form. How would I go about updating the error span?

Thanks so much for any help or tips!


问:
How to get a List of Base class objects, from x number of child classes lists?
For the sake of explanation I made an example

```<code>public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base {

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}",
                              Name, Surname, StudentID);
    }
}

public class Teacher : Base {

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}",
                              Name, Surname, TeachingSubject);
    }
}
</code>```

In my case, there are 4 child classes, but 2 is enough to keep it simple and still hit the point. Keep in mind that Student and Teacher classes contain their own property, so each object from the Base list should be different, according to the derived class properties.

Somewhere in the project I need to have a Method that returns List of Base objects

```<code>List<Base> GetAllLists() {

    return allLists; //Lets name the return list of Base objects like this
}
</code>```

So I need to put lists of objects from derived classes to a Base class List and use it somewhere.

I already did something like this

```<code>List<Base> GetAllLists() {

    var allLists = new List<Base>();

    var studentList = new StudentService().GetList();  //Service class that populates the list of students from a csv file
    foreach (var item in studentList) {
        allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
    }
    var teacherList = new TeacherService().GetList();  //Service class that populates the list of teachers from a csv file
    foreach (var item in teacherList) {
        allLists.Add(new Teacher(item.Name, item.Surname, item.TeachingSubject));
    }

    return allLists;
}
</code>```

I got a comment:

there's no need to iterate all of the lists and instantiate a new
  object of each entity, since all of them inherit from the same base
  class

So how to achieve this in some other way?

答:
I guess the AddRange method will allow you to add all objects in one blow:

```<code>var allLists = new List<Base>();

var studentList = new StudentService().GetList();

allLists.AddRange(studentList);

var teacherList = new TeacherService().GetList();

allLists.AddRange(teacherList);
</code>```

Since Student and Teacher inherit from base they just can fit into the base List.

The big difference here is that you add only references! that means if you change a value in the original studentList it will also be changed in the allLists list!

Whereas in your posted code this will not happen, because you create a new instance for each entry in your studentList. This way you create independence between the two lists.

But if studentList is only a local variable that is not manipulated elsewhere it is legitimate to use AddRange and add simply the references to the allLists list

Here is a small test program. Copy paste it into a console application and see the difference for yourself. Just change the copyreference value and compare the outcome:

```<code>void Main()
{
    bool copyreference = true;

var allLists = new List<Base>();

    var studentList  = new List<Student>();
    studentList.Add(new Student("Alf", "Bedrock", 123));
    studentList.Add(new Student("Alfine", "Bedrock", 456));

    var teacherList  = new List<Teacher>();
    teacherList.Add(new Teacher("Brad", "Gulp", "MATH"));
    teacherList.Add(new Teacher("Evelyn", "Gulp", "BIO"));

    if (copyreference)
    {
        allLists.AddRange(studentList);
        allLists.AddRange(teacherList);
    }
    else
    {
        foreach (var item in studentList)
        {
            allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
        }
    }

    Console.WriteLine(String.Join(Environment.NewLine, allLists));
    // TEST changing a value in the original list
    studentList[0].Name = "Harry";
    // if you copied references you will see the change in the final list
    Console.WriteLine(Environment.NewLine + String.Join(Environment.NewLine, allLists));
}
</code>```

Body:
For the sake of explanation I made an example

public class Base {
    public string Name { get; set; }
    public string Surname { get; set; }

    public Base(string name, string surname) {
        Name = name;
        Surname = surname;
    }
}

public class Student : Base {

    public int StudentID { get; set; }

    public Student(string name, string surname, int studentID)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        StudentID = studentID;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, ID is {2}",
                              Name, Surname, StudentID);
    }
}

public class Teacher : Base {

    public string TeachingSubject { get; set; }

    public Teacher(string name, string surname, string teachingSubject)
                          : base(name, surname) {
        Name = name;
        Surname = surname;
        TeachingSubject = teachingSubject;
    }

    public override string ToString() {
        return string.Format("Name is {0}, surname is {1}, TeachingSubject is {2}",
                              Name, Surname, TeachingSubject);
    }
}

In my case, there are 4 child classes, but 2 is enough to keep it simple and still hit the point. Keep in mind that Student and Teacher classes contain their own property, so each object from the Base list should be different, according to the derived class properties.

Somewhere in the project I need to have a Method that returns List of Base objects

List<Base> GetAllLists() {

    return allLists; //Lets name the return list of Base objects like this
}

So I need to put lists of objects from derived classes to a Base class List and use it somewhere.

I already did something like this

List<Base> GetAllLists() {

    var allLists = new List<Base>();

    var studentList = new StudentService().GetList();  //Service class that populates the list of students from a csv file
    foreach (var item in studentList) {
        allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
    }
    var teacherList = new TeacherService().GetList();  //Service class that populates the list of teachers from a csv file
    foreach (var item in teacherList) {
        allLists.Add(new Teacher(item.Name, item.Surname, item.TeachingSubject));
    }

    return allLists;
}

I got a comment:

there's no need to iterate all of the lists and instantiate a new
  object of each entity, since all of them inherit from the same base
  class

So how to achieve this in some other way?

Body:
I guess the AddRange method will allow you to add all objects in one blow:

var allLists = new List<Base>();

var studentList = new StudentService().GetList();

allLists.AddRange(studentList);

var teacherList = new TeacherService().GetList();

allLists.AddRange(teacherList);

Since Student and Teacher inherit from base they just can fit into the base List.

The big difference here is that you add only references! that means if you change a value in the original studentList it will also be changed in the allLists list!

Whereas in your posted code this will not happen, because you create a new instance for each entry in your studentList. This way you create independence between the two lists.

But if studentList is only a local variable that is not manipulated elsewhere it is legitimate to use AddRange and add simply the references to the allLists list

Here is a small test program. Copy paste it into a console application and see the difference for yourself. Just change the copyreference value and compare the outcome:

void Main()
{
    bool copyreference = true;

var allLists = new List<Base>();

    var studentList  = new List<Student>();
    studentList.Add(new Student("Alf", "Bedrock", 123));
    studentList.Add(new Student("Alfine", "Bedrock", 456));

    var teacherList  = new List<Teacher>();
    teacherList.Add(new Teacher("Brad", "Gulp", "MATH"));
    teacherList.Add(new Teacher("Evelyn", "Gulp", "BIO"));

    if (copyreference)
    {
        allLists.AddRange(studentList);
        allLists.AddRange(teacherList);
    }
    else
    {
        foreach (var item in studentList)
        {
            allLists.Add(new Student(item.Name, item.Surname, item.StudentID));
        }
    }

    Console.WriteLine(String.Join(Environment.NewLine, allLists));
    // TEST changing a value in the original list
    studentList[0].Name = "Harry";
    // if you copied references you will see the change in the final list
    Console.WriteLine(Environment.NewLine + String.Join(Environment.NewLine, allLists));
}


问:
Query nested complex json structure with Apache Drill
I have a json file with many json object like this one

```<code>{
"created_time": "2015-04-15T15:12:43+0000",
"updated_time": "2015-04-15T15:12:43+0000",
"comments": {
    "data": [
        {
            "created_time": "2015-04-15T18:09:06+0000",
            "can_remove": false,
            "like_count": 4,
            "user_likes": false,
            "from": {
                "name": "Ana Paula Mandlaze Gomez",
                "id": "1413157615397359"
            },
            "id": "981539778532568_981613971858482",
            "message": "\"Many people, especially ignorant people, want to punish you for speaking the truth, for being correct, for being you. Never apologize for being correct, or for being years ahead of your time. If you' re right and you know it, speak your mind. Even if you are a minority  of one, the truth is still the truth.\"Gandhi"
        },
        {
            "created_time": "2015-04-15T16:33:27+0000",
            "can_remove": false,
            "like_count": 2,
            "user_likes": false,
            "from": {
                "name": "Ana Paula Mandlaze Gomez",
                "id": "1413157615397359"
            },
            "id": "981539778532568_981574091862470",
            "message": "I love I love GHANDI"
        },
        {
            "created_time": "2015-04-22T19:47:59+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Fardous Alhorafi",
                "id": "1800049323548924"
            },
            "id": "981539778532568_985418828144663",
            "message": "كان عبقري"
        },
        {
            "created_time": "2015-04-15T21:06:35+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Jamal Abdulrahman",
                "id": "1366198393416315"
            },
            "id": "981539778532568_981681661851713",
            "message": "This great leader"
        },
        {
            "created_time": "2015-04-15T15:35:42+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Sergio Pellicciotta",
                "id": "1307515282677785"
            },
            "id": "981539778532568_981548471865032",
            "message": "ci vuole la pazienza"
        },
        {
            "created_time": "2015-04-15T16:31:44+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Merve Tacirli",
                "id": "773109599535260"
            },
            "id": "981539778532568_981573545195858",
            "message": "Key word: patient"
        },
        {
            "created_time": "2015-08-15T21:36:38+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Tu Abuela",
                "id": "10212662776625548"
            },
            "id": "981539778532568_1046913331995212",
            "message": ":)"
        },
        {
            "created_time": "2015-04-15T19:38:53+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Vikash Tiwari",
                "id": "977320485738496"
            },
            "id": "981539778532568_981645241855355",
            "message": "sadar naman bapu"
        },
        {
            "created_time": "2015-04-15T15:29:21+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Nikunj Patel",
                "id": "1370944359688528"
            },
            "id": "981539778532568_981545948531951",
            "message": "Aaapko khiladi ka salaaM"
        },
        {
            "created_time": "2015-04-16T06:01:33+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Satya Prakash",
                "id": "791386747691183"
            },
            "id": "981539778532568_981861258500420",
            "message": "......patience es depth of laef.."
        },
        {
            "created_time": "2015-04-27T20:46:37+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Javier Arce",
                "id": "1353955594657881"
            },
            "id": "981539778532568_988593714493841",
            "message": "COMIC - THE DAY GANDHI DIE - COMIC https://www.youtube.com/watch?v=_g7KpUx0qSQ"
        },
        {
            "created_time": "2015-04-15T15:28:59+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Nikunj Patel",
                "id": "1370944359688528"
            },
            "id": "981539778532568_981545825198630",
            "message": "Bhai"
        }
    ],
    "paging": {"cursors": {
        "before": "MTYZD",
        "after": "MQZDZD"
    }}
},
"status_type": "added_photos",
"link": "https://www.facebook.com/FatherofNation/photos/a.279218472098039.73934.173835512636336/981539778532568/?type=3",
"icon": "https://www.facebook.com/images/icons/photo.gif",
"is_hidden": false,
"privacy": {
    "allow": "",
    "deny": "",
    "description": "",
    "value": "",
    "friends": ""
},
"message": "You cannot achieve durable reform by becoming impatient. - Mahatma Gandhi",
"type": "photo",
"object_id": "981539778532568",
"picture": "https://fb-s-c-a.akamaihd.net/h-ak-fbx/v/t1.0-0/s130x130/10300287_981539778532568_5512778811597106826_n.jpg?oh=900c8f181224cef2b2b93688a0ef9d88&oe=599C0E7D&__gda__=1508137453_7f9508a338248a38665e21299f8410bb",
"shares": {"count": 140},
"is_expired": false,
"name": "Timeline Photos",
"from": {
    "name": "Mahatma Gandhi",
    "id": "173835512636336",
    "category": "Public Figure"
},
"id": "173835512636336_981539778532568",
"likes": {
    "data": [
        {
            "name": "Rai Santi",
            "id": "699214820279365"
        },
        {
            "name": "Rabari Bhavesh Bhandu",
            "id": "197158197474003"
        },
        {
            "name": "Cristiano Hussaini",
            "id": "469179660091433"
        },
        {
            "name": "D Pák Ský",
            "id": "342182466199173"
        },
        {
            "name": "Joseph Muendo",
            "id": "893394437480382"
        },
        {
            "name": "Kati Vali",
            "id": "10209489431495182"
        },
        {
            "name": "Neelam Gupta",
            "id": "278625325934685"
        },
        {
            "name": "Rahul Patel",
            "id": "298644327257948"
        },
        {
            "name": "Niti Jani",
            "id": "1520081698036960"
        },
        {
            "name": "Sara Maria Crespo Echeandía",
            "id": "10155452589526055"
        },
        {
            "name": "Sonia Quintana Castillo",
            "id": "485471615125223"
        },
        {
            "name": "Tello Maweng",
            "id": "720777431451520"
        },
        {
            "name": "David Figueroa",
            "id": "1886084661665963"
        },
        {
            "name": "Aphle Grace Celestre Devera",
            "id": "1517425511643699"
        },
        {
            "name": "Angel Legaspi Alquizar",
            "id": "327218104364636"
        },
        {
            "name": "Sanjeev Mishra",
            "id": "1207468336065542"
        },
        {
            "name": "Patricia Fastinger",
            "id": "1956586287688483"
        },
        {
            "name": "Bojana Simonovska",
            "id": "10155588604414614"
        },
        {
            "name": "Nath Schmidt",
            "id": "1337540319645871"
        },
        {
            "name": "Santoshi Nallanchakravartula",
            "id": "1364678026914798"
        },
        {
            "name": "Pabitra Kumar",
            "id": "631689807038744"
        },
        {
            "name": "Thaís Araujo",
            "id": "1350769495004631"
        },
        {
            "name": "Dilip Singh Rathore",
            "id": "1711441295817067"
        },
        {
            "name": "Kamlesh Saini",
            "id": "1987451464817042"
        },
        {
            "name": "SaDhu Ka",
            "id": "1490063764348943"
        }
    ],
    "paging": {
        "next": "https://graph.facebook.com/v2.3/173835512636336_981539778532568/likes?access_token=166536670200421%7Cb8948bb3c57f35a94afee5d5869854b7&limit=25&after=MTQ5MDA2Mzc2NDM0ODk0MwZDZD",
        "cursors": {
            "before": "Njk5MjE0ODIwMjc5MzY1",
            "after": "MTQ5MDA2Mzc2NDM0ODk0MwZDZD"
        }
    }
}}
</code>```

I want to make an SQL query using apache drill to access nested object eg comments.data[0].message. I tried every thing and followed the official guide for querying complex JSON data but did't work.

select comments.data[0].message FROM dfs./home/dhaker/Desktop/GhandiOffcialPage/Facebookposts.json

this is the error from jdbc:

VALIDATION ERROR: From line 1, column 8 to line 1, column 15: Table 'comments' not found

SQL Query null

[Error Id: c50f3051-79f8-4f35-b9bd-fd51c06ecb61 on dhaker-X550V:31010]
[]

答:
I had to put an alias for the path and then call like this :

select posts.comments.data[0].message FROM dfs./home/dhaker/Desktop/GhandiOffcialPage/Facebookposts.json posts;

it works fine like that.

Body:
I have a json file with many json object like this one

{
"created_time": "2015-04-15T15:12:43+0000",
"updated_time": "2015-04-15T15:12:43+0000",
"comments": {
    "data": [
        {
            "created_time": "2015-04-15T18:09:06+0000",
            "can_remove": false,
            "like_count": 4,
            "user_likes": false,
            "from": {
                "name": "Ana Paula Mandlaze Gomez",
                "id": "1413157615397359"
            },
            "id": "981539778532568_981613971858482",
            "message": "\"Many people, especially ignorant people, want to punish you for speaking the truth, for being correct, for being you. Never apologize for being correct, or for being years ahead of your time. If you' re right and you know it, speak your mind. Even if you are a minority  of one, the truth is still the truth.\"Gandhi"
        },
        {
            "created_time": "2015-04-15T16:33:27+0000",
            "can_remove": false,
            "like_count": 2,
            "user_likes": false,
            "from": {
                "name": "Ana Paula Mandlaze Gomez",
                "id": "1413157615397359"
            },
            "id": "981539778532568_981574091862470",
            "message": "I love I love GHANDI"
        },
        {
            "created_time": "2015-04-22T19:47:59+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Fardous Alhorafi",
                "id": "1800049323548924"
            },
            "id": "981539778532568_985418828144663",
            "message": "كان عبقري"
        },
        {
            "created_time": "2015-04-15T21:06:35+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Jamal Abdulrahman",
                "id": "1366198393416315"
            },
            "id": "981539778532568_981681661851713",
            "message": "This great leader"
        },
        {
            "created_time": "2015-04-15T15:35:42+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Sergio Pellicciotta",
                "id": "1307515282677785"
            },
            "id": "981539778532568_981548471865032",
            "message": "ci vuole la pazienza"
        },
        {
            "created_time": "2015-04-15T16:31:44+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Merve Tacirli",
                "id": "773109599535260"
            },
            "id": "981539778532568_981573545195858",
            "message": "Key word: patient"
        },
        {
            "created_time": "2015-08-15T21:36:38+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Tu Abuela",
                "id": "10212662776625548"
            },
            "id": "981539778532568_1046913331995212",
            "message": ":)"
        },
        {
            "created_time": "2015-04-15T19:38:53+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Vikash Tiwari",
                "id": "977320485738496"
            },
            "id": "981539778532568_981645241855355",
            "message": "sadar naman bapu"
        },
        {
            "created_time": "2015-04-15T15:29:21+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Nikunj Patel",
                "id": "1370944359688528"
            },
            "id": "981539778532568_981545948531951",
            "message": "Aaapko khiladi ka salaaM"
        },
        {
            "created_time": "2015-04-16T06:01:33+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Satya Prakash",
                "id": "791386747691183"
            },
            "id": "981539778532568_981861258500420",
            "message": "......patience es depth of laef.."
        },
        {
            "created_time": "2015-04-27T20:46:37+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Javier Arce",
                "id": "1353955594657881"
            },
            "id": "981539778532568_988593714493841",
            "message": "COMIC - THE DAY GANDHI DIE - COMIC https://www.youtube.com/watch?v=_g7KpUx0qSQ"
        },
        {
            "created_time": "2015-04-15T15:28:59+0000",
            "can_remove": false,
            "like_count": 0,
            "user_likes": false,
            "from": {
                "name": "Nikunj Patel",
                "id": "1370944359688528"
            },
            "id": "981539778532568_981545825198630",
            "message": "Bhai"
        }
    ],
    "paging": {"cursors": {
        "before": "MTYZD",
        "after": "MQZDZD"
    }}
},
"status_type": "added_photos",
"link": "https://www.facebook.com/FatherofNation/photos/a.279218472098039.73934.173835512636336/981539778532568/?type=3",
"icon": "https://www.facebook.com/images/icons/photo.gif",
"is_hidden": false,
"privacy": {
    "allow": "",
    "deny": "",
    "description": "",
    "value": "",
    "friends": ""
},
"message": "You cannot achieve durable reform by becoming impatient. - Mahatma Gandhi",
"type": "photo",
"object_id": "981539778532568",
"picture": "https://fb-s-c-a.akamaihd.net/h-ak-fbx/v/t1.0-0/s130x130/10300287_981539778532568_5512778811597106826_n.jpg?oh=900c8f181224cef2b2b93688a0ef9d88&oe=599C0E7D&__gda__=1508137453_7f9508a338248a38665e21299f8410bb",
"shares": {"count": 140},
"is_expired": false,
"name": "Timeline Photos",
"from": {
    "name": "Mahatma Gandhi",
    "id": "173835512636336",
    "category": "Public Figure"
},
"id": "173835512636336_981539778532568",
"likes": {
    "data": [
        {
            "name": "Rai Santi",
            "id": "699214820279365"
        },
        {
            "name": "Rabari Bhavesh Bhandu",
            "id": "197158197474003"
        },
        {
            "name": "Cristiano Hussaini",
            "id": "469179660091433"
        },
        {
            "name": "D Pák Ský",
            "id": "342182466199173"
        },
        {
            "name": "Joseph Muendo",
            "id": "893394437480382"
        },
        {
            "name": "Kati Vali",
            "id": "10209489431495182"
        },
        {
            "name": "Neelam Gupta",
            "id": "278625325934685"
        },
        {
            "name": "Rahul Patel",
            "id": "298644327257948"
        },
        {
            "name": "Niti Jani",
            "id": "1520081698036960"
        },
        {
            "name": "Sara Maria Crespo Echeandía",
            "id": "10155452589526055"
        },
        {
            "name": "Sonia Quintana Castillo",
            "id": "485471615125223"
        },
        {
            "name": "Tello Maweng",
            "id": "720777431451520"
        },
        {
            "name": "David Figueroa",
            "id": "1886084661665963"
        },
        {
            "name": "Aphle Grace Celestre Devera",
            "id": "1517425511643699"
        },
        {
            "name": "Angel Legaspi Alquizar",
            "id": "327218104364636"
        },
        {
            "name": "Sanjeev Mishra",
            "id": "1207468336065542"
        },
        {
            "name": "Patricia Fastinger",
            "id": "1956586287688483"
        },
        {
            "name": "Bojana Simonovska",
            "id": "10155588604414614"
        },
        {
            "name": "Nath Schmidt",
            "id": "1337540319645871"
        },
        {
            "name": "Santoshi Nallanchakravartula",
            "id": "1364678026914798"
        },
        {
            "name": "Pabitra Kumar",
            "id": "631689807038744"
        },
        {
            "name": "Thaís Araujo",
            "id": "1350769495004631"
        },
        {
            "name": "Dilip Singh Rathore",
            "id": "1711441295817067"
        },
        {
            "name": "Kamlesh Saini",
            "id": "1987451464817042"
        },
        {
            "name": "SaDhu Ka",
            "id": "1490063764348943"
        }
    ],
    "paging": {
        "next": "https://graph.facebook.com/v2.3/173835512636336_981539778532568/likes?access_token=166536670200421%7Cb8948bb3c57f35a94afee5d5869854b7&limit=25&after=MTQ5MDA2Mzc2NDM0ODk0MwZDZD",
        "cursors": {
            "before": "Njk5MjE0ODIwMjc5MzY1",
            "after": "MTQ5MDA2Mzc2NDM0ODk0MwZDZD"
        }
    }
}}

I want to make an SQL query using apache drill to access nested object eg comments.data[0].message. I tried every thing and followed the official guide for querying complex JSON data but did't work.

select comments.data[0].message FROM dfs./home/dhaker/Desktop/GhandiOffcialPage/Facebookposts.json

this is the error from jdbc:

VALIDATION ERROR: From line 1, column 8 to line 1, column 15: Table 'comments' not found

SQL Query null

[Error Id: c50f3051-79f8-4f35-b9bd-fd51c06ecb61 on dhaker-X550V:31010]
[]


问:
Python dictionary, lists ,join and Interpreter
join in python joins the list elements and keys in dictionaries right?.

Whenever I use join to join a list the output is in the same order as the list. I know it not ordered and the output clearly differed when i gave the same in a file and in the interpreter.

My question is how interpreter remembers that and gives the same output everytime for that order. Is it in some sort of cache or??

```<code>>>> x = ['a','b','c']
>>> ','.join(x)
'a,b,c'
>>> x = ['c','b','a']
>>> ','.join(x)
'c,b,a'
</code>```

using a dict

```<code>>>> z = {'a':3,'b':1,'c':4,'d':2}
>>> ','.join(z)
'b,d,a,c'
>>> z = {'a':3,'d':1,'c':4,'b':2}
>>> ','.join(z)
'c,d,a,b'
</code>```

So I concluded that it varies each time but when I give the same dictionary with a specific order after several instructions it still displays the output in some order which is the same everytime in the interpreter!

```<code>>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'spam':4,'egg':2}
>>> ','.join(z)
'spam,bar,foo,egg'
>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
</code>```

I maybe missing something out but how does the interpreter remember it. Clear explanations would help greatly.

NOTE: As seen in the comments mentioned by chris_rands
I quote 'the dict iteration is fixed within an interpreter session because the environmental variable PYTHONHASHSEED is fixed'

is more along the lines of the answer I am looking for. Explanations would be great!.

答: dictionaries dont have an order in python. You might randomly get the same order, but it's not guaranteed. If you need a dictionary with a fixed order, have a look at OrderedDict: https://docs.python.org/2/library/collections.html#collections.OrderedDict

Body:
join in python joins the list elements and keys in dictionaries right?.

Whenever I use join to join a list the output is in the same order as the list. I know it not ordered and the output clearly differed when i gave the same in a file and in the interpreter.

My question is how interpreter remembers that and gives the same output everytime for that order. Is it in some sort of cache or??

>>> x = ['a','b','c']
>>> ','.join(x)
'a,b,c'
>>> x = ['c','b','a']
>>> ','.join(x)
'c,b,a'

using a dict

>>> z = {'a':3,'b':1,'c':4,'d':2}
>>> ','.join(z)
'b,d,a,c'
>>> z = {'a':3,'d':1,'c':4,'b':2}
>>> ','.join(z)
'c,d,a,b'

So I concluded that it varies each time but when I give the same dictionary with a specific order after several instructions it still displays the output in some order which is the same everytime in the interpreter!

>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'spam':4,'egg':2}
>>> ','.join(z)
'spam,bar,foo,egg'
>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'

I maybe missing something out but how does the interpreter remember it. Clear explanations would help greatly.

NOTE: As seen in the comments mentioned by chris_rands
I quote 'the dict iteration is fixed within an interpreter session because the environmental variable PYTHONHASHSEED is fixed'

is more along the lines of the answer I am looking for. Explanations would be great!.


问:
HTML to> AJAX to> Node to> Arduino
I'm a noob to Node and need some help.
Here's my current setup:Current Setup

One the one side I have a basic HTML website with a few <inputs>.  The inputs are assigned to variables via onclick event (jscript). Each input has its own button (not using a form)

One the other side I have Nodejs controlling a simple Arduino circuit via Johnny Five library.

My question:

Can I "pass" the values from my website to Nodejs without using AJAX?  Or is AJAX pretty much my only option?

答:
Last year I made something similar, and I used socket.io to communicate between browser and node js

Just look at an example and you should be able to make your own!

In my setup I used a VPS (static public ip) with node js to provide a relay between the client and the rpi (which also had node js and controlled the arduino)

Title: HTML to> AJAX to> Node to> Arduino


问:
Divide total value of 128 in three rows in SQL Server
Divide sum of quantity 128 in three rows in SQL Server.
Making three rows like:</p>

```<code>50
50
28
</code>```

答:
---- I have done it in another way look my code.If suppose I have Two Digits to splits.Can we do it without using loops

DECLARE @COUNT INT;
DECLARE @ITEMCOUNT INT;

```<code>DECLARE @ShipTable table(
ID INT IDENTITY(1,1),
WbDItemNo char(15),
Qty int

)
INSERT INTO @ShipTable
VALUES
(
'TEST ITEM',
59

),('TEST ITEM 1',225)

SELECT * FROM @ShipTable

SET @COUNT=(SELECT COUNT(*) FROM @ShipTable)
DECLARE @TOTALQTY INT
DECLARE @UPAMOUNT INT
DECLARE @DIVISIONALVAL INT
DECLARE @DIVIDEBY INT
DECLARE @ITEM VARCHAR(50)
SET @DIVIDEBY=50;

DECLARE @ITEMNO VARCHAR(50)
WHILE(@COUNT>0)
BEGIN

  SET @TOTALQTY=(SELECT Qty FROM @ShipTable WHERE ID=@COUNT)
  SET @ITEM=(SELECT WbDItemNo FROM @ShipTable WHERE ID=@COUNT)

  SET @UPAMOUNT=@TOTALQTY%@DIVIDEBY
  SELECT @ITEM,@UPAMOUNT
  SET @DIVISIONALVAL=@TOTALQTY/@DIVIDEBY
  SET @DIVISIONALVAL=FLOOR(@DIVISIONALVAL)

  WHILE(@DIVISIONALVAL>0)
  BEGIN
  SELECT @ITEM,@DIVIDEBY
  SET @DIVISIONALVAL=@DIVISIONALVAL-1
  END

  SET @COUNT=@COUNT-1
END
</code>```

Body:
Divide sum of quantity 128 in three rows in SQL Server.
Making three rows like:

50
50
28

Body:
---- I have done it in another way look my code.If suppose I have Two Digits to splits.Can we do it without using loops

DECLARE @COUNT INT;
DECLARE @ITEMCOUNT INT;

DECLARE @ShipTable table(
ID INT IDENTITY(1,1),
WbDItemNo char(15),
Qty int

)
INSERT INTO @ShipTable
VALUES
(
'TEST ITEM',
59

),('TEST ITEM 1',225)

SELECT * FROM @ShipTable

SET @COUNT=(SELECT COUNT(*) FROM @ShipTable)
DECLARE @TOTALQTY INT
DECLARE @UPAMOUNT INT
DECLARE @DIVISIONALVAL INT
DECLARE @DIVIDEBY INT
DECLARE @ITEM VARCHAR(50)
SET @DIVIDEBY=50;

DECLARE @ITEMNO VARCHAR(50)
WHILE(@COUNT>0)
BEGIN

  SET @TOTALQTY=(SELECT Qty FROM @ShipTable WHERE ID=@COUNT)
  SET @ITEM=(SELECT WbDItemNo FROM @ShipTable WHERE ID=@COUNT)

  SET @UPAMOUNT=@TOTALQTY%@DIVIDEBY
  SELECT @ITEM,@UPAMOUNT
  SET @DIVISIONALVAL=@TOTALQTY/@DIVIDEBY
  SET @DIVISIONALVAL=FLOOR(@DIVISIONALVAL)

  WHILE(@DIVISIONALVAL>0)
  BEGIN
  SELECT @ITEM,@DIVIDEBY
  SET @DIVISIONALVAL=@DIVISIONALVAL-1
  END

  SET @COUNT=@COUNT-1
END


问:
XSLT for-each failing to pick up fields
I've got a curious item, I'm trying to enumerate through an xml file with my XSLT transform, however I'm after putting a for-each loop into the code my records are not pulling any details (anymore).  Help!

XSLT

```<code>    <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>
    <xsl:variable name="pathid" select="montage/path" />
    <xsl:variable name="outputstr" select="''" />
    <xsl:template match="vista">
        <xsl:variable name="pathid" select="path" />
        <html>
            <body>
                <div align="center">
                    <table border="0" cellpadding="0" cellspacing="0" width="800" height="200">
                        <xsl:apply-templates select="item" />
                    </table>
                </div>
            </body>
        </html>
    </xsl:template>
    <xsl:template match="item">
        <xsl:variable name="monid" select="mon" />
            <!--<xsl:value-of select="format-number(position(), '#')" />-->
        <xsl:variable name="outputstr" select="file" />
            <xsl:choose>
                <xsl:when test="position() >= 0 and 4 > position()">
                    <tr height="200">
                    <xsl:for-each select="item">
                        <td width="157" height="108" valign="top">
                            <xsl:attribute name="height">
                                <xsl:value-of select="'200'"/>
                            </xsl:attribute>
                            <a>
                                <xsl:attribute name="href">
                                    <xsl:value-of select="$pathid" />
                                    <xsl:value-of select="thepage" />
                                </xsl:attribute>
                                <img>
                                    <xsl:attribute name="src">
                                        <xsl:value-of select="concat(substring-before($outputstr,'abc'),$pathid)"/>
                                        <xsl:value-of select="$outputstr" />
                                    </xsl:attribute>
                                </img>
                            </a>
                        </td>
                        </xsl:for-each>
                    </tr>
                </xsl:when>
            </xsl:choose>
            <xsl:attribute name="id">mon</xsl:attribute>
    </xsl:template>
</xsl:stylesheet>
</code>```

XML

```<code><?xml version="1.0"?>
<vista>
    <lastupdate>14/12/2010 14:32</lastupdate>
    <path>C:\</path>
    <item>
        <thepage>00000657.html</thepage>
        <heading>heading1</heading>
        <file>test123.png</file>
        <description>df bhdf hdfhdf hdfh he rher herh df bdf bdfb df rfbd bd</description>
    </item>
    <item>
        <thepage>00000660.html</thepage>
        <heading>heading2</heading>
        <file>test456.jpg</file>
        <description>reh erh erherh erh erher herh</description>
    </item>
</vista>
</code>```

Outputted HTML

```<code><html>
<body>
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" width="800" height="200">
<tr height="200"></tr>
<tr height="200"></tr>
<tr height="200"></tr>
<tr height="100"></tr>
<tr height="100"></tr>
<tr height="100"></tr>
<tr height="100"></tr>
</table>
</div>
</body>
</html>
</code>```

答:
You already have an item template - why do you need to for-each inside it?

I expect this to fail, as item nodes do not contain item nodes.

Title: XSLT for-each failing to pick up fields

Body:
I've got a curious item, I'm trying to enumerate through an xml file with my XSLT transform, however I'm after putting a for-each loop into the code my records are not pulling any details (anymore).  Help!

XSLT

    <?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="html" indent="yes" omit-xml-declaration="yes"/>
    <xsl:variable name="pathid" select="montage/path" />
    <xsl:variable name="outputstr" select="''" />
    <xsl:template match="vista">
        <xsl:variable name="pathid" select="path" />

                        <xsl:apply-templates select="item" />

    </xsl:template>
    <xsl:template match="item">
        <xsl:variable name="monid" select="mon" />

        <xsl:variable name="outputstr" select="file" />
            <xsl:choose>
                <xsl:when test="position() >= 0 and 4 > position()">

                    <xsl:for-each select="item">

                            <xsl:attribute name="height">
                                <xsl:value-of select="'200'"/>
                            </xsl:attribute>

                                <xsl:attribute name="href">
                                    <xsl:value-of select="$pathid" />
                                    <xsl:value-of select="thepage" />
                                </xsl:attribute>

                                    <xsl:attribute name="src">
                                        <xsl:value-of select="concat(substring-before($outputstr,'abc'),$pathid)"/>
                                        <xsl:value-of select="$outputstr" />
                                    </xsl:attribute>

                        </xsl:for-each>

                </xsl:when>
            </xsl:choose>
            <xsl:attribute name="id">mon</xsl:attribute>
    </xsl:template>
</xsl:stylesheet>

XML

<?xml version="1.0"?>
<vista>
    <lastupdate>14/12/2010 14:32</lastupdate>
    <path>C:\</path>
    <item>
        <thepage>00000657.html</thepage>
        <heading>heading1</heading>
        <file>test123.png</file>
        <description>df bhdf hdfhdf hdfh he rher herh df bdf bdfb df rfbd bd</description>
    </item>
    <item>
        <thepage>00000660.html</thepage>
        <heading>heading2</heading>
        <file>test456.jpg</file>
        <description>reh erh erherh erh erher herh</description>
    </item>
</vista>

Outputted HTML


问:
Select all cell values of a single row table and list it as separate row in SQL
I've a table like this

```<code>ID        col1         col2        col3      col4
---------------------------------------------------
1          a            b           c         d
2          e            f           g         h
</code>```

So if I pass the ID 2 it should return all the colum values as separate rows as this

```<code>Colum     Value
---------------------
ID        2
Col1      e
col2      f
col3      g
col4      h
</code>```

So all the cells of that single rows been splitted as separate rows.

How can I accomplish this

答:
Please refer the below  stack over flow link     SQL query to split column data into rows

found the question identical as yours.

Body:
I've a table like this

ID        col1         col2        col3      col4
---------------------------------------------------
1          a            b           c         d
2          e            f           g         h

So if I pass the ID 2 it should return all the colum values as separate rows as this

Colum     Value
---------------------
ID        2
Col1      e
col2      f
col3      g
col4      h

So all the cells of that single rows been splitted as separate rows.

How can I accomplish this


问:
Service unavailable message in IIS
I have created a sample ASP.NET website and hosted it in IIS 6.0 . It is working fine , if the identity of the defalut app pool is "local system". But when i changed the identity with some other configurable user id then it is showing as "Service Unavailable".

The following message is found in the event viewver.

"The identity of application pool 'DefaultAppPool' is invalid, so the World Wide Web Publishing Service can not create a worker process to serve the application pool.  Therefore, the application pool has been disabled."

答: The user identity you use needs to have fairly significant rights to operate. At a minimum the user needs to have read/execute permission on the root directory of the folder. This user should also have read/write/execute permission on the Temporary Asp.Net Files folder located within the %SystemRoot%/Microsoft.Net/Framework/ folder.</p>

Title: Service unavailable message in IIS


问:
Formatting Excel rows between values programmatically with C#
I'm working in a proyect and I have to generate an Excel with formatting conditions. I was able to do it with equals values (Ex: B2 = "Correct Value") but in some cases I have to check if the value is between two values (Ex: " 2 < B2 < 4 ") I have this code:

FormatCondition[] format = new FormatCondition[datos.Length];
            Microsoft.Office.Interop.Excel.Range[] cells = new Range[datos.Length];
            for (int i = 1; i < datos.Length; i++)
            {
                string condition = "";
                if (qTipo[i - 1] == "Num" && qMax[i - 1] != "" && qMin[i - 1] != "")
                { // DOES NOT WORK
                    condition = $"=Y(B{i + 1}<{qMax[i - 1]};B{i + 1}>{qMin[i - 1]})"; // THIS RETURNS "=Y(B4<6;B4>4)"
                    format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}",
                    Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,
                    condition));
                }
                else
                {   //WORKS
                    condition = $"=B{i + 1}=\"{qCorrecto[i - 1]}\""; // THIS RETURNS "=B2="Correct Value""
                    format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}",
                    Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,
                    condition));
                }
                format[i].Interior.Color = 0x0000FF00;
                datos[i] = new String[2];
                datos[i][0] = qPregunta[i - 1];
                datos[i][1] = "";
            }
```

When I execute this code it gives me "Invalid argument exception" on the Add statement.

Merci,
Miguel.

答:
Thanks to my super inteligence I was able to resolve this problem. The code I needed was:</p>
```<code>format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlBetween, $"={qMax[i - 1]}", $"={qMin[i - 1]}"));
</code>```

Body:
I'm working in a proyect and I have to generate an Excel with formatting conditions. I was able to do it with equals values (Ex: B2 = "Correct Value") but in some cases I have to check if the value is between two values (Ex: " 2 < B2 < 4 ") I have this code:

FormatCondition[] format = new FormatCondition[datos.Length];
            Microsoft.Office.Interop.Excel.Range[] cells = new Range[datos.Length];
            for (int i = 1; i < datos.Length; i++)
            {
                string condition = "";
                if (qTipo[i - 1] == "Num" && qMax[i - 1] != "" && qMin[i - 1] != "")
                { // DOES NOT WORK
                    condition = $"=Y(B{i + 1}<{qMax[i - 1]};B{i + 1}>{qMin[i - 1]})"; // THIS RETURNS "=Y(B4<6;B4>4)"
                    format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}",
                    Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,
                    condition));
                }
                else
                {   //WORKS
                    condition = $"=B{i + 1}=\"{qCorrecto[i - 1]}\""; // THIS RETURNS "=B2="Correct Value""
                    format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}",
                    Type.Missing).FormatConditions.Add(XlFormatConditionType.xlExpression, Type.Missing,
                    condition));
                }
                format[i].Interior.Color = 0x0000FF00;
                datos[i] = new String[2];
                datos[i][0] = qPregunta[i - 1];
                datos[i][1] = "";
            }

When I execute this code it gives me "Invalid argument exception" on the Add statement.

Merci,
Miguel.

Body:
Thanks to my super inteligence I was able to resolve this problem. The code I needed was:

format[i] = (FormatCondition)(xlWorksheet.get_Range($"B{i + 1}", Type.Missing).FormatConditions.Add(XlFormatConditionType.xlCellValue, XlFormatConditionOperator.xlBetween, $"={qMax[i - 1]}", $"={qMin[i - 1]}"));

ContentLicense: CC BY-SA 4.0


问:
Unexpected PDO "General error 2050" depending on configuration
I have some code where variable $query is supposed to hold different PDOStatement objects, one replaced by another:

```<code>$query = $conn->prepare("select * from ... ");
$query->execute();
while ($tmp=$query->fetch(PDO::FETCH_ASSOC)) {
   ...;
}

//unset($query);
$query = $conn->query("select * from ... ");
while ($tmp=$query->fetch(PDO::FETCH_ASSOC)) {
    ....;
}
</code>```

With such code I get "SQLSTATE[HY000]: General error: 2050" from PDO on the line with the last fetch. But if I uncomment line with "unset" - it starts working correctly.

Any idea of what could it be?

PS Without using unset, it also works with PDO::ATTR_EMULATE_PREPARES = true

UPD
Here is error code description from MySQL site:

Error: 2050 (CR_FETCH_CANCELED)
Message: Row retrieval was canceled by mysql_stmt_close() call

答:
in some php versions error 2050 happen because you must empty the var that holds the object with the result of the query
see  https://stackoverflow.com/a/36631355/2613863

in Matt Cavanagh  commet

Body:
I have some code where variable $query is supposed to hold different PDOStatement objects, one replaced by another:

$query = $conn->prepare("select * from ... ");
$query->execute();
while ($tmp=$query->fetch(PDO::FETCH_ASSOC)) {
   ...;
}

//unset($query);
$query = $conn->query("select * from ... ");
while ($tmp=$query->fetch(PDO::FETCH_ASSOC)) {
    ....;
}

With such code I get "SQLSTATE[HY000]: General error: 2050" from PDO on the line with the last fetch. But if I uncomment line with "unset" - it starts working correctly.

Any idea of what could it be?

PS Without using unset, it also works with PDO::ATTR_EMULATE_PREPARES = true

UPD
Here is error code description from MySQL site:

Error: 2050 (CR_FETCH_CANCELED)
Message: Row retrieval was canceled by mysql_stmt_close() call


问:
No response with a query by ID on Azure DocumentDB
I'm currently facing very slow/ no response on a collection looking by ID. I have ~ 2 milion of documents in a partitioned collection. If lookup the document using the partitionKey and id the response is immediate

```<code>SELECT * FROM c WHERE c.partitionKey=123 AND c.id="20566-2"
</code>```

if I try using only the id

```<code>SELECT * FROM c WHERE c.id="20566-2"
</code>```

the response never returns, java client seems freezed and I have the same situation using the Data Explorer from Azure Portal. I tried also looking up by another field that isn't the id or the partitionKey and the response always returns. When I try the select from Java client I always set the flag to enable cross partition query.

The next thing to try is to avoid the character "-" in the ID to test if this character blocks the query (anyway I didn't find anything on the documentation)

答:
The issue is related to your Java code. Due to Azure DocumentDB Java SDK wrapped the DocumentDB REST APIs, according to the reference of REST API Query Documents, as @DanCiborowski-MSFT said, the header x-ms-documentdb-query-enablecrosspartition explains your issue reason as below.

Header: x-ms-documentdb-query-enablecrosspartition

  Required/Type: Optional/Boolean

  Description: If the collection is partitioned, this must be set to True to allow execution across multiple partitions. Queries that filter against a single partition key, or against single-partitioned collections do not need to set the header.

So you need to set True to enable cross partition for querying across multiple partitions without a partitionKey in where clause via pass a instance of class FeedOption to the method queryDocuments, as below.

```<code>FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true); // Enable query across multiple partitions
String collectionLink = collection.getSelfLink();
FeedResponse<Document> queryResults = documentClient.queryDocuments(
    collectionLink,
    "SELECT * FROM c WHERE c.id='20566-2'", queryOptions);
</code>```

Body:
I'm currently facing very slow/ no response on a collection looking by ID. I have ~ 2 milion of documents in a partitioned collection. If lookup the document using the partitionKey and id the response is immediate

SELECT * FROM c WHERE c.partitionKey=123 AND c.id="20566-2"

if I try using only the id

SELECT * FROM c WHERE c.id="20566-2"

the response never returns, java client seems freezed and I have the same situation using the Data Explorer from Azure Portal. I tried also looking up by another field that isn't the id or the partitionKey and the response always returns. When I try the select from Java client I always set the flag to enable cross partition query.

The next thing to try is to avoid the character "-" in the ID to test if this character blocks the query (anyway I didn't find anything on the documentation)

Body:
The issue is related to your Java code. Due to Azure DocumentDB Java SDK wrapped the DocumentDB REST APIs, according to the reference of REST API Query Documents, as @DanCiborowski-MSFT said, the header x-ms-documentdb-query-enablecrosspartition explains your issue reason as below.

Header: x-ms-documentdb-query-enablecrosspartition

  Required/Type: Optional/Boolean

  Description: If the collection is partitioned, this must be set to True to allow execution across multiple partitions. Queries that filter against a single partition key, or against single-partitioned collections do not need to set the header.

So you need to set True to enable cross partition for querying across multiple partitions without a partitionKey in where clause via pass a instance of class FeedOption to the method queryDocuments, as below.

FeedOptions queryOptions = new FeedOptions();
queryOptions.setEnableCrossPartitionQuery(true); // Enable query across multiple partitions
String collectionLink = collection.getSelfLink();
FeedResponse<Document> queryResults = documentClient.queryDocuments(
    collectionLink,
    "SELECT * FROM c WHERE c.id='20566-2'", queryOptions);


问:
Creating a New Array in a Particular Order
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

```<code>dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});
</code>```

答:
As an option you can also have 3 different arrays which could be concatenated into a result one:

var dataList = [
  {id: 11, status: 'status-start'},
  {id: 2, status: 'status-completed'},
  {id: 3, status: 'status-in-progress'},
  {id: 4, status: 'status-start'},
  {id: 5, status: 'status-completed'},
  {id: 6, status: 'status-in-progress'},
  {id: 7, status: 'status-start'},
  {id: 8, status: 'status-start'},
  {id: 9, status: 'status-in-progress'},
  {id: 10, status: 'status-start'},
  {id: 11, status: 'status-completed'},
  {id: 1, status: 'status-completed'}
];

var currentBatches = [],
currentStartedBatches = [],
currentInProgressBatches = [{id: 200, status: 'status-in-progress'}],
currentCompletedBatches = [{id: 12, status: 'status-completed'}, {id: 119, status: 'status-completed'}];

currentStartedBatches = currentStartedBatches.concat(dataList.filter(function(d){ return d.status ==='status-start' }));

currentInProgressBatches = currentInProgressBatches.concat(dataList.filter(function(d){ return d.status ==='status-in-progress' }));

currentCompletedBatches = currentCompletedBatches.concat(dataList.filter(function(d){ return d.status ==='status-completed' }));

currentBatches = currentBatches.concat(currentStartedBatches).concat(currentInProgressBatches).concat(currentCompletedBatches);

console.log(currentBatches);```

Body:
Once a particular promise is resolved, i wish to loop through each of the items in the response and push them into an array in a specific order.

status-start

status-in-progress

status-completed

How can I go about doing this? Here is my code so far:

dashService.getBatches(refresh)
.then(function (response) {
  if (response.error) {
    console.log("No data received");
  } else {
    angular.forEach(response.items, function (item) {
      if (item.status === 'start') {
        currentBatches.push(job);
      }
    });
  }
});


问:
Xamarin.ios send sms user access permission
I need to know how configure my Xamarin.ios application to acquire a user access permission to send SMS, and where can i find the complete permission list.</p>

答:
There is no way you can send an SMS, the only thing you can do is compose a message is to create a URI like Device.OpenUrl("sms:123456789&body=sometext"); or use the MFMessageComposeViewController.

As far as I know there is no special permission needed for it.
For a complete list of permission and the how and why on iOS 10, read this.

iOS helps prevent apps from accessing a user’s personal information without permission. Additionally, in Settings, users can see which apps they have permitted to access certain information, as well as grant or revoke any future access. This includes access to:

Contacts

Microphone

Calendars

Camera

Reminders

HomeKit

Photos

Health

Motion activity and fitness

Speech recognition

Location Services

Bluetooth sharing

Media Library

Social media accounts, such as Twitter and Facebook

If the user signs in to iCloud, apps are granted access by default to iCloud Drive. Users may control each app’s access under iCloud in Settings. Additionally, iOS provides restrictions that prevent data movement between apps and accounts installed by MDM and those installed by the user.


问:
Create tables from SQL dump generated by phpmyadmin using kohana
I have a PHPMyAdmin SQL dump in a file. I want to use PHP to execute this SQL. How could I do that? I've tried a simple query (with Kohana but without it is enough too!) but I got a syntax error.
How could I do that?</p>

答:
Well this has nothing to do with Kohana. I would recommend you not do this through PHP as you then have memory and time constraints. If you can, use the terminal.

```<code>mysql -u [username] -p [password] [database name] < [filename.sql]
</code>```

Replacing [value] with their respective values.

Body:
Well this has nothing to do with Kohana. I would recommend you not do this through PHP as you then have memory and time constraints. If you can, use the terminal.

mysql -u [username] -p [password] [database name] < [filename.sql]

Replacing [value] with their respective values.


问:
repeating background image which is from 'image map' using CSS
I have a image map (sorry for sloppy drawing...)

The number means x-coordinate, y-coordinate, width, height.
For example, 5, 5, 25, 25 means that this image is located at (5, 5) and has width 25px and height 25px.

(the last image's size is wrong. 100, 5, 5, 25 is correct size.

And I want to make

using above image map with width 100px and height 25px.

At this time, I use image map as following.

```<code>#aDiv {
    width: 25px; height 25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}
</code>```

with one tag

```<code><div></div>
</code>```

for background.

But I have no idea that making something like second image using first image (image map).
How can I do this?

The above code is what I have done. I have no idea totally. The last idea I have is

```<code>#one {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

#two {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-100px -5px;
}

#three {
    display:inline-block;
    width:5px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-50px -5px;
}

<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
</code>```

But in this way, the total width is just 75 pixel. I need to repeat #two, i.e., repeating the third drawing of image map.

答:
Since we want to style our background we should use pseudo-elemets.
also it could be done with more than one div easier.

transform: scaleX(-1) will flip pseudo-element.
be careful with background-positioning.

:before contains first image, aDIV contains third image (----) and :after contains fliped of first image.
also we use z-index:-1 to put middle image on the bahind of two background and lose vertical edge by this hack.

```<code>#aDIV:before
{
content:" ";
width:75px;
height:25px;
background-image:url('path');
background-repeat:no-repeat;
background-position:-5px -5px;
}

 #aDIV:after
{
content:" ";
width:75px;
height:25px;
background-image:url('path');
background-repeat:no-repeat;
background-position:45px -5px;
transform: scaleX(-1);
}

#aDIV
{
 width:75px;
 height:25px;
 z-index:-1;
 background-image:url('path');
 background-repeat:no-repeat;
 background-position:20px -5px;
}
</code>```

Body:
I have a image map (sorry for sloppy drawing...)

The number means x-coordinate, y-coordinate, width, height.
For example, 5, 5, 25, 25 means that this image is located at (5, 5) and has width 25px and height 25px.

(the last image's size is wrong. 100, 5, 5, 25 is correct size.

And I want to make

using above image map with width 100px and height 25px.

At this time, I use image map as following.

#aDiv {
    width: 25px; height 25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

with one tag

for background.

But I have no idea that making something like second image using first image (image map).
How can I do this?

The above code is what I have done. I have no idea totally. The last idea I have is

#one {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-5px -5px;
}

#two {
    display:inline-block;
    width:25px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-100px -5px;
}

#three {
    display:inline-block;
    width:5px; height:25px;
    background-image:url('path');
    background-repeat:no-repeat;
    background-position:-50px -5px;
}

But in this way, the total width is just 75 pixel. I need to repeat #two, i.e., repeating the third drawing of image map.

Body:
Since we want to style our background we should use pseudo-elemets.
also it could be done with more than one div easier.

transform: scaleX(-1) will flip pseudo-element.
be careful with background-positioning.

:before contains first image, aDIV contains third image (----) and :after contains fliped of first image.
also we use z-index:-1 to put middle image on the bahind of two background and lose vertical edge by this hack.

#aDIV:before
{
content:" ";
width:75px;
height:25px;
background-image:url('path');
background-repeat:no-repeat;
background-position:-5px -5px;
}

 #aDIV:after
{
content:" ";
width:75px;
height:25px;
background-image:url('path');
background-repeat:no-repeat;
background-position:45px -5px;
transform: scaleX(-1);
}

#aDIV
{
 width:75px;
 height:25px;
 z-index:-1;
 background-image:url('path');
 background-repeat:no-repeat;
 background-position:20px -5px;
}


问:
To set selected item of Spinner by value, returns -1
i am using the following code to set selected item of a spinner by value. but the position that i get is -1.

Code:

```<code>final ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, location_days2);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        location_days.setAdapter(adapter1);
        String b = "5 Days";
        int a = adapter.getPosition(b); //this should return 5, but returns -1
        location_days.setSelection(a);
</code>```

String Array:

private String[] location_days2 = {"Select days","1 Day", "2 Days", "3 Days", "0 Days", "5 Days","6 Days"};

答:
You can do something like this to set selection in spinner</p>

```<code>int pos = 0;
String[] location_days2 = {"Select days", "1 Day", "2 Days", "3 Days", "0 Days", "5 Days", "6 Days"};
for (String location : location_days2) {
   if (location.equalsIgnoreCase("5 Days")) {
       pos = Arrays.asList(location_days2).indexOf("23");
       break;
      }
    }
location_days.setSelection(pos);
</code>```

Body:
i am using the following code to set selected item of a spinner by value. but the position that i get is -1.

Code:

final ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, location_days2);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        location_days.setAdapter(adapter1);
        String b = "5 Days";
        int a = adapter.getPosition(b); //this should return 5, but returns -1
        location_days.setSelection(a);

String Array:

private String[] location_days2 = {"Select days","1 Day", "2 Days", "3 Days", "0 Days", "5 Days","6 Days"};

Body:
You can do something like this to set selection in spinner

int pos = 0;
String[] location_days2 = {"Select days", "1 Day", "2 Days", "3 Days", "0 Days", "5 Days", "6 Days"};
for (String location : location_days2) {
   if (location.equalsIgnoreCase("5 Days")) {
       pos = Arrays.asList(location_days2).indexOf("23");
       break;
      }
    }
location_days.setSelection(pos);


问:
Saving generated images on IIS virtual directory?
I need to create web API that generate some images and return their paths.

I create the path to save using:

```<code>var resultPath = "Images/" + obiektId.ToString() + ".png";
var fullPath = HttpContext.Current.Server.MapPath("/" + resultPath);
</code>```

and return resultPath.

The problem is, that the virtual directory where I keep my site is C:\\sites\siteA and HttpContext.Current.Server.MapPath("/" + resultPath) returns C:\\inetpub\wwwroot\Images\123456.png. Then it is impossible for me to load the image from 10.0.0.106/siteA/Images/123456.png.

How can I save my image in my base virtual directory instead of saving it in wwwroot directory?

答:
```<code>string resultPath = obiektId.ToString() + ".png";
string fullPath  = System.Web.HttpContext.Current.Server.MapPath("~/Images"+ resultPath );
</code>```

Body:
I need to create web API that generate some images and return their paths.

I create the path to save using:

var resultPath = "Images/" + obiektId.ToString() + ".png";
var fullPath = HttpContext.Current.Server.MapPath("/" + resultPath);

and return resultPath.

The problem is, that the virtual directory where I keep my site is C:\\sites\siteA and HttpContext.Current.Server.MapPath("/" + resultPath) returns C:\\inetpub\wwwroot\Images\123456.png. Then it is impossible for me to load the image from 10.0.0.106/siteA/Images/123456.png.

How can I save my image in my base virtual directory instead of saving it in wwwroot directory?


问:
Pass whole Model through ajax call
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});
</code>```

I have tried with this but it just return a Model that is null:

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});
</code>```

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

```<code>public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}
</code>```

答:
Try something like this in your cshmtl page :

```<code> <script type="text/javascript">
        function GetModel() {
            return @Html.Raw(Json.Encode(Model));
        }
</script>
</code>```

And this how you can send WHOLE model:

```<code>var ModelData = GetModel();
 $.ajax(
        {
                        type: "POST", //HTTP POST Method
                        url: "/Video/UpdateComment", // Controller/View
                        data: { ModelName: GetModel(); }
        });
</code>```

Title: Pass whole Model through ajax call

Body:
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});

I have tried with this but it just return a Model that is null:

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}

Body:
Try something like this in your cshmtl page :

 <script type="text/javascript">
        function GetModel() {
            return @Html.Raw(Json.Encode(Model));
        }
</script>

And this how you can send WHOLE model:

var ModelData = GetModel();
 $.ajax(
        {
                        type: "POST", //HTTP POST Method
                        url: "/Video/UpdateComment", // Controller/View
                        data: { ModelName: GetModel(); }
        });


问:
Store std::string into int[] for Big Integer in C++
I'm trying to create my own class for BigInteger values. In this class Big Integer consist of unsigned int ints[capacity], and I have following code to convert std::string into BigInteger:

```<code>void FromByteString1(const std::string& buf) {
    int mask[] = {0, 8, 16, 24};
    int validMask = 0xff;
    size_t currentMask = 0, currentIndex = 0;
    for (register size_t i = 0; i < buf.size(); ++i) {
        int tmp = (int) buf[i];
        data[currentIndex] |= ((tmp << mask[currentMask]) & (validMask << mask[currentMask]));
        if (++currentMask == 4) {
            currentMask = 0;
            ++currentIndex;
        }
    }
}
</code>```

I trying to resolve this problem using union { char[4] chars; int value; }, but it gives me nothing.

Here is my output:

Here is full code of test project "Convertor", which is created to resolve this issue:

```<code>#include <iostream>
#include <iomanip>
#include <bitset>

#define Write(message) std::cout << message
#define WriteLine(message) std::cout << message << std::endl
#define WriteEndl() std::cout << std::endl

#define WIDTH_STR 9
#define WIDTH_INT 33

void ShowStringChars(const std::string& str) {
    for (size_t i = 0; i < str.length(); ++i)
        Write( std::setw(WIDTH_STR) << str[i] );
    WriteEndl();
}

void ShowStringCodes(const std::string& str) {
    for (size_t i = 0; i < str.length(); ++i)
        Write( std::setw(WIDTH_STR) << (int)str[i] );
    WriteEndl();
}

void ShowStringCodesBin(const std::string& str) {
    for (size_t i = 0; i < str.length(); ++i) {
        std::bitset<8> bites( (int)str[i] );
        Write( std::setw(WIDTH_STR) << bites );
    }
    WriteEndl();
}

void ShowIntValues(int* arr, size_t length) {
    for (size_t i = 0; i < length; ++i)
        Write( std::setw(WIDTH_INT) << arr[i] );
    WriteEndl();
}

void ShowIntValuesBin(int* arr, size_t length) {
    for (size_t i = 0; i < length; ++i) {
        std::bitset<32> bites( arr[i] );
        Write( std::setw(WIDTH_INT) << bites );
    }
    WriteEndl();
}

const int capacity = 256;
int data[capacity];

void Clear() {
    for (size_t i = 0; i < capacity; ++i)
        data[i] = 0;
}

union its {
    char chars[4];
    int value;
} int_to_str;

void FromByteString1(const std::string& buf) {
    int mask[] = {0, 8, 16, 24};
    int validMask = 0xff;
    size_t currentMask = 0, currentIndex = 0;
    for (register size_t i = 0; i < buf.size(); ++i) {
        int tmp = (int) buf[i];
        data[currentIndex] |= ((tmp << mask[currentMask]) & (validMask << mask[currentMask]));
        if (++currentMask == 4) {
            currentMask = 0;
            ++currentIndex;
        }
    }
}

void FromByteString2(const std::string& buf) {
    size_t index = 0;
    for (size_t i = 0; i < buf.size(); i += 4, ++index) {

        int_to_str.chars[0] = buf[i + 0];
        int_to_str.chars[1] = buf[i + 1];
        int_to_str.chars[2] = buf[i + 2];
        int_to_str.chars[3] = buf[i + 3];

        data[index] = int_to_str.value;
    }
}

int main() {

    Clear();

    //std::string value = "this is some string";
    std::string value = "this str";

    ShowStringChars(value);
    ShowStringCodes(value);
    ShowStringCodesBin(value);

    WriteEndl();
    WriteEndl();
    WriteEndl();

    FromByteString1(value);

    ShowIntValues(data, value.length() / 4);
    ShowIntValuesBin(data, value.length() / 4);

    return 0;
}
</code>```

Did anyone had similar problem? Thanks for any help :)

答:
The streaming operator of bitset uses std::bitset::to_string which behaves like this:

The resulting string contains N characters with the first character corresponds to the last (N-1th) bit and the last character corresponding to the first bit.

So, the last (rightmost) character of the output is the least significant (first) bit.

The first byte that you read, you shift the least. Therefore it becomes the least significant byte. Therefore the first byte that you read into the integer will be the right most byte in the output of the bitset.

A solution: Reverse the order in which you read the bytes i.e. interpret the input buffer as little endian, rather than big endian.

Note that since bitset prints highest bit first, you could interpret the output as little endian with individual bytes reversed, or big endian with the entire set reversed. I use reversed here in relation to memory position that grows left to right.

PS. representing a big integer as a null terminated string is not very useful since there is no way to represent numbers that contain bytes with the value zero.

Body:
I'm trying to create my own class for BigInteger values. In this class Big Integer consist of unsigned int ints[capacity], and I have following code to convert std::string into BigInteger:

void FromByteString1(const std::string& buf) {
    int mask[] = {0, 8, 16, 24};
    int validMask = 0xff;
    size_t currentMask = 0, currentIndex = 0;
    for (register size_t i = 0; i < buf.size(); ++i) {
        int tmp = (int) buf[i];
        data[currentIndex] |= ((tmp << mask[currentMask]) & (validMask << mask[currentMask]));
        if (++currentMask == 4) {
            currentMask = 0;
            ++currentIndex;
        }
    }
}

I trying to resolve this problem using union { char[4] chars; int value; }, but it gives me nothing.

Here is my output:

Here is full code of test project "Convertor", which is created to resolve this issue:

#include <iostream>
#include <iomanip>
#include <bitset>

#define Write(message) std::cout << message
#define WriteLine(message) std::cout << message << std::endl
#define WriteEndl() std::cout << std::endl

#define WIDTH_STR 9
#define WIDTH_INT 33

void ShowStringChars(const std::string& str) {
    for (size_t i = 0; i < str.length(); ++i)
        Write( std::setw(WIDTH_STR) << str[i] );
    WriteEndl();
}

void ShowStringCodes(const std::string& str) {
    for (size_t i = 0; i < str.length(); ++i)
        Write( std::setw(WIDTH_STR) << (int)str[i] );
    WriteEndl();
}

void ShowStringCodesBin(const std::string& str) {
    for (size_t i = 0; i < str.length(); ++i) {
        std::bitset<8> bites( (int)str[i] );
        Write( std::setw(WIDTH_STR) << bites );
    }
    WriteEndl();
}

void ShowIntValues(int* arr, size_t length) {
    for (size_t i = 0; i < length; ++i)
        Write( std::setw(WIDTH_INT) << arr[i] );
    WriteEndl();
}

void ShowIntValuesBin(int* arr, size_t length) {
    for (size_t i = 0; i < length; ++i) {
        std::bitset<32> bites( arr[i] );
        Write( std::setw(WIDTH_INT) << bites );
    }
    WriteEndl();
}

const int capacity = 256;
int data[capacity];

void Clear() {
    for (size_t i = 0; i < capacity; ++i)
        data[i] = 0;
}

union its {
    char chars[4];
    int value;
} int_to_str;

void FromByteString1(const std::string& buf) {
    int mask[] = {0, 8, 16, 24};
    int validMask = 0xff;
    size_t currentMask = 0, currentIndex = 0;
    for (register size_t i = 0; i < buf.size(); ++i) {
        int tmp = (int) buf[i];
        data[currentIndex] |= ((tmp << mask[currentMask]) & (validMask << mask[currentMask]));
        if (++currentMask == 4) {
            currentMask = 0;
            ++currentIndex;
        }
    }
}

void FromByteString2(const std::string& buf) {
    size_t index = 0;
    for (size_t i = 0; i < buf.size(); i += 4, ++index) {

        int_to_str.chars[0] = buf[i + 0];
        int_to_str.chars[1] = buf[i + 1];
        int_to_str.chars[2] = buf[i + 2];
        int_to_str.chars[3] = buf[i + 3];

        data[index] = int_to_str.value;
    }
}

int main() {

    Clear();

    //std::string value = "this is some string";
    std::string value = "this str";

    ShowStringChars(value);
    ShowStringCodes(value);
    ShowStringCodesBin(value);

    WriteEndl();
    WriteEndl();
    WriteEndl();

    FromByteString1(value);

    ShowIntValues(data, value.length() / 4);
    ShowIntValuesBin(data, value.length() / 4);

    return 0;
}

Did anyone had similar problem? Thanks for any help :)


问:
Using StatusStrip in C#
Consider System.Windows.Forms.StatusStrip. I have added a StatusStrip to my Windows Forms application, but I am having a few problems.

I would like to have a label anchored at the left and a progressbar anchored on the right in the StatusStrip, but I can't find a way to set these properties.

I then thought that I may need to create two StatusStrips and anchor them on either side of the bottom of the form... That didn't pan out; besides that, it just doesn't feel right.

答: Just set the Spring property on the label control to True and you should be good to go.

OwnerDisplayName: Brad

Title: Using StatusStrip in C#


问:
Insert text value starting with @ with Jquery where razor is active?
I am trying to insert the term @UserName into a CKEditor so that i may replace it at a later stage.

Whilst trying to insert the string the @ sign is highlighted in yellow as its expecting razor markup.

basic example

```<code>$('#SomeTextInput').val("@sometext");
</code>```

答:
use @@ instead of @ @@ is the escape char for @ in razor code your cde would look something like </p>

```<code>CKEditor.insteance[..].insertText('@@Hi there')
</code>```

Body:
I am trying to insert the term @UserName into a CKEditor so that i may replace it at a later stage.

Whilst trying to insert the string the @ sign is highlighted in yellow as its expecting razor markup.

basic example

$('#SomeTextInput').val("@sometext");

Body:
use @@ instead of @ @@ is the escape char for @ in razor code your cde would look something like

CKEditor.insteance[..].insertText('@@Hi there')


问:
How can I build Gradle for existing project?
I have an application which was got after "Decompile" an "apk" file. When I tried to import this existing project into Android Studio, I didn't got "Gradle" build. So this code is not working; can any one help me to resolve this? How can I build "Gradle" for this project...? </p>

答:
Maybe the project is not decompiled correctly.

You can also use apktool to decompile and recompile the APK. Use the following steps to decompile

```<code>apktool d <apk>
</code>```

and to compile back

```<code>apktool b <apk>
</code>```

When your APK is decompiled, it is not in the exact source code form. You will see a lot of dex hooks and in general it is not an exact android project that an IDE can recognise and import. You can use any normal editor to read the code and understand to make changes.

Body:
Maybe the project is not decompiled correctly.

You can also use apktool to decompile and recompile the APK. Use the following steps to decompile

apktool d <apk>

and to compile back

apktool b <apk>

When your APK is decompiled, it is not in the exact source code form. You will see a lot of dex hooks and in general it is not an exact android project that an IDE can recognise and import. You can use any normal editor to read the code and understand to make changes.


问:
Different behavior between my java app and my navigator when querying an url
I would like to query a portlet from a meteo service. But as my navigator gives me the correct page, my java application does not.

Here is my code without try/catch:

```<code>public static void main(String[] args) {
  // The portlet URL
  String cookieUrl = "http://france.meteofrance.com/france/meteo?PREVISIONS_PORTLET.path=previsionspluie/290190";
  HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
  // Some proxy configuration

  // Basic properties set to perform my task, but they might be useless as it does not work as I would
  connection.setRequestProperty("Accept-Charset", "UTF-8");
  connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");

  System.out.println(handler.getHtml(reader));
}

private String getHtml(BufferedReader reader)
{
  String html = "";
  for (String line; (line = reader.readLine()) != null;)
    html += line + "\n";
  return html;
}
</code>```

You can test it with the portle url given as example.
In the navigator the response contains the correct "prevision de pluie pour Brest".
In the java app the response contains this page : http://france.meteofrance.com/NoCookie.htm

It seems to be a cookie matter. But how could I handle it as my first tries to get cookie and send them back were unsuccessful.

Any help please?

答: It looks like the site you are trying to access relies on Cookies which are not supported by HttpURLConnection. A way around this issue is to use a library like HtmlUnit which simulates a browser (supports cookies, javascript, etc..).</p>

Body:
I would like to query a portlet from a meteo service. But as my navigator gives me the correct page, my java application does not.

Here is my code without try/catch:

public static void main(String[] args) {
  // The portlet URL
  String cookieUrl = "http://france.meteofrance.com/france/meteo?PREVISIONS_PORTLET.path=previsionspluie/290190";
  HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
  // Some proxy configuration

  // Basic properties set to perform my task, but they might be useless as it does not work as I would
  connection.setRequestProperty("Accept-Charset", "UTF-8");
  connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");

  System.out.println(handler.getHtml(reader));
}

private String getHtml(BufferedReader reader)
{
  String html = "";
  for (String line; (line = reader.readLine()) != null;)
    html += line + "\n";
  return html;
}

You can test it with the portle url given as example.
In the navigator the response contains the correct "prevision de pluie pour Brest".
In the java app the response contains this page : http://france.meteofrance.com/NoCookie.htm

It seems to be a cookie matter. But how could I handle it as my first tries to get cookie and send them back were unsuccessful.

Any help please?