问:
get an array of objects from php using Volley
I have php file that return a list of objects from database.
this is the php code:

```<code><?php
require_once('../connect.php');

$sql = "SELECT * FROM categories";
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $mydata = $json->addChild('category');
        $mydata->addChild('id',$row['id']);
        $mydata->addChild('name',$row['Name']);
         }
} else {
    echo "0 results";
}
$conn->close();
     echo( json_encode ($json));
?>
</code>```

and this is the result:

{"category":[{"id":"1","name":"test"},{"id":"2","name":"test2"}]}

Now i want to get the list of categories in android, i tried to do it using this code but it always return empty list:

```<code>   public List<Category> getAllCategories(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://localhost/Android/Categories/Select_All_Categories" ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("TAG","response :"+response);
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray sts = null;
                            sts = jsonObject.getJSONArray("category");

                            for (int i = 0; i < sts.length(); i++) {
                                JSONObject jo = sts.getJSONObject(i);
                                Category cc = new Category();
                                cc.setId(jo.getInt("id"));
                                cc.setName(jo.getString("name"));
                                ar.add(cc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });

        return ar;
    }
</code>```

can someone please help me and tell me what I am doing wrong?

Update for diegoveloper: this is the code i used in my main.

```<code>MyListener listener = new MyListener() {
    @Override
    public void returnYourData(List<Category> list) {
        for(Category c:list){
            lc.add(c);
        }
    }

    @Override
    public void returnError() {

    }
};

System.out.println(lc.size());
</code>```

答:
It's because your request is asynchronous, you could use an Interface to return your data.

```<code>public void getAllCategories(final YourInterfaceListener listener){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://localhost/Android/Categories/Select_All_Categories" ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("TAG","response :"+response);
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray sts = null;
                            sts = jsonObject.getJSONArray("category");

                            for (int i = 0; i < sts.length(); i++) {
                                JSONObject jo = sts.getJSONObject(i);
                                Category cc = new Category();
                                cc.setId(jo.getInt("id"));
                                cc.setName(jo.getString("name"));
                                ar.add(cc);
                            }
                            listener.returnYourData(ar);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            listener.returnError();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        listener.returnError();
                    }
                });

    }
</code>```

Your interface:

```<code>public interface YourInterfaceListener {
   void returnYourData(List<Category> list);
   void returnError();
}
</code>```

UPDATE

You are using an incorrect way to retrieve the data, check my "getAllCategories" method, is void.

Your data is received on the listener :

```<code>MyListener listener = new MyListener() {
    @Override
    public void returnYourData(List<Category> list) {
         // HERE YOU HAVE THE DATA, UPDATE YOUR UI HERE.
    }

    @Override
    public void returnError() {

    }
};
</code>```

Body:
I have php file that return a list of objects from database.
this is the php code:

<?php
require_once('../connect.php');

$sql = "SELECT * FROM categories";
$result = $conn->query($sql);
$json = new SimpleXMLElement('<xml/>');
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
      $mydata = $json->addChild('category');
        $mydata->addChild('id',$row['id']);
        $mydata->addChild('name',$row['Name']);
         }
} else {
    echo "0 results";
}
$conn->close();
     echo( json_encode ($json));
?>

and this is the result:

{"category":[{"id":"1","name":"test"},{"id":"2","name":"test2"}]}

Now i want to get the list of categories in android, i tried to do it using this code but it always return empty list:

   public List<Category> getAllCategories(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://localhost/Android/Categories/Select_All_Categories" ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("TAG","response :"+response);
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray sts = null;
                            sts = jsonObject.getJSONArray("category");

                            for (int i = 0; i < sts.length(); i++) {
                                JSONObject jo = sts.getJSONObject(i);
                                Category cc = new Category();
                                cc.setId(jo.getInt("id"));
                                cc.setName(jo.getString("name"));
                                ar.add(cc);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                });

        return ar;
    }

can someone please help me and tell me what I am doing wrong?

Update for diegoveloper: this is the code i used in my main.

MyListener listener = new MyListener() {
    @Override
    public void returnYourData(List<Category> list) {
        for(Category c:list){
            lc.add(c);
        }
    }

    @Override
    public void returnError() {

    }
};

System.out.println(lc.size());

Body:
It's because your request is asynchronous, you could use an Interface to return your data.

public void getAllCategories(final YourInterfaceListener listener){
        StringRequest stringRequest = new StringRequest(Request.Method.GET,"http://localhost/Android/Categories/Select_All_Categories" ,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            Log.d("TAG","response :"+response);
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray sts = null;
                            sts = jsonObject.getJSONArray("category");

                            for (int i = 0; i < sts.length(); i++) {
                                JSONObject jo = sts.getJSONObject(i);
                                Category cc = new Category();
                                cc.setId(jo.getInt("id"));
                                cc.setName(jo.getString("name"));
                                ar.add(cc);
                            }
                            listener.returnYourData(ar);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            listener.returnError();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        listener.returnError();
                    }
                });

    }

Your interface:

public interface YourInterfaceListener {
   void returnYourData(List<Category> list);
   void returnError();
}

UPDATE

You are using an incorrect way to retrieve the data, check my "getAllCategories" method, is void.

Your data is received on the listener :

MyListener listener = new MyListener() {
    @Override
    public void returnYourData(List<Category> list) {
         // HERE YOU HAVE THE DATA, UPDATE YOUR UI HERE.
    }

    @Override
    public void returnError() {

    }
};


来源: stackexchange

问:
How to add something into a div element
I've been trying to make a site that randomizes elements taken from some inputs, and so I don't have a strict amount of inputs I wanted to have a button that generates inputs automatically. My problem is though that the elements that should appear, only either do as text or don't appear at all

```<code>   <div id="objs">
      <input id="obj_1">
      <input id="obj_2">
    </div>
    <button onclick="addObj();">Add an Object</button>
    <script>
        var i = 2;
     function addObj() {
        i = i+1;
        var existObj = document.getElementById("objs");
        var addedElement = '<input id="obj_' + i + '">';
        //var addedElement = document.createTextNode('<input id="obj_' + i + '">');
        //existObj.appendChild(addedElement);
        //above was test with appending a child which resulted in text outcome
        var newObj = existObj + addedElement;
        existObj = newObj;
        console.log(existObj);
      }
     </script>
</code>```

I've already tried looking up an answer here and elsewhere

( how to add element within an element in html  and  How to add canvas to div element dynamically? (these are from StackOverflow))

both attempts resulted in no or text outcome.

答:
Since I got better knowledge now,I updated the answer to be better in line with good JS coding. This is it now:

This will add an element each time you press the button:

let i = 2;

function addObj() {
  i++;
  let container = document.getElementById("objs");
  let newObj = document.createElement("INPUT");
  newObj.setAttribute("id", `obj_${i}`);
  container.appendChild(newObj);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="objs">
  <input id="obj_1">
  <input id="obj_2">
</div>
<button onclick="addObj();">Add an Object</button></code>```

I think you were thinking to complicated.

I don't quite know how JS works in the background. But there is probably a difference between getting an Element and getting it's innerHTML.
Otherwise there wouldn't be a distinction, would it?

ContentLicense: CC BY-SA 3.0

Title: How to add something into a div element

Body:
I've been trying to make a site that randomizes elements taken from some inputs, and so I don't have a strict amount of inputs I wanted to have a button that generates inputs automatically. My problem is though that the elements that should appear, only either do as text or don't appear at all

      <input id="obj_1">
      <input id="obj_2">

    <button onclick="addObj();">Add an Object</button>

I've already tried looking up an answer here and elsewhere

( how to add element within an element in html  and  How to add canvas to div element dynamically? (these are from StackOverflow))

both attempts resulted in no or text outcome.

Body:
Since I got better knowledge now,I updated the answer to be better in line with good JS coding. This is it now:

This will add an element each time you press the button:

let i = 2;

function addObj() {
  i++;
  let container = document.getElementById("objs");
  let newObj = document.createElement("INPUT");
  newObj.setAttribute("id", `obj_${i}`);
  container.appendChild(newObj);
}

<div id="objs">
  <input id="obj_1">
  <input id="obj_2">
</div>
<button onclick="addObj();">Add an Object</button>

I think you were thinking to complicated.

I don't quite know how JS works in the background. But there is probably a difference between getting an Element and getting it's innerHTML.
Otherwise there wouldn't be a distinction, would it?

ContentLicense: CC BY-SA 4.0


答:
You said

above was test with appending a child which resulted in text outcome

And this is logic because you are using document.createTextNode.
However, you should use instead document.createElement .

```<code>   <script>
     var i = 2;
     function addObj() {
        i = i+1;
        var existObj = document.getElementById("objs");
        var addedElement = document.createElement("input");
        addedElement.id = 'obj_' + i;
        existObj.appendChild(addedElement);
        var newObj = existObj + addedElement;
        existObj = newObj;
        console.log(existObj);
      }
     </script>
</code>```

Title: How to add something into a div element

Body:
You said

above was test with appending a child which resulted in text outcome

And this is logic because you are using document.createTextNode.
However, you should use instead document.createElement .

   <script>
     var i = 2;
     function addObj() {
        i = i+1;
        var existObj = document.getElementById("objs");
        var addedElement = document.createElement("input");
        addedElement.id = 'obj_' + i;
        existObj.appendChild(addedElement);
        var newObj = existObj + addedElement;
        existObj = newObj;
        console.log(existObj);
      }
     </script>


问:
C++: Issue overloading I/O operators
I'm currently finding it impossible to fix an occurrence of infinite recursion in my code.

I have the following header that defines the Proces class:

#pragma once
#include <iostream>
class Proces {
    std::string name;
    int maxWaitTime;
    int timeToFinish;
    int timeWaited;
    int timeProcessed;

public:
    Proces(std::string n, int mwt = 1, int ttf = 1) :name(n), maxWaitTime(mwt), timeToFinish(ttf), timeWaited(0), timeProcessed(0) {}
    bool process(int a = 1) { timeProcessed += a; return isComplete(); }
    bool isComplete() { return timeProcessed >= timeToFinish; }
    bool wait(int a = 1) { timeWaited += a;return maxWaitReached(); }
    bool maxWaitReached() { return maxWaitTime <= timeWaited; }
    friend bool operator<(const Proces& a, const Proces& b);
    friend bool operator>(const Proces& a, const Proces& b);
    friend std::ostream &operator<<(std::ostream &output, const Proces& a);
    friend std::istream &operator>>(std::istream &input, const Proces& a);
};
```

<p>Then, for the implementation of the operators, I have:
 </p>

``` #include "proces.h"

    bool operator<(const Proces & a, const Proces & b)
    {
        if (a.timeWaited != b.timeWaited)
            return a.timeWaited < b.timeWaited;
        else
            return a.maxWaitTime (const Proces & a, const Proces & b)
    {
        return ! (a < b);
    }

    std::ostream & operator<<(std::ostream & output, const Proces & a)
    {
        output << a.naziv << " MWT:" << a.maxWaitTime << " TTC:" << a.timeToFinish << " WT:" << a.timeWaited << " TP:" <>(std::istream & input,Proces & a)
    {
        input >> a.name >> a.maxWaitTime >> a.timeToFinish;
        a.timeWaited = 0;
        a.timeProcessed = 0;
        return input;
    }
```

<p>This lead to two (as far as I know unrelated) problems:</p>

<ol>
<li>Use of the output operator lead to said infinite recursion happening</li>
<li>The code itself cannot be compiled without commenting out the implementation
of the input operator as it claims the fields of the class are inaccessible
in spite of being a friend of the class</li>
</ol>

<blockquote>
  <p>Severity  Code    Description Project File    Line    Suppression State
  Error (active)  E0265   member "Proces::name" (declared at line 4 of "[project path]\proces.h") is inaccessible aspdz2  [project path]\proces.cpp</p>
</blockquote>

<p>Here is the main function (the < and > operators work as intended):
</p>

```#include "proces.h"

int main() {
    Proces a{ "Glorious prces",1,2 };
    Proces b{ "Glorious prces2",2,2 };

    if (a < b)std::cout << "A is lesser" << std::endl;
    else std::cout << "B is lesser" << std::endl;

    if (a > b)std::cout << "A is greater" << std::endl;
    else std::cout << "B is greater" << std::endl;
    b.wait(-1);
    if (a < b)std::cout << "A is lesser" << std::endl;
    else std::cout << "B is lesser" << std::endl;

    //Infinite recursion happens here:
    std::cout << b << std::endl;

}
```

答:
It appears that the reason for the

Severity Code Description Project File Line Suppression State Error (active) E0265 member "Proces::name" (declared at line 4 of "[project path]\proces.h") is inaccessible aspdz2 [project path]\proces.cpp

error was due to the accidental inclusion of the const keyword in the declaration of the >> operator;
The recursion on the other hand was happening because I forgot to#include<string>

Title: C++: Issue overloading I/O operators

Body:
I'm currently finding it impossible to fix an occurrence of infinite recursion in my code.

I have the following header that defines the Proces class:

#pragma once
#include <iostream>
class Proces {
    std::string name;
    int maxWaitTime;
    int timeToFinish;
    int timeWaited;
    int timeProcessed;

public:
    Proces(std::string n, int mwt = 1, int ttf = 1) :name(n), maxWaitTime(mwt), timeToFinish(ttf), timeWaited(0), timeProcessed(0) {}
    bool process(int a = 1) { timeProcessed += a; return isComplete(); }
    bool isComplete() { return timeProcessed >= timeToFinish; }
    bool wait(int a = 1) { timeWaited += a;return maxWaitReached(); }
    bool maxWaitReached() { return maxWaitTime <= timeWaited; }
    friend bool operator<(const Proces& a, const Proces& b);
    friend bool operator>(const Proces& a, const Proces& b);
    friend std::ostream &operator<<(std::ostream &output, const Proces& a);
    friend std::istream &operator>>(std::istream &input, const Proces& a);
};

Then, for the implementation of the operators, I have:

 #include "proces.h"

    bool operator<(const Proces & a, const Proces & b)
    {
        if (a.timeWaited != b.timeWaited)
            return a.timeWaited < b.timeWaited;
        else
            return a.maxWaitTime (const Proces & a, const Proces & b)
    {
        return ! (a < b);
    }

    std::ostream & operator<<(std::ostream & output, const Proces & a)
    {
        output << a.naziv << " MWT:" << a.maxWaitTime << " TTC:" << a.timeToFinish << " WT:" << a.timeWaited << " TP:" <>(std::istream & input,Proces & a)
    {
        input >> a.name >> a.maxWaitTime >> a.timeToFinish;
        a.timeWaited = 0;
        a.timeProcessed = 0;
        return input;
    }

This lead to two (as far as I know unrelated) problems:

Use of the output operator lead to said infinite recursion happening

The code itself cannot be compiled without commenting out the implementation
of the input operator as it claims the fields of the class are inaccessible
in spite of being a friend of the class

Severity  Code    Description Project File    Line    Suppression State
  Error (active)  E0265   member "Proces::name" (declared at line 4 of "[project path]\proces.h") is inaccessible aspdz2  [project path]\proces.cpp

Here is the main function (the < and > operators work as intended):

#include "proces.h"

int main() {
    Proces a{ "Glorious prces",1,2 };
    Proces b{ "Glorious prces2",2,2 };

    if (a < b)std::cout << "A is lesser" << std::endl;
    else std::cout << "B is lesser" << std::endl;

    if (a > b)std::cout << "A is greater" << std::endl;
    else std::cout << "B is greater" << std::endl;
    b.wait(-1);
    if (a < b)std::cout << "A is lesser" << std::endl;
    else std::cout << "B is lesser" << std::endl;

    //Infinite recursion happens here:
    std::cout << b << std::endl;

}


问:
Django QuerySet not appearing in HTML file for PythonAnywhere Web App
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates).

Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it).

1) The QuerySet isn't loading at all in the HTML file.

I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page.

2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed).

I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere?

Thanks for the help, I appreciate it!

Here are my local files:

urls.py

```<code>from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
]
</code>```

views.py

```<code>from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})
</code>```

post_list.html

```<code><html>
  <head>
    <title>Dina's blog</title>
  </head>
  <body>
    <div>
      <h1><a href="/">Dina's Blog</a></h1>
    </div>

    {{ posts }}

  </body>
</html>
</code>```

答:
you cant just use the query_list like that in the template, you need to loop through it in the template and it will show all posts titles so your template will be like this

```<code>{% for post in posts %}
<p>{{post.post_title}}</p>
{% endfor %}
</code>```

i recommend following this blog

Body:
I'm having a bit of trouble with this part of the DjangoGirls tutorial (about templates).

Currently, my website is at chocoberrie.pythonanywhere.com. It's supposed to show a few posts inside the QuerySet, but the list is empty, and I don't know why (or how to fix it).

1) The QuerySet isn't loading at all in the HTML file.

I followed the steps to import the Post model into views.py and add the QuerySet in the posts variable (the previous part of the tutorial). When I tried putting {{ posts }} in the HTML file (post_list.html), nothing appears in the QuerySet that loads on the page.

2) I don't know how to edit the database file on PythonAnywhere. This database file is supposed to be separate from the local db.sqlite3 on my computer (since db.sqlite3 is in the .gitignore file, it's not committed).

I read about this here. I understand that this is useful to keep production changes from being displayed on the live website, but how I supposed to have this data on the PythonAnywhere side? What file am I supposed to edit on PythonAnywhere?

Thanks for the help, I appreciate it!

Here are my local files:

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.post_list, name='post_list'),
]

views.py

from django.shortcuts import render
from django.utils import timezone
from .models import Post

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

post_list.html

    <title>Dina's blog</title>

Dina's Blog

    {{ posts }}

Body:
you cant just use the query_list like that in the template, you need to loop through it in the template and it will show all posts titles so your template will be like this

{% for post in posts %}
<p>{{post.post_title}}</p>
{% endfor %}

i recommend following this blog


答:
You can use createElement and appendChild

function addObj() {
    var existObj = document.getElementById("objs");

    // count those input elements
    // change the selector to '*' or whatever fits your needs
    // if there are also other elements you need to count from id="objs"
    var i = existObj.querySelectorAll('[id^="obj_"]').length + 1;

    var newElement = document.createElement('input');
        newElement.id = 'obj_' + i;

    existObj.appendChild(newElement);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="objs">
  <input id="obj_1">
  <input id="obj_2">
</div>
<button onclick="addObj();">Add an Object</button></code>```

Title: How to add something into a div element

Body:
You can use createElement and appendChild

function addObj() {
    var existObj = document.getElementById("objs");

    // count those input elements
    // change the selector to '*' or whatever fits your needs
    // if there are also other elements you need to count from id="objs"
    var i = existObj.querySelectorAll('[id^="obj_"]').length + 1;

    var newElement = document.createElement('input');
        newElement.id = 'obj_' + i;

    existObj.appendChild(newElement);
}

<div id="objs">
  <input id="obj_1">
  <input id="obj_2">
</div>
<button onclick="addObj();">Add an Object</button>


问:
REST API Call from VB ( ZOHO CREATOR )
Trying to make out this call

https://www.zoho.com/creator/help/api/rest-api/rest-api-edit-records.html

I did tried everything but seems i need basic knowledge. Can anyone give me directions what is wrong with my code

```<code>Public Sub updateRecord(ByVal ht As Hashtable, ByVal criteriaField As String)

        Dim apiUrl As String = "https://creator.zoho.com/api/xml/write/apikey=xxxx"
        Dim xmlStr As New System.Text.StringBuilder
        Dim newvalue As New System.Text.StringBuilder

        newvalue.AppendLine("<newvalues>")
        xmlStr.Append("<ZohoCreator><applicationlist>")
        xmlStr.Append("<application name=copy-of-ebay-inventory><formlist><form name=Ebay_Inventory>")
        xmlStr.AppendLine("<update>")
        xmlStr.AppendLine("<criteria>")
        xmlStr.AppendLine("<field name='Ticket Number' compOperator='Equals' value='20573'></field>")
        xmlStr.AppendLine("</criteria>")
        newvalue.AppendLine("<field name='Found on site' value='1'></field>")
        newvalue.AppendLine("</newvalues>")
        xmlStr.Append(newvalue.ToString)
        xmlStr.AppendLine("</update>")
        xmlStr.AppendLine("</form></formlist></application></applicationlist></ZohoCreator>")

        Dim params As String = "XMLString=" + xmlStr.ToString

        Dim res As String = getResponseFromUrl(apiUrl, params)

    End Sub
Public Function getResponseFromUrl(ByVal url As String, ByVal params As String)
        Dim str As String = ""
        Try
            Dim webreq As HttpWebRequest = WebRequest.Create(url)
            webreq.Method = "POST"
            webreq.ContentType = "application/x-www-form-urlencoded"
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(params)
            Dim dataStream As Stream = webreq.GetRequestStream()
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()

            Dim res As WebResponse = webreq.GetResponse()
            Dim stream As Stream = res.GetResponseStream()
            Dim streamReader As New StreamReader(stream)
            str = streamReader.ReadToEnd
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return str.ToString
    End Function
</code>```

At the end of formating my xml looks like

But that is not that.
Found a good example on ..

LINK DEMO

Reposnse

答:
Wrap all XML attribute values with a quote (single or double, although double is more common):</p>

```<code>    xmlStr.Append("<application name=" & ControlChars.Quote & "copy-of-ebay-inventory" & ControlChars.Quote &
                  "><formlist><form name=" & ControlChars.Quote & "Ebay_Inventory" & ControlChars.Quote & ">")
</code>```

Title: REST API Call from VB ( ZOHO CREATOR )

Body:
Trying to make out this call

https://www.zoho.com/creator/help/api/rest-api/rest-api-edit-records.html

I did tried everything but seems i need basic knowledge. Can anyone give me directions what is wrong with my code

Public Sub updateRecord(ByVal ht As Hashtable, ByVal criteriaField As String)

        Dim apiUrl As String = "https://creator.zoho.com/api/xml/write/apikey=xxxx"
        Dim xmlStr As New System.Text.StringBuilder
        Dim newvalue As New System.Text.StringBuilder

        newvalue.AppendLine("<newvalues>")
        xmlStr.Append("<ZohoCreator><applicationlist>")
        xmlStr.Append("<application name=copy-of-ebay-inventory><formlist><form name=Ebay_Inventory>")
        xmlStr.AppendLine("<update>")
        xmlStr.AppendLine("<criteria>")
        xmlStr.AppendLine("<field name='Ticket Number' compOperator='Equals' value='20573'></field>")
        xmlStr.AppendLine("</criteria>")
        newvalue.AppendLine("<field name='Found on site' value='1'></field>")
        newvalue.AppendLine("</newvalues>")
        xmlStr.Append(newvalue.ToString)
        xmlStr.AppendLine("</update>")
        xmlStr.AppendLine("</form></formlist></application></applicationlist></ZohoCreator>")

        Dim params As String = "XMLString=" + xmlStr.ToString

        Dim res As String = getResponseFromUrl(apiUrl, params)

    End Sub
Public Function getResponseFromUrl(ByVal url As String, ByVal params As String)
        Dim str As String = ""
        Try
            Dim webreq As HttpWebRequest = WebRequest.Create(url)
            webreq.Method = "POST"
            webreq.ContentType = "application/x-www-form-urlencoded"
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(params)
            Dim dataStream As Stream = webreq.GetRequestStream()
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()

            Dim res As WebResponse = webreq.GetResponse()
            Dim stream As Stream = res.GetResponseStream()
            Dim streamReader As New StreamReader(stream)
            str = streamReader.ReadToEnd
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        Return str.ToString
    End Function

At the end of formating my xml looks like

But that is not that.
Found a good example on ..

LINK DEMO

Reposnse

Body:
Wrap all XML attribute values with a quote (single or double, although double is more common):

    xmlStr.Append("<application name=" & ControlChars.Quote & "copy-of-ebay-inventory" & ControlChars.Quote &
                  "><formlist><form name=" & ControlChars.Quote & "Ebay_Inventory" & ControlChars.Quote & ">")


问:
How do I get a JQuery object inside a template literal?
So often I have a JQuery object such as

```<code>var element = $('<h1>Title</h1>');
</code>```

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. Here is my attempt

```<code>var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);
</code>```

This, as expected, outputs

```<code><div><div>[Object object]</div></div>
</code>```

as it is referencing an object, not actually the HTML of the element. However I want it to be .

```<code><div><div><h1>Title</h1></div</div>
</code>```

Is there a way of doing this? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds.

答:
Try following code:</p>

```<code>var element = $('<h1>Title</h1>');
var secondElement = $(`<div><div>${element.prop('outerHTML')}</div></div>`);
$('#someRandomDiv').append(secondElement);
</code>```

Body:
So often I have a JQuery object such as

var element = $('
Title
');

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. Here is my attempt

var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);

This, as expected, outputs

[Object object]

as it is referencing an object, not actually the HTML of the element. However I want it to be .

Title
</div

Is there a way of doing this? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds.

Body:
Try following code:

var element = $('<h1>Title</h1>');
var secondElement = $(`<div><div>${element.prop('outerHTML')}</div></div>`);
$('#someRandomDiv').append(secondElement);


问:
Elegant mapping from POJOs to vertx.io's JsonObject?
I am currently working on a vertx.io application and wanted to use the provide mongo api for data storage.  I currently have a rather clunky abstraction on top of the stock JsonObject classes where all get and set methods are  replaced with things like:

```<code>this.backingObject.get(KEY_FOR_THIS_PROPERTY);
</code>```

This is all well and good for now, but it won't scale particularly well.  it also seems dirty, specifically when using nested arrays or objects.  For example, if I want to be able to fill fields only when actual data is known, I have to check if the array exists, and if it doesn't create it and store it in the object.  Then I can add an element to the list.  For example:

```<code>if (this.backingObject.getJsonArray(KEY_LIST) == null) {
    this.backingObject.put(KEY_LIST, new JsonArray());
}
this.backingObject.getJsonArray(KEY_LIST).add(p.getBackingObject());
</code>```

I have thought about potential solutions but don't particularly like any of them.  Namely, I could use Gson or some similar library with annotation support to handle loading the object for the purposes of manipulating the data in my code, and then using the serialize and unserialize function of both Gson and Vertx to convert between the formats (vertx to load data -> json string -> gson to parse json into pojos -> make changes -> serialize to json string -> parse with vertx and save) but that's a really gross and inefficient workflow.  I could also probably come up with some sort of abstract wrapper that extends/implements the vertx json library but passes all the functionality through to gson, but that also seems like a lot of work.

Is there any good way to achieve more friendly and maintainable serialization using vertx?

答:
I think that using Gson as you described is the best possible solution at the current time.

While I agree that if a protocol layer was included in Vert.x it would indeed be first prize, using Gson keeps your server internals pretty organised and is unlikely to be the performance bottleneck.

When and only when this strategy becomes the performance bottleneck have you reached the point to engineer a better solution. Anything before that is premature optimisation.

My two cents.

Body:
I am currently working on a vertx.io application and wanted to use the provide mongo api for data storage.  I currently have a rather clunky abstraction on top of the stock JsonObject classes where all get and set methods are  replaced with things like:

this.backingObject.get(KEY_FOR_THIS_PROPERTY);

This is all well and good for now, but it won't scale particularly well.  it also seems dirty, specifically when using nested arrays or objects.  For example, if I want to be able to fill fields only when actual data is known, I have to check if the array exists, and if it doesn't create it and store it in the object.  Then I can add an element to the list.  For example:

if (this.backingObject.getJsonArray(KEY_LIST) == null) {
    this.backingObject.put(KEY_LIST, new JsonArray());
}
this.backingObject.getJsonArray(KEY_LIST).add(p.getBackingObject());

I have thought about potential solutions but don't particularly like any of them.  Namely, I could use Gson or some similar library with annotation support to handle loading the object for the purposes of manipulating the data in my code, and then using the serialize and unserialize function of both Gson and Vertx to convert between the formats (vertx to load data -> json string -> gson to parse json into pojos -> make changes -> serialize to json string -> parse with vertx and save) but that's a really gross and inefficient workflow.  I could also probably come up with some sort of abstract wrapper that extends/implements the vertx json library but passes all the functionality through to gson, but that also seems like a lot of work.

Is there any good way to achieve more friendly and maintainable serialization using vertx?


问:
Amazon Alexa Entity Resolution
I am having trouble getting Alexa to understand any synonyms for the words I'm speaking to her. She will always return that she does not know the meaning of the synonym despite having added it as part of the intent schema:

```<code>{
  "languageModel": {
    "types": [
      {
        "name": "LIST_OF_DEFINITIONS",
        "values": [
          {
            "id": "USER_EXPERIENCE",
            "name": {
              "value": "user experience",
              "synonyms": [
                "ux"
              ]
            }
          }
        ]
      }
    ],
  "intents": [
    {
      "name": "AMAZON.CancelIntent",
      "samples": []
    },
    {
      "name": "AMAZON.HelpIntent",
      "samples": []
    },
    {
      "name": "AMAZON.RepeatIntent",
      "samples": []
    },
    {
      "name": "AMAZON.StopIntent",
      "samples": []
    },
    {
      "name": "RecipeIntent",
      "samples": [
        "what is a {Definition}"
      ],
      "slots": [
        {
          "name": "Definition",
          "type": "LIST_OF_DEFINITIONS"
        }
      ]
    }
  ],
  "invocationName": "digital dictionary"
 }
}
</code>```

Am I missing something?

答: Your synonym "ux" isn't going to be understood because the user won't pronounce it like a word but rather they will say two letters. So, try adding "u x" and "U.X.". That should work.</p>

Title: Amazon Alexa Entity Resolution

Body:
I am having trouble getting Alexa to understand any synonyms for the words I'm speaking to her. She will always return that she does not know the meaning of the synonym despite having added it as part of the intent schema:

{
  "languageModel": {
    "types": [
      {
        "name": "LIST_OF_DEFINITIONS",
        "values": [
          {
            "id": "USER_EXPERIENCE",
            "name": {
              "value": "user experience",
              "synonyms": [
                "ux"
              ]
            }
          }
        ]
      }
    ],
  "intents": [
    {
      "name": "AMAZON.CancelIntent",
      "samples": []
    },
    {
      "name": "AMAZON.HelpIntent",
      "samples": []
    },
    {
      "name": "AMAZON.RepeatIntent",
      "samples": []
    },
    {
      "name": "AMAZON.StopIntent",
      "samples": []
    },
    {
      "name": "RecipeIntent",
      "samples": [
        "what is a {Definition}"
      ],
      "slots": [
        {
          "name": "Definition",
          "type": "LIST_OF_DEFINITIONS"
        }
      ]
    }
  ],
  "invocationName": "digital dictionary"
 }
}

Am I missing something?


问:
How can I return rows for IDs that meet criteria for EXACTLY 3 occurrences in a row?
I have a requirement that is throwing me for a loop.I have to return location IDs that have exactly 3 consecutive rows of monthly invoice amounts >$2,000. In other words, I do not want to return IDs for mature locations (that might have hundreds of monthly invoices rows).

Rextester example data: http://rextester.com/CNJC15871

Info:

The report will be run on the first of each month

Monthly invoice dates are the 15th of the month

Desired Output: In the invoice table below,

For a report run date of 10/1, loc_ids 2223 and 3344 would be returned, because 9/15 was the third ever consecutive month of invoice amount >$2,000

For a report run date of 11/1, loc_id 6678 would be returned, by the same logic.

For subsequent report months, 2223, 3344, and 6678 should NOT be returned because they have >3 consecutive months >$2,000.

```<code>| loc_id | invoice_date | invoice_amt | Notes                     |
|--------|--------------|-------------|---------------------------|
| 1234   | 5/15/2002    | 7000        |                           |
| 1234   | 6/15/2002    | 8000        |                           |
| ..     | …            | …           |                           |
| 1234   | 11/15/2017   | 58000       |                           |
|        |              |             |                           |
| 9987   | 11/15/2006   | 7500        |                           |
| 9987   | 12/15/2006   | 8500        |                           |
| …      | …            |             |                           |
| 9987   | 11/15/2017   | 63000       |                           |
|        |              |             |                           |
| 5544   | 3/15/2015    | 9200        |                           |
| 5544   | 4/15/2015    | 10000       |                           |
| …      | …            |             |                           |
| 5544   | 11/15/2017   | 70000       |                           |
|        |              |             |                           |
| 2223   | 5/15/2017    | 2500        | Count| >2000              |
| 2223   | 6/15/2017    | 1375        | Do not count| <2000       |
| 2223   | 7/15/2017    | 8000        | Restart count| >2000 (1)  |
| 2223   | 8/15/2017    | 9000        | Continue count| >2000 (2) |
| 2223   | 9/15/2017    | 9800        | Continue count| >2000 (3) |
| 2223   | 10/15/2017   | 10500       | Stop count| >3 in a row   |
| 2223   | 11/15/2017   | 11200       | Stop count| >3 in a row   |
|        |              |             |                           |
| 3344   | 7/15/2017    | 3500        | Count| >2000 (1)          |
| 3344   | 8/15/2017    | 4500        | Continue count| >2000 (2) |
| 3344   | 9/15/2017    | 6000        | Continue count| >2000 (3) |
| 3344   | 10/15/2017   | 7000        | Stop count| >3 in a row   |
| 3344   | 11/15/2017   | 8000        | Stop count| >3 in a row   |
|        |              |             |                           |
| 6678   | 8/15/2017    | 3000        | Count| >2000 (1)          |
| 6678   | 9/15/2017    | 4000        | Continue count| >2000 (2) |
| 6678   | 10/15/2017   | 5000        | Continue count| >2000 (3) |
</code>```

I also have a loc_id dimension that includes the location open date.

```<code>| loc_id | loc_open_dt |
|--------|-------------|
| 1234   | 2002-05-01  |
| 9987   | 2006-10-22  |
| 5544   | 2015-03-04  |
| 2223   | 2017-05-05  |
| 3344   | 2017-07-05  |
| 6678   | 2017-08-01  |
</code>```

答:
Here is query that checks that:

the months with >=2000 amounts are consecutive, and

the month preceding the listing date is the last one of those, and

if there is an amount for the month preceding those three, it is below 2000

Query:

```<code>select distinct loc_id
from   (
        select loc_id,
               first_value(invoice_amt) over win                            first_amt,
               floor((list_date - first_value(invoice_date) over win)/30)+1 month_count,
               list_date - last_value(invoice_date) over win < 30           has_last_month,
               count(case when invoice_amt >= 2000 then 1 end) over win     large_amt_count
        from   invoices,
               (select date '2017-10-01' /* current_date */ list_date) ref
        where  invoice_date between (list_date - 120) and list_date
        window win as (partition by loc_id order by invoice_date)
       ) base
where  month_count = 3 + (first_amt < 2000)::int
   and large_amt_count = 3
   and has_last_month;
</code>```

See it run on rextester

Change the literal date in the middle of the query to your actual reporting date (or current_date).

Body:
I have a requirement that is throwing me for a loop.I have to return location IDs that have exactly 3 consecutive rows of monthly invoice amounts >$2,000. In other words, I do not want to return IDs for mature locations (that might have hundreds of monthly invoices rows).

Rextester example data: http://rextester.com/CNJC15871

Info:

The report will be run on the first of each month

Monthly invoice dates are the 15th of the month

Desired Output: In the invoice table below,

For a report run date of 10/1, loc_ids 2223 and 3344 would be returned, because 9/15 was the third ever consecutive month of invoice amount >$2,000

For a report run date of 11/1, loc_id 6678 would be returned, by the same logic.

For subsequent report months, 2223, 3344, and 6678 should NOT be returned because they have >3 consecutive months >$2,000.

| loc_id | invoice_date | invoice_amt | Notes                     |
|--------|--------------|-------------|---------------------------|
| 1234   | 5/15/2002    | 7000        |                           |
| 1234   | 6/15/2002    | 8000        |                           |
| ..     | …            | …           |                           |
| 1234   | 11/15/2017   | 58000       |                           |
|        |              |             |                           |
| 9987   | 11/15/2006   | 7500        |                           |
| 9987   | 12/15/2006   | 8500        |                           |
| …      | …            |             |                           |
| 9987   | 11/15/2017   | 63000       |                           |
|        |              |             |                           |
| 5544   | 3/15/2015    | 9200        |                           |
| 5544   | 4/15/2015    | 10000       |                           |
| …      | …            |             |                           |
| 5544   | 11/15/2017   | 70000       |                           |
|        |              |             |                           |
| 2223   | 5/15/2017    | 2500        | Count| >2000              |
| 2223   | 6/15/2017    | 1375        | Do not count| <2000       |
| 2223   | 7/15/2017    | 8000        | Restart count| >2000 (1)  |
| 2223   | 8/15/2017    | 9000        | Continue count| >2000 (2) |
| 2223   | 9/15/2017    | 9800        | Continue count| >2000 (3) |
| 2223   | 10/15/2017   | 10500       | Stop count| >3 in a row   |
| 2223   | 11/15/2017   | 11200       | Stop count| >3 in a row   |
|        |              |             |                           |
| 3344   | 7/15/2017    | 3500        | Count| >2000 (1)          |
| 3344   | 8/15/2017    | 4500        | Continue count| >2000 (2) |
| 3344   | 9/15/2017    | 6000        | Continue count| >2000 (3) |
| 3344   | 10/15/2017   | 7000        | Stop count| >3 in a row   |
| 3344   | 11/15/2017   | 8000        | Stop count| >3 in a row   |
|        |              |             |                           |
| 6678   | 8/15/2017    | 3000        | Count| >2000 (1)          |
| 6678   | 9/15/2017    | 4000        | Continue count| >2000 (2) |
| 6678   | 10/15/2017   | 5000        | Continue count| >2000 (3) |

I also have a loc_id dimension that includes the location open date.

| loc_id | loc_open_dt |
|--------|-------------|
| 1234   | 2002-05-01  |
| 9987   | 2006-10-22  |
| 5544   | 2015-03-04  |
| 2223   | 2017-05-05  |
| 3344   | 2017-07-05  |
| 6678   | 2017-08-01  |

Body:
Here is query that checks that:

the months with >=2000 amounts are consecutive, and

the month preceding the listing date is the last one of those, and

if there is an amount for the month preceding those three, it is below 2000

Query:

select distinct loc_id
from   (
        select loc_id,
               first_value(invoice_amt) over win                            first_amt,
               floor((list_date - first_value(invoice_date) over win)/30)+1 month_count,
               list_date - last_value(invoice_date) over win < 30           has_last_month,
               count(case when invoice_amt >= 2000 then 1 end) over win     large_amt_count
        from   invoices,
               (select date '2017-10-01' /* current_date */ list_date) ref
        where  invoice_date between (list_date - 120) and list_date
        window win as (partition by loc_id order by invoice_date)
       ) base
where  month_count = 3 + (first_amt < 2000)::int
   and large_amt_count = 3
   and has_last_month;

See it run on rextester

Change the literal date in the middle of the query to your actual reporting date (or current_date).


问:
Swift how to tell when a variable changed in a shared instance
I have a variable in a singleton pattern that is used/referenced through out the app.

I have a mainVC that has a custom view in it that sets a variable.  I want the view controller that is presented in the navigation controller to be notified when this variable changes.

For example:

in my mainVC it has an embedded navigation controller, which I push View1.  On the mainVC toolbar, there is a textfield that the user can enter values.  When this values changes, I would like to have View1 to know it has changed.  View1 can be any view that is currently presented.

答:
I have used this pattern a few times and I prefer to use NotificationCenter.

In your Singleton class you need to use Post method every time the value changes , And in your viewcontroller you would add the observer to reflect or react to the change.

There are multiple ways to tackle this. And there are plenty of great tutorials out there for the same.


问:
Greasemonkey change div id class
I'm trying to change the class to "sidebar" and style height to "50%" of this div (Facebook):

```<code><div id="pagelet_ticker" class="hidden_elem" style="height: 0px;">
</code>```

I don't know why the following Greasemonkey script is not working. Any suggestions are much appreciated. Thank you!
---Edited to reflect the changes suggested --- still not working

```<code>// ==UserScript==
// @name           Ticker
// @namespace      Ticker
// @description    Ticker
// @include        https://www.facebook.com
// ==/UserScript==

var query = document.querySelector('#pagelet_ticker'); //added #
        query.setAttribute("class", "sidebar");
        query.setAttribute("style", "height: 50%;");  //changed attribute to style
</code>```

答:
I did it using this:

var ticker = document.getElementById ("pagelet_ticker");
ticker.classList.remove ("hidden_elem");
ticker.classList.add ("sidebar");
ticker.style.height = '200px';

Thank you all for the help!

Title: Greasemonkey change div id class

Body:
I'm trying to change the class to "sidebar" and style height to "50%" of this div (Facebook):

I don't know why the following Greasemonkey script is not working. Any suggestions are much appreciated. Thank you!
---Edited to reflect the changes suggested --- still not working

// ==UserScript==
// @name           Ticker
// @namespace      Ticker
// @description    Ticker
// @include        https://www.facebook.com
// ==/UserScript==

var query = document.querySelector('#pagelet_ticker'); //added #
        query.setAttribute("class", "sidebar");
        query.setAttribute("style", "height: 50%;");  //changed attribute to style


问:
Delete folder from svn having the special character sign & ampersand
I m trying to delete or remove the svn folder which has the speacial character & sign in between the folder name and unfortunately its not being found in the working copy in xcode and all the time my build gets failed.
When trying to delete the Folder using terminal it always returns the error as
"svn delete --force PlayDate/Model/Cell\ Classes/Places&FavoritesCell
1 43050
-bash: FavoritesCell: command not found"

Attaching up the screenshot for the same to get the clear idea
https://imgur.com/a/oP6Jv
Thanks in Advance for the help

答:
Because & is a special/reserved character for the shell (similar to space), you need to escape it by either:

Preceding it with a backslash (svn delete --force PlayDate/Model/Cell\ Classes/Places\&FavoritesCell)

Wrap the whole path in single quotes ('svn delete --force PlayDate/Model/Cell\ Classes/Places&FavoritesCell')

See also https://unix.stackexchange.com/a/69147

A third option would be to delete the item from the repository by URL instead. To do that, you'd need to URLEncode the spaces and ampersand(s) in the name, or wrap the URL in single quotes as above. Then run svn update to sync that change to your working copy and delete the now-"orphaned" file locally via Finder or normal bash commands.


问:
If I have an array in excel like (1,1,0,0,0,1,0,0) a
If I have an array in excel like

```<code>A   B   C   D   E   F   G   H

1   1   0   0   0   1   0   0
</code>```

and I want to check the condition that IF even one 1 exists I want to get output as BUY, and if all are 0, then not buy. Can you please tell  me how to get this? Thanks in advance.

答:
Try this

=IF(COUNTIF(A1:H1,1)>0,"BUY","Remaind")

Body:
If I have an array in excel like

A   B   C   D   E   F   G   H

1   1   0   0   0   1   0   0

and I want to check the condition that IF even one 1 exists I want to get output as BUY, and if all are 0, then not buy. Can you please tell  me how to get this? Thanks in advance.


问:
Splitting a SAS dataset into mutual-exclusive by row in parallel?
There is SO question on split a large dataset into smaller one but with the advent of proc ds2 there must a way to do this using threads?

I have written the below data step to split a dataset into &chunks. chunks. I tried to write the same in proc ds but it just fails. I am quite new to proc ds2 so a simple explanation for someone with good understanding of data step would be ideal.

Data stepcode

```<code>%macro output_chunks(in, out, by, chunks);
data %do i = 1 %to &chunks.;
    &out.&i.(compress=char drop = i)
    %end;
;
    set &in.;
    by &by.;
    retain i 0;
    if first.&by. then do;
        i = i + 1;
        if i = &chunks.+1 then i = 1;
    end;

    %do i = 1 %to &chunks.;
        if i = &i. then do;
            output  &out.&i.;
        end;
    %end;
run;
%mend;
</code>```

proc ds2 code

```<code>proc ds2;
  thread split/overwrite=yes;
    method run();
      set in_data;
      thisThread=_threadid_;
      /* can make below into macro but I can't seem to get it to work */
      if thisThread = 1 then do;
        output ds1;
      end;
      else if thisThread = 2 then do;
        output ds2;
      end;
    end;
    method term();
      put '**Thread' _threadid_ 'processed'  count 'rows:';
    end;
  endthread;
  run;
quit;
</code>```

答:
Example of a User-Defined DS2 package to split a data set using HoH method, the big downside is the inability to name the dataset by the keys without a LOT of fudgery due to very limited utility of variable lists in DS2, as a result I opt for a simpler naming convension:</p>

```<code>data cars;
set sashelp.cars;
run;

proc ds2;

package hashSplit / overwrite=yes;

declare package hash  h  ();
declare package hash  hs ();
declare package hiter hi;

/**
  * create a child multidata hash object
  */
private method mHashSub(varlist k, varlist d) returns package hash;
  hs = _new_ [this] hash();
  hs.keys(k);
  hs.data(d);
  hs.multidata('Y');
  hs.defineDone();
  return hs;
end;

/**
  * constructor, create the parent and child hash objects
  */
method hashSplit(varlist k);
  h = _new_ [this] hash();
  h.keys(k);
  h.definedata('hs');
  h.defineDone();
end;

/**
  * adds key values to parent hash, if necessary
  * adds key values and data values to child hash
  * consilidates the FIND, ADD and nested ADD methods
  */
method add(varlist k, varlist d);
  declare double rc;

  rc = h.find();
  if rc ^= 0 then do;
    hs = mHashSub(k, d);
      h.add();
  end;
  hs.add();
end;

/**
  * outputs the child hashes to data sets with a fixed naming convention
  *
  * SAS needs to add more support for using variable lists with functions/methods besides hash
  */
method output();
  declare double rc;
  declare int i;

  hi = _new_ hiter('h');

  rc = hi.first();
  do i = 1 to h.num_items by 1 while (rc = 0);
    hs.output(catx('_', 'hashSplit', i));
      rc = hi.next();
  end;
end;

endpackage;
run;
quit;

/**
  * example of using the hashSplit package
  */
proc ds2;
data _null_;
varlist k [origin];
varlist d [_all_];
declare package hashSplit split(k);

method run();
  set cars;
  split.add(k, d);
end;

method term();
  split.output();
end;
enddata;
run;
quit;
</code>```

Body:
There is SO question on split a large dataset into smaller one but with the advent of proc ds2 there must a way to do this using threads?

I have written the below data step to split a dataset into &chunks. chunks. I tried to write the same in proc ds but it just fails. I am quite new to proc ds2 so a simple explanation for someone with good understanding of data step would be ideal.

Data stepcode

%macro output_chunks(in, out, by, chunks);
data %do i = 1 %to &chunks.;
    &out.&i.(compress=char drop = i)
    %end;
;
    set &in.;
    by &by.;
    retain i 0;
    if first.&by. then do;
        i = i + 1;
        if i = &chunks.+1 then i = 1;
    end;

    %do i = 1 %to &chunks.;
        if i = &i. then do;
            output  &out.&i.;
        end;
    %end;
run;
%mend;

proc ds2 code

proc ds2;
  thread split/overwrite=yes;
    method run();
      set in_data;
      thisThread=_threadid_;
      /* can make below into macro but I can't seem to get it to work */
      if thisThread = 1 then do;
        output ds1;
      end;
      else if thisThread = 2 then do;
        output ds2;
      end;
    end;
    method term();
      put '**Thread' _threadid_ 'processed'  count 'rows:';
    end;
  endthread;
  run;
quit;

Body:
Example of a User-Defined DS2 package to split a data set using HoH method, the big downside is the inability to name the dataset by the keys without a LOT of fudgery due to very limited utility of variable lists in DS2, as a result I opt for a simpler naming convension:

data cars;
set sashelp.cars;
run;

proc ds2;

package hashSplit / overwrite=yes;

declare package hash  h  ();
declare package hash  hs ();
declare package hiter hi;

/**
  * create a child multidata hash object
  */
private method mHashSub(varlist k, varlist d) returns package hash;
  hs = _new_ [this] hash();
  hs.keys(k);
  hs.data(d);
  hs.multidata('Y');
  hs.defineDone();
  return hs;
end;

/**
  * constructor, create the parent and child hash objects
  */
method hashSplit(varlist k);
  h = _new_ [this] hash();
  h.keys(k);
  h.definedata('hs');
  h.defineDone();
end;

/**
  * adds key values to parent hash, if necessary
  * adds key values and data values to child hash
  * consilidates the FIND, ADD and nested ADD methods
  */
method add(varlist k, varlist d);
  declare double rc;

  rc = h.find();
  if rc ^= 0 then do;
    hs = mHashSub(k, d);
      h.add();
  end;
  hs.add();
end;

/**
  * outputs the child hashes to data sets with a fixed naming convention
  *
  * SAS needs to add more support for using variable lists with functions/methods besides hash
  */
method output();
  declare double rc;
  declare int i;

  hi = _new_ hiter('h');

  rc = hi.first();
  do i = 1 to h.num_items by 1 while (rc = 0);
    hs.output(catx('_', 'hashSplit', i));
      rc = hi.next();
  end;
end;

endpackage;
run;
quit;

/**
  * example of using the hashSplit package
  */
proc ds2;
data _null_;
varlist k [origin];
varlist d [_all_];
declare package hashSplit split(k);

method run();
  set cars;
  split.add(k, d);
end;

method term();
  split.output();
end;
enddata;
run;
quit;


问:
How to import headers recusively in Objective-C
Ok this is probably a silly question but why can I do something like this:

```<code>objectA.h

#import <objectB>
#import <objectC>

objectA.m

#import <ObjectA.h>
</code>```

And in ObjectA.m have access to ObjectB and OBjectC definition ?
It's silly to have to import everything you use in each implementation file.
Am i missing something obvious ?

答:
Rather than importing headers in your .h file you could just use the @class declaration for objects you need to declare in your header file, and then in your .m file #import the header files you need.

I'm not sure if this is what you are asking, though.

This has been discussed in more detail in this SO Question

ContentLicense: CC BY-SA 2.5

Body:
Ok this is probably a silly question but why can I do something like this:

objectA.h

#import <objectB>
#import <objectC>

objectA.m

#import <ObjectA.h>

And in ObjectA.m have access to ObjectB and OBjectC definition ?
It's silly to have to import everything you use in each implementation file.
Am i missing something obvious ?


问:
Separating field into multiple columns XML/Varchar2/SQL
I am working with a database that pulls data in from an application. The data appears as XML in the field, but the datatype is actually varchar2. How do I split the data into columns by the names in the brackets? So end result would be each name in <> would be the column header and the value between the closing and ending brackets would be the row data.

Example:

Column Name: VAL_TXT

```<code>xml:<objects.CollegeInfo>
  <collegeOrgId>0000000000</collegeOrgId>
  <useCollegeOrgId>0000000000</useCollegeOrgId>
  <collegeName>University [City, ST, USA]</collegeName>
  <collegeCountry>USA</collegeCountry>
  <collegeState>ST</collegeState>
  <fromDate>08/15/2004</fromDate>
  <toDate>05/15/2007</toDate>
  <degreeDate>08/15/2008</degreeDate>
  <gpaType>4PT</gpaType>
  <gradePointAverage>3.5</gradePointAverage>
  <enteredDegree>Bachelor's</enteredDegree>
</objects.CollegeInfo>
</code>```

Each row may have different fields in them as well.

Also, this data is stored in an Oracle server, but I am pulling the data in through linked server on MS SQL.

Thanks!

EDIT: I did try the following

```<code>SELECT CAST(a.VAL_TXT as xml).value('(/objects.CollegeInfo/collegeOrgId)[1]','INT') AS col1
from TABLE a;
</code>```

I received the error: Msg 9403, Level 16, State 1, Line 1
XML parsing: line 0, character 0, unrecognized input signature

New EDIT (Second try):

```<code>SELECT *
FROM
    (
       SELECT
          VAL_TXT = CAST(VAL_TXT AS XML)
       FROM
          TABLE
    ) t
    CROSS APPLY
    (
       SELECT
          collegeOrgId = x.n.value('collegeOrgId[1]','varchar(20)')
          ,useCollegeOrgId = x.n.value('useCollegeOrgId[1]','varchar(50)')
          ,collegeName = x.n.value('collegeName[1]','VARCHAR(100)')
          ,collegeCountry = x.n.value('collegeCountry[1]','VARCHAR(20)')
          ,collegeState = x.n.value('collegeState[1]','CHAR(2)')
          ,fromDate = x.n.value('fromDate[1]','varchar(30)')
          ,toDate = x.n.value('toDate[1]','varchar(30)')
          ,degreeDate = x.n.value('degreeDate[1]','varchar(30)')
          ,gpaType = x.n.value('gpaType[1]','VARCHAR(20)')
          ,gradePointAverage = x.n.value('gradePointAverage[1]','DECIMAL(5,3)')
          ,enteredDegree = x.n.value('enteredDegree[1]','VARCHAR(20)')
       FROM
          t.VAL_TXT.nodes ('objects.CollegeInfo') as x(n)
    ) c;
</code>```

Receives error:
Msg 9411, Level 16, State 1, Line 8
XML parsing: line 1, character 10, semicolon expected

答:
```<code>DECLARE @TableWithXMLAsVarchar AS TABLE (XMLasVarchar VARCHAR(MAX))
INSERT INTO @TableWithXMLAsVarchar VALUES ('<objects.CollegeInfo>
  <collegeOrgId>0000000000</collegeOrgId>
  <useCollegeOrgId>0000000000</useCollegeOrgId>
  <collegeName>University [City, ST, USA]</collegeName>
  <collegeCountry>USA</collegeCountry>
  <collegeState>ST</collegeState>
  <fromDate>08/15/2004</fromDate>
  <toDate>05/15/2007</toDate>
  <degreeDate>08/15/2008</degreeDate>
  <gpaType>4PT</gpaType>
  <gradePointAverage>3.5</gradePointAverage>
  <enteredDegree>Bachelor's</enteredDegree>
</objects.CollegeInfo>')

SELECT *
FROM
    (
       SELECT
          XMLColumn = CAST(XMLasVarchar AS XML)
       FROM
          @TableWithXMLAsVarchar
    ) t
    CROSS APPLY
    (
       SELECT
          collegeOrgId = x.n.value('collegeOrgId[1]','INT')
          ,useCollegeOrgId = x.n.value('useCollegeOrgId[1]','INT')
          ,collegeName = x.n.value('collegeName[1]','VARCHAR(100)')
          ,collegeCountry = x.n.value('collegeCountry[1]','VARCHAR(20)')
          ,collegeState = x.n.value('collegeState[1]','CHAR(2)')
          ,fromDate = x.n.value('fromDate[1]','DATE')
          ,toDate = x.n.value('toDate[1]','DATE')
          ,degreeDate = x.n.value('degreeDate[1]','DATE')
          ,gpaType = x.n.value('gpaType[1]','VARCHAR(20)')
          ,gradePointAverage = x.n.value('gradePointAverage[1]','DECIMAL(5,3)')
          ,enteredDegree = x.n.value('enteredDegree[1]','VARCHAR(20)')
       FROM
          t.XMLColumn.nodes ('objects.CollegeInfo') as x(n)
    ) c
</code>```

Basically you kind of had the right idea but instead of selecting the value directly you have to select the value from the nodes.  But because this data is in a table you actually have a little more to do.  First you will have to cast the column as XML but you can't do that in the FROM statement so you can do it via a Common Table Expression [CTE] or an aliased Derived Table.  After that you can CROSS/OUTER APPLY to get all of the columns.

Body:
I am working with a database that pulls data in from an application. The data appears as XML in the field, but the datatype is actually varchar2. How do I split the data into columns by the names in the brackets? So end result would be each name in <> would be the column header and the value between the closing and ending brackets would be the row data.

Example:

Column Name: VAL_TXT

xml:<objects.CollegeInfo>
  <collegeOrgId>0000000000</collegeOrgId>
  <useCollegeOrgId>0000000000</useCollegeOrgId>
  <collegeName>University [City, ST, USA]</collegeName>
  <collegeCountry>USA</collegeCountry>
  <collegeState>ST</collegeState>
  <fromDate>08/15/2004</fromDate>
  <toDate>05/15/2007</toDate>
  <degreeDate>08/15/2008</degreeDate>
  <gpaType>4PT</gpaType>
  <gradePointAverage>3.5</gradePointAverage>
  <enteredDegree>Bachelor's</enteredDegree>
</objects.CollegeInfo>

Each row may have different fields in them as well.

Also, this data is stored in an Oracle server, but I am pulling the data in through linked server on MS SQL.

Thanks!

EDIT: I did try the following

SELECT CAST(a.VAL_TXT as xml).value('(/objects.CollegeInfo/collegeOrgId)[1]','INT') AS col1
from TABLE a;

I received the error: Msg 9403, Level 16, State 1, Line 1
XML parsing: line 0, character 0, unrecognized input signature

New EDIT (Second try):

SELECT *
FROM
    (
       SELECT
          VAL_TXT = CAST(VAL_TXT AS XML)
       FROM
          TABLE
    ) t
    CROSS APPLY
    (
       SELECT
          collegeOrgId = x.n.value('collegeOrgId[1]','varchar(20)')
          ,useCollegeOrgId = x.n.value('useCollegeOrgId[1]','varchar(50)')
          ,collegeName = x.n.value('collegeName[1]','VARCHAR(100)')
          ,collegeCountry = x.n.value('collegeCountry[1]','VARCHAR(20)')
          ,collegeState = x.n.value('collegeState[1]','CHAR(2)')
          ,fromDate = x.n.value('fromDate[1]','varchar(30)')
          ,toDate = x.n.value('toDate[1]','varchar(30)')
          ,degreeDate = x.n.value('degreeDate[1]','varchar(30)')
          ,gpaType = x.n.value('gpaType[1]','VARCHAR(20)')
          ,gradePointAverage = x.n.value('gradePointAverage[1]','DECIMAL(5,3)')
          ,enteredDegree = x.n.value('enteredDegree[1]','VARCHAR(20)')
       FROM
          t.VAL_TXT.nodes ('objects.CollegeInfo') as x(n)
    ) c;

Receives error:
Msg 9411, Level 16, State 1, Line 8
XML parsing: line 1, character 10, semicolon expected

Body:
DECLARE @TableWithXMLAsVarchar AS TABLE (XMLasVarchar VARCHAR(MAX))
INSERT INTO @TableWithXMLAsVarchar VALUES ('<objects.CollegeInfo>
  <collegeOrgId>0000000000</collegeOrgId>
  <useCollegeOrgId>0000000000</useCollegeOrgId>
  <collegeName>University [City, ST, USA]</collegeName>
  <collegeCountry>USA</collegeCountry>
  <collegeState>ST</collegeState>
  <fromDate>08/15/2004</fromDate>
  <toDate>05/15/2007</toDate>
  <degreeDate>08/15/2008</degreeDate>
  <gpaType>4PT</gpaType>
  <gradePointAverage>3.5</gradePointAverage>
  <enteredDegree>Bachelor&apos;s</enteredDegree>
</objects.CollegeInfo>')

SELECT *
FROM
    (
       SELECT
          XMLColumn = CAST(XMLasVarchar AS XML)
       FROM
          @TableWithXMLAsVarchar
    ) t
    CROSS APPLY
    (
       SELECT
          collegeOrgId = x.n.value('collegeOrgId[1]','INT')
          ,useCollegeOrgId = x.n.value('useCollegeOrgId[1]','INT')
          ,collegeName = x.n.value('collegeName[1]','VARCHAR(100)')
          ,collegeCountry = x.n.value('collegeCountry[1]','VARCHAR(20)')
          ,collegeState = x.n.value('collegeState[1]','CHAR(2)')
          ,fromDate = x.n.value('fromDate[1]','DATE')
          ,toDate = x.n.value('toDate[1]','DATE')
          ,degreeDate = x.n.value('degreeDate[1]','DATE')
          ,gpaType = x.n.value('gpaType[1]','VARCHAR(20)')
          ,gradePointAverage = x.n.value('gradePointAverage[1]','DECIMAL(5,3)')
          ,enteredDegree = x.n.value('enteredDegree[1]','VARCHAR(20)')
       FROM
          t.XMLColumn.nodes ('objects.CollegeInfo') as x(n)
    ) c

Basically you kind of had the right idea but instead of selecting the value directly you have to select the value from the nodes.  But because this data is in a table you actually have a little more to do.  First you will have to cast the column as XML but you can't do that in the FROM statement so you can do it via a Common Table Expression [CTE] or an aliased Derived Table.  After that you can CROSS/OUTER APPLY to get all of the columns.


问:
Error with Jenkins Pipeline spinning up multiple docker containers for cucumber tests, one feature file per container
We have been stuck with this problem for a week now though we have been working with pipelines for past few months.  Our goal is to spin-up as many containers as many feature files in our cucumber test suite and run those tests in parallel (one per container). Here is the error we are getting with the pipeline code below:

java.lang.UnsupportedOperationException: Calling public static
  java.util.List
  org.codehaus.groovy.runtime.DefaultGroovyMethods.each(java.util.List,groovy.lang.Closure)
  on a CPS-transformed closure is not yet supported (JENKINS-26481);
  encapsulate in a @NonCPS method, or use Java-style loops

pipeline code:

```<code>def cucumberTestImage
pipeline {
    agent any
    options {
         echo "options stuff"
    }

  stages {
    stage('Build & Deploy'){
            steps {
        parallel (
                SPA: {
            script {
                  echo "deploying SPA app"
                }
              }
            }
                    echo 'SPA JOB COMPLETED!!'
          },
          Tests: {
            script {
              }
              //building docker image name cucumberTestImage

            }
          }
        )
      }
    }

     stage('Test') {
     steps {
         script {
            def tests = [:]
            getFeatures().each {stage -> tests[stage] = {
                    cucumberTestImage.inside{sh "echo ${stage}"}
                }}
            parallel tests;
        }
     }
    }

  }
}

@NonCPS
def getFeatures() {
            return sh(script: 'cd testfolder && find features -type f -name \'*.feature\'', returnStdout: true).tokenize()
    }
</code>```

答:
As my original issue is resolved and i was able to run the jenkins pipeline twice successfully, all of sudden the other issue popped-up without any code change done by me.. weird!! The issue is that variable inside the dockerimage.inside block holds the same value for all parallel runs. .I don't know why its happening.. it doesn't make any sense. The below code is in question!</p>

```<code>stage('Test') {
     steps {
         script {
            def tests = [:]
            def features = getFeatures()
            for(def stage: features) {
               tests[stage] = {cucumberTestImage.inside{
                   sh "echo running test --- ${stage}"
                   //sh "cd /app && ./bin/cucumber ${stage}"
               }}}
             parallel tests;
        }
     }
    }

def getFeatures() {
            return sh(script: 'cd frameworkfolder && find features -type f -name \'*.feature\'', returnStdout: true).tokenize()
    }
</code>```

Body:
We have been stuck with this problem for a week now though we have been working with pipelines for past few months.  Our goal is to spin-up as many containers as many feature files in our cucumber test suite and run those tests in parallel (one per container). Here is the error we are getting with the pipeline code below:

java.lang.UnsupportedOperationException: Calling public static
  java.util.List
  org.codehaus.groovy.runtime.DefaultGroovyMethods.each(java.util.List,groovy.lang.Closure)
  on a CPS-transformed closure is not yet supported (JENKINS-26481);
  encapsulate in a @NonCPS method, or use Java-style loops

pipeline code:

def cucumberTestImage
pipeline {
    agent any
    options {
         echo "options stuff"
    }

  stages {
    stage('Build & Deploy'){
            steps {
        parallel (
                SPA: {
            script {
                  echo "deploying SPA app"
                }
              }
            }
                    echo 'SPA JOB COMPLETED!!'
          },
          Tests: {
            script {
              }
              //building docker image name cucumberTestImage

            }
          }
        )
      }
    }

     stage('Test') {
     steps {
         script {
            def tests = [:]
            getFeatures().each {stage -> tests[stage] = {
                    cucumberTestImage.inside{sh "echo ${stage}"}
                }}
            parallel tests;
        }
     }
    }

  }
}

@NonCPS
def getFeatures() {
            return sh(script: 'cd testfolder && find features -type f -name \'*.feature\'', returnStdout: true).tokenize()
    }

Body:
As my original issue is resolved and i was able to run the jenkins pipeline twice successfully, all of sudden the other issue popped-up without any code change done by me.. weird!! The issue is that variable inside the dockerimage.inside block holds the same value for all parallel runs. .I don't know why its happening.. it doesn't make any sense. The below code is in question!

stage('Test') {
     steps {
         script {
            def tests = [:]
            def features = getFeatures()
            for(def stage: features) {
               tests[stage] = {cucumberTestImage.inside{
                   sh "echo running test --- ${stage}"
                   //sh "cd /app && ./bin/cucumber ${stage}"
               }}}
             parallel tests;
        }
     }
    }

def getFeatures() {
            return sh(script: 'cd frameworkfolder && find features -type f -name \'*.feature\'', returnStdout: true).tokenize()
    }


问:
How can I query for embedded rows? Do I need Postgres JSON?
In my application, a user can belong to many groups, and each group can have many members.

I want to issue a query that, based on a user ID, will return all the groups that user belongs to, and the list of members for each group. Something that would let me build a response like this:

```<code>{
    "user_id": 405,
    "user_name": "foobar",
    "groups": [
        {
            "name": "Tomato Club",
            "members": [
                {
                    "user_id": 408,
                    "user_name": "barry"
                },
                {
                    "user_id": 410,
                    "user_name": "sarah"
                }
            ]
        }
    ]
}
</code>```

My problem is that I have no idea how to do this in only one query, or even if such a thing is possible. I'd really appreciate any tips about what to research.

Here's how my schema looks:

users

```<code>id | name
---|-----
 1 | Dave
 2 | Laura
</code>```

groups

```<code>id | name
---|--------
 1 | Tomato Club
 2 | Watermelon Club
</code>```

groups_users_link

```<code>user_id | group_id
--------|----------
   1    |   2
   2    |   2
   5    |   1
   5    |   3
</code>```

答:
That sort of relational structure makes it really easy to get all users in a group:

```<code>SELECT * FROM groups
  LEFT JOIN groups_users_link ON groups_users_link.group_id=groups.id
  LEFT JOIN users ON groups_users_link.user_id=users.id
</code>```

You can add WHERE groups.id=2 to narrow those results down to a single group.

Example on SQL Fiddle.

To do this all from the top with a single user in mind it gets a bit convoluted, but the same pattern applies:

```<code>SELECT * FROM users
  LEFT JOIN groups_users_link ON groups_users_link.user_id=users.id
  LEFT JOIN groups ON groups.id=groups_users_link.group_id
  LEFT JOIN groups_users_link AS gul_sub ON gul_sub.group_id=groups.id
  LEFT JOIN users AS group_users ON gul_sub.user_id=group_users.id
  WHERE users.id=5 AND group_users.id!=users.id
</code>```

Which you can see here.

Body:
In my application, a user can belong to many groups, and each group can have many members.

I want to issue a query that, based on a user ID, will return all the groups that user belongs to, and the list of members for each group. Something that would let me build a response like this:

{
    "user_id": 405,
    "user_name": "foobar",
    "groups": [
        {
            "name": "Tomato Club",
            "members": [
                {
                    "user_id": 408,
                    "user_name": "barry"
                },
                {
                    "user_id": 410,
                    "user_name": "sarah"
                }
            ]
        }
    ]
}

My problem is that I have no idea how to do this in only one query, or even if such a thing is possible. I'd really appreciate any tips about what to research.

Here's how my schema looks:

users

id | name
---|-----
 1 | Dave
 2 | Laura

groups

id | name
---|--------
 1 | Tomato Club
 2 | Watermelon Club

groups_users_link

user_id | group_id
--------|----------
   1    |   2
   2    |   2
   5    |   1
   5    |   3

Body:
That sort of relational structure makes it really easy to get all users in a group:

SELECT * FROM groups
  LEFT JOIN groups_users_link ON groups_users_link.group_id=groups.id
  LEFT JOIN users ON groups_users_link.user_id=users.id

You can add WHERE groups.id=2 to narrow those results down to a single group.

Example on SQL Fiddle.

To do this all from the top with a single user in mind it gets a bit convoluted, but the same pattern applies:

SELECT * FROM users
  LEFT JOIN groups_users_link ON groups_users_link.user_id=users.id
  LEFT JOIN groups ON groups.id=groups_users_link.group_id
  LEFT JOIN groups_users_link AS gul_sub ON gul_sub.group_id=groups.id
  LEFT JOIN users AS group_users ON gul_sub.user_id=group_users.id
  WHERE users.id=5 AND group_users.id!=users.id

Which you can see here.


问:
Empty 'folder' not removed in GCS
When I delete through the Console all files from a "folder" in a bucket, that folder is gone too since there is no such thing as directories - the whole path after the bucket is the key.

However when I move (copy & delete method) programmatically these files through REST API, the folder remains, empty. I must therefore write additional logic to check for these and remove explicitly.

Isn't that a bug in the REST API handling ? I had expected the same behavior regardless of the method used.

答:
Turns out that you can safely remove all object ending with / if you don't need them once empty. "Content" will not be deleted.

If you are using Google Console, you must create a folder before uploading to it. That folder is therefore an explicit object that will remain even if empty. Same behavior apparently when uploading with tools like Cyberduck.

But if you upload the file using REST API and its full path i.e. bucket/folder/file, the folder is implicit visually but it's not getting created as such. So when removing the file, there is no folder left behind since it wasn't there in the first place.

Since the expected behavior for my use case is to auto-remove empty folders, I just have a pre-processing routine that deletes all blobs ending with /

Title: Empty 'folder' not removed in GCS


问:
CSS div height fill remaing space and scroll if reach max height of screen
I have searched everywhere on the web for this but i couldn't find anyone that really fits me or even work. The answers that I found are very old and/or are not 100% what I am looking for so I hope if anyone can help me with this.

I use bootstrap 4 in my application so if it can be done with bootstrap then yeay but pure css is ok as well.

What I try to do is having 4 div side by side

example:

```<code><div class="row">
    <div class="col">
        <h1>Item 1</h1>
    </div>

    <div class="col">
        <h1>Item 2</h1>
    </div>
    <div class="col">
        <h1>Item 2</h1>
    </div>
    <div class="col">
        <h1>Item 2</h1>
    </div>
</div>
</code>```

This works because of bootstrap 4 but now I also want the div height will extend till the bottom of the screen  and if the content of that div is longer then the screen height, then it should scroll (inside the div).

I was thinking about flex boxes but I couldn't get it to work.

答:
Since you use bootsrap 4 , flex is already involved.

If the idea is to let the row grow till 100% height of the viewport, then show a scroll bar within the child that will grow past that value, you need to create a custom class involving max-height and overflow:

custom class example

```<code><div class="row h100-scroll  ">
</code>```

selectors and rules to uses to start with

```<code>.h100-scroll .col {/* to scroll col individually*/
  max-height: 100vh;
  overflow: auto;
}
</code>```

or

```<code>.h100-scroll  {/* to scroll the row itself */
  max-height: 100vh;
  overflow: auto;
}
</code>```

demo below, run snippet and hover text on first col

.h100-scroll .col {
  max-height: 100vh;
  overflow: auto;
}

.col br {display:none;}
p:hover br {display:block;}
body {
  margin: 0 1em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css" rel="stylesheet" />
<div class="row h100-scroll  ">
  <div class="col">
    <h1>Item 1</h1>
    <p>hover me show the br and add a scrollbar<br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> .
  </div>

  <div class="col">
    <h1>Item 2</h1>
  </div>
  <div class="col">
    <h1>Item 2</h1>
  </div>
  <div class="col">
    <h1>Item 2</h1>
  </div>
</div></code>```

Body:
I have searched everywhere on the web for this but i couldn't find anyone that really fits me or even work. The answers that I found are very old and/or are not 100% what I am looking for so I hope if anyone can help me with this.

I use bootstrap 4 in my application so if it can be done with bootstrap then yeay but pure css is ok as well.

What I try to do is having 4 div side by side

example:

Item 1

Item 2

Item 2

Item 2

This works because of bootstrap 4 but now I also want the div height will extend till the bottom of the screen  and if the content of that div is longer then the screen height, then it should scroll (inside the div).

I was thinking about flex boxes but I couldn't get it to work.

Body:
Since you use bootsrap 4 , flex is already involved.

If the idea is to let the row grow till 100% height of the viewport, then show a scroll bar within the child that will grow past that value, you need to create a custom class involving max-height and overflow:

custom class example

<div class="row h100-scroll  ">

selectors and rules to uses to start with

.h100-scroll .col {/* to scroll col individually*/
  max-height: 100vh;
  overflow: auto;
}

or

.h100-scroll  {/* to scroll the row itself */
  max-height: 100vh;
  overflow: auto;
}

demo below, run snippet and hover text on first col

.h100-scroll .col {
  max-height: 100vh;
  overflow: auto;
}

.col br {display:none;}
p:hover br {display:block;}
body {
  margin: 0 1em;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta.2/css/bootstrap-grid.css" rel="stylesheet" />
<div class="row h100-scroll  ">
  <div class="col">
    <h1>Item 1</h1>
    <p>hover me show the br and add a scrollbar<br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> . <br/> .<br/> .
  </div>

  <div class="col">
    <h1>Item 2</h1>
  </div>
  <div class="col">
    <h1>Item 2</h1>
  </div>
  <div class="col">
    <h1>Item 2</h1>
  </div>
</div>


问:
how to add 4 image view to flipper in android?
i want to add 4 imageviews to flipper at a time.Please provide some sample code

my code is

```<code>    final ImageView imageview=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img1);

    final ImageView imageview1=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img2);

    final ImageView imageview2=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img3);

    final ImageView imageview3=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img4);
</code>```

I want to add these images to flipper on by one.

答:
You want each flipper to contain 4 imageviews?

Create a .xml layout with four imageviews, inflate the view, fetch your imageviews by findViewById and set their source-value then add the inflated view to your flipper with

```<code>myFlipper.addView(myInflatedView)
</code>```

Body:
i want to add 4 imageviews to flipper at a time.Please provide some sample code

my code is

    final ImageView imageview=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img1);

    final ImageView imageview1=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img2);

    final ImageView imageview2=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img3);

    final ImageView imageview3=new ImageView(this);
    imageview.setBackgroundResource(R.drawable.img4);

I want to add these images to flipper on by one.

Body:
You want each flipper to contain 4 imageviews?

Create a .xml layout with four imageviews, inflate the view, fetch your imageviews by findViewById and set their source-value then add the inflated view to your flipper with

myFlipper.addView(myInflatedView)


问:
Firebase: Check for existing before adding
I am adding data with generated ID's but am trying to group "Authors".

I have a script that adds certain people to this every day based on a few formulas. There is no way for me to know who will be added on any given day so I am forced to structure the database by have it generate the keys on submission (push) and then locating the author key and finding other keys with the same value.

The issue I'm having is checking to see if a value is present before adding a new record. One of the key values is "URL". I have tried to write something to check each record for that value, but it seems to repeat and write to the database regardless of what the value is even though I can properly detect the duplicate.

```<code>function CheckDupes(newUrl, author, title, score, url, certified, date){
  var stories = [];
  var duped = "false";

  var leadsRef = database.ref().child("Authors").once("value").then(function(authorSnapshot)
  {
    authorSnapshot.forEach(function(child) {
        stories.push(child.val());
      });
    for(var i = 0; i < stories.length; i++)
    {
      console.log("Story: " + stories[i].url);
      if(stories[i].url == newUrl)
      {
        console.log("Duplicate - " + stories[i].url);
        duped = "true";
        alert("Story Exists!");
        break;
      }
    }
  });

  console.log(duped);
  if(duped == "false")
  {
    firebase.database().ref('Authors/').push({
      author: author,
      title: title,
      score: score,
      url: url,
      certified: certified,
      date: date
    });
    alert("Story has been added!");
  }
</code>```

This is what I currently have. It will find the duplicate but it adds to the database regardless of whether or not it finds one. I've moved the check outside of the foreach loop, but then it doesn't store anything at all.

答:
```<code>function CheckDupes(newUrl, author, title, score, url, certified, date){
  var stories = [];
  var duped = "false";
  var leadsRef = database.ref().child("Authors").once("value").then(function(authorSnapshot)
  {
    authorSnapshot.forEach(function(child) {
        stories.push(child.val());
        count++;
      });
      for(var i = 0; i < stories.length; i++)
      {
        if(stories[i].url == newUrl)
        {
          duped = "true";
          alert("Story Exists!");
          return;
          break;
        }
      }
      if(duped == "false")
      {
        firebase.database().ref('Authors/').push({
          author: author,
          title: title,
          score: score,
          url: url,
          certified: certified,
          date: date
        });
        alert("Story has been added!");
      }
  });
</code>```

Needed everything within the authorSnapshot function. Silly mistake.

Body:
I am adding data with generated ID's but am trying to group "Authors".

I have a script that adds certain people to this every day based on a few formulas. There is no way for me to know who will be added on any given day so I am forced to structure the database by have it generate the keys on submission (push) and then locating the author key and finding other keys with the same value.

The issue I'm having is checking to see if a value is present before adding a new record. One of the key values is "URL". I have tried to write something to check each record for that value, but it seems to repeat and write to the database regardless of what the value is even though I can properly detect the duplicate.

function CheckDupes(newUrl, author, title, score, url, certified, date){
  var stories = [];
  var duped = "false";

  var leadsRef = database.ref().child("Authors").once("value").then(function(authorSnapshot)
  {
    authorSnapshot.forEach(function(child) {
        stories.push(child.val());
      });
    for(var i = 0; i < stories.length; i++)
    {
      console.log("Story: " + stories[i].url);
      if(stories[i].url == newUrl)
      {
        console.log("Duplicate - " + stories[i].url);
        duped = "true";
        alert("Story Exists!");
        break;
      }
    }
  });

  console.log(duped);
  if(duped == "false")
  {
    firebase.database().ref('Authors/').push({
      author: author,
      title: title,
      score: score,
      url: url,
      certified: certified,
      date: date
    });
    alert("Story has been added!");
  }

This is what I currently have. It will find the duplicate but it adds to the database regardless of whether or not it finds one. I've moved the check outside of the foreach loop, but then it doesn't store anything at all.

Body:
function CheckDupes(newUrl, author, title, score, url, certified, date){
  var stories = [];
  var duped = "false";
  var leadsRef = database.ref().child("Authors").once("value").then(function(authorSnapshot)
  {
    authorSnapshot.forEach(function(child) {
        stories.push(child.val());
        count++;
      });
      for(var i = 0; i < stories.length; i++)
      {
        if(stories[i].url == newUrl)
        {
          duped = "true";
          alert("Story Exists!");
          return;
          break;
        }
      }
      if(duped == "false")
      {
        firebase.database().ref('Authors/').push({
          author: author,
          title: title,
          score: score,
          url: url,
          certified: certified,
          date: date
        });
        alert("Story has been added!");
      }
  });

Needed everything within the authorSnapshot function. Silly mistake.


问:
Difference between RxJava API and the Java 9 Flow API
It seems on every iteration of Java for the last few major releases, there are consistently new ways to manage concurrent tasks.

In Java 9, we have the Flow API which resembles the Flowable API of RxJava but with Java 9 has a much simpler set of classes and interfaces.

Java 9

Has a Flow.Publisher, Flow.Subscriber, Flow.Processor, Flow.Subscription, and SubmissionPublisher, and that's about it.

RxJava

Has whole packages of Flow API-like classes, i.e. io.reactivex.flowables, io.reactivex.subscribers, io.reactivex.processors, io.reactivex.observers, and io.reactivex.observables which seem to do something similar.

What are the main differences between these two libraries? Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?

答:
What are the main differences between these two libraries?

The Java 9 Flow API is not a standalone library but a component of the Java Standard Edition library and consists of 4 interfaces adopted from the Reactive Streams specification established in early 2015. In theory, it's inclusion can enable in-JDK specific usages, such as the incubating HttpClient, maybe the planned Async Database Connection in parts, and of course SubmissionPublisher.

RxJava is Java library that uses the ReactiveX style API design to provide a rich set of operators over reactive (push) dataflows. Version 2, through Flowable and various XxxProcessors, implements the Reactive Streams API which allows instances of Flowable to be consumed by other compatible libraries and in turn one can wrap any Publisher into a Flowable to consume those and compose the rich set of operators with them.

So the Reactive Streams API is the minimal interface specification and RxJava 2 is one implementation of it, plus RxJava declares a large set of additional methods to form a rich and fluent API of its own.

RxJava 1 inspired, among other sources, the Reactive Streams specification but couldn't capitalize on it (had to remain compatible). RxJava 2, being a full rewrite and a separate main version, could embrace and use the Reactive Streams specification (and even expand upon it internally, thanks to the Rsc project) and has been released almost a year before Java 9. In addition, it was decided both v1 and v2 keeps supporting Java 6 and thus a lot of Android runtimes. Therefore it couldn't capitalize directly on the Flow API provided now by Java 9 directly but only through a bridge. Such bridge is required by and/or provided in other Reactive Streams-based libraries too.

RxJava 3 may target the Java 9 Flow API but this hasn't been decided yet and depending on what features the subsequent Java versions bring (i.e., value types), we may not have v3 within a year or so.

Till then, there is a prototype library called Reactive4JavaFlow which does implement the Flow API and offers a ReactiveX style rich fluent API over it.

Why would someone use the Java 9 Flow library over the much more diverse RxJava library or vice versa?

The Flow API is an interoperation specification and not an end-user API. Normally, you wouldn't use it directly but to pass flows around to various implementations of it. When JEP 266 was discussed, the authors didn't find any existing library's API good enough to have something default with the Flow API (unlike the rich java.util.Stream). Therefore, it was decided that users will have to rely on 3rd party implementations for now.

You have to wait for existing reactive libraries to support the Flow API natively,  through their own bridge implementation or new libraries to be implemented.

Providing a rich set of operators over the Flow API is only reason a library would implement it. Datasource vendors (i.e., reactive database drivers, network libraries) can start implementing their own data accessors via the Flow API and rely on the rich libraries to wrap those and provide the transformation and coordination for them without forcing everybody to implement all sorts of these operators.

Consequently, a better question is, should you start using the Flow API-based interoperation now or stick to Reactive Streams?

If you need working and reliable solutions relatively soon, I suggest you stick with the Reactive Streams ecosystem for now. If you have plenty of time or you want to explore things, you could start using the Flow API.