问:
Java beginner question: Method for finding next available ID in an ArrayList
ive been given this Exercise: Make a method for finding the next available member ID in an ArrayList of member objects. I create the member ID's manually when creating a new member, and i can always assume that the members have been arranged in order by ID.
For example: If i have 4 members with ID's from 0-3, and i remove the 2nd member, the method should return 1. </p>

<p>Here is the messy part i have for now: </p>

```<code>public int getNextID (){
    int i;
    for(i = 0; i < members.size(); i++){
        if(i == members.get(i).getID()){
            i++;

        }
        else if(i != members.get(i).getID()){
            System.out.println("Next available ID:  " + i);

        } else {
            System.out.println("Next available ID: " + members.size());
            break;
        }
    }
    return i;
}
</code>```

答:
This solution provides a new Member ID from a List, where all MemberItems are sorted by ID. Item 0 in the List, must have the ID 0. Item 1 -> ID 1.
The new ID will always be the lowest available ID which is currently not assigned.

Solution 1

public int getNextID (){
    for(int i = 0; i < members.size(); i++){
        if(i < members.get(i).getID()){
            System.out.println("Next available ID:  " + i);
            // at this point we know this is the next id.
            // we can leave the method and return the next ID.
            return i;
        }
    }
    // we did not leave the loop (and method), because all id's are assigned.
    System.out.println("Next available ID:  " + members.size());
    return members.size();
}
```
<hr />
<h3>Solution 2 (Java 1.8+ Stream)</h3>
<p>If you prefer a 2 line java 8 stream solution you could also use this:</p>
<pre class="lang-java prettyprint-override"><code>public int getNextID() {
   Member m = members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().orElse(null);
   return (m != null ? members.indexOf(m) : members.size());
}
</code>```

Solution 3 (Java 1.8+ Stream)

or a 1 line stream solution:

public int getNextID() {
   return members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().map(m2 -> members.indexOf(m2)).orElse(members.size());
}
```
<hr />
<p>To say something about your code:
You are increasing <code>i</code> twice.
Once in the <code>for</code> statement at the end with <code>i++</code> and two lines below with <code>i++</code> again.
This way, you are skipping the index 1. if the first member has the same id like index.</p>
<hr />
<h3>Timings and testing</h3>
<p>For anyone who is interested into the comparision of timings between the 3 solutions. This are the Timings from my maschine with java1.8:</p>
```|----------------------------------------------------------------------|
| 10000 Items, Free Position 9998    | 10000 Items, Free Position 1    |
|----------------------------------------------------------------------|
| Solution1: ~2ms                    |  Solution1: ~0.005ms            |
| Solution2: ~65ms                   |  Solution2: ~0.05ms             |
| Solution3: ~60ms                   |  Solution3: ~0.06ms             |
|----------------------------------------------------------------------|
```
<p>Code to execute it on your maschine. will definitly result in different timing results, but the proportion should stay about the same.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.ArrayList;
import java.util.List;

public class Test {
    private static List<Member> members = new ArrayList<>();

    public static void main(String[] args) {
        members = getTestList(10000);

        warmUp();

        members.remove(9998);
        testSolutions();
        members.remove(1);
        testSolutions();

    }

    private static void warmUp() {
        for (int i = 0; i < 5; i++) {
            for (Member m : members) {
                // warm up cpu for iteration
            }
            members.forEach(Member::getID);
        }
    }

    private static void testSolutions() {
        long start = System.nanoTime();
        int result1 = getNextID();
        System.out.println("#1 Iterative result: " + result1 + " | in " + (System.nanoTime() - start) / 1000000.0 + "ms");
        start = System.nanoTime();
        Member m = members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().orElse(null);
        int result2 = m != null ? members.indexOf(m) : members.size();
        System.out.println("#2 Stream Result: " + result2 + " | in " + ((System.nanoTime() - start) / 1000000.0) + "ms");
        start = System.nanoTime();
        int result3 = members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().map(m2 -> members.indexOf(m2)).orElse(members.size());
        System.out.println("#3 Stream Result: " + result3 + " | in " + ((System.nanoTime() - start) / 1000000.0) + "ms");
    }

    private static int getNextID() {
        for (int i = 0; i < members.size(); i++) {
            if (i < members.get(i).getID()) {
                return i;
            }
        }
        return members.size();
    }

    private static List<Member> getTestList(int count) {
        List<Member> members = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            members.add(new Member(i));
        }
        return members;
    }

    private static class Member {
        private int id;

        public Member(int id) {
            this.id = id;
        }

        private int getID() {
            return id;
        }
    }
}
</code>```

Body:
ive been given this Exercise: Make a method for finding the next available member ID in an ArrayList of member objects. I create the member ID's manually when creating a new member, and i can always assume that the members have been arranged in order by ID.
For example: If i have 4 members with ID's from 0-3, and i remove the 2nd member, the method should return 1.

Here is the messy part i have for now:

public int getNextID (){
    int i;
    for(i = 0; i < members.size(); i++){
        if(i == members.get(i).getID()){
            i++;

        }
        else if(i != members.get(i).getID()){
            System.out.println("Next available ID:  " + i);

        } else {
            System.out.println("Next available ID: " + members.size());
            break;
        }
    }
    return i;
}

Body:
This solution provides a new Member ID from a List, where all MemberItems are sorted by ID. Item 0 in the List, must have the ID 0. Item 1 -> ID 1.
The new ID will always be the lowest available ID which is currently not assigned.

Solution 1

public int getNextID (){
    for(int i = 0; i < members.size(); i++){
        if(i < members.get(i).getID()){
            System.out.println("Next available ID:  " + i);
            // at this point we know this is the next id.
            // we can leave the method and return the next ID.
            return i;
        }
    }
    // we did not leave the loop (and method), because all id's are assigned.
    System.out.println("Next available ID:  " + members.size());
    return members.size();
}

Solution 2 (Java 1.8+ Stream)

If you prefer a 2 line java 8 stream solution you could also use this:

public int getNextID() {
   Member m = members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().orElse(null);
   return (m != null ? members.indexOf(m) : members.size());
}

Solution 3 (Java 1.8+ Stream)

or a 1 line stream solution:

public int getNextID() {
   return members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().map(m2 -> members.indexOf(m2)).orElse(members.size());
}

To say something about your code:
You are increasing i twice.
Once in the for statement at the end with i++ and two lines below with i++ again.
This way, you are skipping the index 1. if the first member has the same id like index.

Timings and testing

For anyone who is interested into the comparision of timings between the 3 solutions. This are the Timings from my maschine with java1.8:

|----------------------------------------------------------------------|
| 10000 Items, Free Position 9998    | 10000 Items, Free Position 1    |
|----------------------------------------------------------------------|
| Solution1: ~2ms                    |  Solution1: ~0.005ms            |
| Solution2: ~65ms                   |  Solution2: ~0.05ms             |
| Solution3: ~60ms                   |  Solution3: ~0.06ms             |
|----------------------------------------------------------------------|

Code to execute it on your maschine. will definitly result in different timing results, but the proportion should stay about the same.

import java.util.ArrayList;
import java.util.List;

public class Test {
    private static List<Member> members = new ArrayList<>();

    public static void main(String[] args) {
        members = getTestList(10000);

        warmUp();

        members.remove(9998);
        testSolutions();
        members.remove(1);
        testSolutions();

    }

    private static void warmUp() {
        for (int i = 0; i < 5; i++) {
            for (Member m : members) {
                // warm up cpu for iteration
            }
            members.forEach(Member::getID);
        }
    }

    private static void testSolutions() {
        long start = System.nanoTime();
        int result1 = getNextID();
        System.out.println("#1 Iterative result: " + result1 + " | in " + (System.nanoTime() - start) / 1000000.0 + "ms");
        start = System.nanoTime();
        Member m = members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().orElse(null);
        int result2 = m != null ? members.indexOf(m) : members.size();
        System.out.println("#2 Stream Result: " + result2 + " | in " + ((System.nanoTime() - start) / 1000000.0) + "ms");
        start = System.nanoTime();
        int result3 = members.stream().filter(member -> member.getID() != members.indexOf(member)).findFirst().map(m2 -> members.indexOf(m2)).orElse(members.size());
        System.out.println("#3 Stream Result: " + result3 + " | in " + ((System.nanoTime() - start) / 1000000.0) + "ms");
    }

    private static int getNextID() {
        for (int i = 0; i < members.size(); i++) {
            if (i < members.get(i).getID()) {
                return i;
            }
        }
        return members.size();
    }

    private static List<Member> getTestList(int count) {
        List<Member> members = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            members.add(new Member(i));
        }
        return members;
    }

    private static class Member {
        private int id;

        public Member(int id) {
            this.id = id;
        }

        private int getID() {
            return id;
        }
    }
}


来源: stackexchange

问:
How to pass an argument to a form class in Django?
I want to pass a product id to my form class to create a form with that item in my database.

My form:

class Order_form(forms.Form):
    def __init__(self, product_id,*args,**kwargs):

        self.add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all())
        super(Order_form,self).__init__(*args,**kwargs)
```

<p>The form above doesn't create anything but this form is creating exactly what I need. However, I need to pass the <code>product_id</code> dynamically, and not have to hardcode <code>1</code> as the id:</p>

```class Order_form2(forms.Form):
    add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = 1).add_option.all())
```

<p>PS: everything is working thanks to answer and comments below now my form looking like that</p>

```class Order_form(forms.Form):
    add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=None)
    def __init__(self, product_id,*args,**kwargs):
        super(Order_form, self).__init__(*args, **kwargs)
        self.fields['add_option'].queryset=product.objects.get(id = product_id).add_option.all()
```

答:
This is roughly what it should look like. </p>

```<code>class Order_form(forms.Form):
    def __init__(self, product_id,*args,**kwargs):
        super().__init__(product_id, *args, **kwargs) # This is the default stuff that forms.Form does

         # You need to add this part so that it edits the field after creation
        self.fields['add_option']= forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all())
        # super(Order_form,self).__init__(*args,**kwargs) this  would re-overwrite it so we don't want it here
</code>```

<p>This is generally how it's done in django. </p>

ContentLicense: CC BY-SA 4.0

Body:
I want to pass a product id to my form class to create a form with that item in my database.

My form:

class Order_form(forms.Form):
    def __init__(self, product_id,*args,**kwargs):

        self.add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all())
        super(Order_form,self).__init__(*args,**kwargs)

The form above doesn't create anything but this form is creating exactly what I need. However, I need to pass the product_id dynamically, and not have to hardcode 1 as the id:

class Order_form2(forms.Form):
    add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = 1).add_option.all())

PS: everything is working thanks to answer and comments below now my form looking like that

class Order_form(forms.Form):
    add_option = forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=None)
    def __init__(self, product_id,*args,**kwargs):
        super(Order_form, self).__init__(*args, **kwargs)
        self.fields['add_option'].queryset=product.objects.get(id = product_id).add_option.all()

Body:
This is roughly what it should look like.

class Order_form(forms.Form):
    def __init__(self, product_id,*args,**kwargs):
        super().__init__(product_id, *args, **kwargs) # This is the default stuff that forms.Form does

         # You need to add this part so that it edits the field after creation
        self.fields['add_option']= forms.ModelMultipleChoiceField(widget = forms.CheckboxSelectMultiple, required = False, queryset=product.objects.get(id = product_id).add_option.all())
        # super(Order_form,self).__init__(*args,**kwargs) this  would re-overwrite it so we don't want it here

This is generally how it's done in django.


问:
Showing Editors on click of a node in Xtratreelist
I am using the latest version of DevExpress XtratreeList and have a requirement of showing editors on click of each node on the tree. Please see this screenshot http://community.devexpress.com/forums/p/89574/310095.aspx

I am wondering how i can dynamically save and render a specific editor(rather a form) per node on the treelist. Clicking on "Friends" in the screenshot should bring up a different editor as compared to clicking on "Parties". Also, if a user tries to add more objects on the editor for Parties/Friends like say a Textbox/Listbox, it should be saved and come up fine when i click the nodes. Does anyone have ideas regarding how do i dynamically bring up different editors on click of a random node on the lefT?

答: This can be done by handling the TreeList's FocusedNodeChanged event.  All you need to do is to determine the current FocusedNode and its values and show the required editor.</p>

ContentLicense: CC BY-SA 3.0


问:
Invalid read of size 8 at .. by
it shows invalid read of size 8 at HTSize by my main function and it seems to work(it prints  0) for an empty hash but what I believe is the issue is that the initialized hash in my HTCreate is passed as an argument in HTSize but unitialized.

I've tried(not in the code that is shown) passing the argument as &Table with the definition HTSize(HThash**) but instead of solving it the programm doesn't run and valgrind shows "Address 0x0 is not stack'd, malloc'd or (recently) free'd" as well. Inside the function I also put a pointer T to the hash to dereference the **hash.I work in linux.

```<code>typedef char* KeyType;
typedef int HTItem;
typedef struct node{
    KeyType key;
    HTItem item;
    struct node *next;
}List;
typedef struct {
    List *head;
}TableEntry;
typedef TableEntry *HTHash;

HTHash* HTCreate(void);
int HTSize(HTHash);

int TABLESIZE = 10;

int main(void)
{
    HTItem *p;
    HTHash *Table = HTCreate();
    printf("%d\n",HTSize(*Table));
}

HTHash* HTCreate(void)
{
    int i;
    HTHash table = (HTHash)malloc(TABLESIZE*sizeof(TableEntry));
    HTHash *T;
    for(i=0;i<TABLESIZE;i++)
        table[i].head = NULL;
    T = &table;
    return T;
}

int HTSize(HTHash hash)
{
    int i,count=0;
    List *temp = (List*)malloc(sizeof(List));
    for(i=0;i<TABLESIZE;i++)
    {
        if(hash[i].head != NULL)
        {
            count++;
            temp = hash[i].head->next;
            while(temp != NULL)
            {
                count++;
                temp = temp->next;
            }
        }
    }
    return count;
}
</code>```

The mistake may be in HTCreate but Im'not sure.I checked if the hash gets initialized in the main function and it does.

答:
Your problem is effectivelly in HTCreate function: it returns &table which is local to the function.

Demo:

```<code>HTHash *HTCreate(void)
{
    int i;

    HTHash table = NULL;

    printf("&table before malloc: %p\n", &table);

    table = malloc(TABLESIZE*sizeof(TableEntry));

    printf("&table after  malloc: %p\n", &table);

    HTHash *T;

    for(i=0;i<TABLESIZE;i++)
        table[i].head = NULL;

    T = &table;
    return T;
}
</code>```

Will print:

```<code>&table before malloc: 0x7fff200eb818
&table after  malloc: 0x7fff200eb818
</code>```

We see that malloc is without effect on this value.

Since this is local to the function, using this in another function can cause anything (undefined behavior)

The good way to return what you need from the function is to return a HTHash type:

```<code>HTHash HTCreate(void)
{
    int i;

    HTHash table = malloc(TABLESIZE*sizeof(TableEntry));

    for(i=0;i<TABLESIZE;i++)
        table[i].head = NULL;

    return table;
}
</code>```

Looking what is done in it, I saw that this function can be simplified :

```<code>HTHash HTCreate(void)
{
    return calloc(TABLESIZE, sizeof(TableEntry));
}
</code>```

Title: Invalid read of size 8 at .. by

Body:
it shows invalid read of size 8 at HTSize by my main function and it seems to work(it prints  0) for an empty hash but what I believe is the issue is that the initialized hash in my HTCreate is passed as an argument in HTSize but unitialized.

I've tried(not in the code that is shown) passing the argument as &Table with the definition HTSize(HThash**) but instead of solving it the programm doesn't run and valgrind shows "Address 0x0 is not stack'd, malloc'd or (recently) free'd" as well. Inside the function I also put a pointer T to the hash to dereference the **hash.I work in linux.

typedef char* KeyType;
typedef int HTItem;
typedef struct node{
    KeyType key;
    HTItem item;
    struct node *next;
}List;
typedef struct {
    List *head;
}TableEntry;
typedef TableEntry *HTHash;

HTHash* HTCreate(void);
int HTSize(HTHash);

int TABLESIZE = 10;

int main(void)
{
    HTItem *p;
    HTHash *Table = HTCreate();
    printf("%d\n",HTSize(*Table));
}

HTHash* HTCreate(void)
{
    int i;
    HTHash table = (HTHash)malloc(TABLESIZE*sizeof(TableEntry));
    HTHash *T;
    for(i=0;i<TABLESIZE;i++)
        table[i].head = NULL;
    T = &table;
    return T;
}

int HTSize(HTHash hash)
{
    int i,count=0;
    List *temp = (List*)malloc(sizeof(List));
    for(i=0;i<TABLESIZE;i++)
    {
        if(hash[i].head != NULL)
        {
            count++;
            temp = hash[i].head->next;
            while(temp != NULL)
            {
                count++;
                temp = temp->next;
            }
        }
    }
    return count;
}

The mistake may be in HTCreate but Im'not sure.I checked if the hash gets initialized in the main function and it does.

Body:
Your problem is effectivelly in HTCreate function: it returns &table which is local to the function.

Demo:

HTHash *HTCreate(void)
{
    int i;

    HTHash table = NULL;

    printf("&table before malloc: %p\n", &table);

    table = malloc(TABLESIZE*sizeof(TableEntry));

    printf("&table after  malloc: %p\n", &table);

    HTHash *T;

    for(i=0;i<TABLESIZE;i++)
        table[i].head = NULL;

    T = &table;
    return T;
}

Will print:

&table before malloc: 0x7fff200eb818
&table after  malloc: 0x7fff200eb818

We see that malloc is without effect on this value.

Since this is local to the function, using this in another function can cause anything (undefined behavior)

The good way to return what you need from the function is to return a HTHash type:

HTHash HTCreate(void)
{
    int i;

    HTHash table = malloc(TABLESIZE*sizeof(TableEntry));

    for(i=0;i<TABLESIZE;i++)
        table[i].head = NULL;

    return table;
}

Looking what is done in it, I saw that this function can be simplified :

HTHash HTCreate(void)
{
    return calloc(TABLESIZE, sizeof(TableEntry));
}


问:
Remove duplicate elements by class with JQuery
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

```<code><div class="film-time-list">
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">5.20pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Thur30May">Thur 30 May</span>
<a class="film-tickets" href="#">5.20pm</a>
</div>
</code>```

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

```<code>$('.couldBeAnyClass').not(':first').remove();
</code>```

Any pointers would be great!

My output would be:

```<code>Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm
</code>```

答:
Using a set so it does not have to be ordered. Considering the date is the second class passed to the html element.

const dateSet = new Set();
$(".film-date").each((idx, el) => {
  if(dateSet.has(el.classList[1])) { el.remove(); }
  else { dateSet.add(el.classList[1]); }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="film-time-list">
<span class="film-date Wed29May">Wed 29 May</span>
2.30pm
<span class="film-date Wed29May">Wed 29 May</span>
5.20pm
<span class="film-date Thur30May">Wed 29 May</span>
2.30pm
<span class="film-date Thur30May">Wed 29 May</span>
5.20pm
</div></code>```

Body:
I want to delete duplicate span.film-date elements using the secondary class. For example I only want to keep the first span with the classes of "film-date Wed29May" and the first span with the classes of "film-date Thur30May".

Wed 29 May
2.30pm
Wed 29 May
5.20pm
Thur 30 May
2.30pm
Thur 30 May
5.20pm

I thought this would be straight forward enough but as the class that is output dynamically could be any date this snippet won't work which was my initial thought.

$('.couldBeAnyClass').not(':first').remove();

Any pointers would be great!

My output would be:

Wed 29 May 2.30pm 5.20pm
Thur 30 May 2.30pm 5.20pm

Body:
Using a set so it does not have to be ordered. Considering the date is the second class passed to the html element.

const dateSet = new Set();
$(".film-date").each((idx, el) => {
  if(dateSet.has(el.classList[1])) { el.remove(); }
  else { dateSet.add(el.classList[1]); }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="film-time-list">
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Wed29May">Wed 29 May</span>
<a class="film-tickets" href="#">5.20pm</a>
<span class="film-date Thur30May">Wed 29 May</span>
<a class="film-tickets" href="#">2.30pm</a>
<span class="film-date Thur30May">Wed 29 May</span>
<a class="film-tickets" href="#">5.20pm</a>
</div>


问:
What is the correct approach to check if array exists in JS?
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

```<code>if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}
</code>```

Error

```<code>TypeError: Cannot read property 'length' of undefined
</code>```

答:
Try swapping the order of the checks:</p>

```<code>if (Array.isArray(drugPrice.mailPrice.rejectMessage) && drugPrice.mailPrice.rejectMessage.length !== 0) {
                                        code goes here
}
</code>```

Body:
I'm getting the below error when I check the length of an array. What would be the correct approach?

main.js

if (drugPrice.mailPrice.rejectMessage.length !== 0 && Array.isArray(drugPrice.mailPrice.rejectMessage)) {
   //code goes here
}

Error

TypeError: Cannot read property 'length' of undefined

Body:
Try swapping the order of the checks:

if (Array.isArray(drugPrice.mailPrice.rejectMessage) && drugPrice.mailPrice.rejectMessage.length !== 0) {
                                        code goes here
}


问:
Need to design custom tabbar in swift 4 . - Update
I have created the custom class for UITabBar, to design raised button and tabbar strip. Actually İ need to give wave background effect behind the raised button. İ have already created circle and raised button but setting not accurate not wave flow effect. İmage and code attached.

Update:

I have attached my code for download and actual image(tabbar design I need included in assests).
Reference link: https://drive.google.com/file/d/1evDPYdG2fGiMohWohJR2BQJNsKJHStQy/view?usp=sharing

```<code>func createPathCircle() -> CGPath {

            let radius: CGFloat = 40.0
            let path = UIBezierPath()
            let centerWidth = self.frame.width / 2

            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: (centerWidth - radius * 2), y: 0))
            path.addArc(withCenter: CGPoint(x: centerWidth, y: 0), radius: radius, startAngle: CGFloat(180).degreesToRadians, endAngle: CGFloat(0).degreesToRadians, clockwise: true)
            path.addLine(to: CGPoint(x: self.frame.width, y: 0))
            path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
            path.addLine(to: CGPoint(x: 0, y: self.frame.height))
            path.close()
            return path.cgPath
        }
</code>```

Actual what İ need to achieve

need this

答:
Hmm, you just fixed its position on ViewController.swift, button.frame

Simple to decrease y-axis like this

```<code>button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - 80, width: 64, height: 64)
</code>```

Body:
I have created the custom class for UITabBar, to design raised button and tabbar strip. Actually İ need to give wave background effect behind the raised button. İ have already created circle and raised button but setting not accurate not wave flow effect. İmage and code attached.

Update:

I have attached my code for download and actual image(tabbar design I need included in assests).
Reference link: https://drive.google.com/file/d/1evDPYdG2fGiMohWohJR2BQJNsKJHStQy/view?usp=sharing

func createPathCircle() -> CGPath {

            let radius: CGFloat = 40.0
            let path = UIBezierPath()
            let centerWidth = self.frame.width / 2

            path.move(to: CGPoint(x: 0, y: 0))
            path.addLine(to: CGPoint(x: (centerWidth - radius * 2), y: 0))
            path.addArc(withCenter: CGPoint(x: centerWidth, y: 0), radius: radius, startAngle: CGFloat(180).degreesToRadians, endAngle: CGFloat(0).degreesToRadians, clockwise: true)
            path.addLine(to: CGPoint(x: self.frame.width, y: 0))
            path.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
            path.addLine(to: CGPoint(x: 0, y: self.frame.height))
            path.close()
            return path.cgPath
        }

Actual what İ need to achieve

need this

Body:
Hmm, you just fixed its position on ViewController.swift, button.frame

Simple to decrease y-axis like this

button.frame = CGRect.init(x: self.tabBar.center.x - 32, y: self.view.bounds.height - 80, width: 64, height: 64)


问:
Ajax and Laravel 500 (Internal server error)
I am trying to make a crud small application to learn ajax, but I am facing serious problems here.
Here are some snippets, when I click on submit, the form doesn't do anything, just show me error 500 in chrome's console.And if I try to show something in success ajax function the request it's showing "undefined".
Thank you so much!

Here is my controller

```<code>public function store(Request $request)
{
    $response = array(
        'msg' => 'Thank you nephew'
    );

    $request->validate([
        'name' => 'required|min:3',
        'mobile' => 'required',
        'address' => 'nullable',
        'email' => 'nullable'
    ]);

    $values = $request->all();

    echo $values;

    return Response::json($response);
}
</code>```

Here is my Ajax script

```<code><script>
    $('#create-form').on('submit', function (event) {
        event.preventDefault();

        let name = $("input[name=name]").val();
        let mobile = $("input[name=mobile]").val();
        let email = $("input[name=email]").val();
        let address = $("input[name=address]").val();

        console.log(name);

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });

        $.ajax({
            type: 'POST',
            url: '{{ route('addresses.store') }}',
            data: {name: name, mobile: mobile, email: email, address: address, token: $('input[name="_token"]').val()},
            success: function (data) {
                console.log(data);
            }
        });
    });
</script>
</code>```

Here is the blade modal

```<code><div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Create address</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="result"></div>
                <form action="{{ route('addresses.store') }}" method="post" id="create-form">
                    @csrf

                    <div class="form-group">
                        <label for="">Name</label>
                        <input type="text" class="sequence-input" name="name"/>
                    </div>
                    <div class="form-group">
                        <label for="#">Mobile</label>
                        <input type="text" class="sequence-input" name="mobile"/>
                    </div>
                    <div class="form-group">
                        <label for="#">Address</label>
                        <textarea name="address" class="sequence-input" cols="30" rows="6"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="#">Email Address</label>
                        <input type="text" class="sequence-input" name="email"/>
                    </div>
                    <div class="form-group">
                        <button type="submit" id="create" class="sequence-btn sequence-btn--primary">Create</button>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="sequence-btn sequence-btn--danger" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

答:
Try using single quotes on the name's value let mobile = $("input[name='mobile']").val(); and so on

Or

```<code>$.ajax({
            type: 'POST',
            url: '{{ route('addresses.store') }}',
            data: $(this).serialize(),
            success: function (data) {
                console.log(data);
            }
        });
</code>```

Body:
I am trying to make a crud small application to learn ajax, but I am facing serious problems here.
Here are some snippets, when I click on submit, the form doesn't do anything, just show me error 500 in chrome's console.And if I try to show something in success ajax function the request it's showing "undefined".
Thank you so much!

Here is my controller

public function store(Request $request)
{
    $response = array(
        'msg' => 'Thank you nephew'
    );

    $request->validate([
        'name' => 'required|min:3',
        'mobile' => 'required',
        'address' => 'nullable',
        'email' => 'nullable'
    ]);

    $values = $request->all();

    echo $values;

    return Response::json($response);
}

Here is my Ajax script

Here is the blade modal

Create address

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <form action="{{ route('addresses.store') }}" method="post" id="create-form">
                    @csrf

                        Name
                        <input type="text" class="sequence-input" name="name"/>

                        Mobile
                        <input type="text" class="sequence-input" name="mobile"/>

                        Address
                        <textarea name="address" class="sequence-input" cols="30" rows="6"></textarea>

                        Email Address
                        <input type="text" class="sequence-input" name="email"/>

                        <button type="submit" id="create" class="sequence-btn sequence-btn--primary">Create</button>

                </form>

                <button type="button" class="sequence-btn sequence-btn--danger" data-dismiss="modal">Close</button>

Body:
Try using single quotes on the name's value let mobile = $("input[name='mobile']").val(); and so on

Or

$.ajax({
            type: 'POST',
            url: '{{ route('addresses.store') }}',
            data: $(this).serialize(),
            success: function (data) {
                console.log(data);
            }
        });


问:
Rails ActiveRecord update_attributes problems
I am trying to run the update_attributes for a particular object, but everytime I try to run my script, I get the following error: TypeError (can't convert String into Integer):

Here is the code I am working with

```<code>media = Media.find(params[:media_id])
media.update_attributes({:started_encode => false, :encode_success => false, :akamai => false})
</code>```

Any idea why this keeps throwing that error?

答:
Which are the names of the Media columns table?

You may have found this problem:

http://ethernetflow.blogspot.com/2010/11/rails-typeerror-cant-convert-string.html

Basicaly, you cannot have a column named "HASH" in your table.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to run the update_attributes for a particular object, but everytime I try to run my script, I get the following error: TypeError (can't convert String into Integer):

Here is the code I am working with

media = Media.find(params[:media_id])
media.update_attributes({:started_encode => false, :encode_success => false, :akamai => false})

Any idea why this keeps throwing that error?


问:
How can I model the Circle packing problem with pyomo?
Circle packing problem in a circle container with minimal radius </p>

答: Take a look at these strip packing examples. The circle packing problem will be similar.</p>


问:
Where to find a dataset with literal data already annotated with dbpedia property concepts (having their range in float or int)?
I'm working on a project that tries to map DBpedia concepts to table data columns. Specifically I wanted to map literal(numerical values; float, int..). Therefore I need adequate number of data to build a background knowledge base. I extract some data from T2D-golden-dataset as the given format at the end of this description. Actually I should use them as a bench mark for testing and it only contains less than 20 columns from overall tables. Could anyone help me to find such a literal valued and dbpedia annotated dataset ?

Literal valued dbpedia ranges;

```<code>"http://www.w3.org/2001/XMLSchema#float"
"http://www.w3.org/2001/XMLSchema#integer"
"http://www.w3.org/2001/XMLSchema#positiveInteger"
"http://www.w3.org/2001/XMLSchema#integer"
</code>```

Some properties having these ranges;

```<code>"http://dbpedia.org/ontology/speaker",
"http://dbpedia.org/ontology/ranking",
"http://dbpedia.org/ontology/humanDevelopmentIndex",
"http://dbpedia.org/ontology/numberOfPlatformLevels",
"http://dbpedia.org/ontology/enginePower",
"http://dbpedia.org/ontology/graySubject",
"http://dbpedia.org/ontology/shareOfAudience",
"http://dbpedia.org/ontology/percentageLiteracyWomen",.........
</code>```

Sample examples I need to found or somehow generate is an array corresponding to concepts given above. For an example;

```<code> "http://dbpedia.org/ontology/enginePower" : ["220", "125", "1300",....],
 "http://dbpedia.org/ontology/humanDevelopmentIndex" : ["0.34", "0.78", "0.98", ...]
</code>```

I don't need that exact format. It would be great If I can find enough number of data tables given as T2D golden dataset for dbpedia.

答:
This query starts you down the road, as it gets you 100 typed literal values for <http://dbpedia.org/ontology/populationTotal>, which are all typed as <http://www.w3.org/2001/XMLSchema#nonNegativeInteger> --

```<code>PREFIX  dbo:  <http://dbpedia.org/ontology/>

SELECT DISTINCT ?value
WHERE
  { ?subject dbo:populationTotal ?value }
LIMIT 100
</code>```

This rather more complex (and expensive) query gets you something like the end result I think you want -- but you will need to run it a number of times, for a few predicates at a time, to get everything you're asking for from the public endpoint.  If needed, you could spin up your own DBpedia mirror instance in the AWS cloud, and adjust Virtuoso's timeouts and other limits, in order to build and run one query that would deliver one giant result set.

```<code>PREFIX  xsd:  <http://www.w3.org/2001/XMLSchema#>
PREFIX  dbo:  <http://dbpedia.org/ontology/>

SELECT # DISTINCT ?predicate ?value ?value_type ?value_str
                  ?predicate ?value_type ( GROUP_CONCAT ( DISTINCT ?value_str ; separator=", " ) AS ?values )
WHERE
  { ?subject  ?predicate  ?value
    VALUES ( ?predicate ) { ( dbo:numberOfPlatformLevels )
                            ( dbo:shareOfAudience )
                            ( dbo:populationTotal )
                          }
      BIND ( DATATYPE ( ?value ) AS ?value_type )
      BIND (      STR ( ?value ) AS ?value_str )
  }
GROUP BY ?predicate ?value_type
ORDER BY ?predicate ?value_type
LIMIT 1000
</code>```

Body:
I'm working on a project that tries to map DBpedia concepts to table data columns. Specifically I wanted to map literal(numerical values; float, int..). Therefore I need adequate number of data to build a background knowledge base. I extract some data from T2D-golden-dataset as the given format at the end of this description. Actually I should use them as a bench mark for testing and it only contains less than 20 columns from overall tables. Could anyone help me to find such a literal valued and dbpedia annotated dataset ?

Literal valued dbpedia ranges;

"http://www.w3.org/2001/XMLSchema#float"
"http://www.w3.org/2001/XMLSchema#integer"
"http://www.w3.org/2001/XMLSchema#positiveInteger"
"http://www.w3.org/2001/XMLSchema#integer"

Some properties having these ranges;

"http://dbpedia.org/ontology/speaker",
"http://dbpedia.org/ontology/ranking",
"http://dbpedia.org/ontology/humanDevelopmentIndex",
"http://dbpedia.org/ontology/numberOfPlatformLevels",
"http://dbpedia.org/ontology/enginePower",
"http://dbpedia.org/ontology/graySubject",
"http://dbpedia.org/ontology/shareOfAudience",
"http://dbpedia.org/ontology/percentageLiteracyWomen",.........

Sample examples I need to found or somehow generate is an array corresponding to concepts given above. For an example;

 "http://dbpedia.org/ontology/enginePower" : ["220", "125", "1300",....],
 "http://dbpedia.org/ontology/humanDevelopmentIndex" : ["0.34", "0.78", "0.98", ...]

I don't need that exact format. It would be great If I can find enough number of data tables given as T2D golden dataset for dbpedia.

Body:
This query starts you down the road, as it gets you 100 typed literal values for <http://dbpedia.org/ontology/populationTotal>, which are all typed as <http://www.w3.org/2001/XMLSchema#nonNegativeInteger> --

PREFIX  dbo:  <http://dbpedia.org/ontology/>

SELECT DISTINCT ?value
WHERE
  { ?subject dbo:populationTotal ?value }
LIMIT 100

<a href="http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&qtxt=PREFIX%20%20xsd%3A%20%20%3Chttp%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%23%3E%0D%0APREFIX%20%20dbo%3A%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0A%0D%0ASELECT%20%23%20DISTINCT%20%3Fpredicate%20%3Fvalue%20%3Fvalue_type%20%3Fvalue_str%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Fpredicate%20%3Fvalue_type%20%28%20GROUP_CONCAT%20%28%20DISTINCT%20%3Fvalue_str%20%3B%20separator%3D%22%2C%20%22%20%29%20AS%20%3Fvalues%20%29%0D%0AWHERE%20%0D%0A%20%20%7B%20%3Fsubject%20%20%3Fpredicate%20%20%3Fvalue%20%0D%0A%20%20%20%20VALUES%20%28%20%3Fpredicate%20%29%20%7B%20%28%20dbo%3AnumberOfPlatformLevels%20%29%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%28%20dbo%3AshareOfAudience%20%29%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%28%20dbo%3ApopulationTotal%20%29%20%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%0D%0A%23%20%20%20%20FILTER%20%28%20DATATYPE%20%28%20%3Fvalue%20%29%20%3D%20xsd%3AnonNegativeInteger%20%29%0D%0A%20%20%20%20%20%20BIND%20%28%20DATATYPE%20%28%20%3Fvalue%20%29%20AS%20%3Fvalue_type%20%29%0D%0A%20%20%20%20%20%20BIND%20%28%20%20%20%20%20%20STR%20%28%20%3Fvalue%20%29%20AS%20%3Fvalue_str%20%29%0D%0A%20%20%7D%20%0D%0AGROUP%20BY%20%3Fpredicate%20%3Fvalue_type%0D%0AORDER%20BY%20%3Fpredicate%20%3Fvalue_type%0D%0ALIMIT%201000&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=3000000&debug=on&run=%20Run%20Query%20" rel="nofollow noreferrer">This rather more complex (and expensive) query gets you <a href="http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=PREFIX%20%20xsd%3A%20%20%3Chttp%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%23%3E%0D%0APREFIX%20%20dbo%3A%20%20%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3E%0D%0A%0D%0ASELECT%20%23%20DISTINCT%20%3Fpredicate%20%3Fvalue%20%3Fvalue_type%20%3Fvalue_str%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Fpredicate%20%3Fvalue_type%20%28%20GROUP_CONCAT%20%28%20DISTINCT%20%3Fvalue_str%20%3B%20separator%3D%22%2C%20%22%20%29%20AS%20%3Fvalues%20%29%0D%0AWHERE%20%0D%0A%20%20%7B%20%3Fsubject%20%20%3Fpredicate%20%20%3Fvalue%20%0D%0A%20%20%20%20VALUES%20%28%20%3Fpredicate%20%29%20%7B%20%28%20dbo%3AnumberOfPlatformLevels%20%29%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%28%20dbo%3AshareOfAudience%20%29%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%28%20dbo%3ApopulationTotal%20%29%20%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D%0D%0A%23%20%20%20%20FILTER%20%28%20DATATYPE%20%28%20%3Fvalue%20%29%20%3D%20xsd%3AnonNegativeInteger%20%29%0D%0A%20%20%20%20%20%20BIND%20%28%20DATATYPE%20%28%20%3Fvalue%20%29%20AS%20%3Fvalue_type%20%29%0D%0A%20%20%20%20%20%20BIND%20%28%20%20%20%20%20%20STR%20%28%20%3Fvalue%20%29%20AS%20%3Fvalue_str%20%29%0D%0A%20%20%7D%20%0D%0AGROUP%20BY%20%3Fpredicate%20%3Fvalue_type%0D%0AORDER%20BY%20%3Fpredicate%20%3Fvalue_type%0D%0ALIMIT%201000&format=text%2Fhtml&CXML_redir_for_subjs=121&CXML_redir_for_hrefs=&timeout=3000000&debug=on&run=%20Run%20Query%20" rel="nofollow noreferrer">something like the end result I think you want -- but you will need to run it a number of times, for a few predicates at a time, to get everything you're asking for from the public endpoint.  If needed, you could spin up your own DBpedia mirror instance in the AWS cloud, and adjust Virtuoso's timeouts and other limits, in order to build and run one query that would deliver one giant result set.

PREFIX  xsd:  <http://www.w3.org/2001/XMLSchema#>
PREFIX  dbo:  <http://dbpedia.org/ontology/>

SELECT # DISTINCT ?predicate ?value ?value_type ?value_str
                  ?predicate ?value_type ( GROUP_CONCAT ( DISTINCT ?value_str ; separator=", " ) AS ?values )
WHERE
  { ?subject  ?predicate  ?value
    VALUES ( ?predicate ) { ( dbo:numberOfPlatformLevels )
                            ( dbo:shareOfAudience )
                            ( dbo:populationTotal )
                          }
      BIND ( DATATYPE ( ?value ) AS ?value_type )
      BIND (      STR ( ?value ) AS ?value_str )
  }
GROUP BY ?predicate ?value_type
ORDER BY ?predicate ?value_type
LIMIT 1000


问:
How to find all combinations in column and count occurrences in data
I am trying to find all actual combinations within my data of values in column 1.

I then want to count all occurrences of these by column 2.

It feels like R should be able to do this fairly quickly. I tried reading up on combn and expand.grid, but with no success. The main problem was I could not find any guidance on how to generate combinations within a column.

My data looks like:

```<code>Animal (n=57) | Person ID (n=1000)
Dog     | 0001
Cat     | 0004
Bird    | 0001
Snake   | 0002
Spider  | 0002
Cat     | 0003
Dog     | 0004
</code>```

Expected output is:

```<code>AnimalComb | CountbyID

Cat         | 1
DogBird     | 1
SnakeSpider | 1
CatDog      | 1
</code>```

EDIT deleted an erroneous entry for cat

答:
An option using data.table

```<code>library(data.table)
setDT(df)[,  .(AnimalComb = toString(unique(Animal)),
      CountbyID = .N/uniqueN(Animal)), by = PersonID]
</code>```

data

```<code>df <- structure(list(Animal = c("Dog", "Cat", "Bird", "Snake", "Spider",
"Cat", "Dog"), PersonID = c(1L, 4L, 1L, 2L, 2L, 3L, 4L)),
 class = "data.frame", row.names = c(NA, -7L))
</code>```

Body:
I am trying to find all actual combinations within my data of values in column 1.

I then want to count all occurrences of these by column 2.

It feels like R should be able to do this fairly quickly. I tried reading up on combn and expand.grid, but with no success. The main problem was I could not find any guidance on how to generate combinations within a column.

My data looks like:

Animal (n=57) | Person ID (n=1000)
Dog     | 0001
Cat     | 0004
Bird    | 0001
Snake   | 0002
Spider  | 0002
Cat     | 0003
Dog     | 0004

Expected output is:

AnimalComb | CountbyID

Cat         | 1
DogBird     | 1
SnakeSpider | 1
CatDog      | 1

EDIT deleted an erroneous entry for cat

Body:
An option using data.table

library(data.table)
setDT(df)[,  .(AnimalComb = toString(unique(Animal)),
      CountbyID = .N/uniqueN(Animal)), by = PersonID]

data

df <- structure(list(Animal = c("Dog", "Cat", "Bird", "Snake", "Spider",
"Cat", "Dog"), PersonID = c(1L, 4L, 1L, 2L, 2L, 3L, 4L)),
 class = "data.frame", row.names = c(NA, -7L))


问:
Split time value from json using java
I want to split the value 08:41:19 from below json response. How to split the value?</p>

```<code>{
  "parameters": [
    {
      "name": "CurrentLocalTime",
      "value": "2019-05-29 08:41:19",
      "dataType": 4,
      "parameterCount": 1,
      "message": "Success"
    }
  ],
  "statusCode": 200
}
</code>```

答:
Try this,</p>

```<code> JSONArray jSONArray = inputJSON.getJSONArray("parameters");
 int length = jSONArray.length();
  for (int i = 0; i < length; i++) {
        JSONObject jSONObject= jSONArray.getJSONObject(i);
        System.out.println(jSONObject.get("value").split("\\s")[1]);
    }
</code>```

Title: Split time value from json using java

Body:
I want to split the value 08:41:19 from below json response. How to split the value?

{
  "parameters": [
    {
      "name": "CurrentLocalTime",
      "value": "2019-05-29 08:41:19",
      "dataType": 4,
      "parameterCount": 1,
      "message": "Success"
    }
  ],
  "statusCode": 200
}

Body:
Try this,

 JSONArray jSONArray = inputJSON.getJSONArray("parameters");
 int length = jSONArray.length();
  for (int i = 0; i < length; i++) {
        JSONObject jSONObject= jSONArray.getJSONObject(i);
        System.out.println(jSONObject.get("value").split("\\s")[1]);
    }


问:
How to apply left join on two JSON objects in groovy script
I have two JSON files:

first.json

```<code>[
{"a":"1", "b": "tmp"},
{"a":"2", "b": "tmp"},
{"a":"3", "b": "tmp"}
]
</code>```

second.json

```<code>[
{"c":"1", "d": "tmp"},
{"c":"2", "d": "tmp"},
{"c":"4", "d": "tmp"}
]
</code>```

output.json

```<code>[
{"a":"1", "b": "tmp", "c": "1" , "d": "tmp"},
{"a":"2", "b": "tmp", "c": "2" , "d": "tmp"},
{"a":"3", "b": "tmp", "c": "" , "d": ""}
]
</code>```

I want to apply left join on two json files first.json and second.json on basis of two fields - "a" of first.json and "c" of second.json to get the output as output.json. How can I achieve the same using Groovy Script?

NOTE: I would like to achieve this in a single line if possible.

答:
You would need to do something like this:</p>

```<code>def firstJson = '''[
    {"a":"1", "b": "tmp"},
    {"a":"2", "b": "tmp"},
    {"a":"3", "b": "tmp"}
]'''

def secondJson = '''[
    {"c":"1", "d": "tmp"},
    {"c":"2", "d": "tmp"},
    {"c":"4", "d": "tmp"}
]'''

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def slurpy = new JsonSlurper()

def first = slurpy.parseText(firstJson)
def second = slurpy.parseText(secondJson)

def result = first.collect { f ->
    f + (second.find { it.c == f.a } ?: second[0].keySet().collectEntries { [it, ''] })
}

println JsonOutput.toJson(result)
</code>```

Body:
I have two JSON files:

first.json

[
{"a":"1", "b": "tmp"},
{"a":"2", "b": "tmp"},
{"a":"3", "b": "tmp"}
]

second.json

[
{"c":"1", "d": "tmp"},
{"c":"2", "d": "tmp"},
{"c":"4", "d": "tmp"}
]

output.json

[
{"a":"1", "b": "tmp", "c": "1" , "d": "tmp"},
{"a":"2", "b": "tmp", "c": "2" , "d": "tmp"},
{"a":"3", "b": "tmp", "c": "" , "d": ""}
]

I want to apply left join on two json files first.json and second.json on basis of two fields - "a" of first.json and "c" of second.json to get the output as output.json. How can I achieve the same using Groovy Script?

NOTE: I would like to achieve this in a single line if possible.

Body:
You would need to do something like this:

def firstJson = '''[
    {"a":"1", "b": "tmp"},
    {"a":"2", "b": "tmp"},
    {"a":"3", "b": "tmp"}
]'''

def secondJson = '''[
    {"c":"1", "d": "tmp"},
    {"c":"2", "d": "tmp"},
    {"c":"4", "d": "tmp"}
]'''

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def slurpy = new JsonSlurper()

def first = slurpy.parseText(firstJson)
def second = slurpy.parseText(secondJson)

def result = first.collect { f ->
    f + (second.find { it.c == f.a } ?: second[0].keySet().collectEntries { [it, ''] })
}

println JsonOutput.toJson(result)


问:
Using Case Statements As a Pivot - DB2 SQL
I want a list of motor carriers, with trailer equipment counts listed in separate columns. I am using case statements to categorize the different equipment types, but I'm getting multiple returns instead of seeing one return for each carrier.

I've tried ROW OVER () and get the same results.

```<code>SELECT C.ECP_CARRIER_IDENT_ID AS ECP_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'TR' THEN E.EQUIPMENT_CT END) AS TRACTORS,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'SV' THEN E.EQUIPMENT_CT END) AS VAN_TRLS,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'FT' THEN E.EQUIPMENT_CT END) AS FLATBEDS
FROM ECP_CARRIER C
JOIN ECP_CARRIER_EQUIPMENT E ON C.ECP_CARRIER_IDENT_ID = E.ECP_CARRIER_ID
WHERE CERTIFIED_FG = 1
GROUP BY C.ECP_CARRIER_IDENT_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
E.EQUIPMENT_TYPE_CD, E.EQUIPMENT_CT
</code>```

I would expect everything to be on one row, but this is the result that I'm getting

```<code>ECP_NB   CARRIER_NM     MC_NB    DOT_NB  TRACTORS VAN_TRLS   FLATBEDS
 1234   Bob's Trucking   606066     66    10
 1234   Bob's Trucking   606066     66              12
</code>```

答:
Use aggregation functions and fix the group by:

```<code>SELECT C.ECP_CARRIER_IDENT_ID AS ECP_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'TR' THEN E.EQUIPMENT_CT END) AS TRACTORS,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'SV' THEN E.EQUIPMENT_CT END) AS VAN_TRLS,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'FT' THEN E.EQUIPMENT_CT END) AS FLATBEDS
FROM ECP_CARRIER C JOIN
     ECP_CARRIER_EQUIPMENT E
     ON C.ECP_CARRIER_IDENT_ID = E.ECP_CARRIER_ID
WHERE CERTIFIED_FG = 1
GROUP BY C.ECP_CARRIER_IDENT_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB;
</code>```

The combination of keys in the GROUP BY should define each row you want in the result set.  You don't want separate rows for E.EQUIPMENT_TYPE_CD (for instance) so it should not be in the GROUP BY.

Body:
I want a list of motor carriers, with trailer equipment counts listed in separate columns. I am using case statements to categorize the different equipment types, but I'm getting multiple returns instead of seeing one return for each carrier.

I've tried ROW OVER () and get the same results.

SELECT C.ECP_CARRIER_IDENT_ID AS ECP_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'TR' THEN E.EQUIPMENT_CT END) AS TRACTORS,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'SV' THEN E.EQUIPMENT_CT END) AS VAN_TRLS,
(CASE WHEN E.EQUIPMENT_TYPE_CD = 'FT' THEN E.EQUIPMENT_CT END) AS FLATBEDS
FROM ECP_CARRIER C
JOIN ECP_CARRIER_EQUIPMENT E ON C.ECP_CARRIER_IDENT_ID = E.ECP_CARRIER_ID
WHERE CERTIFIED_FG = 1
GROUP BY C.ECP_CARRIER_IDENT_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
E.EQUIPMENT_TYPE_CD, E.EQUIPMENT_CT

I would expect everything to be on one row, but this is the result that I'm getting

ECP_NB   CARRIER_NM     MC_NB    DOT_NB  TRACTORS VAN_TRLS   FLATBEDS
 1234   Bob's Trucking   606066     66    10
 1234   Bob's Trucking   606066     66              12

Body:
Use aggregation functions and fix the group by:

SELECT C.ECP_CARRIER_IDENT_ID AS ECP_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'TR' THEN E.EQUIPMENT_CT END) AS TRACTORS,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'SV' THEN E.EQUIPMENT_CT END) AS VAN_TRLS,
       MAX(CASE WHEN E.EQUIPMENT_TYPE_CD = 'FT' THEN E.EQUIPMENT_CT END) AS FLATBEDS
FROM ECP_CARRIER C JOIN
     ECP_CARRIER_EQUIPMENT E
     ON C.ECP_CARRIER_IDENT_ID = E.ECP_CARRIER_ID
WHERE CERTIFIED_FG = 1
GROUP BY C.ECP_CARRIER_IDENT_ID, C.CARRIER_NM, C.MC_NB, C.DOT_NB;

The combination of keys in the GROUP BY should define each row you want in the result set.  You don't want separate rows for E.EQUIPMENT_TYPE_CD (for instance) so it should not be in the GROUP BY.


问:
Optional parameters on delegates doesn't work properly
Why this piece of code does not compile? </p>

```<code>delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}
</code>```

答:
Try this way:</p>

```<code>static int f(bool a)
{
  return 4;
}
</code>```

Body:
Why this piece of code does not compile?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}

Body:
Try this way:

static int f(bool a)
{
  return 4;
}


问:
How to read content from a file , uploaded using "Input Type" = file in HTML
I have a simple HTML form, where I have a field with browse button for uploading local files.

When fetching the uploaded file's path, it is showing as C:/fakepath/filename.xls. I came to know that it is the browser security that is not allowing to read exact file path from local Computer.

Is there any way that I can read contents from the Uploaded file.

```<code><input type="file" id = "FilePath" name="FilePath" size="18">
</code>```

So when I do document.getElementById("FilePath"). I got C:/fakepath/filename.xls.

Can anyone please help how to read file content from uploaded file

答: You're looking for the HTML5 File API.</p>

Body:
I have a simple HTML form, where I have a field with browse button for uploading local files.

When fetching the uploaded file's path, it is showing as C:/fakepath/filename.xls. I came to know that it is the browser security that is not allowing to read exact file path from local Computer.

Is there any way that I can read contents from the Uploaded file.

<input type="file" id = "FilePath" name="FilePath" size="18">

So when I do document.getElementById("FilePath"). I got C:/fakepath/filename.xls.

Can anyone please help how to read file content from uploaded file

Body: You're looking for the HTML5 File API.


问:
How to take the output of a function and put into pandas dataframe for further analysis?
I am using a function to find out how many rainfall events between magnitude thresholds result in flood events (denoted as 1 for flood, 0 for no flood). My data looks a bit like this:

```<code>      Date     rain      Flood
2010-01-01     0.2       0
2010-01-02     2.7       0
2010-01-03     11.3      1
2010-01-04     0.1       0
2010-01-05     5.3       1
</code>```

Here is my function:

```<code>def Thresholds(df, thresholds):
    lower, upper = thresholds
    u_mask = df['rain'] < upper
    l_mask = df['rain'] > lower
    between = df[l_mask & u_mask]
    return between['Flood'].value_counts()

my_intervals = np.array([(0.0,2.5),(2.5,5),(5,10),(10,15),(15,20),(20,30),(30,np.inf)])

dframes = [YEAR1,YEAR2,YEAR3]

for df in dframes:
    print('\n Dataframe')
    for interval in my_intervals:
        print(Thresholds(df,interval))
</code>```

which works well, in that it provides me with counts of flood or not for each threshold, here's the output from a full dataframe:

```<code>Dataframe
0.0    304
1.0      5
Name: Flood, dtype: int64
0.0    7
Name: Flood, dtype: int64
0.0    5
Name: Flood, dtype: int64
0.0    2
1.0    2
Name: Flood, dtype: int64
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)
</code>```

However the output is not in a form that I can do further calculations on. For example, I want to calculate the frequentist probability of floods occurring at each rainfall magnitude. To do this I anticipate needing to have the data in a dataframe, with columns for flood, or not, and rows titled by rainfall magnitude range (in this case labelled Threshold). So something like this:

```<code>Threshold     '1'     '0'
      2.5      0       2
      5.0      0       1
     10.0      1       0
     15.0      1       0
</code>```

Any ideas out there? Thanks a lot in advance :)

答:
So you can store them into list then concat it back

```<code>l=[]
x=[]
for df in dframes:
    print('\n Dataframe')
    for interval in my_intervals:
        l.append(Thresholds(df,interval))
        x.append(interval[0])

pd.concat(l,axis=1,keys=x)
</code>```

Update

```<code>d = []
for df in dframes:
    print('\n Dataframe')
    l = []
    x = []
    for interval in my_intervals:
        l.append(Thresholds(df,interval))
        x.append(interval[0])

    d.append(pd.concat(l,axis=1,keys=x))

pd.concat(d,keys=list(range(len(dframes))))
</code>```

Body:
I am using a function to find out how many rainfall events between magnitude thresholds result in flood events (denoted as 1 for flood, 0 for no flood). My data looks a bit like this:

      Date     rain      Flood
2010-01-01     0.2       0
2010-01-02     2.7       0
2010-01-03     11.3      1
2010-01-04     0.1       0
2010-01-05     5.3       1

Here is my function:

def Thresholds(df, thresholds):
    lower, upper = thresholds
    u_mask = df['rain'] < upper
    l_mask = df['rain'] > lower
    between = df[l_mask & u_mask]
    return between['Flood'].value_counts()

my_intervals = np.array([(0.0,2.5),(2.5,5),(5,10),(10,15),(15,20),(20,30),(30,np.inf)])

dframes = [YEAR1,YEAR2,YEAR3]

for df in dframes:
    print('\n Dataframe')
    for interval in my_intervals:
        print(Thresholds(df,interval))

which works well, in that it provides me with counts of flood or not for each threshold, here's the output from a full dataframe:

Dataframe
0.0    304
1.0      5
Name: Flood, dtype: int64
0.0    7
Name: Flood, dtype: int64
0.0    5
Name: Flood, dtype: int64
0.0    2
1.0    2
Name: Flood, dtype: int64
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)
Series([], Name: Flood, dtype: int64)

However the output is not in a form that I can do further calculations on. For example, I want to calculate the frequentist probability of floods occurring at each rainfall magnitude. To do this I anticipate needing to have the data in a dataframe, with columns for flood, or not, and rows titled by rainfall magnitude range (in this case labelled Threshold). So something like this:

Threshold     '1'     '0'
      2.5      0       2
      5.0      0       1
     10.0      1       0
     15.0      1       0

Any ideas out there? Thanks a lot in advance :)

Body:
So you can store them into list then concat it back

l=[]
x=[]
for df in dframes:
    print('\n Dataframe')
    for interval in my_intervals:
        l.append(Thresholds(df,interval))
        x.append(interval[0])

pd.concat(l,axis=1,keys=x)

Update

d = []
for df in dframes:
    print('\n Dataframe')
    l = []
    x = []
    for interval in my_intervals:
        l.append(Thresholds(df,interval))
        x.append(interval[0])

    d.append(pd.concat(l,axis=1,keys=x))

pd.concat(d,keys=list(range(len(dframes))))


问:
AWS Elastic Beanstalk - error requirements.txt
When I try to deploy my Amazon Web Services Elastic Beanstalk project (Python + Django), I get the following error:

```<code> 2016-09-14 14:46:37,244 ERROR    Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1
  Traceback (most recent call last):
    File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main
      install_dependencies()
    File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies
      check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True)
    File "/usr/lib64/python2.7/subprocess.py", line 540, in check_call
      raise CalledProcessError(retcode, cmd)
  CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (Executor::NonZeroExitStatus)
</code>```

I had this error a few months ago and I simply changed my configuration in .ebextensions which enabled the deployment to work correctly (problem was postgresql93-devel missing):

```<code>packages:
    yum:
        git: []
        postgresql93-devel: []
        libffi-devel: []
</code>```

I guess AWS has an issue with one or more of my libraries in requirements.txt- I tried installing/deinstalling some of them to find the one that causes the troubles, but haven't managed yet. This is my requirements.txt:

```<code>awsebcli==3.7.7
beautifulsoup4==4.4.1
boto==2.40.0
botocore==1.4.40
cement==2.8.2
cffi==1.5.2
colorama==0.3.7
cryptography==1.3.1
Django==1.9.4
django-storages==1.4.1
docker-py==1.7.2
dockerpty==0.4.1
docopt==0.6.2
docutils==0.12
enum34==1.1.2
future==0.15.2
futures==3.0.5
gax-google-logging-v2==0.8.1
gax-google-pubsub-v1==0.8.1
google-api-python-client==1.5.0
google-gax==0.13.0
googleads==3.13.0
googleapis-common-protos==1.3.4
grpc-google-logging-v2==0.8.1
grpc-google-pubsub-v1==0.8.1
grpcio==1.0.0
httplib2==0.9.2
idna==2.1
ipaddress==1.0.16
jmespath==0.9.0
oauth2client==2.0.1
pathspec==0.3.4
ply==3.8
protobuf==3.0.0
psycopg2==2.6.1
pyasn1==0.1.9
pyasn1-modules==0.0.8
pycparser==2.14
pyOpenSSL==16.0.0
PySocks==1.5.6
python-dateutil==2.5.3
pytz==2016.2
PyYAML==3.11
requests==2.9.1
rsa==3.4
s3transfer==0.1.4
semantic-version==2.5.0
simplejson==3.8.2
six==1.10.0
suds-jurko==0.6
texttable==0.8.4
uritemplate==0.6
websocket-client==0.37.0
xmltodict==0.10.1
</code>```

My guess is that the issue comes from one of these libraries (but I might be wrong!):

```<code>future==0.15.2
futures==3.0.5
gax-google-logging-v2==0.8.1
gax-google-pubsub-v1==0.8.1
google-gax==0.13.0
googleapis-common-protos==1.3.4
grpc-google-logging-v2==0.8.1
grpc-google-pubsub-v1==0.8.1
grpcio==1.0.0
ply==3.8
protobuf==3.0.0
s3transfer==0.1.4
</code>```

The Django project works perfectly locally. My issue is only with the AWS Elastic Beanstalk deployment.

Please let me know if you have any idea.

答:
I see the same issue here, it's the future library. If you look at the AWS EB server error log (/var/log/httpd/error_log) you can see the error.

python3 / django2 don't play well with the future module, but awsebcli insists on it.

I solve it here by NOT installing awsebcli to the virtual environment. You then need to deploy using the local environment (where awsebcli is installed).

Seems like we should have an update for AWSEBCLI to solve this eventually.

Body:
When I try to deploy my Amazon Web Services Elastic Beanstalk project (Python + Django), I get the following error:

 2016-09-14 14:46:37,244 ERROR    Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1
  Traceback (most recent call last):
    File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 22, in main
      install_dependencies()
    File "/opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py", line 18, in install_dependencies
      check_call('%s install -r %s' % (os.path.join(APP_VIRTUAL_ENV, 'bin', 'pip'), requirements_file), shell=True)
    File "/usr/lib64/python2.7/subprocess.py", line 540, in check_call
      raise CalledProcessError(retcode, cmd)
  CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 (Executor::NonZeroExitStatus)

I had this error a few months ago and I simply changed my configuration in .ebextensions which enabled the deployment to work correctly (problem was postgresql93-devel missing):

packages:
    yum:
        git: []
        postgresql93-devel: []
        libffi-devel: []

I guess AWS has an issue with one or more of my libraries in requirements.txt- I tried installing/deinstalling some of them to find the one that causes the troubles, but haven't managed yet. This is my requirements.txt:

awsebcli==3.7.7
beautifulsoup4==4.4.1
boto==2.40.0
botocore==1.4.40
cement==2.8.2
cffi==1.5.2
colorama==0.3.7
cryptography==1.3.1
Django==1.9.4
django-storages==1.4.1
docker-py==1.7.2
dockerpty==0.4.1
docopt==0.6.2
docutils==0.12
enum34==1.1.2
future==0.15.2
futures==3.0.5
gax-google-logging-v2==0.8.1
gax-google-pubsub-v1==0.8.1
google-api-python-client==1.5.0
google-gax==0.13.0
googleads==3.13.0
googleapis-common-protos==1.3.4
grpc-google-logging-v2==0.8.1
grpc-google-pubsub-v1==0.8.1
grpcio==1.0.0
httplib2==0.9.2
idna==2.1
ipaddress==1.0.16
jmespath==0.9.0
oauth2client==2.0.1
pathspec==0.3.4
ply==3.8
protobuf==3.0.0
psycopg2==2.6.1
pyasn1==0.1.9
pyasn1-modules==0.0.8
pycparser==2.14
pyOpenSSL==16.0.0
PySocks==1.5.6
python-dateutil==2.5.3
pytz==2016.2
PyYAML==3.11
requests==2.9.1
rsa==3.4
s3transfer==0.1.4
semantic-version==2.5.0
simplejson==3.8.2
six==1.10.0
suds-jurko==0.6
texttable==0.8.4
uritemplate==0.6
websocket-client==0.37.0
xmltodict==0.10.1

My guess is that the issue comes from one of these libraries (but I might be wrong!):

future==0.15.2
futures==3.0.5
gax-google-logging-v2==0.8.1
gax-google-pubsub-v1==0.8.1
google-gax==0.13.0
googleapis-common-protos==1.3.4
grpc-google-logging-v2==0.8.1
grpc-google-pubsub-v1==0.8.1
grpcio==1.0.0
ply==3.8
protobuf==3.0.0
s3transfer==0.1.4

The Django project works perfectly locally. My issue is only with the AWS Elastic Beanstalk deployment.

Please let me know if you have any idea.


问:
Is the Azure notification hub available to use?
We are developing a website and would like to use the Azure portal notification module. Does anyone know what this is built with and if we could implement this on our site rather than building from scratch? We have some some processes that take some time so want users to be able to go off and do other things and come back when it's completed.  We host our product on Azure so if this is using an Azure feature then we can use this also.

答:
The question is tagged for Azure Notification Hubs, but the screen shot you showing is for the notification section of the Azure Portal UI. I'm not aware that Microsoft makes the component available for third-party use.

Can you please remove the Notification Hubs tag from this issue as it's not related.


问:
Django: Update Model-Field everytime a Foreign-Key is associated with said model?
Lets suppose we have the following classes:

class Cart(models.Model):
      total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
```

<p>and</p>

```class CartItem(models.Model):
      cart = models.ForeignKey(Cart, related_name='items', on_delete=models.CASCADE)
```

<p>I'd like to <strong>update the total everytime a Cart-Item is added to the Cart</strong>. When/ How can I call my <em>addItUp()</em> method here?</p>

<p>Thought about using a signal like this, but this doesn't trigger:</p>

<pre class="lang-py prettyprint-override"><code>@receiver(post_save, sender=CartItem, weak=False)
def post_save_cartItem_receiver(sender, instance, *args, **kwargs):
    print("inside signal")
</code>```

Here's my very simplified addToCart() method:

```<code>    def add(self, request, product_id, cart_obj):
        product = get_object_or_404(Product, id=product_id)
        CartItem.objects.create(cart=cart_obj, ...)
        cart_obj.save()
        return True
</code>```

This is my first question here, if i can better my explanation please tell me.

答:
Welcome to StackOverflow.

A common problem that people have when creating triggers is that they forget (or don't know) to import signals in their apps.py file.  That's the only reason that I can imagine your signal wouldn't be triggering.

I imagine your apps.py file should look something like (if the name of your app is Shop):

```<code>from django.apps import AppConfig

class ShopConfig(AppConfig):
    name = 'Shop'

    def ready(self):
        import Shop.signals
</code>```

You can then use the post_save signal for a CartItem to get its related Cart, add up the total value, and save the Cart with a new total.

Body:
Lets suppose we have the following classes:

class Cart(models.Model):
      total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)

and

class CartItem(models.Model):
      cart = models.ForeignKey(Cart, related_name='items', on_delete=models.CASCADE)

I'd like to update the total everytime a Cart-Item is added to the Cart. When/ How can I call my addItUp() method here?

Thought about using a signal like this, but this doesn't trigger:

@receiver(post_save, sender=CartItem, weak=False)
def post_save_cartItem_receiver(sender, instance, *args, **kwargs):
    print("inside signal")

Here's my very simplified addToCart() method:

    def add(self, request, product_id, cart_obj):
        product = get_object_or_404(Product, id=product_id)
        CartItem.objects.create(cart=cart_obj, ...)
        cart_obj.save()
        return True

This is my first question here, if i can better my explanation please tell me.

Body:
Welcome to StackOverflow.

A common problem that people have when creating triggers is that they forget (or don't know) to import signals in their apps.py file.  That's the only reason that I can imagine your signal wouldn't be triggering.

I imagine your apps.py file should look something like (if the name of your app is Shop):

from django.apps import AppConfig

class ShopConfig(AppConfig):
    name = 'Shop'

    def ready(self):
        import Shop.signals

You can then use the post_save signal for a CartItem to get its related Cart, add up the total value, and save the Cart with a new total.


问:
firebase_analytics 0.0.4 which requires SDK version >=1.8.0 <2.0.0, version solving failed
I am trying to learn mobile devt using flutter, dat and firebase. SO as a start I downloaded the chat app code from here

But I can't seem to run the code via vscode and android studio. Can anyone please help me figure out how to run this.

error is:
VScode:

{
      "resource": "/C:/Users/Administrator/Downloads/flutter-chat-app-master/flutter-chat-app-master/lib/ChatMessageListItem.dart",
      "owner": "dart",
      "code": "uri_does_not_exist",
      "severity": 8,
      "message": "Target of URI doesn't exist: 'package:firebase_database/firebase_database.dart'.\nTry creating the file referenced by the URI, or Try using a URI for a file that does exist.",
      "source": "dart",
      "startLineNumber": 1,
      "startColumn": 8,
      "endLineNumber": 1,
      "endColumn": 58,
      "tags": []
  }

this is the error when i run it in android studio.

C:\src\flutter\bin\flutter.bat --no-color packages get Running
  "flutter packages get" in flutter-chat-app-master...      The current
  Dart SDK version is 2.3.0-dev.0.5.flutter-a1668566e5.

Because flutter_chat_app depends on firebase_analytics 0.0.4 which
  requires SDK version >=1.8.0 <2.0.0, version solving failed. pub get
  failed (1)

I was able to run other sample codes, one is from this so I know that my setup is working.

I already tried few possbile solutions but not working, I saw this , but did not solve my issue.

I think the error requires me to downgrade android sdk but I dont know where to do that. I just need to run so I can see what it looks and I can follow. thanks.

答:
After a lot of googling , reinstalling, downgrade, upgrade, package get(which never worked coz the error was in the way so it exits before it could 'get'), package upgrade etc,  I was finally able to solve this.

The only problem I had was I did not know which version (or what is the latest) to use coz for some reason, it wasn't indicated in their list of "versions", or least it wasn't easy to find coz I always end up in this page. Simply putting these lines (and/or doing the answer above)

```<code>environment:
  sdk: '>=2.1.0 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
    google_sign_in: ^0.3.1
    firebase_analytics: ^0.0.4
    firebase_auth: ^0.2.0
    firebase_database: ^0.0.12
    firebase_storage: ^0.0.5
</code>```

in yaml did not solve it, although a lot of ppl claimed it did.

the only thing that solved it was when I happen to go in this page where it contains the correct and latest firebase versions that the latest Dart SDK where in my case - DART SDK 2.3 supports.
just get the current version to this You can search every plugin in the search bar.

my yaml looks like this now:

```<code>dependencies:
  flutter:
    sdk: flutter
  image_picker: ^0.6.0+8
  google_sign_in:  ^4.0.1+3
  firebase_analytics: ^3.0.1
  firebase_auth: ^0.11.1+1
  firebase_database: ^3.0.0
  firebase_storage: ^3.0.0
</code>```

Added steps which I am not sure if it is necessary, but I did it before the version correcting.

invalidate cache, restart
In relation with running the app itself, and not particular to firebase:

change gradle version by doing steps from here (because of some error with gradle not related to firebase) and look for answer of keviepanas

Body:
After a lot of googling , reinstalling, downgrade, upgrade, package get(which never worked coz the error was in the way so it exits before it could 'get'), package upgrade etc,  I was finally able to solve this.

The only problem I had was I did not know which version (or what is the latest) to use coz for some reason, it wasn't indicated in their list of "versions", or least it wasn't easy to find coz I always end up in this page. Simply putting these lines (and/or doing the answer above)

environment:
  sdk: '>=2.1.0 <3.0.0'

dependencies:
  flutter:
    sdk: flutter
    google_sign_in: ^0.3.1
    firebase_analytics: ^0.0.4
    firebase_auth: ^0.2.0
    firebase_database: ^0.0.12
    firebase_storage: ^0.0.5

in yaml did not solve it, although a lot of ppl claimed it did.

the only thing that solved it was when I happen to go in this page where it contains the correct and latest firebase versions that the latest Dart SDK where in my case - DART SDK 2.3 supports.
just get the current version to this You can search every plugin in the search bar.

my yaml looks like this now:

dependencies:
  flutter:
    sdk: flutter
  image_picker: ^0.6.0+8
  google_sign_in:  ^4.0.1+3
  firebase_analytics: ^3.0.1
  firebase_auth: ^0.11.1+1
  firebase_database: ^3.0.0
  firebase_storage: ^3.0.0

Added steps which I am not sure if it is necessary, but I did it before the version correcting.

invalidate cache, restart
In relation with running the app itself, and not particular to firebase:

change gradle version by doing steps from here (because of some error with gradle not related to firebase) and look for answer of keviepanas


问:
Code works in CSHTML but does not work in external Javascript file
I'm trying to move my script from CSHTML to an external Javascript file. All the scripts runs perfectly except from one function: $.post('@Url.Action("GetPoint", "Main")').done(function (xml)

The error I get on the browser debugger is:

jquery.min.js:2 POST http://localhost:58153/@Url.Action(%22GetPoint%22,%20%22Main%22) 404 (Not Found)

How can I make this function work??

var script = document.createElement('script');
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js";
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

var createPoint = function(ctx, lat, lon) {
  ctx.beginPath();
  ctx.arc(lat, lon, 8, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.strokeStyle = "black";
  ctx.lineWidth = 3;
  ctx.fill();
  ctx.stroke();
  ctx.closePath();
}
var isFirstMission = document.getElementById("first").value;
var ctx = document.getElementById("myCanvas").getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

if (isFirstMission) {
  // ...
} else {
  myTimer = (function(ctx) {

    $.post('@Url.Action("GetPoint", "Main")').done(function(xml) { // This function does not work..
      alert(xml);
      var xmlDoc = $.parseXML(xml);
      $xml = $(xmlDoc);
      var lat = (parseFloat($xml.find("lat").text()) + 90)(screen.height / 180);
      var lon = (parseFloat($xml.find("lon").text()) + 180) * (screen.height / 360);
      alert(lat);
      alert(lon);

      createPoint(ctx, lat, lon);
    });
  });

  setInterval(function() {
    myTimer(ctx);
  }, 1000);
}
```

答:
The problem is that the Javascript file is not parsed as C# on the server, so the '@Url.Action("GetPoint", "Main")' string is taken literally.  To solve this you can set a variable in the cshtml file, so that it is parsed, and use that variable in the Javascript file.

In the cshtml file...

```<code><script>
    var postUrl = '@Url.Action("GetPoint", "Main")';
</script>
</code>```

Then include your Javascript file below that declaration, and change the post to this...

```<code>$.post(postUrl).done(// etc..
</code>```

Body:
The problem is that the Javascript file is not parsed as C# on the server, so the '@Url.Action("GetPoint", "Main")' string is taken literally.  To solve this you can set a variable in the cshtml file, so that it is parsed, and use that variable in the Javascript file.

In the cshtml file...

<script>
    var postUrl = '@Url.Action("GetPoint", "Main")';
</script>

Then include your Javascript file below that declaration, and change the post to this...

$.post(postUrl).done(// etc..


问:
Avoid exception using CopyToDataTable() when no rows are found
Avoid exception using CopyToDataTable() when no rows are found
I tried this code when no rows found then it gives me error The source contains no DataRows. </p>

```<code>ds.Tables.Add(dsDecEjID.Tables(0).Select(Cond).CopyToDataTable())
</code>```

答:
If you are using C# 6.0, then you can use:</p>

```<code>table?.CopyToDataTable()
</code>```

Body:
Avoid exception using CopyToDataTable() when no rows are found
I tried this code when no rows found then it gives me error The source contains no DataRows.

ds.Tables.Add(dsDecEjID.Tables(0).Select(Cond).CopyToDataTable())

Body:
If you are using C# 6.0, then you can use:

table?.CopyToDataTable()


答:
Server-side C# (Razor) code isn't interpreted in .js files.  (Nor should it be, you don't want to go down that road.)

Instead, something you can do is just set JavaScript variables in your Razor-driven code (possibly global, depending on how you manage scope in your JavaScript code) and use those values in your external JavaScript.  So perhaps something like this in the Razor:

```<code><script type="text/javascript">
    var getPointURL = '@Url.Action("GetPoint", "Main")';
</script>
</code>```

And elsewhere you can use that value:

```<code>$.post(getPointURL)
</code>```

There are a variety of ways to manage/scale/etc. this approach, depending on your growing needs in your system.  But in general the idea is that anything which is dynamic from server-side code is in the Razor file and then the page's JavaScript would use it later.

Title: Code works in CSHTML but does not work in external Javascript file

Body:
I'm trying to move my script from CSHTML to an external Javascript file. All the scripts runs perfectly except from one function: $.post('@Url.Action("GetPoint", "Main")').done(function (xml)

The error I get on the browser debugger is:

jquery.min.js:2 POST http://localhost:58153/@Url.Action(%22GetPoint%22,%20%22Main%22) 404 (Not Found)

How can I make this function work??

var script = document.createElement('script');
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js";
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

var createPoint = function(ctx, lat, lon) {
  ctx.beginPath();
  ctx.arc(lat, lon, 8, 0, Math.PI * 2);
  ctx.fillStyle = "red";
  ctx.strokeStyle = "black";
  ctx.lineWidth = 3;
  ctx.fill();
  ctx.stroke();
  ctx.closePath();
}
var isFirstMission = document.getElementById("first").value;
var ctx = document.getElementById("myCanvas").getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;

if (isFirstMission) {
  // ...
} else {
  myTimer = (function(ctx) {

    $.post('@Url.Action("GetPoint", "Main")').done(function(xml) { // This function does not work..
      alert(xml);
      var xmlDoc = $.parseXML(xml);
      $xml = $(xmlDoc);
      var lat = (parseFloat($xml.find("lat").text()) + 90)(screen.height / 180);
      var lon = (parseFloat($xml.find("lon").text()) + 180) * (screen.height / 360);
      alert(lat);
      alert(lon);

      createPoint(ctx, lat, lon);
    });
  });

  setInterval(function() {
    myTimer(ctx);
  }, 1000);
}

Body:
Server-side C# (Razor) code isn't interpreted in .js files.  (Nor should it be, you don't want to go down that road.)

Instead, something you can do is just set JavaScript variables in your Razor-driven code (possibly global, depending on how you manage scope in your JavaScript code) and use those values in your external JavaScript.  So perhaps something like this in the Razor:

<script type="text/javascript">
    var getPointURL = '@Url.Action("GetPoint", "Main")';
</script>

And elsewhere you can use that value:

$.post(getPointURL)

There are a variety of ways to manage/scale/etc. this approach, depending on your growing needs in your system.  But in general the idea is that anything which is dynamic from server-side code is in the Razor file and then the page's JavaScript would use it later.


问:
How can I append this value in addition to what the user inputs?
I have a script that implements FindNext in order to search a sheet for a row to match two column values that the user inputs via Application.InputBox. Works flawlessly. But there is an instance where I'd like one of the msgboxs to display another cell value in that row without the user input.

Example: User inputs Job code 000001 found in column A, cost-center 100100010001 Found in column C.

The msgbox will match it and say: MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center.

What if I also wanted that message box to add in a value found in another column, but automatically? Like, without the user input because they wouldn't know this info off hand.

New MsgBox Example: MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & Column H Value for this row & ") cost-center.

I was thinking something like a str variable and reference the column, but I'm having trouble having VBA trigger that value once the row is matched.

Rest of script:

```<code>Option Explicit
Sub findJC_CC()

Dim wsData As Worksheet
Dim rFound As Range
Dim lJobCode As String
Dim lCC As String
Dim sFirst As String
Dim matched As Boolean

lJobCode = Application.InputBox("Please provide a job code", "Job Code", Type:=2)
If lJobCode = "False" Then Exit Sub 'Pressed cancel
lCC = Application.InputBox("Please enter in a cost-center", "CC", Type:=2)
If lCC = "False" Then Exit Sub 'Pressed cancel

matched = False
Set wsData = ThisWorkbook.Worksheets("Sheet2")
Set rFound = wsData.Columns("A").Find(lJobCode, wsData.Cells(wsData.Rows.Count, "A"), xlValues, xlWhole)

If Not rFound Is Nothing Then
    sFirst = rFound.Address
    Do

        If rFound.Offset(, 2).Value = lCC Then
            matched = True

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 4).Value = "Exempt" Then
                MsgBox "The business identified this exempt job as being eligible for schedule pay allowance ."
                Exit Sub
            End If

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 5).Value = "Eligible - Employee Level" Then
                MsgBox "This job is only eligible at the employee level. If you have further questions, please reach out to your HRBP."
                Exit Sub
            End If

            'if non-exempt role, and matched, display msgbox and exit
            MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center."
            Exit Sub
        End If

        'loop after first address found until column C has lCC value matched
        Set rFound = wsData.Columns("A").FindNext(rFound)
    Loop While rFound.Address <> sFirst

    'lJobCode value matched, lCC value not matched
    If Not matched Then MsgBox "Job Code (" & lJobCode & ") found, but not eligible for this cost-center."
Else

    'lJobCode not matched
    MsgBox "Job Code (" & lJobCode & ") not eligible."

End If

End Sub
</code>```

答:
If I'm understanding correctly, the variable rFound points to a cell in column A from which you want to offset. If that's the case, you could write code like:

```<code>MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & rFound.Offset(,7).Value & ") cost-center.
</code>```

Body:
I have a script that implements FindNext in order to search a sheet for a row to match two column values that the user inputs via Application.InputBox. Works flawlessly. But there is an instance where I'd like one of the msgboxs to display another cell value in that row without the user input.

Example: User inputs Job code 000001 found in column A, cost-center 100100010001 Found in column C.

The msgbox will match it and say: MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center.

What if I also wanted that message box to add in a value found in another column, but automatically? Like, without the user input because they wouldn't know this info off hand.

New MsgBox Example: MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & Column H Value for this row & ") cost-center.

I was thinking something like a str variable and reference the column, but I'm having trouble having VBA trigger that value once the row is matched.

Rest of script:

Option Explicit
Sub findJC_CC()

Dim wsData As Worksheet
Dim rFound As Range
Dim lJobCode As String
Dim lCC As String
Dim sFirst As String
Dim matched As Boolean

lJobCode = Application.InputBox("Please provide a job code", "Job Code", Type:=2)
If lJobCode = "False" Then Exit Sub 'Pressed cancel
lCC = Application.InputBox("Please enter in a cost-center", "CC", Type:=2)
If lCC = "False" Then Exit Sub 'Pressed cancel

matched = False
Set wsData = ThisWorkbook.Worksheets("Sheet2")
Set rFound = wsData.Columns("A").Find(lJobCode, wsData.Cells(wsData.Rows.Count, "A"), xlValues, xlWhole)

If Not rFound Is Nothing Then
    sFirst = rFound.Address
    Do

        If rFound.Offset(, 2).Value = lCC Then
            matched = True

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 4).Value = "Exempt" Then
                MsgBox "The business identified this exempt job as being eligible for schedule pay allowance ."
                Exit Sub
            End If

            'if criteria is met, display msgbox and exit
            If rFound.Offset(, 5).Value = "Eligible - Employee Level" Then
                MsgBox "This job is only eligible at the employee level. If you have further questions, please reach out to your HRBP."
                Exit Sub
            End If

            'if non-exempt role, and matched, display msgbox and exit
            MsgBox "Job Code (" & lJobCode & ") is eligible for this cost-center."
            Exit Sub
        End If

        'loop after first address found until column C has lCC value matched
        Set rFound = wsData.Columns("A").FindNext(rFound)
    Loop While rFound.Address <> sFirst

    'lJobCode value matched, lCC value not matched
    If Not matched Then MsgBox "Job Code (" & lJobCode & ") found, but not eligible for this cost-center."
Else

    'lJobCode not matched
    MsgBox "Job Code (" & lJobCode & ") not eligible."

End If

End Sub

Body:
If I'm understanding correctly, the variable rFound points to a cell in column A from which you want to offset. If that's the case, you could write code like:

MsgBox "Job Code (" & lJobCode & ") is eligible for this (" & rFound.Offset(,7).Value & ") cost-center.


问:
Calling functions on my SavingsAccount object and printing the result
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.

If I try to print the output for one of the accounts I make I get a memory adress.

I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.

public class SavingsAccount {
  // Class
  int balance;
  int amountToDeposit;
  int amountToWithdraw;

  //Constructor
  public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    amountToDeposit = deposit;
    amountToWithdraw = withdraw;
  }

  //Functions thats I wanna call

  // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

  // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
  }

  // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

      return amountToWithdraw;
  }

  // Main
  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    //Check balance
     System.out.println(test); // Will give a memory adress
  }
}
```

I would like to use my functions on the object I make and print the result.

Thanks for reading.

答:
I have the feeling that I have done something wrong and I don't quite
  understand how to call my functions on the object.

You can call your methods with the variable name of a SavingsAccount, followed by a ".", and then the method you would like to call.

So, rather than

```<code>//Check balance
 System.out.println(test); // Will give a memory address
</code>```

You can do this, for example:

```<code>  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    test.checkBalance();
  }
</code>```

or

```<code>public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    test.deposit(50);
    test.checkBalance();
}
</code>```

With that in mind, perhaps it makes more sense to only specify a starting balance when constructing a SavingsAccount. Hope this helps!

Body:
I have a SavingsAccount object and I am trying to use my functions to manipulate the balance of the account. Now I get no errors but no output. I have the feeling that I have done something wrong and I don't quite understand how to call my functions on the object.

If I try to print the output for one of the accounts I make I get a memory adress.

I got all kinds of different errors while tweaking and its finally error free. But still no output and I am afraid I got it quite wrong and its just buggy and I don't call my functions the right way, or my constructor is not coded as its ment to be.

public class SavingsAccount {
  // Class
  int balance;
  int amountToDeposit;
  int amountToWithdraw;

  //Constructor
  public SavingsAccount(int initialBalance, int deposit, int withdraw){
    balance = initialBalance;
    amountToDeposit = deposit;
    amountToWithdraw = withdraw;
  }

  //Functions thats I wanna call

  // Setting balance
    public void checkBalance() {
        System.out.println("Hello!");
        System.out.println("Your balance is " + balance);
    }

  // Depositing amounts
    public void deposit(int amountToDeposit) {
        balance = balance + amountToDeposit;
        System.out.println("You just deposited" + amountToDeposit);
  }

  // Withdrawing amounts
    public int withdraw(int amountToWithdraw) {
        balance = balance - amountToWithdraw;
        System.out.println("You just withdrew" + amountToWithdraw);

      return amountToWithdraw;
  }

  // Main
  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    //Check balance
     System.out.println(test); // Will give a memory adress
  }
}

I would like to use my functions on the object I make and print the result.

Thanks for reading.

Body:
I have the feeling that I have done something wrong and I don't quite
  understand how to call my functions on the object.

You can call your methods with the variable name of a SavingsAccount, followed by a ".", and then the method you would like to call.

So, rather than

//Check balance
 System.out.println(test); // Will give a memory address

You can do this, for example:

  public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    test.checkBalance();
  }

or

public static void main(String[] args){
    //Setting values, balance, deposit, withdraw.
    SavingsAccount savings = new SavingsAccount(2000, 100, 2000);
    SavingsAccount test = new SavingsAccount(5000, 200, 100);

    test.deposit(50);
    test.checkBalance();
}

With that in mind, perhaps it makes more sense to only specify a starting balance when constructing a SavingsAccount. Hope this helps!


问:
Sending email in R version 3.6.0 via outlook by RDCOMClient package
I updated R in version 3.6.0. Then I started to have problem with Library RDCOMClient. Does anyone know how to solve problem with R version 3.6.0 and library RDCOMClient? Or does it exist some alternative way how to send emails in R via Outlook?

Installing package into ‘C:/Users/xxxx/Documents/R/win-library/3.6’
(as ‘lib’ is unspecified)

Warning in install.packages :   package ‘RDCOMClient’ is not available (for R version 3.6.0)

答:
I had almost the same problem, try installing it this way :

```<code>install.packages("RDCOMClient", repos = "http://www.omegahat.net/R")
</code>```

Tell me if it worked for you.

Body:
I had almost the same problem, try installing it this way :

install.packages("RDCOMClient", repos = "http://www.omegahat.net/R")

Tell me if it worked for you.