问:
Scrapy Xpath returning null but working fine in Chrome
I am quite new to Scrapy but am designing a web scrape to pull certain information from GoFundMe, specifically in this case the amount of people who have donated to a project. I have written an xpath statement which works fine in Chrome but returns null in Scrapy.

A random example project is https://www.gofundme.com/f/passage/donations, which at present has 22 donations. The below when entered in Chrome inspect gives me  "Donations(22)" which is what I need -

```<code>//h2[@class="heading-5 mb0"]/text()
</code>```

However in my Scrapy spider the following yields null -

```<code>class DonationsSpider(scrapy.Spider):
name = 'get_donations'

start_urls = [
    'https://www.gofundme.com/f/passage/donations'
]

def parse(self, response):
    amount_of_donations = response.xpath('//h2[@class="heading-5 mb0"]/text()').extract_first()

    yield{
        'Donations': amount_of_donations
    }
</code>```

Does anyone know why Scrapy is unable to see this value?

I am doing this in an attempt to find out how many times the rest of the spider needs to loop, as when I hard code this value it works with no problems and yields all of the donations.

答:
Well because there are many requests going on the fulfil the request "https://www.gofundme.com/f/passage/donations". Where

your chrome is smart enough to under stand javascript, using that
  smartness it reads the JavaScript code and fetches all the responses
  from different different endpoints to fulfil your request

there's one request to the endpoint "https://gateway.gofundme.com/web-gateway/v1/feed/passage/counts" which loads the data you're looking for. which your python script can't do and also it's not recommend.

Instead you can call directly to that api and you'll get the data, good news is that endpoint responds JSON data which is very structured, easy to parse.

and I'm sure you're also looking for the data which is coming from this endpoint "https://gateway.gofundme.com/web-gateway/v1/feed/passage/donations?limit=20&offset=0&sort=recent"

for more information you may refer to one of my blog by clicking here

Body:
I am quite new to Scrapy but am designing a web scrape to pull certain information from GoFundMe, specifically in this case the amount of people who have donated to a project. I have written an xpath statement which works fine in Chrome but returns null in Scrapy.

A random example project is https://www.gofundme.com/f/passage/donations, which at present has 22 donations. The below when entered in Chrome inspect gives me  "Donations(22)" which is what I need -

//h2[@class="heading-5 mb0"]/text()

However in my Scrapy spider the following yields null -

class DonationsSpider(scrapy.Spider):
name = 'get_donations'

start_urls = [
    'https://www.gofundme.com/f/passage/donations'
]

def parse(self, response):
    amount_of_donations = response.xpath('//h2[@class="heading-5 mb0"]/text()').extract_first()

    yield{
        'Donations': amount_of_donations
    }

Does anyone know why Scrapy is unable to see this value?

I am doing this in an attempt to find out how many times the rest of the spider needs to loop, as when I hard code this value it works with no problems and yields all of the donations.


来源: stackexchange

问:
Multiple permission types (roles) stored in database as single decimal
I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:

What is the best way to handle multiple permission types?

It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer

I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.

Here is the original answer in the off chance the other question gets deleted:

"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.

```<code>[Flags]
public enum Permission
{
    VIEWUSERS = 1, // 2^0 // 0000 0001
    EDITUSERS = 2, // 2^1 // 0000 0010
    VIEWPRODUCTS = 4, // 2^2 // 0000 0100
    EDITPRODUCTS = 8, // 2^3 // 0000 1000
    VIEWCLIENTS = 16, // 2^4 // 0001 0000
    EDITCLIENTS = 32, // 2^5 // 0010 0000
    DELETECLIENTS = 64, // 2^6 // 0100 0000
}
</code>```

Then, you can combine several permissions using the AND bitwise operator.

For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).

Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."

答:
You use bitwise operations.  The pseudo-code would be something like:

```<code>bool HasPermission(User user, Permission permission) {
    return (user.Permission & permission) != 0;
}

void SetPermission(User user, Permission permission) {
    user.Permission |= permission;
}

void ClearPermission(User user, Permission permission) {
    user.Permission &= ~permission;
}
</code>```

Permission is the enum type defined in your post, though whatever type it is needs to be based on an integer-like type.  The same applies to the User.Permission field.

If those operators (&, |=, and &=) don't make sense to you, then read up on bitwise operations (bitwise AND and bitwise OR).

ContentLicense: CC BY-SA 2.5

Body:
I was going to ask a question here about whether or not my design for some users/roles database tables was acceptable, but after some research I came across this question:

What is the best way to handle multiple permission types?

It sounds like an innovative approach, so instead of a many-to-many relationship users_to_roles table, I have multiple permissions defined as a single decimal (int data type I presume). That means all permissions for a single user are in one row. It probably won't make sense until you read the other question and answer

I can't get my brain around this one. Can someone please explain the conversion process? It sounds "right", but I'm just not getting how I convert the roles to a decimal before it goes in the db, and how it gets converted back when it comes out of the db. I'm using Java, but if you stubbed it out, that would be cool as well.

Here is the original answer in the off chance the other question gets deleted:

"Personally, I sometimes use a flagged enumeration of permissions. This way you can use AND, OR, NOT and XOR bitwise operations on the enumeration's items.

[Flags]
public enum Permission
{
    VIEWUSERS = 1, // 2^0 // 0000 0001
    EDITUSERS = 2, // 2^1 // 0000 0010
    VIEWPRODUCTS = 4, // 2^2 // 0000 0100
    EDITPRODUCTS = 8, // 2^3 // 0000 1000
    VIEWCLIENTS = 16, // 2^4 // 0001 0000
    EDITCLIENTS = 32, // 2^5 // 0010 0000
    DELETECLIENTS = 64, // 2^6 // 0100 0000
}

Then, you can combine several permissions using the AND bitwise operator.

For example, if a user can view & edit users, the binary result of the operation is 0000 0011 which converted to decimal is 3.
You can then store the permission of one user into a single column of your DataBase (in our case it would be 3).

Inside your application, you just need another bitwise operation (OR) to verify if a user has a particular permission or not."

Body:
You use bitwise operations.  The pseudo-code would be something like:

bool HasPermission(User user, Permission permission) {
    return (user.Permission & permission) != 0;
}

void SetPermission(User user, Permission permission) {
    user.Permission |= permission;
}

void ClearPermission(User user, Permission permission) {
    user.Permission &= ~permission;
}

Permission is the enum type defined in your post, though whatever type it is needs to be based on an integer-like type.  The same applies to the User.Permission field.

If those operators (&, |=, and &=) don't make sense to you, then read up on bitwise operations (bitwise AND and bitwise OR).

OwnerDisplayName: Brannon


问:
Can depends_on in terraform be set to a file path?
I am trying to break down my main.tf file . So I have set aws config via terraform, created the configuration recorder and set the delivery channel to a s3 bucket created in the same main.tf file. Now for the AWS config rules, I have created a separate file viz config-rule.tf. As known , every aws_config_config_rule that we create has a depends_on clause where in we call the dependent resource, which in this case being aws_config_configuration_recorder. So my question is can I interpolate the depends_on clause to something like :

```<code>    resource "aws_config_config_rule" "s3_bucket_server_side_encryption_enabled" {
    name = "s3_bucket_server_side_encryption_enabled"

    source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED"
    }

    depends_on = ["${file("aws-config-setup.tf")}"]
    }
</code>```

Considering I move my aws config setup from my main.tf file to a new file called aws-config-setup.tf.

答:
If I'm reading your question correctly, you shouldn't need to make any changes for this to work, assuming you didn't move code to its own module (a separate directory).

When terraform executes in a particular directory it takes all files into account, basically treating them all as one terraform file.

So, in general, if you had a main.tf that looks like the following

```<code>resource "some_resource" "resource_1" {
  # ...
}

resource "some_resource" "resource_2" {
  # ...

  depends_on = [some_resource.resource_1]
}
</code>```

and you decided to split these out into the following files

file1.tf

```<code>resource "some_resource" "resource_1" {
  # ...
}
</code>```

file2.tf

```<code>resource "some_resource" "resource_2" {
  # ...

  depends_on = [some_resource.resource_1]
}
</code>```

if terraform is run in the same directory, it will evaluate the main.tf scenario exactly the same as the multi-file scenario.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to break down my main.tf file . So I have set aws config via terraform, created the configuration recorder and set the delivery channel to a s3 bucket created in the same main.tf file. Now for the AWS config rules, I have created a separate file viz config-rule.tf. As known , every aws_config_config_rule that we create has a depends_on clause where in we call the dependent resource, which in this case being aws_config_configuration_recorder. So my question is can I interpolate the depends_on clause to something like :

    resource "aws_config_config_rule" "s3_bucket_server_side_encryption_enabled" {
    name = "s3_bucket_server_side_encryption_enabled"

    source {
    owner             = "AWS"
    source_identifier = "S3_BUCKET_SERVER_SIDE_ENCRYPTION_ENABLED"
    }

    depends_on = ["${file("aws-config-setup.tf")}"]
    }

Considering I move my aws config setup from my main.tf file to a new file called aws-config-setup.tf.

Body:
If I'm reading your question correctly, you shouldn't need to make any changes for this to work, assuming you didn't move code to its own module (a separate directory).

When terraform executes in a particular directory it takes all files into account, basically treating them all as one terraform file.

So, in general, if you had a main.tf that looks like the following

resource "some_resource" "resource_1" {
  # ...
}

resource "some_resource" "resource_2" {
  # ...

  depends_on = [some_resource.resource_1]
}

and you decided to split these out into the following files

file1.tf

resource "some_resource" "resource_1" {
  # ...
}

file2.tf

resource "some_resource" "resource_2" {
  # ...

  depends_on = [some_resource.resource_1]
}

if terraform is run in the same directory, it will evaluate the main.tf scenario exactly the same as the multi-file scenario.


问:
Setting a value to a cell in a pandas dataframe
I have the following pandas dataframe:

```<code>K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})
</code>```

Then I set the cell in the first row and first column to 11:

```<code>K.iloc[0]["A"] = 11
</code>```

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

```<code>K["C"] = 0
K.iloc[0]["C"] = 11
</code>```

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

答:
When you use K.iloc[0]["C"], you first take the first line, so you have a copy of a slice from your dataframe,  then you take the column C. So you change the copy from the slice, not the original dataframe.

That your first call, K.iloc[0]["A"] = 11 worked fine was in some sens a luck.

The good habit is to use loc in "one shot", so you have access to the original value of the dataframe, not on a slice copy :

```<code>K.loc[0,"C"] = 11
</code>```

Be careful that iloc and loc are different function, even if they seems quite similar here.

Body:
I have the following pandas dataframe:

K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})

Then I set the cell in the first row and first column to 11:

K.iloc[0]["A"] = 11

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

K["C"] = 0
K.iloc[0]["C"] = 11

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

Body:
When you use K.iloc[0]["C"], you first take the first line, so you have a copy of a slice from your dataframe,  then you take the column C. So you change the copy from the slice, not the original dataframe.

That your first call, K.iloc[0]["A"] = 11 worked fine was in some sens a luck.

The good habit is to use loc in "one shot", so you have access to the original value of the dataframe, not on a slice copy :

K.loc[0,"C"] = 11

Be careful that iloc and loc are different function, even if they seems quite similar here.


问:
Find a value of an element in vector in a std::map < int , std::vector <int >>
Is there a prettier way to get a value from inside a vector in a map without using loops?
For example , How to get the key of the vector which has an element of value 50?

```<code>std::map < int , std::vector < int >> myMap;
std::vector < int > a= {10,20,30};
std::vector < int > b= {50,60,70};
myMap.insert({1000,a});
myMap.insert({2000,b});
</code>```

Can I get the key(s) if the value is in more than one vector ?
For Example if 50 Is in both vectors ?

```<code>std::vector < int > a= {10,20,50};
std::vector < int > b= {50,60,70};
</code>```

答:
If you need to be efficient to find the key from the value, and conversely, you could use two maps. If needed, you can encapsulate that into a single class. You are then paying for efficiency of search with space.
Something along the lines of:

```<code>class DoubleMap {
public:
   DoubleMap() {}

   void insert(int key, std::vector<int> value) {
        myMap1.insert({key, value});
        myMap2.insert({value, key});
   }

   std::vector<int> getValue (int key) {return myMap1[key];}
   int getKey(std::vector<int> value) {return myMap2[value];}

private :
std::map <int, std::vector<int>> myMap1;
std::map<std::vector<int>, int> myMap2;
}
</code>```

I wouldn't advise this kind of heavy class unless you really need the efficiency of search in both directions, though.

Body:
Is there a prettier way to get a value from inside a vector in a map without using loops?
For example , How to get the key of the vector which has an element of value 50?

std::map < int , std::vector < int >> myMap;
std::vector < int > a= {10,20,30};
std::vector < int > b= {50,60,70};
myMap.insert({1000,a});
myMap.insert({2000,b});

Can I get the key(s) if the value is in more than one vector ?
For Example if 50 Is in both vectors ?

std::vector < int > a= {10,20,50};
std::vector < int > b= {50,60,70};

Body:
If you need to be efficient to find the key from the value, and conversely, you could use two maps. If needed, you can encapsulate that into a single class. You are then paying for efficiency of search with space.
Something along the lines of:

class DoubleMap {
public:
   DoubleMap() {}

   void insert(int key, std::vector<int> value) {
        myMap1.insert({key, value});
        myMap2.insert({value, key});
   }

   std::vector<int> getValue (int key) {return myMap1[key];}
   int getKey(std::vector<int> value) {return myMap2[value];}

private :
std::map <int, std::vector<int>> myMap1;
std::map<std::vector<int>, int> myMap2;
}

I wouldn't advise this kind of heavy class unless you really need the efficiency of search in both directions, though.


问:
Trying to reorganize this PHP array so it's values are toghether by id and easily accesible later
First of all, I couldn't think of any better title, sorry if you find it inapropiate.

I have this function which task is to bring data from 2 databases, modify some of that data, and upload everything to an external API.

The first database accounting has

subscriber_id | amount | zone_id

stored in the table named cdr

The second db billing has stored inside the table billing_zones these values:

zone_id | zone_name

Everything I've done works fine, but the resulting array is not what I expected/wanted.

This is my code:

try {
    $conn = new PDO('mysql:host=host;dbname=accounting','user','password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();
}

$destinationId = 0;
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_external_subscriber_id`, SUM(b.`source_customer_cost`) AS total
    FROM `billing`.billing_zones a INNER JOIN cdr b
    ON a.`id` = b.`source_customer_billing_zone_id`
    WHERE destination_account_id = :destinationId
    GROUP BY b.`source_external_subscriber_id`, a.`zone`');
$stmt->execute(array('destinationId' => $destinationId));

foreach ($stmt as $row) {
    $data[] = $row;
}

for ($i=0; $i < sizeof($data); $i++) {
    $sanitizedData[$i] = array(
        0 => $data[$i][0],
        1 => $data[$i][1],
        2 => $data[$i][2]
    );
}

/*ATTEMPT TO MAKE THE ARRAY I WANTED - DIDN'T WORK*/
for ($i=0; $i < sizeof($data); $i++) {
    while ($sanitizedData[$i] == $sanitizedData[$i-1][1]) {
        $newArray[] = array_merge($sanitizedData[$i], $sanitizedData[$i-1]);
    }
}

var_dump($sanitizedData);
```

<p>The result of the code above my <code>ATTEMPT</code> comment is a big array, I will show you a piece of it so you can understand better what I want to do:</p>

<pre class="lang-php prettyprint-override"><code>[1047]=>
  array(3) {
    [0]=>
    string(27) "Llamadas Moviles nacionales"
    [1]=>
    string(9) "V30048086"
    [2]=>
    string(10) "460.440000"
  }
  [1048]=>
  array(3) {
    [0]=>
    string(28) "Llamadas Premium 902 Nivel 1"
    [1]=>
    string(9) "V30048086"
    [2]=>
    string(9) "87.301236"
  }
  [1049]=>
  array(3) {
    [0]=>
    string(25) "Llamadas Fijos nacionales"
    [1]=>
    string(9) "W24154073"
    [2]=>
    string(9) "64.340367"
  }
  [1050]=>
  array(3) {
    [0]=>
    string(27) "Llamadas Moviles nacionales"
    [1]=>
    string(9) "W24154073"
    [2]=>
    string(10) "116.480000"
  }
  [1051]=>
  array(3) {
    [0]=>
    string(28) "Llamadas Premium 901 Nivel 1"
    [1]=>
    string(9) "W24154073"
    [2]=>
    string(9) "62.559759"
  }
</code>```

To clarify:

array[n][0] is the aforementioned zone_name

array[n][1] is the subscriber_id - The id defining the customer

array[n][2] is the SUM() of the amount for that id in that zone.

So the result is that for every id, there are several arrays for each zone.

What I want to do is to group those in a unique array like:

[1051]=>
  array(3) {
    [0]=>
    string(9) "W24154073"
    [1]=>
    string(28) "Llamadas Premium 901 Nivel 1"
    [2]=>
    string(9) "62.559759"
    [3]=>
    string(28) "Llamadas Moviles nacionales"
    [4]=>
    string(9) "116.480000"
    [5]=>
    string(28) "Llamadas Fijos nacionales"
    [6]=>
    string(9) "64.340367"
    .
    .
    .
    If there were more
  }
```

<p>As @Misorude pointed out in the comments, maybe using the subscriber_id as key for the main array would be a better solution:</p>

<pre class="lang-php prettyprint-override"><code>["W24154073"]=>
  array(3) {
    [0]=>
    string(28) "Llamadas Premium 901 Nivel 1"
    [1]=>
    string(9) "62.559759"
    [2]=>
    string(28) "Llamadas Moviles nacionales"
    [3]=>
    string(9) "116.480000"
    [4]=>
    string(28) "Llamadas Fijos nacionales"
    [5]=>
    string(9) "64.340367"
    .
    .
    .
    If there were more
  }
</code>```

This way, I could later access the array and fetch the info customer by customer, not having in mind how many zones they are in.

I don't know if this is all necessary or if I don't even need any of this to begin with, but I could not think about any way to do it. Maybe I have overthinked this a lot.

If you know how to turn the array I get into the array I want it would be great, but if there is another solution to pass the data easier than this, then please, bring me the light I need.

Thank you for the help, have a great weekend!

答:
After a bit of discussion and clarifying the requirement, this boiled down to inserting two data fields from each record into an array, grouped under an ID value from a third field.

This can be a achieved in quite a simple fashion, like this:

```<code>$data = [];
foreach ($stmt as $row) {
    // $row[1] is the subscriber_id
    $data[$row[1]][] = $row[0]; // $row[0] is zone_name
    $data[$row[1]][] = $row[2]; // $row[2] is the sum amount
}
var_dump($data);
</code>```

The “trick” here is to let PHP take care of the grouping, basically, by providing the grouping id as array key on the first level, $data[$row[1]], and then simply appending new items under that on the second level, using [] = … syntax.

Body:
First of all, I couldn't think of any better title, sorry if you find it inapropiate.

I have this function which task is to bring data from 2 databases, modify some of that data, and upload everything to an external API.

The first database accounting has

subscriber_id | amount | zone_id

stored in the table named cdr

The second db billing has stored inside the table billing_zones these values:

zone_id | zone_name

Everything I've done works fine, but the resulting array is not what I expected/wanted.

This is my code:

try {
    $conn = new PDO('mysql:host=host;dbname=accounting','user','password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
    echo "ERROR: " . $e->getMessage();
}

$destinationId = 0;
$stmt = $conn->prepare('SELECT a.`zone`, b.`source_external_subscriber_id`, SUM(b.`source_customer_cost`) AS total
    FROM `billing`.billing_zones a INNER JOIN cdr b
    ON a.`id` = b.`source_customer_billing_zone_id`
    WHERE destination_account_id = :destinationId
    GROUP BY b.`source_external_subscriber_id`, a.`zone`');
$stmt->execute(array('destinationId' => $destinationId));

foreach ($stmt as $row) {
    $data[] = $row;
}

for ($i=0; $i < sizeof($data); $i++) {
    $sanitizedData[$i] = array(
        0 => $data[$i][0],
        1 => $data[$i][1],
        2 => $data[$i][2]
    );
}

/*ATTEMPT TO MAKE THE ARRAY I WANTED - DIDN'T WORK*/
for ($i=0; $i < sizeof($data); $i++) {
    while ($sanitizedData[$i] == $sanitizedData[$i-1][1]) {
        $newArray[] = array_merge($sanitizedData[$i], $sanitizedData[$i-1]);
    }
}

var_dump($sanitizedData);

The result of the code above my ATTEMPT comment is a big array, I will show you a piece of it so you can understand better what I want to do:

[1047]=>
  array(3) {
    [0]=>
    string(27) "Llamadas Moviles nacionales"
    [1]=>
    string(9) "V30048086"
    [2]=>
    string(10) "460.440000"
  }
  [1048]=>
  array(3) {
    [0]=>
    string(28) "Llamadas Premium 902 Nivel 1"
    [1]=>
    string(9) "V30048086"
    [2]=>
    string(9) "87.301236"
  }
  [1049]=>
  array(3) {
    [0]=>
    string(25) "Llamadas Fijos nacionales"
    [1]=>
    string(9) "W24154073"
    [2]=>
    string(9) "64.340367"
  }
  [1050]=>
  array(3) {
    [0]=>
    string(27) "Llamadas Moviles nacionales"
    [1]=>
    string(9) "W24154073"
    [2]=>
    string(10) "116.480000"
  }
  [1051]=>
  array(3) {
    [0]=>
    string(28) "Llamadas Premium 901 Nivel 1"
    [1]=>
    string(9) "W24154073"
    [2]=>
    string(9) "62.559759"
  }

To clarify:

array[n][0] is the aforementioned zone_name

array[n][1] is the subscriber_id - The id defining the customer

array[n][2] is the SUM() of the amount for that id in that zone.

So the result is that for every id, there are several arrays for each zone.

What I want to do is to group those in a unique array like:

[1051]=>
  array(3) {
    [0]=>
    string(9) "W24154073"
    [1]=>
    string(28) "Llamadas Premium 901 Nivel 1"
    [2]=>
    string(9) "62.559759"
    [3]=>
    string(28) "Llamadas Moviles nacionales"
    [4]=>
    string(9) "116.480000"
    [5]=>
    string(28) "Llamadas Fijos nacionales"
    [6]=>
    string(9) "64.340367"
    .
    .
    .
    If there were more
  }

As @Misorude pointed out in the comments, maybe using the subscriber_id as key for the main array would be a better solution:

["W24154073"]=>
  array(3) {
    [0]=>
    string(28) "Llamadas Premium 901 Nivel 1"
    [1]=>
    string(9) "62.559759"
    [2]=>
    string(28) "Llamadas Moviles nacionales"
    [3]=>
    string(9) "116.480000"
    [4]=>
    string(28) "Llamadas Fijos nacionales"
    [5]=>
    string(9) "64.340367"
    .
    .
    .
    If there were more
  }

This way, I could later access the array and fetch the info customer by customer, not having in mind how many zones they are in.

I don't know if this is all necessary or if I don't even need any of this to begin with, but I could not think about any way to do it. Maybe I have overthinked this a lot.

If you know how to turn the array I get into the array I want it would be great, but if there is another solution to pass the data easier than this, then please, bring me the light I need.

Thank you for the help, have a great weekend!

Body:
After a bit of discussion and clarifying the requirement, this boiled down to inserting two data fields from each record into an array, grouped under an ID value from a third field.

This can be a achieved in quite a simple fashion, like this:

$data = [];
foreach ($stmt as $row) {
    // $row[1] is the subscriber_id
    $data[$row[1]][] = $row[0]; // $row[0] is zone_name
    $data[$row[1]][] = $row[2]; // $row[2] is the sum amount
}
var_dump($data);

The “trick” here is to let PHP take care of the grouping, basically, by providing the grouping id as array key on the first level, $data[$row[1]], and then simply appending new items under that on the second level, using [] = … syntax.


问:
What is the difference between JAIN SIP and MJSIP?
I've been investigating various API options for making use of the SIP (Session Initiation Protocol) in Java.

So far I've narrowed it down to JAIN SIP and MJSIP but I can't figure out the difference between the two.

Can someone please explain why and when to choose one over the other?

Thanks in advance.

答: MJSIP's licence is a GNU style license, which you may or may not have to be careful about.</p>

ContentLicense: CC BY-SA 3.0


问:
SQL Select data from two tables, one row -> multiple rows
I have the following two tables:

```<code>customers:  |  phones:
--------------------------------------
id          |  id
name        |  owner (FK_CUSTOMERS)
address     |  number
</code>```

I load a html table in laravel blade to show all the customers and I want a table cell with the phones saved for each customer.

So one customer may have no phones, just one or multiple phones. I need to retrieve each customer with their phones in one row, or there is a better way to do this?

If I do something like this results one row per phone with duplicate data:

```<code> $customers = DB::table('customers')
        ->join("phones","customers.id", "=", "phones.owner")
        ->where("phones.group",1)
        ->select(
            'customers.id',
            'customers.name',
            'customers.fiscalNumber',
            'customers.disscount',
            'customers.billAddress',
            'customers.tax',
            'phones.number'
        )
        ->get();
</code>```

I want this:

```<code>id | name    | address          | phones
5  | Michael | fake address 123 | 666777888,111222333,444555666
</code>```

I have tried several things but nothings works. Thanks

答:
You should group your customers by id, and use group_concat to extract all phone numbers as a comma separated string. It should look something like this:</p>

```<code>$customers = DB::table('customers')
    ->join("phones","customers.id", "=", "phones.owner")
    ->where("phones.group",1)
    ->select(
        'customers.id',
        'customers.name',
        'customers.fiscalNumber',
        'customers.disscount',
        'customers.billAddress',
        'customers.tax',
        DB::raw('group_concat(phones.number) as number')
    )
    ->groupBy('customers.id')
    ->get();
</code>```

Body:
I have the following two tables:

customers:  |  phones:
--------------------------------------
id          |  id
name        |  owner (FK_CUSTOMERS)
address     |  number

I load a html table in laravel blade to show all the customers and I want a table cell with the phones saved for each customer.

So one customer may have no phones, just one or multiple phones. I need to retrieve each customer with their phones in one row, or there is a better way to do this?

If I do something like this results one row per phone with duplicate data:

 $customers = DB::table('customers')
        ->join("phones","customers.id", "=", "phones.owner")
        ->where("phones.group",1)
        ->select(
            'customers.id',
            'customers.name',
            'customers.fiscalNumber',
            'customers.disscount',
            'customers.billAddress',
            'customers.tax',
            'phones.number'
        )
        ->get();

I want this:

id | name    | address          | phones
5  | Michael | fake address 123 | 666777888,111222333,444555666

I have tried several things but nothings works. Thanks

Body:
You should group your customers by id, and use group_concat to extract all phone numbers as a comma separated string. It should look something like this:

$customers = DB::table('customers')
    ->join("phones","customers.id", "=", "phones.owner")
    ->where("phones.group",1)
    ->select(
        'customers.id',
        'customers.name',
        'customers.fiscalNumber',
        'customers.disscount',
        'customers.billAddress',
        'customers.tax',
        DB::raw('group_concat(phones.number) as number')
    )
    ->groupBy('customers.id')
    ->get();


问:
How to check if a framework is Bitcode supported for Xcode7
From Xcode 7 it became one of the common problem that third party frameworks should support Bitcode. We can also disable the BITCODE by setting ENABLE_BITCODE to NO in Build settings. But i do not want to turn it off, instead i want to convert all my frameworks to BITCODE compatible.

So how to check if a framework is BITCODE compatible apart from compiling the framework in Xcode. Sometimes Xcode give error for BITCODE compatibility for one framework leaving the others even though they don't have BITCODE support.

Is there any tool/command line check?

答:
Set the flag in the Targets:

Bitcode enabled

```<code>otool -arch arm64 -l myFramework | grep __LLVM
  segname __LLVM
   segname __LLVM
</code>```

I ( wrongly ) expected to read the same output against a local iOS app build.  That was not the case. The same command produced nothing, despite have ENABLE_BITCODE YES.  Only when you selected Archive did the bitcode process start.

This answer helped me:

What's the difference between `-fembed-bitcode` and BITCODE_GENERATION_MODE?

Body:
Set the flag in the Targets:

Bitcode enabled

otool -arch arm64 -l myFramework | grep __LLVM
  segname __LLVM
   segname __LLVM

I ( wrongly ) expected to read the same output against a local iOS app build.  That was not the case. The same command produced nothing, despite have ENABLE_BITCODE YES.  Only when you selected Archive did the bitcode process start.

This answer helped me:

What's the difference between `-fembed-bitcode` and BITCODE_GENERATION_MODE?


问:
How to find and collect Objects to Map by its parameter?
Given enum:

```<code>enum Type {
  PRIMARY,
  SECONDARY
}
</code>```

and two different Sets of Objects with same parameter (type):

```<code>class OldObject {
  Long id;
  Type type;
}

class NewObject {
  Long id;
  String title;
  Type type;
}
</code>```

...which looks like:

```<code>Set<OldObject> ...
Set<NewObject> ...
</code>```

Beeing confused about Stream API with Collectors and Groupings I am not able to finish with a Map[OldObject, NewObject] with pairs grouped by Type. I am able to guarantee that both sets ale full and I am able to find pairs. I thought that I can start with stream of enum (but do not know if it is a good aproach):

```<code>Map<OldObject, NewObject> pairs = Optional.of(Schema.values())...
</code>```

答:
If you're really going for Streams, the simplest approach would be to go for something like

```<code>Map<Type, OldObject> oldObjectMap = oldObjectSet.stream().collect(Collectors.toMap(OldObject::getType, Function.identity()))
Map<Type, NewObject> newObjectMap = newObjectSet.stream().collect(Collectors.toMap(NewObject::getType, Function.identity()))

Map<OldObject, NewObject> pairs = Arrays
    .stream(Type.values())
    .collect(Collectors.toMap(oldObjectMap::get, newObjectMap::get))
</code>```

Note that this approach will likely run into errors if some enum is not present in one of the sets because the map collector doesn't support null values.
You can prevent that by adding a filter call just before this happens:

```<code>Map<OldObject, NewObject> pairs = Arrays
    .stream(Type.values())
    .filter(oldObjectSet::contains)
    .filter(newObjectSet::contains)
    .collect(Collectors.toMap(oldObjectMap::get, newObjectMap::get))
</code>```

Body:
Given enum:

enum Type {
  PRIMARY,
  SECONDARY
}

and two different Sets of Objects with same parameter (type):

class OldObject {
  Long id;
  Type type;
}

class NewObject {
  Long id;
  String title;
  Type type;
}

...which looks like:

Set<OldObject> ...
Set<NewObject> ...

Beeing confused about Stream API with Collectors and Groupings I am not able to finish with a Map[OldObject, NewObject] with pairs grouped by Type. I am able to guarantee that both sets ale full and I am able to find pairs. I thought that I can start with stream of enum (but do not know if it is a good aproach):

Map<OldObject, NewObject> pairs = Optional.of(Schema.values())...

Body:
If you're really going for Streams, the simplest approach would be to go for something like

Map<Type, OldObject> oldObjectMap = oldObjectSet.stream().collect(Collectors.toMap(OldObject::getType, Function.identity()))
Map<Type, NewObject> newObjectMap = newObjectSet.stream().collect(Collectors.toMap(NewObject::getType, Function.identity()))

Map<OldObject, NewObject> pairs = Arrays
    .stream(Type.values())
    .collect(Collectors.toMap(oldObjectMap::get, newObjectMap::get))

Note that this approach will likely run into errors if some enum is not present in one of the sets because the map collector doesn't support null values.
You can prevent that by adding a filter call just before this happens:

Map<OldObject, NewObject> pairs = Arrays
    .stream(Type.values())
    .filter(oldObjectSet::contains)
    .filter(newObjectSet::contains)
    .collect(Collectors.toMap(oldObjectMap::get, newObjectMap::get))


问:
Using Flurl in web service to handle calls to an outside service
I wanted to put a situation to you to get your thoughts on the use of Flurl; if I have developed a restful api which is designed to support authentication and sessions from multiple users and you part of the operation of the restful service is that it needs to make authenticated calls to another outside service. If I used the standard flurl implementation of call asyn from a string URL and if I need to set different headers depending on the user that authenticated to my service, would this cause unpredictable behaviour due to it using a single httpclient (as they are all calling the same host).</p>

答:
Doing it the way you describe is completely safe. Setting headers fluently off a URL string or Url object will apply them to the request, not the client. Example:

```<code>await url.WithHeader(name, value).PostAsync(body);
</code>```

This call can be made a zillion times from different threads with different header values and a single shared HttpClient instance with no conflicts. This works because under the hood it sets the header on the HttpRequestMessage, not the default headers on the HttpClient.

Body:
Doing it the way you describe is completely safe. Setting headers fluently off a URL string or Url object will apply them to the request, not the client. Example:

await url.WithHeader(name, value).PostAsync(body);

This call can be made a zillion times from different threads with different header values and a single shared HttpClient instance with no conflicts. This works because under the hood it sets the header on the HttpRequestMessage, not the default headers on the HttpClient.


问:
Need some help with regular expressions (php)
For example, I have the following code :

```<code>$string  = "adf  gggg  eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.
</code>```

I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value, no luck so far though.

Thanks for any help.

答:
```<code>.*?value.*?\((\d+)\).*
</code>```

Being *? a reluctant match.

Body:
For example, I have the following code :

$string  = "adf  gggg  eere value aaaa bbb (10) value
ddttt ggg www (20) value ddttt ggg www dddd (40) ";
preg_match("/(value).*(\(\d+\))/is", $string, $result);
var_dump($result[2]); // outputs 40.

I'm trying to get the first value (10). The code above outputs 40 which makes sense, but not what I want. The string pattern is : word "value", then a number of any characters, then "(", integer, ")". It seems that I'm missing something obvious... I haven't worked too much with regular expressions, but I believe it can be solved somehow with ?<!value, no luck so far though.

Thanks for any help.

Body:
.*?value.*?\((\d+)\).*

Being *? a reluctant match.


问:
Why can't local variable be used in GNU C basic inline asm statements?
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

```<code>int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}
</code>```

example of extended:

```<code>int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}
</code>```

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

答:
There is little distinction between "Basic asm" and "Extended asm"; "basic asm" is just a special case where the __asm__ statement has no lists of outputs, inputs, or clobbers.  The compiler does not do % substitution in the assembly string for Basic asm.  If you want inputs or outputs you have to specify them, and then it's what people call "extended asm".

In practice, it may be possible to access external (or even file-scope static) objects from "basic asm". This is because these objects will (respectively may) have symbol names at the assembly level. However, to perform such access you need to be careful of whether it is position-independent (if your code will be linked into libraries or PIE executables) and meets other ABI constraints that might be imposed at linking time, and there are various considerations for compatibility with link-time optimization and other transformations the compiler may perform. In short, it's a bad idea because you can't tell the compiler that a basic asm statement modified memory.  There's no way to make it safe.

A "memory" clobber (Extended asm) can make it safe to access static-storage variables by name from the asm template.

The use-case for basic asm is things that modify the machine state only, like asm("cli") in a kernel to disable interrupts, without reading or writing any C variables.  (Even then, you'd often use a "memory" clobber to make sure the compiler had finished earlier memory operations before changing machine state.)

Local (automatic storage, not static ones) variables fundamentally never have symbol names, because they don't exist in a single instance; there's one object per live instance of the block they're declared in, at runtime. As such, the only possible way to access them is via input/output constraints.

Users coming from MSVC-land may find this surprising since MSVC's inline assembly scheme papers over the issue by transforming local variable references in their version of inline asm into stack-pointer-relative accesses, among other things. The version of inline asm it offers however is not compatible with an optimizing compiler, and little to no optimization can happen in functions using that type of inline asm. GCC and the larger compiler world that grew alongside C out of unix does not do anything similar.

Body:
Why cannot I use local variables from main to be used in basic asm inline? It is only allowed in extended asm, but why so?

(I know local variables are on the stack after return address (and therefore cannot be used once the function return), but that should not be the reason to not use them)

And example of basic asm:

int a = 10; //global a
int b = 20; //global b
int result;

int main() {
    asm ( "pusha\n\t"
          "movl a, %eax\n\t"
          "movl b, %ebx\n\t"
          "imull %ebx, %eax\n\t"
          "movl %eax, result\n\t"
          "popa");

    printf("the answer is %d\n", result);
    return 0;
}

example of extended:

int main (void) {
    int data1 = 10;  //local var - could be used in extended
    int data2 = 20;
    int result;

    asm ( "imull %%edx, %%ecx\n\t"
          "movl %%ecx, %%eax"
          : "=a"(result)
          : "d"(data1), "c"(data2));

    printf("The result is %d\n",result);
    return 0;
}

Compiled with:
gcc -m32 somefile.c

platform:
uname -a:
Linux 5.0.0-32-generic #34-Ubuntu SMP Wed Oct 2 02:06:48 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux


问:
ML .Net Can’t retrain the neural network
I am trying to retrain the model based on new data.
The neural network learning algorithm allows retraining according to the documentation.

```<code>//формируем данные для обучения из коллекции
var trainingDataView =
mlContext.Data.LoadFromEnumerable(trainDataFromDb.TrainData);

//формируем данные в формате для обучения
var trainingPipeline = mlContext.Transforms.Conversion.MapValueToKey(inputColumnName: "IdCategory", outputColumnName: "Label")
    .Append(mlContext.Transforms.Text.FeaturizeText(inputColumnName: "DescriptionProduct", outputColumnName: "DescriptionProductFeaturized"))
    .Append(mlContext.Transforms.Concatenate("Features", "DescriptionProductFeaturized"))
    .Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy())
    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));

//обучаем нейросеть
ITransformer trainedModel = trainingPipeline.Fit(trainingDataView);

//используем FileStream
using (var fileStream = new FileStream(FullPathModelNeural, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    //сохраняем обученную модель нейронной сети
    mlContext.Model.Save(trainedModel, trainingDataView.Schema, fileStream);
}
</code>```

The neural network copes with the tasks assigned to it.

But as soon as I want to retrain it, I use the following code:

```<code>//загружаем обученную модель
var trainedModelFromFile = mlContext.Model.Load(FullPathModelNeural, out var modelSchema);

//извлекаем параметры обученной модели
var originalModelParameters = ((ISingleFeaturePredictionTransformer<object>)trainedModelFromFile).Model as MaximumEntropyModelParameters;

//формируем данные для обучения из коллекции
var trainingDataView = mlContext.Data.LoadFromEnumerable(trainDataFromDb.TrainData);

//дообучаем модель с учетом новых данных
var retrainedModel = mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy().Fit(trainingDataView, originalModelParameters);

//используем FileStream
using (var fileStream = new FileStream(FullPathModelNeural, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    //сохраняем обученную модель нейронной сети
    mlContext.Model.Save(retrainedModel, modelSchema, fileStream);
}
</code>```

I get an exception. Failed to cast object type Microsoft.ML.Data.TransformerChain [Microsoft.ML.ITransformer] to type Microsoft.ML.ISingleFeaturePredictionTransformer [System.Object]
In this line of code

```<code>var originalModelParameters = ((ISingleFeaturePredictionTransformer<object>)trainedModelFromFile).Model as MaximumEntropyModelParameters;
</code>```

Please, help me understand how to retrain the neural network correctly

答:
The problem is probably in how you saved your model, i.e. you saved more than just the Estimator.

A similar example that may help:

```<code>IDataView inputDataView = mlContext.Data.LoadFromTextFile<ModelInput>("initialdata.csv");

// Prepare input data to a form consumable by a machine learning model
var inputDataPreparer = mlContext.Transforms.Text.FeaturizeText("Features", nameof(ModelInput.Comment)).Fit(inputDataView);

// Create a training algorithm
var trainer = mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression();

var transformedData = inputDataPreparer.Transform(inputDataSplit.TrainSet);
var trainedModel = trainer.Fit(transformedData);

//Save the model
mlContext.Model.Save(trainedModel, inputDataView.Schema, "modelfile.zip");

//Save the input data preparing pipeline");
mlContext.Model.Save(inputDataPreparer, inputDataView.Schema, "preparePipeline.zip");

// -- Later retraining step --

// Load data preparation pipeline
ITransformer dataPrepPipeline = mlContext.Model.Load("preparePipeline.zip", out _);

// Load trained model
ITransformer originalModel = mlContext.Model.Load("modelfile.zip", out _);

// Extract trained model parameters
var originalModelParameters = ((ISingleFeaturePredictionTransformer<CalibratedModelParametersBase<LinearBinaryModelParameters, PlattCalibrator>>)originalModel).Model.SubModel;

IDataView retrainingDataView = mlContext.Data.LoadFromTextFile<ModelInput>("MOREDATA.CSV");

var newData = dataPrepPipeline.Transform(retrainingDataView);
IDataView transformedNewData = dataPrepPipeline.Transform(newData);

// Retrain model
var retrainedModel = mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression().Fit(transformedNewData, originalModelParameters);

//Save complete pipeline for usage
var completeRetrainedPipeline = dataPrepPipeline.Append(retrainedModel);
mlContext.Model.Save(completeRetrainedPipeline, transformedNewData.Schema, "retrainedModel.zip);
</code>```

Body:
I am trying to retrain the model based on new data.
The neural network learning algorithm allows retraining according to the documentation.

//формируем данные для обучения из коллекции
var trainingDataView =
mlContext.Data.LoadFromEnumerable(trainDataFromDb.TrainData);

//формируем данные в формате для обучения
var trainingPipeline = mlContext.Transforms.Conversion.MapValueToKey(inputColumnName: "IdCategory", outputColumnName: "Label")
    .Append(mlContext.Transforms.Text.FeaturizeText(inputColumnName: "DescriptionProduct", outputColumnName: "DescriptionProductFeaturized"))
    .Append(mlContext.Transforms.Concatenate("Features", "DescriptionProductFeaturized"))
    .Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy())
    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));

//обучаем нейросеть
ITransformer trainedModel = trainingPipeline.Fit(trainingDataView);

//используем FileStream
using (var fileStream = new FileStream(FullPathModelNeural, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    //сохраняем обученную модель нейронной сети
    mlContext.Model.Save(trainedModel, trainingDataView.Schema, fileStream);
}

The neural network copes with the tasks assigned to it.

But as soon as I want to retrain it, I use the following code:

//загружаем обученную модель
var trainedModelFromFile = mlContext.Model.Load(FullPathModelNeural, out var modelSchema);

//извлекаем параметры обученной модели
var originalModelParameters = ((ISingleFeaturePredictionTransformer<object>)trainedModelFromFile).Model as MaximumEntropyModelParameters;

//формируем данные для обучения из коллекции
var trainingDataView = mlContext.Data.LoadFromEnumerable(trainDataFromDb.TrainData);

//дообучаем модель с учетом новых данных
var retrainedModel = mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy().Fit(trainingDataView, originalModelParameters);

//используем FileStream
using (var fileStream = new FileStream(FullPathModelNeural, FileMode.Create, FileAccess.Write, FileShare.Write))
{
    //сохраняем обученную модель нейронной сети
    mlContext.Model.Save(retrainedModel, modelSchema, fileStream);
}

I get an exception. Failed to cast object type Microsoft.ML.Data.TransformerChain [Microsoft.ML.ITransformer] to type Microsoft.ML.ISingleFeaturePredictionTransformer [System.Object]
In this line of code

var originalModelParameters = ((ISingleFeaturePredictionTransformer<object>)trainedModelFromFile).Model as MaximumEntropyModelParameters;

Please, help me understand how to retrain the neural network correctly

Body:
The problem is probably in how you saved your model, i.e. you saved more than just the Estimator.

A similar example that may help:

IDataView inputDataView = mlContext.Data.LoadFromTextFile<ModelInput>("initialdata.csv");

// Prepare input data to a form consumable by a machine learning model
var inputDataPreparer = mlContext.Transforms.Text.FeaturizeText("Features", nameof(ModelInput.Comment)).Fit(inputDataView);

// Create a training algorithm
var trainer = mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression();

var transformedData = inputDataPreparer.Transform(inputDataSplit.TrainSet);
var trainedModel = trainer.Fit(transformedData);

//Save the model
mlContext.Model.Save(trainedModel, inputDataView.Schema, "modelfile.zip");

//Save the input data preparing pipeline");
mlContext.Model.Save(inputDataPreparer, inputDataView.Schema, "preparePipeline.zip");

// -- Later retraining step --

// Load data preparation pipeline
ITransformer dataPrepPipeline = mlContext.Model.Load("preparePipeline.zip", out _);

// Load trained model
ITransformer originalModel = mlContext.Model.Load("modelfile.zip", out _);

// Extract trained model parameters
var originalModelParameters = ((ISingleFeaturePredictionTransformer<CalibratedModelParametersBase<LinearBinaryModelParameters, PlattCalibrator>>)originalModel).Model.SubModel;

IDataView retrainingDataView = mlContext.Data.LoadFromTextFile<ModelInput>("MOREDATA.CSV");

var newData = dataPrepPipeline.Transform(retrainingDataView);
IDataView transformedNewData = dataPrepPipeline.Transform(newData);

// Retrain model
var retrainedModel = mlContext.BinaryClassification.Trainers.LbfgsLogisticRegression().Fit(transformedNewData, originalModelParameters);

//Save complete pipeline for usage
var completeRetrainedPipeline = dataPrepPipeline.Append(retrainedModel);
mlContext.Model.Save(completeRetrainedPipeline, transformedNewData.Schema, "retrainedModel.zip);


问:
How to Import Java Class from ViewController in Model Impl Class in Oracle adf?
I am using Jdeveloper 12 ... I have a custom Java Class in ViewController Project in oracle adf...
How can I access and use that class in the VO Impl class  in Model ??  </p>

答:
In the Model project go to Project Properties > Dependencies and then click the green + to Add.

Expand the View Controller Project and Select "Build Output". Rebuild the app and now you can import the packages from the View Controller Application Sources.


问:
Objects and copy ctors created without RVO in C++
I am new to C++. Please consider the following code:

```<code>class foo
{
 int f;

 public:
   foo(int f1=0) : f(f1) {
   cout<<"In conversion ctor\n";
 }

foo(const foo & rhs) : f(rhs.f)
{
    cout<<" In copy ctor\n";
}

 foo& operator=(const foo & that)
{
    f=that.f;
    cout<<"In = optor\n";
    return *this;
}

};

 foo rbv()
  {
    foo obj(9);
    return obj;                        //named return by value [def. 1]
  }

   foo caller()
   {
      return rbv();              // return by value [def. 2]
   }

int main(void)
{
   foo box=caller();
   return 0;
 }
</code>```

Are the definitions for RBV and NRBV correct as indicated in the
comments?

Is it mandatory to have an accessible copy ctor defined though it
is not called during RVO?

Without RVO, in the code blocks

```<code>   foo rbv()
    {
     foo obj(9);
     return obj;
    }

    foo ret= rbv();
</code>```

Are the following steps correct in creation of 'ret'

(1) a temporary ( say obj_temp) is created using copy ctor from obj,
 stack object 'obj' destroyed,

(2) ret is copy constructed from obj_temp, obj_temp destroyed later;

which implies there are three objects, 'obj' , 'obj_temp' and 'ret' and two copy ctors involved.

答:
Are the definitions for RBV and NRBV correct as indicated in the comments?

They are RVO and NRVO (Return Value Optimization and Named Return Value Optimization)

Is it mandatory to have an accessible copy ctor defined though it is not called during RVO?

It is mandatory, the compiler has to verify that the constructors are accessible, if they are not, the compiler must trigger an error and fail to compile.

Without RVO, in the code blocks

```<code>foo rbv() {
  foo obj(9);
  return obj;
}
foo ret = rbv();
</code>```

The code, as it stands would require the following operations: Constructor taking an int inside foo to create obj. Copy construction in the return statement to the return temporary $tmp1, copy construction of ret at the call place from the temporary. Now, the compiler can elide the two copies by placing the return value (according to the call convention) on top of ret, so $tmp1 and ret are the same memory location, and by constructing obj on top of the same memory location, so at the end all three objects can be a single object and no copies need to be performed.

Body:
I am new to C++. Please consider the following code:

class foo
{
 int f;

 public:
   foo(int f1=0) : f(f1) {
   cout<<"In conversion ctor\n";
 }

foo(const foo & rhs) : f(rhs.f)
{
    cout<<" In copy ctor\n";
}

 foo& operator=(const foo & that)
{
    f=that.f;
    cout<<"In = optor\n";
    return *this;
}

};

 foo rbv()
  {
    foo obj(9);
    return obj;                        //named return by value [def. 1]
  }

   foo caller()
   {
      return rbv();              // return by value [def. 2]
   }

int main(void)
{
   foo box=caller();
   return 0;
 }

Are the definitions for RBV and NRBV correct as indicated in the
comments?

Is it mandatory to have an accessible copy ctor defined though it
is not called during RVO?

Without RVO, in the code blocks

   foo rbv()
    {
     foo obj(9);
     return obj;
    }

    foo ret= rbv();

Are the following steps correct in creation of 'ret'

(1) a temporary ( say obj_temp) is created using copy ctor from obj,
 stack object 'obj' destroyed,

(2) ret is copy constructed from obj_temp, obj_temp destroyed later;

which implies there are three objects, 'obj' , 'obj_temp' and 'ret' and two copy ctors involved.

Body:
Are the definitions for RBV and NRBV correct as indicated in the comments?

They are RVO and NRVO (Return Value Optimization and Named Return Value Optimization)

Is it mandatory to have an accessible copy ctor defined though it is not called during RVO?

It is mandatory, the compiler has to verify that the constructors are accessible, if they are not, the compiler must trigger an error and fail to compile.

Without RVO, in the code blocks

foo rbv() {
  foo obj(9);
  return obj;
}
foo ret = rbv();

The code, as it stands would require the following operations: Constructor taking an int inside foo to create obj. Copy construction in the return statement to the return temporary $tmp1, copy construction of ret at the call place from the temporary. Now, the compiler can elide the two copies by placing the return value (according to the call convention) on top of ret, so $tmp1 and ret are the same memory location, and by constructing obj on top of the same memory location, so at the end all three objects can be a single object and no copies need to be performed.


问:
Why is my XML file not rendered properly in Firefox?
I am using Firefox to read XML files, but it is not rendering the XML file properly. What could be the problem? I’m posting the XML sample below:

```<code><?xml version="1.0" encoding="utf-8"?>
<ExtPostTransaction>
    <TransactionInfo>
        <UserID>us</UserID>
        <Password>pwd</Password>
        <ServiceCode>1010</ServiceCode>
        <TransactionID>T20120518091833</TransactionID>
    </TransactionInfo>
</ExtPostTransaction>
</code>```

My Firefox shows it as:

```<code>uspwd1010T20120518091833
</code>```

I am expecting this:

```<code><ExtPostTransaction>
  <TransactionInfo>
    <UserID>us</UserID>
    <Password>pwd</Password>
    <ServiceCode>1010</ServiceCode>
    <TransactionID>T20120518091833</TransactionID>
  </TransactionInfo>
</ExtPostTransaction>
</code>```

答:
There appear to be a number of extensions that modify the display of the page in such a way as to break the rendering of XML.

The best way to check if the issue is caused by an addon is to try and view the page in a private window. If it displays correctly, disable your addons one by one until you find the offender. Then, please add it to the list.

Some of the known addons from other posts are:

Nimbus Screen Capture: Screenshots, Annotate

Selenium IDE

LanguageTool - Grammar and Style Checker

Kaspersky Protection

Avira browser Safety

AdBlocker Lite

AdBlocker Ultimate

Skype click to call

Adobe Acrobat

Awesome Screenshot

Youtube download

Katalon Recorder

WhatFont

Honey

Body:
I am using Firefox to read XML files, but it is not rendering the XML file properly. What could be the problem? I’m posting the XML sample below:

<?xml version="1.0" encoding="utf-8"?>
<ExtPostTransaction>
    <TransactionInfo>
        <UserID>us</UserID>
        <Password>pwd</Password>
        <ServiceCode>1010</ServiceCode>
        <TransactionID>T20120518091833</TransactionID>
    </TransactionInfo>
</ExtPostTransaction>

My Firefox shows it as:

uspwd1010T20120518091833

I am expecting this:

<ExtPostTransaction>
  <TransactionInfo>
    <UserID>us</UserID>
    <Password>pwd</Password>
    <ServiceCode>1010</ServiceCode>
    <TransactionID>T20120518091833</TransactionID>
  </TransactionInfo>
</ExtPostTransaction>


问:
Complex EntityFramework query with multiple tables and many to many relationship
I'm having a heck of a time getting Entity Framework to do what I want.  I'm writing a feed aggregator so I can add multiple rss feeds to a "FeedList" that will group all the individual podcasts and order by pubDate.

Classes (all but FeedListFeed have identity column called Id):

Feed (Id is identity primary key, has List Items property)

FeedItem (Id is identity primary key, as int FeedId and Feed Feed properties)

FeedList (FeedListName is string and List Feeds property)

FeedListFeed (many-to-many linking table, FeedListId and FeedId properties)

These mappings seems to work:

```<code>modelBuilder.Entity<FeedListFeed>().HasKey(x => x.FeedId).HasKey(x => x.FeedListId);
modelBuilder.Entity<FeedList>()
.HasMany(fl => fl.Feeds).WithMany(f => f.FeedLists)
.Map(t => t.MapLeftKey("FeedListId")
.MapRightKey("FeedId")
.ToTable("FeedListFeeds"));
</code>```

Now what I want to do is get the latest 20 FeedListItem entries for Feeds in a FeedList given the FeedListName.  I've come  up with this, but is there a better way to do it?  Will the query actually expand all the items, or will it be smart enough to do it on the SQL side?

```<code>var query =
    from fl in ctx.FeedLists.Include("Feeds").Include("FeedItems")
    from f in fl.Feeds
    from fi in f.Items
    where fl.FeedListName == id
    orderby fi.PubDate descending
    select fi;
List<FeedItem> items = query.Take(20).ToList();
</code>```

If I try to link the tables manually using the Id columns, I get the error Invalid object name 'dbo.FeedListFeeds1'.  If I took out the Lists that link the tables to each other would this help?  Is there some other mapping that let this work?

```<code>var query =
    from fl in ctx.FeedLists
    join flf in ctx.FeedListFeeds on fl.Id equals flf.FeedListId
    join fi in ctx.FeedItems on flf.FeedId equals fi.FeedId
    where fl.FeedListName == id
    orderby fi.PubDate descending
    select fi;
</code>```

答:
Remove this line from your mapping ...

```<code>modelBuilder.Entity<FeedListFeed>()
            .HasKey(x => x.FeedId)
            .HasKey(x => x.FeedListId);
</code>```

... because it has 2 issues:

1) If you want a composite key you must not chain HasKey but create the key via an anonymous type:

```<code>modelBuilder.Entity<FeedListFeed>()
            .HasKey(x => new { x.FeedId, x.FeedListId });
</code>```

2) (more important) This line lets EF consider FeedListFeed as an entity which it isn't in your model. The result is that EF creates a separate table for it with the name FeedListFeeds1 because FeedListFeeds is reserved as table name in your many-to-many mapping (.ToTable("FeedListFeeds")). For many-to-many mapping you don't need to create a class for the linking table. The linking table is managed by EF internally.

Edit

You can then also remove the FeedListFeed class completely of course.

For the query I would try then:

```<code>var query = from fi in ctx.FeedItems
            where fi.Feed.FeedLists.Any(fl => fl.FeedListName == id)
            orderby fi.PubDate descending
            select fi;
</code>```

I think you have all the necessary navigation properties in your model classes so that this query should be possible.

Body:
I'm having a heck of a time getting Entity Framework to do what I want.  I'm writing a feed aggregator so I can add multiple rss feeds to a "FeedList" that will group all the individual podcasts and order by pubDate.

Classes (all but FeedListFeed have identity column called Id):

Feed (Id is identity primary key, has List Items property)

FeedItem (Id is identity primary key, as int FeedId and Feed Feed properties)

FeedList (FeedListName is string and List Feeds property)

FeedListFeed (many-to-many linking table, FeedListId and FeedId properties)

These mappings seems to work:

modelBuilder.Entity<FeedListFeed>().HasKey(x => x.FeedId).HasKey(x => x.FeedListId);
modelBuilder.Entity<FeedList>()
.HasMany(fl => fl.Feeds).WithMany(f => f.FeedLists)
.Map(t => t.MapLeftKey("FeedListId")
.MapRightKey("FeedId")
.ToTable("FeedListFeeds"));

Now what I want to do is get the latest 20 FeedListItem entries for Feeds in a FeedList given the FeedListName.  I've come  up with this, but is there a better way to do it?  Will the query actually expand all the items, or will it be smart enough to do it on the SQL side?

var query =
    from fl in ctx.FeedLists.Include("Feeds").Include("FeedItems")
    from f in fl.Feeds
    from fi in f.Items
    where fl.FeedListName == id
    orderby fi.PubDate descending
    select fi;
List<FeedItem> items = query.Take(20).ToList();

If I try to link the tables manually using the Id columns, I get the error Invalid object name 'dbo.FeedListFeeds1'.  If I took out the Lists that link the tables to each other would this help?  Is there some other mapping that let this work?

var query =
    from fl in ctx.FeedLists
    join flf in ctx.FeedListFeeds on fl.Id equals flf.FeedListId
    join fi in ctx.FeedItems on flf.FeedId equals fi.FeedId
    where fl.FeedListName == id
    orderby fi.PubDate descending
    select fi;

Body:
Remove this line from your mapping ...

modelBuilder.Entity<FeedListFeed>()
            .HasKey(x => x.FeedId)
            .HasKey(x => x.FeedListId);

... because it has 2 issues:

1) If you want a composite key you must not chain HasKey but create the key via an anonymous type:

modelBuilder.Entity<FeedListFeed>()
            .HasKey(x => new { x.FeedId, x.FeedListId });

2) (more important) This line lets EF consider FeedListFeed as an entity which it isn't in your model. The result is that EF creates a separate table for it with the name FeedListFeeds1 because FeedListFeeds is reserved as table name in your many-to-many mapping (.ToTable("FeedListFeeds")). For many-to-many mapping you don't need to create a class for the linking table. The linking table is managed by EF internally.

Edit

You can then also remove the FeedListFeed class completely of course.

For the query I would try then:

var query = from fi in ctx.FeedItems
            where fi.Feed.FeedLists.Any(fl => fl.FeedListName == id)
            orderby fi.PubDate descending
            select fi;

I think you have all the necessary navigation properties in your model classes so that this query should be possible.


问:
Onclick function does not work in external javascript file
I have a button that is supposed to have onclick="submitItem()" but the function does not work when it is created in an external javascript file (app.js).

```<code><button class="btn" type="submit" onclick="submitItem()">Save</button>
</code>```

When the function is placed in between script tags, then it works, but that's not what I want.

```<code>  <script src="./js/app.js" type="module"></script>
  <script>
    function submitItem() {
      alert("works");
    }
  </script>
</code>```

But this does not work:

```<code>app.js

function submitItem() {
  alert("does not work");
}
</code>```

What can I do?

答:
It isn't a module. Don't claim it is. Remove type="module".

(Top-level variables, including those created by function declarations, are scoped to the module and not as globals in ES6 module scripts).

Body:
I have a button that is supposed to have onclick="submitItem()" but the function does not work when it is created in an external javascript file (app.js).

<button class="btn" type="submit" onclick="submitItem()">Save</button>

When the function is placed in between script tags, then it works, but that's not what I want.

But this does not work:

app.js

function submitItem() {
  alert("does not work");
}

What can I do?


问:
Dynamically change height of BottomSheetBehavior
I'm using the BottomSheetBehavior from Google recently released AppCompat v23.2. The height of my bottom sheet depends on the content displayed inside of the bottom sheet (similar to the what Google does themselves in their Maps app).

It works fine with the data loaded initially, but my application changes the content displayed during runtime and when this happens the bottom sheet retains at it's old height, which either leads to unused space at the bottom or a cut of view.

Is there any way to inform the bottom sheet layout to recalculate the height used for expanded state (when height of the ViewGroup is set to MATCH_HEIGHT) or any way to manually set the required height?

EDIT: I also tried to manually call invalidate() on the ViewGroup and the parent of it but without any success.

答:
Below code snippet helped me solve this issue where i am toggling between visibility of different views in layout and height is automatically changing for my bottom sheet.</p>

```<code>override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.your_bottom_sheet_layout, container, false)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
    dialog.setContentView(R.layout.your_bottom_sheet_layout)

    dialog.setOnShowListener {
        val castDialog = it as BottomSheetDialog
        val bottomSheet = castDialog.findViewById<View?>(R.id.design_bottom_sheet)
        val behavior = BottomSheetBehavior.from(bottomSheet)
        behavior.state = BottomSheetBehavior.STATE_EXPANDED
        behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                    behavior.state = BottomSheetBehavior.STATE_EXPANDED
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {}
        })
    }

    return dialog
}
</code>```

Body:
Below code snippet helped me solve this issue where i am toggling between visibility of different views in layout and height is automatically changing for my bottom sheet.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.your_bottom_sheet_layout, container, false)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
    dialog.setContentView(R.layout.your_bottom_sheet_layout)

    dialog.setOnShowListener {
        val castDialog = it as BottomSheetDialog
        val bottomSheet = castDialog.findViewById<View?>(R.id.design_bottom_sheet)
        val behavior = BottomSheetBehavior.from(bottomSheet)
        behavior.state = BottomSheetBehavior.STATE_EXPANDED
        behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                    behavior.state = BottomSheetBehavior.STATE_EXPANDED
                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {}
        })
    }

    return dialog
}


问:
Regex to check for at least 8 digits and exactly 2 characters
I'd like to make an regular expression that check in a string that match at least 8 digits and exactly 2 characters in uppercase. the letters and decimals can be anywhere.

Thanks

答:
Would this work:

```<code>^(?=[A-Z0-9]{10,})\d*[A-Z]\d*[A-Z]\d*$
</code>```

^ - Match start of string

(?=[A-Z0-9]{10,}) - A positive LookAhead to match at least 10 chars from [A-Z0-9] only

\d*[A-Z]\d*[A-Z]\d* - Two chars in the range [A-Z] surrounded by zero or more digits

$ - Match end of string

Alternatively, create another capture group:

```<code>^(?=[A-Z0-9]{10,})(\d*[A-Z]){2}\d*$
</code>```

Now you got a little bit more flexibility to tell the pattern you need an x-amount of upper case letters > {x}

Body:
Would this work:

^(?=[A-Z0-9]{10,})\d*[A-Z]\d*[A-Z]\d*$

^ - Match start of string

(?=[A-Z0-9]{10,}) - A positive LookAhead to match at least 10 chars from [A-Z0-9] only

\d*[A-Z]\d*[A-Z]\d* - Two chars in the range [A-Z] surrounded by zero or more digits

$ - Match end of string

Alternatively, create another capture group:

^(?=[A-Z0-9]{10,})(\d*[A-Z]){2}\d*$

Now you got a little bit more flexibility to tell the pattern you need an x-amount of upper case letters > {x}


问:
Backbone: Hide dialog popup if input has not changed
I'm trying to show a dialog popup if field has the value 0. I'm able to do that, but in render page, if input has the value 0 and is not changed, again I'm seeing that dialog.

Dialog shouldn't be there if input has value 0 on render

```<code><input id="input-value" type="text" class="text-controll"/> //this model return values from attributeName from the backend
</code>```

Model on Save:

```<code>save() {
 if(this.model.get('attributeName') === 0) {
  dialog.confirm(
   "Are you sure you want to save the data"
  )
 }
}
</code>```

答:
I think Backbone has code to check for this built in:

```<code>save() {
 var nameChanged = !!this.model.changedAttributes()['attributeName'];

 if(nameChanged && this.model.get('attributeName') === 0) {
  dialog.confirm(
   "Are you sure you want to save the data"
  )
 }
}
</code>```

This could fail if you initialize your Model in some nonstandard way, like creating an empty one and then "changing" to values from your db. But for standard uses, this should work.

Documentation here: https://backbonejs.org/#Model-changedAttributes

Body:
I'm trying to show a dialog popup if field has the value 0. I'm able to do that, but in render page, if input has the value 0 and is not changed, again I'm seeing that dialog.

Dialog shouldn't be there if input has value 0 on render

<input id="input-value" type="text" class="text-controll"/> //this model return values from attributeName from the backend

Model on Save:

save() {
 if(this.model.get('attributeName') === 0) {
  dialog.confirm(
   "Are you sure you want to save the data"
  )
 }
}

Body:
I think Backbone has code to check for this built in:

save() {
 var nameChanged = !!this.model.changedAttributes()['attributeName'];

 if(nameChanged && this.model.get('attributeName') === 0) {
  dialog.confirm(
   "Are you sure you want to save the data"
  )
 }
}

This could fail if you initialize your Model in some nonstandard way, like creating an empty one and then "changing" to values from your db. But for standard uses, this should work.

Documentation here: https://backbonejs.org/#Model-changedAttributes


问:
Scroll is not smooth for image listing web page
I am trying to create an image listing website in angular like the google photos. I have a custom scrollbar which lists the month and year. When user moves the scroll thumb, the image list should scroll.
I have written,

```<code>scrollContainer = document.getElementById("photosContainer");
scrollContainer.scrollTop += 20;
</code>```

and the mousemove event will fire the above code.
There are about 5000 img tags and for testing purpose the src is just an avatar icon hardcoded.
So no changes happen to the image when it is scrolled.

```<code> onmousemove(){
  this.scrollThumbPosition = <value>;
}
</code>```

This will move the scrollbar thumb. The scrollbar and everything works fine if there are upto a 1000 images.But when there are more than 1000 images,

Scroll thumb wont move when dragged.

The image list wont move.

But when the mouseup action is triggered the Ui responds.
Is there a way to smoothen the performance of the page with huge number of image tags?

答:
Have you tried a simple CSS solution? (Edit: added will-change: scroll-position thanks to lucifer63).

```<code>html {
  scroll-behavior: smooth;
  will-change: scroll-position;
}
</code>```

scroll-behavior: smooth politely asks the browser to smooth out automated scrolling (i.e. not user scrolling)

will-change: scroll-position lets the browser know where a performance hit is expected. It is only intended as a last resort if you are still seeing issues.

Edit:

Or if you want a pure JS approach, you can use the window.scroll() fuction:

```<code>window.scrollBy({
  top: 20,
  left: 0,
  behavior: 'smooth'
});
</code>```

``

Body:
I am trying to create an image listing website in angular like the google photos. I have a custom scrollbar which lists the month and year. When user moves the scroll thumb, the image list should scroll.
I have written,

scrollContainer = document.getElementById("photosContainer");
scrollContainer.scrollTop += 20;

and the mousemove event will fire the above code.
There are about 5000 img tags and for testing purpose the src is just an avatar icon hardcoded.
So no changes happen to the image when it is scrolled.

 onmousemove(){
  this.scrollThumbPosition = <value>;
}

This will move the scrollbar thumb. The scrollbar and everything works fine if there are upto a 1000 images.But when there are more than 1000 images,

Scroll thumb wont move when dragged.

The image list wont move.

But when the mouseup action is triggered the Ui responds.
Is there a way to smoothen the performance of the page with huge number of image tags?

Body:
Have you tried a simple CSS solution? (Edit: added will-change: scroll-position thanks to lucifer63).

html {
  scroll-behavior: smooth;
  will-change: scroll-position;
}

scroll-behavior: smooth politely asks the browser to smooth out automated scrolling (i.e. not user scrolling)

will-change: scroll-position lets the browser know where a performance hit is expected. It is only intended as a last resort if you are still seeing issues.

Edit:

Or if you want a pure JS approach, you can use the window.scroll() fuction:

window.scrollBy({
  top: 20,
  left: 0,
  behavior: 'smooth'
});

``


问:
JHipster inheritance
I'm currently trying to code my UML-diagram scheme in JDL-Studio, but inheritance isn't supported apparently. Answers from different platforms didn't help.

Let's say I want the class Fashion to inherit from Department. Is there a way to bypass the inheritance issue?

I aim to import the finished JDL-Studio code to my IntelliJ project.

I included some relation types, so you can see the syntax of JDL-studio.

```<code>relationship OneToOne {
    Location{country} to Country
}

relationship OneToOne {
    Department{location} to Location
}

relationship ManyToMany {
    Job{task(title)} to Task{job}
}

</code>```

答:
As Gaël Marziou commented, you have to implement it manually. I just want to repeat it to see an answer on your question on stackoverflow - by no means to take his credits (he's undoubtedly great!!).

For coding the generated source further, I just want to point at Side-by-Side-coding to be able to update your code with jhipster in the future. There is a good practice example and detailed explanation from David Steiman (xetys) on youtube, along with inheritance.

Title: JHipster inheritance

Body:
I'm currently trying to code my UML-diagram scheme in JDL-Studio, but inheritance isn't supported apparently. Answers from different platforms didn't help.

Let's say I want the class Fashion to inherit from Department. Is there a way to bypass the inheritance issue?

I aim to import the finished JDL-Studio code to my IntelliJ project.

I included some relation types, so you can see the syntax of JDL-studio.

relationship OneToOne {
    Location{country} to Country
}

relationship OneToOne {
    Department{location} to Location
}

relationship ManyToMany {
    Job{task(title)} to Task{job}
}


问:
SQL Select data from two tables, one row -> multiple rows
I have the following two tables:

```<code>customers:  |  phones:
--------------------------------------
id          |  id
name        |  owner (FK_CUSTOMERS)
address     |  number
</code>```

I load a html table in laravel blade to show all the customers and I want a table cell with the phones saved for each customer.

So one customer may have no phones, just one or multiple phones. I need to retrieve each customer with their phones in one row, or there is a better way to do this?

If I do something like this results one row per phone with duplicate data:

```<code> $customers = DB::table('customers')
        ->join("phones","customers.id", "=", "phones.owner")
        ->where("phones.group",1)
        ->select(
            'customers.id',
            'customers.name',
            'customers.fiscalNumber',
            'customers.disscount',
            'customers.billAddress',
            'customers.tax',
            'phones.number'
        )
        ->get();
</code>```

I want this:

```<code>id | name    | address          | phones
5  | Michael | fake address 123 | 666777888,111222333,444555666
</code>```

I have tried several things but nothings works. Thanks

答:
Instead of joining your tables, which sometimes is an anti pattern using Eloquent. Use Eloquent mutators to solve your problem.

Define the relationship to phones and a mutator.

```<code>class Customer {
    public function phones() {
        return $this->hasMany(Phone::class, 'owner');
    }

    public function getPhoneNumbersAttribute() {
        return implode(',', $this->phones->pluck('number')->all());
    }
}
</code>```

To use you mutator simply fetch your model and access it. For performance optimisation, load phones with the with() method, that eager loads the relationship.

```<code>Customer::with('phones')->find(1)->phoneNumbers; // [666777888,111222333,444555666]
</code>```

Body:
I have the following two tables:

customers:  |  phones:
--------------------------------------
id          |  id
name        |  owner (FK_CUSTOMERS)
address     |  number

I load a html table in laravel blade to show all the customers and I want a table cell with the phones saved for each customer.

So one customer may have no phones, just one or multiple phones. I need to retrieve each customer with their phones in one row, or there is a better way to do this?

If I do something like this results one row per phone with duplicate data:

 $customers = DB::table('customers')
        ->join("phones","customers.id", "=", "phones.owner")
        ->where("phones.group",1)
        ->select(
            'customers.id',
            'customers.name',
            'customers.fiscalNumber',
            'customers.disscount',
            'customers.billAddress',
            'customers.tax',
            'phones.number'
        )
        ->get();

I want this:

id | name    | address          | phones
5  | Michael | fake address 123 | 666777888,111222333,444555666

I have tried several things but nothings works. Thanks

Body:
Instead of joining your tables, which sometimes is an anti pattern using Eloquent. Use Eloquent mutators to solve your problem.

Define the relationship to phones and a mutator.

class Customer {
    public function phones() {
        return $this->hasMany(Phone::class, 'owner');
    }

    public function getPhoneNumbersAttribute() {
        return implode(',', $this->phones->pluck('number')->all());
    }
}

To use you mutator simply fetch your model and access it. For performance optimisation, load phones with the with() method, that eager loads the relationship.

Customer::with('phones')->find(1)->phoneNumbers; // [666777888,111222333,444555666]


问:
Async/await - data is undefined
Trying to convert CSV to JSON, then download an image,then upload it to S3 bucket, then update current JSON and finally generate a new CSV. However the code doesn't wait for the async function to complete so const data = await handle_image_URLs(csv); returns as undefined.

```<code>//parse CSV - extract images, then upload to S3 bucket
const handle_image_URLs = file => {
  new Promise((resolve, reject) => {
    fs.createReadStream(file)
      .pipe(csv_to_json())
      .on("data", async data => {
        // console.log("data", data);
        try {
          if (is_image_url(data.image_link)) {
            console.log("data.image_link", data.image_link);
            image_buffer = await download_image(data.image_link);
            name = uuid() + ".jpg";
            const location = await upload_to_S3(image_buffer, name);
            //Inject back updated image url
            data.image_link = location.Location;
            //New generated data goes into an array
            results.push(data);
          }
          // console.log("RESULT", results);
          resolve(results);
        } catch (error) {
          reject(error);
        }
      });
  });
};
</code>```

express to handle a csv upload

```<code>app.post("/", upload.single("file"), async (req, res) => {
  const file = req.file;
  const csv = `./uploads/${file.originalname}`;
  const data = await handle_image_URLs(csv);
  console.log("DATA", data);
  // await json_to_csv_converter.json2csv(data, json2csvCallback);
  res.status(200).json({ message: "working " });
});
</code>```

答: Update the return new promise((resolve, reject)) to return new promise( async (resolve, reject)) and it should work

Title: Async/await - data is undefined

Body:
Trying to convert CSV to JSON, then download an image,then upload it to S3 bucket, then update current JSON and finally generate a new CSV. However the code doesn't wait for the async function to complete so const data = await handle_image_URLs(csv); returns as undefined.

//parse CSV - extract images, then upload to S3 bucket
const handle_image_URLs = file => {
  new Promise((resolve, reject) => {
    fs.createReadStream(file)
      .pipe(csv_to_json())
      .on("data", async data => {
        // console.log("data", data);
        try {
          if (is_image_url(data.image_link)) {
            console.log("data.image_link", data.image_link);
            image_buffer = await download_image(data.image_link);
            name = uuid() + ".jpg";
            const location = await upload_to_S3(image_buffer, name);
            //Inject back updated image url
            data.image_link = location.Location;
            //New generated data goes into an array
            results.push(data);
          }
          // console.log("RESULT", results);
          resolve(results);
        } catch (error) {
          reject(error);
        }
      });
  });
};

express to handle a csv upload

app.post("/", upload.single("file"), async (req, res) => {
  const file = req.file;
  const csv = `./uploads/${file.originalname}`;
  const data = await handle_image_URLs(csv);
  console.log("DATA", data);
  // await json_to_csv_converter.json2csv(data, json2csvCallback);
  res.status(200).json({ message: "working " });
});


问:
Symfony form builder: How to iterate/render dynamic amount of text fields in twig? (Sylius - exta checkout step)
I added an extra checkout step to the Sylius checkout procedure and I am trying to add 1 text field per instance of an ordered item. Thus having put 3x itemA and 1x itemB in cart should spawn 4 text fields.

I have this code so far in the form builder (based on code from here: https://sf.khepin.com/2011/08/basic-usage-of-the-symfony2-collectiontype-form-field/)

```<code>        $builder->add('myCollection', CollectionType::class, $formOptions);

        $totalCounter = 0;
        /** @var OrderItem $item */
        foreach($order->getItems() as $item) {
            for($itemCounter = 0 ; $itemCounter < $item->getQuantity(); $itemCounter++ ) {
                $totalCounter++;
                $builder->get('myCollection')->add('item_' . $totalCounter, TextType::class, $formOptions);
            }
        }
</code>```

First Question: Is this the right approach for the form builder for my particular scenario, and secondly: If yes, how do I read from this in the twig template?

form.children.myCollection does exist but does not seem to contain these children, so that I could use them with the form_row function. What I would have expected is something like this:

```<code>{% set totalCounter = 0 %}
{% for item in order.items %}
    {% for itemCounter in 1..item.quantity %}
        {% set totalCounter = totalCounter + 1 %}
        {{  form_row(form.children.myCollection['item_' ~ totalCounter ]) }}
    {% endfor %}
{% endfor %}
</code>```

Any idea how to do this? Thanks for any hint in advance!

答:
Just saw my exact case is described in the beginning of the documentation of CollectionType https://symfony.com/doc/current/reference/forms/types/collection.html

The form builder part..

```<code>$builder->add('emails', CollectionType::class, [
    // each entry in the array will be an "email" field
    'entry_type' => EmailType::class,
    // these options are passed to each "email" type
    'entry_options' => [
        'attr' => ['class' => 'email-box'],
    ],
]);
</code>```

..and the twig part:

```<code>{{ form_label(form.emails) }}
{{ form_errors(form.emails) }}

<ul>
{% for emailField in form.emails %}
    <li>
        {{ form_errors(emailField) }}
        {{ form_widget(emailField) }}
    </li>
{% endfor %}
</code>```

Body:
I added an extra checkout step to the Sylius checkout procedure and I am trying to add 1 text field per instance of an ordered item. Thus having put 3x itemA and 1x itemB in cart should spawn 4 text fields.

I have this code so far in the form builder (based on code from here: https://sf.khepin.com/2011/08/basic-usage-of-the-symfony2-collectiontype-form-field/)

        $builder->add('myCollection', CollectionType::class, $formOptions);

        $totalCounter = 0;
        /** @var OrderItem $item */
        foreach($order->getItems() as $item) {
            for($itemCounter = 0 ; $itemCounter < $item->getQuantity(); $itemCounter++ ) {
                $totalCounter++;
                $builder->get('myCollection')->add('item_' . $totalCounter, TextType::class, $formOptions);
            }
        }

First Question: Is this the right approach for the form builder for my particular scenario, and secondly: If yes, how do I read from this in the twig template?

form.children.myCollection does exist but does not seem to contain these children, so that I could use them with the form_row function. What I would have expected is something like this:

{% set totalCounter = 0 %}
{% for item in order.items %}
    {% for itemCounter in 1..item.quantity %}
        {% set totalCounter = totalCounter + 1 %}
        {{  form_row(form.children.myCollection['item_' ~ totalCounter ]) }}
    {% endfor %}
{% endfor %}

Any idea how to do this? Thanks for any hint in advance!

Body:
Just saw my exact case is described in the beginning of the documentation of CollectionType https://symfony.com/doc/current/reference/forms/types/collection.html

The form builder part..

$builder->add('emails', CollectionType::class, [
    // each entry in the array will be an "email" field
    'entry_type' => EmailType::class,
    // these options are passed to each "email" type
    'entry_options' => [
        'attr' => ['class' => 'email-box'],
    ],
]);

..and the twig part:

{{ form_label(form.emails) }}
{{ form_errors(form.emails) }}

<ul>
{% for emailField in form.emails %}
    <li>
        {{ form_errors(emailField) }}
        {{ form_widget(emailField) }}
    </li>
{% endfor %}