问:
NSFetchedResultsController - KVO, UITableView and a "Tree"
I'm using a NSFetchedResultsController to implement KVO for my UITableView (which is obvious). What I can't figure out is, how to use multiple Entities - sort of a tree structure - to be present(ed) simultaneously.

Here is my setup:

Entity1

DisplayName

RelationToEntity2

Entity2

DisplayName

Now I can fetch the data of either to be presented - so far so good. What I want is to have a one-sectioned TableView (like a flattened view) with the following structure:

Entity1 (Entry 1)

Entity2 (Entry 1)

Entity2 (Entry 2)

…

Entity1 (Entry 2)

…

Though it might look like a thing to be done via sections, it's not. Both Entities should be a UITableViewCells. Can someone please point me the right direction to flatten the without loosing the actual hierarchy.

答: This is exactly the situation to use entity inheritance. When fetching a parent abstract entity with a fetched results controller all of the child entities can be displayed by the table. Use a section order property to display the sections in the order you prefer. And use a second sort property to order within the sections. The Notes app does this by fetching an abstract Container entity and displays Accounts and Folders which are child entities. It sections by Account and the first folder "All iCloud" cell is actually an Account. Folders have a relation to an account even though they are equals in the entity inheritance tree.</p>


来源: stackexchange

问:
Scala : Dataframe Merge
I have two dataframes in scala, i created them using the sql queries via hive context, please see the df as images here

Another dataframe is as

Please ignore the repetition of headers in second df, i want to compare the Skill column present in both the data frames and get the equivalent Role, Skill2  and emerging in df1 i.e. demand_df,

I tried this in pandas and was able to achieve by using the following code segment

```<code>df1 = pd.DataFrame([
    ["INDIA", "XXX","developer","UNKNOWN",121],
    ["INDIA", "XXXX","software engineer","UNKNOWN",121],
    ["POLAND","XX","english","KNOWN",122]],
    columns=['country', 'level','Skill','r2d2','tax'])

df2 = pd.DataFrame([
    ["english", "NaN","teacher","NaN","NaN"],
    [20000,"Unknown","NaN","NaN","NaN"],
    ["microsoft","Known","Software Engineer","Microsoft","Enterprise"]],
    columns=['Skill', 'R2D2','Role','Skill2','Emerging'])

result= df1.merge(df2[['Skill','Role','Skill2','emerging']], how = 'left', left_on = 'Skill', right_on = 'Skill')
</code>```

Please guide me,as I am new to scala

答:
Since you have created two dataframes and want to join two on the basis of skill and create a new dataframe which has df1 and  Role, Skill2 and emerging from df2.
You can do it through sqlcontext.
 val sqlContext = new org.apache.spark.sql.SQLContext(sc)

register both dataframe as temptable with the command :

df1.registerTempTable("df1")

df2.registerTempTable("df2")

after that you use simple hive query to join and fetch the required columns from data frame :

val df3 = sqlContext.sql("select a.,b. from df1 a left join df2 b on (a.skill = b.skill)")

ContentLicense: CC BY-SA 4.0

Title: Scala : Dataframe Merge

Body:
I have two dataframes in scala, i created them using the sql queries via hive context, please see the df as images here

Another dataframe is as

Please ignore the repetition of headers in second df, i want to compare the Skill column present in both the data frames and get the equivalent Role, Skill2  and emerging in df1 i.e. demand_df,

I tried this in pandas and was able to achieve by using the following code segment

df1 = pd.DataFrame([
    ["INDIA", "XXX","developer","UNKNOWN",121],
    ["INDIA", "XXXX","software engineer","UNKNOWN",121],
    ["POLAND","XX","english","KNOWN",122]],
    columns=['country', 'level','Skill','r2d2','tax'])

df2 = pd.DataFrame([
    ["english", "NaN","teacher","NaN","NaN"],
    [20000,"Unknown","NaN","NaN","NaN"],
    ["microsoft","Known","Software Engineer","Microsoft","Enterprise"]],
    columns=['Skill', 'R2D2','Role','Skill2','Emerging'])

result= df1.merge(df2[['Skill','Role','Skill2','emerging']], how = 'left', left_on = 'Skill', right_on = 'Skill')

Please guide me,as I am new to scala

ContentLicense: CC BY-SA 3.0


问:
Can you figure out this PHP timing issue?
Can anyone tell me why when I ran a script with the below contents and then stop it after 5 seconds that I need to divide the elapsed time by 2 to get the correct script execution time?

```<code>ignore_user_abort(true); set_time_limit(0);

$begin_time = microtime(true);

$elapsed_time = 0;

while(!connection_aborted()) {
    echo ' ';
    flush();
    usleep(1000000);
}

$elapsed_time = microtime(true) - $begin_time;

$timer_seconds = $elapsed_time; //10 seconds

$timer_seconds = $elapsed_time / 2; //5 seconds

/*I am writing to a DB - but you can use this to test */
$fp = fopen('times.txt', 'w');
fwrite($fp, 'Time Elapsed: '.$timer_seconds);
fclose($fp);
</code>```

Feel free to try the code as it has baffled me on why the $elapsed_time needs to be divided by two. Maybe I have misunderstood something?

Thanks all for any help

Update

I have updated the code so that anyone can try this out and it will write to a text file to view the output.

答:
You're relying on connection_aborted() to be true the moment you hit the 'Stop' button in your browser, but have shown no evidence that you have verified that this is the case. In fact, it is not.

You've forgotten how "connection aborted" checking happens in networking. An application (php in this case) doesn't know what's happened until it tries to write to the pipe.

The first comment on the documentation for connection_abort() says: "In order to detect a disconnection inside the script we need to flush the buffer (it is only when the the server tries to send the buffer content that it will see that the connection is broken)."

So I do not believe that you could reliably use connection_abort() in this way.

Rest assured, microtime() works properly.

ContentLicense: CC BY-SA 2.5

Body:
Can anyone tell me why when I ran a script with the below contents and then stop it after 5 seconds that I need to divide the elapsed time by 2 to get the correct script execution time?

ignore_user_abort(true); set_time_limit(0);

$begin_time = microtime(true);

$elapsed_time = 0;

while(!connection_aborted()) {
    echo ' ';
    flush();
    usleep(1000000);
}

$elapsed_time = microtime(true) - $begin_time;

$timer_seconds = $elapsed_time; //10 seconds

$timer_seconds = $elapsed_time / 2; //5 seconds

/*I am writing to a DB - but you can use this to test */
$fp = fopen('times.txt', 'w');
fwrite($fp, 'Time Elapsed: '.$timer_seconds);
fclose($fp);

Feel free to try the code as it has baffled me on why the $elapsed_time needs to be divided by two. Maybe I have misunderstood something?

Thanks all for any help

Update

I have updated the code so that anyone can try this out and it will write to a text file to view the output.


问:
Is optimize select max(date) sql query?
This query is too slow. Is it possible to optimize it?</p>

```<code>SELECT
    CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM
    X_Prices price
INNER JOIN
    RMetal cat ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE
    cat.Country = 'India'
    AND cat.Section = 1
    AND cat.active = 1
    AND cat.inactive = 0
    AND price.Dat < GETDATE() - 60
</code>```

答:
For this query:

```<code>SELECT CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM X_Prices price INNER JOIN
     RMetal cat
     ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE cat.Country = 'India' AND
      cat.Section = 1 AND
      cat.active = 1 AND
      cat.inactive = 0 AND
      price.Dat < GETDATE()- 60 ;
</code>```

I would start with an index on RMetal(Country, Section, Active, Inactive, Category, SubCat) and X_Prices(Category, SubCat, date).

Title: Is optimize select max(date) sql query?

Body:
This query is too slow. Is it possible to optimize it?

SELECT
    CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM
    X_Prices price
INNER JOIN
    RMetal cat ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE
    cat.Country = 'India'
    AND cat.Section = 1
    AND cat.active = 1
    AND cat.inactive = 0
    AND price.Dat < GETDATE() - 60

Body:
For this query:

SELECT CONVERT(CHAR(10), MAX(dat), 101) AS MaxDate
FROM X_Prices price INNER JOIN
     RMetal cat
     ON cat.SubCat = price.Subcat AND cat.Category = price.Category
WHERE cat.Country = 'India' AND
      cat.Section = 1 AND
      cat.active = 1 AND
      cat.inactive = 0 AND
      price.Dat < GETDATE()- 60 ;

I would start with an index on RMetal(Country, Section, Active, Inactive, Category, SubCat) and X_Prices(Category, SubCat, date).


问:
Gson parsing a Json to a Realm object with SerializedName fields

I'm parsing a json string to a Realm object, but the json has the key "id", So I'm using a serializedName to bypass it.

Here is my Json (jsonString in the following example)

```<code>{
    "id": "someuuidString",
    ...
    (some more irrelevant fields)
}
</code>```

Here is my object decleration

```<code>public class MyObject extends RealmObject {

    @PrimaryKey
    private long id;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}
</code>```

And later in the code i try the following

```<code>Gson gson = new GsonBuilder().create();
MyObject obj = gson.fromJson(jsonString, MyObject.class);
</code>```

So instead of parsing correctly, it crashes with the following exception

```<code>java.lang.IllegalArgumentException: class com.example.objects.MyObject declares multiple JSON fields named id
</code>```

So, what did I miss?

答:
You got error because id conflicts with your primary key and JSON key, Change your primary key name,

Try as below,

```<code>public class MyObject extends RealmObject {

    @PrimaryKey
    private long primaryId;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}
</code>```

Body:
I'm parsing a json string to a Realm object, but the json has the key "id", So I'm using a serializedName to bypass it.

Here is my Json (jsonString in the following example)

{
    "id": "someuuidString",
    ...
    (some more irrelevant fields)
}

Here is my object decleration

public class MyObject extends RealmObject {

    @PrimaryKey
    private long id;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}

And later in the code i try the following

Gson gson = new GsonBuilder().create();
MyObject obj = gson.fromJson(jsonString, MyObject.class);

So instead of parsing correctly, it crashes with the following exception

java.lang.IllegalArgumentException: class com.example.objects.MyObject declares multiple JSON fields named id

So, what did I miss?

Body:
You got error because id conflicts with your primary key and JSON key, Change your primary key name,

Try as below,

public class MyObject extends RealmObject {

    @PrimaryKey
    private long primaryId;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}


问:
BeautifulSoup select all href in some element with specific class
I'm trying to scrap images from this website. I tried with Scrapy(using Docker)and with scrapy/slenium. Scrapy seems not to work in windows10 home so I'm now trying with Selenium/Beautifulsoup. I'm using Python 3.6 with Spider into an Anaconda env.

This is how the href elements I need look like:

```<code><a class="emblem" href="detail/emblem/av1615001">
</code>```

I have to major problems:

- how should I select href with Beautifulsoup? Below in my code, you can see what I tried (but didn't work)

- As it is possible to observe the href is only a partial path to url...how should I deal with this issue?

Here my code so far:

```<code>from bs4 import BeautifulSoup
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import urllib
import requests
from os.path  import basename

def start_requests(self):
        self.driver = webdriver.Firefox("C:/Anaconda3/envs/scrapy/selenium/webdriver")
        #programPause = input("Press the <ENTER> key to continue...")
        self.driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        html = self.driver.page_source

        #html = requests.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        soup = BeautifulSoup(html, "html.parser")
        emblemshref = soup.select("a", {"class" : "emblem", "href" : True})

        for href in emblemshref:
            link = href["href"]
            with open(basename(link)," wb") as f:
                f.write(requests.get(link).content)

        #click on "next>>"
        while True:
            try:
                next_page = self.driver.find_element_by_xpath("//a[@id='next']")
                sleep(3)
                self.logger.info('Sleeping for 3 seconds')
                next_page.click()

                #here again the same emblemshref loop

            except NoSuchElementException:
                #execute next on the last page
                self.logger.info('No more pages to load')
                self.driver.quit()
                break
</code>```

答:
you can get href by class name as:

que1:

```<code>for link in soup.findAll('a', {'class': 'emblem'}):
   try:
      print link['href']
   except KeyError:
      pass`
</code>```

Body:
I'm trying to scrap images from this website. I tried with Scrapy(using Docker)and with scrapy/slenium. Scrapy seems not to work in windows10 home so I'm now trying with Selenium/Beautifulsoup. I'm using Python 3.6 with Spider into an Anaconda env.

This is how the href elements I need look like:

I have to major problems:

- how should I select href with Beautifulsoup? Below in my code, you can see what I tried (but didn't work)

- As it is possible to observe the href is only a partial path to url...how should I deal with this issue?

Here my code so far:

from bs4 import BeautifulSoup
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import urllib
import requests
from os.path  import basename

def start_requests(self):
        self.driver = webdriver.Firefox("C:/Anaconda3/envs/scrapy/selenium/webdriver")
        #programPause = input("Press the <ENTER> key to continue...")
        self.driver.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        html = self.driver.page_source

        #html = requests.get("http://emblematica.grainger.illinois.edu/browse/emblems?Filter.Collection=Utrecht&Skip=0&Take=18")
        soup = BeautifulSoup(html, "html.parser")
        emblemshref = soup.select("a", {"class" : "emblem", "href" : True})

        for href in emblemshref:
            link = href["href"]
            with open(basename(link)," wb") as f:
                f.write(requests.get(link).content)

        #click on "next>>"
        while True:
            try:
                next_page = self.driver.find_element_by_xpath("//a[@id='next']")
                sleep(3)
                self.logger.info('Sleeping for 3 seconds')
                next_page.click()

                #here again the same emblemshref loop

            except NoSuchElementException:
                #execute next on the last page
                self.logger.info('No more pages to load')
                self.driver.quit()
                break

Body:
you can get href by class name as:

que1:

for link in soup.findAll('a', {'class': 'emblem'}):
   try:
      print link['href']
   except KeyError:
      pass`


问:
How to allow user to export Dynamics 365 report to PDF format only?
Right now when users choose to export a report from my Dynamics 365 system, they can select the following formats: csv, pdf, mhtml, xlsx, tif, docx.

How can I restrict users to export to pdf format only?

I'm using Dynamics 365 Online Version 1612 (8.2.2.154) (DB 8.2.2.154).

答:
Not sure if this is possible, atleast in CRM online. But found out the config is stored in RSReportServer.config

The WORDOPENXML extension defines the Word renderer for Microsoft Word .docx files. The WORD extension defines the Microsoft Word 2003 version. Visible = “false” indicates the Word 2003 renderer is hidden.

Hiding Export option from Report

Change how the rendering extension name appears in the Export list of the report toolbar (for example, to change "Web archive" to "MHTML"), or localize the name to a different language.

Customize Rendering Extension Parameters in RSReportServer.Config


问:
Insert data for "Many to Many"
I'm developing an admin panel for the library. I need insert book with more authors. I bild book insert in my controller/ But i don`t understand how i can insert authors i to table "authors" from BooksController, with the condition that I need to check, there is my such author in the table and if there is not to add.
Thath code of BooksController:

```<code>public function insert(Request $request)
{
    $BookName = $request->input('bookname');
    if(!empty($BookName)){
        $NewBook = new Books;
        $NewBook->name = $BookName;
        $BookFile = $request->file('books_file');
        if(!empty($BookFile)){
            $NewBook->img = $BookFile->getClientOriginalName();
            $BookFile->move( storage_path('images/books/'), $BookFile->getClientOriginalName());
        }
        $NewBook->save();

        $AuthorsNames = $request->input('authors');
        if(!empty($AuthorsNames)){
            $AuthorsFiles = $request->file('authfiles');

        }
        return "Scs";
    }else{
        return 'Enter book title';
    }
}
</code>```

I read the documentation about the necessary functions, but I did not understand how to use them. In my code, I accept an array of authors, since one book can have many authors. I will be very grateful not for the code, but for the necessary functions and an explanation of how to use them.

答:
The Laravel docs cover this in detail.

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

Attaching / Detaching

Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:

```<code>$user = App\User::find(1);

$user->roles()->attach($roleId);
</code>```

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

In your example, an author should already exist because a many to many relationship means you have a book in the books table, an author in the authors table, and both primary keys (id) linked in an intermediate table.

If the author does not yet exist, save the author and get the id and use attach to add their id to the book.  A Book model should not care about the author name, only the ID.

Authors and Books should be thought of as completely separate until you link them.  So a Book should be created separately and an Author should be created separately then you link them.   In other words, you really shouldn't be creating authors from the BookController, but if you want to,  create an Author model like you would with any other, something like $author = Author::create($data), then attach it using $book->authors()->attach($author->id)

The major problem I see with your structure is how do you know if an author already exists?  Two different authors could share the same name.  Ideally, I'd recommended passing ids to the BookController, not names.

Title: Insert data for "Many to Many"

Body:
I'm developing an admin panel for the library. I need insert book with more authors. I bild book insert in my controller/ But i don`t understand how i can insert authors i to table "authors" from BooksController, with the condition that I need to check, there is my such author in the table and if there is not to add.
Thath code of BooksController:

public function insert(Request $request)
{
    $BookName = $request->input('bookname');
    if(!empty($BookName)){
        $NewBook = new Books;
        $NewBook->name = $BookName;
        $BookFile = $request->file('books_file');
        if(!empty($BookFile)){
            $NewBook->img = $BookFile->getClientOriginalName();
            $BookFile->move( storage_path('images/books/'), $BookFile->getClientOriginalName());
        }
        $NewBook->save();

        $AuthorsNames = $request->input('authors');
        if(!empty($AuthorsNames)){
            $AuthorsFiles = $request->file('authfiles');

        }
        return "Scs";
    }else{
        return 'Enter book title';
    }
}

I read the documentation about the necessary functions, but I did not understand how to use them. In my code, I accept an array of authors, since one book can have many authors. I will be very grateful not for the code, but for the necessary functions and an explanation of how to use them.

Body:
The Laravel docs cover this in detail.

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

Attaching / Detaching

Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:

$user = App\User::find(1);

$user->roles()->attach($roleId);

When attaching a relationship to a model, you may also pass an array of additional data to be inserted into the intermediate table:

In your example, an author should already exist because a many to many relationship means you have a book in the books table, an author in the authors table, and both primary keys (id) linked in an intermediate table.

If the author does not yet exist, save the author and get the id and use attach to add their id to the book.  A Book model should not care about the author name, only the ID.

Authors and Books should be thought of as completely separate until you link them.  So a Book should be created separately and an Author should be created separately then you link them.   In other words, you really shouldn't be creating authors from the BookController, but if you want to,  create an Author model like you would with any other, something like $author = Author::create($data), then attach it using $book->authors()->attach($author->id)

The major problem I see with your structure is how do you know if an author already exists?  Two different authors could share the same name.  Ideally, I'd recommended passing ids to the BookController, not names.


问:
Which yocto is best for me
I am new to yocto. and working on imx6ul board. There is a different type of yocto BSP like Morty, jethro, fido etc.

I want to use BSP with qt lgpl(not GPL) & Dynamic library.
How can differentiate them and can decide which one is best for my application?
Help to me to sort out this.

Thanks,
Jignesh

答: Morty, Jethro, Fido etc. are not different "yoctos", but different releases given the timeline of the project. Generally, pick the most current that is available, as it is the most actively maintained one. (At the current moment in time, Rocko is the stable release)</p>

Title: Which yocto is best for me


问:
Relocate form created inside a previous form
I have two form classes (IHM and HelpPanel). In my first loaded form (IHM) I call the function bHclass_Click to create and load a HelpPanel. The PopulatePCBclasses() function basically creates all the controls that will be displayed.

My issue is that this HelpPanel is always displayed at the exact same location no matter what value is input in it's Location property.
I tried also by setting the Top and Left attributes but result was the same.

Do I miss an instruction?

```<code>private void bHclass_Click(object sender, EventArgs e)
{
    HelpPanel hp = new HelpPanel();
    hp.PopulatePCBclasses();
    hp.Location = new Point(10, 500);
    hp.Show();
}
</code>```

答:
Try setting the start position as manual before changing the location:</p>

```<code>private void bHclass_Click(object sender, EventArgs e)
{
    HelpPanel hp = new HelpPanel();
    hp.PopulatePCBclasses();
    hp.StartPosition = FormStartPosition.Manual;
    hp.Location = new Point(10, 500);
    hp.Show();
}
</code>```

Body:
I have two form classes (IHM and HelpPanel). In my first loaded form (IHM) I call the function bHclass_Click to create and load a HelpPanel. The PopulatePCBclasses() function basically creates all the controls that will be displayed.

My issue is that this HelpPanel is always displayed at the exact same location no matter what value is input in it's Location property.
I tried also by setting the Top and Left attributes but result was the same.

Do I miss an instruction?

private void bHclass_Click(object sender, EventArgs e)
{
    HelpPanel hp = new HelpPanel();
    hp.PopulatePCBclasses();
    hp.Location = new Point(10, 500);
    hp.Show();
}

Body:
Try setting the start position as manual before changing the location:

private void bHclass_Click(object sender, EventArgs e)
{
    HelpPanel hp = new HelpPanel();
    hp.PopulatePCBclasses();
    hp.StartPosition = FormStartPosition.Manual;
    hp.Location = new Point(10, 500);
    hp.Show();
}


问:
When using gcov, is there a way to avoid instrumenting the header files included in the cpp file?
I instrument my productive code with the flags -fprofile-arcs and -ftest-coverage, then I test this code with unit tests. For the unit tests to compile and run, I am forced to make some fakes and mocks.

I can control during compilation which cpp files are instrumented and which ones are not. But, when compiling my productive code with flags for instrumentation, the code for the fakes and mocks will also be included through the header files.

Is there a way to avoid instrumenting the header files included in the cpp files?, for example using some attribute, pre processor directive or compilation flag.

答: No, there should be no way. What #include does is actually putting content inside cpp file before its compilation.


问:
Edit file using chef
I know there are a lot of answers plus solved ones too but nothing seems to work for me, What I'm trying to do is I want to add few lines of code after tomcat is completed with it's installation in /var/lib/tomcat8/conf/catalina.properties file.

here is what i have tried so far the simple ruby way and with chef utils too.

```<code>File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
  f << "\n"
  f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
end

ruby_block "insert_line" do
  block do
    file = Chef::Util::FileEdit.new("/var/lib/tomcat8/conf/catalina.properties")
    file.insert_line_if_no_match("/javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl/", "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl")
    file.write_file
  end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end
</code>```

I tried putting puts "testing" and it seems that chef isn't even getting into code.

答:
There is a fundamental flaw with this logic as chef-client will append the lines regardless if they are already in the file every time it runs.  I also don't think Chef really likes this approach.

If you don't want to manage the whole file as a template, then you should use the sous-chef/line-cookbook as it has conditionals / guards built into it to prevent this problem.

Title: Edit file using chef

Body:
I know there are a lot of answers plus solved ones too but nothing seems to work for me, What I'm trying to do is I want to add few lines of code after tomcat is completed with it's installation in /var/lib/tomcat8/conf/catalina.properties file.

here is what i have tried so far the simple ruby way and with chef utils too.

File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
  f << "\n"
  f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
end

ruby_block "insert_line" do
  block do
    file = Chef::Util::FileEdit.new("/var/lib/tomcat8/conf/catalina.properties")
    file.insert_line_if_no_match("/javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl/", "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl")
    file.write_file
  end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

file '/var/lib/tomcat8/conf/catalina.properties' do
   action :create
   owner 'root'
   group 'root'
   content File.open("/var/lib/tomcat8/conf/catalina.properties", "a+") do |f|
      f << "\n"
      f << "javax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl"
    end
end

I tried putting puts "testing" and it seems that chef isn't even getting into code.


问:
Return binary HTTP response from OpenWhisk (IBM Cloud Function) action
I want to return a binary file which resides in (IBM Cloud) ObjectStorage via HTTP using OpenWhisk in a IBM Cloud Function.

Is this possible? To me it seems OpenWhisk only supports JSON as result to an action.

This is the code I'm using (get_object_storage_file returns binary data):

```<code>import sys
from io import StringIO
import requests
import json

def get_object_storage_file(container, filename):
    """This functions returns a StringIO object containing
    the file content from Bluemix Object Storage."""

    url1 = ''.join(['https://identity.open.softlayer.com', '/v3/auth/tokens'])
    data = {'auth': {'identity': {'methods': ['password'],
            'password': {'user': {'name': 'member_1feaf9dc308e9d57b5fce8a2424e51cd3f04af17','domain': {'id': '4619da2fa8524beda11c89d2d1969c5b'},
            'password': 'nviJ.XXXXXXX.aexT'}}}}}
    headers1 = {'Content-Type': 'application/json'}
    resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
    resp1_body = resp1.json()
    for e1 in resp1_body['token']['catalog']:
        if(e1['type']=='object-store'):
            for e2 in e1['endpoints']:
                        if(e2['interface']=='public'and e2['region']=='dallas'):
                            url2 = ''.join([e2['url'],'/', container, '/', filename])
    s_subject_token = resp1.headers['x-subject-token']
    headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
    resp2 = requests.get(url=url2, headers=headers2)
    return StringIO(resp2.text)

def main(dict):
    get_object_storage_file('data', 'raw.bin')
    return {'greeting':'test'}
</code>```

答:
Is this about a web-action or a "normal" action?

In general, you can always return a Base64 encoded representation of your binary data, encoded in a JSON object. It is true, that a CloudFunctions action always needs to return a JSON object.

In your specific example, the following could work:

```<code>import base64

def main(dict):
    binary = get_object_storage_file('data', 'raw.bin')
    return {'data':base64.base64encode(binary)}
</code>```

(untested pseudocode)

Body:
I want to return a binary file which resides in (IBM Cloud) ObjectStorage via HTTP using OpenWhisk in a IBM Cloud Function.

Is this possible? To me it seems OpenWhisk only supports JSON as result to an action.

This is the code I'm using (get_object_storage_file returns binary data):

import sys
from io import StringIO
import requests
import json

def get_object_storage_file(container, filename):
    """This functions returns a StringIO object containing
    the file content from Bluemix Object Storage."""

    url1 = ''.join(['https://identity.open.softlayer.com', '/v3/auth/tokens'])
    data = {'auth': {'identity': {'methods': ['password'],
            'password': {'user': {'name': 'member_1feaf9dc308e9d57b5fce8a2424e51cd3f04af17','domain': {'id': '4619da2fa8524beda11c89d2d1969c5b'},
            'password': 'nviJ.XXXXXXX.aexT'}}}}}
    headers1 = {'Content-Type': 'application/json'}
    resp1 = requests.post(url=url1, data=json.dumps(data), headers=headers1)
    resp1_body = resp1.json()
    for e1 in resp1_body['token']['catalog']:
        if(e1['type']=='object-store'):
            for e2 in e1['endpoints']:
                        if(e2['interface']=='public'and e2['region']=='dallas'):
                            url2 = ''.join([e2['url'],'/', container, '/', filename])
    s_subject_token = resp1.headers['x-subject-token']
    headers2 = {'X-Auth-Token': s_subject_token, 'accept': 'application/json'}
    resp2 = requests.get(url=url2, headers=headers2)
    return StringIO(resp2.text)

def main(dict):
    get_object_storage_file('data', 'raw.bin')
    return {'greeting':'test'}

Body:
Is this about a web-action or a "normal" action?

In general, you can always return a Base64 encoded representation of your binary data, encoded in a JSON object. It is true, that a CloudFunctions action always needs to return a JSON object.

In your specific example, the following could work:

import base64

def main(dict):
    binary = get_object_storage_file('data', 'raw.bin')
    return {'data':base64.base64encode(binary)}

(untested pseudocode)


问:
Creating a density plot in R
I am new in R and I am trying to create a density plot.
I am looking to create a plot based on some regression analysis I have done earlier. So, basically, I want to see the relationship of Z to a,b and c variables that I have. All variables have values that range between 0 and 1 (numeric).

I have been trying to use ggplot to do the plot using the following code:

```<code>     dataset$test <- data.frame(a, b, c)
     ggplot(dataset, aes(Z, colour = test)) + geom_density()
</code>```

I am not sure how I can group the a,b,c variables into 1 so I can use that in the colour of the ggplot function (see test variable)

When I run the ggplot I get this error: Aesthetics must be either length 1 or the same as the data (417): x, colour.

Can anyone help me develop this plot?

Thanks!

See the sample image of what I'm going for

答:
```<code># example dataset
df = data.frame(a = rnorm(50, 5, 6),
                b = rnorm(50, 0, 1),
                c = runif(50,0,1))

library(dplyr)
library(tidyr)
library(ggplot2)

df %>%
  gather(var, Z) %>%                                  # reshape dataset
  ggplot(aes(Z, fill=var))+geom_density(alpha = 0.3)  # plot data
</code>```

Title: Creating a density plot in R

Body:
I am new in R and I am trying to create a density plot.
I am looking to create a plot based on some regression analysis I have done earlier. So, basically, I want to see the relationship of Z to a,b and c variables that I have. All variables have values that range between 0 and 1 (numeric).

I have been trying to use ggplot to do the plot using the following code:

     dataset$test <- data.frame(a, b, c)
     ggplot(dataset, aes(Z, colour = test)) + geom_density()

I am not sure how I can group the a,b,c variables into 1 so I can use that in the colour of the ggplot function (see test variable)

When I run the ggplot I get this error: Aesthetics must be either length 1 or the same as the data (417): x, colour.

Can anyone help me develop this plot?

Thanks!

See the sample image of what I'm going for


问:
Comment out lines in multiple .htaccess files in multiple directories
I need to comment out specific lines in .htaccess files for many different websites on a server.

The .htaccess files are in directories like this:

```<code>/home/siteA/public_html/.htaccess

/home/siteB/public_html/.htaccess
</code>```

and so on...

these are the blocks of code I want to comment out from all .htaccess files:

```<code><IfModule mod_suphp.c>
suPHP_ConfigPath /home/bcrunch
<Files php.ini>
order allow,deny
deny from all
</Files>
</IfModule>

<Files ".user.ini">
<IfModule mod_authz_core.c>
    Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
    Order deny,allow
    Deny from all
</IfModule>
</Files>
</code>```

Ive tried the following:

```<code>root@server [/home]# shopt -s globstar
root@server [/home]# sed -i.bak -r '/<IfModule     mod_suphp\.c>/,/<\/IfModule>/ s/^/#/; /<Files
"\.user\.ini">/,/<\/Files>/ s/^/#/' **/.htaccess
</code>```

Ive tested it on a test directory I made with other test sub dirs and test .htaccess files in with the above content and it worked fine but once I run this from /home where I have about 30+ sites it hangs for a long time and just starts using up more and more memory. The problem is that its searching recursively and as there are other .htaccess files in other directories that Im not interested in its just getting bogged down.

So how can I change the above code and tell it to ONLY make changes to all files like this?

/home/siteA/public_html/.htaccess

and ignore other .htacccess files?

Ive been trying to use various find searches but been having no luck so far.

答:
You can use this sed:

```<code>sed '/<IfModule mod_suphp\.c>/,/<\/IfModule>/s/^/#/; /<Files "\.user\.ini">/,/<\/Files>/s/^/#/' file
</code>```

Combined with find:

```<code>find /home/site*/public_html -name '.htaccess' -exec \
sed -i.bak '/<IfModule mod_suphp\.c>/,/<\/IfModule>/s/^/#/; /<Files "\.user\.ini">/,/<\/Files>/s/^/#/' {} \;
</code>```

Body:
I need to comment out specific lines in .htaccess files for many different websites on a server.

The .htaccess files are in directories like this:

/home/siteA/public_html/.htaccess

/home/siteB/public_html/.htaccess

and so on...

these are the blocks of code I want to comment out from all .htaccess files:

<IfModule mod_suphp.c>
suPHP_ConfigPath /home/bcrunch
<Files php.ini>
order allow,deny
deny from all
</Files>
</IfModule>

<Files ".user.ini">
<IfModule mod_authz_core.c>
    Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
    Order deny,allow
    Deny from all
</IfModule>
</Files>

Ive tried the following:

root@server [/home]# shopt -s globstar
root@server [/home]# sed -i.bak -r '/<IfModule     mod_suphp\.c>/,/<\/IfModule>/ s/^/#/; /<Files
"\.user\.ini">/,/<\/Files>/ s/^/#/' **/.htaccess

Ive tested it on a test directory I made with other test sub dirs and test .htaccess files in with the above content and it worked fine but once I run this from /home where I have about 30+ sites it hangs for a long time and just starts using up more and more memory. The problem is that its searching recursively and as there are other .htaccess files in other directories that Im not interested in its just getting bogged down.

So how can I change the above code and tell it to ONLY make changes to all files like this?

/home/siteA/public_html/.htaccess

and ignore other .htacccess files?

Ive been trying to use various find searches but been having no luck so far.

Body:
You can use this sed:

sed '/<IfModule mod_suphp\.c>/,/<\/IfModule>/s/^/#/; /<Files "\.user\.ini">/,/<\/Files>/s/^/#/' file

Combined with find:

find /home/site*/public_html -name '.htaccess' -exec \
sed -i.bak '/<IfModule mod_suphp\.c>/,/<\/IfModule>/s/^/#/; /<Files "\.user\.ini">/,/<\/Files>/s/^/#/' {} \;


问:
Two Django projects with same database - permission denied for relation django_migrations
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database.

I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception:

```<code>django.db.utils.ProgrammingError: permission denied for relation django_migrations
</code>```

My setup is as follows:

```<code>//First project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '******************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
//Second project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin_2',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
</code>```

I have granted SUPERUSER privileges to both users.
I have tried to set individual privileges while being connected as the corresponding user in the psql shell.

```<code>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2;
</code>```

The DB access privileges in the psql shell:

```<code>=Tc/simeonparvanov
simeonparvanov=CTc/simeonparvanov
srt_side_by_side_admin=CTc/simeonparvanov
srt_side_by_side_admin_2=CTc/simeonparvanov
</code>```

Any idea what am I doing wrong?

答: You don't need to create two separate users. for more info checkout https://groups.google.com/forum/#!msg/django-users/uA_XyGYKn2o/km80RXBB2uMJ</p>

Body:
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database.

I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception:

django.db.utils.ProgrammingError: permission denied for relation django_migrations

My setup is as follows:

//First project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '******************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
//Second project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin_2',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}

I have granted SUPERUSER privileges to both users.
I have tried to set individual privileges while being connected as the corresponding user in the psql shell.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2;

The DB access privileges in the psql shell:

=Tc/simeonparvanov
simeonparvanov=CTc/simeonparvanov
srt_side_by_side_admin=CTc/simeonparvanov
srt_side_by_side_admin_2=CTc/simeonparvanov

Any idea what am I doing wrong?


答:
Basically you need two other table beside your book table, one is author table which for that you need to create a model class for your Author and with that you can add Author. And a pivot table authors_books, since it is a many to many relation.

```<code> Author::create(['name' => $name,....]);
</code>```

and

```<code> Schema::create('authors_books', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('author_id')->unsigned();
        $table->integer('book_id')->unsigned();
        $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
        $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
        $table->timestamps();
    });
</code>```

And you can add to the pivot table:

```<code>DB::table('authors_books')->insert(
            ['author_id' => $author, 'book_id' => $book_id]
        );
</code>```

Title: Insert data for "Many to Many"

Body:
Basically you need two other table beside your book table, one is author table which for that you need to create a model class for your Author and with that you can add Author. And a pivot table authors_books, since it is a many to many relation.

 Author::create(['name' => $name,....]);

and

 Schema::create('authors_books', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('author_id')->unsigned();
        $table->integer('book_id')->unsigned();
        $table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
        $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
        $table->timestamps();
    });

And you can add to the pivot table:

DB::table('authors_books')->insert(
            ['author_id' => $author, 'book_id' => $book_id]
        );


问:
Plotting huge data files in R?
I have a input file that has about 20 million lines.  The size of the file is about 1.2 G.  Is there anyway I can plot the data in R.  Some of the columns have categories, most of them are numbers.

I have tried my plotting script with a small subset of the input file about 800K lines, but even though i have about 8G of RAM, I dont seem to be able to plot all the data.  Is there any simple way to do this.

答: Increasing the memory with memory.limit() helped me ... This is for plotting with ggplot nearly 36K records. </p>

Title: Plotting huge data files in R?


问:
Restart exception handling if one part fails
I have the following snippet:

```<code>def check1(n):
    if len(n) != 4:
        return raw_input("Enter 4 digits only")
    else:
        return True

def check2(n):
    if n.isdigit() != True:
        return raw_input("Enter digits only")
    else:
        return True

def check3(n):
    if len(set(str(n))) != 4:
        return raw_input("Enter non duplicate numbers only")
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    if (check1(b) != True or check2(b) != True or check3(b) != True):
        if check1(b) != True:
            print check1(b)
        elif check2(b) != True:
            print check2(b)
        elif check3(b) != True:
            print check3(b)
    else:
        print b
</code>```

How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.

UPDATE
I've improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn't work properly. If I enter '1' consecutively, it bounces between different exceptions instead of staying on the first check.

```<code>def checks(n):
    if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
        return False
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    while checks(b) != True:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        if b.isdigit() != True:
            b = raw_input("Enter digits only")
        if len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")

    print b
</code>```

答: you should try to create wrapper function which will contain all the checks. Once one will fail call the function again and again </p>

Body:
I have the following snippet:

def check1(n):
    if len(n) != 4:
        return raw_input("Enter 4 digits only")
    else:
        return True

def check2(n):
    if n.isdigit() != True:
        return raw_input("Enter digits only")
    else:
        return True

def check3(n):
    if len(set(str(n))) != 4:
        return raw_input("Enter non duplicate numbers only")
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    if (check1(b) != True or check2(b) != True or check3(b) != True):
        if check1(b) != True:
            print check1(b)
        elif check2(b) != True:
            print check2(b)
        elif check3(b) != True:
            print check3(b)
    else:
        print b

How can I rewrite this such that if any of the check functions fail, it starts from the b = raw_input line again and retests all the checks.

UPDATE
I've improved the code after heeding the advice from keithjgrant and m1k3y02 but it doesn't work properly. If I enter '1' consecutively, it bounces between different exceptions instead of staying on the first check.

def checks(n):
    if len(n) != 4 or n.isdigit() != True or len(set(str(n))) != 4:
        return False
    else:
        return True

sturn = 1
lturn = 8

a = raw_input("Enter the 4 numbers you want to play with: ")

for turn in range(sturn, lturn):
    b = raw_input("Enter your guess: ")
    while checks(b) != True:
        if len(b) != 4:
            b = raw_input("Enter 4 digits only")
        if b.isdigit() != True:
            b = raw_input("Enter digits only")
        if len(set(str(b))) != 4:
            b = raw_input("Enter non duplicate numbers only")

    print b


问:
Combine two collections with predicate using Stream API
I have two collections of type Entity.

```<code>class Entity {
    long id;
    // other fields
}

Collection<Entity> first = ...
Collection<Entity> second = ...
</code>```

I need to combine them in a such way that all elements in first should be replaced by elements from second if their ids are equal.

So, e.g if first contains [{"id": 1}, {"id": 2}, {"id": 3}] and second contains [{"id": 3}, {"id": 4}, {"id": 5}]

the result should be like this: [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}] where {"id": 3} from second replaced {"id": 3} from first.

Is there a way how to implement it in a Java 8 way, using Stream API.

答:
Maybe some old-fashioned, simple Collection methods can help you :

```<code>first.removeAll(second);
first.addAll(second);
</code>```

Note you have to implement both hashCode and equals to use id as a parameter in your Entity class.

Ideone demo

Edit

As you cannot change equals, you can use Collection.removeIf to replicate the effect of removeAll:

```<code>second.forEach(entity2 -> first.removeIf(entity1 -> entity1.getId() == entity2.getId()));
first.addAll(second);
</code>```

Ideone demo 2

Body:
I have two collections of type Entity.

class Entity {
    long id;
    // other fields
}

Collection<Entity> first = ...
Collection<Entity> second = ...

I need to combine them in a such way that all elements in first should be replaced by elements from second if their ids are equal.

So, e.g if first contains [{"id": 1}, {"id": 2}, {"id": 3}] and second contains [{"id": 3}, {"id": 4}, {"id": 5}]

the result should be like this: [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}] where {"id": 3} from second replaced {"id": 3} from first.

Is there a way how to implement it in a Java 8 way, using Stream API.

Body:
Maybe some old-fashioned, simple Collection methods can help you :

first.removeAll(second);
first.addAll(second);

Note you have to implement both hashCode and equals to use id as a parameter in your Entity class.

Ideone demo

Edit

As you cannot change equals, you can use Collection.removeIf to replicate the effect of removeAll:

second.forEach(entity2 -> first.removeIf(entity1 -> entity1.getId() == entity2.getId()));
first.addAll(second);

Ideone demo 2


问:
How to resolve "dyld: Library not loaded: @executable_path.." error

I was trying to check the AWS-CLI version on my MAC OS X. And the below error hit back:

```<code>dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /usr/local/aws/bin/python
  Reason: image not found
Abort trap: 6
</code>```

Any relevant inputs on how to fix this would be highly appreciated.

答:
This error occurs because your virtual environment has broken symlinks.
Here is a nice solution taken from tevino's fix_virtualenv gist:

#!/usr/bin/env bash

ENV_PATH="$(dirname "$(dirname "$(which pip)")")"
SYSTEM_VIRTUALENV="$(which -a virtualenv|tail -1)"

BAD_ENV_PATHS="/usr/local"

echo "Ensure the root of the broken virtualenv:"
echo "    $ENV_PATH"

if [[ -z "$ENV_PATH" ]] || [[ "$ENV_PATH" = *"$BAD_ENV_PATHS"* ]]; then
    echo "The root path above doesn't seems to be a valid one."
    echo "Please make sure you ACTIVATED the broken virtualenv."
    echo "‼  Exiting for your safety... (thanks @laymonk for reporting this)"
    exit 1
fi

read -p "‼  Press Enter if you are not sure (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "♻  Removing old symbolic links......"
    find "$ENV_PATH" -type l -delete -print
    echo "  Creating new symbolic links......"
    $SYSTEM_VIRTUALENV "$ENV_PATH"
    echo "  Done!"
fi
```

Also, here is a similar question:
Broken references in Virtualenvs.

Body:
I was trying to check the AWS-CLI version on my MAC OS X. And the below error hit back:

dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /usr/local/aws/bin/python
  Reason: image not found
Abort trap: 6

Any relevant inputs on how to fix this would be highly appreciated.

Body:
This error occurs because your virtual environment has broken symlinks.
Here is a nice solution taken from tevino's fix_virtualenv gist:

#!/usr/bin/env bash

ENV_PATH="$(dirname "$(dirname "$(which pip)")")"
SYSTEM_VIRTUALENV="$(which -a virtualenv|tail -1)"

BAD_ENV_PATHS="/usr/local"

echo "Ensure the root of the broken virtualenv:"
echo "    $ENV_PATH"

if [[ -z "$ENV_PATH" ]] || [[ "$ENV_PATH" = *"$BAD_ENV_PATHS"* ]]; then
    echo "The root path above doesn't seems to be a valid one."
    echo "Please make sure you ACTIVATED the broken virtualenv."
    echo "‼  Exiting for your safety... (thanks @laymonk for reporting this)"
    exit 1
fi

read -p "‼  Press Enter if you are not sure (y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "♻  Removing old symbolic links......"
    find "$ENV_PATH" -type l -delete -print
    echo "  Creating new symbolic links......"
    $SYSTEM_VIRTUALENV "$ENV_PATH"
    echo "  Done!"
fi

Also, here is a similar question:
Broken references in Virtualenvs.


问:
Magento database tables - where is EAN stored
I am working on a Magento project and to complete an import to ebay process I may need to do a bulk update on EAN numbers.

I am reviewing the database and the tables - and I haven't found or see any indication as to where this "EAN" field is stored.

I can see it present on individual products under "general" in the edit panel on the magento site

答:
As it is present under "General" tab when viewing individual products, it means that EAN is a product attribute.

Values are stored in catalog_product_entity_* tables, based on the backend type of the EAN product attribute. In case you don't know the type, you will need to check the contents of eav_attribute table for the EAN record.

A good article that explains Magento's database structure can be found here: https://fishpig.co.uk/magento/tutorials/eav-database-structure/


问:
bash: using find with multiple file types, provided as an array
In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:

```<code>getMatchingFiles() {
  output=$1
  directory=$2
  shift 2
  _types_=("$@")

  file_array=find $directory -type f where-name-matches-item-in-_types_

  # do other stuff with $file_array, such as trimming file names to
  # just the basename with no extension

  eval $output="${file_array[@]}"
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"
</code>```

For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.

```<code>getMatchingFiles() {
  local _output=$1
  local _dir=$2
  shift 2
  local _type=("$@")
  local _files=($_dir/$_type/*)
  local -i ii=${#_files[@]}
  local -a _filetypes
  local _file _regex

  case $_type in
    audio )
      _filetypes=(ogg mp3)
      ;;
    images )
      _filetypes=(jpg png)
      ;;
  esac

  _regex="^.*\.("
  for _filetype in "${_filetypes[@]}"
  do
     _regex+=$_filetype"|"
  done

  _regex=${_regex:0:-1}
  _regex+=")$"

  for (( ; ii-- ; ))
  do
    _file=${_files[$ii]}
    if ! [[ $_file =~ $_regex ]];then
      unset _files[ii]
    fi
  done

  echo "${_files[@]}"

  # eval $_output="${_files[@]}" # tries to execute the files
}

dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"
</code>```

答:
Update: namerefs can indeed be arrays (see PesaThe's answer)

Without spaces in file and directory names

I first assume you do not have spaces in your file and directory names. See the second part of this answer if you have spaces in your file and directory names.

In order to pass result, dir and types by name to your function, you need to use namerefs (local -n or declare -n, available only in recent versions of bash).

Another difficulty is to build the find command based on the types you passed but this is not a major one. Pattern substitutions can do this. All in all, something like this should do about what you want:

```<code>#!/usr/bin/env bash

getMatchingFiles() {
    local -n output=$1
    local -n directory=$2
    local -n _types_=$3
    local filter

    filter="${_types_[@]/#/ -o -name *.}"
    filter="${filter# -o }"
    output=( $( find "$directory" -type f \( $filter \) ) )

    # do other stuff with $output, such as trimming file names to
    # just the basename with no extension
}

declare dir
declare -a types
declare -a result=()

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
for f in "${result[@]}"; do echo "$f"; done
</code>```

With spaces in file and directory names (but not in file suffixes)

If you have spaces in your file and directory names, things are a bit more difficult because you must assign your array such that names are not split in words; one possibility to do this is to use \0 as file names separator, instead of a space, thanks to the -print0 option of find and the -d $'\0' option of read:

```<code>#!/usr/bin/env bash

getMatchingFiles() {
    local -n output=$1
    local -n directory=$2
    local -n _types_=$3
    local filter

    filter="${_types_[@]/#/ -o -name *.}"
    filter="${filter# -o }"
    while read -d $'\0' file; do
        output+=( "$file" )
    done < <( find "$directory" -type f \( $filter \) -print0 )

    # do other stuff with $output, such as trimming file names to
    # just the basename with no extension
}

declare dir
declare -a types
declare -a result=()

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types[@]
for f in "${result[@]}"; do echo "$f"; done
</code>```

With spaces in file and directory names, even in file suffixes

Well, you deserve what happens to you... Still possible but left as an exercise.

Body:
In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:

getMatchingFiles() {
  output=$1
  directory=$2
  shift 2
  _types_=("$@")

  file_array=find $directory -type f where-name-matches-item-in-_types_

  # do other stuff with $file_array, such as trimming file names to
  # just the basename with no extension

  eval $output="${file_array[@]}"
}

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"

For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.

getMatchingFiles() {
  local _output=$1
  local _dir=$2
  shift 2
  local _type=("$@")
  local _files=($_dir/$_type/*)
  local -i ii=${#_files[@]}
  local -a _filetypes
  local _file _regex

  case $_type in
    audio )
      _filetypes=(ogg mp3)
      ;;
    images )
      _filetypes=(jpg png)
      ;;
  esac

  _regex="^.*\.("
  for _filetype in "${_filetypes[@]}"
  do
     _regex+=$_filetype"|"
  done

  _regex=${_regex:0:-1}
  _regex+=")$"

  for (( ; ii-- ; ))
  do
    _file=${_files[$ii]}
    if ! [[ $_file =~ $_regex ]];then
      unset _files[ii]
    fi
  done

  echo "${_files[@]}"

  # eval $_output="${_files[@]}" # tries to execute the files
}

dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"

Body:
Update: namerefs can indeed be arrays (see PesaThe's answer)

Without spaces in file and directory names

I first assume you do not have spaces in your file and directory names. See the second part of this answer if you have spaces in your file and directory names.

In order to pass result, dir and types by name to your function, you need to use namerefs (local -n or declare -n, available only in recent versions of bash).

Another difficulty is to build the find command based on the types you passed but this is not a major one. Pattern substitutions can do this. All in all, something like this should do about what you want:

#!/usr/bin/env bash

getMatchingFiles() {
    local -n output=$1
    local -n directory=$2
    local -n _types_=$3
    local filter

    filter="${_types_[@]/#/ -o -name *.}"
    filter="${filter# -o }"
    output=( $( find "$directory" -type f \( $filter \) ) )

    # do other stuff with $output, such as trimming file names to
    # just the basename with no extension
}

declare dir
declare -a types
declare -a result=()

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
for f in "${result[@]}"; do echo "$f"; done

With spaces in file and directory names (but not in file suffixes)

If you have spaces in your file and directory names, things are a bit more difficult because you must assign your array such that names are not split in words; one possibility to do this is to use \0 as file names separator, instead of a space, thanks to the -print0 option of find and the -d $'\0' option of read:

#!/usr/bin/env bash

getMatchingFiles() {
    local -n output=$1
    local -n directory=$2
    local -n _types_=$3
    local filter

    filter="${_types_[@]/#/ -o -name *.}"
    filter="${filter# -o }"
    while read -d $'\0' file; do
        output+=( "$file" )
    done < <( find "$directory" -type f \( $filter \) -print0 )

    # do other stuff with $output, such as trimming file names to
    # just the basename with no extension
}

declare dir
declare -a types
declare -a result=()

dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types[@]
for f in "${result[@]}"; do echo "$f"; done

With spaces in file and directory names, even in file suffixes

Well, you deserve what happens to you... Still possible but left as an exercise.


问:
How to run an instance of Excel Online on my own domain?
I stumbled on this website and found it very interesting because I'm trying to do the same thing: run Excel Online on my own domain. I tried Googling around without success. Does anyone have a resource or approach to this problem (see image for more information*) ?

答: They may be using one of the following: CSPP or using their own domain. </p>


问:
How to use Driver Wait Until Text is in selenium
I am trying to use driver wait function with the following wait condition.

I want to test that the text on a button is equal to/matches "Sign Up".
The following is my code:

```<code>driver.wait(until.elementTextIs(By.css('body > div.site-wrapper > div > div
> div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary'),'Sign
Up'),80000)
</code>```

But after running it I get the error:

```<code>C:\Users\bob\Documents\testElectron\node_modules\selenium-
webdriver\lib\promise.js:2626   Uncaught TypeError: element.getText is not a
function
</code>```

I have tried retrieving the text on the button manually using

```<code>var Button = driver.findElement(By.css('body > div.site-wrapper > div > div
> div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary'));
Button.getText().then(function(text){
 console.log(text);
});
</code>```

and it works , but I would like to use the condition for the wait.
PS: The button does exist and is visible when I run the commands
I am using selenium nodeJS implementation with the chrome driver.

答:
The function until.elementTextIs takes a web element but you are providing a locator.

Either wait for the element and then for the text:

```<code>var buttonLogin = By.css('body > div.site-wrapper > div > div > div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary');

driver.wait(until.elementTextIs(driver.wait(until.elementLocated(buttonLogin)), 'Sign Up'), 80000);
</code>```

or create an expected condition which will wait for an element that has the desired text:

```<code>var Condition = webdriver.Condition;

until.elementLocatedTextIs = function elementLocatedTextIs(locator, text) {
  return new Condition(
    'for element to be located ' + locator + ' with text ' + text,
    function(driver) {
      return driver.findElements(locator).then(function(elements) {
        return elements.filter(function(element) {
          return element.getText().then(t => t === text ? element : null);
        }).then(function(elements) {
          return elements[0];
        });
      });
    });
};

var buttonLogin = By.css('body > div.site-wrapper > div > div > div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary');

driver.wait(until.elementLocatedTextIs(buttonLogin), 'Sign Up'), 80000);
</code>```

Body:
I am trying to use driver wait function with the following wait condition.

I want to test that the text on a button is equal to/matches "Sign Up".
The following is my code:

driver.wait(until.elementTextIs(By.css('body > div.site-wrapper > div > div
> div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary'),'Sign
Up'),80000)

But after running it I get the error:

C:\Users\bob\Documents\testElectron\node_modules\selenium-
webdriver\lib\promise.js:2626   Uncaught TypeError: element.getText is not a
function

I have tried retrieving the text on the button manually using

var Button = driver.findElement(By.css('body > div.site-wrapper > div > div
> div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary'));
Button.getText().then(function(text){
 console.log(text);
});

and it works , but I would like to use the condition for the wait.
PS: The button does exist and is visible when I run the commands
I am using selenium nodeJS implementation with the chrome driver.

Body:
The function until.elementTextIs takes a web element but you are providing a locator.

Either wait for the element and then for the text:

var buttonLogin = By.css('body > div.site-wrapper > div > div > div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary');

driver.wait(until.elementTextIs(driver.wait(until.elementLocated(buttonLogin)), 'Sign Up'), 80000);

or create an expected condition which will wait for an element that has the desired text:

var Condition = webdriver.Condition;

until.elementLocatedTextIs = function elementLocatedTextIs(locator, text) {
  return new Condition(
    'for element to be located ' + locator + ' with text ' + text,
    function(driver) {
      return driver.findElements(locator).then(function(elements) {
        return elements.filter(function(element) {
          return element.getText().then(t => t === text ? element : null);
        }).then(function(elements) {
          return elements[0];
        });
      });
    });
};

var buttonLogin = By.css('body > div.site-wrapper > div > div > div.inner.cover > p:nth-child(3) > a.btn.btn-lg.btn-primary');

driver.wait(until.elementLocatedTextIs(buttonLogin), 'Sign Up'), 80000);


问:
How to externalise sslContextParameters
I'm using Apache Camel 2.20.0 and deploying a REST service using REST DSL with a HTTP scheme.

I'm referencing sslContextParameters with hard coded values and all works just fine.

I can't find a way of externalizing the resource into a properties file. So far I've tried with Camel PropertiesComponent and also Spring PropertyPlaceholderConfigurer and BridgePropertyPlaceholderConfigurer and I want to be able to do the following in the config:

```<code><camel:sslContextParameters camelContextId="camelContext1" id="routeSSLContextParameters">
    <camel:keyManagers keyPassword="{{mypassword}}">
        <camel:keyStore password="{{mypassword}}"
            resource="{{mykeystore}}" type="JKS"/>
    </camel:keyManagers>
    <camel:trustManagers>
        <camel:keyStore password="{{mypassword}}"
            resource="{{mykeystore}}" type="JKS"/>
    </camel:trustManagers>
</camel:sslContextParameters>
</code>```

I've also tried putting ${} as per Spring properties, this also does not work.

Would it be possible to tell me where I'm going wrong?

答:
This is what I did in the end:

1.Use Spring/Camel properties bridge:

```<code><bean class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer" id="springProperties">
        <property name="location" value="classpath:application.properties"/>
</bean>
</code>```

2.Set up the SSLContext Parameters from Spring:

```<code>   <bean class="org.apache.camel.util.jsse.SSLContextParameters" id="routeSSLContextParameters">
        <property name="keyManagers" ref="routeKeyManagers"/>
        <property name="trustManagers" ref="routeTrustManagers"/>
        <property name="serverParameters" ref="routeSSLContextServerParameters"/>
    </bean>
    <bean class="org.apache.camel.util.jsse.KeyManagersParameters" id="routeKeyManagers">
        <property name="keyStore" ref="routeKeystore"/>
        <property name="keyPassword" value="${keyStorePassword}"/>
    </bean>
    <bean class="org.apache.camel.util.jsse.TrustManagersParameters" id="routeTrustManagers">
        <property name="keyStore" ref="routeTruststore"/>
    </bean>
    <bean class="org.apache.camel.util.jsse.SSLContextServerParameters" id="routeSSLContextServerParameters">
        <property name="clientAuthentication" value="REQUIRE"/>
    </bean>
    <keyStoreParameters id="routeKeystore" password="${keyStorePassword}" resource="${keyStoreResource}" type="JKS" xmlns="http://camel.apache.org/schema/spring"/>
    <keyStoreParameters id="routeTruststore" password="${trustStorePassword}" resource="${trustStoreResource}" type="JKS" xmlns="http://camel.apache.org/schema/spring"/>
</code>```

Reference the SSLContext in the restconfiguration

```<code><restConfiguration apiContextPath="api-docs" bindingMode="json" component="restlet" contextPath="/mytest" enableCORS="true"
    host="localhost" port="9090" scheme="https">
    <endpointProperty key="sslContextParameters" value="#routeSSLContextParameters"/>.....
</code>```

Title: How to externalise sslContextParameters

Body:
I'm using Apache Camel 2.20.0 and deploying a REST service using REST DSL with a HTTP scheme.

I'm referencing sslContextParameters with hard coded values and all works just fine.

I can't find a way of externalizing the resource into a properties file. So far I've tried with Camel PropertiesComponent and also Spring PropertyPlaceholderConfigurer and BridgePropertyPlaceholderConfigurer and I want to be able to do the following in the config:

<camel:sslContextParameters camelContextId="camelContext1" id="routeSSLContextParameters">
    <camel:keyManagers keyPassword="{{mypassword}}">
        <camel:keyStore password="{{mypassword}}"
            resource="{{mykeystore}}" type="JKS"/>
    </camel:keyManagers>
    <camel:trustManagers>
        <camel:keyStore password="{{mypassword}}"
            resource="{{mykeystore}}" type="JKS"/>
    </camel:trustManagers>
</camel:sslContextParameters>

I've also tried putting ${} as per Spring properties, this also does not work.

Would it be possible to tell me where I'm going wrong?

Body:
This is what I did in the end:

1.Use Spring/Camel properties bridge:

<bean class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer" id="springProperties">
        <property name="location" value="classpath:application.properties"/>
</bean>

2.Set up the SSLContext Parameters from Spring:

   <bean class="org.apache.camel.util.jsse.SSLContextParameters" id="routeSSLContextParameters">
        <property name="keyManagers" ref="routeKeyManagers"/>
        <property name="trustManagers" ref="routeTrustManagers"/>
        <property name="serverParameters" ref="routeSSLContextServerParameters"/>
    </bean>
    <bean class="org.apache.camel.util.jsse.KeyManagersParameters" id="routeKeyManagers">
        <property name="keyStore" ref="routeKeystore"/>
        <property name="keyPassword" value="${keyStorePassword}"/>
    </bean>
    <bean class="org.apache.camel.util.jsse.TrustManagersParameters" id="routeTrustManagers">
        <property name="keyStore" ref="routeTruststore"/>
    </bean>
    <bean class="org.apache.camel.util.jsse.SSLContextServerParameters" id="routeSSLContextServerParameters">
        <property name="clientAuthentication" value="REQUIRE"/>
    </bean>
    <keyStoreParameters id="routeKeystore" password="${keyStorePassword}" resource="${keyStoreResource}" type="JKS" xmlns="http://camel.apache.org/schema/spring"/>
    <keyStoreParameters id="routeTruststore" password="${trustStorePassword}" resource="${trustStoreResource}" type="JKS" xmlns="http://camel.apache.org/schema/spring"/>

Reference the SSLContext in the restconfiguration

<restConfiguration apiContextPath="api-docs" bindingMode="json" component="restlet" contextPath="/mytest" enableCORS="true"
    host="localhost" port="9090" scheme="https">
    <endpointProperty key="sslContextParameters" value="#routeSSLContextParameters"/>.....


问:
Injecting Repository in Controller - Class does not exist
I've created App/Repositories/HelloRepository, but get Class App\Http\Controllers\HelloRepository does not exist

What am I missing to be able to inject my new repository into my controller

Repository:

```<code>namespace App\Repositories;

class HelloRepository
{
    public function sayHello()
    {
        return "Hello!";
    }
}
</code>```

Controller:

```<code><?php

namespace App\Http\Controllers;

use App\Repositories;

    public function index(HelloRepository $repo)
    {
        dd($repo->sayHello());
    }
</code>```

答:
The problem is in the use "use App\Repositories;", the name of the Repository is missed.

```<code>use App\Repositories\HelloRepository
</code>```

Body:
I've created App/Repositories/HelloRepository, but get Class App\Http\Controllers\HelloRepository does not exist

What am I missing to be able to inject my new repository into my controller

Repository:

namespace App\Repositories;

class HelloRepository
{
    public function sayHello()
    {
        return "Hello!";
    }
}

Controller:

<?php

namespace App\Http\Controllers;

use App\Repositories;

    public function index(HelloRepository $repo)
    {
        dd($repo->sayHello());
    }

Body:
The problem is in the use "use App\Repositories;", the name of the Repository is missed.

use App\Repositories\HelloRepository


问:
Doctrine2 Query Builder Left Join with Select
I want to implement this SQL using doctrine2 query builder:

```<code>SELECT c.*, COUNT(s.id) AS studentCount
FROM classes c
LEFT JOIN (
    SELECT *
    FROM student_classes
    WHERE YEAR =  '2012'
) sc ON c.id = sc.class_id
LEFT JOIN students s ON sc.student_id = s.id
GROUP BY c.id
</code>```

I tried this one but didn't work

```<code>$qb = $this->getEntityManager()
    ->getRepository('Classes')
    ->createQueryBuilder('c');
$qb->select('c.id AS id, c.name AS name, COUNT(s) AS studentCount');
$qb->leftJoin(
    $qb->select('sc1')
        ->from('StudentClasses', 'sc1')
        ->where('sc1.year = :year')
        ->setParameter('year', $inputYear),
    'sc2'
);
$qb->leftJoin('sc2.students', 's');
$qb->groupBy('c.id');
return $qb->getQuery()->getScalarResult();
</code>```

or should I use nativeSQL instead?

any help would be appreciated,
thanks.

答:
You can use WITH clause to join entity with additional check, For your subquery you can write the same using left join with year filter, In join part i have used c.studentClasses based on the assumption that in Classes entity you have some mapped property for StudentClasses entity

```<code>$qb = $this->getEntityManager()
    ->getRepository('Classes')
    ->createQueryBuilder('c');
$qb->select('c.id AS id, c.name AS name, COUNT(s) AS studentCount');
$qb->leftJoin('c.studentClasses','sc2', 'WITH', 'sc2.year = :year');
$qb->leftJoin('sc2.students', 's');
$qb->setParameter('year', $inputYear);
$qb->groupBy('c.id');
</code>```

Body:
I want to implement this SQL using doctrine2 query builder:

SELECT c.*, COUNT(s.id) AS studentCount
FROM classes c
LEFT JOIN (
    SELECT *
    FROM student_classes
    WHERE YEAR =  '2012'
) sc ON c.id = sc.class_id
LEFT JOIN students s ON sc.student_id = s.id
GROUP BY c.id

I tried this one but didn't work

$qb = $this->getEntityManager()
    ->getRepository('Classes')
    ->createQueryBuilder('c');
$qb->select('c.id AS id, c.name AS name, COUNT(s) AS studentCount');
$qb->leftJoin(
    $qb->select('sc1')
        ->from('StudentClasses', 'sc1')
        ->where('sc1.year = :year')
        ->setParameter('year', $inputYear),
    'sc2'
);
$qb->leftJoin('sc2.students', 's');
$qb->groupBy('c.id');
return $qb->getQuery()->getScalarResult();

or should I use nativeSQL instead?

any help would be appreciated,
thanks.

Body:
You can use WITH clause to join entity with additional check, For your subquery you can write the same using left join with year filter, In join part i have used c.studentClasses based on the assumption that in Classes entity you have some mapped property for StudentClasses entity

$qb = $this->getEntityManager()
    ->getRepository('Classes')
    ->createQueryBuilder('c');
$qb->select('c.id AS id, c.name AS name, COUNT(s) AS studentCount');
$qb->leftJoin('c.studentClasses','sc2', 'WITH', 'sc2.year = :year');
$qb->leftJoin('sc2.students', 's');
$qb->setParameter('year', $inputYear);
$qb->groupBy('c.id');


问:
port 80 for apache server is in use by PID 4 (System) and cannot be stopped
I am starting apache at port 80 with xampp. However, the port 80 is taken by PID of 4 by the name system.
I have tried Taskkill /F /PID 4 to force kill the task by even using the administor's rights but access is still denied.
Any idea on how to solve this problem (I don't want to change the port of apache)</p>

答: When I ran into the same problem of yours, I changed the apache port to 81 which is 80 by default, and it worked and I have been using since. here is how to do that. start xampp Control Panel-> click on the config button against apache -> click on httpd.conf -> look for port number and change it to a desired port -> restart xampp ->done.</p>


问:
Integrate User Registration with Azure AD
I'm currently trying to design and build an ASP.NET core application which will allow users to login via Azure AD. My goal is to have a web application that is hosted in Azure that allow (internal/external) users to login with our/their company's azure ad to access the application's functionality with a profile.

I'm looking to implement the workflow:

Step 1) User logs in with their Company email and authenticates with their company's Office 365 log-in. (I was able to get this working using the ASP.NET core sample project).

Step 2) If it's the users' first time, they are prompted with a registration page where they configure their profile. The profile information would be tracked in an internal sql server database. Their profile would be locked until an administrator completed the configuration/activation of their profile.

Step 3) If the user is already registered, their profile would be retrieved and loaded and the application would load the home page for the application so the user can access all the features they are allowed to.

I'm stuck on implementation Step 2. It's possible this isn't a great design and would welcome feedback to improve the workflow of an authenticated users accessing the web application.

For some history, I previously created an ASP.NET 4.5 MVC application (using the sample Visual Studio generates) where the users are internally tracked and registered, but I'm unable to figure out how to connect Step 1 to Step 2 when using ASP.NET core and Azure AD. I have no experience with Azure AD, and I'm a beginner with ASP.NET.

答:
Your question is quite broad.

I suggest you take a look at ASP.NET Core Identity. It allows you to outsource the authentication to Azure AD (and many other login providers), and also have a local user database with profile information.

Using standard Entity Framework methods to extend data classes and add migrations to the database, you can add profile information to your local database.

For some reason there is no sample that integrates Azure AD and ASP.NET Core Identity, so you have to see what needs to be done by looking at
the other external providers.

In short, you add the identity framework with these lines in the ConfigureServices method in Startup.cs:

```<code>services.AddDbContext<IdentityDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("IdentityDbConnectionString")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<IdentityDbContext>()
    .AddDefaultTokenProviders();
</code>```

and then add Azure AD authentication using Open ID Connect:

```<code>services.AddAuthentication()
    .AddOpenIdConnect(
        o =>
        {
            o.ClientId = Configuration["AzureAd:ClientId"];
            o.Authority = String.Format(
                        "https://login.microsoftonline.com/{0}", Configuration["AzureAd:Tenant"]);
            o.SignedOutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"];
        });
</code>```

Body:
Your question is quite broad.

I suggest you take a look at ASP.NET Core Identity. It allows you to outsource the authentication to Azure AD (and many other login providers), and also have a local user database with profile information.

Using standard Entity Framework methods to extend data classes and add migrations to the database, you can add profile information to your local database.

For some reason there is no sample that integrates Azure AD and ASP.NET Core Identity, so you have to see what needs to be done by looking at
the other external providers.

In short, you add the identity framework with these lines in the ConfigureServices method in Startup.cs:

services.AddDbContext<IdentityDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("IdentityDbConnectionString")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<IdentityDbContext>()
    .AddDefaultTokenProviders();

and then add Azure AD authentication using Open ID Connect:

services.AddAuthentication()
    .AddOpenIdConnect(
        o =>
        {
            o.ClientId = Configuration["AzureAd:ClientId"];
            o.Authority = String.Format(
                        "https://login.microsoftonline.com/{0}", Configuration["AzureAd:Tenant"]);
            o.SignedOutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"];
        });


问:
Remember expanded detail grids on refresh in Kendo-UI
I have a scenario with grid within grid implemented using the detailInit method. Here when user makes edit, i do some calculations that will change the data in the both parent and child. and then to refresh data, i will call the datasource.read to render data. this works and the data is displayed, however any detail grid which are expanded will be collapsed, is there any way i can prevent this from happening.</p>

答:
Different but similar solution that i used for same problem:</p>

```<code>       expandedItemIDs = [];

            function onDataBound() {
        //expand rows
                    for (var i = 0; i < expandedItemIDs.length; i++) {
                        var row = $(this.tbody).find("tr.k-master-row:eq(" + expandedItemIDs[i] + ")");
                        this.expandRow(row);
                    }
                }

        function onDetailExpand(e) {
            //refresh the child grid when click expand
            var grid = e.detailRow.find("[data-role=grid]").data("kendoGrid");
            grid.dataSource.read();
            //get index of expanded row
            $(e.detailCell).text("inner content");
            var row = $(e.masterRow).index(".k-master-row");
            if (contains(expandedItemIDs, row) == false)
                expandedItemIDs.push(row);
        }

        function onDetailCollapse(e) {
    //on collapse minus this row from array
            $(e.detailCell).text("inner content");
            var row = $(e.masterRow).index(".k-master-row");
            for (var i = 0; i < expandedItemIDs.length; i++)
                if (expandedItemIDs[i] == row)
                    expandedItemIDs.splice(i, 1);
        }

        function contains(a, obj) {
            for (var i = 0; i < a.length; i++)
                if (a[i] === obj) return true;
            return false;
        }
</code>```

Body:
Different but similar solution that i used for same problem:

       expandedItemIDs = [];

            function onDataBound() {
        //expand rows
                    for (var i = 0; i < expandedItemIDs.length; i++) {
                        var row = $(this.tbody).find("tr.k-master-row:eq(" + expandedItemIDs[i] + ")");
                        this.expandRow(row);
                    }
                }

        function onDetailExpand(e) {
            //refresh the child grid when click expand
            var grid = e.detailRow.find("[data-role=grid]").data("kendoGrid");
            grid.dataSource.read();
            //get index of expanded row
            $(e.detailCell).text("inner content");
            var row = $(e.masterRow).index(".k-master-row");
            if (contains(expandedItemIDs, row) == false)
                expandedItemIDs.push(row);
        }

        function onDetailCollapse(e) {
    //on collapse minus this row from array
            $(e.detailCell).text("inner content");
            var row = $(e.masterRow).index(".k-master-row");
            for (var i = 0; i < expandedItemIDs.length; i++)
                if (expandedItemIDs[i] == row)
                    expandedItemIDs.splice(i, 1);
        }

        function contains(a, obj) {
            for (var i = 0; i < a.length; i++)
                if (a[i] === obj) return true;
            return false;
        }


问:
Global variable not updated inside function
I spent few hours trying to find the reason why the variable dataset_path which is a global variable is always undefined

```<code>var dataset_path ;

function myFunction() {
  offline_data_mainlooper_bitfinex();
  print_bilan();
}
function offline_data_mainlooper_bitfinex(){
    var hours_step_size = 1*2;
    var daily_step_size = 24*2,
    // dataset_path = './quote/bitfinex/from_1480550400to_1512100800_1hquote.json';
    // dataset_path =  ('./quote/bitfinex/from_1480550400to_1512100800quote.json') //thats's 30 min
    dataset_path =  './quote/bitfinex/from_1480550400to_1512100800_15mquote.json'
       //... somecode

}
function print_bilan(){
   var filename = './analysis/test_log.json';
   //... somecode
 console.log('Quote saved! to ' +dataset_path, filename)
}
</code>```

答:
Because of this:

```<code>var daily_step_size = 24*2,
//                        ^
dataset_path =  './quote/bitfinex/from_1480550400to_1512100800_15mquote.json'
</code>```

That's declaring multiple variables in the local scope of offline_data_mainlooper_bitfinex, not ending the daily_step_size declaration and then doing an assignment to the global variable. Replace the comma by a semicolon (or omit it).

Body:
I spent few hours trying to find the reason why the variable dataset_path which is a global variable is always undefined

var dataset_path ;

function myFunction() {
  offline_data_mainlooper_bitfinex();
  print_bilan();
}
function offline_data_mainlooper_bitfinex(){
    var hours_step_size = 1*2;
    var daily_step_size = 24*2,
    // dataset_path = './quote/bitfinex/from_1480550400to_1512100800_1hquote.json';
    // dataset_path =  ('./quote/bitfinex/from_1480550400to_1512100800quote.json') //thats's 30 min
    dataset_path =  './quote/bitfinex/from_1480550400to_1512100800_15mquote.json'
       //... somecode

}
function print_bilan(){
   var filename = './analysis/test_log.json';
   //... somecode
 console.log('Quote saved! to ' +dataset_path, filename)
}

Body:
Because of this:

var daily_step_size = 24*2,
//                        ^
dataset_path =  './quote/bitfinex/from_1480550400to_1512100800_15mquote.json'

That's declaring multiple variables in the local scope of offline_data_mainlooper_bitfinex, not ending the daily_step_size declaration and then doing an assignment to the global variable. Replace the comma by a semicolon (or omit it).


问:
Boost::shared_ptr instantiated using this
Consider the following case:

```<code>typedef boost::shared_ptr<B> BPtr;

class A
{
public:
    A() { b_ptr = BPtr(new B); }
    void a_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class B
{
public:
    B() { b_ptr = BPtr(this); }
    void b_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class C
{
public:
    static void c_func(BPtr b_ptr) { /*...*/ }
}
</code>```

Is it ok to instantiate a shared_ptr with this?

Is it ok to have two shared_ptr objects pointing to the same object? (e.g. A::b_ptr and B::b_ptr)

If one of these two gets out of scope - would B's instance be deleted?

I'm guessing I'm doing something fundamentally wrong.

I also thought about using dependency injection of b_ptr to B's constructor, but that too seems very wrong.

UPDATE:

To clarify - Both A and B need to use C::c_func. In turn, after some processing, C needs to call a callback function in B which I haven't specified above.
Actually two cases are interesting:

If there's a requirement that C won't be stateful - then it needs to receive BPtr both from A and from B as in the code above.

If C is stateful and both A and B instantiate separate C instances, giving a BPtr in C's ctor.

答:
I would recommend that you re-design to use std::enable_shared_from_this, e.g.

```<code>class B
{
   B();
public:
   std::shared_ptr<B> create() { return std::make_shared<B>(); } // Make sure B is allocated as shared_ptr inorder to ensure that shared_from_this() works.
};
</code>```

However, if it's an API issue you have then you can do the following (although I don't recommend it).

```<code>void b_func() { C::c_func(BPtr(this, [](B*){})); } // Empty deleter. Nothing happens when shared_ptr goes out of scope. Note that c_func cannot take ownership of the pointer.
</code>```

Body:
Consider the following case:

typedef boost::shared_ptr BPtr;

class A
{
public:
    A() { b_ptr = BPtr(new B); }
    void a_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class B
{
public:
    B() { b_ptr = BPtr(this); }
    void b_func() { C::c_func(b_ptr); }
private:
    BPtr b_ptr;
}

class C
{
public:
    static void c_func(BPtr b_ptr) { /*...*/ }
}

Is it ok to instantiate a shared_ptr with this?

Is it ok to have two shared_ptr objects pointing to the same object? (e.g. A::b_ptr and B::b_ptr)

If one of these two gets out of scope - would B's instance be deleted?

I'm guessing I'm doing something fundamentally wrong.

I also thought about using dependency injection of b_ptr to B's constructor, but that too seems very wrong.

UPDATE:

To clarify - Both A and B need to use C::c_func. In turn, after some processing, C needs to call a callback function in B which I haven't specified above.
Actually two cases are interesting:

If there's a requirement that C won't be stateful - then it needs to receive BPtr both from A and from B as in the code above.

If C is stateful and both A and B instantiate separate C instances, giving a BPtr in C's ctor.

Body:
I would recommend that you re-design to use std::enable_shared_from_this, e.g.

class B
{
   B();
public:
   std::shared_ptr<B> create() { return std::make_shared<B>(); } // Make sure B is allocated as shared_ptr inorder to ensure that shared_from_this() works.
};

However, if it's an API issue you have then you can do the following (although I don't recommend it).

void b_func() { C::c_func(BPtr(this, [](B*){})); } // Empty deleter. Nothing happens when shared_ptr goes out of scope. Note that c_func cannot take ownership of the pointer.


问:
Unable to compile MPI program with OpenMP with OpenMPI
I am trying to compare solvers with one of them being parallelized in OpenMP; Solvers are all running in parallel under OpenMPI using Fixed Form Fortran 77; mpif77 does not let me link the object files with the -fopenmp switch; Make does not create the executable. I tried to compile the OpenMP source files separately with gfortran and then tried to link them with mpif77 - does not work; When I do not use the switch it throws the common error:

```<code>Undefined symbols for architecture x86_64:
  "_GOMP_parallel", referenced from:
      _parmatdiff_ in matdiff.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [solvercomp] Error
</code>```

1

My question is does OpenMPI support OpenMP and if yes, how do I ensure that 'make' links object files created to functions in OpenMP libraries?

Here is a copy of my makefile:

```<code>SOURCES = solvcomp.f matdiff.f seqjacobi.f seqconjgrad.f parsor.f
FCC = mpif77
MPIRUN = mpirun
OBJECTS = $(SOURCES:.f=.o)
TARGET = soln
FFLAGS = -o
CFLAGS = -c
NP = 4

all: $(TARGET) clean

$(TARGET): $(OBJECTS)
        $(FCC) $(FFLAGS) $(TARGET) $(OBJECTS)

$(OBJECTS): $(SOURCES)
        $(FCC) $(CFLAGS) $(SOURCES)

clean:
    rm -rf *.o *.dSYM
</code>```

答:
Your link command is bogus

```<code>mpif77 -o -fopenmp a.out foo.o
</code>```

Try

```<code>LDFLAGS='-fopenmp -o'
</code>```

As far as I am concerned, having -o in your LDFLAGS looks pretty messed up in the first place.

Body:
I am trying to compare solvers with one of them being parallelized in OpenMP; Solvers are all running in parallel under OpenMPI using Fixed Form Fortran 77; mpif77 does not let me link the object files with the -fopenmp switch; Make does not create the executable. I tried to compile the OpenMP source files separately with gfortran and then tried to link them with mpif77 - does not work; When I do not use the switch it throws the common error:

Undefined symbols for architecture x86_64:
  "_GOMP_parallel", referenced from:
      _parmatdiff_ in matdiff.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
make: *** [solvercomp] Error

1

My question is does OpenMPI support OpenMP and if yes, how do I ensure that 'make' links object files created to functions in OpenMP libraries?

Here is a copy of my makefile:

SOURCES = solvcomp.f matdiff.f seqjacobi.f seqconjgrad.f parsor.f
FCC = mpif77
MPIRUN = mpirun
OBJECTS = $(SOURCES:.f=.o)
TARGET = soln
FFLAGS = -o
CFLAGS = -c
NP = 4

all: $(TARGET) clean

$(TARGET): $(OBJECTS)
        $(FCC) $(FFLAGS) $(TARGET) $(OBJECTS)

$(OBJECTS): $(SOURCES)
        $(FCC) $(CFLAGS) $(SOURCES)

clean:
    rm -rf *.o *.dSYM

Body:
Your link command is bogus

mpif77 -o -fopenmp a.out foo.o

Try

LDFLAGS='-fopenmp -o'

As far as I am concerned, having -o in your LDFLAGS looks pretty messed up in the first place.


问:
redirect part of url if query-var exists
I have relaunched a TYPO3 Website and have a problem with the redirects of old links listed by google. I want to redirect this:

```<code>https://www.mydomain.ac/index.php?id=88&itemID=123
</code>```

to

```<code>https://www.mydomain.ac/item/item-detail/?itemID=123
</code>```

The id 88 is fix. It still does not exists in the new site, but maybe can be added later. So I just want to redirect if the id=88 AND an itemID (any number) is in the URL. I tried this:

```<code>RewriteRule ^index\.php\?id=88&itemID= /item/item-detail/?itemID= [L]
</code>```

but this didn't work ... obviously ;-)

Any idea how to solve this?
Thanx in advance!

答:
You need a RewriteCond too.

You can test it here: http://htaccess.mwl.be/

```<code>RewriteCond %{QUERY_STRING} ^id=88&itemID=([0-9]*)$
RewriteRule ^index\.php$ https://www.mydomain.ac/item/item-detail/?itemID=%1 [L]
</code>```

Body:
I have relaunched a TYPO3 Website and have a problem with the redirects of old links listed by google. I want to redirect this:

https://www.mydomain.ac/index.php?id=88&itemID=123

to

https://www.mydomain.ac/item/item-detail/?itemID=123

The id 88 is fix. It still does not exists in the new site, but maybe can be added later. So I just want to redirect if the id=88 AND an itemID (any number) is in the URL. I tried this:

RewriteRule ^index\.php\?id=88&itemID= /item/item-detail/?itemID= [L]

but this didn't work ... obviously ;-)

Any idea how to solve this?
Thanx in advance!

Body:
You need a RewriteCond too.

You can test it here: http://htaccess.mwl.be/

RewriteCond %{QUERY_STRING} ^id=88&itemID=([0-9]*)$
RewriteRule ^index\.php$ https://www.mydomain.ac/item/item-detail/?itemID=%1 [L]