问:
Are compilers allowed to evaluate tautologies in static assert
Providing a static_assert in templates are often helpful. In the case where a template shouldn't be instantiated in a certain way at all, I often do this

```<code>template<typename T, typename = void>
struct S
{
    static_assert(false, "Unconditional error");
    static_assert(sizeof(T) != sizeof(T), "Error on instantiation");
};

template<typename T>
struct S<T, std::enable_if_t<std::is_integral_v<T>>>
{
    // ...
};
</code>```

The first static_assert will fail instantly, even without an instantiation of S, while the second will succeed if no instantiations will result in the primary template.

The second static_assert is obviously a tautology, but it "depends" on T such that the intended effect is achieved. But is this guaranteed? Are compilers allowed to evaluate these tautologies?

答:
The relevant rule is [temp.res]/8:

Knowing which names are type names allows the syntax of every template to be checked. The program is ill-formed, no diagnostic required, if:

no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or

[...]

Both static_asserts in the example cause the program to be ill-formed, but no diagnostic is required. Compilers are certainly allowed to evaluate arbitrarily complex expressions to attempt to prove that no valid specialization could be generated, but they are not required that they do so. false is certainly an easy case to immediately verify, so it's not surprising that it is diagnosed.

A common approach to the desire to always issue a diagnostic is:

```<code>// never specialize me!
template <typename T>
struct always_false : std::false_type { };

template <typename T>
constexpr bool always_false_v = always_false<T>::value;

template<typename T, typename = void>
struct S {
    static_assert(always_false_v<T>, "Unconditional error");
};
</code>```

always_false could hypothetically be specialized on a particular T to yield true_type, so there could hypothetically be a valid specialization S<T>. But don't let anybody actually do that.

Body:
Providing a static_assert in templates are often helpful. In the case where a template shouldn't be instantiated in a certain way at all, I often do this

template<typename T, typename = void>
struct S
{
    static_assert(false, "Unconditional error");
    static_assert(sizeof(T) != sizeof(T), "Error on instantiation");
};

template<typename T>
struct S<T, std::enable_if_t<std::is_integral_v<T>>>
{
    // ...
};

The first static_assert will fail instantly, even without an instantiation of S, while the second will succeed if no instantiations will result in the primary template.

The second static_assert is obviously a tautology, but it "depends" on T such that the intended effect is achieved. But is this guaranteed? Are compilers allowed to evaluate these tautologies?

Body:
The relevant rule is [temp.res]/8:

Knowing which names are type names allows the syntax of every template to be checked. The program is ill-formed, no diagnostic required, if:

no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or

[...]

Both static_asserts in the example cause the program to be ill-formed, but no diagnostic is required. Compilers are certainly allowed to evaluate arbitrarily complex expressions to attempt to prove that no valid specialization could be generated, but they are not required that they do so. false is certainly an easy case to immediately verify, so it's not surprising that it is diagnosed.

A common approach to the desire to always issue a diagnostic is:

// never specialize me!
template <typename T>
struct always_false : std::false_type { };

template <typename T>
constexpr bool always_false_v = always_false<T>::value;

template<typename T, typename = void>
struct S {
    static_assert(always_false_v<T>, "Unconditional error");
};

always_false could hypothetically be specialized on a particular T to yield true_type, so there could hypothetically be a valid specialization S<T>. But don't let anybody actually do that.


来源: stackexchange

问:
Admin Controllers in Merb
How does one do namespaced controllers in Merb, for instance to create an admin section to the site? In Rails one would use Admin::CategoriesController, is this similar in Merb or is this another recommended way of doing it?</p>

答:
The above answer is correct, but for what it's worth, I had a hard time trying to make use of the new route with link_to in my views.

I ended up getting this to work:

```<code><%= link_to("Categories Admin", resource(:admin, :categories) %>
</code>```

OwnerDisplayName: Laz

ContentLicense: CC BY-SA 2.5

Title: Admin Controllers in Merb

Body:
The above answer is correct, but for what it's worth, I had a hard time trying to make use of the new route with link_to in my views.

I ended up getting this to work:

<%= link_to("Categories Admin", resource(:admin, :categories) %>

OwnerDisplayName: claytonlz


问:
Using an external jar in a Scala.js project
I have a library in a jar that I would like to use in a Scala.js project.
Is any jar usable as a dependency of a Scala.js project?
Or should the jar have been compiled in a specific way?</p>

答:
The jar must have been compiled by the Scala.js compiler, so that it contains the .sjsir files, necessary for compilation to JavaScript. If it was compiled by the regular Scala/JVM compiler, you will not be able to use it in a Scala.js project (unless it only contains macros).

See also How to add lib with jars to shared folder?

ContentLicense: CC BY-SA 3.0


问:
ASP.NET: Repeater does not work for me
My C# Code

```<code>public partial class Message : System.Web.UI.Page
{
    String strconn = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        members();
    }

    public void members()
    {
        SqlConnection con = new SqlConnection(strconn);
        con.Open();
        try
        {
            string str = "Select Users.Username,Users.Name,ProfilePic.Pathh From Users FULL OUTER JOIN ProfilePic ON Users.username = ProfilePic.Username ORDER BY Users.Sno";
            SqlCommand cmd = new SqlCommand(str,con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            repMembers.DataSource = ds;
            repMembers.DataBind();
            GridView1.DataSource = ds;
            GridView1.DataBind();
            cmd.Dispose();
            con.Close();
        }
        catch(Exception ex) {
            lbMembers.Text = ex.ToString();
        }
    }
}
</code>```

And My HTML Code

```<code>   <asp:Repeater ID="repMembers" runat="server" >
                           <asp:ItemTemplate >
                               <div style="width:100%; border-bottom:#ffffff 2px solid;"> <asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="60px" Height="60px"/> <asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label><br/><asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label><br/></div>
                           </asp:ItemTemplate>
                        </asp:Repeater>
</code>```

My Table is absolutely correct and is working, i checked it with Grid View. It gives me the "Name","Username", and "Path" Stored.
I checked it with SQL query and displayed it in grid view.

This is the Photo of my table,it is the combination of two tables

答:
Use ItemTemplate instead of asp:ItemTemplate. There's also a typo with the word "Pathh", does this solve your issue?

```<code><ItemTemplate >
    <div style="width:100%; border-bottom:#ffffff 2px solid;">
        <asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Path") %>' width="60px" Height="60px"/>

        <asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label>
        <br/>
        <asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
        <br/>
    </div>
</ItemTemplate>
</code>```

Title: ASP.NET: Repeater does not work for me

Body:
My C# Code

public partial class Message : System.Web.UI.Page
{
    String strconn = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        members();
    }

    public void members()
    {
        SqlConnection con = new SqlConnection(strconn);
        con.Open();
        try
        {
            string str = "Select Users.Username,Users.Name,ProfilePic.Pathh From Users FULL OUTER JOIN ProfilePic ON Users.username = ProfilePic.Username ORDER BY Users.Sno";
            SqlCommand cmd = new SqlCommand(str,con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            repMembers.DataSource = ds;
            repMembers.DataBind();
            GridView1.DataSource = ds;
            GridView1.DataBind();
            cmd.Dispose();
            con.Close();
        }
        catch(Exception ex) {
            lbMembers.Text = ex.ToString();
        }
    }
}

And My HTML Code

   <asp:Repeater ID="repMembers" runat="server" >
                           <asp:ItemTemplate >

 <asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Pathh") %>' width="60px" Height="60px"/> <asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label>
<asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>

                           </asp:ItemTemplate>
                        </asp:Repeater>

My Table is absolutely correct and is working, i checked it with Grid View. It gives me the "Name","Username", and "Path" Stored.
I checked it with SQL query and displayed it in grid view.

This is the Photo of my table,it is the combination of two tables

Body:
Use ItemTemplate instead of asp:ItemTemplate. There's also a typo with the word "Pathh", does this solve your issue?

<ItemTemplate >
    <div style="width:100%; border-bottom:#ffffff 2px solid;">
        <asp:Image ID="Image4" runat="server" ImageUrl='<%#Eval("Path") %>' width="60px" Height="60px"/>
        &nbsp;
        <asp:Label ID="lb" runat="server" Text='<%#Eval("Username") %>'></asp:Label>
        <br/>
        <asp:Label ID="lbname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
        <br/>
    </div>
</ItemTemplate>


问:
What's the correct permissions to write log from a python CLI?

I'm developing python CLI, I want write log file in /var/log/myapp/myapp.log but I don't know What's the correctly permissions that need set to log file in the install, because the CLI can be executed from differents users.

Currently I have this permissions:

```<code>-rw-rw-r-- 1 someone someone 137 dic  4 17:00 /var/log/myapp/myapp.log
</code>```

But when another user execute the CLI show this error:

IOError: [Errno 13] Permission denied: '/var/log/myapp/myapp.log'

I want know what's the correct permissions, user or group to write log in /var/log

答:
There are a few ways to do it.  One way would be to put all the users in a group, set the group of that directory to that group, and set the group write permission on /var/log/myapp.  Then all users in the group will be able to write files to that location.  </p>

<p>You might need to change the group write permission and group of the file you're creating instead, since all users appear to write to the same file.  Be aware however that they may interfere with each other's logs if you all log to the same file.  </p>

Body:
I'm developing python CLI, I want write log file in /var/log/myapp/myapp.log but I don't know What's the correctly permissions that need set to log file in the install, because the CLI can be executed from differents users.

Currently I have this permissions:

-rw-rw-r-- 1 someone someone 137 dic  4 17:00 /var/log/myapp/myapp.log

But when another user execute the CLI show this error:

IOError: [Errno 13] Permission denied: '/var/log/myapp/myapp.log'

I want know what's the correct permissions, user or group to write log in /var/log

Body:
There are a few ways to do it.  One way would be to put all the users in a group, set the group of that directory to that group, and set the group write permission on /var/log/myapp.  Then all users in the group will be able to write files to that location.

You might need to change the group write permission and group of the file you're creating instead, since all users appear to write to the same file.  Be aware however that they may interfere with each other's logs if you all log to the same file.


问:
C linked list problems
I really need your help with my program. I'm a newbie in C and need to create a linked list in my project.

I use xcode on macOS.
My code is here:

```<code>typedef struct person
{
    char name[500];
    char telnum[16];
    char wohnort[500];
    struct person *next;

}person;

person *head=NULL;
void einlesen()
{
    person *p;
    char name[30];
    char telnum[16];
    char wohnort[30];
    //char buff1[15], buff2[15];
    int cnt=0;

    FILE *fp=fopen("Data2.txt", "r");
    if(fp==NULL)
    {
        printf("File konnte nicht geoeffnet werden!\n");
        exit(1);
    }
    while(fscanf(fp," %29[A-z ]\t%s\t%s", &name, &telnum, &wohnort)!=EOF)
    {

        cnt++;

        printf("Datei gefunden!\nDaten:%s, %s, %s\n", name, telnum, wohnort);

        if(head == NULL){
            head = (person*)malloc(sizeof(person));
            strcpy(head->name, name);
            strcpy(head->telnum, telnum);
            strcpy(head->wohnort, wohnort);
            head->next = NULL;
        }
        else{
            p = head;
            while(p->next != NULL)
            {
                p = p->next;
            }

            p->next = (person*)malloc(sizeof(person));
            strcpy(p->next->name,name);
            strcpy(p->next->telnum,telnum);
            strcpy(p->next->wohnort,wohnort);
            p->next->next = NULL;
        }

    }
    printf("Die Daten von %d Personen wurden eingelesen!\n\n", cnt);
    fclose(fp);
}

void addieren()
{   char name[30];
    char telnum[16];
    char wohnort[30];
    person *p = head;

    printf("Bitte den Namen der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", name);
    while(getchar() != '\n');
    printf("\nBitte die Telefunnumer der hinzufuegenden Person eingeben:\n");
    scanf(" %15s", telnum);
    while(getchar() != '\n');
    printf("\nBitte den Wohnort der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", wohnort);
    while(getchar() != '\n');

    if(p==NULL) return;
    while(p->next)
    {
        p=p->next;
    }
    p->next = (person*)malloc(sizeof(person));
    strcpy(p->next->name, name);
    strcpy(p->next->telnum, telnum);
    strcpy(p->next->wohnort, wohnort);
    p->next->next=NULL;
}
</code>```

and i have this in my main function:

```<code>int main()
{
    person *p1=head;

    einlesen();
    addieren();
    while(p1 !=NULL)
    {
        printf("Namen: %s\n", p1->name);
        p1=p1->next;
    }

    return 0;

}
</code>```

It's already read the data from the file and I wanted to add some new records to it and the print to the screen. This returns 0 and doesn't really print the list on the screen.

Later I need to add more functions to my program, like:
-deletefromlist
-modify element
-search in the linked list
-save to file
-and a menue

答:
You are creating a new person inside the function addieren instead of receiving the one you created on the main function. You need to receive it as an argument, something like that

int addieren(person **head) { ... }

And on the main you should make

```<code>addieren(&p1);
</code>```

Notice the double pointer so you can pass the pointer and modify it inside of the function. Also you probably should return an int to confirm either the operation was succesfull or not

Title: C linked list problems

Body:
I really need your help with my program. I'm a newbie in C and need to create a linked list in my project.

I use xcode on macOS.
My code is here:

typedef struct person
{
    char name[500];
    char telnum[16];
    char wohnort[500];
    struct person *next;

}person;

person *head=NULL;
void einlesen()
{
    person *p;
    char name[30];
    char telnum[16];
    char wohnort[30];
    //char buff1[15], buff2[15];
    int cnt=0;

    FILE *fp=fopen("Data2.txt", "r");
    if(fp==NULL)
    {
        printf("File konnte nicht geoeffnet werden!\n");
        exit(1);
    }
    while(fscanf(fp," %29[A-z ]\t%s\t%s", &name, &telnum, &wohnort)!=EOF)
    {

        cnt++;

        printf("Datei gefunden!\nDaten:%s, %s, %s\n", name, telnum, wohnort);

        if(head == NULL){
            head = (person*)malloc(sizeof(person));
            strcpy(head->name, name);
            strcpy(head->telnum, telnum);
            strcpy(head->wohnort, wohnort);
            head->next = NULL;
        }
        else{
            p = head;
            while(p->next != NULL)
            {
                p = p->next;
            }

            p->next = (person*)malloc(sizeof(person));
            strcpy(p->next->name,name);
            strcpy(p->next->telnum,telnum);
            strcpy(p->next->wohnort,wohnort);
            p->next->next = NULL;
        }

    }
    printf("Die Daten von %d Personen wurden eingelesen!\n\n", cnt);
    fclose(fp);
}

void addieren()
{   char name[30];
    char telnum[16];
    char wohnort[30];
    person *p = head;

    printf("Bitte den Namen der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", name);
    while(getchar() != '\n');
    printf("\nBitte die Telefunnumer der hinzufuegenden Person eingeben:\n");
    scanf(" %15s", telnum);
    while(getchar() != '\n');
    printf("\nBitte den Wohnort der hinzufuegenden Person eingeben:\n");
    scanf(" %29s", wohnort);
    while(getchar() != '\n');

    if(p==NULL) return;
    while(p->next)
    {
        p=p->next;
    }
    p->next = (person*)malloc(sizeof(person));
    strcpy(p->next->name, name);
    strcpy(p->next->telnum, telnum);
    strcpy(p->next->wohnort, wohnort);
    p->next->next=NULL;
}

and i have this in my main function:

int main()
{
    person *p1=head;

    einlesen();
    addieren();
    while(p1 !=NULL)
    {
        printf("Namen: %s\n", p1->name);
        p1=p1->next;
    }

    return 0;

}

It's already read the data from the file and I wanted to add some new records to it and the print to the screen. This returns 0 and doesn't really print the list on the screen.

Later I need to add more functions to my program, like:
-deletefromlist
-modify element
-search in the linked list
-save to file
-and a menue

Body:
You are creating a new person inside the function addieren instead of receiving the one you created on the main function. You need to receive it as an argument, something like that

int addieren(person **head) { ... }

And on the main you should make

addieren(&p1);

Notice the double pointer so you can pass the pointer and modify it inside of the function. Also you probably should return an int to confirm either the operation was succesfull or not


问:
Django How can i split string using template tag
Hello I want to know that how can I split string of dictionary values

This is my crawler which is returns dictionary data looks like

```<code>data = {
    {0:'http://..., product name, product price'},
    {1:'http://...2, product name2, product price2'},
    {N:'http://...2, product name2, product price n'}
}
</code>```

I want to split these data by comma
 like,

```<code>for value in data.values():
     href, product_name, product_price = str(value).split(",")
</code>```

in Django

This is my crawler.py

```<code>import requests
from urllib import parse
from bs4 import BeautifulSoup

def spider(item_name):
    url_item_name = parse.quote(item_name.encode('euc-kr'))

    url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name
    resp = requests.get(url)
    resp.raise_for_status()

    resp.encoding='euc-kr'
    plain_text = resp.text

    soup = BeautifulSoup(plain_text, 'lxml')
    mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]})
    #for link in soup.select('div.list_info p.info_tit a') :
    data = {}
    count = -1;
    for link in mytag:
        if(link.find('a')):
            count+=1
            href = link.find('a').get('href')
            product_name = link.find('a').string
            data[count] = str(href) + ", " + str(product_name)
        else:
            product_price = link.string
            if(product_price):
                data[count] = data[count] +", " + str(product_price)

    for value in data.values():
        print(value)
    resp.close()

    return data
</code>```

and this is my views

```<code>def post_shop_list(request):
    posts = spider("product name")
    return render(request, 'blog/post_list.html',{'posts' : posts})
</code>```

and this is my post_list.html

```<code>{% for key, value in posts.items %}
    <div>
        <td>{{key}}</td>
        <p>product name :{{value}}</p>
        <h1><a href=href> </a></h1>
        <p>{{ product_price|linebreaksbr}}</p>
    </div>
{% endfor %}
</code>```

Thank you .. !!

答:
i'd advise against doing these sort of things in templates. you end up having half of your view logic embedded in them.
i suggest doing something like this in your view or better yet your crawler:

```<code>products = []
for key, value in posts.items():
    product = value.split(',')
    # product = [href,name,price]
    product_entry = {
            'key' : key,
            'name' : product[1],
            'href' : product[0],
            'price' : product[2]
    }
    products.append(product_entry)
</code>```

You end up with a nice array of dicts, hand it out to the template and in there you simply iterate over it and read the elements fields.

```<code>{% for item in products %}
    <td>{{ item.key }}</td>
    <p>product name :{{ item.name}}</p>
    <h1><a href={{ item.href }}> </a></h1>
    <p>{{ item.price }}</p>
{% endfor %}
</code>```

Alternatively, create a custom template-tag as described here

Body:
Hello I want to know that how can I split string of dictionary values

This is my crawler which is returns dictionary data looks like

data = {
    {0:'http://..., product name, product price'},
    {1:'http://...2, product name2, product price2'},
    {N:'http://...2, product name2, product price n'}
}

I want to split these data by comma
 like,

for value in data.values():
     href, product_name, product_price = str(value).split(",")

in Django

This is my crawler.py

import requests
from urllib import parse
from bs4 import BeautifulSoup

def spider(item_name):
    url_item_name = parse.quote(item_name.encode('euc-kr'))

    url = 'http://search.11st.co.kr/SearchPrdAction.tmall?method=getTotalSearchSeller&isGnb=Y&prdType=&category=&cmd=&pageSize=&lCtgrNo=&mCtgrNo=&sCtgrNo=&dCtgrNo=&fromACK=recent&semanticFromGNB=&gnbTag=TO&schFrom=&schFrom=&ID=&ctgrNo=&srCtgrNo=&keyword=&adUrl=&adKwdTrcNo=&adPrdNo=&targetTab=T&kwd=' + url_item_name
    resp = requests.get(url)
    resp.raise_for_status()

    resp.encoding='euc-kr'
    plain_text = resp.text

    soup = BeautifulSoup(plain_text, 'lxml')
    mytag = soup.find_all(True, {"class": ["sale_price", "list_info"]})
    #for link in soup.select('div.list_info p.info_tit a') :
    data = {}
    count = -1;
    for link in mytag:
        if(link.find('a')):
            count+=1
            href = link.find('a').get('href')
            product_name = link.find('a').string
            data[count] = str(href) + ", " + str(product_name)
        else:
            product_price = link.string
            if(product_price):
                data[count] = data[count] +", " + str(product_price)

    for value in data.values():
        print(value)
    resp.close()

    return data

and this is my views

def post_shop_list(request):
    posts = spider("product name")
    return render(request, 'blog/post_list.html',{'posts' : posts})

and this is my post_list.html

{% for key, value in posts.items %}

        {{key}}

product name :{{value}}

{{ product_price|linebreaksbr}}

{% endfor %}

Thank you .. !!

Body:
i'd advise against doing these sort of things in templates. you end up having half of your view logic embedded in them.
i suggest doing something like this in your view or better yet your crawler:

products = []
for key, value in posts.items():
    product = value.split(',')
    # product = [href,name,price]
    product_entry = {
            'key' : key,
            'name' : product[1],
            'href' : product[0],
            'price' : product[2]
    }
    products.append(product_entry)

You end up with a nice array of dicts, hand it out to the template and in there you simply iterate over it and read the elements fields.

{% for item in products %}
    <td>{{ item.key }}</td>
    <p>product name :{{ item.name}}</p>
    <h1><a href={{ item.href }}> </a></h1>
    <p>{{ item.price }}</p>
{% endfor %}

Alternatively, create a custom template-tag as described here


问:
Can't populate a jstree with ajax data
I'm using jstree 3.2.1 and am trying to populate it with json data returned from an ajax script.

I've tested the script that produces the json data by accessing the URL, and it's returning valid json:

```<code>[{"id":"5","name":"Sector","parent_id":null},
{"id":"6","name":"Location","parent_id":null},
{"id":"7","name":"Italy","parent_id":"6"},
{"id":"8","name":"Poland","parent_id":"6"}]
</code>```

The call to the ajax script is based on jsTree - Populate Tree Dynamically using AJAX/C#Web Method. So I have:

```<code>  $('#tree').jstree({
    core: {
      check_callback: true,
    },
    "data": {
      type: "POST",
      url: "/ajaxGetTree",
      contentType: "application/json; charset=utf-8",
      success: function (data) {
         data.d;
         $(data).each(function () {
            return { "id": this.id };
         });
      }
   },

  });
</code>```

When I load the page, no request is being made to /ajaxGetTree and therefore there is no data appearing in the tree.

I previously had it partially working (but cannot revert back to the file I was in, annoyingly). However in that instance it was making the request to /ajaxGetTree but then just showing "Loading..." with a spinner in the area where the tree is supposed to appear. The data didn't appear in the jstree.

Please can someone provide some guidance and if possible code that actually does this - i.e. populates a tree from an ajax source.

The official documentation on it is extremely poor.

答:
I cannot see who is triggering call to build the jstree and from where.

The approach is a bit different but it works for me.

https://everyething.com/Example-of-simple-jsTree-with-dynamic-JSON-data

Title: Can't populate a jstree with ajax data

Body:
I'm using jstree 3.2.1 and am trying to populate it with json data returned from an ajax script.

I've tested the script that produces the json data by accessing the URL, and it's returning valid json:

[{"id":"5","name":"Sector","parent_id":null},
{"id":"6","name":"Location","parent_id":null},
{"id":"7","name":"Italy","parent_id":"6"},
{"id":"8","name":"Poland","parent_id":"6"}]

The call to the ajax script is based on jsTree - Populate Tree Dynamically using AJAX/C#Web Method. So I have:

  $('#tree').jstree({
    core: {
      check_callback: true,
    },
    "data": {
      type: "POST",
      url: "/ajaxGetTree",
      contentType: "application/json; charset=utf-8",
      success: function (data) {
         data.d;
         $(data).each(function () {
            return { "id": this.id };
         });
      }
   },

  });

When I load the page, no request is being made to /ajaxGetTree and therefore there is no data appearing in the tree.

I previously had it partially working (but cannot revert back to the file I was in, annoyingly). However in that instance it was making the request to /ajaxGetTree but then just showing "Loading..." with a spinner in the area where the tree is supposed to appear. The data didn't appear in the jstree.

Please can someone provide some guidance and if possible code that actually does this - i.e. populates a tree from an ajax source.

The official documentation on it is extremely poor.


问:
Using earth engine as a processing step for raster data
We have raster data that we want to process using earth engine and then use that data in another cloud environment. All this should happen programmatically. So manual tools like the asset manager are out. I could not find an API to expose its functionality.

Is there an earth engine API we could use to import and export raster data?

答:
All of Earth Engine is API driven, however some portions of the API are easier to access than others.

For automated imports, you can try using the earthengine command line tool, which formats the API calls for you: https://developers.google.com/earth-engine/command_line

For exports, the easiest path is using the Python client library and the ee.batch.Export calls.


问:
How to get text into Unity?
I have a basic Java program with output of "hello world". What I want to do is to write a Java script to run that program and import that into Unity so I can use it in my program in Unity.

Is there a way?

答:
Don't use OnGui as this is bad for performance rather use Canvas to edit and place the text you prefer on or in (parent) object you want.

to make this look better put the font size higher and the width and height lower.
this will make it look sharper.

ContentLicense: CC BY-SA 4.0

Title: How to get text into Unity?


问:
Position child div to the left of parent div?
I have an image that has a width of 50% and a div with text that is 65% because I want the heading inside the div to overlap the image. But, the problem is that I don't want the other content inside the div to overlap the image - just the heading. I want the text and the button to be next to the image not on top of it.
But I can't seem to figure it out.

Here's a Codepen: https://codepen.io/tayanderson/pen/EbJZxy

```<code>.project {
    height: 75vh;
    margin: 15em 0;
    position: relative;

    .project-info {
        z-index: 100;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        width: 65%;
        height: 100%;
        right: 0;
        h2 {
            text-transform: initial;
            color: #eee;
        }
        p {
            font-weight: 300;
            color: #ccc;
            margin: 40px 0;
        }
        .project-desc {
            width: 70%;
            .button {display:inline-block;}
        }
    }

    .project-img {
        background-size: cover;
        background-position: center;
        height: 100%;
        -webkit-filter: grayscale(100%) brightness(50%);
        filter: grayscale(100%) brightness(50%);
        width: 51.3%;
    }

    a {text-decoration:none;
        color: #fff;}
    @media only screen and (max-width: 768px) {
        .project-info, .project-img {
            width: 100%;
        }
        .project-info {
            left: 0;
            padding: 0 20px;
            .project-desc>*{
                width: 100% !important;
                float: left !important;
            }
            p {display: none;}
        }
    }
}
</code>```

答:
You can try something like that using flexbox.

https://codepen.io/dakata911/pen/BmEpeB

```<code>.article {
  width: 60%;
  margin: 0 auto;
  display: flex;
}

.article__image,
.article__text {
  width: 50%;
}

.article__image {
  background: url('http://www.country1067.com/wp-content/uploads/sites/28/2017/07/logoImage_4.jpg') center center no-repeat;
  background-size: cover
}

.article__text {
  padding: 12px;
  background: #c3c3c3;
}

.article__text h2 {
  margin-left: -96px;
  color: #FFF;
  font-size: 40px;
}
</code>```

Body:
I have an image that has a width of 50% and a div with text that is 65% because I want the heading inside the div to overlap the image. But, the problem is that I don't want the other content inside the div to overlap the image - just the heading. I want the text and the button to be next to the image not on top of it.
But I can't seem to figure it out.

Here's a Codepen: https://codepen.io/tayanderson/pen/EbJZxy

.project {
    height: 75vh;
    margin: 15em 0;
    position: relative;

    .project-info {
        z-index: 100;
        display: flex;
        flex-direction: column;
        justify-content: center;
        position: absolute;
        width: 65%;
        height: 100%;
        right: 0;
        h2 {
            text-transform: initial;
            color: #eee;
        }
        p {
            font-weight: 300;
            color: #ccc;
            margin: 40px 0;
        }
        .project-desc {
            width: 70%;
            .button {display:inline-block;}
        }
    }

    .project-img {
        background-size: cover;
        background-position: center;
        height: 100%;
        -webkit-filter: grayscale(100%) brightness(50%);
        filter: grayscale(100%) brightness(50%);
        width: 51.3%;
    }

    a {text-decoration:none;
        color: #fff;}
    @media only screen and (max-width: 768px) {
        .project-info, .project-img {
            width: 100%;
        }
        .project-info {
            left: 0;
            padding: 0 20px;
            .project-desc>*{
                width: 100% !important;
                float: left !important;
            }
            p {display: none;}
        }
    }
}

Body:
You can try something like that using flexbox.

https://codepen.io/dakata911/pen/BmEpeB

.article {
  width: 60%;
  margin: 0 auto;
  display: flex;
}

.article__image,
.article__text {
  width: 50%;
}

.article__image {
  background: url('http://www.country1067.com/wp-content/uploads/sites/28/2017/07/logoImage_4.jpg') center center no-repeat;
  background-size: cover
}

.article__text {
  padding: 12px;
  background: #c3c3c3;
}

.article__text h2 {
  margin-left: -96px;
  color: #FFF;
  font-size: 40px;
}


问:
How should I use NSSetUncaughtExceptionHandler in Swift
At Objective-C, I call the NSSetUncaughtExceptionHandler(&exceptionHandler) method to log exceptions. How does it called in Swift?

答:
The error you can see at the reopen of a subsequent application in this way.

This code for swift 4.
Add in didFinishLaunchingWithOptions() :

```<code>NSSetUncaughtExceptionHandler { exception in
            print("Error Handling: ", exception)
            print("Error Handling callStackSymbols: ", exception.callStackSymbols)

            UserDefaults.standard.set(exception.callStackSymbols, forKey: "ExceptionHandler")
            UserDefaults.standard.synchronize()
        }
</code>```

And The code add in fistViewController viewLoad()

```<code>// ERROR ExceptionHandler
        if let exception = UserDefaults.standard.object(forKey: "ExceptionHandler") as? [String] {

            print("Error was occured on previous session! \n", exception, "\n\n-------------------------")
            var exceptions = ""
            for e in exception {
                exceptions = exceptions + e + "\n"
            }
            AlertFunctions.messageType.showYesNoAlert("Error was occured on previous session!", bodyMessage: exceptions, {

            }, no: {
                UserDefaults.standard.removeObject(forKey: "ExceptionHandler")
                UserDefaults.standard.synchronize()
            })
        }
</code>```

EDIT:
The code work. But you need reopen your application after error.

Body:
The error you can see at the reopen of a subsequent application in this way.

This code for swift 4.
Add in didFinishLaunchingWithOptions() :

NSSetUncaughtExceptionHandler { exception in
            print("Error Handling: ", exception)
            print("Error Handling callStackSymbols: ", exception.callStackSymbols)

            UserDefaults.standard.set(exception.callStackSymbols, forKey: "ExceptionHandler")
            UserDefaults.standard.synchronize()
        }

And The code add in fistViewController viewLoad()

// ERROR ExceptionHandler
        if let exception = UserDefaults.standard.object(forKey: "ExceptionHandler") as? [String] {

            print("Error was occured on previous session! \n", exception, "\n\n-------------------------")
            var exceptions = ""
            for e in exception {
                exceptions = exceptions + e + "\n"
            }
            AlertFunctions.messageType.showYesNoAlert("Error was occured on previous session!", bodyMessage: exceptions, {

            }, no: {
                UserDefaults.standard.removeObject(forKey: "ExceptionHandler")
                UserDefaults.standard.synchronize()
            })
        }

EDIT:
The code work. But you need reopen your application after error.


问:
CSS flex box - how to make items center vertically with a full height background
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

```<code><div class="feature-content">
<div class="feature-visual">
    <div class="embed-container">
        <iframe src="https://player.vimeo.com/video/214852366?controls=0&hd=1&autohide=1" title="Factory Pattern & REHAU" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="640" height="312" frameborder="0"></iframe>
    </div>
</div>
<div class="quote">
    <div class="words">Improved our conversion rates to a level that far surpassed expectation.
    </div>
</div>
</code>```

CSS:

```<code>article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}
</code>```

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

答:
You need to make the following changes in order to align the items to the center of your .quote container:

First, remove the padding-top:4.5em from your .words CSS otherwise the Y-offset will be shifted down.

Second, change the display of .quote to flex and then use align-items property to vertically align the .word container in the middle of your .quote container. (display:flex;  align-items:center;) in .quote

.feature-content {
  align-items: stretch;
  align-content: stretch;
  display: flex;
  padding-top: .35em;
}

.feature-visual {
  flex-grow: 1;
  flex-basis: 65%;
}

.quote {
  align-self: stretch;
  background: #db6f72;
  color: #FFF;
  flex-basis: 35%;
  flex-grow: 1;
  position: relative;
  display:flex;
  align-items: center;
}

.words {
  font-family: "Georgia", serif;
  padding-left:2em;
  font-size: 2em;
  font-style: italic;
  line-height: 1.5;
  width: 80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="feature-content">
  <div class="feature-visual">
    <div class="embed-container">
      <iframe src="https://player.vimeo.com/video/214852366?controls=0&hd=1&autohide=1" title="Factory Pattern & REHAU" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="640" height="312" frameborder="0"></iframe>
    </div>
  </div>
  <div class="quote">
    <div class="words">Improved our conversion rates to a level that far surpassed expectation.
    </div>
  </div></code>```

Body:
I'm trying to align some text within a box vertically centered, whilst ensuring the background colour stretches full height.

HTML:

Improved our conversion rates to a level that far surpassed expectation.

CSS:

article section.case-study .feature-content {
    align-items: stretch;
    align-content: stretch;
    display: flex;
    padding-top: .35em;
}
article section.case-study .feature-content .feature-visual {
    flex-grow: 1;
    flex-basis: 65%;
}
article section.case-study .feature-content .quote {
    align-self: stretch;
    background: #db6f72;
    color: #FFF;
    flex-basis: 35%;
    flex-grow: 1;
    position: relative;
}
article section.case-study .feature-content .quote .words {
    font-family: "Georgia", serif;
    font-size: 2em;
    font-style: italic;
    line-height: 1.5;
    padding-top: 4.5em;
    width: 80%;
}

Current live version here https://factorypattern.co.uk/case-study/rehau-interactive-touchscreen/

Image here of what I want it to look like:
enter image description here

Any assistance greatly appreciated :)

Body:
You need to make the following changes in order to align the items to the center of your .quote container:

First, remove the padding-top:4.5em from your .words CSS otherwise the Y-offset will be shifted down.

Second, change the display of .quote to flex and then use align-items property to vertically align the .word container in the middle of your .quote container. (display:flex;  align-items:center;) in .quote

.feature-content {
  align-items: stretch;
  align-content: stretch;
  display: flex;
  padding-top: .35em;
}

.feature-visual {
  flex-grow: 1;
  flex-basis: 65%;
}

.quote {
  align-self: stretch;
  background: #db6f72;
  color: #FFF;
  flex-basis: 35%;
  flex-grow: 1;
  position: relative;
  display:flex;
  align-items: center;
}

.words {
  font-family: "Georgia", serif;
  padding-left:2em;
  font-size: 2em;
  font-style: italic;
  line-height: 1.5;
  width: 80%;
}

<div class="feature-content">
  <div class="feature-visual">
    <div class="embed-container">
      <iframe src="https://player.vimeo.com/video/214852366?controls=0&amp;hd=1&amp;autohide=1" title="Factory Pattern &amp; REHAU" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen="" width="640" height="312" frameborder="0"></iframe>
    </div>
  </div>
  <div class="quote">
    <div class="words">Improved our conversion rates to a level that far surpassed expectation.
    </div>
  </div>


问:
Int won't show numbers after the comma
I want to get from a string to a int. My problem is now that i'll get a int value but it wont show the number after the comma. If the string is -0,23, than the int will print 0.How can i fix this? Please help.       </p>

```<code>let int = (percent_change_24hArray[indexPath.row] as NSString).integerValue
</code>```

答:
You need to use a float, integers don't take numbers after the comma
https://developer.apple.com/documentation/swift/float</p>

Title: Int won't show numbers after the comma

Body:
I want to get from a string to a int. My problem is now that i'll get a int value but it wont show the number after the comma. If the string is -0,23, than the int will print 0.How can i fix this? Please help.

let int = (percent_change_24hArray[indexPath.row] as NSString).integerValue


问:
Sending messages to specific Smack domains after initial broadcast message
I'm creating an instant messaging client using Smack 3.1.0 and Java. The problem I'm running in to has to do with sending messages to the user on a specific domain.

For example, I have two users, 1@gmail.com and 2@gmail.com. 1@gmail.com logs in to XMPP through my IM client. 2@gmail.com logs in to GChat through gmail.com AND a second time through pidgin. So now I have one instance of 1@gmail.com and 2 instances of 2@gmail.com.

The way gmail works, if 1@gmail.com sends a message to 2@gmail.com, the gmail and the pidgin client both get the initial message. But then if the gmail instance responds to the message, every message from then on only goes between 1@gmail.com and the gmail instance of 2@gmail.com.

I would like to mimic this behavior with my IM client. I would think the way to do it would be to set up a Chat, send the initial IM to all instances of the recipient. Then I'd set up a MessageListener to listen for a response. When I get the response, I'd have to create a new chat, specifying the 2@gmail.com/resource. But then I'd have to write the MessageListener twice. Any ideas? Here's some sample code that I'm using (the method AddText() simply appends the message to my conversation pane):

```<code>recipient = buddy;
setTitle("Instant Message - "+recipient);
chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser(), new MessageListener() {
    public void processMessage(Chat chat, Message msg) {
        //if(chat.getParticipant().indexOf('/')!=-1)
        addText(msg.getBody(), chat.getParticipant(), true);
    }
});
</code>```

UPDATE
I wanted to supplement the answer below with actual code that I used to make this work:

```<code>chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser(), new MessageListener() {
    public void processMessage(Chat new_chat, Message msg) {
        if(msg.getFrom().replaceFirst("/.*", "").equals(recipient.getUser()))
        {
            if(buddy_resource==null || !msg.getFrom().replaceFirst(".*?/", "").equals(buddy_resource.getResource()))
            {
                buddy_resource = recipient.getResource(msg.getFrom().replaceFirst(".*?/", ""));
                chat = null;
                chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser()+"/"+buddy_resource.getResource(), new MessageListener(){
                    public void processMessage(Chat new_chat2, Message msg) {
                        addText(msg.getBody(), new_chat2.getParticipant(), true);
                    }
                });
            }
            addText(msg.getBody(), chat.getParticipant(), true);
        }
    }
});
</code>```

To summarize, I send the first message to all resources of the recipient's address and wait for a response. When I get the response, I replace the current Chat object with a new one that specifies the individual resource that responded to the initial message. The code is a little messy with two different MessageListener objects that could probably be combined into a new class. But it works.

答: In your MessageListener why not always respond to the sender? I think you get it by calling something like msg.getSender() or getFrom() (I'm on mobile right now, cannot check)</p>

Body:
I'm creating an instant messaging client using Smack 3.1.0 and Java. The problem I'm running in to has to do with sending messages to the user on a specific domain.

For example, I have two users, 1@gmail.com and 2@gmail.com. 1@gmail.com logs in to XMPP through my IM client. 2@gmail.com logs in to GChat through gmail.com AND a second time through pidgin. So now I have one instance of 1@gmail.com and 2 instances of 2@gmail.com.

The way gmail works, if 1@gmail.com sends a message to 2@gmail.com, the gmail and the pidgin client both get the initial message. But then if the gmail instance responds to the message, every message from then on only goes between 1@gmail.com and the gmail instance of 2@gmail.com.

I would like to mimic this behavior with my IM client. I would think the way to do it would be to set up a Chat, send the initial IM to all instances of the recipient. Then I'd set up a MessageListener to listen for a response. When I get the response, I'd have to create a new chat, specifying the 2@gmail.com/resource. But then I'd have to write the MessageListener twice. Any ideas? Here's some sample code that I'm using (the method AddText() simply appends the message to my conversation pane):

recipient = buddy;
setTitle("Instant Message - "+recipient);
chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser(), new MessageListener() {
    public void processMessage(Chat chat, Message msg) {
        //if(chat.getParticipant().indexOf('/')!=-1)
        addText(msg.getBody(), chat.getParticipant(), true);
    }
});

UPDATE
I wanted to supplement the answer below with actual code that I used to make this work:

chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser(), new MessageListener() {
    public void processMessage(Chat new_chat, Message msg) {
        if(msg.getFrom().replaceFirst("/.*", "").equals(recipient.getUser()))
        {
            if(buddy_resource==null || !msg.getFrom().replaceFirst(".*?/", "").equals(buddy_resource.getResource()))
            {
                buddy_resource = recipient.getResource(msg.getFrom().replaceFirst(".*?/", ""));
                chat = null;
                chat = com.andreaslekas.pim.PIM.connection.getChatManager().createChat(recipient.getUser()+"/"+buddy_resource.getResource(), new MessageListener(){
                    public void processMessage(Chat new_chat2, Message msg) {
                        addText(msg.getBody(), new_chat2.getParticipant(), true);
                    }
                });
            }
            addText(msg.getBody(), chat.getParticipant(), true);
        }
    }
});

To summarize, I send the first message to all resources of the recipient's address and wait for a response. When I get the response, I replace the current Chat object with a new one that specifies the individual resource that responded to the initial message. The code is a little messy with two different MessageListener objects that could probably be combined into a new class. But it works.


问:
Java : Need to get the same functionality of the Integer.toHexString() with a String parameter and not an Int parameter due to NumberFormat Exception
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

```<code>String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException
</code>```

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

答:
Try this way:</p>

```<code> String largeNumberAsAString = "9999999999";
    System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));
</code>```

Body:
I have this line of Java code that will throw NumberFormatException if the number represented as a String is above 2,147,483,647.

Because:

The int data type is a 32-bit signed two's complement integer. It has
  a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647

Code Throwing the NumberFormatException:

String largeNumberAsAString = "9999999999";
Integer.toHexString(Integer.parseInt(largeNumberAsAString)); // NumberFormatException

How can I get the same functionality of theInteger.toHexString() with a String parameter and not an int parameter due to NumberFormatException?

Body:
Try this way:

 String largeNumberAsAString = "9999999999";
    System.out.println(Integer.toHexString(BigDecimal.valueOf(Double.valueOf(largeNumberAsAString)).intValue()));


问:
Get values to each Label from a Method, which return as a List
I need to get values of ItemCode and ItemName into separate Labels using Linq. I implemented a query joining tblItem and tblInventry. It returns all rows as a List. Query is below,

```<code>public tblItem GetItemNameAndCode(int itemID)
{
    var iNameCode = from it in DB.tblItems
                    join inv in DB.tblInventories on it.ItemID equals inv.ItemID
                    where it.ItemID == itemID
                    orderby it.ItemName ascending
                    select it;
    return iNameCode.ToList<tblItem>();
}
</code>```

From the above query(GetItemNameAndCode(ItemID)), I need to get ItemCode and ItemName(ascending). That code is below,

```<code>if (lblItemID != null)
{
      int ItemID = Convert.ToInt32(lblItemID.Text);
      this.ItemBO.Item = this.ItemBO.GetItemNameAndCode(ItemID);
      if (this.ItemBO.Item != null)
      {
          lblItemCode.Text = this.ItemBO.Item.ItemCode;
          lblItemName.Text = this.ItemBO.Item.ItemName;
      }
}
</code>```

But how do I return only those 2 fields ?
When I use this,

return iNameCode.ToList();

It gives an exception.
Ultimately I need ItemName get ordered in ascending order.

答:
it's not very clear if you expect one result or many from the GetItemNameAndCode method, but based on

the name of the method

the return type

the usage afterwards

I presume you actually expect one single element having a code and a name property

In any case i would define an object to hold the return type

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

and refactor your method to return that one single element from the list

```<code>public Shape GetItemNameAndCode(int itemID)
{
    var query = from it in DB.tblItems
                join inv in DB.tblInventories on it.ItemID equals inv.ItemID
                where it.ItemID == itemID
                orderby it.ItemName ascending
                select new Shape
                {
                    Code = it.ItemCode,
                    Name = it.ItemName,
                };

    return query.SingleOrDefault();
}
</code>```

notice the .SingleOrDefault() at the end

Body:
I need to get values of ItemCode and ItemName into separate Labels using Linq. I implemented a query joining tblItem and tblInventry. It returns all rows as a List. Query is below,

public tblItem GetItemNameAndCode(int itemID)
{
    var iNameCode = from it in DB.tblItems
                    join inv in DB.tblInventories on it.ItemID equals inv.ItemID
                    where it.ItemID == itemID
                    orderby it.ItemName ascending
                    select it;
    return iNameCode.ToList<tblItem>();
}

From the above query(GetItemNameAndCode(ItemID)), I need to get ItemCode and ItemName(ascending). That code is below,

if (lblItemID != null)
{
      int ItemID = Convert.ToInt32(lblItemID.Text);
      this.ItemBO.Item = this.ItemBO.GetItemNameAndCode(ItemID);
      if (this.ItemBO.Item != null)
      {
          lblItemCode.Text = this.ItemBO.Item.ItemCode;
          lblItemName.Text = this.ItemBO.Item.ItemName;
      }
}

But how do I return only those 2 fields ?
When I use this,

return iNameCode.ToList();

It gives an exception.
Ultimately I need ItemName get ordered in ascending order.

Body:
it's not very clear if you expect one result or many from the GetItemNameAndCode method, but based on

the name of the method

the return type

the usage afterwards

I presume you actually expect one single element having a code and a name property

In any case i would define an object to hold the return type

public class Shape
{
    public string Code { get; set; }
    public string Name { get; set; }
}

and refactor your method to return that one single element from the list

public Shape GetItemNameAndCode(int itemID)
{
    var query = from it in DB.tblItems
                join inv in DB.tblInventories on it.ItemID equals inv.ItemID
                where it.ItemID == itemID
                orderby it.ItemName ascending
                select new Shape
                {
                    Code = it.ItemCode,
                    Name = it.ItemName,
                };

    return query.SingleOrDefault();
}

notice the .SingleOrDefault() at the end


答:
Easiest way I know is the below (but has Pandas dependency):</p>

```<code>path_df.toPandas().set_index('FromComponentID').T.to_dict('list')
</code>```

Title: Dataframe pyspark to dict

Body:
I have this dataframe path_df:

path_df.show()
+---------------+-------------+----+
|FromComponentID|ToComponentID|Cost|
+---------------+-------------+----+
|            160|          163|27.0|
|            160|          183|27.0|
|            161|          162|22.0|
|            161|          170|31.0|
|            162|          161|22.0|
|            162|          167|24.0|
|            163|          160|27.0|
|            163|          164|27.0|
|            164|          163|27.0|
|            164|          165|35.0|
|            165|          164|35.0|
|            165|          166|33.0|
|            166|          165|33.0|
|            166|          167|31.0|
|            167|          162|24.0|
|            167|          166|31.0|
|            167|          168|27.0|
|            168|          167|27.0|
|            168|          169|23.0|
|            169|          168|23.0|
+---------------+-------------+----+
only showing top 20 rows

From this, I want to make a dictionnary, as follow:
{FromComponentID:{ToComponentID:Cost}}

For my current data, it would be:

{160 : {163 : 27,
        183 : 27},
 161 : {162 : 22,
        170 : 31},
 162 : {161 : 22
        167 : 24},
 ...
 167 : {162 : 24,
        166 : 31,
        168 : 27}
 168 : {167 : 27,
        169 : 23},
 169 : {168 : 23}
}

Can I do that using only PySpark and how ? Or maybe it's better to extract my data and process them directly with python.

Body:
Easiest way I know is the below (but has Pandas dependency):

path_df.toPandas().set_index('FromComponentID').T.to_dict('list')


问:
Array of objects to query string with dot notation, jQuery
I am using $.param() function to convert objects to query strings. However I came to a point where I have an object like this:

```<code>{
   myArray: [{
      prop1: "somevalue"
   }, {
      prop1: "somevalue"
   }],
   someOtherProp: ...
}
</code>```

The result from $.param when passing such an object is something in the lines of:

myArray[0][prop1]=somevalue&myArray[1][prop1]=somevalue&someOtherProp=...

However, I would like to encode the object with dot notation, like so:

myArray[0].prop1=somevalue&myArray[1].prop1=somevalue&someOtherProp=...

It doesn't strictly have to be with jquery. Other solutions are acceptable as well.

Any ideas on how to achieve it? Thanks!

答:
If you willing to extend the jQuery a bit

see this code below taken from the gist

It seems that if you want to use param, there is no easy way to do it

jQuery query param serialization with dot notation support

```<code>var r20 = /%20/g,
    rbracket = /\[\]$/,
    rCRLF = /\r?\n/g,
    rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
    rsubmittable = /^(?:input|select|textarea|keygen)/i,
    rIdentifier = /^[$A-Z_][0-9A-Z_$]*$/i;

jQuery.fn.extend({
    serialize: function() {
        return jQuery.param( this.serializeArray() );
    },
    serializeArray: function() {
        return this.map(function(){
            // Can add propHook for "elements" to filter or add form elements
            var elements = jQuery.prop( this, "elements" );
            return elements ? jQuery.makeArray( elements ) : this;
        })
        .filter(function(){
            var type = this.type;
            // Use .is(":disabled") so that fieldset[disabled] works
            return this.name && !jQuery( this ).is( ":disabled" ) &&
                rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
                ( this.checked || !manipulation_rcheckableType.test( type ) );
        })
        .map(function( i, elem ){
            var val = jQuery( this ).val();

            return val == null ?
                null :
                jQuery.isArray( val ) ?
                    jQuery.map( val, function( val ){
                        return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                    }) :
                    { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
        }).get();
    }
});

//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional, dotNotation ) {
    var prefix,
        s = [],
        add = function( key, value ) {
            // If value is a function, invoke it and return its value
            value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
            s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
        };

    // Set traditional to true for jQuery <= 1.3.2 behavior.
    if ( traditional === undefined ) {
        traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
    }
    if ( dotNotation === undefined ) {
        dotNotation = jQuery.ajaxSettings && jQuery.ajaxSettings.dotNotation;
    }

    // If an array was passed in, assume that it is an array of form elements.
    if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
        // Serialize the form elements
        jQuery.each( a, function() {
            add( this.name, this.value );
        });

    } else {
        // If traditional, encode the "old" way (the way 1.3.2 or older
        // did it), otherwise encode params recursively.
        for ( prefix in a ) {
            buildParams( prefix, a[ prefix ], traditional, dotNotation, add );
        }
    }

    // Return the resulting serialization
    return s.join( "&" ).replace( r20, "+" );
};

function buildParams( prefix, obj, traditional, dotNotation, add ) {
    var name;

    if ( jQuery.isArray( obj ) ) {
        // Serialize array item.
        jQuery.each( obj, function( i, v ) {
            if ( traditional || rbracket.test( prefix ) ) {
                // Treat each array item as a scalar.
                add( prefix, v );

            } else {
                // Item is non-scalar (array or object), encode its numeric index.
                buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, dotNotation, add );
            }
        });

    } else if ( !traditional && jQuery.type( obj ) === "object" ) {
        // Serialize object item.
        for ( name in obj ) {
            if( dotNotation && rIdentifier.test(name) ) {
                buildParams( prefix + '.' + name, obj[name], traditional, dotNotation, add )
            } else {
                buildParams( prefix + "[" + name + "]", obj[ name ], traditional, dotNotation, add );
            }
        }

    } else {
        // Serialize scalar item.
        add( prefix, obj );
    }
}
</code>```

Body:
I am using $.param() function to convert objects to query strings. However I came to a point where I have an object like this:

{
   myArray: [{
      prop1: "somevalue"
   }, {
      prop1: "somevalue"
   }],
   someOtherProp: ...
}

The result from $.param when passing such an object is something in the lines of:

myArray[0][prop1]=somevalue&myArray[1][prop1]=somevalue&someOtherProp=...

However, I would like to encode the object with dot notation, like so:

myArray[0].prop1=somevalue&myArray[1].prop1=somevalue&someOtherProp=...

It doesn't strictly have to be with jquery. Other solutions are acceptable as well.

Any ideas on how to achieve it? Thanks!

Body:
If you willing to extend the jQuery a bit

see this code below taken from the gist

It seems that if you want to use param, there is no easy way to do it

jQuery query param serialization with dot notation support

var r20 = /%20/g,
    rbracket = /\[\]$/,
    rCRLF = /\r?\n/g,
    rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
    rsubmittable = /^(?:input|select|textarea|keygen)/i,
    rIdentifier = /^[$A-Z_][0-9A-Z_$]*$/i;

jQuery.fn.extend({
    serialize: function() {
        return jQuery.param( this.serializeArray() );
    },
    serializeArray: function() {
        return this.map(function(){
            // Can add propHook for "elements" to filter or add form elements
            var elements = jQuery.prop( this, "elements" );
            return elements ? jQuery.makeArray( elements ) : this;
        })
        .filter(function(){
            var type = this.type;
            // Use .is(":disabled") so that fieldset[disabled] works
            return this.name && !jQuery( this ).is( ":disabled" ) &&
                rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
                ( this.checked || !manipulation_rcheckableType.test( type ) );
        })
        .map(function( i, elem ){
            var val = jQuery( this ).val();

            return val == null ?
                null :
                jQuery.isArray( val ) ?
                    jQuery.map( val, function( val ){
                        return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                    }) :
                    { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
        }).get();
    }
});

//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional, dotNotation ) {
    var prefix,
        s = [],
        add = function( key, value ) {
            // If value is a function, invoke it and return its value
            value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
            s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
        };

    // Set traditional to true for jQuery <= 1.3.2 behavior.
    if ( traditional === undefined ) {
        traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
    }
    if ( dotNotation === undefined ) {
        dotNotation = jQuery.ajaxSettings && jQuery.ajaxSettings.dotNotation;
    }

    // If an array was passed in, assume that it is an array of form elements.
    if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
        // Serialize the form elements
        jQuery.each( a, function() {
            add( this.name, this.value );
        });

    } else {
        // If traditional, encode the "old" way (the way 1.3.2 or older
        // did it), otherwise encode params recursively.
        for ( prefix in a ) {
            buildParams( prefix, a[ prefix ], traditional, dotNotation, add );
        }
    }

    // Return the resulting serialization
    return s.join( "&" ).replace( r20, "+" );
};

function buildParams( prefix, obj, traditional, dotNotation, add ) {
    var name;

    if ( jQuery.isArray( obj ) ) {
        // Serialize array item.
        jQuery.each( obj, function( i, v ) {
            if ( traditional || rbracket.test( prefix ) ) {
                // Treat each array item as a scalar.
                add( prefix, v );

            } else {
                // Item is non-scalar (array or object), encode its numeric index.
                buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, dotNotation, add );
            }
        });

    } else if ( !traditional && jQuery.type( obj ) === "object" ) {
        // Serialize object item.
        for ( name in obj ) {
            if( dotNotation && rIdentifier.test(name) ) {
                buildParams( prefix + '.' + name, obj[name], traditional, dotNotation, add )
            } else {
                buildParams( prefix + "[" + name + "]", obj[ name ], traditional, dotNotation, add );
            }
        }

    } else {
        // Serialize scalar item.
        add( prefix, obj );
    }
}


问:
How to manage dependency when cloning repository?
I am using mercurial and I am wondering how to do the following.
Here is my repository architecture :

```<code>./repo/utils/workers/[...]
./repo/utils/tools/[...]
./repo/proj1/file.py
</code>```

Let's say that in proj1/file.py I need to import some code located in workers and tools. eg

```<code>from utils.workers import foo
from utils.tools import bar
</code>```

What would be the best way/tool to check out proj1 with all the needed dependencies (eg, workers/ and tools/) without having to clone utils/workers and utils/tools inside of proj1.

Also - doing a sys.path.append(repo/utils/workers) is not a option.

== Edit 01/24/11 ==

Thanks for all the answers.
I've been thinking of a way to really explain my problem differently, and it seams that we should make abstraction of hg for a better understanding.
Let's say that in /utils/ there also are another few modules in there, that do not belong to my project, but that are actually needed. For example: http://code.google.com/p/python-gflags/
When checking out /repo/proj1/ I want all the dependencies, not matter which repository they're form, to be checked out too - but with read-only since.

So if I do hg clone /proj1/ I want this action to also clone all the needed modules from /utils/workers/,
/utils/tools/,
 and python-gflags under
 /utils/python-gflags

I hope this helps a little bit to clarify what I am trying to do.

Cheers,

Martin

答: You should look at subrepositories (which also called nested)</p>

Body:
I am using mercurial and I am wondering how to do the following.
Here is my repository architecture :

./repo/utils/workers/[...]
./repo/utils/tools/[...]
./repo/proj1/file.py

Let's say that in proj1/file.py I need to import some code located in workers and tools. eg

from utils.workers import foo
from utils.tools import bar

What would be the best way/tool to check out proj1 with all the needed dependencies (eg, workers/ and tools/) without having to clone utils/workers and utils/tools inside of proj1.

Also - doing a sys.path.append(repo/utils/workers) is not a option.

== Edit 01/24/11 ==

Thanks for all the answers.
I've been thinking of a way to really explain my problem differently, and it seams that we should make abstraction of hg for a better understanding.
Let's say that in /utils/ there also are another few modules in there, that do not belong to my project, but that are actually needed. For example: http://code.google.com/p/python-gflags/
When checking out /repo/proj1/ I want all the dependencies, not matter which repository they're form, to be checked out too - but with read-only since.

So if I do hg clone /proj1/ I want this action to also clone all the needed modules from /utils/workers/,
/utils/tools/,
 and python-gflags under
 /utils/python-gflags

I hope this helps a little bit to clarify what I am trying to do.

Cheers,

Martin


问:
OpenAPI multiple types inside an array
I'm having trouble defining a reusable schema component using OpenAPI 3 which would allow for an array that contains multiple types. Each item type inherits from the same parent class but has specific child properties. This seems to work alright in the model view on SwaggerHub but the example view doesn't show the data correctly.

TLDR; Is there a way to define an array containing different object types in OpenAPI 3?

```<code>Response:
  allOf:
    - $ref: '#/components/schemas/BaseResponse'
    - type: object
      title: A full response
      required:
      - things
      properties:
        things:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/ItemOne'
              - $ref: '#/components/schemas/ItemTwo'
              - $ref: '#/components/schemas/ItemThree'
</code>```

答:
Your spec is correct. It's just that example rendering for oneOf and anyOf schemas is not yet supported in Swagger UI. You can track this issue for status updates:

Multiple responses using oneOf attribute do not appear in UI

The workaround is to manually add an example alongside the oneOf/anyOf schema or to the parent schema:

        things:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/ItemOne'
              - $ref: '#/components/schemas/ItemTwo'
              - $ref: '#/components/schemas/ItemThree'
          # Note that array example is on the same
          # level as `type: array`
          example:
            - foo: bar        # Example of ItemOne
              baz: qux
            - "Hello, world"  # Example of ItemTwo
            - [4, 8, 15, 16, 23, 42]  # Example of ItemThree
```

Title: OpenAPI multiple types inside an array

Body:
I'm having trouble defining a reusable schema component using OpenAPI 3 which would allow for an array that contains multiple types. Each item type inherits from the same parent class but has specific child properties. This seems to work alright in the model view on SwaggerHub but the example view doesn't show the data correctly.

TLDR; Is there a way to define an array containing different object types in OpenAPI 3?

Response:
  allOf:
    - $ref: '#/components/schemas/BaseResponse'
    - type: object
      title: A full response
      required:
      - things
      properties:
        things:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/ItemOne'
              - $ref: '#/components/schemas/ItemTwo'
              - $ref: '#/components/schemas/ItemThree'


问:
Pandas merge two datasets with same number of rows
I have two tables with same number of rows (second table is computed from first one by processing of text inside T1). I have both of them stored as pandas dataframe. T2 is no common column with T1. This is example because my tables are huge:

```<code>T1:
| name  | street  | city   |
|-------|---------|--------|
| David | street1 | Prague |
| John  | street2 | Berlin |
| Joe   | street3 | London |

T2:
| computed1 | computed2 |
|-----------|-----------|
| 0.5       | 0.3       |
| 0.2       | 0.8       |
| 0.1       | 0.6       |

Merged:
| name  | street  | city   | computed1 | computed2 |
|-------|---------|--------|-----------|-----------|
| David | street1 | Prague | 0.5       | 0.3       |
| John  | street2 | Berlin | 0.2       | 0.8       |
| Joe   | street3 | London | 0.1       | 0.6       |
</code>```

I tried these commands:

```<code>pd.concat([T1,T2])
pd.merge([T1,T2])
result=T1.join(T1)
</code>```

With concat and merge I will get only first thousand combined and rest is filled with nan (I double checked that both are same size), and with .join it not combine them because there is nothing in common.

Is there any way how to combine these two tables in pandas?

Thanks

答:
Another way would be to merge on the index values:</p>

```<code>df = T1.reset_index().merge(T2.reset_index(), left_index=True, right_index=True, how='left)
</code>```

Body:
I have two tables with same number of rows (second table is computed from first one by processing of text inside T1). I have both of them stored as pandas dataframe. T2 is no common column with T1. This is example because my tables are huge:

T1:
| name  | street  | city   |
|-------|---------|--------|
| David | street1 | Prague |
| John  | street2 | Berlin |
| Joe   | street3 | London |

T2:
| computed1 | computed2 |
|-----------|-----------|
| 0.5       | 0.3       |
| 0.2       | 0.8       |
| 0.1       | 0.6       |

Merged:
| name  | street  | city   | computed1 | computed2 |
|-------|---------|--------|-----------|-----------|
| David | street1 | Prague | 0.5       | 0.3       |
| John  | street2 | Berlin | 0.2       | 0.8       |
| Joe   | street3 | London | 0.1       | 0.6       |

I tried these commands:

pd.concat([T1,T2])
pd.merge([T1,T2])
result=T1.join(T1)

With concat and merge I will get only first thousand combined and rest is filled with nan (I double checked that both are same size), and with .join it not combine them because there is nothing in common.

Is there any way how to combine these two tables in pandas?

Thanks

Body:
Another way would be to merge on the index values:

df = T1.reset_index().merge(T2.reset_index(), left_index=True, right_index=True, how='left)


问:
sample sequence of successive integer of an interval
I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so?
For example,

```<code>sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30
</code>```

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84)  etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

```<code>sizevec <- sample(c(1:4),10,replace = T)
</code>```

Thanks for the help

答:
HI you are unclear if the vectors may overlap or not. assuming the may overlap this should work

```<code>lapply(sample(c(1:97), 10, replace = F),function(i){ 0:2 + i})
</code>```

having a random length would then look like this

```<code>lapply(sample(c(1:97), 10, replace = F),function(i){ 0:sample(1:10,1) + i})
</code>```

Body:
I have a question about sampling: I would like to sample successive number in a vector without replacement. Is there a simple way to do so?
For example,

sample(c(1:100), 10, replace = F)
76 99 94 53 12 34  5 82 75 30

gives me 10 number between 1 and 100. Now I would like to have 10 sequence of 3 successive integer without replacement: c(2,3,4), c(10,11,12), c(82,83,84)  etc.

The different sequences can't overlap, that is if c(2,3,4) is my first sampling, then none of the following one can have these numbers.

I would even look for the possibility of sampling 10 sequences of different sizes, the sizes given by a vector like

sizevec <- sample(c(1:4),10,replace = T)

Thanks for the help

Body:
HI you are unclear if the vectors may overlap or not. assuming the may overlap this should work

lapply(sample(c(1:97), 10, replace = F),function(i){ 0:2 + i})

having a random length would then look like this

lapply(sample(c(1:97), 10, replace = F),function(i){ 0:sample(1:10,1) + i})


问:
Firestore query for size only
Is it possible to query a Firestore collection for document size only? And thereby skipping the reads of all documents in a collection? I need to know the size of a collection to make pagination showing page x of x. I wish to avoid using unnecessary read quotas just to get the size of a collection.</p>

答:
There is no way to just get the number of documents in a collection. The only way to determine this is to download the documents and count them, a wasteful operation in your scenario.

If you need this, I recommend you keep a separate counter property somewhere and update that as you add/remove documents to and from the collection.

Doing this in Cloud Functions is a quite natural fit. I recommend that you have a look at the sample of keeping a counter. While it is written for Firebase's Realtime Database, the same approach works for Cloud Firestore. If you're having trouble making this work, post a new question with the minimal code where you are stuck.

Title: Firestore query for size only


问:
graphics.h programs not running in Dosbox Windows 7 environment
I have installed Dosbox to run Turbo C in it. But my graphics.h programs are not executing in it. I am getting Linker Error which says"Undefined sumbol initgraph in module..." and so on.</p>

答:
The problem you are facing is quite simple to solve.

Open your Turboc IDE

Click on options
click on linker
click on libraries
mark the graphics option(a cross mark usually)
now run.


问:
TriggerFirstNavigate() calls start() method of ViewModel before Show() method of presenter
I have a scenario where I have LoginActivity with Fingerprint option.
When the app starts, I want fingerprint dialog to be shown. I start the fingerprint flow from Start() method of LoginViewModel but the activity instance is null since Show() is not yet called from presenter.

Please let me know if there is a way to fix this.

答:
In MvvmCross, The ViewModel lifecycle is agnostic to any platform lifecycle.

If you need to do something when a particular event happens at UI level, you can use the View callbacks that MvxViewModel has. In this particular case, you can use ViewAppearing or ViewAppeared.

You can read more about this in the official documentation.


答:
You will probably have to use a NumberFormatter for that, set up for your locale. In the US, the decimal separator is a period. (".") A comma is considered a delimiter.

Plus, assuming you are in a locale where the decimal separator is a comma, converting to an integer will truncate the part after the decimal separator anyway.

Code like the code below should work:

```<code>var str = "-0,23"

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "fr_FR")

let aVal = formatter.number(from: str)?.doubleValue
</code>```

(I'm using France's French as the locale since France uses a comma as a decimal separator.)

Note that you need to think carefully about where you numeric strings come from in order to decide how to handle locale. if these are user-entered strings then you should probably use a number formatter with the default locale for the device. That way a European user can use a comma as a decimal separator and a US user can use a period as a decimal separator and both will work.

Title: Int won't show numbers after the comma

Body:
You will probably have to use a NumberFormatter for that, set up for your locale. In the US, the decimal separator is a period. (".") A comma is considered a delimiter.

Plus, assuming you are in a locale where the decimal separator is a comma, converting to an integer will truncate the part after the decimal separator anyway.

Code like the code below should work:

var str = "-0,23"

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale(identifier: "fr_FR")

let aVal = formatter.number(from: str)?.doubleValue

(I'm using France's French as the locale since France uses a comma as a decimal separator.)

Note that you need to think carefully about where you numeric strings come from in order to decide how to handle locale. if these are user-entered strings then you should probably use a number formatter with the default locale for the device. That way a European user can use a comma as a decimal separator and a US user can use a period as a decimal separator and both will work.


答:
We can use methods from tidyverse

```<code>library(dplyr)
library(tidyr)
df %>%
   separate(ID, into = c("ID", "v1"), sep="(?<=\\d)(?![0-9])") %>%
   gather(key, val,  -one_of("ID", "v1"))  %>%
   unite(key_v1, key, v1) %>%
   spread(key_v1, val)
#  ID X1_l X1_r X2_l X2_r X3_l X3_r X4_l X4_r
#1  1    1    2    5    6    9   10   13   14
#2  2    4    3    8    7   12   11   16   15
</code>```

Title: reduce number of rows by cbinding data, also rename columns

Body:
I want to "partially" make the data.frame "wider"
Not really succeeding in doing so.

data looks like

 ID X1 X2 X3 X4
 1l  1  5  9 13
 1r  2  6 10 14
 2r  3  7 11 15
 2l  4  8 12 16

desired output

 ID X1_l X2_l X3_l X4_l X1_r X2_r X3_r X4_r
  1    1    5    9   13    2    6   10   14
  2    4    8   12   16    3    7   11   15

rep data

df <- data.frame(ID=c("1l","1r","2r","2l"),matrix(1:16,ncol=4))

please note:

the order of l and r are not always the same. As shown in the example. So no cheating possible here. We could do a natural sort to solve that but let's don't do it. Possibly there is a single r or l number. So for e.g., there exists 18l but NOT 18r.

My try is to first split the data up by same numbers: Like so

split(x = df,f = sub("[lr]","",df$ID))

Any fast solutions for a problem like that?

Edit

@Arkun

Error Message:

    Error: Duplicate identifiers for rows (7561, 7562), (7581, 7582), (7599, 7600), (7619, 7620), (7563, 7564), (7583, 7584), (7601, 7602), (7621, 7622), (7565, 7566), (7585, 7586), (7603, 7604), (7623, 7624), (7567, 7568), (7587, 7588), (7605, 7606), (7625, 7626), (7569, 7570), (7607, 7608), (7571, 7572), (7589, 7590), (7609, 7610), (7573, 7574), (7591, 7592), (7611, 7612), (7575, 7576), (7593, 7594), (7613, 7614), (7577, 7578), (7595, 7596), (7615, 7616), (7579, 7580), (7597, 7598), (7617, 7618), (6577, 6578), (6597, 6598), (6615, 6616), (6635, 6636), (6579, 6580), (6599, 6600), (6617, 6618), (6637, 6638), (6581, 6582), (6601, 6602), (6619, 6620), (6639, 6640), (6583, 6584), (6603, 6604), (6621, 6622), (6641, 6642), (6585, 6586), (6623, 6624), (6587, 6588), (6605, 6606), (6625, 6626), (6589, 6590), (6607, 6608), (6627, 6628), (6591, 6592), (6609, 6610), (6629, 6630), (6593, 6594), (6611, 6612), (6631, 6632), (6595, 6596), (6613, 6614), (6633, 6634), (7643, 7644), (7663, 7664), (7681, 76
In addition: Warning message:
Too many values at 66 locations: 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, ...

About the real data:

43 patients (1r,1l, ... 43r,43l)
About 112 Variables. First after ID is called v2_1_prot and last v2_80_CK

So i replaced the part of x1:x4 with v2_1_prot:v2_80_CK. Am I doing something wrong here?

I checked my ID variable there are not duplicates so far.

all_pat_rbind2$ID %>% count %>% extract2("freq") %>% max # is equal to one

Body:
We can use methods from tidyverse

library(dplyr)
library(tidyr)
df %>%
   separate(ID, into = c("ID", "v1"), sep="(?<=\\d)(?![0-9])") %>%
   gather(key, val,  -one_of("ID", "v1"))  %>%
   unite(key_v1, key, v1) %>%
   spread(key_v1, val)
#  ID X1_l X1_r X2_l X2_r X3_l X3_r X4_l X4_r
#1  1    1    2    5    6    9   10   13   14
#2  2    4    3    8    7   12   11   16   15


问:
Sum integer list when next integer is the same value
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

```<code>input1 = [int(i) for i in str(1234441122)]
x= 0
</code>```

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

答:
Another way using itertools.groupby

```<code>l = [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]
from itertools import groupby
sum(sum(g)-k for k,g in groupby(l))
#11
</code>```

Body:
So I need to have a code that checks one integer, and checks if the integer after it is the same value. If so, it will add the value to x.

input1 = [int(i) for i in str(1234441122)]
x= 0

So my code currently gives the result [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]. I want it to give the result of x = 0+4+4+1+2.
I do not know any way to do that.

Body:
Another way using itertools.groupby

l = [1, 2, 3, 4, 4, 4, 1, 1 ,2 ,2]
from itertools import groupby
sum(sum(g)-k for k,g in groupby(l))
#11


问:
UITabBar width using Storyboard
I want to get a UITabBar's width in order to get the width of an item.
For this, I'm using:

```<code>let itemWidth = tabBar.frame.size.width / tabBar.items.count
</code>```

However the width I get seems wrong...

The tabBar.frame.size.width gives me the width of the tabBar in the Storyboard depending of the preview...

In other words, if my Storyboard preview is set to iPad Pro 12.9", tabBar.frame.size.width will return 1024.0 even if the code is run on an iPhone 5s.

What am I missing here?

答:
UITabBar's dimensions will only be accurate after its layoutSubviews() function was executed. Subclass UITabBarController and access the tab bar's size in viewDidLayoutSubviews().

```<code>class CustomTabBarController: UITabBarController {
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        print(tabBar.frame.width) //this will print the actual width
    }
}
</code>```

Title: UITabBar width using Storyboard

Body:
I want to get a UITabBar's width in order to get the width of an item.
For this, I'm using:

let itemWidth = tabBar.frame.size.width / tabBar.items.count

However the width I get seems wrong...

The tabBar.frame.size.width gives me the width of the tabBar in the Storyboard depending of the preview...

In other words, if my Storyboard preview is set to iPad Pro 12.9", tabBar.frame.size.width will return 1024.0 even if the code is run on an iPhone 5s.

What am I missing here?

Body:
UITabBar's dimensions will only be accurate after its layoutSubviews() function was executed. Subclass UITabBarController and access the tab bar's size in viewDidLayoutSubviews().

class CustomTabBarController: UITabBarController {
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        print(tabBar.frame.width) //this will print the actual width
    }
}


问:
In iOS, how do I reference an object in a view that is created with a xib file?
I have a view controller that is instantiated in appDelegate and pushed onto a navigation controller. The view controller's view is created with a xib file. The xib file puts a UILabel on the view (among other things). Now I need to set the label's text property programatically but I don't see how to get a reference to it. How do I reference the label object?

I'm using xcode 3.2.5 and building an iPad app.

答:
You do this with what's called an "outlet". You define them in your controller, mark them clearly as IBOutlet and then connect them in Interface Builder to your file owner (or other delegate object created in IB).

For instance, in your FooController.m you might have this:

```<code>@interface FooController ()
@property (nonatomic, weak) IBOutlet UILabel* fooLabel;
@end
</code>```

Then you would select your label, and either control drag from it to the file owner, or go to its connections tab, and drag from the + under referencing outlet, to the file owner and select the fooLabel.

UPDATE: Code sample changed to reflect modern way of handling this case.

Body:
You do this with what's called an "outlet". You define them in your controller, mark them clearly as IBOutlet and then connect them in Interface Builder to your file owner (or other delegate object created in IB).

For instance, in your FooController.m you might have this:

@interface FooController ()
@property (nonatomic, weak) IBOutlet UILabel* fooLabel;
@end

Then you would select your label, and either control drag from it to the file owner, or go to its connections tab, and drag from the + under referencing outlet, to the file owner and select the fooLabel.

UPDATE: Code sample changed to reflect modern way of handling this case.


问:
Excel formula to get number of days between two dates in months with precision
what's the formula to get number of days between two dates in months with days precision.

For example: the number of days between 01-01-2017 & 14-02-2017 these two dates is 45 days. (31 days + 14 days - including both) So I'm expecting 1 month 14 days as output. So the format should be 1.14 (1 month 14 days)

Edit:
There is no assumption of 30 days in a month. I'm expecting exact calendar difference.

答:
With data in A1 and B1, in C1 enter:

```<code>=DATEDIF(A1,B1,"m") & "." & DATEDIF(A1,B1,"md")
</code>```

EDIT#1:

The formula gives a text value.  To convert to number and preserve formatting, select the cells in column C containing the formula and run this short macro:

```<code>Sub KonverToNumber()
    Dim r As Range, L As Long, T As String
    Dim rr As Range

    For Each r In Selection
        Set rr = r.Offset(0, 1)
        T = r.Text
        v = CDbl(T)
        L = Len(Split(T, ".")(1))
        If L = 2 Then
           rr.NumberFormat = "0.00"
        Else
            rr.NumberFormat = "0.0"
        End If
        rr.Value = v
    Next r
End Sub
</code>```

The results will be in column D

Body:
With data in A1 and B1, in C1 enter:

=DATEDIF(A1,B1,"m") & "." & DATEDIF(A1,B1,"md")

EDIT#1:

The formula gives a text value.  To convert to number and preserve formatting, select the cells in column C containing the formula and run this short macro:

Sub KonverToNumber()
    Dim r As Range, L As Long, T As String
    Dim rr As Range

    For Each r In Selection
        Set rr = r.Offset(0, 1)
        T = r.Text
        v = CDbl(T)
        L = Len(Split(T, ".")(1))
        If L = 2 Then
           rr.NumberFormat = "0.00"
        Else
            rr.NumberFormat = "0.0"
        End If
        rr.Value = v
    Next r
End Sub

The results will be in column D


问:
Why is garbage collector allowed to collect seemingly referenced objects with a finalizer?
This question is basically why we need GC.KeepAlive() in the first place.

Here's where we need it. We have a wrapper for some unmanaged resource

```<code>public class CoolWrapper
{
     public CoolWrapper()
     {
         coolResourceHandle = UnmanagedWinApiCode.CreateCoolResource();
         if (coolResourceHandle == IntPtr.Zero)
         {
             // something went wrong, throw exception
         }
     }

     ~CoolWrapper()
     {
         UnmanagedWinApiCode.DestroyCoolResource(coolResource);
     }

     public void DoSomething()
     {
         var result = UnmanagedWinApiCode.DoSomething(coolResource);
         if (result == 0)
         {
             // something went wrong, throw exception
         }
     }

     private IntPtr coolResourceHandle;
}
</code>```

and our code uses that wrapper:

```<code>var wrapper = CoolWrapper();
wrapper.DoSomething();
</code>```

and if this code is run in Release configuration and not under debugger then it may so happen that code optimizer sees that the reference is not actually used after this code and also that coolResourceHandle member variable is not accessed (by managed code) after it was read inside DoSomething() and its value was passed into unmanaged code and so the following happens:

DoSomething() is called

coolResourceHandle is read

garbage collection suddenly starts

~CoolWrapper() runs

UnmanagedWinApiCode.DestroyCoolResource() runs and the resource is destroyed, the resource handle is invalidated

UnmanagedWinApiCode.DoSomething() runs using the value which now refers to a non-existing object (or maybe another object is created and assigned that handle)

The situation described above is actually possible and it's a race between a method of the object and a running garbage collection. No matter there's a local variable of reference type on stack - optimized code ignores that reference and the object becomes eligible for garbage collection immediately after coolResourceHandle was read inside DoSomething().

So, to prevent this we use GC.KeepAlive():

```<code>var wrapper = CoolWrapper();
wrapper.DoSomething();
GC.KeepAlive(wrapper);
</code>```

which makes the object non-eligible for GC until GC.KeepAlive() is invoked.

This of course requires that all users use GC.KeepAlive() everywhere which they will forget, so the right place is CoolWrapper.DoSomething():

```<code> public void DoSomething()
 {
     var result = UnmanagedWinApiCode.DoSomething(coolResource);
     GC.KeepAlive(this);
     if (result == 0)
     {
         // something went wrong, throw exception
     }
 }
</code>```

and this basically prevents the objects from getting eligible for GC while there's a method of this object running.

Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer? This would make life much easier yet we need to use GC.KeepAlive() instead.

Why is such aggressive collection allowed instead of ignoring objects which have methods currently running and a finalizer (and so likely to have problems in case there's a race as described above)?

答:
Consider any method that creates garbage and then spends a long time doing other things before exiting. The obvious example is the main method of any executable which may perform any number of initialization actions before entering some form of loop (such as a windows message loop) that won't exit for the entire lifetime of the process.

We want to be able to clean up that garbage. But that means we have to allow the GC to not treat methods as opaque - it has to be able to inspect a running method and know what is still in use right at this moment and only protect those items from being collected.

This is why the GC is "aggressive" and why object collection can happen at any time - even whilst the constructor is still running (assuming it will not access any instance members from the current point of its execution forwards).

Body:
This question is basically why we need GC.KeepAlive() in the first place.

Here's where we need it. We have a wrapper for some unmanaged resource

public class CoolWrapper
{
     public CoolWrapper()
     {
         coolResourceHandle = UnmanagedWinApiCode.CreateCoolResource();
         if (coolResourceHandle == IntPtr.Zero)
         {
             // something went wrong, throw exception
         }
     }

     ~CoolWrapper()
     {
         UnmanagedWinApiCode.DestroyCoolResource(coolResource);
     }

     public void DoSomething()
     {
         var result = UnmanagedWinApiCode.DoSomething(coolResource);
         if (result == 0)
         {
             // something went wrong, throw exception
         }
     }

     private IntPtr coolResourceHandle;
}

and our code uses that wrapper:

var wrapper = CoolWrapper();
wrapper.DoSomething();

and if this code is run in Release configuration and not under debugger then it may so happen that code optimizer sees that the reference is not actually used after this code and also that coolResourceHandle member variable is not accessed (by managed code) after it was read inside DoSomething() and its value was passed into unmanaged code and so the following happens:

DoSomething() is called

coolResourceHandle is read

garbage collection suddenly starts

~CoolWrapper() runs

UnmanagedWinApiCode.DestroyCoolResource() runs and the resource is destroyed, the resource handle is invalidated

UnmanagedWinApiCode.DoSomething() runs using the value which now refers to a non-existing object (or maybe another object is created and assigned that handle)

The situation described above is actually possible and it's a race between a method of the object and a running garbage collection. No matter there's a local variable of reference type on stack - optimized code ignores that reference and the object becomes eligible for garbage collection immediately after coolResourceHandle was read inside DoSomething().

So, to prevent this we use GC.KeepAlive():

var wrapper = CoolWrapper();
wrapper.DoSomething();
GC.KeepAlive(wrapper);

which makes the object non-eligible for GC until GC.KeepAlive() is invoked.

This of course requires that all users use GC.KeepAlive() everywhere which they will forget, so the right place is CoolWrapper.DoSomething():

 public void DoSomething()
 {
     var result = UnmanagedWinApiCode.DoSomething(coolResource);
     GC.KeepAlive(this);
     if (result == 0)
     {
         // something went wrong, throw exception
     }
 }

and this basically prevents the objects from getting eligible for GC while there's a method of this object running.

Why is this needed? Why wouldn't GC ignore the objects which have a method running at that moment and also have a finalizer? This would make life much easier yet we need to use GC.KeepAlive() instead.

Why is such aggressive collection allowed instead of ignoring objects which have methods currently running and a finalizer (and so likely to have problems in case there's a race as described above)?