问:
Print JSON data from csv list of multiple urls
Very new to Python and haven't found specific answer on SO but apologies in advance if this appears very naive or elsewhere already.

I am trying to print 'IncorporationDate' JSON data from multiple urls of public data set. I have the urls saved as a csv file, snippet below. I am only getting as far as printing ALL the JSON data from one url, and I am uncertain how to run that over all of the csv urls, and write to csv just the IncorporationDate values.

Any basic guidance or edits are really welcomed!

```<code>try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json

def get_jsonparsed_data(url):

    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url = ("http://data.companieshouse.gov.uk/doc/company/01046514.json")
print(get_jsonparsed_data(url))

import csv
with open('test.csv') as f:
    lis=[line.split() for line in f]
    for i,x in enumerate(lis):
        print ()

import StringIO
s = StringIO.StringIO()
with open('example.csv', 'w') as f:
    for line in s:
        f.write(line)
</code>```

Snippet of csv:

```<code>http://business.data.gov.uk/id/company/01046514.json
http://business.data.gov.uk/id/company/01751318.json
http://business.data.gov.uk/id/company/03164710.json
http://business.data.gov.uk/id/company/04403406.json
http://business.data.gov.uk/id/company/04405987.json
</code>```

答:
First step, you have to read all the URLs in your CSV

```<code>import csv
csvReader = csv.reader('text.csv')
# next(csvReader) uncomment if you have a header in the .CSV file
all_urls = [row for row in csvReader if row]
</code>```

Second step, fetch the data from the URL

```<code>from urllib.request import urlopen
def get_jsonparsed_data(url):
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url_data = get_jsonparsed_data("give_your_url_here")
</code>```

Third step:

Go through all URLs that you got from CSV file

Get JSON data

Fetch the field what you need, in your case "IncorporationDate"

Write into an output CSV file, I'm naming it as IncorporationDates.csv

Code below:

```<code>for each_url in all_urls:
    url_data = get_jsonparsed_data(each_url)
    with open('IncorporationDates.csv', 'w' ) as abc:
        abc.write(url_data['primaryTopic']['IncorporationDate'])
</code>```

Body:
Very new to Python and haven't found specific answer on SO but apologies in advance if this appears very naive or elsewhere already.

I am trying to print 'IncorporationDate' JSON data from multiple urls of public data set. I have the urls saved as a csv file, snippet below. I am only getting as far as printing ALL the JSON data from one url, and I am uncertain how to run that over all of the csv urls, and write to csv just the IncorporationDate values.

Any basic guidance or edits are really welcomed!

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json

def get_jsonparsed_data(url):

    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url = ("http://data.companieshouse.gov.uk/doc/company/01046514.json")
print(get_jsonparsed_data(url))

import csv
with open('test.csv') as f:
    lis=[line.split() for line in f]
    for i,x in enumerate(lis):
        print ()

import StringIO
s = StringIO.StringIO()
with open('example.csv', 'w') as f:
    for line in s:
        f.write(line)

Snippet of csv:

http://business.data.gov.uk/id/company/01046514.json
http://business.data.gov.uk/id/company/01751318.json
http://business.data.gov.uk/id/company/03164710.json
http://business.data.gov.uk/id/company/04403406.json
http://business.data.gov.uk/id/company/04405987.json

Body:
First step, you have to read all the URLs in your CSV

import csv
csvReader = csv.reader('text.csv')
# next(csvReader) uncomment if you have a header in the .CSV file
all_urls = [row for row in csvReader if row]

Second step, fetch the data from the URL

from urllib.request import urlopen
def get_jsonparsed_data(url):
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url_data = get_jsonparsed_data("give_your_url_here")

Third step:

Go through all URLs that you got from CSV file

Get JSON data

Fetch the field what you need, in your case "IncorporationDate"

Write into an output CSV file, I'm naming it as IncorporationDates.csv

Code below:

for each_url in all_urls:
    url_data = get_jsonparsed_data(each_url)
    with open('IncorporationDates.csv', 'w' ) as abc:
        abc.write(url_data['primaryTopic']['IncorporationDate'])


来源: stackexchange

问:
Create vector of data frame names from a list of data frames
I have a list of data frames, and I want to create a character vector that contains the data frame names that meet a certain criteria.  In this case, I want the names of the data frames that contain at least 1 observation.  I need these names in a vector for use in another function later on.

The list of data frames is created automatically by the split function.  For reproducibility, here's a list of data frames:

```<code>df1 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df2 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df3 <- data.frame(replicate(0,sample(0:1,5,rep=TRUE))) #empty

mylist <- list(df1, df2,df3) #create list of data frames

mylist2 <- mylist[sapply(mylist, function(x) dim(x)[1]) > 0] #subset list so that df's with no observations are dropped
</code>```

Now, what I need is a character vector with the names of the data frames in mylist2.  (In this example, "df1" and "df2".)

Thanks!

答:
If you want this to be somewhat automatized, for instance you have a large number of data.frames in your environment, you might want to select them with a pattern matching in one line:

```<code>mylist = do.call("list", mget(grep("df", ls(), value=T)))
mylist2 <- mylist[sapply(mylist, function(x) dim(x)[1]) > 0]
</code>```

This creates the first list with all data.frames that have "df" in their names, while keeping their names as attributes of the list elements.

Then I apply your filter for 1-element data.frames and you just retrieve the names:

```<code>names(mylist2)
#### [1] "df1" "df2"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a list of data frames, and I want to create a character vector that contains the data frame names that meet a certain criteria.  In this case, I want the names of the data frames that contain at least 1 observation.  I need these names in a vector for use in another function later on.

The list of data frames is created automatically by the split function.  For reproducibility, here's a list of data frames:

df1 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df2 <- data.frame(replicate(2,sample(0:1,5,rep=TRUE)))
df3 <- data.frame(replicate(0,sample(0:1,5,rep=TRUE))) #empty

mylist <- list(df1, df2,df3) #create list of data frames

mylist2 <- mylist[sapply(mylist, function(x) dim(x)[1]) > 0] #subset list so that df's with no observations are dropped

Now, what I need is a character vector with the names of the data frames in mylist2.  (In this example, "df1" and "df2".)

Thanks!

Body:
If you want this to be somewhat automatized, for instance you have a large number of data.frames in your environment, you might want to select them with a pattern matching in one line:

mylist = do.call("list", mget(grep("df", ls(), value=T)))
mylist2 <- mylist[sapply(mylist, function(x) dim(x)[1]) > 0]

This creates the first list with all data.frames that have "df" in their names, while keeping their names as attributes of the list elements.

Then I apply your filter for 1-element data.frames and you just retrieve the names:

names(mylist2)
#### [1] "df1" "df2"


问:
Prevent ng-cli to associate css with components
I'm trying to migrate an app which was using SystemJS to ng-cli environment. I don't want to change too much the structure of the app, and beside, I dont use a css file for each component, I want to keep it global.

When I run ng serve, I get the following error :

```<code>ERROR in ./src/app/components/guest-sidebar.component.ts
Module not found: Error: Can't resolve './assets/css/guest-sidebar.css' in '/project/src/app/components'
</code>```

I'm pretty new on ng-cli or webpack, how do I tell ng-cli I dont want it to associate components with their css and handle it separatly ?

答:
Use this flag: --inline-style (alias: -is) default value: false

If you specify true then it will expect you to handle the styles "inline" and won't generate a separate css file.

Body:
I'm trying to migrate an app which was using SystemJS to ng-cli environment. I don't want to change too much the structure of the app, and beside, I dont use a css file for each component, I want to keep it global.

When I run ng serve, I get the following error :

ERROR in ./src/app/components/guest-sidebar.component.ts
Module not found: Error: Can't resolve './assets/css/guest-sidebar.css' in '/project/src/app/components'

I'm pretty new on ng-cli or webpack, how do I tell ng-cli I dont want it to associate components with their css and handle it separatly ?


问:
Generic Interfaces Extends?
Hi I have this question on Generic interfaces if someone could explain the answer to me in a detailed way ill be extremely grateful.

Inteface I

```<code>public interface I <T> {
void  f (T a);
}
</code>```

Interface J

```<code>public interface J <T extends I<T>>{
  void g(T b);
}
</code>```

Class A

```<code>public class A<T> implements J<T>{
    public void g(T b) {

    }
}
</code>```

The Code In Class A will give an error.
Could You explain to me why it gives an error?

Class A FIX

```<code>public class A<T extends I<T>> implements J<T>{
    public void g(T b) {

    }
}
</code>```

Could Someone explain to me why this code fixes the error?

Thanks in advance

答:
This is because your T does not extend/implement I<T>.

It is often confusing to use the same generic placeholder. Try looking at it like this:

```<code>public interface I<TI> {
    void f(TI a);
}

public interface J<TJ extends I<TJ>> {
    void g(TJ b);
}

// Error:(17, 37) java: type argument TA is not within bounds of type-variable TJ
// i.e. This `TA` does NOT implement/extend J<TA extends I<TA>>
public class A<TA> implements J<TA> {
    public void g(TA b) {

    }
}

// Works fine because `TB extends I<TB>`
public class B<TB extends I<TB>> implements J<TB> {
    public void g(TB b) {

    }
}
</code>```

Title: Generic Interfaces Extends?

Body:
Hi I have this question on Generic interfaces if someone could explain the answer to me in a detailed way ill be extremely grateful.

Inteface I

public interface I <T> {
void  f (T a);
}

Interface J

public interface J <T extends I<T>>{
  void g(T b);
}

Class A

public class A<T> implements J<T>{
    public void g(T b) {

    }
}

The Code In Class A will give an error.
Could You explain to me why it gives an error?

Class A FIX

public class A<T extends I<T>> implements J<T>{
    public void g(T b) {

    }
}

Could Someone explain to me why this code fixes the error?

Thanks in advance

Body:
This is because your T does not extend/implement I<T>.

It is often confusing to use the same generic placeholder. Try looking at it like this:

public interface I<TI> {
    void f(TI a);
}

public interface J<TJ extends I<TJ>> {
    void g(TJ b);
}

// Error:(17, 37) java: type argument TA is not within bounds of type-variable TJ
// i.e. This `TA` does NOT implement/extend J<TA extends I<TA>>
public class A<TA> implements J<TA> {
    public void g(TA b) {

    }
}

// Works fine because `TB extends I<TB>`
public class B<TB extends I<TB>> implements J<TB> {
    public void g(TB b) {

    }
}


问:
jQuery - How to get an element's class from ajax request
I'm loading my website's pages with ajax by replacing the content inside the main tag.
Problem is, using Wordpress, each page has its own body classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.

I thought i'd run a new ajax request to get the whole html page, then check for the body element, then use .attr("class") to get the list of class and finally replace the old body classes by the new one...

But the classes always return undefined instead of a list of classes.

EDIT: I tried to use .cd-main-content instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.

How can I possibly get it to work on the body element ? (I already tried to replace .find by .filter but it doesn't work either.)

HTML stucture

```<code><body id="body" class="home page-id-number other-classes">
    <main>
        <div class="cd-main-content">
            <!-- inside is the dynamically loaded content-->
        </div>
    </main>
</body>
</code>```

jQuery

```<code>$.ajax({url: url,
    success: function(data){
        var body = $(data).find("#body");
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});
</code>```

答:
I found a solution, it's not ideal but it fixed the problem.

First, I have to assume that it is not possible to get the attributes of the body element as it appears to be filtered by jQuery. However it is possible to get the child elements.

I ended up adding the body classes to both the body and main elements (in the header.php file of wordpress).

Here's my code now :

HTML

```<code><body id="body" class="home page-id-number other-classes">
    <main class="home page-id-number other-classes">
    <!-- if I had the possibility, I'd have added "data-body-class" instead of "class" -->
        <div class="cd-main-content">
            <!-- inside is the dynamically loaded content-->
        </div>
    </main>
</body>
</code>```

jQuery

```<code>$.ajax({url: url,
    success: function(data){
        var classes = $(data).filter("main").attr("class"); //get the classes
        $("body, main").attr("class", classes); //set the classes
    }
});
</code>```

Body:
I'm loading my website's pages with ajax by replacing the content inside the main tag.
Problem is, using Wordpress, each page has its own body classes that are useful for styling purposes, so I want to replace the old page's body classes by the next page's classes.

I thought i'd run a new ajax request to get the whole html page, then check for the body element, then use .attr("class") to get the list of class and finally replace the old body classes by the new one...

But the classes always return undefined instead of a list of classes.

EDIT: I tried to use .cd-main-content instead of body and weirdly it works, I get the classes of this element. So I assume now that the problem doesn't come from my syntax but from the element itself.

How can I possibly get it to work on the body element ? (I already tried to replace .find by .filter but it doesn't work either.)

HTML stucture

jQuery

$.ajax({url: url,
    success: function(data){
        var body = $(data).find("#body");
        var classes = body.attr("class");
        console.log(data); //returns the html as expected
        console.log("body : "+body); //returns [object Object]
        console.log("classes : "+classes); //returns undefined
    }
});

Body:
I found a solution, it's not ideal but it fixed the problem.

First, I have to assume that it is not possible to get the attributes of the body element as it appears to be filtered by jQuery. However it is possible to get the child elements.

I ended up adding the body classes to both the body and main elements (in the header.php file of wordpress).

Here's my code now :

HTML

<body id="body" class="home page-id-number other-classes">
    <main class="home page-id-number other-classes">
    <!-- if I had the possibility, I'd have added "data-body-class" instead of "class" -->
        <div class="cd-main-content">
            <!-- inside is the dynamically loaded content-->
        </div>
    </main>
</body>

jQuery

$.ajax({url: url,
    success: function(data){
        var classes = $(data).filter("main").attr("class"); //get the classes
        $("body, main").attr("class", classes); //set the classes
    }
});


问:
Pandas: how to identify the values in a column of a dataframe and do some math operations

I want to do operations, such that I produce something like this:

In other words, if the values in Name are in the 'first_list', I want to multiply the 'Values' by two. If they are in the 'second_list', I want to multiply them  by 0.5. If they are not in either (for Nick and Nicky), do not do anything.

This is what I have:

```<code>first_list = ['John', 'James', 'Julius', 'Alex']
second_list = ['Lilly', 'Alexis', 'Becly']
if df['Name'].isin(first_list).any():
    df['New Values'] = df['Values'] * 2
elif df['Name'].isin(second_list).any():
    df['New Values'] = df['Values'] * 0.5
</code>```

But its' not doing the multiplication as I want. Instead, it gives me:

答:
Let's use np.where and isin:

```<code>df['New Value'] = (np.where(df.Name.isin(first_list),
                            df.Values*2,
                            np.where(df.Name.isin(second_list),
                                     df.Values*.5,
                                     df.Values)))
</code>```

Setup:

```<code>df = pd.DataFrame({'Name':['John','Lily','Alexis','Becky','James','Julian','Alex','Nick','Nicky'],'Values':[50,100,30,60,40,20,80,25,46]})

first_list = ['John','James','Julius','Alex']
second_list = ['Lily','Alexis','Becky']
</code>```

Output:

```<code>     Name  Values  New Value
0    John      50      100.0
1    Lily     100       50.0
2  Alexis      30       15.0
3   Becky      60       30.0
4   James      40       80.0
5  Julian      20       20.0
6    Alex      80      160.0
7    Nick      25       25.0
8   Nicky      46       46.0
</code>```

Body:
I want to do operations, such that I produce something like this:

In other words, if the values in Name are in the 'first_list', I want to multiply the 'Values' by two. If they are in the 'second_list', I want to multiply them  by 0.5. If they are not in either (for Nick and Nicky), do not do anything.

This is what I have:

first_list = ['John', 'James', 'Julius', 'Alex']
second_list = ['Lilly', 'Alexis', 'Becly']
if df['Name'].isin(first_list).any():
    df['New Values'] = df['Values'] * 2
elif df['Name'].isin(second_list).any():
    df['New Values'] = df['Values'] * 0.5

But its' not doing the multiplication as I want. Instead, it gives me:

Body:
Let's use np.where and isin:

df['New Value'] = (np.where(df.Name.isin(first_list),
                            df.Values*2,
                            np.where(df.Name.isin(second_list),
                                     df.Values*.5,
                                     df.Values)))

Setup:

df = pd.DataFrame({'Name':['John','Lily','Alexis','Becky','James','Julian','Alex','Nick','Nicky'],'Values':[50,100,30,60,40,20,80,25,46]})

first_list = ['John','James','Julius','Alex']
second_list = ['Lily','Alexis','Becky']

Output:

     Name  Values  New Value
0    John      50      100.0
1    Lily     100       50.0
2  Alexis      30       15.0
3   Becky      60       30.0
4   James      40       80.0
5  Julian      20       20.0
6    Alex      80      160.0
7    Nick      25       25.0
8   Nicky      46       46.0


问:
Interface Builder: determine which element has the initial focus
I have a Cocoa app with a table view and a few other controls. When the app launches and the window is shown, a blue focus ring is drawn around the table view.

How can I get rid of that focus ring? I'd like nothing to have the focus when the window first shows.

答:
The best way I've found of stopping any of the controls from being the first responder when a window is first displayed is in the window controller:

Swift 3:

```<code>class YourWindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        // Wait a frame before setting the first responder to be the window itself.
        // We can't just set it right now, because if the first responder is set
        // to the window now the system just interprets that as meaning that we
        // want the default behavior where it automatically selects a view to be
        // the first responder.
        DispatchQueue.main.async {
            window!.makeFirstResponder(nil)
        }
    }

}
</code>```

It's messy, and sometimes when the window loads you see the focus ring starting to appear on one of the controls for one frame, but I haven't found a better way yet.

Body:
The best way I've found of stopping any of the controls from being the first responder when a window is first displayed is in the window controller:

Swift 3:

class YourWindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        // Wait a frame before setting the first responder to be the window itself.
        // We can't just set it right now, because if the first responder is set
        // to the window now the system just interprets that as meaning that we
        // want the default behavior where it automatically selects a view to be
        // the first responder.
        DispatchQueue.main.async {
            window!.makeFirstResponder(nil)
        }
    }

}

It's messy, and sometimes when the window loads you see the focus ring starting to appear on one of the controls for one frame, but I haven't found a better way yet.


问:
How to get the disk size of portable disks via cURL
I would like to get the portable disk size per each of my vms.

Get ID of VMs by requesting
curl --user ":" -sk https://api.softlayer.com/rest/v3/SoftLayer_Account/getVirtualDiskImages

Get List of VMs by requesting with Key=ID
curl --user ":" -sk https://api.softlayer.com/rest/v3//SoftLayer_Virtual_Guest/Key

No method to get PortableStorageVolumes with key=VM's ID

There is only method to get PortableStorageVolumes under 'SoftLayer_Account' so that i cannot get volume size per vm id.

答:
Unfortunately, there is not method in SoftLayer_VIrtual_Guest service which can help to retrieve portable storage volumes information.

As workaround, It's possible to get this information through SoftLayer_Account::getPortableStorageVolumes but we need to use an Object Filter, below a request which can help to retrieve Portable Storage for a specific Virtual Guest:

```<code>curl -k "https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getPortableStorageVolumes?objectFilter={"portableStorageVolumes":{"blockDevices":{"guest":{"id":{"operation":123123123}}}}}"
</code>```

Replace: $user, $apiKey and 123123123(VSI id) with your own information

If you have a problem with encoding, try this:

```<code>curl -k "https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getPortableStorageVolumes?objectFilter=%7B%22portableStorageVolumes%22%3A%7B%22blockDevices%22%3A%7B%22guest%22%3A%7B%22id%22%3A%7B%22operation%22%3A123123123%7D%7D%7D%7D%7D"
</code>```

Replace: $user, $apiKey and 123123123(VirtualGuest's id)

Body:
Unfortunately, there is not method in SoftLayer_VIrtual_Guest service which can help to retrieve portable storage volumes information.

As workaround, It's possible to get this information through SoftLayer_Account::getPortableStorageVolumes but we need to use an Object Filter, below a request which can help to retrieve Portable Storage for a specific Virtual Guest:

curl -k "https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getPortableStorageVolumes?objectFilter={"portableStorageVolumes":{"blockDevices":{"guest":{"id":{"operation":123123123}}}}}"

Replace: $user, $apiKey and 123123123(VSI id) with your own information

If you have a problem with encoding, try this:

curl -k "https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Account/getPortableStorageVolumes?objectFilter=%7B%22portableStorageVolumes%22%3A%7B%22blockDevices%22%3A%7B%22guest%22%3A%7B%22id%22%3A%7B%22operation%22%3A123123123%7D%7D%7D%7D%7D"

Replace: $user, $apiKey and 123123123(VirtualGuest's id)


问:
How to start a major iPhone app update in Xcode
I have an app in the iPhone app store and have released several minor updates to it. I want to begin work on some major feature additions and reorganization, but don't want to lose the source code of my most recent version in case everything goes horribly wrong.

Should I start a new Xcode project from scratch and copy my existing source in? If I do this will I be able to submit the build from this new project as an update or will Apple complain that the build comes from a different Xcode project?

I've seen (but not used) Xcode's "Snapshots" and "Source Control" features - are these what I'm looking for?

Any help or direction greatly appreciated.

答:
I highly recommend you check out Git.  There is great Git support built into XCode 4, and you can use Git just fine with XCode 3 as well.

One great thing about Git is that you do not need a server to take advantage of the source code management features.  It is a lot easier for a solo developer to work with than SVN once you get your head wrapped around it.

I also highly recommend GitX - a free graphical UI for Git that is absolutely amazing.

One other recommendation it GitBox - a simple tool that allows using a Dropbox as a Git master repository.  This is great for sharing code between multiple machines without needing to have or pay for Git hosting at GitHub or elsewhere.

ContentLicense: CC BY-SA 2.5


问:
Detecting parent and child page types with Python using Wagtail CMS
I am setting up a Wagtail website.

There will be an Event Index page with Events as child pages.

Each event page could also have child pages, if it is part of a event series.

The main event will show the child events as a series of links on the page. The child events also need to display the parent event and also its own siblings.

In models.py I have an Event class. So far I am detecting children, siblings, parents like this:

```<code>@property
def childpages(self):
    event_children = Event.objects.live().descendant_of(self)
    return event_children

@property
def parentpage(self):
    event_parent = self.get_parent()
    return event_parent

@property
def siblingpages(self):
    event_siblings = Event.objects.live().sibling_of(self, inclusive=False)
    return event_siblings
</code>```

Is there a way of finding out what the parent page type is? If it is the event index I wouldn't want to display it on the event page. I also wouldn't want the main event pages to show siblings.

I've tried various things with not_child_of(somepage) but not quite sure how to use this. What does 'somepage' reference? A class, a variable? I'm used to Javascript and pretty new to Python.

答:
Here's how I'd write it:

```<code>@property
def parent_event(self):
    parent_page = self.get_parent()
    if parent_page.specific_class == Event:
        return parent_page.specific  # or just `return parent_page` if you don't need the extra detail from that page
    else:
        return None

@property
def sibling_events(self):
    parent_page = self.get_parent()
    if parent_page.specific_class == Event:
        return Event.objects.live().sibling_of(self, inclusive=False)
    else:
        # this is not a child event, so don't return siblings
        return Event.objects.none()
</code>```

In Python, the standard way of checking whether an object is an instance of a given class (i.e. in Wagtail terms, whether a page is of a particular type) is isinstance(parent_page, Event).

However, with Wagtail there's an extra complication - when you traverse up and down the page tree using methods like get_parent and get_children, there's no way for it to know in advance which page type it's going to get back - so, for performance reasons, it will return a "minimal" object of type Page which includes just the properties like title that are common to all pages. So, self.get_parent().title would work, but self.get_parent().start_date wouldn't. To turn that into a "real" object of the proper type, you'd access the property specific, which will do an extra database request behind the scenes to fill in the missing detail.

(Note that this doesn't apply when you run a query that explicitly asks for a specific type of page: with a query like Event.objects.sibling_of(self), we know we'll be getting Event pages back, so we don't need to call specific on the results.)

So, if isinstance(parent_page, Event): wouldn't work - it'll always be false, because at that point parent_page is a basic Page object (regardless of whether the page is really an Event or an EventIndex).

if isinstance(parent_page.specific, Event): would work, but it's a little bit inefficient, because in the case that parent_page is the event index page, you're firing off an extra database request that you don't really need. A better alternative is to use parent_page.specific_class, which tells you the specific type of the page without firing off that extra database request.

Body:
I am setting up a Wagtail website.

There will be an Event Index page with Events as child pages.

Each event page could also have child pages, if it is part of a event series.

The main event will show the child events as a series of links on the page. The child events also need to display the parent event and also its own siblings.

In models.py I have an Event class. So far I am detecting children, siblings, parents like this:

@property
def childpages(self):
    event_children = Event.objects.live().descendant_of(self)
    return event_children

@property
def parentpage(self):
    event_parent = self.get_parent()
    return event_parent

@property
def siblingpages(self):
    event_siblings = Event.objects.live().sibling_of(self, inclusive=False)
    return event_siblings

Is there a way of finding out what the parent page type is? If it is the event index I wouldn't want to display it on the event page. I also wouldn't want the main event pages to show siblings.

I've tried various things with not_child_of(somepage) but not quite sure how to use this. What does 'somepage' reference? A class, a variable? I'm used to Javascript and pretty new to Python.

Body:
Here's how I'd write it:

@property
def parent_event(self):
    parent_page = self.get_parent()
    if parent_page.specific_class == Event:
        return parent_page.specific  # or just `return parent_page` if you don't need the extra detail from that page
    else:
        return None

@property
def sibling_events(self):
    parent_page = self.get_parent()
    if parent_page.specific_class == Event:
        return Event.objects.live().sibling_of(self, inclusive=False)
    else:
        # this is not a child event, so don't return siblings
        return Event.objects.none()

In Python, the standard way of checking whether an object is an instance of a given class (i.e. in Wagtail terms, whether a page is of a particular type) is isinstance(parent_page, Event).

However, with Wagtail there's an extra complication - when you traverse up and down the page tree using methods like get_parent and get_children, there's no way for it to know in advance which page type it's going to get back - so, for performance reasons, it will return a "minimal" object of type Page which includes just the properties like title that are common to all pages. So, self.get_parent().title would work, but self.get_parent().start_date wouldn't. To turn that into a "real" object of the proper type, you'd access the property specific, which will do an extra database request behind the scenes to fill in the missing detail.

(Note that this doesn't apply when you run a query that explicitly asks for a specific type of page: with a query like Event.objects.sibling_of(self), we know we'll be getting Event pages back, so we don't need to call specific on the results.)

So, if isinstance(parent_page, Event): wouldn't work - it'll always be false, because at that point parent_page is a basic Page object (regardless of whether the page is really an Event or an EventIndex).

if isinstance(parent_page.specific, Event): would work, but it's a little bit inefficient, because in the case that parent_page is the event index page, you're firing off an extra database request that you don't really need. A better alternative is to use parent_page.specific_class, which tells you the specific type of the page without firing off that extra database request.


问:
how to initialize all the base class objects from derived class using base keyword
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.

```<code>    class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B : A
    {
        int c;
        public B(int s, int n,int z)
            : base(s, n)
        {
            c = z;
        }
        public int add()
        {
            return a + b+c;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(2, 3,5);
            Console.WriteLine(b.add());//the output is 10 OK

        }
    }
</code>```

Question

what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**

```<code>class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B:A
    {

        public int d;
        public int e;
        public B(int x, int y)
        {
            d = x;
            e = y;
        }
    }
    class C:B
    {

    }
</code>```

then from class C how to initialize both the base classes using base keyword.

答:
You can try this out like so in LINQPad:

Copy-pastable code below (note, will only be 'valid' in LinqPad, due to } in odd places - requirement of linqpad)

```<code>var test = new C(1, 2);
}

class A
{

    public int a;
    public int b;
    public A(int x, int y)
    {
        a = x;
        b = y;

        Console.WriteLine("A");
    }
}

class B : A
{

    public int d;
    public int e;
    public B(int x, int y) : base(x, y)
    {
        d = x;
        e = y;
        Console.WriteLine("B");
    }
}

class C : B
{

    public C(int x, int y) : base(x, y)
    {
        Console.WriteLine("C");
    }
</code>```

Body:
The following code initializes the base class from derived class using 'base' keyword by calling the base class constructor from the derived class.

    class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B : A
    {
        int c;
        public B(int s, int n,int z)
            : base(s, n)
        {
            c = z;
        }
        public int add()
        {
            return a + b+c;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            B b = new B(2, 3,5);
            Console.WriteLine(b.add());//the output is 10 OK

        }
    }

Question

what happens if a derived class inherits from more than one base class.then how to initialize all the base classes from the derived class using base keyword(how to call the base class constructors).**

class A
    {

        public int a;
        public int b;
        public A(int x, int y)
        {
            a = x;
            b = y;
        }
    }
    class B:A
    {

        public int d;
        public int e;
        public B(int x, int y)
        {
            d = x;
            e = y;
        }
    }
    class C:B
    {

    }

then from class C how to initialize both the base classes using base keyword.

Body:
You can try this out like so in LINQPad:

Copy-pastable code below (note, will only be 'valid' in LinqPad, due to } in odd places - requirement of linqpad)

var test = new C(1, 2);
}

class A
{

    public int a;
    public int b;
    public A(int x, int y)
    {
        a = x;
        b = y;

        Console.WriteLine("A");
    }
}

class B : A
{

    public int d;
    public int e;
    public B(int x, int y) : base(x, y)
    {
        d = x;
        e = y;
        Console.WriteLine("B");
    }
}

class C : B
{

    public C(int x, int y) : base(x, y)
    {
        Console.WriteLine("C");
    }


问:
nodejs call two class functions synchronous
I have two class functions in nodejs and I want to call both synchronously both one after another.

```<code>var questionData = questionModelObj.getQuestionbyId(req.params.id);
var answerData = answerModelObj.getAnsByQuesId(req.params.id);
</code>```

Here questionModelObj take time to execute and it calls answerModelObj without completing questionModelObj. It results answerData overwrites the questionData.

Please suggest how to call these two functions one after another(synchronous) and explain.

答:
One option is to execute the second function as a callback to the first. This is pretty standard for Javascript.

```<code>// Declare variable to hold response
var answerData;

var questionData = questionModelObj.getQuestionbyId(req.params.id, function() {
    // This is the callback function
    answerData = answerModelObj.getAnsByQuesId(req.params.id);
}
</code>```

The function signature of getQuestionbyId would then need to take in 2 parameters, the second being a function to be called later on:

```<code>questionModelObj.getQuestionbyId = function(id, callback) {
    // Do things with the id
    callback();
}
</code>```

The callback function is then called after getQuestionbyId is done.

Body:
I have two class functions in nodejs and I want to call both synchronously both one after another.

var questionData = questionModelObj.getQuestionbyId(req.params.id);
var answerData = answerModelObj.getAnsByQuesId(req.params.id);

Here questionModelObj take time to execute and it calls answerModelObj without completing questionModelObj. It results answerData overwrites the questionData.

Please suggest how to call these two functions one after another(synchronous) and explain.

Body:
One option is to execute the second function as a callback to the first. This is pretty standard for Javascript.

// Declare variable to hold response
var answerData;

var questionData = questionModelObj.getQuestionbyId(req.params.id, function() {
    // This is the callback function
    answerData = answerModelObj.getAnsByQuesId(req.params.id);
}

The function signature of getQuestionbyId would then need to take in 2 parameters, the second being a function to be called later on:

questionModelObj.getQuestionbyId = function(id, callback) {
    // Do things with the id
    callback();
}

The callback function is then called after getQuestionbyId is done.


问:
PHP: echo number of duplicates in a table by most common
I am trying to echo the most common duplicates in a table. I have been able to echo the name of the duplicates but what I'm looking for is a separate column in the table that shows how many times the duplicate occurs. Is there a way of echoing the COUNT(*) value? Also a way of organizing the values by size would be helpful.

My php:

```<code>$interests = "SELECT name, COUNT(*) FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1";
$interestresults = mysqli_query($conn, $interests);
</code>```

My html:

```<code>      <div class="panel panel-default panel-table">
<div class="panel-heading">
<div class="row">
<h2 class="cba-title">Interests</h2>

                    </div>
                    </div>
                    <div>
                            <?php
                                if(mysqli_num_rows($interestresults) > 0){
                                    $rim = mysqli_num_rows($interestresults);
                                    echo "
                                     <table class = 'table table-striped table-bordered table-list'>
                                     <thead>
                                      <tr>
                                       <th>Name</th>

                                      </tr>
                                       </thead>
                                      <tbody>'";

                                    for($x = 1; $x <= $rim; $x++){
                                        $rat = mysqli_fetch_assoc($interestresults);
                                        echo "<tr>

                                            <td>".$rat['name']."</td>
                                            </tr>";

                                    }

                                    echo '</tbody>
                                        </table>
                                      </center>';
                                }else{
                                    echo " There doesn't seem to be any common interests yet";
                                }
                            ?>
                        </div>
                        </div>
</code>```

答:
You could use an alias like this:</p>

```<code>SELECT name, COUNT() as The_Count
FROM pageinterests
WHERE pageid = '$id'
GROUP BY name HAVING COUNT() > 1
ORDER BY The_Count DESC;
</code>```

Body:
I am trying to echo the most common duplicates in a table. I have been able to echo the name of the duplicates but what I'm looking for is a separate column in the table that shows how many times the duplicate occurs. Is there a way of echoing the COUNT(*) value? Also a way of organizing the values by size would be helpful.

My php:

$interests = "SELECT name, COUNT(*) FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1";
$interestresults = mysqli_query($conn, $interests);

My html:

Interests

                            <?php
                                if(mysqli_num_rows($interestresults) > 0){
                                    $rim = mysqli_num_rows($interestresults);
                                    echo "

                                       Name

'";

                                    for($x = 1; $x <= $rim; $x++){
                                        $rat = mysqli_fetch_assoc($interestresults);
                                        echo "

                                            ".$rat['name']."

";

                                    }

                                    echo '

                                      ';
                                }else{
                                    echo " There doesn't seem to be any common interests yet";
                                }
                            ?>

Body:
You could use an alias like this:

SELECT name, COUNT() as The_Count
FROM pageinterests
WHERE pageid = '$id'
GROUP BY name HAVING COUNT() > 1
ORDER BY The_Count DESC;


问:
Read binary into hex byte array
How would do you read file byte for byte and save every byte in hex form in an array?
So it would look like this:

```<code>unsigned char binaryData[10] = {
    0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x4B
};
</code>```

Thanks in advance

答:
I think the question should have been worded: "how can I convert binary data into C++ source code defining an array that contains the same data."

I think you will want to know about

```<code>xxd -i file.bin
</code>```

For the above markdown it would emit:

```<code>unsigned char file_bin[] = {
  0x49, 0x20, 0x74, 0x68, 0x69, 0x6e, 0x6b, 0x20, 0x79, 0x6f, 0x75, 0x20,
  0x77, 0x69, 0x6c, 0x6c, 0x20, 0x77, 0x61, 0x6e, 0x74, 0x20, 0x74, 0x6f,
  0x20, 0x6b, 0x6e, 0x6f, 0x77, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x0a,
  0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x78, 0x64, 0x20, 0x2d, 0x69, 0x20,
  0x66, 0x69, 0x6c, 0x65, 0x2e, 0x62, 0x69, 0x6e, 0x0a
};
unsigned int file_bin_len = 57;
</code>```

Title: Read binary into hex byte array

Body:
How would do you read file byte for byte and save every byte in hex form in an array?
So it would look like this:

unsigned char binaryData[10] = {
    0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x4B
};

Thanks in advance

Body:
I think the question should have been worded: "how can I convert binary data into C++ source code defining an array that contains the same data."

I think you will want to know about

xxd -i file.bin

For the above markdown it would emit:

unsigned char file_bin[] = {
  0x49, 0x20, 0x74, 0x68, 0x69, 0x6e, 0x6b, 0x20, 0x79, 0x6f, 0x75, 0x20,
  0x77, 0x69, 0x6c, 0x6c, 0x20, 0x77, 0x61, 0x6e, 0x74, 0x20, 0x74, 0x6f,
  0x20, 0x6b, 0x6e, 0x6f, 0x77, 0x20, 0x61, 0x62, 0x6f, 0x75, 0x74, 0x0a,
  0x0a, 0x20, 0x20, 0x20, 0x20, 0x78, 0x78, 0x64, 0x20, 0x2d, 0x69, 0x20,
  0x66, 0x69, 0x6c, 0x65, 0x2e, 0x62, 0x69, 0x6e, 0x0a
};
unsigned int file_bin_len = 57;


答:
you need to use an alias for count(*).Then you can use it for order and echo. </p>

```<code>$interests = "SELECT name, COUNT(*) as count_alias FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1 ORDER BY count_alias DESC";
</code>```

Title: PHP: echo number of duplicates in a table by most common

Body:
you need to use an alias for count(*).Then you can use it for order and echo.

$interests = "SELECT name, COUNT(*) as count_alias FROM pageinterests WHERE pageid = '$id' GROUP BY name HAVING COUNT(*) > 1 ORDER BY count_alias DESC";


问:
RMySQL encoding issue on Windows - Spanish Character ñ
While using RMySQL::dbWriteTable function in R to write a table to MySQL on Windows I get an error message concerning the character [ñ].

The simplified example is:

```<code>    table <- data.frame(a=seq(1:3), b=c("És", "España", "Compañía"))
    table

 a        b
1 1       És
2 2   España
3 3 Compañía

db <- dbConnect(MySQL(), user = "####", password = "####", dbname ="test", host= "localhost")

RMySQL::dbWriteTable(db, name="test1", table, overwrite=T, append=F )

Error in .local(conn, statement, ...) :
  could not run statement: Invalid utf8 character string: 'Espa'
</code>```

As you can see, there is no problem with the accents ("És") but there is with the ñ character ("España").

On the other hand, there is no problem with MySQL since this query works fine:

```<code>INSERT INTO test.test1 (a,b)
values (1, "España");
</code>```

Things I have already tried previous to write the table:

Encoding(x) <- "UTF-8" for all table.

iconv(x, "UTF-8", "UTF-8") for all table.

Sent pre-query: dbSendQuery(db, "SET NAMES UTF8;")

Change MySQL table Collation to: "utf-8-general, latin-1, latin-1-spanish...)

*Tried "Latin-1" encoding and didn't work either.

I have been looking for an answer to this question for a while with no luck.

Please help!

Versions:

MySQL 5.7.17

R version 3.3.0

Sys.getlocale()

```<code>[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=C"
</code>```

PS: Works fine in Linux environment but I am stuck with Windows in my current project :(

答:
This works for me in Windows:</p>

```<code>write.csv(table, file = "tmp.csv", fileEncoding = "utf8", quote = FALSE, row.names = FALSE)

db <- dbConnect(MySQL(), user = "####", password = "####", dbname ="test", host= "localhost")

dbWriteTable( db, value = "tmp.csv", name = "test1", append = TRUE, row.names = FALSE, sep = ",", quote='\"', eol="\r\n")
</code>```

Body:
While using RMySQL::dbWriteTable function in R to write a table to MySQL on Windows I get an error message concerning the character [ñ].

The simplified example is:

    table <- data.frame(a=seq(1:3), b=c("És", "España", "Compañía"))
    table

 a        b
1 1       És
2 2   España
3 3 Compañía

db <- dbConnect(MySQL(), user = "####", password = "####", dbname ="test", host= "localhost")

RMySQL::dbWriteTable(db, name="test1", table, overwrite=T, append=F )

Error in .local(conn, statement, ...) :
  could not run statement: Invalid utf8 character string: 'Espa'

As you can see, there is no problem with the accents ("És") but there is with the ñ character ("España").

On the other hand, there is no problem with MySQL since this query works fine:

INSERT INTO test.test1 (a,b)
values (1, "España");

Things I have already tried previous to write the table:

Encoding(x) <- "UTF-8" for all table.

iconv(x, "UTF-8", "UTF-8") for all table.

Sent pre-query: dbSendQuery(db, "SET NAMES UTF8;")

Change MySQL table Collation to: "utf-8-general, latin-1, latin-1-spanish...)

*Tried "Latin-1" encoding and didn't work either.

I have been looking for an answer to this question for a while with no luck.

Please help!

Versions:

MySQL 5.7.17

R version 3.3.0

Sys.getlocale()

[1] "LC_COLLATE=English_United States.1252;LC_CTYPE=English_United States.1252;LC_MONETARY=English_United States.1252;LC_NUMERIC=C;LC_TIME=C"

PS: Works fine in Linux environment but I am stuck with Windows in my current project :(

Body:
This works for me in Windows:

write.csv(table, file = "tmp.csv", fileEncoding = "utf8", quote = FALSE, row.names = FALSE)

db <- dbConnect(MySQL(), user = "####", password = "####", dbname ="test", host= "localhost")

dbWriteTable( db, value = "tmp.csv", name = "test1", append = TRUE, row.names = FALSE, sep = ",", quote='\"', eol="\r\n")


问:
Hiding an element after clicking outside in vue 2
I'm trying to hide a sidebar after clicking outside using Vue 2 and laravel. This sidebar was created inside a navbar component. At first, I added a @click="showSidenav = !showSidenav" just to open it and initialize data to showSidenav: false. And also added a close anchor tag to hide the sidebar. Working fine actually but when the thing comes in my mind that how about hiding it also when clicking outside the sidebar? I created a method showSidenav and perform the opening of the element and tried to use nextTick but it executes same time as when I call the method. For now I use jquery inside the method to change again the data but when I click again the hamburger menu it won't change the data.

template structure

```<code><a href="#" v-on-clickaway="away" @click="openSidenav">Hamburger menu</a>
</code>```

Script

```<code> import { mixin as clickaway } from 'vue-clickaway';
    export default {
         mixins: [ clickaway ],
         data() {
             return {
                 showSidenav: false,
             }
         },
         methods: {
             openSidenav: function () {
                 this.showSidenav = true
             },
             away: function () {
                this.showSidenav = false
             }
         }
    }
</code>```

EDIT: Added vue-clickaway as suggested by @Nathan.

答:
I just had this problem. Use vue-clickaway.

Their 'hello world' example:

```<code>import { mixin as clickaway } from 'vue-clickaway';

export default {
  mixins: [ clickaway ],
  template: '<p v-on-clickaway="away">Click away</p>',
  methods: {
    away: function() {
      console.log('clicked away');
    },
  },
};
</code>```

Body:
I'm trying to hide a sidebar after clicking outside using Vue 2 and laravel. This sidebar was created inside a navbar component. At first, I added a @click="showSidenav = !showSidenav" just to open it and initialize data to showSidenav: false. And also added a close anchor tag to hide the sidebar. Working fine actually but when the thing comes in my mind that how about hiding it also when clicking outside the sidebar? I created a method showSidenav and perform the opening of the element and tried to use nextTick but it executes same time as when I call the method. For now I use jquery inside the method to change again the data but when I click again the hamburger menu it won't change the data.

template structure

Hamburger menu

Script

 import { mixin as clickaway } from 'vue-clickaway';
    export default {
         mixins: [ clickaway ],
         data() {
             return {
                 showSidenav: false,
             }
         },
         methods: {
             openSidenav: function () {
                 this.showSidenav = true
             },
             away: function () {
                this.showSidenav = false
             }
         }
    }

EDIT: Added vue-clickaway as suggested by @Nathan.

Body:
I just had this problem. Use vue-clickaway.

Their 'hello world' example:

import { mixin as clickaway } from 'vue-clickaway';

export default {
  mixins: [ clickaway ],
  template: '<p v-on-clickaway="away">Click away</p>',
  methods: {
    away: function() {
      console.log('clicked away');
    },
  },
};


问:
Deserializing JSON and saving the object to MySQL database
I am trying to save an object from POST request to my service. The request is sending a JSON:

```<code>{
"FirstName": "Ronnsie",
"LastName": "Wesleeyson",
"BirthPlace": "Zagreb",
"Gender": "M",
"OIB": "12345678901",
"CurrentPlace": "Mauritius",
"Department": "D_21510"
}
</code>```

and the error I am getting is as follows:

```<code>{
"Message": "An error has occurred.",
"ExceptionMessage": "Error executing the command 'INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) VALUES (, , , Mauritius, 1, 21510, )'. The error is 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , Mauritius, 1, 21510, )' at line 1'." ...}
</code>```

Now the request hits the controller here:

```<code>    [HttpPost]
    [Route("")]
    public void Post([FromBody] Employee employee)
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }
</code>```

and the SaveEmployee function is as follows:

```<code>    public long SaveEmployee(Employee employee)
    {
        string sqlString = String.Format(
            "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
            employee.FirstName,
            employee.LastName,
            employee.BirthPlace,
            employee.CurrentPlace,
            employee.Gender == EmployeeGender.M ? 1 : 0,
            employee.Department.GetStringValue(),
            employee.OIB
        );

        MySqlCommand cmd = ExecuteSqlCommand(sqlString);
        return cmd.LastInsertedId;
    }

    MySqlCommand ExecuteSqlCommand(string sqlString)
    {
        try
        {
            // execute the SQL command
            MySqlCommand cmd = new MySqlCommand(sqlString, conn);
            cmd.ExecuteNonQuery();

            return cmd;
        }
        catch (MySqlException e)
        {
            // log the error
            throw new Exception(
                String.Format("Error executing the command '{0}'. The error is '{1}'.",
                             sqlString, e.Message));
        }
    }
</code>```

I can't seem to find any error in the SQL syntax. However, it might be that there is a problem deserializing enums, so here they are:

DepartmentCode.cs

[JsonConverter(typeof(StringEnumConverter))]
    public enum DepartmentCode
    {
        D_21510,
        D_21520,
        D_21540,
        D_21570,
        D_SLFIN,
        D_SLKPO
    }

```<code>public static class DepartmentCodeExtensions
{
    const string S_21510 = "21510";
    const string S_21520 = "21520";
    const string S_21540 = "21540";
    const string S_21570 = "21570";
    const string S_SLFIN = "SLFIN";
    const string S_SLKPO = "SLKPO";

    public static string GetStringValue(this DepartmentCode dep)
    {
        switch (dep)
        {
            case DepartmentCode.D_21510:
                return S_21510;

            case DepartmentCode.D_21520:
                return S_21520;

            case DepartmentCode.D_21540:
                return S_21540;

            case DepartmentCode.D_21570:
                return S_21570;

            case DepartmentCode.D_SLFIN:
                return S_SLFIN;

            case DepartmentCode.D_SLKPO:
                return S_SLKPO;

            default:
                throw new ArgumentException("Given department code not supported.");
        }
    }
</code>```

EmployeeGender.cs

```<code>[JsonConverter(typeof(StringEnumConverter))]
    public enum EmployeeGender
    {
        M,
        F
    }
</code>```

Any ideas on what's the error here?

答:
You have a SQL injection vulnerability. You should always parameterize your SQL and it is also the reason the query had a syntax error because you did not place the string parameters inside quotes. This is roughly what you want to do:</p>

```<code>public long SaveEmployee(Employee employee)
    {
string connStr = "server=localhost;user=root;database=world;port=3306;password=******;";
MySqlConnection conn = new MySqlConnection(connStr);
        string sqlString = "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES (@FirstName,@LastName,@BirthPlace,@CurrentPlace,@Gender,@Department,@OIB)";

cmd.Parameters.AddWithValue(“@FirstName”, employee.FirstName);
cmd.Parameters.AddWithValue(“@LastName”, employee.LastName);
cmd.Parameters.AddWithValue(“@BirthPlace”, employee.BirthPlace);
cmd.Parameters.AddWithValue(“@CurrentPlace”, employee.CurrentPlace);
cmd.Parameters.AddWithValue(“@Gender”, employee.Gender == EmployeeGender.M ? 1 : 0);
cmd.Parameters.AddWithValue(“@Department”, employee.Department.GetStringValue());
cmd.Parameters.AddWithValue(“@OIB”, employee.OIB);

        MySqlCommand cmd = ExecuteSqlCommand(sqlString, conn);
        return cmd.LastInsertedId;
    }
</code>```

Body:
I am trying to save an object from POST request to my service. The request is sending a JSON:

{
"FirstName": "Ronnsie",
"LastName": "Wesleeyson",
"BirthPlace": "Zagreb",
"Gender": "M",
"OIB": "12345678901",
"CurrentPlace": "Mauritius",
"Department": "D_21510"
}

and the error I am getting is as follows:

{
"Message": "An error has occurred.",
"ExceptionMessage": "Error executing the command 'INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) VALUES (, , , Mauritius, 1, 21510, )'. The error is 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , Mauritius, 1, 21510, )' at line 1'." ...}

Now the request hits the controller here:

    [HttpPost]
    [Route("")]
    public void Post([FromBody] Employee employee)
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }

and the SaveEmployee function is as follows:

    public long SaveEmployee(Employee employee)
    {
        string sqlString = String.Format(
            "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
            employee.FirstName,
            employee.LastName,
            employee.BirthPlace,
            employee.CurrentPlace,
            employee.Gender == EmployeeGender.M ? 1 : 0,
            employee.Department.GetStringValue(),
            employee.OIB
        );

        MySqlCommand cmd = ExecuteSqlCommand(sqlString);
        return cmd.LastInsertedId;
    }

    MySqlCommand ExecuteSqlCommand(string sqlString)
    {
        try
        {
            // execute the SQL command
            MySqlCommand cmd = new MySqlCommand(sqlString, conn);
            cmd.ExecuteNonQuery();

            return cmd;
        }
        catch (MySqlException e)
        {
            // log the error
            throw new Exception(
                String.Format("Error executing the command '{0}'. The error is '{1}'.",
                             sqlString, e.Message));
        }
    }

I can't seem to find any error in the SQL syntax. However, it might be that there is a problem deserializing enums, so here they are:

DepartmentCode.cs

[JsonConverter(typeof(StringEnumConverter))]
    public enum DepartmentCode
    {
        D_21510,
        D_21520,
        D_21540,
        D_21570,
        D_SLFIN,
        D_SLKPO
    }

public static class DepartmentCodeExtensions
{
    const string S_21510 = "21510";
    const string S_21520 = "21520";
    const string S_21540 = "21540";
    const string S_21570 = "21570";
    const string S_SLFIN = "SLFIN";
    const string S_SLKPO = "SLKPO";

    public static string GetStringValue(this DepartmentCode dep)
    {
        switch (dep)
        {
            case DepartmentCode.D_21510:
                return S_21510;

            case DepartmentCode.D_21520:
                return S_21520;

            case DepartmentCode.D_21540:
                return S_21540;

            case DepartmentCode.D_21570:
                return S_21570;

            case DepartmentCode.D_SLFIN:
                return S_SLFIN;

            case DepartmentCode.D_SLKPO:
                return S_SLKPO;

            default:
                throw new ArgumentException("Given department code not supported.");
        }
    }

EmployeeGender.cs

[JsonConverter(typeof(StringEnumConverter))]
    public enum EmployeeGender
    {
        M,
        F
    }

Any ideas on what's the error here?

Body:
You have a SQL injection vulnerability. You should always parameterize your SQL and it is also the reason the query had a syntax error because you did not place the string parameters inside quotes. This is roughly what you want to do:

public long SaveEmployee(Employee employee)
    {
string connStr = "server=localhost;user=root;database=world;port=3306;password=******;";
MySqlConnection conn = new MySqlConnection(connStr);
        string sqlString = "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES (@FirstName,@LastName,@BirthPlace,@CurrentPlace,@Gender,@Department,@OIB)";

cmd.Parameters.AddWithValue(“@FirstName”, employee.FirstName);
cmd.Parameters.AddWithValue(“@LastName”, employee.LastName);
cmd.Parameters.AddWithValue(“@BirthPlace”, employee.BirthPlace);
cmd.Parameters.AddWithValue(“@CurrentPlace”, employee.CurrentPlace);
cmd.Parameters.AddWithValue(“@Gender”, employee.Gender == EmployeeGender.M ? 1 : 0);
cmd.Parameters.AddWithValue(“@Department”, employee.Department.GetStringValue());
cmd.Parameters.AddWithValue(“@OIB”, employee.OIB);

        MySqlCommand cmd = ExecuteSqlCommand(sqlString, conn);
        return cmd.LastInsertedId;
    }


问:
PHP Authentication
Currently my authentication looks like this:

User enters username/password combination
 Sent to the server, the username and password are salted and hashed (md5) and checked against the database.

If correct, and the user has specified, a month long cookie is set.

If the user does not specify to set a cookie, they are automatically signed out after five minutes of inactivity.

My question is simply if I need to, and how to, make this more secure. I'm pretty fluent in PHP, but I'm not as well off in security. Any help, pointers, leads, and general assistance would be appreciated.

Thanks. :)

答:
Sounds like you are trying to invent a new authentification. Do not do - Follow Amir's advice instead.

But if you want to tweak the crypto by all means, here is an idea with Javascript:

The salt is not secret. Send it to the client, together with a nonce - another random value of enough entropy.

The client sends back nonce + hash(timestamp + hash(salt + password)). The server than checks if nonce is recent.

This would counter any replay attack.

(By + I denote concatenation.)

Title: PHP Authentication


问:
Set Xcode automatic signing to false and set provision profile and certificate with fastlane match and gym
We use Fusetools to build an app. Using the command uno build --target=ios --configuration=Release we generate a new myapp.xcodeproj file for the app.

When I open the .xcodeproj in Xcode IDE manually I see the Automatically manage signing checkbox is selected. We then use Fastlane match to get certificates and select appstore certificate manually in Xcode. This all works fine.

Now - we try to build this using a CI provider like Bitrise using a headless build process. Then everything stops at the same point. our .xcodeproj has Automatically manage signing checkbox is selected.

Our Fastfile looks like this:

```<code>disable_automatic_code_signing(path: "../myapp.xcodeproj")

match(git_url: "git@github.com:MyRepo/match.git",
      app_identifier: "com.myapp.myapp",
      type: "appstore",
      readonly: true)

gym(
      workspace: "myapp.xcworkspace",
      scheme: "MyApp",
      export_method: "app-store",
      xcargs: "PROVISIONING_PROFILE_SPECIFIER='match AppStore
      com.myapp.myapp'"
)
</code>```

In our Fastfile we try to disable automatic signing first, the in gym - pass in parameter xcargs: "PROVISIONING_PROFILE_SPECIFIER='match AppStore com.myapp.myapp'" to set the provisioning profile before build.

I then get this from Bitrise CI monitor:

Code signing is required for product type 'Application' in SDK 'iOS 10.3'

I can reproduce this if running locally trying to set automatic signing to false and do the same.

Any idea?

答:
xcargs: "PROVISIONING_PROFILE_SPECIFIER='match AppStore com.myapp.myapp'"

This approach doesn't work well any more since apps might have multiple targets. Instead check out the Xcode setup guide that describes that you can use environment variables, that are being filled by match, for each target's provisioning profile name option

ContentLicense: CC BY-SA 4.0

Body:
We use Fusetools to build an app. Using the command uno build --target=ios --configuration=Release we generate a new myapp.xcodeproj file for the app.

When I open the .xcodeproj in Xcode IDE manually I see the Automatically manage signing checkbox is selected. We then use Fastlane match to get certificates and select appstore certificate manually in Xcode. This all works fine.

Now - we try to build this using a CI provider like Bitrise using a headless build process. Then everything stops at the same point. our .xcodeproj has Automatically manage signing checkbox is selected.

Our Fastfile looks like this:

disable_automatic_code_signing(path: "../myapp.xcodeproj")

match(git_url: "git@github.com:MyRepo/match.git",
      app_identifier: "com.myapp.myapp",
      type: "appstore",
      readonly: true)

gym(
      workspace: "myapp.xcworkspace",
      scheme: "MyApp",
      export_method: "app-store",
      xcargs: "PROVISIONING_PROFILE_SPECIFIER='match AppStore
      com.myapp.myapp'"
)

In our Fastfile we try to disable automatic signing first, the in gym - pass in parameter xcargs: "PROVISIONING_PROFILE_SPECIFIER='match AppStore com.myapp.myapp'" to set the provisioning profile before build.

I then get this from Bitrise CI monitor:

Code signing is required for product type 'Application' in SDK 'iOS 10.3'

I can reproduce this if running locally trying to set automatic signing to false and do the same.

Any idea?


问:
Find position of last Non Null element in a list in C#
I have the following values in my MySQL DB

```<code>Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null
</code>```

and I have create the a list in the below format

```<code>List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);
</code>```

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

答:
```<code>var date = StockData.Where(lst=>lst.High_Low_Price!=null).OrderByDescending(lst=>lst.Date).FirstOrDefault().Date;
</code>```

Body:
I have the following values in my MySQL DB

Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null

and I have create the a list in the below format

List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.


问:
Refreshing a textbox on screen
I have a process that runs a series of tasks and with each tasks updates a text box, my issue is however that the screen doesnt load until all the tasks are done, and I need to see them as they happen. In my old language of VBA this would have been DoEvents or Me.Repaint. What am I doing wrong causing my text box to not show what is sent to it each time something is sent to it?

This is in ASP.net and C#. This is the aspx page:-

```<code><%@ Page Title="ASC Open" Language="C#" AutoEventWireup="true" CodeBehind="ASC_OSC.aspx.cs" Inherits="HICS.ASC_OSC" %>

<head runat="server">
    <title>HICS</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>
    <webopt:BundleReference runat="server" Path="~/Content/css" />
</head>
<body style="padding-top: 5px">
    <form id="main" runat="server">
        <div class="container-fluid" style="padding-top: 0px">
            <h1>Open Access Supply Chain</h1>
            <hr />
            <div class="container-fluid">
              <div ID="ContRow" class="row">
                <div class="col-md-12">
                    <asp:TextBox ID="TxtStatus" runat="server" Height="80%" Width="80%" ReadOnly="true" Wrap="true" AutoPostBack="false" TextMode="MultiLine"></asp:TextBox>
                </div>
              </div>
            </div>
        </div>
    </form>
</body>
</code>```

And this is the snippet of C# (not all showing as it is representative), it is TxtStatus that I care about right now.

```<code>using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Web;
using System.Web.UI;
//using System.Web.UI.WebControls;
//using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace HICS
{
    public partial class ASC_OSC : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlDataReader RS;
            int     IntPort;
            int     IntEnvironment;
            bool    BlnOK;
            string StrEnvironmentName;
            string StrEnvironmentDB;
            Database DB_ASC = new Database();

            if (!IsPostBack)
            {
                BlnOK = true;
                TxtStatus.Text += "Getting Port: ";
                string StrReturn = home.Procs.UserSetting("ASC_Port");
                if (StrReturn == "" || StrReturn == "0")
                {
                    RS = home.DB_HICS.GetRS("SELECT MAX([ASC_Port]) FROM [Tb_Users]");
                    RS.Read();
                    IntPort = (RS.GetInt32(0) < 4444)? 4444 : RS.GetInt32(0) + 1;
                    home.Procs.UserSetting("ASC_Port", IntPort.ToString());
                    RS.Close();
                }
                else
                {
                    IntPort = Convert.ToInt32(StrReturn);
                }
                TxtStatus.Text += String.Concat(IntPort.ToString() , Environment.NewLine);

                TxtStatus.Text += "Getting Environment: ";
                IntEnvironment = 0;
                StrReturn = home.Procs.UserSetting("ASC_Environment");
                if (StrReturn == "" || StrReturn == "0")
                {
                    RS = home.DB_HICS.GetRS("SELECT MIN([ID]) FROM [Tb_ASC_Environments]");
                    RS.Read();
                    if (RS.IsDBNull(0))
                    {
                       BlnOK = false;
                    }
                    else
                    {
                        IntEnvironment = RS.GetInt32(0);
                        home.Procs.UserSetting("ASC_Environment", IntEnvironment.ToString());
                    }
                    RS.Close();
                }
                else
                {
                    IntEnvironment = Convert.ToInt32(StrReturn);
                    RS = home.DB_HICS.GetRS("SELECT COUNT([ID]) FROM [Tb_ASC_Environments] WHERE [ID] = " + IntEnvironment);
                    RS.Read();
                    if (RS.GetInt32(0)==0)
                    {
                        RS.Close();
                        RS = home.DB_HICS.GetRS("SELECT MIN([ID]) FROM [Tb_ASC_Environments]");
                        RS.Read();
                        if (RS.IsDBNull(0))
                        {
                            BlnOK = false;
                        }
                        else
                        {
                            IntEnvironment = RS.GetInt32(0);
                            home.Procs.UserSetting("ASC_Environment", IntEnvironment.ToString());
                        }
                    }
                    RS.Close();
                }
                TxtStatus.Text += String.Concat((BlnOK)?IntEnvironment.ToString():"Error", Environment.NewLine);

                if (BlnOK)
                {
                    RS = home.DB_HICS.GetRS("SELECT [Name],[Database] FROM [Tb_ASC_Environments] WHERE [ID] = " + IntEnvironment);
                    RS.Read();
                    StrEnvironmentName = RS.GetString(0);
                    StrEnvironmentDB = RS.GetString(1);
                    TxtStatus.Text += String.Concat("Environment Name: ", StrEnvironmentName, Environment.NewLine);
                    TxtStatus.Text += String.Concat("Environment Database: ", StrEnvironmentDB, Environment.NewLine);
                    TxtStatus.Text += "Connecting to ASC Database: ";

                }
            }
        }
    }
}
</code>```

答:
You need to understand that a web page is fundamentally different from a desktop client application where you can DoEvents and Repaint whenever you need. ASP.NET is executed server side and thus performs a full round trip between submitting a page and processing events on the server.

If you start a long running task and want to get progress information, you need to use AJAX.

See Introduction to the UpdateProgress Control for a older concept

or

track the progress of a database save in a “live” progress bar asp.net mvc for a modern approach

... you'll have to make a choice for your specific scenario.

Title: Refreshing a textbox on screen

Body:
I have a process that runs a series of tasks and with each tasks updates a text box, my issue is however that the screen doesnt load until all the tasks are done, and I need to see them as they happen. In my old language of VBA this would have been DoEvents or Me.Repaint. What am I doing wrong causing my text box to not show what is sent to it each time something is sent to it?

This is in ASP.net and C#. This is the aspx page:-

<%@ Page Title="ASC Open" Language="C#" AutoEventWireup="true" CodeBehind="ASC_OSC.aspx.cs" Inherits="HICS.ASC_OSC" %>

    <title>HICS</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <asp:PlaceHolder runat="server">
        <%: Scripts.Render("~/bundles/modernizr") %>
    </asp:PlaceHolder>
    <webopt:BundleReference runat="server" Path="~/Content/css" />

    <form id="main" runat="server">

Open Access Supply Chain

                    <asp:TextBox ID="TxtStatus" runat="server" Height="80%" Width="80%" ReadOnly="true" Wrap="true" AutoPostBack="false" TextMode="MultiLine"></asp:TextBox>

    </form>

And this is the snippet of C# (not all showing as it is representative), it is TxtStatus that I care about right now.

using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Web;
using System.Web.UI;
//using System.Web.UI.WebControls;
//using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace HICS
{
    public partial class ASC_OSC : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlDataReader RS;
            int     IntPort;
            int     IntEnvironment;
            bool    BlnOK;
            string StrEnvironmentName;
            string StrEnvironmentDB;
            Database DB_ASC = new Database();

            if (!IsPostBack)
            {
                BlnOK = true;
                TxtStatus.Text += "Getting Port: ";
                string StrReturn = home.Procs.UserSetting("ASC_Port");
                if (StrReturn == "" || StrReturn == "0")
                {
                    RS = home.DB_HICS.GetRS("SELECT MAX([ASC_Port]) FROM [Tb_Users]");
                    RS.Read();
                    IntPort = (RS.GetInt32(0) < 4444)? 4444 : RS.GetInt32(0) + 1;
                    home.Procs.UserSetting("ASC_Port", IntPort.ToString());
                    RS.Close();
                }
                else
                {
                    IntPort = Convert.ToInt32(StrReturn);
                }
                TxtStatus.Text += String.Concat(IntPort.ToString() , Environment.NewLine);

                TxtStatus.Text += "Getting Environment: ";
                IntEnvironment = 0;
                StrReturn = home.Procs.UserSetting("ASC_Environment");
                if (StrReturn == "" || StrReturn == "0")
                {
                    RS = home.DB_HICS.GetRS("SELECT MIN([ID]) FROM [Tb_ASC_Environments]");
                    RS.Read();
                    if (RS.IsDBNull(0))
                    {
                       BlnOK = false;
                    }
                    else
                    {
                        IntEnvironment = RS.GetInt32(0);
                        home.Procs.UserSetting("ASC_Environment", IntEnvironment.ToString());
                    }
                    RS.Close();
                }
                else
                {
                    IntEnvironment = Convert.ToInt32(StrReturn);
                    RS = home.DB_HICS.GetRS("SELECT COUNT([ID]) FROM [Tb_ASC_Environments] WHERE [ID] = " + IntEnvironment);
                    RS.Read();
                    if (RS.GetInt32(0)==0)
                    {
                        RS.Close();
                        RS = home.DB_HICS.GetRS("SELECT MIN([ID]) FROM [Tb_ASC_Environments]");
                        RS.Read();
                        if (RS.IsDBNull(0))
                        {
                            BlnOK = false;
                        }
                        else
                        {
                            IntEnvironment = RS.GetInt32(0);
                            home.Procs.UserSetting("ASC_Environment", IntEnvironment.ToString());
                        }
                    }
                    RS.Close();
                }
                TxtStatus.Text += String.Concat((BlnOK)?IntEnvironment.ToString():"Error", Environment.NewLine);

                if (BlnOK)
                {
                    RS = home.DB_HICS.GetRS("SELECT [Name],[Database] FROM [Tb_ASC_Environments] WHERE [ID] = " + IntEnvironment);
                    RS.Read();
                    StrEnvironmentName = RS.GetString(0);
                    StrEnvironmentDB = RS.GetString(1);
                    TxtStatus.Text += String.Concat("Environment Name: ", StrEnvironmentName, Environment.NewLine);
                    TxtStatus.Text += String.Concat("Environment Database: ", StrEnvironmentDB, Environment.NewLine);
                    TxtStatus.Text += "Connecting to ASC Database: ";

                }
            }
        }
    }
}


问:
Q: Rails Best Practices for database calls
Quick question. I am building out a portfolio application for an artist, currently have 9 tables of different types of projects (exhibitions, press, news, texts, photography, etc). As a visual artist, he wants his site to represent his vision.

Background:

edit: The information is loaded from the controller originally, not from an API call. I later changed it to an API call because I was worried 9 calls from the controller was too much.

This means the site is graphic and information heavy. Loading all the information just for the navigation was 15 mb (and this was after shrinking the images when needed and running them through tinypng). I put all the information off to different layout views to be rendered only when needed to keep loading times down and offset it, which helped speed everything. But this setup no matter which way resulted in 9 different database calls on each page load.

I rebuilt the back end to API endpoints, so the information is only pulled from the database when needed. This has slightly increased the load time for the information though, only like a second more if that. I'm not bothered by it, but the artist might be.

Actual Question

So I've been wondering for the past few days, is 9 database calls too much at once and how will it affect scalability? Postgres database for reference. Normal load, I cant imagine too many users will view the site on any given time, so I wouldnt be worried about it. But when he has an exhibition and there are 100-500 people using the site at once, thats 900-4500 database calls each page load. Or with the API route, people may only do 1 or 2 calls before finding what they want. I just want to follow the industry best practice for handling this situation and this seemed like a good time to ask this question.

Also, this will be hosted on heroku currently, and wondering which way (all at once or API routes) will be better for handling postgres connections since the free tier (which will be enough 95% of the time) has a limit of 20 connections. Though for months where he has a show we could bump it up to the next tier for 60 connections.

答:
Have a look at this blog post about Rails Database Best Practices.

Without knowing too much about your application, see if you can reduce the number of database calls with scopes and/or query objects. Combining calls with a .includes() or .join() is a way to reduce the load as well. See if the data can be aggregated with .group() or .having(). If each call is necessary, then you can potentially increase the speed of the query by introducing some indexing.

From my experience, I wouldn't say there's an industry standard for the maximum number of database calls a page load should have; it really depends on the data being returned.


问:
Is there any posibility to put model classes in abstract sphere?
I want to put the autogenerated part of model into abstract sphere, for example if i generate model for table users, \Model\Entity\User and \Model\Table\UsersTable, I dont want to write code in these classes, i want to create a implementation class, for example \Model\Table\UserTableImpl which extends \Model\Table\UsersTable, and write a queries code in there, so my question is:

Is there any posibility to make these implementation classes autoload with controller, in the way that loadModel work?

Thanks for any help.

答:
You could simply rename the generated classes (eg AbstractUsersTable), mark them as abstract, and then create implementations with names that follow the CakePHP naming conventions (eg UsersTable extends AbstractUsersTable), that way you don't have to deal with further configuration for the table locator, your associations, etc.

That being said, you can always use fully qualified classnames to load table classes, to configure classes for associations, to set a controllers default table class, etc.

```<code>// load model
$this->loadModel(\App\Model\Table\UnconventionalClassName::class);
</code>```

```<code>// set default controller table class
$this->_setModelClass(\App\Model\Table\UnconventionalClassName::class);
</code>```

```<code>// configure association class
$this->associationType('Alias', [
    'className' => \App\Model\Table\UnconventionalClassName::class
]);
</code>```

```<code>// set tables entity class
$this->setEntityClass(\App\Model\Entity\UnconventionalClassName::class);
</code>```

...

You could even go further and create custom locators and associations that change the default Table suffix to something different, but I'd rather go with method number 1 and follow the conventions.

Body:
You could simply rename the generated classes (eg AbstractUsersTable), mark them as abstract, and then create implementations with names that follow the CakePHP naming conventions (eg UsersTable extends AbstractUsersTable), that way you don't have to deal with further configuration for the table locator, your associations, etc.

That being said, you can always use fully qualified classnames to load table classes, to configure classes for associations, to set a controllers default table class, etc.

// load model
$this->loadModel(\App\Model\Table\UnconventionalClassName::class);

// set default controller table class
$this->_setModelClass(\App\Model\Table\UnconventionalClassName::class);

// configure association class
$this->associationType('Alias', [
    'className' => \App\Model\Table\UnconventionalClassName::class
]);

// set tables entity class
$this->setEntityClass(\App\Model\Entity\UnconventionalClassName::class);

...

You could even go further and create custom locators and associations that change the default Table suffix to something different, but I'd rather go with method number 1 and follow the conventions.


问:
AngularJS : get datas from (api rest)Symfony's url result
I am trying to retrieve datas from my Restful api symfony with AngularJS, but i get this error "Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object".

Here is my Symfony controller :

```<code>$agent = $this->get('doctrine')
        ->getRepository('CERAgentBundle:Agent', 'agent')
        ->findByCode($employeeID);

    $session = new Session();
    $session->set('agent', $agent);

    $formatted = [
        'civilite' => $agent[0]->getCivilite(),
        'prenom' => $agent[0]->getPrenom(),
        'nom' => $agent[0]->getNom(),
        ];

    return $formatted;
}
</code>```

that give me :
result

Here is my AngularJS controller :

```<code>angular.module('frontProfilDeveloppementApp')
.controller('AboutCtrl', function ($scope, $http, $sce){
  var url = $sce.trustAsResourceUrl('http://localhost:8000/index');
  $http.get({
      method:'GET',
      url:url})
      .success(function (data) {
          $scope.result = data;
      });
</code>```

});

My Angular view :

```<code><div ng-app="frontProfilDeveloppementApp" ng-controller="AboutCtrl">

<p>Today's welcome message is:</p>

<h1>{{result.nom}}</h1>
</code>```

Thanks for help

答:
Looking over the documentation for SCE, it appears that you're not using it for its intended use. SCE is more for rendering raw html/css into the DOM from a trusted source without having it parsed for vulnerabilities since it's treated as trusted. In the case of the URL, you'd use SCE to bind it safely somewhere in a template, but your use case doesn't seem appropriate, why not just use a string?

If anything, you probably want to use SCE for the actual content retrieved, not the URL used to retrieve the content itself.

Body:
I am trying to retrieve datas from my Restful api symfony with AngularJS, but i get this error "Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object".

Here is my Symfony controller :

$agent = $this->get('doctrine')
        ->getRepository('CERAgentBundle:Agent', 'agent')
        ->findByCode($employeeID);

    $session = new Session();
    $session->set('agent', $agent);

    $formatted = [
        'civilite' => $agent[0]->getCivilite(),
        'prenom' => $agent[0]->getPrenom(),
        'nom' => $agent[0]->getNom(),
        ];

    return $formatted;
}

that give me :
result

Here is my AngularJS controller :

angular.module('frontProfilDeveloppementApp')
.controller('AboutCtrl', function ($scope, $http, $sce){
  var url = $sce.trustAsResourceUrl('http://localhost:8000/index');
  $http.get({
      method:'GET',
      url:url})
      .success(function (data) {
          $scope.result = data;
      });

});

My Angular view :

Today's welcome message is:

{{result.nom}}

Thanks for help