问:
Split a string into a String[] of a specific size
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

```<code>String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]
</code>```

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

答:
I don’t remember all the syntax by heart, but your are looking at something like this:

```<code>Pattern p = new Pattern("[^,]+");
String[] strings = new String[limit];
int offset = 0;
int i = 0;
for (; i < limit; i++) {
    Match m = str.match(p, offset);
    if (m == null) break;
    offset += m.string.length + 1;
    strings[i] = m.string;
}
for (; i < limit; i++) {
    strings[i] = "";
}
</code>```

Again, this is not valid Java

Body:
Assuming my delimiter is ',' (comma), I'm looking for a function split that will guarantee that the returned String[] array is a certain size (no more, no less):

String[] split(String str, int limit);

split("hello", 2);               => ["hello", ""]
split("hello,", 2);              => ["hello", ""]
split(",hello", 2);              => ["", "hello"]
split("hello,world", 2);         => ["hello", "world"]
split("hello,world,goodbye", 2); => ["hello", "world,goodbye"]

See how the array size is always 2? I can get some of this behavior with Pattern.split, but not for every case... How can I do this?

Body:
I don’t remember all the syntax by heart, but your are looking at something like this:

Pattern p = new Pattern("[^,]+");
String[] strings = new String[limit];
int offset = 0;
int i = 0;
for (; i < limit; i++) {
    Match m = str.match(p, offset);
    if (m == null) break;
    offset += m.string.length + 1;
    strings[i] = m.string;
}
for (; i < limit; i++) {
    strings[i] = "";
}

Again, this is not valid Java


来源: stackexchange

问:
Looping through web pages to webscrape data
I'm trying to loop through Zillow pages and extract data. I know that the URL is being updated with a new page number after each iteration but the data extracted is as if the URL is still on page 1.</p>

```<code>import selenium
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import pandas as pd

next_page='https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/'

num_data1=pd.DataFrame(columns=['name','number'])

browser=webdriver.Chrome()
browser.get('https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/')

while True:

    page=requests.get(next_page)

    contents=page.content

    soup = BeautifulSoup(contents, 'html.parser')

    number_p=soup.find_all('p', attrs={'class':'ldb-phone-number'},text=True)
    name_p=soup.find_all('p', attrs={'class':'ldb-contact-name'},text=True)

    number_p=pd.DataFrame(number_p,columns=['number'])
    name_p=pd.DataFrame(name_p,columns=['name'])

    num_data=number_p['number'].apply(lambda x: x.text.strip())
    nam_data=name_p['name'].apply(lambda x: x.text.strip())

    number_df=pd.DataFrame(num_data,columns=['number'])
    name_df=pd.DataFrame(nam_data,columns=['name'])

    num_data0=pd.concat([number_df,name_df],axis=1)

    num_data1=num_data1.append(num_data0)

        try:

            button=browser.find_element_by_css_selector('.zsg-pagination>li.zsg-pagination-next>a').click()
            next_page=str(browser.current_url)

        except IndexError:

            break
</code>```

答:
Replace page=requests.get(next_page) with page = browser.page_source

Basically what's happening is that you're going to the next page in Chrome, but then trying to load that page's url with requests which is getting redirected back to page one by Zillow (probably because it doesn't have the cookies or appropriate request headers).

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to loop through Zillow pages and extract data. I know that the URL is being updated with a new page number after each iteration but the data extracted is as if the URL is still on page 1.

import selenium
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import pandas as pd

next_page='https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/'

num_data1=pd.DataFrame(columns=['name','number'])

browser=webdriver.Chrome()
browser.get('https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/')

while True:

    page=requests.get(next_page)

    contents=page.content

    soup = BeautifulSoup(contents, 'html.parser')

    number_p=soup.find_all('p', attrs={'class':'ldb-phone-number'},text=True)
    name_p=soup.find_all('p', attrs={'class':'ldb-contact-name'},text=True)

    number_p=pd.DataFrame(number_p,columns=['number'])
    name_p=pd.DataFrame(name_p,columns=['name'])

    num_data=number_p['number'].apply(lambda x: x.text.strip())
    nam_data=name_p['name'].apply(lambda x: x.text.strip())

    number_df=pd.DataFrame(num_data,columns=['number'])
    name_df=pd.DataFrame(nam_data,columns=['name'])

    num_data0=pd.concat([number_df,name_df],axis=1)

    num_data1=num_data1.append(num_data0)

        try:

            button=browser.find_element_by_css_selector('.zsg-pagination>li.zsg-pagination-next>a').click()
            next_page=str(browser.current_url)

        except IndexError:

            break


问:
Python: Creating column based on a condition from the other dataframe
I have two data frames as follows:

```<code> df1=
   date               company      userDomain   keyword  pageViews category
  2015-12-02   1-800 Contacts     glasses.com     SAN          2   STORAGE
  2015-12-02   1-800 Contacts        rhgi.com     SAN          3   STORAGE
  2015-12-02  100 Percent Fun dialogdesign.ca     SAN          1   STORAGE
  2015-12-02       101netlink  101netlink.com     SAN          8   STORAGE
  2015-12-02             1020       nlc.bc.ca     SAN          4   STORAGE

df2=
                      Outcome                     Job Title  Wave
          Created Opportunity                    IT Manager   1.0
  Closed Out Prospect/Contact        Infrastructure Manager   1.0
                          NaN                   IT Director   1.0
                          NaN  Supervisor Technical Support   1.0
          Created Opportunity       Director of IT Services   1.0

           Wave Date       userDomain
 2016-02-16 15:07:05  dialogdesign.ca
 2016-02-16 15:07:05         rhgi.com
 2016-02-16 15:07:05     surefire.com
 2016-02-16 15:07:05      isd2144.org
 2016-02-16 15:07:05        nlc.bc.ca
</code>```

I would like to add a column in df1 called wave_date with dates from df2['Wave Date'] for all the df1['userDomain'] is in the df2['userDomain']
If there is no match of userDomain in both the frames, the value should be nan. I'm sorry if this is a very naive question but I'm frustrated with my failure. What I'm doing is something like this:

```<code>df1['wave_date'] = df1.apply(lambda x: df2['Wave Date'] if x['userDomain'].isin(df2['userDomain']) else np.nan)
</code>```

I keep getting

IndexError: ('userDomain', 'occurred at index date')
  Can you please point out the correct to do it? Thanks a lot

答:
```<code>m = dict(zip(df2['userDomain'], df2['Wave Date']))
df1.assign(wave_date=df1.userDomain.map(m))

         date          company       userDomain keyword  pageViews category            wave_date
0  2015-12-02   1-800 Contacts      glasses.com     SAN          2  STORAGE                  NaN
1  2015-12-02   1-800 Contacts         rhgi.com     SAN          3  STORAGE  2016-02-16 15:07:05
2  2015-12-02  100 Percent Fun  dialogdesign.ca     SAN          1  STORAGE  2016-02-16 15:07:05
3  2015-12-02       101netlink   101netlink.com     SAN          8  STORAGE                  NaN
4  2015-12-02             1020        nlc.bc.ca     SAN          4  STORAGE  2016-02-16 15:07:05
</code>```

Body:
I have two data frames as follows:

 df1=
   date               company      userDomain   keyword  pageViews category
  2015-12-02   1-800 Contacts     glasses.com     SAN          2   STORAGE
  2015-12-02   1-800 Contacts        rhgi.com     SAN          3   STORAGE
  2015-12-02  100 Percent Fun dialogdesign.ca     SAN          1   STORAGE
  2015-12-02       101netlink  101netlink.com     SAN          8   STORAGE
  2015-12-02             1020       nlc.bc.ca     SAN          4   STORAGE

df2=
                      Outcome                     Job Title  Wave
          Created Opportunity                    IT Manager   1.0
  Closed Out Prospect/Contact        Infrastructure Manager   1.0
                          NaN                   IT Director   1.0
                          NaN  Supervisor Technical Support   1.0
          Created Opportunity       Director of IT Services   1.0

           Wave Date       userDomain
 2016-02-16 15:07:05  dialogdesign.ca
 2016-02-16 15:07:05         rhgi.com
 2016-02-16 15:07:05     surefire.com
 2016-02-16 15:07:05      isd2144.org
 2016-02-16 15:07:05        nlc.bc.ca

I would like to add a column in df1 called wave_date with dates from df2['Wave Date'] for all the df1['userDomain'] is in the df2['userDomain']
If there is no match of userDomain in both the frames, the value should be nan. I'm sorry if this is a very naive question but I'm frustrated with my failure. What I'm doing is something like this:

df1['wave_date'] = df1.apply(lambda x: df2['Wave Date'] if x['userDomain'].isin(df2['userDomain']) else np.nan)

I keep getting

IndexError: ('userDomain', 'occurred at index date')
  Can you please point out the correct to do it? Thanks a lot


问:
Add to ArrayList from different WebForms
I have 2 web forms in webform1 I have 2 buttons (Add and Show_WebForm2) and a textbox. In WebForm1, when the user types in the names in the textbox and clicks add button the name is added to the ArrayList. When the user is done typing in the names in WebForm1 they open WebForms2. In WebForms2 there is also a textbox and an add button. When the user types in the names in this TextBox I want it to be added to the same ArrayList variable which I used in WebForm1. How can I achieve this?

```<code>    public ArrayList FullNameApplicantArray = new ArrayList();
    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text +")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/WebForm2.aspx");

    }
</code>```

```<code>    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }
</code>```

答:
You'll want to create a second instance of the ArrayList on the second form and assign it to what is saved in session. </p>

```<code>public ArrayList FullNameApplicantArray = (ArrayList)Session["ListOfApplicants"];

protected void Button1_Click(object sender, EventArgs e)
{
    FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
    Session["ListOfApplicants"] = FullNameApplicantArray;

    foreach (var item in Session["ListOfApplicants"].ToString())
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
}
</code>```

Body:
I have 2 web forms in webform1 I have 2 buttons (Add and Show_WebForm2) and a textbox. In WebForm1, when the user types in the names in the textbox and clicks add button the name is added to the ArrayList. When the user is done typing in the names in WebForm1 they open WebForms2. In WebForms2 there is also a textbox and an add button. When the user types in the names in this TextBox I want it to be added to the same ArrayList variable which I used in WebForm1. How can I achieve this?

    public ArrayList FullNameApplicantArray = new ArrayList();
    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text +")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/WebForm2.aspx");

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
        Session["ListOfApplicants"] = FullNameApplicantArray[0];

        foreach (var item in Session["ListOfApplicants"].ToString())
        {
            Debug.Write(item);
        }
        Debug.WriteLine("");
    }

Body:
You'll want to create a second instance of the ArrayList on the second form and assign it to what is saved in session.

public ArrayList FullNameApplicantArray = (ArrayList)Session["ListOfApplicants"];

protected void Button1_Click(object sender, EventArgs e)
{
    FullNameApplicantArray.Add("(" + TextBox1.Text + ")");
    Session["ListOfApplicants"] = FullNameApplicantArray;

    foreach (var item in Session["ListOfApplicants"].ToString())
    {
        Debug.Write(item);
    }
    Debug.WriteLine("");
}


问:
Import data from Excel using SSIS without knowing sheet name
I have a spreadsheet that is updated by another server (out of my control) and I need to automate bringing that data into SQL 2005.  The data is always the first page of the spreadsheet.  However, the name of that sheet changes depending on the number of rows.

Is there a way to run an SSIS job that pulls in data from Excel without knowing the sheetname beforehand?  It seems to rely on the sheet name as the data source, but I'm looking to tell it "sheet number 1" or something similar.

答:
I would script out the Worksheet name to a SSIS User Variable. If you are not opposed to inserting a script task into your SSIS package try this: (Based on link text )</p>

```<code>Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open("<Name of your excel app>.xls", 0, xlWorkBook true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Look up worksheet by index
Excel.Worksheet xlWorkSheet =(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

user::worksheetname = xlWorkSheet.Name;

/* Do clean up.  Working with COM object */
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would script out the Worksheet name to a SSIS User Variable. If you are not opposed to inserting a script task into your SSIS package try this: (Based on link text )

Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open("<Name of your excel app>.xls", 0, xlWorkBook true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Look up worksheet by index
Excel.Worksheet xlWorkSheet =(Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

user::worksheetname = xlWorkSheet.Name;

/* Do clean up.  Working with COM object */


问:
How to Depict Either/Or Inheritance in a UML diagram?
So lets say I have a class CelebrityDog. CelebrityDog can either be a BigDog or a SmallDog depending on what the user wants.

It will inherit the properties of one of them, but not of both. How would I depict this in a UML diagram?

答:
UML perspective

I am sorry to come with an unpleasant answer, but this is not possible in UML according to the UML 2.5 standard, section 9.2.4.1:

Generalizations define generalization/specialization relationships
  between Classifiers. Each Generalization relates a specific Classifier
  to a more general Classifier.

  ...

  An instance of a Classifier is also an (indirect) instance of each of
  its generalizations. Any Constraints applying to instances of the
  generalizations also apply to instances of the Classifier.

In other words, an inheritance relation in UML is a relationship between a generalization and a specialization.  A class can be the specialization of several more generalization class but always in the same time (i.e. multiple inheritance.

Design perspective

I'll add to the already unpleasant answer, that this is anyways a very bad desgin, that you will not be able to implement in most of the mainstream languages.

You can improve with a model that is closer to the reality of the relationsips:

CelebrityDog is a Dog (inheritance, this is always true)

Dog has a DogSize (association, i.e. composition when implementing) which can change over time

DogSize can be specialized into BigDogSize or SmallDogSize

Et voilà !


问:
Generate SQLite database scheme from Java code
Is there any way to generate SQLite database model from Java code using JOOQ?</p>

答:
You can generate DDL statements like CREATE TABLE .. or ALTER TABLE .. ADD CONSTRAINT .. using the DSLContext.ddl() API, for instance:

// SCHEMA is the generated schema that contains a reference to all generated tables
Queries ddl =
DSL.using(configuration)
   .ddl(SCHEMA);

for (Query query : ddl.queries()) {
    System.out.println(query);
}
```

This is documented here:
https://www.jooq.org/doc/latest/manual/sql-building/ddl-statements/generating-ddl/

Body:
You can generate DDL statements like CREATE TABLE .. or ALTER TABLE .. ADD CONSTRAINT .. using the DSLContext.ddl() API, for instance:

// SCHEMA is the generated schema that contains a reference to all generated tables
Queries ddl =
DSL.using(configuration)
   .ddl(SCHEMA);

for (Query query : ddl.queries()) {
    System.out.println(query);
}

This is documented here:
https://www.jooq.org/doc/latest/manual/sql-building/ddl-statements/generating-ddl/


问:
Determining if get handler in Proxy object is handling a function call
I currently have a Proxy object that I want to capture property calls to if the property is not defined.
A basic version of my code would be something like this.

```<code>var a = new Proxy({}, {
    get: function(target, name, receiver) {
        if (target in name) {
            return target[name];
        } else {
            function a() {
                return arguments;
            }
            var args = a();
            return [target, name, receiver, args];
        }
    }
});
</code>```

Property calls to a here (i.e: a.b; a.c() etc) should return the target, name, receiver and arguments of the property call.

The problem I wish to solve, however, requires me to know whether the property call is for a property or a function, such that I can apply different treatments to each. Checking the length of the arguments object does not work, as calling a.c() would yield a length of 0 just like a.b, so it would be treated as a plain property and not a method.

Is there a way, therefore, to identify whether the property attempting to be accessed is being called as a function or not.

UPDATE: I should clarify, this method needs to work if the accessed property/method is undefined, as well as existing.

答:
It's possible in a very hacky way. We return a function if the property is undefined. If this function is called, then we know the user was trying to call the property as a function. If it never is, it was called as a property. To check if the function was called, we take advantage of the fact that a Promise's callback is called in the next iteration of the event loop. This means that we won't know if it's a property or not until later, as the user needs a chance to call the function first (as our code is a getter).

One drawback of this method is that the value returned from the object will be the new function, not undefined, if the user was expecting a property. Also this won't work for you if you need the result right away and can't wait until the next event loop iteration.

const obj = {
  func: undefined,
  realFunc: () => "Real Func Called",
  prop: undefined,
  realProp: true
};

const handlers = {
  get: (target, name) => {
    const prop = target[name];
    if (prop != null) { return prop; }

    let isProp = true;
    Promise.resolve().then(() => {
      if (isProp) {
        console.log(`Undefined ${name} is Prop`)
      } else {
        console.log(`Undefined ${name} is Func`);
      }
    });
    return new Proxy(()=>{}, {
      get: handlers.get,
      apply: () => {
        isProp = false;
        return new Proxy(()=>{}, handlers);
      }
    });
  }
};

const proxied = new Proxy(obj, handlers);

let res = proxied.func();
res = proxied.func;
res = proxied.prop;
res = proxied.realFunc();
console.log(`realFunc: ${res}`);
res = proxied.realProp;
console.log(`realProp: ${res}`);
proxied.propC1.funcC2().propC3.funcC4().funcC5();```

Body:
I currently have a Proxy object that I want to capture property calls to if the property is not defined.
A basic version of my code would be something like this.

var a = new Proxy({}, {
    get: function(target, name, receiver) {
        if (target in name) {
            return target[name];
        } else {
            function a() {
                return arguments;
            }
            var args = a();
            return [target, name, receiver, args];
        }
    }
});

Property calls to a here (i.e: a.b; a.c() etc) should return the target, name, receiver and arguments of the property call.

The problem I wish to solve, however, requires me to know whether the property call is for a property or a function, such that I can apply different treatments to each. Checking the length of the arguments object does not work, as calling a.c() would yield a length of 0 just like a.b, so it would be treated as a plain property and not a method.

Is there a way, therefore, to identify whether the property attempting to be accessed is being called as a function or not.

UPDATE: I should clarify, this method needs to work if the accessed property/method is undefined, as well as existing.


问:
Self-Referencing ManyToMany Relationship TypeORM
I have just started using TypeORM and I'm struggling getting the following relationship to work:

User->Friends, whereas a Friend is also a User Object.
My getters, getFriends & getFriendsInverse are working, however; I do now want to distinguish between the two. In other words; when I perform a mysql join I do not want to do a left join on friends and another one on inverseFriends.

The getter getFriends() needs to return all friends, regardless of which "side" the object I'm on.

Does that make sense?

This is my model definition:

```<code>getFriends() {
    // This method should also return inverseFriends;
    // I do not want to return the concat version; this should
    // happen on the database/orm level
    // So I dont want: this.friends.concat(this.inverseFriends)
    return this.friends;
}

@ManyToMany(type => User, user => user.friendsInverse, {
    cascadeInsert: false,
    cascadeUpdate: false,
})
@JoinTable()
friends = [];

@ManyToMany(type => User, user => user.friends, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: false,
})
friendsInverse = [];
</code>```

I hope someone understands my question :D
Thanks
Matt

答:
You can self-reference your relations. Here is an example of a simple directed graph (aka a node can have a parent and multiple children).

```<code>@Entity()
export class Service extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Index({ unique: true })
  title: string;

  @ManyToOne(type => Service, service => service.children)
  parent: Service;

  @OneToMany(type => Service, service => service.parent)
  children: Service[];
}
</code>```

An important note to keep in mind is that these relations are not auto loaded when reading an object from the DB with find* functions.

To actually load them, you have to use query builder at the moment and join them. (You can join multiple levels.) An example:

```<code>let allServices = await this.repository.createQueryBuilder('category')
  .andWhere('category.price IS NULL')
  .innerJoinAndSelect('category.children', 'product')
  .leftJoinAndSelect('product.children', 'addon')
  .getMany();
</code>```

Please note how I used different names to reference them (category, product, and addon).

Body:
I have just started using TypeORM and I'm struggling getting the following relationship to work:

User->Friends, whereas a Friend is also a User Object.
My getters, getFriends & getFriendsInverse are working, however; I do now want to distinguish between the two. In other words; when I perform a mysql join I do not want to do a left join on friends and another one on inverseFriends.

The getter getFriends() needs to return all friends, regardless of which "side" the object I'm on.

Does that make sense?

This is my model definition:

getFriends() {
    // This method should also return inverseFriends;
    // I do not want to return the concat version; this should
    // happen on the database/orm level
    // So I dont want: this.friends.concat(this.inverseFriends)
    return this.friends;
}

@ManyToMany(type => User, user => user.friendsInverse, {
    cascadeInsert: false,
    cascadeUpdate: false,
})
@JoinTable()
friends = [];

@ManyToMany(type => User, user => user.friends, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: false,
})
friendsInverse = [];

I hope someone understands my question :D
Thanks
Matt

Body:
You can self-reference your relations. Here is an example of a simple directed graph (aka a node can have a parent and multiple children).

@Entity()
export class Service extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Index({ unique: true })
  title: string;

  @ManyToOne(type => Service, service => service.children)
  parent: Service;

  @OneToMany(type => Service, service => service.parent)
  children: Service[];
}

An important note to keep in mind is that these relations are not auto loaded when reading an object from the DB with find* functions.

To actually load them, you have to use query builder at the moment and join them. (You can join multiple levels.) An example:

let allServices = await this.repository.createQueryBuilder('category')
  .andWhere('category.price IS NULL')
  .innerJoinAndSelect('category.children', 'product')
  .leftJoinAndSelect('product.children', 'addon')
  .getMany();

Please note how I used different names to reference them (category, product, and addon).

ContentLicense: CC BY-SA 4.0


问:
Sort list by name, date and hierarchy
I want to sort the following list in the following order:

first by object without any parent

then by name

by year

by month

related objects should come directly after by the criteria (2-4).

So what I want to achieve is basically a tree structure as a flat list.

This is what I've come up with until now, but can't figure out how to implement the parent relation.

```<code>function monthYearCheck(a, b) {
    if(a.year < b.year) {
        return -1;
    } else if(a.year > b.year) {
        return 1;
    } else {
        if(a.month < b.month) {
            return -1;
        } else if(a.month > b.month) {
            return 1;
        } else {
            return 0;
        }
    }
}

var sortedArray = nonSortedArray.sort(function (a, b) {
    if(a.name === b.name) {
        return monthYearCheck(a, b);
    } else if(a.name < b.name) {
        return -1;
    } else if(a.name > b.name) {
        return 1;
    }
});
</code>```

This is the array before sorting:

```<code>[{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
}]
</code>```

This is what I want to achieve:

```<code>[{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
}]
</code>```

答:
I suggest to use a tree structure for getting the dependencies and then the ordered result.

var data = [{ name: "Bottom", id: 4, parentId: 54, month: 6, year: 2016, value: 16 }, { name: "Topp", id: 12, month: 6, year: 2016, value: 24 }, { name: "Middle", id: 54, parentId: 12, month: 5, year: 2016, value: 14 }, { name: "Middle2", id: 118, parentId: 104, month: 6, year: 2016, value: 4 }, { name: "Bottom2", id: 5, parentId: 54, month: 5, year: 2016, value: 12 }, { name: "Topp", id: 12, month: 5, year: 2016, value: 12 }, { name: "Middle", id: 54, parentId: 12, month: 6, year: 2016, value: 4 }, { name: "Topp2", id: 104, month: 5, year: 2016, value: 12 }, { name: "Bottom2", id: 5, parentId: 54, month: 6, year: 2016, value: 2 }]
    .sort(function (a, b) {
        return a.name.localeCompare(b.name) || a.year - b.year || a.month - b.month;
    }),
    tree = function (data, root) {
        var r = [],
            o = {};
        data.forEach(function (a) {
            var temp = { data: [a], children: o[a.id] && o[a.id].children };
            if (o[a.id] && o[a.id].data) {
                o[a.id].data.push(a);
                return;
            }
            o[a.id] = temp;
            if (a.parentId === root) {
                r.push(temp);
            } else {
                o[a.parentId] = o[a.parentId] || {};
                o[a.parentId].children = o[a.parentId].children || [];
                o[a.parentId].children.push(temp);
            }
        });
        return r;
    }(data, undefined),
    result = function getValue(array) {
        return array.reduce(function (r, o) {
            return r.concat(o.data, getValue(o.children || []));
        }, []);
    }(tree);

console.log(result);
console.log(tree); // just how it works ...```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Sort list by name, date and hierarchy

Body:
I want to sort the following list in the following order:

first by object without any parent

then by name

by year

by month

related objects should come directly after by the criteria (2-4).

So what I want to achieve is basically a tree structure as a flat list.

This is what I've come up with until now, but can't figure out how to implement the parent relation.

function monthYearCheck(a, b) {
    if(a.year  b.year) {
        return 1;
    } else {
        if(a.month  b.month) {
            return 1;
        } else {
            return 0;
        }
    }
}

var sortedArray = nonSortedArray.sort(function (a, b) {
    if(a.name === b.name) {
        return monthYearCheck(a, b);
    } else if(a.name  b.name) {
        return 1;
    }
});

This is the array before sorting:

[{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
}]

This is what I want to achieve:

[{
    name: "Topp",
    id: 12,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp",
    id: 12,
    month: 6,
    year: 2016,
    value: 24
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 5,
    year: 2016,
    value: 14
},{
    name: "Middle",
    id: 54,
    parentId: 12,
    month: 6,
    year: 2016,
    value: 4
},{
    name: "Bottom",
    id: 4,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 16
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 6,
    year: 2016,
    value: 2
},{
    name: "Bottom2",
    id: 5,
    parentId: 54,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Topp2",
    id: 104,
    month: 5,
    year: 2016,
    value: 12
},{
    name: "Middle2",
    id: 118,
    parentId: 104,
    month: 6,
    year: 2016,
    value: 4
}]

Body:
I suggest to use a tree structure for getting the dependencies and then the ordered result.

var data = [{ name: "Bottom", id: 4, parentId: 54, month: 6, year: 2016, value: 16 }, { name: "Topp", id: 12, month: 6, year: 2016, value: 24 }, { name: "Middle", id: 54, parentId: 12, month: 5, year: 2016, value: 14 }, { name: "Middle2", id: 118, parentId: 104, month: 6, year: 2016, value: 4 }, { name: "Bottom2", id: 5, parentId: 54, month: 5, year: 2016, value: 12 }, { name: "Topp", id: 12, month: 5, year: 2016, value: 12 }, { name: "Middle", id: 54, parentId: 12, month: 6, year: 2016, value: 4 }, { name: "Topp2", id: 104, month: 5, year: 2016, value: 12 }, { name: "Bottom2", id: 5, parentId: 54, month: 6, year: 2016, value: 2 }]
    .sort(function (a, b) {
        return a.name.localeCompare(b.name) || a.year - b.year || a.month - b.month;
    }),
    tree = function (data, root) {
        var r = [],
            o = {};
        data.forEach(function (a) {
            var temp = { data: [a], children: o[a.id] && o[a.id].children };
            if (o[a.id] && o[a.id].data) {
                o[a.id].data.push(a);
                return;
            }
            o[a.id] = temp;
            if (a.parentId === root) {
                r.push(temp);
            } else {
                o[a.parentId] = o[a.parentId] || {};
                o[a.parentId].children = o[a.parentId].children || [];
                o[a.parentId].children.push(temp);
            }
        });
        return r;
    }(data, undefined),
    result = function getValue(array) {
        return array.reduce(function (r, o) {
            return r.concat(o.data, getValue(o.children || []));
        }, []);
    }(tree);

console.log(result);
console.log(tree); // just how it works ...

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How can I open a letter in mail.ru using selenium's webdriver?
I try:

```<code>driver = webdriver.Firefox()
driver.get('https://e.mail.ru/messages/inbox/')
...
letterTag = driver.find_element_by_css_selector("div.b-datalist__item__addr")
</code>```

and it gives me:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"div.b-datalist__item__addr"}
</code>```

I see 'div.b-datalist__item__addr' in develop tools, but I can't find it in page's source code. I suppose it generates by javascript... I need to click this element in order to open a letter. How can I do this?

答:
Link to documentation.
My solution:</p>

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

name = input("Login: ")
password = input("Password: ")
driver = webdriver.Chrome()
driver.get('https://mail.ru/')
driver.find_element_by_id('mailbox__login')
mail_name = driver.find_element_by_id('mailbox__login')
mail_name.send_keys(name)
mail_pass = driver.find_element_by_id('mailbox__password')
mail_pass.send_keys(password)
mail_pass.submit()
# get first letter
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.js-href.b-datalist__item__link")))
element.click()
</code>```

Body:
I try:

driver = webdriver.Firefox()
driver.get('https://e.mail.ru/messages/inbox/')
...
letterTag = driver.find_element_by_css_selector("div.b-datalist__item__addr")

and it gives me:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"div.b-datalist__item__addr"}

I see 'div.b-datalist__item__addr' in develop tools, but I can't find it in page's source code. I suppose it generates by javascript... I need to click this element in order to open a letter. How can I do this?

Body:
Link to documentation.
My solution:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

name = input("Login: ")
password = input("Password: ")
driver = webdriver.Chrome()
driver.get('https://mail.ru/')
driver.find_element_by_id('mailbox__login')
mail_name = driver.find_element_by_id('mailbox__login')
mail_name.send_keys(name)
mail_pass = driver.find_element_by_id('mailbox__password')
mail_pass.send_keys(password)
mail_pass.submit()
# get first letter
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.js-href.b-datalist__item__link")))
element.click()


问:
Iterating over the array returned from a function in another service in angularjs
I have a function in my controller that is making a call to a function defined in a service shared by that controller. I am able to make a call correctly, but the function returns an array and i want to get individual item from that array. Here is the snippet

```<code>    ctrl.loadInterfaces = function(driver) {
      angular.forEach(ctrl.driverInterfaces, function(value, key){
        ctrl.interfaces = myservice.driverInfo(driver, value);
      })
    };
</code>```

So here, driverInfo() will return an array, something like ['one', 'two'] but now i want to split that and put individually 'one' and 'two' into ctrl.interfaces and not like an array. Any idea how should i do that?
By the way ctrl.driverInterfaces is just another static array declared in the controller.

My html

```<code>    <select>
      <option ng-repeat="interface in ctrl.interfaces"
              value="{$ interface }">{$ interface $}</option>
      </select>
</code>```

Inputs are much appreciated. Thanks

答:
Try this</p>

```<code>ctrl.loadInterfaces = function(driver) {
  ctrl.interfaces = [];
  angular.forEach(ctrl.driverInterfaces, function(value, key){
    ctrl.interfaces = ctrl.interfaces.concat(myservice.driverInfo(driver, value));
  })
};
</code>```

Body:
I have a function in my controller that is making a call to a function defined in a service shared by that controller. I am able to make a call correctly, but the function returns an array and i want to get individual item from that array. Here is the snippet

    ctrl.loadInterfaces = function(driver) {
      angular.forEach(ctrl.driverInterfaces, function(value, key){
        ctrl.interfaces = myservice.driverInfo(driver, value);
      })
    };

So here, driverInfo() will return an array, something like ['one', 'two'] but now i want to split that and put individually 'one' and 'two' into ctrl.interfaces and not like an array. Any idea how should i do that?
By the way ctrl.driverInterfaces is just another static array declared in the controller.

My html

    <select>
      <option ng-repeat="interface in ctrl.interfaces"
              value="{$ interface }">{$ interface $}</option>
      </select>

Inputs are much appreciated. Thanks

Body:
Try this

ctrl.loadInterfaces = function(driver) {
  ctrl.interfaces = [];
  angular.forEach(ctrl.driverInterfaces, function(value, key){
    ctrl.interfaces = ctrl.interfaces.concat(myservice.driverInfo(driver, value));
  })
};


问:
Ionic 2 - Show notification when app is in foreground on IOS
I am making a chat application in Ionic 2. I want notifications to appear even when app is in foreground. I have tried using Phonegap Plugin Push and FCM Plugin both and I'm getting notifications when app is in background and when app is killed.

But these plugins didn't show notifications when app is in foreground. So I used Local Notifications Plugin by Katzer. It works for Android perfectly but in IOS I'm facing multiple issues.

When used with Phonegap Plugin Push, the local notification does appear but its click event does not work. Also, the two plugins seem to have some conflicts so when used together, sometimes normal push notifications does not arrive or their click events does not work.
When used with FCM plugin, no local notification arrived.

I also tried using phonegap-plugin-local-notification but again it worked for Android but in IOS, notification arrives in form of alert and also its click event gets called automatically.

I am stuck on this for a long time. Can someone please provide a solution? All I want is to get notification in the notification center when app is in foreground in IOS and also a click event so I can do redirection on click.

Any help would be appreciated.

答:
I was implementing in my cordova app this plugin.

And when device ready I fired this code:

```<code>pushNotification.register(
function (result) {
    //Do some stuff
}, function (error) {
    //Do some stuff on error
}, {
    "badge":"true",
    "sound":"true",
    "alert":"true",
    "ecb": "onNotificationAPN"
});
</code>```

And also implemented below function:

```<code>function onNotificationAPN(event) {
  if (event) {
    if ( event.alert ) {
      alert(Recieved alert: + event.alert);
    }
    if ( event.sound ) {
      var snd = new Media(event.sound);
      snd.play();
    }
    if ( event.badge ) {
      pushNotification.setApplicationIconBadgeNumber(function() {
        //SetApplicationIconBadgeNumber success.
      }, function() {
        //SetApplicationIconBadgeNumber error.
      },
      event.badge);
    }
  }
}
</code>```

And I am able to receive notifications also in foreground.

Body:
I was implementing in my cordova app this plugin.

And when device ready I fired this code:

pushNotification.register(
function (result) {
    //Do some stuff
}, function (error) {
    //Do some stuff on error
}, {
    "badge":"true",
    "sound":"true",
    "alert":"true",
    "ecb": "onNotificationAPN"
});

And also implemented below function:

function onNotificationAPN(event) {
  if (event) {
    if ( event.alert ) {
      alert(Recieved alert: + event.alert);
    }
    if ( event.sound ) {
      var snd = new Media(event.sound);
      snd.play();
    }
    if ( event.badge ) {
      pushNotification.setApplicationIconBadgeNumber(function() {
        //SetApplicationIconBadgeNumber success.
      }, function() {
        //SetApplicationIconBadgeNumber error.
      },
      event.badge);
    }
  }
}

And I am able to receive notifications also in foreground.


问:
GCC ppc64 aligned functions
I'm using GCC for make some powerpc64 executable, but sometimes between functions i have the following mistakes: Screenshot

Powerpc instructions format are still in 4 bytes, i tried some gcc commands (-fno-align-functions) but the compiler still fill bytes between functions.

I want my functions start directly after the end of the previous functions, without any values/zero filled (in the case of the screenshots the functions should start at 0x124).

Thanks.

答:
In addition to the traceback table issue noted in the previous answer, functions are normally aligned on a 16-byte boundary.  This is important for various reasons, including so the compiler can align hot loops on a 16-byte boundary for improved icache performance.  Assembly code from GCC will have a directive like:

.p2align 4,,15

before each function definition to enforce this.  So even without the traceback table your function will not start at address 0x124 without more effort.

This behavior can be overridden using -fno-align-functions, or using optimization level -Os (optimize for size).  I've tried both methods, and they both remove the .p2align directive.  Using -fno-align-functions is preferable unless you really want smaller and potentially slower code.

(If you are compiling with -O0 or -O1, you won't see the directive either, but we do not recommend compiling at such low optimization levels for either size or speed.)

Title: GCC ppc64 aligned functions


问:
.NET Core 1.0, Enumerate All classes that implement base class
I am working on migrating an ASP.NET project to RC2. I am using AutoFac to try to enumerate classes that implement AutoMapper Profile base class to set up all my mapping profiles without having to call them explicitly.  Previously in older version of ASP.NET (even in RC1) I was able to use the following code:

```<code>public class AutoMapperModule : Module
{

    protected override void Load(ContainerBuilder builder)
    {

        builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).As<Profile>();

        builder.Register(context =>
        {
            var profiles =
               AppDomain.CurrentDomain.GetAssemblies()
               .SelectMany(IoC.GetLoadableTypes)
               .Where(t => t != typeof(Profile) && t.Name != "NamedProfile" && typeof(Profile).IsAssignableFrom(t));

            var config = new MapperConfiguration(cfg =>
            {
                foreach (var profile in profiles)
                {
                    cfg.AddProfile((Profile)Activator.CreateInstance(profile));
                }
            });
            return config;
        })
        .AsSelf()
        .As<IConfigurationProvider>()
        .SingleInstance();

        builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
        builder.RegisterType<MappingEngine>().As<IMappingEngine>();

    }
}
</code>```

This worked fantastically, until I tried converting my project to RC2 using the new netcoreapp1.0 framework, except now I am getting a design time error on AppDomain stating the "AppDomain does not exist in the current context". I've seen some suggestions about using ILibraryManager or DependencyContext to do this but I can't figure out how to get any of that to work. Any suggestions?

答:
Will this work?</p>

```<code>var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}
</code>```

Body:
I am working on migrating an ASP.NET project to RC2. I am using AutoFac to try to enumerate classes that implement AutoMapper Profile base class to set up all my mapping profiles without having to call them explicitly.  Previously in older version of ASP.NET (even in RC1) I was able to use the following code:

public class AutoMapperModule : Module
{

    protected override void Load(ContainerBuilder builder)
    {

        builder.RegisterAssemblyTypes().AssignableTo(typeof(Profile)).As<Profile>();

        builder.Register(context =>
        {
            var profiles =
               AppDomain.CurrentDomain.GetAssemblies()
               .SelectMany(IoC.GetLoadableTypes)
               .Where(t => t != typeof(Profile) && t.Name != "NamedProfile" && typeof(Profile).IsAssignableFrom(t));

            var config = new MapperConfiguration(cfg =>
            {
                foreach (var profile in profiles)
                {
                    cfg.AddProfile((Profile)Activator.CreateInstance(profile));
                }
            });
            return config;
        })
        .AsSelf()
        .As<IConfigurationProvider>()
        .SingleInstance();

        builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)).As<IMapper>().InstancePerLifetimeScope();
        builder.RegisterType<MappingEngine>().As<IMappingEngine>();

    }
}

This worked fantastically, until I tried converting my project to RC2 using the new netcoreapp1.0 framework, except now I am getting a design time error on AppDomain stating the "AppDomain does not exist in the current context". I've seen some suggestions about using ILibraryManager or DependencyContext to do this but I can't figure out how to get any of that to work. Any suggestions?

Body:
Will this work?

var all =
        Assembly
        .GetEntryAssembly()
        .GetReferencedAssemblies()
        .Select(Assembly.Load)
        .SelectMany(x => x.DefinedTypes)
        .Where(type => typeof(ICloudProvider).IsAssignableFrom(type.AsType()));
foreach (var ti in all)
{
    var t = ti.AsType();
    if (!t.Equals(typeof(ICloudProvider)))
    {
        // do work
    }
}


问:
Sending an email with php from a html page
I am trying to configure this boostrap template: Github link

I do not have a datebase to use and on the Github page it says:

"Your must enter your database information and your email in
  form-handler.php - if you don't have a database, that's fine. Edit
  contact.html to direct the form to form-handler-nodb.php and emails
  will be sent with no database writes."

I do not understand exactly what it means to "direct the form to form-handler-nodb.php". I have tried to change the form attributes in contact.html to be <form action="/form-handler-nodb.php" method="post" role="form"> , but that just results in form-handler-nodb.php being downloaded when I hit the submit button.

My question is then what do I need to change in contact.html to be able to submit the email that is in the form on the page?

This is driving me insane! Thank you for your help.

答:
As Capsule mentioned in the comments I was not running a server when I was testing it locally. By uploading the contact.html to my server I started seeing this working.

As a side note, there was also a mistake in the form-handler-nodb.php file where "\nEmail: " . $email; needed to be changed to "\nEmail: " . $message to actually have the inputed email message submitted.

Thank you for the help Capsule!


问:
Bash - while inside for loop not exiting
I'm a beginner getting started with bash scripting.

I have 10 directories in current working directory dir1-dir10 + script.sh + a file called "tocopyfile".

Dir1-10 are empty.
tocopyfile is a test text file to be used for the purpose of my training
script.sh contains the following code:

```<code>dir=`pwd`
i="0"
for directory in `ls $dir`;do
        while [ $i -le 10 ]
        do
        cp tocopyfile $directory/file$i &
        i=$[$i+1]
        done
done
</code>```

The script should copy 10 copies of the file "tocopyfile" to every dir (dir1-10) in the naming convention file#. The problem is that ones the script is exists after the first directory without executing the while loop to the remaining remaining dirs.

Can someone explain what I'm doing wrong please?

Help is greatly appreciated.

答:
The immediate issue is that you need to reset the value of i for each iteration of the outer loop.

```<code>for directory in `ls $dir`; do  # No! but more on that in a moment
    i=0
    while [ $i -le 10 ]
</code>```

There are a few other issues with your code.

dir=$(pwd) is almost always pointless; bash already provides a variable PWD containing the name of the current working directory. You don't actually need this, though; you can simply use ./*/ to expand to a list of directories in the current working directory.

Never use the output of ls in a script.

$[...] is obsolete syntax; use $((...)) instead.

Cleaning your code up a bit, we get

```<code>for directory in ./*/; do
    i=0
    while [ "$i" -le 10 ]; do
        cp tocopyfile "$directory/file$i" &
        i=$((i+1))
    done
done
</code>```

Body:
I'm a beginner getting started with bash scripting.

I have 10 directories in current working directory dir1-dir10 + script.sh + a file called "tocopyfile".

Dir1-10 are empty.
tocopyfile is a test text file to be used for the purpose of my training
script.sh contains the following code:

dir=`pwd`
i="0"
for directory in `ls $dir`;do
        while [ $i -le 10 ]
        do
        cp tocopyfile $directory/file$i &
        i=$[$i+1]
        done
done

The script should copy 10 copies of the file "tocopyfile" to every dir (dir1-10) in the naming convention file#. The problem is that ones the script is exists after the first directory without executing the while loop to the remaining remaining dirs.

Can someone explain what I'm doing wrong please?

Help is greatly appreciated.

Body:
The immediate issue is that you need to reset the value of i for each iteration of the outer loop.

for directory in `ls $dir`; do  # No! but more on that in a moment
    i=0
    while [ $i -le 10 ]

There are a few other issues with your code.

dir=$(pwd) is almost always pointless; bash already provides a variable PWD containing the name of the current working directory. You don't actually need this, though; you can simply use ./*/ to expand to a list of directories in the current working directory.

Never use the output of ls in a script.

$[...] is obsolete syntax; use $((...)) instead.

Cleaning your code up a bit, we get

for directory in ./*/; do
    i=0
    while [ "$i" -le 10 ]; do
        cp tocopyfile "$directory/file$i" &
        i=$((i+1))
    done
done


问:
Dynamically change ThinkingSphinx max_matches / offset
Our ThinkingSphinx indexes a table with over 500 million records. We are trying to find 120,000 records that match a given query. However, I don't want to change the max_matches for fear that we will run out of RAM.

Obviously, the error we are getting is:

```<code>Exception ThinkingSphinx::SphinxError -> offset out of bounds (offset=100000, max_matches=100000)

<query>
AND `sphinx_deleted` = 0 LIMIT 100000, 1000 OPTION max_matches=100000;
</code>```

Is there a way to either:

Dynamically change the max_matches if I have not aggregated enough results?

A better solution that I'm missing?

答:
Well you can just set it just as big as you need. ie set max_matches to offset+limit.

ie to LIMIT 100000, 1000 OPTION max_matches=101000  or LIMIT 7000, 1000 OPTION max_matches=8000

Body:
Our ThinkingSphinx indexes a table with over 500 million records. We are trying to find 120,000 records that match a given query. However, I don't want to change the max_matches for fear that we will run out of RAM.

Obviously, the error we are getting is:

Exception ThinkingSphinx::SphinxError -> offset out of bounds (offset=100000, max_matches=100000)

<query>
AND `sphinx_deleted` = 0 LIMIT 100000, 1000 OPTION max_matches=100000;

Is there a way to either:

Dynamically change the max_matches if I have not aggregated enough results?

A better solution that I'm missing?


问:
breaking columns using substring
i am having long string in column as a full name of the employee , i want to break that down in first name, middle name and last name. for example i am having Andrade, Maria Sandra (lname,(space)fname(space)mname)breaking will be like
fname =Maria, lname= Andrade and middle name like Sandra.

My column generally have lname,fname.

i am able to divide lname, but not correct breaking for fname and mname

```<code>  SELECT  EmployeeName as [full name  ], SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName)+1,LEN(EmployeeName)) as[First name ]
  ,SUBSTRING( EmployeeName,0,CHARINDEX(',',EmployeeName)) [Last Name]
 , SUBSTRING( SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName)+1,LEN(EmployeeName)),CHARINDEX(' ',EmployeeName),LEN (SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName),LEN(EmployeeName)))) as[Middle  name ]
 FROM test$`
</code>```

答:
Here's a perfect reason why you should normalize your data.</p>

```<code>declare @table table(thename varchar(500))
insert into @table
values
('Andrade, Maria Sandra'),
('Andrade, Maria'),
('Andrade, Maria Sandra OhSnap')

select
    left(thename,CHARINDEX(',',thename) - 1) as LastName
    ,substring(thename,charindex(' ',thename),case when charindex(' ',thename) + charindex(' ',reverse(thename)) > len(thename) then charindex(' ',reverse(thename))  else len(thename) - (charindex(' ',thename) + charindex(' ',reverse(thename))) + 1 end) as FirstName
    ,case when charindex(' ',thename) + charindex(' ',reverse(thename)) - 1 = len(thename) then null else right(thename,charindex(' ',reverse(thename))) end as MiddleName
from @table
</code>```

Title: breaking columns using substring

Body:
i am having long string in column as a full name of the employee , i want to break that down in first name, middle name and last name. for example i am having Andrade, Maria Sandra (lname,(space)fname(space)mname)breaking will be like
fname =Maria, lname= Andrade and middle name like Sandra.

My column generally have lname,fname.

i am able to divide lname, but not correct breaking for fname and mname

  SELECT  EmployeeName as [full name  ], SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName)+1,LEN(EmployeeName)) as[First name ]
  ,SUBSTRING( EmployeeName,0,CHARINDEX(',',EmployeeName)) [Last Name]
 , SUBSTRING( SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName)+1,LEN(EmployeeName)),CHARINDEX(' ',EmployeeName),LEN (SUBSTRING( EmployeeName,CHARINDEX(',',EmployeeName),LEN(EmployeeName)))) as[Middle  name ]
 FROM test$`

Body:
Here's a perfect reason why you should normalize your data.

declare @table table(thename varchar(500))
insert into @table
values
('Andrade, Maria Sandra'),
('Andrade, Maria'),
('Andrade, Maria Sandra OhSnap')

select
    left(thename,CHARINDEX(',',thename) - 1) as LastName
    ,substring(thename,charindex(' ',thename),case when charindex(' ',thename) + charindex(' ',reverse(thename)) > len(thename) then charindex(' ',reverse(thename))  else len(thename) - (charindex(' ',thename) + charindex(' ',reverse(thename))) + 1 end) as FirstName
    ,case when charindex(' ',thename) + charindex(' ',reverse(thename)) - 1 = len(thename) then null else right(thename,charindex(' ',reverse(thename))) end as MiddleName
from @table


问:
Trying to use HttpContext.Session in a static method
I have the following method that gives the error

An object reference is required for the non-static field, method, or property 'HttpContext.Session'

```<code>namespace Website.Controllers
{

  // CONTROLLER CLASS IS HERE BUT REMOVED AS NOT RELEVANT CODE

  public static class HtmlExtensions
  {
    public static decimal GetCartTotal()
    {
      decimal cartTotal = 0;

      var storedData = HttpContext.Session.GetString(ShoppingCartTotal);

      if (storedData != null)
      {
        cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
      }

      return cartTotal;
    }
  }
}
</code>```

Obviously I understand I am calling a non static call from a static method, but I am not sure how to create an HttpContext.Session object. I need the method to be static as I am calling that data from the view. I can not pass the data in the view model as the data is being used on the _Layout.cshtml page and I do not want to go in and manually add it to every viewmodel and assign it in each controller method... What is the best way to call a method in the controller in a shared view?

I have the following in the View that works, but only when it is a static method, which because it is a static method that HttpContext is not working

```<code>@using Website.Controllers

@{
  var ShoppingCartTotal = HtmlExtensions.GetCartTotal();
}
</code>```

答:
You should be passing the dependencies of the method from the caller, better would be to add a parameter in the method that takes Session object input and the caller would need to pass it in :

```<code>public static decimal GetCartTotal(HttpSessionState session)
{
  decimal cartTotal = 0;

  var storedData = session.GetString(ShoppingCartTotal);

  if (storedData != null)
  {
    cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
  }

  return cartTotal;
}
</code>```

Hope it helps!

@Edit:

As suggested in comments by @Scott, you could make an extension method as well, as you already have it in a static class you could write it like:

```<code>public static decimal GetCartTotal(this HttpSessionState session)
{
      decimal cartTotal = 0;

      var storedData = session.GetString(ShoppingCartTotal);

      if (storedData != null)
      {
        cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
      }

      return cartTotal;
}
</code>```

and now you can call it at calling side like:

```<code>var total = HttpContext.Session.GetCartTotal()
</code>```

Body:
I have the following method that gives the error

An object reference is required for the non-static field, method, or property 'HttpContext.Session'

namespace Website.Controllers
{

  // CONTROLLER CLASS IS HERE BUT REMOVED AS NOT RELEVANT CODE

  public static class HtmlExtensions
  {
    public static decimal GetCartTotal()
    {
      decimal cartTotal = 0;

      var storedData = HttpContext.Session.GetString(ShoppingCartTotal);

      if (storedData != null)
      {
        cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
      }

      return cartTotal;
    }
  }
}

Obviously I understand I am calling a non static call from a static method, but I am not sure how to create an HttpContext.Session object. I need the method to be static as I am calling that data from the view. I can not pass the data in the view model as the data is being used on the _Layout.cshtml page and I do not want to go in and manually add it to every viewmodel and assign it in each controller method... What is the best way to call a method in the controller in a shared view?

I have the following in the View that works, but only when it is a static method, which because it is a static method that HttpContext is not working

@using Website.Controllers

@{
  var ShoppingCartTotal = HtmlExtensions.GetCartTotal();
}

Body:
You should be passing the dependencies of the method from the caller, better would be to add a parameter in the method that takes Session object input and the caller would need to pass it in :

public static decimal GetCartTotal(HttpSessionState session)
{
  decimal cartTotal = 0;

  var storedData = session.GetString(ShoppingCartTotal);

  if (storedData != null)
  {
    cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
  }

  return cartTotal;
}

Hope it helps!

@Edit:

As suggested in comments by @Scott, you could make an extension method as well, as you already have it in a static class you could write it like:

public static decimal GetCartTotal(this HttpSessionState session)
{
      decimal cartTotal = 0;

      var storedData = session.GetString(ShoppingCartTotal);

      if (storedData != null)
      {
        cartTotal = JsonConvert.DeserializeObject<decimal>(storedData);
      }

      return cartTotal;
}

and now you can call it at calling side like:

var total = HttpContext.Session.GetCartTotal()


问:
on press button mass stay the color
Hi can some one please help me with this code

```<code>horse_btn_a1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      horse_btn_a1.setBackgroundColor(Color.parseColor("@drawable/ront2"));
    }
});
</code>```

and what I wanna do is when the button is pressed it must stay that color.

答:
The parseColor method takes a String, sure, but not a resource string.

You first need to fetch your resource String, then parse that:

Define your color resource like this

```<code><resources>
    <color name="colorA">#FF00FF</color>
</resources>
</code>```

Then use it in Java like this:

```<code>String colorString = getContext().getResources().getString(R.color.colorA);

Color c = Color.parseColor(colorString);

btn.setBackgroundColor(c);
</code>```

Title: on press button mass stay the color

Body:
Hi can some one please help me with this code

horse_btn_a1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      horse_btn_a1.setBackgroundColor(Color.parseColor("@drawable/ront2"));
    }
});

and what I wanna do is when the button is pressed it must stay that color.

Body:
The parseColor method takes a String, sure, but not a resource string.

You first need to fetch your resource String, then parse that:

Define your color resource like this

<resources>
    <color name="colorA">#FF00FF</color>
</resources>

Then use it in Java like this:

String colorString = getContext().getResources().getString(R.color.colorA);

Color c = Color.parseColor(colorString);

btn.setBackgroundColor(c);


问:
Jquery add index to name attribute when adding input elements
I am creating a dynamic table. Below is the Jquery for add function. Does anyone know how to dynamically change var "i" in the name attribute of the input field? For example, when I add row one, it should be uploadForms[1].name. Thanks!</p>

```<code>$(document).ready(function(){
 var i=1;
 $("#add").click(function(){
 var input1 = $(document.createElement('input'))
 .attr("name", "uploadForms[i].name");
 input1.appendTo("#uploadFormsTable");
 })
 });
</code>```

答: change .attr("name", "uploadForms[i].name"); to .attr("name", "uploadForms["+i+"].name"); so you can access to the variable instead of applying a string

Body:
I am creating a dynamic table. Below is the Jquery for add function. Does anyone know how to dynamically change var "i" in the name attribute of the input field? For example, when I add row one, it should be uploadForms[1].name. Thanks!

$(document).ready(function(){
 var i=1;
 $("#add").click(function(){
 var input1 = $(document.createElement('input'))
 .attr("name", "uploadForms[i].name");
 input1.appendTo("#uploadFormsTable");
 })
 });


问:
Angular 4 : Master page with side bar concept
I'm working with Angular 4 and I wanted to create a master page concept for all pages.

This is what I want :

In fact, I want to have a authentication page with its own template (like my screen), and others pages, with a different template.

For example, I want to have a fixed toolbar and a left sidebar. And inside page, a dynamic content.

In my idea, the router-outlet in the page AppComponent will display Authentication page or "Master Page" (toolbar and sidebar) and then, in this Master Page, I created a Div for my dynamic content.

But it doesn't work...

How can I do it ?

Thanks

答:
If you are using angular4, then use components.

You can make theses components:

```<code>Authentification
Authentification-Content
Authentification-Sidebar
Master
Master-Titlebar
Master-Sidebar
Master-Content
Home
Product
</code>```

Then it's just a matter of injecting components into each other to get the desired results.

For example, if you wanted to show the Product page, you'd have your component injected like this:

```<code>index.html
    Master
        Master-Titlebar
        Master-Sidebar
        Master-content
            Product
</code>```

Body:
If you are using angular4, then use components.

You can make theses components:

Authentification
Authentification-Content
Authentification-Sidebar
Master
Master-Titlebar
Master-Sidebar
Master-Content
Home
Product

Then it's just a matter of injecting components into each other to get the desired results.

For example, if you wanted to show the Product page, you'd have your component injected like this:

index.html
    Master
        Master-Titlebar
        Master-Sidebar
        Master-content
            Product


问:
CSV to directory
I have CSV file which contains information about
     Car and Email

```<code>BMW, person1@mail.com
Mercedes, person2@mail.com
Dodge, person1@mail.com
</code>```

etc.

I'm trying to do the script which makes a dictionary from CSV where email is key and a car is value. Every key can have more values.

```<code>import csv

reader = csv.reader(open('report.csv'))

output = {}
for row in reader:
key = row[1]
value = row[0]
if key in output:
    if row[0] == output.get(key):
        pass
    else:
        output[key].append(value)
output[key] = value

print(output)
</code>```

for every row, I'm trying to check if is the car(value) already value of email(key). If is then pass to next row, if not then add value to the key.

Output should looks like

```<code>{'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}
</code>```

but after compilating error 'str' object has no attribute 'append' comes up

Thank you

答:
Using the collections module you can use the defaultdict object to achieve the output that you need

```<code>import csv
from collections import defaultdict

d =defaultdict(list)

with open("t.csv","rb") as f:
    reader = csv.reader(f)
    for line in reader:
        d[line[1]].append(line[0])
</code>```

outputs:

```<code>d

defaultdict(list,
            {' person1@mail.com': ['BMW', 'Dodge'],
             ' person2@mail.com': ['Mercedes']})
</code>```

Title: CSV to directory

Body:
I have CSV file which contains information about
     Car and Email

BMW, person1@mail.com
Mercedes, person2@mail.com
Dodge, person1@mail.com

etc.

I'm trying to do the script which makes a dictionary from CSV where email is key and a car is value. Every key can have more values.

import csv

reader = csv.reader(open('report.csv'))

output = {}
for row in reader:
key = row[1]
value = row[0]
if key in output:
    if row[0] == output.get(key):
        pass
    else:
        output[key].append(value)
output[key] = value

print(output)

for every row, I'm trying to check if is the car(value) already value of email(key). If is then pass to next row, if not then add value to the key.

Output should looks like

{'person1@mail.com': ['BMW', 'Dodge'],'person2@mail.com': ['Mercedes']}

but after compilating error 'str' object has no attribute 'append' comes up

Thank you

Body:
Using the collections module you can use the defaultdict object to achieve the output that you need

import csv
from collections import defaultdict

d =defaultdict(list)

with open("t.csv","rb") as f:
    reader = csv.reader(f)
    for line in reader:
        d[line[1]].append(line[0])

outputs:

d

defaultdict(list,
            {' person1@mail.com': ['BMW', 'Dodge'],
             ' person2@mail.com': ['Mercedes']})


问:
Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug
Update: A sample project reproducing this bug can be found here at Microsoft Connect. I have also tested and verified that the solution given in the accepted answer below works on that sample project. If this solution doesn't work for you, you are probably having a different issue (which belongs in a separate question).

This is a question asked before, both here on Stack Overflow and other places, but none of the suggestions I've found this far have helped me, so I just have to try asking a new question.

Scenario: I have a simple Windows Forms application (C#, .NET 4.0, Visual Studio 2010). It has a couple of base forms that most other forms inherit from, it uses Entity Framework (and POCO classes) for database access. Nothing fancy, no multi-threading or anything.

Problem: All was fine for a while. Then, all out of the blue, Visual Studio failed to build when I was about to launch the application. I got the warning "Unable to delete file '...bin\Debug\[ProjectName].exe'. Access to the path '...bin\Debug\[ProjectName].exe' is denied." and the error "Unable to copy file 'obj\x86\Debug\[ProjectName].exe' to 'bin\Debug\[ProjectName].exe'. The process cannot access the file 'bin\Debug\[ProjectName].exe' because it is being used by another process." (I get both the warning and the error when running Rebuild, but only the error when running Build - don't think that is relevant?)

I understand perfectly fine what the warning and error message says: Visual Studio is obviously trying to overwrite the exe-file while it at the same time has a lock on it for some reason. However, this doesn't help me find a solution to the problem... The only thing I've found working is to shut down Visual Studio and start it again. Building and launching then work, until I make a change in some of the forms, then I have the same problem again and have to restart... Quite frustrating!

As I mentioned above, this seems to be a known problem, so there are lots of suggested solutions. I'll just list what I've already tried here, so people know what to skip:

Creating a new clean solution and just copy the files from the old solution.

Adding the following to the following to the project's pre-build event:

```<code> if exist "$(TargetPath).locked" del "$(TargetPath).locked"
    if not exist "$(TargetPath).locked" if exist "$(TargetPath)" move "$(TargetPath)" "$(TargetPath).locked"
</code>```

Adding the following to the project properties (.csproj file):

```<code> <GenerateResourceNeverLockTypeAssemblies>true</GenerateResourceNeverLockTypeAssemblies>
</code>```

However, none of them worked for me, so you can probably see why I'm starting to get a bit frustrated. I don't know where else to look, so I hope somebody has something to give me! Is this a bug in VS, and if so is there a patch? Or has I done something wrong, do I have a circular reference or similar, and if so how could I find out?

Any suggestions are highly appreciated :)

Update: As mentioned in the comment below, I've also checked using Process Explorer that it actually is Visual Studio that is locking the file.

答:
I have the same problem (MSB3021) with WPF project in VS2008 (on Windows 7 x32).
The problem appearing if i try to re-run application too quick after previous run.
After a few minutes exe-file unlocked by itself and i can re-run application again. But such a long pause angers me.
The only thing that really helped me was running VS as Administrator.

Body:
Update: A sample project reproducing this bug can be found here at Microsoft Connect. I have also tested and verified that the solution given in the accepted answer below works on that sample project. If this solution doesn't work for you, you are probably having a different issue (which belongs in a separate question).

This is a question asked before, both here on Stack Overflow and other places, but none of the suggestions I've found this far have helped me, so I just have to try asking a new question.

Scenario: I have a simple Windows Forms application (C#, .NET 4.0, Visual Studio 2010). It has a couple of base forms that most other forms inherit from, it uses Entity Framework (and POCO classes) for database access. Nothing fancy, no multi-threading or anything.

Problem: All was fine for a while. Then, all out of the blue, Visual Studio failed to build when I was about to launch the application. I got the warning "Unable to delete file '...bin\Debug\[ProjectName].exe'. Access to the path '...bin\Debug\[ProjectName].exe' is denied." and the error "Unable to copy file 'obj\x86\Debug\[ProjectName].exe' to 'bin\Debug\[ProjectName].exe'. The process cannot access the file 'bin\Debug\[ProjectName].exe' because it is being used by another process." (I get both the warning and the error when running Rebuild, but only the error when running Build - don't think that is relevant?)

I understand perfectly fine what the warning and error message says: Visual Studio is obviously trying to overwrite the exe-file while it at the same time has a lock on it for some reason. However, this doesn't help me find a solution to the problem... The only thing I've found working is to shut down Visual Studio and start it again. Building and launching then work, until I make a change in some of the forms, then I have the same problem again and have to restart... Quite frustrating!

As I mentioned above, this seems to be a known problem, so there are lots of suggested solutions. I'll just list what I've already tried here, so people know what to skip:

Creating a new clean solution and just copy the files from the old solution.

Adding the following to the following to the project's pre-build event:

 if exist "$(TargetPath).locked" del "$(TargetPath).locked"
    if not exist "$(TargetPath).locked" if exist "$(TargetPath)" move "$(TargetPath)" "$(TargetPath).locked"

Adding the following to the project properties (.csproj file):

 <GenerateResourceNeverLockTypeAssemblies>true</GenerateResourceNeverLockTypeAssemblies>

However, none of them worked for me, so you can probably see why I'm starting to get a bit frustrated. I don't know where else to look, so I hope somebody has something to give me! Is this a bug in VS, and if so is there a patch? Or has I done something wrong, do I have a circular reference or similar, and if so how could I find out?

Any suggestions are highly appreciated :)

Update: As mentioned in the comment below, I've also checked using Process Explorer that it actually is Visual Studio that is locking the file.


问:
Failed to use TypeORM in Angular 2, module MySQL not found
I tried to use use TypeORM in Angular2. So I installed TypeORM npm install typeorm and MySQL by npm install mysql and now when I run my app I get the following error:  Mysql package has not been found installed. Try to install it: npm install mysql --save"

Can someone help me?

答:
I tried to use use typeorm in angular2.

You cannot use TypeORM in the browser with MySQL, you have to use the WebSQL driver.

To use TypeORM with MySQL you have to use NodeJS.


问:
New Prestashop module is not showing in module list
I'm creating a module for Prestashop 1.7 following tutorial, my actual code is like this:

/themes/myTheme/modules/hwmodule/hwmodule.php

```<code>class HwModule extends Module
{
    public function __construct() {
        $this->name = 'hwmodule';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Lai';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('My module');
        $this->description = $this->l('Description of my module.');

        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');

        if(!Configuration::get("MYMODULE_NAME"))
            $this->warning = $this->l('No name provided');
    }

}
</code>```

As wrote in the documentation, this code is allow a basic installation, but when I can't find it in my module list (Admin > Module > Modules & Services).

What is wrong in my code?

答: The module should be located at /modules/hwmodule/hwmodule.php instead. themes/myTheme/modules/hwmodule/ you can place the theme tpl. For example, if you use a template in /modules/hwmodule/views/template.tpl you can modify for each theme the same template placing it in themes/myTheme/modules/hwmodule/views/template.tpl

Body:
I'm creating a module for Prestashop 1.7 following tutorial, my actual code is like this:

/themes/myTheme/modules/hwmodule/hwmodule.php

class HwModule extends Module
{
    public function __construct() {
        $this->name = 'hwmodule';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Lai';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('My module');
        $this->description = $this->l('Description of my module.');

        $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');

        if(!Configuration::get("MYMODULE_NAME"))
            $this->warning = $this->l('No name provided');
    }

}

As wrote in the documentation, this code is allow a basic installation, but when I can't find it in my module list (Admin > Module > Modules & Services).

What is wrong in my code?


问:
Dynamically load XML with CSS styling
I want to load an XML file and its CSS stylesheets into a textarea ordiv.  Each XML file has CSS stylesheets that display it correctly:

```<code><?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="first.css"?>
<?xml-stylesheet href="second.css"?>
<book>
  <sentence>
  !!! SNIP !!!
</code>```

If I load the file directly into a web browser by typing its URL into the address bar, it is displayed correctly, including all styling.  Now I want to display it the same way, loading it dynamically.

I have tried several variations on this, e.g.

```<code><textarea id="display">
</textarea>

$.ajax({
    type: "GET",
    url: "https://raw.githubusercontent.com/someplace/my.xml",
    dataType: "text",
    success: function(xml) {
        alert("GET succeeded")
        var xmlDoc = $.parseXML(xml);
        document.getElementById("display").append(xmlDoc.childNodes);
    }
});
</code>```

I can't figure out how to dynamically apply styles to the parsed XML document and display it.  I don't want to convert it to HTML, I just want to show the same documents that already display properly in the web browser.

Anyone know how to do this?

答: The point of XML and CSS is that it renders fine in a browser. But why in a textarea? You could display it with an iframe tag instead, if the tag in which it is displayed does not matter too much. By changing the src attribute of that iframe, you can load it dynamically.

Title: Dynamically load XML with CSS styling

Body:
I want to load an XML file and its CSS stylesheets into a textarea ordiv.  Each XML file has CSS stylesheets that display it correctly:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="first.css"?>
<?xml-stylesheet href="second.css"?>
<book>
  <sentence>
  !!! SNIP !!!

If I load the file directly into a web browser by typing its URL into the address bar, it is displayed correctly, including all styling.  Now I want to display it the same way, loading it dynamically.

I have tried several variations on this, e.g.

<textarea id="display">
</textarea>

$.ajax({
    type: "GET",
    url: "https://raw.githubusercontent.com/someplace/my.xml",
    dataType: "text",
    success: function(xml) {
        alert("GET succeeded")
        var xmlDoc = $.parseXML(xml);
        document.getElementById("display").append(xmlDoc.childNodes);
    }
});

I can't figure out how to dynamically apply styles to the parsed XML document and display it.  I don't want to convert it to HTML, I just want to show the same documents that already display properly in the web browser.

Anyone know how to do this?


问:
com.microsoft.sqlserver.jdbc.SQLServerException: The index 8 is out of range
I am trying the following code:

```<code>public class StoredProcedureParam
{
    private String m_sType;
    private String m_sValue;
    private String m_sParamName;

    public StoredProcedureParam(String a_sParamName, String a_sType, String a_sValue)
    {
        m_sType = a_sType;
        m_sValue = a_sValue;
        m_sParamName = a_sParamName;
    }
}

ArrayList<StoredProcedureParam> spmArr = new ArrayList<StoredProcedureParam>();

spmArr.add(new StoredProcedureParam("sBridgePhone",             "NString",  "value1"));
spmArr.add(new StoredProcedureParam("sCallerPaidTelNumber",             "NString",  "value2"));
spmArr.add(new StoredProcedureParam("sTollFreeTelNumber",       "NString",  "default"));
spmArr.add(new StoredProcedureParam("sParticipantAccessCode",   "NString",  "value3"));
spmArr.add(new StoredProcedureParam("sHostPassword",            "NString",  "value4"));
spmArr.add(new StoredProcedureParam("tNowUtc",                  "output",   "timestamp"));
spmArr.add(new StoredProcedureParam("nStatusCode",              "output",   "Int"));

if (!m_jdbcWrapper.callStoredProcedure("{call spAddConference(?,?,?,?,?,?,?)}", spmArr)) {
    System.out.println("callAddConferenceSp - Failed to execute");
    return "";
}

public boolean callStoredProcedure(String a_sStoredProcedure, ArrayList<StoredProcedureParam> a_ParamList)
{
    try
    {
        connect();

        m_cStatement = m_Connection.prepareCall(a_sStoredProcedure,
                                            ResultSet.TYPE_SCROLL_INSENSITIVE,
                                            ResultSet.CONCUR_READ_ONLY);

        registerSpParams(a_ParamList);

        m_cStatement.execute();
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
        return false;
    }
    finally
    {
        try
        {
            m_cStatement.close();
            System.out.println("JDBCWrapper - Statement Closed!");
            m_Connection.close();
            System.out.println("JDBCWrapper - Connection Closed!");
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    return true;
}

private void registerSpParams(ArrayList<StoredProcedureParam> a_ParamList) throws SQLException {

        if (a_ParamList.size() > 0)
        {
            for (int i = 1; i <= a_ParamList.size(); i++)
            {
                StoredProcedureParam spp = a_ParamList.get(i - 1);
                switch (TypesEnum.valueOf(spp.getType()))
                {
                    case Integer:
                        m_cStatement.setInt(spp.getParamName(), Integer.parseInt(spp.getValue()));
                        break;
                    case String:
                        m_cStatement.setString(spp.getParamName(), spp.getValue());
                        break;
                    case NString:
                        m_cStatement.setNString(spp.getParamName(), spp.getValue());
                        break;
                    case Timestamp:
                        m_cStatement.setTimestamp(spp.getParamName(), Timestamp.valueOf(spp.getValue()));
                        break;
                    case output:
                        switch (TypesEnum.valueOf(spp.getValue()))
                        {
                            case Integer:
                                m_cStatement.registerOutParameter(spp.getParamName(), java.sql.Types.INTEGER);
                                break;
                            case Timestamp:
                                m_cStatement.registerOutParameter(spp.getParamName(), java.sql.Types.TIMESTAMP);
                                break;
                            default:
                                break;
                        }
                        break;
                    case bit:
                        m_cStatement.setByte(spp.getParamName(), Byte.parseByte(spp.getValue()));
                        break;
                    case Bigint:
                        m_cStatement.setBigDecimal(spp.getParamName(), BigDecimal.valueOf(Long.parseLong(spp.getValue())));
                        break;
                }
            }
        }
    }
</code>```

For some reason I am getting the exception in subject:

```<code>com.microsoft.sqlserver.jdbc.SQLServerException: The index 8 is out of range.
      at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
      at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.registerOutParameter(SQLServerCallableStatement.java:75)
      at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.registerOutParameter(SQLServerCallableStatement.java:1735)
      at com.att.ecm.jdbcwrapper.JDBCWrapper.registerSpParams(JDBCWrapper.java:216)
      at com.att.ecm.jdbcwrapper.JDBCWrapper.callStoredProcedure(JDBCWrapper.java:138)
      at com.client.main.ConferenceStoredProcedures.callAddConferenceSp(ConferenceStoredProcedures.java:74)
      at com.main.Main.startFlow(Main.java:51)
      at com.main.Main.executeFlow(Main.java:34)
      at com.main.Main.main(Main.java:26)
</code>```

And cannot understand why? As far as I understand I set 7 question marks and set 7 parameters.
So, why does it throws an exception on the 8th index??

Can you advise please?

Best Regards, Tal

答: This happened to me when I mapped a parameter and didn't actually use the parameter in the query.  Surprised the parameter wasn't simply ignored.</p>

Body:
I am trying the following code:

public class StoredProcedureParam
{
    private String m_sType;
    private String m_sValue;
    private String m_sParamName;

    public StoredProcedureParam(String a_sParamName, String a_sType, String a_sValue)
    {
        m_sType = a_sType;
        m_sValue = a_sValue;
        m_sParamName = a_sParamName;
    }
}

ArrayList<StoredProcedureParam> spmArr = new ArrayList<StoredProcedureParam>();

spmArr.add(new StoredProcedureParam("sBridgePhone",             "NString",  "value1"));
spmArr.add(new StoredProcedureParam("sCallerPaidTelNumber",             "NString",  "value2"));
spmArr.add(new StoredProcedureParam("sTollFreeTelNumber",       "NString",  "default"));
spmArr.add(new StoredProcedureParam("sParticipantAccessCode",   "NString",  "value3"));
spmArr.add(new StoredProcedureParam("sHostPassword",            "NString",  "value4"));
spmArr.add(new StoredProcedureParam("tNowUtc",                  "output",   "timestamp"));
spmArr.add(new StoredProcedureParam("nStatusCode",              "output",   "Int"));

if (!m_jdbcWrapper.callStoredProcedure("{call spAddConference(?,?,?,?,?,?,?)}", spmArr)) {
    System.out.println("callAddConferenceSp - Failed to execute");
    return "";
}

public boolean callStoredProcedure(String a_sStoredProcedure, ArrayList<StoredProcedureParam> a_ParamList)
{
    try
    {
        connect();

        m_cStatement = m_Connection.prepareCall(a_sStoredProcedure,
                                            ResultSet.TYPE_SCROLL_INSENSITIVE,
                                            ResultSet.CONCUR_READ_ONLY);

        registerSpParams(a_ParamList);

        m_cStatement.execute();
    }
    catch (SQLException ex)
    {
        ex.printStackTrace();
        return false;
    }
    finally
    {
        try
        {
            m_cStatement.close();
            System.out.println("JDBCWrapper - Statement Closed!");
            m_Connection.close();
            System.out.println("JDBCWrapper - Connection Closed!");
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    return true;
}

private void registerSpParams(ArrayList<StoredProcedureParam> a_ParamList) throws SQLException {

        if (a_ParamList.size() > 0)
        {
            for (int i = 1; i <= a_ParamList.size(); i++)
            {
                StoredProcedureParam spp = a_ParamList.get(i - 1);
                switch (TypesEnum.valueOf(spp.getType()))
                {
                    case Integer:
                        m_cStatement.setInt(spp.getParamName(), Integer.parseInt(spp.getValue()));
                        break;
                    case String:
                        m_cStatement.setString(spp.getParamName(), spp.getValue());
                        break;
                    case NString:
                        m_cStatement.setNString(spp.getParamName(), spp.getValue());
                        break;
                    case Timestamp:
                        m_cStatement.setTimestamp(spp.getParamName(), Timestamp.valueOf(spp.getValue()));
                        break;
                    case output:
                        switch (TypesEnum.valueOf(spp.getValue()))
                        {
                            case Integer:
                                m_cStatement.registerOutParameter(spp.getParamName(), java.sql.Types.INTEGER);
                                break;
                            case Timestamp:
                                m_cStatement.registerOutParameter(spp.getParamName(), java.sql.Types.TIMESTAMP);
                                break;
                            default:
                                break;
                        }
                        break;
                    case bit:
                        m_cStatement.setByte(spp.getParamName(), Byte.parseByte(spp.getValue()));
                        break;
                    case Bigint:
                        m_cStatement.setBigDecimal(spp.getParamName(), BigDecimal.valueOf(Long.parseLong(spp.getValue())));
                        break;
                }
            }
        }
    }

For some reason I am getting the exception in subject:

com.microsoft.sqlserver.jdbc.SQLServerException: The index 8 is out of range.
      at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
      at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.registerOutParameter(SQLServerCallableStatement.java:75)
      at com.microsoft.sqlserver.jdbc.SQLServerCallableStatement.registerOutParameter(SQLServerCallableStatement.java:1735)
      at com.att.ecm.jdbcwrapper.JDBCWrapper.registerSpParams(JDBCWrapper.java:216)
      at com.att.ecm.jdbcwrapper.JDBCWrapper.callStoredProcedure(JDBCWrapper.java:138)
      at com.client.main.ConferenceStoredProcedures.callAddConferenceSp(ConferenceStoredProcedures.java:74)
      at com.main.Main.startFlow(Main.java:51)
      at com.main.Main.executeFlow(Main.java:34)
      at com.main.Main.main(Main.java:26)

And cannot understand why? As far as I understand I set 7 question marks and set 7 parameters.
So, why does it throws an exception on the 8th index??

Can you advise please?

Best Regards, Tal


问:
Extracting string between special characters in a csv column
I want to extract userhandles from retweets, ie; any username between
"RT @username:xyzxyzxyz" to a new column. I did the following

```<code>df = pd.read_csv("string.csv")
for index,row in df.iterrows():
    df['Influencers'] = df['Tweet'].str.extract("\(@*?)\:")
df.to_csv('string3.csv', index=False)
</code>```

It generated following error :

```<code>  File "C:\ANACONDA\lib\re.py", line 251, in _compile
    raise error, v # invalid expression

error: unbalanced parenthesis
</code>```

Sample DF:

```<code>df=pd.DataFrame({"Tweet": ["RT @saikatd: Are editors involved in the transfer of Income Tax officials?","RT @CLManojET: Can't allow L-G's fantasy of running a parallel administration"," Fairplay n equity 2 consumers 2 be ensured"]})
</code>```

答:
Sorry, I solved this one but I'm unable to implement the else condition for the above situation :

```<code>df = pd.read_csv("string.csv")
for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Influencers'] = "@"+df['Tweet'].str.extract("\@(.+?)\:", expand= False)
    else :
        df['Influencers'] = "Original"
df.to_csv('string3.csv', index=False)
</code>```

Its producing blank rows for the else condition.

Body:
I want to extract userhandles from retweets, ie; any username between
"RT @username:xyzxyzxyz" to a new column. I did the following

df = pd.read_csv("string.csv")
for index,row in df.iterrows():
    df['Influencers'] = df['Tweet'].str.extract("\(@*?)\:")
df.to_csv('string3.csv', index=False)

It generated following error :

  File "C:\ANACONDA\lib\re.py", line 251, in _compile
    raise error, v # invalid expression

error: unbalanced parenthesis

Sample DF:

df=pd.DataFrame({"Tweet": ["RT @saikatd: Are editors involved in the transfer of Income Tax officials?","RT @CLManojET: Can't allow L-G's fantasy of running a parallel administration"," Fairplay n equity 2 consumers 2 be ensured"]})

Body:
Sorry, I solved this one but I'm unable to implement the else condition for the above situation :

df = pd.read_csv("string.csv")
for index,row in df.iterrows():
    if "RT @" in row["Tweet"]:
        df['Influencers'] = "@"+df['Tweet'].str.extract("\@(.+?)\:", expand= False)
    else :
        df['Influencers'] = "Original"
df.to_csv('string3.csv', index=False)

Its producing blank rows for the else condition.


问:
Asp.NET WebGrid with Bootstrap pagination
There is default Bootstrap pagiantion

        «

1

2

3

4

5

        »

```
</div>
</div>
</p>

<p>In Asp.NET WebGrid I only can</p>

```footerStyle: "pagination",
```

<p>In HTML of WebGrid I see this</p>

```

        1 2 >

```

What a easiest way to take in WebGrid bootstrap pagination style?

答: https://github.com/mdobie/WebGridPagerReplacement  - this work good for WebGrid. Thank's to author.</p>

Body:
There is default Bootstrap pagiantion

        «

1

2

3

4

5

        »

In Asp.NET WebGrid I only can

footerStyle: "pagination",

In HTML of WebGrid I see this

        1 2 >

What a easiest way to take in WebGrid bootstrap pagination style?


问:
Why are the following Datalog programs equivalent?
For some existentional predicates a,b why is this: </p>

```<code>q(X,Y) <-- a(X,Y), q(Z,Y)
q(X,Y) <-- b(X,Y)
</code>```

<p>equivalent to this: </p>

```<code>q(X,Y) <-- a(X,Y), b(Z,Y)
q(X,Y) <-- b(X,Y)
</code>```

<p>?
Why can't the top recursion just continue to expand? </p>

答: If you expand the first clause once, you get a(X,Y), a(Z,Y), b(Z′,Y). Since Z is free, a(Z,Y) is a simple existential quantifier on Y, which has already been asserted by the first clause, so the expression collapses to a(X,Y), b(Z′,Y), which is of course equivalent to a(X,Y), b(Z,Y), since Z′ is also a free variable.

Body:
For some existentional predicates a,b why is this:

q(X,Y) <-- a(X,Y), q(Z,Y)
q(X,Y) <-- b(X,Y)

equivalent to this:

q(X,Y) <-- a(X,Y), b(Z,Y)
q(X,Y) <-- b(X,Y)

?
Why can't the top recursion just continue to expand?