问:
PHP: Foreach Simlplexml output
I got a xmlfile exported from the datamodelling-tool wwwsqldesigner. It contains all tables, their comments, columns and their datatypes, primary key columns and so on.

I imported the xml file in my php script successfully with simplexml_load_file and now I want to loop through the nodes/tags to get 3 lists (to insert them into a database in 3 tables afterwards, for the moment echoing is enough).

Those lists are:
1) Tables: Tablenames in the datamodel/xml-file, their comments and primary key names.
2) Columns: The columns of that tables: columnname, datatype, nullable (and column order if possible).
3) Primary Key Columns: columnname and column order.

The xml looks like this:

```<code><?xml version="1.0" encoding="utf-8" ?>
<sql>
<table x="673" y="237" name="DIM_CUSTOMER">
<row name="CUSTOMER_SID" null="0" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default><comment>Customer-SK</comment>
</row>
<row name="CUSTOMER_NAME" null="0" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>'NULL'</default><comment>Customername</comment>
</row>
<row name="CUSTOMER_GROUP" null="1" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="DIM_CUSTOMER_PK">
<part>CUSTOMER_SID</part>
</key>
<comment>Kunden</comment>
</table>
<table x="1150" y="204" name="DIM_PRODUCT">
<row name="PRODUCT_SID" null="0" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default><comment>Produkt-Sk</comment>
</row>
<row name="PRODUCT_NAME" null="0" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>'NULL'</default><comment>Productname</comment>
</row>
<key type="PRIMARY" name="DIM_PRODUCT_PK">
<part>PRODUCT_SID</part>
</key>
<comment>Product</comment>
</table>
<table x="632" y="499" name="DIM_DATE">
<row name="DATE_ID" null="0" autoincrement="1">
<datatype>DATE</datatype>
<default>'NULL'</default></row>
<row name="YEAR" null="1" autoincrement="0">
<datatype>CHAR(4)</datatype>
<default>NULL</default></row>
<row name="QUARTER" null="1" autoincrement="0">
<datatype>CHAR(2)</datatype>
<default>NULL</default></row>
<row name="MONTH" null="1" autoincrement="0">
<datatype>VARCHAR(2)</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="DIM_DATE_PK">
<part>DATE_ID</part>
</key>
</table>
<table x="1214" y="511" name="DIM_INVENTORY">
<row name="INVENTORY_SID" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default><comment>Inventory SK</comment>
</row>
<row name="INVENTORY_NAME" null="0" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>'NULL'</default><comment>Inventory</comment>
</row>
<key type="PRIMARY" name="DIM_DATE_PK">
<part>INVENTORY_SID</part>
</key>
</table>
<table x="950" y="358" name="FACT_SALES">
<row name="DATE_ID" null="0" autoincrement="0">
<datatype>DATE</datatype>
<default>'NULL'</default><relation table="DIM_DATE" row="DATE_ID" />
</row>
<row name="INVENTORY_SID" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="DIM_INVENTORY" row="INVENTORY_SID" />
<comment>Inventory SK</comment>
</row>
<row name="PRODUCT_SID" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="DIM_PRODUCT" row="PRODUCT_SID" />
<comment>Product-Sk</comment>
</row>
<row name="CUSTOMER_SID" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="DIM_CUSTOMER" row="CUSTOMER_SID" />
<comment>Customer-SK</comment>
</row>
<row name="REVENUE" null="0" autoincrement="0">
<datatype>DECIMAL(10,2)</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="FACT_SALES_PK">
<part>DATE_ID</part>
<part>INVENTORY_SID</part>
<part>PRODUCT_SID</part>
<part>CUSTOMER_SID</part>
</key>
<comment>Sales</comment>
</table>
</sql>
</code>```

For each database table there is a  tag that contains several  tags and a  tag for the primary key and a  tag. The  tag itself has several  tags for every primary key columns.

To create the 3 needed lists mentioned above I wrote follwing php script:

```<code><?php
$xml = simplexml_load_file('C:\xampp\htdocs\sqldesigner\backend\php-mysql\Datamart.xml');

// Tables
echo "+++++++++++++ TABLES +++++++++++++<br>";
foreach ($xml->table as $table) {
        echo "----------------------------------------<br>";
        echo "Tabelle: "  . $table['name']  . "<br>"; //Tabelle
        echo "Primary: "  . $table->key['name']     . "<br>"; //PK
        echo "Comment: "  . $table->comment     . "<br>"; //Table-Comment

}
// Columns
echo "+++++++++++++ COLUMNS +++++++++++++<br>";
foreach ($xml->table as $table) {

        foreach ($table as $row) {
            echo "Column: "   . $table['name'] . "." . $row['name'] . "<br>";
            echo "Nullable: " . $row["null"]    . "<br>";
            echo "Datatype: " . $row->datatype."<br>";
            echo "Comment: "  . $row->comment . "<br>";
            echo "---------------------<br>";
        }
}

// PK-Columns
echo "+++++++++++++ PRIMARY KEY COLS +++++++++++++<br>";
foreach ($xml->table as $table) {

        foreach ($table as $primarykey) {
            echo "PK-Col.: " . $table['name'] . "." . $primarykey->part . "<br>";

        }
}
?>
</code>```

Unfortunately the output is wrong for columns and primary keys. It produces empty lines. So my guess is, there is a connection from the inner foreach to the outer foreach missing. The output looks like this:

```<code>+++++++++++++ TABLES +++++++++++++
----------------------------------------
Tabelle: DIM_CUSTOMER
Primary: DIM_CUSTOMER_PK
Comment: Kunden
----------------------------------------
Tabelle: DIM_PRODUCT
Primary: DIM_PRODUCT_PK
Comment: Product
----------------------------------------
Tabelle: DIM_DATE
Primary: DIM_DATE_PK
Comment:
----------------------------------------
Tabelle: DIM_INVENTORY
Primary: DIM_DATE_PK
Comment:
----------------------------------------
Tabelle: FACT_SALES
Primary: FACT_SALES_PK
Comment: Sales
+++++++++++++ COLUMNS +++++++++++++
Column: DIM_CUSTOMER.CUSTOMER_SID
Nullable: 0
Datatype: INTEGER
Comment: Customer-SK
---------------------
Column: DIM_CUSTOMER.CUSTOMER_NAME
Nullable: 0
Datatype: VARCHAR(30)
Comment: Customername
---------------------
Column: DIM_CUSTOMER.CUSTOMER_GROUP
Nullable: 1
Datatype: VARCHAR(30)
Comment:
---------------------
Column: DIM_CUSTOMER.DIM_CUSTOMER_PK
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_CUSTOMER.
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_PRODUCT.PRODUCT_SID
Nullable: 0
Datatype: INTEGER
Comment: Produkt-Sk
---------------------
Column: DIM_PRODUCT.PRODUCT_NAME
Nullable: 0
Datatype: VARCHAR(30)
Comment: Productname
---------------------
Column: DIM_PRODUCT.DIM_PRODUCT_PK
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_PRODUCT.
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_DATE.DATE_ID
Nullable: 0
Datatype: DATE
Comment:
---------------------
Column: DIM_DATE.YEAR
Nullable: 1
Datatype: CHAR(4)
Comment:
---------------------
Column: DIM_DATE.QUARTER
Nullable: 1
Datatype: CHAR(2)
Comment:
---------------------
Column: DIM_DATE.MONTH
Nullable: 1
Datatype: VARCHAR(2)
Comment:
---------------------
Column: DIM_DATE.DIM_DATE_PK
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_INVENTORY.INVENTORY_SID
Nullable: 1
Datatype: INTEGER
Comment: Inventory SK
---------------------
Column: DIM_INVENTORY.INVENTORY_NAME
Nullable: 0
Datatype: VARCHAR(30)
Comment: Inventory
---------------------
Column: DIM_INVENTORY.DIM_DATE_PK
Nullable:
Datatype:
Comment:
---------------------
Column: FACT_SALES.DATE_ID
Nullable: 0
Datatype: DATE
Comment:
---------------------
Column: FACT_SALES.INVENTORY_SID
Nullable: 1
Datatype: INTEGER
Comment: Inventory SK
---------------------
Column: FACT_SALES.PRODUCT_SID
Nullable: 0
Datatype: INTEGER
Comment: Product-Sk
---------------------
Column: FACT_SALES.CUSTOMER_SID
Nullable: 0
Datatype: INTEGER
Comment: Customer-SK
---------------------
Column: FACT_SALES.REVENUE
Nullable: 0
Datatype: DECIMAL(10,2)
Comment:
---------------------
Column: FACT_SALES.FACT_SALES_PK
Nullable:
Datatype:
Comment:
---------------------
Column: FACT_SALES.
Nullable:
Datatype:
Comment:
---------------------
+++++++++++++ PRIMARY KEY COLS +++++++++++++
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_CUSTOMER.CUSTOMER_SID
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_PRODUCT.
PK-Col.: DIM_PRODUCT.
PK-Col.: DIM_PRODUCT.PRODUCT_SID
PK-Col.: DIM_PRODUCT.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.DATE_ID
PK-Col.: DIM_INVENTORY.
PK-Col.: DIM_INVENTORY.
PK-Col.: DIM_INVENTORY.INVENTORY_SID
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.DATE_ID
PK-Col.: FACT_SALES.
</code>```

Here is how the datamodel from the xml looks like in the wwwsqldesigner

Any suggestions how to handle this problem?

Thank you and cheers!

答:
In the same way that you use $xml->table in your outer loop, you also need to get the inner loop to just select the <row> elements.

So your inner foreach loop becomes..

```<code>foreach ($table->row as $row) {
</code>```

As you can see, your picking up all the subelements of
, this will limit it to just the <row> ones.

Title: PHP: Foreach Simlplexml output

Body:
I got a xmlfile exported from the datamodelling-tool wwwsqldesigner. It contains all tables, their comments, columns and their datatypes, primary key columns and so on.

I imported the xml file in my php script successfully with simplexml_load_file and now I want to loop through the nodes/tags to get 3 lists (to insert them into a database in 3 tables afterwards, for the moment echoing is enough).

Those lists are:
1) Tables: Tablenames in the datamodel/xml-file, their comments and primary key names.
2) Columns: The columns of that tables: columnname, datatype, nullable (and column order if possible).
3) Primary Key Columns: columnname and column order.

The xml looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<sql>

<row name="CUSTOMER_SID" null="0" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default><comment>Customer-SK</comment>
</row>
<row name="CUSTOMER_NAME" null="0" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>'NULL'</default><comment>Customername</comment>
</row>
<row name="CUSTOMER_GROUP" null="1" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="DIM_CUSTOMER_PK">
<part>CUSTOMER_SID</part>
</key>
<comment>Kunden</comment>

<row name="PRODUCT_SID" null="0" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default><comment>Produkt-Sk</comment>
</row>
<row name="PRODUCT_NAME" null="0" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>'NULL'</default><comment>Productname</comment>
</row>
<key type="PRIMARY" name="DIM_PRODUCT_PK">
<part>PRODUCT_SID</part>
</key>
<comment>Product</comment>

<row name="DATE_ID" null="0" autoincrement="1">
<datatype>DATE</datatype>
<default>'NULL'</default></row>
<row name="YEAR" null="1" autoincrement="0">
<datatype>CHAR(4)</datatype>
<default>NULL</default></row>
<row name="QUARTER" null="1" autoincrement="0">
<datatype>CHAR(2)</datatype>
<default>NULL</default></row>
<row name="MONTH" null="1" autoincrement="0">
<datatype>VARCHAR(2)</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="DIM_DATE_PK">
<part>DATE_ID</part>
</key>

<row name="INVENTORY_SID" null="1" autoincrement="1">
<datatype>INTEGER</datatype>
<default>NULL</default><comment>Inventory SK</comment>
</row>
<row name="INVENTORY_NAME" null="0" autoincrement="0">
<datatype>VARCHAR(30)</datatype>
<default>'NULL'</default><comment>Inventory</comment>
</row>
<key type="PRIMARY" name="DIM_DATE_PK">
<part>INVENTORY_SID</part>
</key>

<row name="DATE_ID" null="0" autoincrement="0">
<datatype>DATE</datatype>
<default>'NULL'</default><relation table="DIM_DATE" row="DATE_ID" />
</row>
<row name="INVENTORY_SID" null="1" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="DIM_INVENTORY" row="INVENTORY_SID" />
<comment>Inventory SK</comment>
</row>
<row name="PRODUCT_SID" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="DIM_PRODUCT" row="PRODUCT_SID" />
<comment>Product-Sk</comment>
</row>
<row name="CUSTOMER_SID" null="0" autoincrement="0">
<datatype>INTEGER</datatype>
<default>NULL</default><relation table="DIM_CUSTOMER" row="CUSTOMER_SID" />
<comment>Customer-SK</comment>
</row>
<row name="REVENUE" null="0" autoincrement="0">
<datatype>DECIMAL(10,2)</datatype>
<default>NULL</default></row>
<key type="PRIMARY" name="FACT_SALES_PK">
<part>DATE_ID</part>
<part>INVENTORY_SID</part>
<part>PRODUCT_SID</part>
<part>CUSTOMER_SID</part>
</key>
<comment>Sales</comment>

</sql>

For each database table there is a  tag that contains several  tags and a  tag for the primary key and a  tag. The  tag itself has several  tags for every primary key columns.

To create the 3 needed lists mentioned above I wrote follwing php script:

<?php
$xml = simplexml_load_file('C:\xampp\htdocs\sqldesigner\backend\php-mysql\Datamart.xml');

// Tables
echo "+++++++++++++ TABLES +++++++++++++
";
foreach ($xml->table as $table) {
        echo "----------------------------------------
";
        echo "Tabelle: "  . $table['name']  . "
"; //Tabelle
        echo "Primary: "  . $table->key['name']     . "
"; //PK
        echo "Comment: "  . $table->comment     . "
"; //Table-Comment

}
// Columns
echo "+++++++++++++ COLUMNS +++++++++++++
";
foreach ($xml->table as $table) {

        foreach ($table as $row) {
            echo "Column: "   . $table['name'] . "." . $row['name'] . "
";
            echo "Nullable: " . $row["null"]    . "
";
            echo "Datatype: " . $row->datatype."
";
            echo "Comment: "  . $row->comment . "
";
            echo "---------------------
";
        }
}

// PK-Columns
echo "+++++++++++++ PRIMARY KEY COLS +++++++++++++
";
foreach ($xml->table as $table) {

        foreach ($table as $primarykey) {
            echo "PK-Col.: " . $table['name'] . "." . $primarykey->part . "
";

        }
}
?>

Unfortunately the output is wrong for columns and primary keys. It produces empty lines. So my guess is, there is a connection from the inner foreach to the outer foreach missing. The output looks like this:

+++++++++++++ TABLES +++++++++++++
----------------------------------------
Tabelle: DIM_CUSTOMER
Primary: DIM_CUSTOMER_PK
Comment: Kunden
----------------------------------------
Tabelle: DIM_PRODUCT
Primary: DIM_PRODUCT_PK
Comment: Product
----------------------------------------
Tabelle: DIM_DATE
Primary: DIM_DATE_PK
Comment:
----------------------------------------
Tabelle: DIM_INVENTORY
Primary: DIM_DATE_PK
Comment:
----------------------------------------
Tabelle: FACT_SALES
Primary: FACT_SALES_PK
Comment: Sales
+++++++++++++ COLUMNS +++++++++++++
Column: DIM_CUSTOMER.CUSTOMER_SID
Nullable: 0
Datatype: INTEGER
Comment: Customer-SK
---------------------
Column: DIM_CUSTOMER.CUSTOMER_NAME
Nullable: 0
Datatype: VARCHAR(30)
Comment: Customername
---------------------
Column: DIM_CUSTOMER.CUSTOMER_GROUP
Nullable: 1
Datatype: VARCHAR(30)
Comment:
---------------------
Column: DIM_CUSTOMER.DIM_CUSTOMER_PK
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_CUSTOMER.
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_PRODUCT.PRODUCT_SID
Nullable: 0
Datatype: INTEGER
Comment: Produkt-Sk
---------------------
Column: DIM_PRODUCT.PRODUCT_NAME
Nullable: 0
Datatype: VARCHAR(30)
Comment: Productname
---------------------
Column: DIM_PRODUCT.DIM_PRODUCT_PK
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_PRODUCT.
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_DATE.DATE_ID
Nullable: 0
Datatype: DATE
Comment:
---------------------
Column: DIM_DATE.YEAR
Nullable: 1
Datatype: CHAR(4)
Comment:
---------------------
Column: DIM_DATE.QUARTER
Nullable: 1
Datatype: CHAR(2)
Comment:
---------------------
Column: DIM_DATE.MONTH
Nullable: 1
Datatype: VARCHAR(2)
Comment:
---------------------
Column: DIM_DATE.DIM_DATE_PK
Nullable:
Datatype:
Comment:
---------------------
Column: DIM_INVENTORY.INVENTORY_SID
Nullable: 1
Datatype: INTEGER
Comment: Inventory SK
---------------------
Column: DIM_INVENTORY.INVENTORY_NAME
Nullable: 0
Datatype: VARCHAR(30)
Comment: Inventory
---------------------
Column: DIM_INVENTORY.DIM_DATE_PK
Nullable:
Datatype:
Comment:
---------------------
Column: FACT_SALES.DATE_ID
Nullable: 0
Datatype: DATE
Comment:
---------------------
Column: FACT_SALES.INVENTORY_SID
Nullable: 1
Datatype: INTEGER
Comment: Inventory SK
---------------------
Column: FACT_SALES.PRODUCT_SID
Nullable: 0
Datatype: INTEGER
Comment: Product-Sk
---------------------
Column: FACT_SALES.CUSTOMER_SID
Nullable: 0
Datatype: INTEGER
Comment: Customer-SK
---------------------
Column: FACT_SALES.REVENUE
Nullable: 0
Datatype: DECIMAL(10,2)
Comment:
---------------------
Column: FACT_SALES.FACT_SALES_PK
Nullable:
Datatype:
Comment:
---------------------
Column: FACT_SALES.
Nullable:
Datatype:
Comment:
---------------------
+++++++++++++ PRIMARY KEY COLS +++++++++++++
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_CUSTOMER.CUSTOMER_SID
PK-Col.: DIM_CUSTOMER.
PK-Col.: DIM_PRODUCT.
PK-Col.: DIM_PRODUCT.
PK-Col.: DIM_PRODUCT.PRODUCT_SID
PK-Col.: DIM_PRODUCT.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.
PK-Col.: DIM_DATE.DATE_ID
PK-Col.: DIM_INVENTORY.
PK-Col.: DIM_INVENTORY.
PK-Col.: DIM_INVENTORY.INVENTORY_SID
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.
PK-Col.: FACT_SALES.DATE_ID
PK-Col.: FACT_SALES.

Here is how the datamodel from the xml looks like in the wwwsqldesigner

Any suggestions how to handle this problem?

Thank you and cheers!

Body:
In the same way that you use $xml->table in your outer loop, you also need to get the inner loop to just select the <row> elements.

So your inner foreach loop becomes..

foreach ($table->row as $row) {

As you can see, your picking up all the subelements of <table>, this will limit it to just the <row> ones.


来源: stackexchange

问:
Modeling relationships with domain models
In my system, an User can be member of a Team.

I got a domain model called Team which contains id, name, member_count and is_channel. So when I fetch teams in the repository I retrieve the Team domain model.

How would I model the relation between a User and a Team? Because when talking about the relation I don’t care about the member_count and is_channel from the Team model. I even have extra data in the relation which is a role_type.

Should I create a domain model for the relation called TeamScope or something? That contains id, user_id, team_id, role_type?

答:
See my comments on your question regarding your use of terms (model, class, association). I'm assuming you are misusing them when I wrote my answer.

How would I model the relation between a User and a Team? Because when talking about the relation I don’t care about the member_count and is_channel from the Team model (sic). I even have extra data in the relation which is a role_type.

You could use an association class in your domain model to represent this.

Membership can capture the role_type, which really is linked to the association as you have figured out.

member_count is represented with a / at the start, indicating that you'll derive its value from the multiplicity (it's a count of the number of members associated with the team).

You tagged node.js in your question, so I'm going to point to how to implement association classes in Java (not exactly your case, but in Node.js it should be easy to apply).

ContentLicense: CC BY-SA 3.0


问:
How do I query msSFU30MaxUidNumber attribute with Powershell?
Does anyone know of a way to query this UNIX attribute msSFU30MaxUidNumber
in Active Directory with Powershell? I'm working on a script that will assign Unix attribute to users as needed. I also have the Quest AD Powershell module available.</p>

答:
I borrowed this to set UNIX attributes (NISdomain, GID, loginshell, UIDnumber, UID) http://danieltromp.com/2014/06/09/powershell-ad-enable-unix-attributes/.

I updated it so it also updates the stored msSFU30MaxUidNumber. All scripts I've seen forget this.
Prevents issues with duplicate UIDnumbers if you use ADUC to set UNIX attributes in the future (or even if you run the script again against another OU):

```<code>Remove-Variable -Name * -Force -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
$NIS = Get-ADObject "CN=DOMAIN,CN=ypservers,CN=ypServ30,CN=RpcServices,CN=System,DC=Domain,DC=com" -Properties:* #Get NIS server information
$maxUid = $NIS.msSFU30MaxUidNumber #Get the last used User ID

$usuarios = Get-ADUser -Filter * -SearchBase "OU=NAME,OU=NAME,OU=NAME,DC=Domain,DC=com" -Properties:* #Get all users
foreach($usr in $usuarios)
{
  if ($usr.mssfu30nisdomain -eq $null){
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{mssfu30nisdomain="Domain"} #Enable NIS
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{gidnumber="10005"} #Set Group ID
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{loginShell="/bin/bash"} #Set Login Shell
  $maxUid++ #Raise the User ID number
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{uidnumber=$maxUid} #Set User ID number
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{uid=$usr.SamAccountName} #Set UID
  Write-Host -Backgroundcolor Green -Foregroundcolor Black $usr.SamAccountName changed #Write Changed Username to console
  }
  else{Write-Host -Backgroundcolor Yellow -Foregroundcolor Black $usr.SamAccountName unchanged} #Write Unchanged Username to console with a yellow background
}
$NIS | Set-ADObject -Replace @{msSFU30MaxUidNumber = $maxuid++}
$NIS | Set-ADObject -Replace @{msSFU30MaxUidNumber = $maxuid++}
</code>```

Body:
I borrowed this to set UNIX attributes (NISdomain, GID, loginshell, UIDnumber, UID) http://danieltromp.com/2014/06/09/powershell-ad-enable-unix-attributes/.

I updated it so it also updates the stored msSFU30MaxUidNumber. All scripts I've seen forget this.
Prevents issues with duplicate UIDnumbers if you use ADUC to set UNIX attributes in the future (or even if you run the script again against another OU):

Remove-Variable -Name * -Force -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
$NIS = Get-ADObject "CN=DOMAIN,CN=ypservers,CN=ypServ30,CN=RpcServices,CN=System,DC=Domain,DC=com" -Properties:* #Get NIS server information
$maxUid = $NIS.msSFU30MaxUidNumber #Get the last used User ID

$usuarios = Get-ADUser -Filter * -SearchBase "OU=NAME,OU=NAME,OU=NAME,DC=Domain,DC=com" -Properties:* #Get all users
foreach($usr in $usuarios)
{
  if ($usr.mssfu30nisdomain -eq $null){
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{mssfu30nisdomain="Domain"} #Enable NIS
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{gidnumber="10005"} #Set Group ID
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{loginShell="/bin/bash"} #Set Login Shell
  $maxUid++ #Raise the User ID number
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{uidnumber=$maxUid} #Set User ID number
  Set-ADUser -Identity "$($usr.SamAccountName)" -Replace @{uid=$usr.SamAccountName} #Set UID
  Write-Host -Backgroundcolor Green -Foregroundcolor Black $usr.SamAccountName changed #Write Changed Username to console
  }
  else{Write-Host -Backgroundcolor Yellow -Foregroundcolor Black $usr.SamAccountName unchanged} #Write Unchanged Username to console with a yellow background
}
$NIS | Set-ADObject -Replace @{msSFU30MaxUidNumber = $maxuid++}
$NIS | Set-ADObject -Replace @{msSFU30MaxUidNumber = $maxuid++}


问:
Azure App Service + Docker Autodeploy?
I have setup an Azure App Service to host a docker container.  This is all running fine -- pointing at a private Docker repository/image, using the latest tag.

I would like to be able to publish a new Dockage image from my CI server to the Docker repository under the latest tag and somehow trigger the App Service to pick up that there is a change of the latest image.

It seems I can trigger the change by modifying an Application Setting on the App Service and saving it -- but this does not seem like the correct way to handle it.

Is there a best practise for this kind of deployment?

答:
In the properties section of the web app you'll find a DEPLOYMENT TRIGGER URL.

This URL should point to the /deploy endpoint. Remove that part and use the /docker/hook endpoint.
Your URL should look something like this: https://xxxx.scm.azurewebsites.net/docker/hook

If you POST to that URL with empty body it will trigger a deployment using the latest docker image.

Title: Azure App Service + Docker Autodeploy?


问:
Android: EditText in ListView
I would like to have a custom ListView, where each row contains an EditText field, that may be edited by the user. But when I click on one of the EditTexts I lose the focus, and can't type text there (I suppose because the other rows are redrawn and get the focus).
What can I do?</p>

答: You must set the focusable of the edittext (EditText.setFocusable(true))</p>

OwnerDisplayName: Yossi

Title: Android: EditText in ListView

ContentLicense: CC BY-SA 2.5


问:
Python: for loops if self.bricks[i - 1].rect.colliderect(self.ball.rect): IndexError: list index out of range
So, I'm making a breakout clone, and I'm having a rendering issue, I think. What I have coded it to do is when the ball hits a brick, it A.) bounces the ball B.) makes the brick disappear, and C.) removes the brick from a list of all bricks so that it doesn't render it again. It does this with a for loop:

```<code>for i in range(len(self.bricks)):
    if self.bricks[i - 1].rect.colliderect(self.ball.rect):
      if self.ball.rect.right > self.bricks[i - 1].rect.right or self.ball.rect.left < self.bricks[i - 1].rect.left:
        self.ball.speed[0] *= -1
      elif self.ball.rect.top > self.bricks[i - 1].rect.top or self.ball.rect.bottom < self.bricks[i - 1].rect.bottom:
        self.ball.speed[1] *= -1
    self.bricks[i - 1].image.fill([0,0,0])
    self.bricks.pop(i - 1)
</code>```

the way that I did it before wouldn't make the brick disappear, it would stay on the screen but be removed from the list. I've tried several solutions and can't come up with anything better than this. The problem is that now it tells me that self.brick[i - 1] is out of range. I think that it's popping the the brick before running the rest of the loop. I don't know why it would, but its the only thing that makes sense to me.

Any help is appreciated. If you need to see more code then just ask.

Anthony Fancella

答: range(len(self.bricks)) is precomputed before the loop is executed. However, you are popping objects out of the list during the iteration, and thus i will be out of bounds. Try marking the bricks to be removed during this iteration by adding a new property on the brick class/object and then removing them all at once afterwards.

Body:
So, I'm making a breakout clone, and I'm having a rendering issue, I think. What I have coded it to do is when the ball hits a brick, it A.) bounces the ball B.) makes the brick disappear, and C.) removes the brick from a list of all bricks so that it doesn't render it again. It does this with a for loop:

for i in range(len(self.bricks)):
    if self.bricks[i - 1].rect.colliderect(self.ball.rect):
      if self.ball.rect.right > self.bricks[i - 1].rect.right or self.ball.rect.left < self.bricks[i - 1].rect.left:
        self.ball.speed[0] *= -1
      elif self.ball.rect.top > self.bricks[i - 1].rect.top or self.ball.rect.bottom < self.bricks[i - 1].rect.bottom:
        self.ball.speed[1] *= -1
    self.bricks[i - 1].image.fill([0,0,0])
    self.bricks.pop(i - 1)

the way that I did it before wouldn't make the brick disappear, it would stay on the screen but be removed from the list. I've tried several solutions and can't come up with anything better than this. The problem is that now it tells me that self.brick[i - 1] is out of range. I think that it's popping the the brick before running the rest of the loop. I don't know why it would, but its the only thing that makes sense to me.

Any help is appreciated. If you need to see more code then just ask.

Anthony Fancella


问:
Codeigniter pagination not adding new page
I tried to use the codeigniter pagination library and it doesn't work for me. I'm trying to have 24 products on the all products page and when there's more products it should add a link to the next page. So right now I have more than 24 products on the site and no new page is added.

with this line I'm getting all the products from product table:

```<code>$data['products'] = $this->Product_model->selectProducts();
</code>```

This is my controller function:

```<code>  public function pagination() {
        //load pagination library
        $this->load->library('pagination');
        //laad Products_model voor pagination
        $this->load->model('Products_model');
        $this->load->model('Product_model');

        $config = array();
        $config["base_url"] = base_url() . "AlleCadeausController/pagination";
        $config["total_rows"] = $this->products->record_count();
        $config["per_page"] = 24;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['products'] = $this->Product_model->selectProducts();
        $data["links"] = $this->pagination->create_links();

        $this->load->view("allecadeaus", $data);
    }
</code>```

My model (Products_model):

```<code><?php
class Products extends CI_Model
{

    public function __construct() {
        parent::__construct();
    }

    public function record_count() {
        return $this->db->count_all("products");
    }

    public function fetch_products() {
        $query = $this->db->get("products");

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }
}

?>
</code>```

This is my view file (I don't know if I need to add anything in the view file for the pagination to work):

```<code><?php   include_once ('templates/header.php');  ?>

<!-- Alle cadeaus gele title bovenaan pagina -->
<div class="all-content">
    <div class="row">
        <div class="col-lg-12 bg-warning header-text" style="font-size:25px;font-weight: bold;">
            <center>Alle cadeaus</center>
        </div>
        </div>

 <hr />

<br>

<!-- Cadeau categorie side menu -->

    <div class="row">
            <div class="menu">
                <div id="categorymenu">
                    <center>  <h3>Categorieën</h3> </center>

 <div class="categorieen">
      <?php foreach (get_categories_h() as $category) : ?>
  <input id="box1" type="checkbox" />
  <label for="box1"><a class="listcat" href="<?php echo base_url().'Product/category/' . $category->id; ?>"> <?php echo $category->name; ?></a></label>
  <?php endforeach; ?>
</div>

                </div>
            </div>

<!-- Laat cadeau zien op alle cadeaus pagina -->

<div class="main">
<?php foreach($products as $product) : ?>

   <a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>"> <div class="main-products">

          <img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">

        <div class="product_naam"><h3><?php echo $product["product_naam"]; ?></h3></div>
        <div class="ophaal_plaats">
           <?php  echo $product["ophaal_plaats"]; ?>
        </div>
        </a>

         <div class="aangeboden_door">
         <?php
          //Here is the active record query which is getting the 'voorname' and other data
          $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();
          // you can print_r($userarray); for see the array you get
      ?>
      <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
      <td><?php echo $userarray['voornaam'];?></td>
    </tr>

        </div>

</div>

<?php endforeach; ?>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>

 <?php   include_once ('templates/footer.php');?>
</code>```

答:
Below is the fine working pagination code, hope it will fix the issue you have.

Model

```<code>public function fetch_oldusers($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get_where('dc_user',array('Is_Hidden'=>0));

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
    }
</code>```

View

```<code> <div class="text-center"><nav aria-label="Page navigation">
                                            <ul class="pagination">

                                                <li><?php echo $links; ?></li>

                                            </ul>
                                        </nav></div>
</code>```

Controller

```<code>public function Users()
    {
        $config = array();
        $config["base_url"] = base_url() . "master/Users";
        $config["total_rows"] = $this->bm->record_countolduser();
        $config['use_page_numbers'] =True;

        $config['cur_tag_open'] = '<a><b class="text-success">';
        $config['cur_tag_close'] = '</b></a>';
        $config["per_page"] =10;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['title'] = "Users List";
        $data["posts"] = $this->bm->fetch_oldusers($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();
        $this->load->view('Admin/header',$data);
        $this->load->view('Admin/nav');
        $this->load->view('Admin/sidebar');
        $this->load->view('Admin/old_user', $data);
        $this->load->view('Admin/footer');
    }
</code>```

It is working fine for me.

Body:
I tried to use the codeigniter pagination library and it doesn't work for me. I'm trying to have 24 products on the all products page and when there's more products it should add a link to the next page. So right now I have more than 24 products on the site and no new page is added.

with this line I'm getting all the products from product table:

$data['products'] = $this->Product_model->selectProducts();

This is my controller function:

  public function pagination() {
        //load pagination library
        $this->load->library('pagination');
        //laad Products_model voor pagination
        $this->load->model('Products_model');
        $this->load->model('Product_model');

        $config = array();
        $config["base_url"] = base_url() . "AlleCadeausController/pagination";
        $config["total_rows"] = $this->products->record_count();
        $config["per_page"] = 24;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['products'] = $this->Product_model->selectProducts();
        $data["links"] = $this->pagination->create_links();

        $this->load->view("allecadeaus", $data);
    }

My model (Products_model):

<?php
class Products extends CI_Model
{

    public function __construct() {
        parent::__construct();
    }

    public function record_count() {
        return $this->db->count_all("products");
    }

    public function fetch_products() {
        $query = $this->db->get("products");

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
   }
}

?>

This is my view file (I don't know if I need to add anything in the view file for the pagination to work):

<?php   include_once ('templates/header.php');  ?>

            Alle cadeaus

Categorieën

      <?php foreach (get_categories_h() as $category) : ?>
  <input id="box1" type="checkbox" />
  <a class="listcat" href="<?php echo base_url().'Product/category/' . $category->id; ?>"> <?php echo $category->name; ?>
  <?php endforeach; ?>

<?php foreach($products as $product) : ?>

   <a href="<?php echo base_url() ?>/Product/details/<?php echo $product["product_id"]; ?>">

          <img id="cadeaufoto" src="<?php echo base_url(); ?>upload/<?php echo $product["product_foto_thumb"]; ?>">

<?php echo $product["product_naam"]; ?>

           <?php  echo $product["ophaal_plaats"]; ?>

         <?php
          //Here is the active record query which is getting the 'voorname' and other data
          $userarray = $this->db->get_Where('users', array('user_id'=>$product["user_id"]))->row_array();
          // you can print_r($userarray); for see the array you get
      ?>
      <a href="<?php echo base_url() . 'User/userdetails/'.$product['user_id'];?>">
      <?php echo $userarray['voornaam'];?>

<?php endforeach; ?>

 <?php   include_once ('templates/footer.php');?>

Body:
Below is the fine working pagination code, hope it will fix the issue you have.

Model

public function fetch_oldusers($limit, $start) {
        $this->db->limit($limit, $start);
        $query = $this->db->get_where('dc_user',array('Is_Hidden'=>0));

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $data[] = $row;
            }
            return $data;
        }
        return false;
    }

View

 <div class="text-center"><nav aria-label="Page navigation">
                                            <ul class="pagination">

                                                <li><?php echo $links; ?></li>

                                            </ul>
                                        </nav></div>

Controller

public function Users()
    {
        $config = array();
        $config["base_url"] = base_url() . "master/Users";
        $config["total_rows"] = $this->bm->record_countolduser();
        $config['use_page_numbers'] =True;

        $config['cur_tag_open'] = '<a><b class="text-success">';
        $config['cur_tag_close'] = '</b></a>';
        $config["per_page"] =10;
        $config["uri_segment"] = 3;

        $this->pagination->initialize($config);

        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data['title'] = "Users List";
        $data["posts"] = $this->bm->fetch_oldusers($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();
        $this->load->view('Admin/header',$data);
        $this->load->view('Admin/nav');
        $this->load->view('Admin/sidebar');
        $this->load->view('Admin/old_user', $data);
        $this->load->view('Admin/footer');
    }

It is working fine for me.


问:
Sharepoint Online Web Api Bearer Error 401
I want to get the Web Api work on SPO.
I did the example code of https://blogs.msmvps.com/windsor/2017/03/12/walkthrough-building-a-custom-web-api-for-use-with-sharepoint-online/ and it does works fine.

Now I want to add a get-Request to SPO, which works on-premise as well.
I tried reading a file with clientcontext and Webclient, which I would to prefer.
But I always get an 401 error "the remote server returned an error (401) unauthorized"

I do not understand the 401 error, because the example code works fine. I do not see any differences.

```<code>        public async Task<IEnumerable<string>> GetUserInfo(string sharePointUrl)
    {
        var results = new List<string>();

        try
        {
            var userToken = this.Request.Headers.Authorization.Parameter;
            var newToken = await GetSharePointAccessToken(sharePointUrl, userToken);

            using (var context = new ClientContext(sharePointUrl))
            {
                context.ExecutingWebRequest +=
                    (s, e) => e.WebRequestExecutor.WebRequest.Headers.Add(
                    "Authorization", "Bearer " + newToken);

                var web = context.Web;
                var user = web.CurrentUser;
                context.Load(user);
                context.ExecuteQuery();

                results.Add(user.Title);
                results.Add(user.LoginName);
                results.Add(user.Email);
            }
        }
        catch (Exception ex)
        {
            results.Add(ex.ToString());
        }

        return results;
    }
</code>```

Here is my code snippet:

```<code>        public async Task<IEnumerable<LessVariables>> GetLess(string url, string id)
    {
       [...]

        var list = new List<LessVariables>();

        try
        {
            var userToken = this.Request.Headers.Authorization.Parameter;
            var newToken = await GetSharePointAccessToken(url, userToken);
            var siteUrl = url;
            var file = siteUrl + "/Style Library/xxx/less/" + id + ".less";
            var files = "/Style Library/xxx/less/" + id + ".less";

            using (var context = new ClientContext(url))
            {
                context.ExecutingWebRequest +=
                    (s, e) => e.WebRequestExecutor.WebRequest.Headers.Add(
                    "Authorization", "Bearer " + newToken);
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.ExecuteQuery();
                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, files);

// After this line I get the 401 error

                using (WebClient client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + newToken;
                    //client.UseDefaultCredentials = true;
                    string s = client.DownloadString(file);

// After try to DownloadString I got the 401 error.

                    var regex = new Regex(@"(?<name>[@].*:)\s(?<value>.*)(;)");
                    var matches = regex.Matches(s);
                    var parameters = new List<KeyValuePair<string, string>>();

                    foreach (var match in matches.Cast<Match>())
                    {
                        list.Add(new LessVariables
                        {
                            key = match.Groups["name"].Value,
                            value = match.Groups["value"].Value
                        });
                    }
                }
            }
            return list;
        }
        catch (Exception ex)
        { [...]

        }
    }
</code>```

答:
The reason you are experiencing this behavior while reading file is that the request http://<site url>//<folder name>/<file name> causes redirect but WebClient strip out authorization headers (such as Bearer token) when following a redirect. The similar behavior has been explained in this post.

Since you are targeting SharePoint Online, you could retrieve a file content using a different approach that does not cause a redirect, for example using SharePoint REST API, in particular the following File resource endpoint:

```<code>Url: http://<site url>/_api/web/getfilebyserverrelativeurl('/<folder name>/<file name>')/$value
Method: Get
</code>```

Example

```<code>using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + accessToken;
    var content = client.DownloadString("https://contoso.sharepoint.com/_api/web/getfilebyserverrelativeurl('/Shared%20Documents/Guide.docx')/$value");
    //...
}
</code>```

Body:
I want to get the Web Api work on SPO.
I did the example code of https://blogs.msmvps.com/windsor/2017/03/12/walkthrough-building-a-custom-web-api-for-use-with-sharepoint-online/ and it does works fine.

Now I want to add a get-Request to SPO, which works on-premise as well.
I tried reading a file with clientcontext and Webclient, which I would to prefer.
But I always get an 401 error "the remote server returned an error (401) unauthorized"

I do not understand the 401 error, because the example code works fine. I do not see any differences.

        public async Task<IEnumerable<string>> GetUserInfo(string sharePointUrl)
    {
        var results = new List<string>();

        try
        {
            var userToken = this.Request.Headers.Authorization.Parameter;
            var newToken = await GetSharePointAccessToken(sharePointUrl, userToken);

            using (var context = new ClientContext(sharePointUrl))
            {
                context.ExecutingWebRequest +=
                    (s, e) => e.WebRequestExecutor.WebRequest.Headers.Add(
                    "Authorization", "Bearer " + newToken);

                var web = context.Web;
                var user = web.CurrentUser;
                context.Load(user);
                context.ExecuteQuery();

                results.Add(user.Title);
                results.Add(user.LoginName);
                results.Add(user.Email);
            }
        }
        catch (Exception ex)
        {
            results.Add(ex.ToString());
        }

        return results;
    }

Here is my code snippet:

        public async Task<IEnumerable<LessVariables>> GetLess(string url, string id)
    {
       [...]

        var list = new List<LessVariables>();

        try
        {
            var userToken = this.Request.Headers.Authorization.Parameter;
            var newToken = await GetSharePointAccessToken(url, userToken);
            var siteUrl = url;
            var file = siteUrl + "/Style Library/xxx/less/" + id + ".less";
            var files = "/Style Library/xxx/less/" + id + ".less";

            using (var context = new ClientContext(url))
            {
                context.ExecutingWebRequest +=
                    (s, e) => e.WebRequestExecutor.WebRequest.Headers.Add(
                    "Authorization", "Bearer " + newToken);
                context.AuthenticationMode = ClientAuthenticationMode.Default;
                context.ExecuteQuery();
                var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, files);

// After this line I get the 401 error

                using (WebClient client = new WebClient())
                {
                    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + newToken;
                    //client.UseDefaultCredentials = true;
                    string s = client.DownloadString(file);

// After try to DownloadString I got the 401 error.

                    var regex = new Regex(@"(?<name>[@].*:)\s(?<value>.*)(;)");
                    var matches = regex.Matches(s);
                    var parameters = new List<KeyValuePair<string, string>>();

                    foreach (var match in matches.Cast<Match>())
                    {
                        list.Add(new LessVariables
                        {
                            key = match.Groups["name"].Value,
                            value = match.Groups["value"].Value
                        });
                    }
                }
            }
            return list;
        }
        catch (Exception ex)
        { [...]

        }
    }

Body:
The reason you are experiencing this behavior while reading file is that the request http://<site url>//<folder name>/<file name> causes redirect but WebClient strip out authorization headers (such as Bearer token) when following a redirect. The similar behavior has been explained in this post.

Since you are targeting SharePoint Online, you could retrieve a file content using a different approach that does not cause a redirect, for example using SharePoint REST API, in particular the following File resource endpoint:

Url: http://<site url>/_api/web/getfilebyserverrelativeurl('/<folder name>/<file name>')/$value
Method: Get

Example

using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.Authorization] = "Bearer " + accessToken;
    var content = client.DownloadString("https://contoso.sharepoint.com/_api/web/getfilebyserverrelativeurl('/Shared%20Documents/Guide.docx')/$value");
    //...
}


问:
How to remove duplicate values of only one column element based on another column
I have data where I have one element of interest (111) in a column. My data looks something like this:

```<code>pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
        rep(222,5)),B= c(rep(1,9), rep(2,10)))

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   222 1
7   222 1
8   222 1
9   222 1
10  111 2
11  111 2
12  111 2
13  111 2
14  111 2
15  222 2
16  222 2
17  222 2
18  222 2
19  222 2
</code>```

I want to collapse all of only variable 222 and leave all 111 untouched throughout my data based upon the IDs in column B like so:

```<code>     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   111 2
7   111 2
8   111 2
9   111 2
10  111 2
11  222 2
</code>```

All I have been able to find that is close reduces all the variables (both 111 and 222).

```<code>library(data.table)
dat <- as.data.table(pcp2, key = "B")
data <- dat[, by = key(dat)][!duplicated(A == "222")]
</code>```

as follows:

```<code>   A    B
1 111   1
2 222   2
</code>```

I've played around with various iterations of this code and others, but other things I've tried as well have just gotten my data down to two rows or collapsed both 111 and 222. I.e. this wouldn't be sufficient:

```<code>   A  B
1 111 1
2 222 2
3 111 2
4 222 2
</code>```

Does anyone have any guidance for how you would maintain the 111 and collapse the 222 within one column based on another column like the example (B in this case)? I know other examples are similar but none seem to give the option to specify not collapsing a particular variable within one column while collapsing the other(s).

答:
You can add a counter for the uncollapsed rows:

```<code>dat[, r := rowid(A)*(A == 111)]
unique(dat, by=c("B","r"))[, !"r"]

      A B
 1: 111 1
 2: 111 1
 3: 111 1
 4: 111 1
 5: 222 1
 6: 111 2
 7: 111 2
 8: 111 2
 9: 111 2
10: 111 2
11: 222 2
</code>```

(This requires data.table, while Gregor's answer works in base R as well.)

Body:
I have data where I have one element of interest (111) in a column. My data looks something like this:

pcp2 <- data.frame(A = c(rep(111, 4), rep(222, 5), rep(111,5),
        rep(222,5)),B= c(rep(1,9), rep(2,10)))

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   222 1
7   222 1
8   222 1
9   222 1
10  111 2
11  111 2
12  111 2
13  111 2
14  111 2
15  222 2
16  222 2
17  222 2
18  222 2
19  222 2

I want to collapse all of only variable 222 and leave all 111 untouched throughout my data based upon the IDs in column B like so:

     A  B
1   111 1
2   111 1
3   111 1
4   111 1
5   222 1
6   111 2
7   111 2
8   111 2
9   111 2
10  111 2
11  222 2

All I have been able to find that is close reduces all the variables (both 111 and 222).

library(data.table)
dat <- as.data.table(pcp2, key = "B")
data <- dat[, by = key(dat)][!duplicated(A == "222")]

as follows:

   A    B
1 111   1
2 222   2

I've played around with various iterations of this code and others, but other things I've tried as well have just gotten my data down to two rows or collapsed both 111 and 222. I.e. this wouldn't be sufficient:

   A  B
1 111 1
2 222 2
3 111 2
4 222 2

Does anyone have any guidance for how you would maintain the 111 and collapse the 222 within one column based on another column like the example (B in this case)? I know other examples are similar but none seem to give the option to specify not collapsing a particular variable within one column while collapsing the other(s).

Body:
You can add a counter for the uncollapsed rows:

dat[, r := rowid(A)*(A == 111)]
unique(dat, by=c("B","r"))[, !"r"]

      A B
 1: 111 1
 2: 111 1
 3: 111 1
 4: 111 1
 5: 222 1
 6: 111 2
 7: 111 2
 8: 111 2
 9: 111 2
10: 111 2
11: 222 2

(This requires data.table, while Gregor's answer works in base R as well.)


问:
Looking for the biggest number before and after 'i' in list
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3

I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?

'a' is the list in my code

```<code>a = [1, 3, 2, 4, 3]
for i in a:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)
</code>```

答:
The only mistake in your code is the for i in a loop, which loops throgh i = 1,3,2,4,3 and not i=0,1,2,3,4

The following piece of code works

```<code>a=[1,3,2,4,3]
for i in range(len(a)) :
    print max(i,max(a[:i+1]))
    print max(i,max(a[i:]))
</code>```

Body:
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3

I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?

'a' is the list in my code

a = [1, 3, 2, 4, 3]
for i in a:
    west = a[0:i]
    east = a[i:int(len(a))]
    if max(west) > i:
        print(max(west))
    else:
        print(i)
    if max(east) > i:
        print(max(east))
    else:
        print(i)

Body:
The only mistake in your code is the for i in a loop, which loops throgh i = 1,3,2,4,3 and not i=0,1,2,3,4

The following piece of code works

a=[1,3,2,4,3]
for i in range(len(a)) :
    print max(i,max(a[:i+1]))
    print max(i,max(a[i:]))


问:
Translate a string from UTF-8 to ISO-8859-1
I'm reading some text data from my database that is in UTF-8 charset. But i need to generate a file with ISO-8859-1 charset.

To do this I'm using the following code.

```<code>StringBuilder filaStr = new StringBuilder();
filaStr.append("INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN");//this is a UTF-8 string got from my database
Charset utf8 = Charset.forName("UTF-8");
Charset iso8859_1 = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = utf8.newDecoder();
CharsetEncoder encoder = iso8859_1.newEncoder();
CharBuffer decodedCB = decoder.decode(ByteBuffer.wrap(filaStr.toString().getBytes()));
ByteBuffer encodedBB = encoder.encode(decodedCB);
pw.write(new String(encodedBB.array()));//pw is the PrintWriter that writes in the file
pw.write(new String(encodedBB.array(), iso8859_1));
</code>```

When I open the file with the text editor using UTF-8 charset I see this:

```<code>INGENIER�A DE EJECUCI�N EN ADMINISTRACI�N
INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN
</code>```

And when I open it using ISO-8859-1 I see this:

```<code>INGENIERï¿½A DE EJECUCIï¿½N EN ADMINISTRACIï¿½N
INGENIERÃA DE EJECUCIÃN EN ADMINISTRACIÃN
</code>```

The desired result is to print INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN in ISO-8859-1 charset.

答:
The problem was the PrintWriter, this must be initialized with the desired charset.

PrintWriter pw = new PrintWriter(file, "ISO-8859-1"); Solved the problem and even no CharsetDecoder and CharsetEncoder were needed.

Body:
I'm reading some text data from my database that is in UTF-8 charset. But i need to generate a file with ISO-8859-1 charset.

To do this I'm using the following code.

StringBuilder filaStr = new StringBuilder();
filaStr.append("INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN");//this is a UTF-8 string got from my database
Charset utf8 = Charset.forName("UTF-8");
Charset iso8859_1 = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = utf8.newDecoder();
CharsetEncoder encoder = iso8859_1.newEncoder();
CharBuffer decodedCB = decoder.decode(ByteBuffer.wrap(filaStr.toString().getBytes()));
ByteBuffer encodedBB = encoder.encode(decodedCB);
pw.write(new String(encodedBB.array()));//pw is the PrintWriter that writes in the file
pw.write(new String(encodedBB.array(), iso8859_1));

When I open the file with the text editor using UTF-8 charset I see this:

INGENIER�A DE EJECUCI�N EN ADMINISTRACI�N
INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN

And when I open it using ISO-8859-1 I see this:

INGENIERï¿½A DE EJECUCIï¿½N EN ADMINISTRACIï¿½N
INGENIERÃA DE EJECUCIÃN EN ADMINISTRACIÃN

The desired result is to print INGENIERÍA DE EJECUCIÓN EN ADMINISTRACIÓN in ISO-8859-1 charset.


问:
How to conditionally update multiple rows using knex with postgresql?
Here is an example of the table layout;

```<code>CREATE TABLE test (id1 int, id2 int, auth boolean);
INSERT INTO test VALUES (1, 1, true);
</code>```

I'm trying to convert the following query into the knex.js framework;

```<code>UPDATE test as t
    SET auth = c.auth
    from (values (1, 1, false),(2, 1, false))
    as c(id1, id2, auth)
    where c.id1 = t.id1 AND c.id2 = t.id2;

select * from test
</code>```

Here is a fiddle: http://sqlfiddle.com/#!17/62529/8

I've looked around, and found the following resources: github issue, update multiple queries (no conditional)

After trying to implement these methods, I'm still coming up unsuccessful and not sure where I'm going wrong.

I've tried to brute force the query by wrapping my original postgres query into a knex.raw statement, like:

```<code>return knex.raw('' +
    'UPDATE test as t ' +
    'SET auth = c.auth ' +
    'from (values (1, 1, false),(2, 1, false))' +
    'as c(id1, id2, auth)' +
    'where c.id1 = t.id1 AND c.id2 = t.id2;')
</code>```

which comes up with the error syntax error on or near « as »

I've also tried to follow the github issue advice by using;

```<code> let string = knex
        .into('test t')
        .update('auth, c.auth')
        .values('(1, 1, false), (2, 1, false)')
        .where(knex.raw('c.id1 = t.id1 AND c.id2 = t.id2'))
        .toString()

        knex.raw(string)
</code>```

which returns the error 'values' is not a function.

I am new to both knex and postgres, so I'm not sure if I'm missing something painfully obvious! Any help is much appreciated.

答:
In the raw version it looks like you may need a space before the 'as' at false))as to become false)) as...

I saw this by adding the .on('query-error', as shown below. With this info you should be able to determine whether it's a SQL engine error vs a Knex error, and if the SQL was generated as you desired.

```<code>return knex.raw('' +
    'UPDATE test as t ' +
    'SET auth = c.auth ' +
    'from (values (1, 1, false),(2, 1, false)) ' +
    'as c(id1, id2, auth)' +
    'where c.id1 = t.id1 AND c.id2 = t.id2;')
    .on('query-error', function(ex, obj) {
        console.log("KNEX query-error ex:", ex, "obj:", obj);
    }).then(function(retVal) {
        console.log("Query ran okay.");
        return retVal;
    });
</code>```

There is also .on('query', which will give you info about the query to help get it right. see: http://knexjs.org/#Interfaces-query

Regards,
Gary.

Body:
Here is an example of the table layout;

CREATE TABLE test (id1 int, id2 int, auth boolean);
INSERT INTO test VALUES (1, 1, true);

I'm trying to convert the following query into the knex.js framework;

UPDATE test as t
    SET auth = c.auth
    from (values (1, 1, false),(2, 1, false))
    as c(id1, id2, auth)
    where c.id1 = t.id1 AND c.id2 = t.id2;

select * from test

Here is a fiddle: http://sqlfiddle.com/#!17/62529/8

I've looked around, and found the following resources: github issue, update multiple queries (no conditional)

After trying to implement these methods, I'm still coming up unsuccessful and not sure where I'm going wrong.

I've tried to brute force the query by wrapping my original postgres query into a knex.raw statement, like:

return knex.raw('' +
    'UPDATE test as t ' +
    'SET auth = c.auth ' +
    'from (values (1, 1, false),(2, 1, false))' +
    'as c(id1, id2, auth)' +
    'where c.id1 = t.id1 AND c.id2 = t.id2;')

which comes up with the error syntax error on or near « as »

I've also tried to follow the github issue advice by using;

 let string = knex
        .into('test t')
        .update('auth, c.auth')
        .values('(1, 1, false), (2, 1, false)')
        .where(knex.raw('c.id1 = t.id1 AND c.id2 = t.id2'))
        .toString()

        knex.raw(string)

which returns the error 'values' is not a function.

I am new to both knex and postgres, so I'm not sure if I'm missing something painfully obvious! Any help is much appreciated.

Body:
In the raw version it looks like you may need a space before the 'as' at false))as to become false)) as...

I saw this by adding the .on('query-error', as shown below. With this info you should be able to determine whether it's a SQL engine error vs a Knex error, and if the SQL was generated as you desired.

return knex.raw('' +
    'UPDATE test as t ' +
    'SET auth = c.auth ' +
    'from (values (1, 1, false),(2, 1, false)) ' +
    'as c(id1, id2, auth)' +
    'where c.id1 = t.id1 AND c.id2 = t.id2;')
    .on('query-error', function(ex, obj) {
        console.log("KNEX query-error ex:", ex, "obj:", obj);
    }).then(function(retVal) {
        console.log("Query ran okay.");
        return retVal;
    });

There is also .on('query', which will give you info about the query to help get it right. see: http://knexjs.org/#Interfaces-query

Regards,
Gary.


问:
Angular 2 - change videos src after clicking on div
I have problem with video src. After clicking on my div (camera) in source code I can see that video src is changing properly, but videos arent being played. What should I do?

Below are my components - streaming.component.ts (responsible for displaying videos of chosen camera component) and camera.component.ts (for viewing icon with camera name)

streaming.component.ts

```<code>import {Component} from '@angular/core';
import {CameraComponent} from '../camera/camera.component';

@Component({
   moduleId: module.id,
   selector: 'streaming',
   template: `
            <camera cameraName="Kamera 1" (click)='cameraStream("sample.mp4")'></camera>
            <camera cameraName="Kamera 2" (click)='cameraStream("sample2.mp4")'></camera>
            <camera cameraName="Kamera 3" (click)='cameraStream("sample3.mp4")'></camera>
            <camera cameraName="Kamera 4" (click)='cameraStream("sample4.mp4")'></camera>
            <video width="800" controls>
                <source src = "{{cameraSrc}}" type="video/mp4">
                Your browser does not support HTML5 video.
            </video>
            <p>{{cameraSrc}}</p>
            `,
directives: [CameraComponent]
})
export class StreamingComponent {

 cameraSrc:string;
 constructor() { }

 cameraStream(chosenCamera :string){
    this.cameraSrc=chosenCamera;
  }
 }
</code>```

Videos are working ,because when I put

```<code><source src = "{{cameraSrc}}" type="video/mp4">
</code>```

everything is fine.

camera.component.ts

```<code>import { Component ,Input } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'camera',
    templateUrl: 'camera.component.html'
})
export class CameraComponent {
     @Input() cameraName:string = "";

     constructor() { }

 }
</code>```

Here is what I get after clicking on camera2 for example
.

答:
I had a similar problem... I settled with using a backing array

```<code><span *ngFor="let video of app.videoPlayer.videos">
<img src="{{video.artBig()}}" style="width: 1920px;height: 1080px;top: 0px;left:0px;z-index: -1; position: absolute;"/>

<video preload="auto" crossorigin controls autoplay
   style="width: 1920px;height: 1080px;top: 0px;left:0px;z-index:1; position: absolute;">
  <source src="{{video.url()}}" type="{{video.mimeType()}}">
</video>
</span>
</code>```

Whenever my array is emptied the video component disappears... if my array changes the component gets renew.

Works like a charm, hope it helps.

Body:
I have problem with video src. After clicking on my div (camera) in source code I can see that video src is changing properly, but videos arent being played. What should I do?

Below are my components - streaming.component.ts (responsible for displaying videos of chosen camera component) and camera.component.ts (for viewing icon with camera name)

streaming.component.ts

import {Component} from '@angular/core';
import {CameraComponent} from '../camera/camera.component';

@Component({
   moduleId: module.id,
   selector: 'streaming',
   template: `
            <camera cameraName="Kamera 1" (click)='cameraStream("sample.mp4")'></camera>
            <camera cameraName="Kamera 2" (click)='cameraStream("sample2.mp4")'></camera>
            <camera cameraName="Kamera 3" (click)='cameraStream("sample3.mp4")'></camera>
            <camera cameraName="Kamera 4" (click)='cameraStream("sample4.mp4")'></camera>
            <video width="800" controls>
                <source src = "{{cameraSrc}}" type="video/mp4">
                Your browser does not support HTML5 video.
            </video>

{{cameraSrc}}

            `,
directives: [CameraComponent]
})
export class StreamingComponent {

 cameraSrc:string;
 constructor() { }

 cameraStream(chosenCamera :string){
    this.cameraSrc=chosenCamera;
  }
 }

Videos are working ,because when I put

<source src = "{{cameraSrc}}" type="video/mp4">

everything is fine.

camera.component.ts

import { Component ,Input } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'camera',
    templateUrl: 'camera.component.html'
})
export class CameraComponent {
     @Input() cameraName:string = "";

     constructor() { }

 }

Here is what I get after clicking on camera2 for example
.

Body:
I had a similar problem... I settled with using a backing array

<span *ngFor="let video of app.videoPlayer.videos">
<img src="{{video.artBig()}}" style="width: 1920px;height: 1080px;top: 0px;left:0px;z-index: -1; position: absolute;"/>

<video preload="auto" crossorigin controls autoplay
   style="width: 1920px;height: 1080px;top: 0px;left:0px;z-index:1; position: absolute;">
  <source src="{{video.url()}}" type="{{video.mimeType()}}">
</video>
</span>

Whenever my array is emptied the video component disappears... if my array changes the component gets renew.

Works like a charm, hope it helps.


问:
Is it possible to maintain user sessions for facebook messenger bot?
I'm working on a facebook messenger bot, the webhook is written in node.js which listens for messages from user and responds back, the flow of conversation is guided and structured in modules. Each module has a module name and  bot-statement and a reference of a child modules. Forex ample there is a welcome module with the statement
"Hello I'm great bot i can offer following informations 1:- Movies 2:-Music"
now the welcome module has the references of two child modules Movies and Music, the conversation has to progress in one of these two directions based on user response, for example if the user responds Movies, the bot will pick up the module statement from the movies module and send back to facebook , so the reply to user for movies will be like
"exciting, what kind of movies do you want to know about? action, adventure, sci-fi" and again the user responds back with the thing he wants to know about and the bot picks up the module statement and send back to the user.
now this all works good but the problem here is, if there are two users say User A and User B. user A says Hi, bot says welcome what you want to know movies or music? user responds Movies and the bot throws what kind of movies action adventure or sci-fi, but then there comes  a user B who says hi so the bot responds with same current module that is for user A.
here is the code </p>

```<code>var sender;
var ModID=0;
exports.Facebook_bot = function(req, res) {
// console.log(req.body);
var messaging_events = req.body.entry[0].messaging;
// console.log(messaging_events);
for (var i = 0; i < messaging_events.length; i++) {
  var event = messaging_events[i];
  sender = event.sender.id;
  //  console.log('this is event',event);
  if (event.message && event.message.text) {
    var msg = event.message.text;
    console.log( "this is recived text",msg);
    // sendText(sender, "text echo" + msg.substring(0, 100));
  }
}
res.send(200);

if (ModID == 0) {
  ModID = "71072";
  botSchema.findOne({ Bot_name: "My Bot" }, function(err, data) {
    for (var i = 0; i < data.Modules.length; i++) {
      var back = data.Modules[i].ModuleResponse;

      if (data.Modules[i].ModuleID === ModID) {
        for (var j = 0; j < back.length; j++) {
          console.log("back", back[j].Response);

          if (back[j].Response === msg || back[j].Response === "-input-") {
            //got to module ModID
            ModID = back[j].TransBotID;
            // console.log("else",ModID);
            // console.log(back[j]);
          }
        }
      }
    }
  }).then(function(data) {
    for (var i = 0; i < data.Modules.length; i++) {
      if (data.Modules[i].ModuleID === ModID) {
        sendText(
          sender,
          data.Modules[i].ModuleStatement.substring(0, 500)
        );
        sendUI(sender,data.Modules[i].FBUI)
        console.log(data.Modules[i].FBUI);

      } else if (ModID === null) {
        console.log(false);
      }
    }
  });;
} else {
  botSchema
    .findOne({ Bot_name: "HIA Airport" }, function(err, data) {
      // console.log(data)
      for (var i = 0; i < data.Modules.length; i++) {
        var back = data.Modules[i].ModuleResponse;
        // console.log(back);
        if (data.Modules[i].ModuleID === ModID && back != null) {
          for (var j = 0; j < back.length; j++) {
            console.log("back 2", back[j].Response);

            if (back[j].Response === msg || back[j].Response === "-input-") {
              ModID = back[j].TransBotID;
              console.log("Go to :", ModID);
            }
          }
        }
      }
    })
    .then(function(data) {
      for (var i = 0; i < data.Modules.length; i++) {
        if (data.Modules[i].ModuleID === ModID) {
          sendText(
            sender,
            data.Modules[i].ModuleStatement.substring(0, 500)
          );
          console.log(data.Modules[i].ModuleStatement);
        } else if (ModID === null) {
          console.log(false);
        }
      }
    });
}
//end if
</code>```

<p>};
the variables sender and ModID are defined globally i want it to be defined seperately for each new user so that the state of conversation for user B is not dependent on state of conversation for user B, how can i do it? I hope it makes sense, please do ask if you need to know anything further. </p>

答: You should block scope sender and then pass it from module to module. That will ensure each incoming PSID will follow its own path.

Body:
I'm working on a facebook messenger bot, the webhook is written in node.js which listens for messages from user and responds back, the flow of conversation is guided and structured in modules. Each module has a module name and  bot-statement and a reference of a child modules. Forex ample there is a welcome module with the statement
"Hello I'm great bot i can offer following informations 1:- Movies 2:-Music"
now the welcome module has the references of two child modules Movies and Music, the conversation has to progress in one of these two directions based on user response, for example if the user responds Movies, the bot will pick up the module statement from the movies module and send back to facebook , so the reply to user for movies will be like
"exciting, what kind of movies do you want to know about? action, adventure, sci-fi" and again the user responds back with the thing he wants to know about and the bot picks up the module statement and send back to the user.
now this all works good but the problem here is, if there are two users say User A and User B. user A says Hi, bot says welcome what you want to know movies or music? user responds Movies and the bot throws what kind of movies action adventure or sci-fi, but then there comes  a user B who says hi so the bot responds with same current module that is for user A.
here is the code

var sender;
var ModID=0;
exports.Facebook_bot = function(req, res) {
// console.log(req.body);
var messaging_events = req.body.entry[0].messaging;
// console.log(messaging_events);
for (var i = 0; i < messaging_events.length; i++) {
  var event = messaging_events[i];
  sender = event.sender.id;
  //  console.log('this is event',event);
  if (event.message && event.message.text) {
    var msg = event.message.text;
    console.log( "this is recived text",msg);
    // sendText(sender, "text echo" + msg.substring(0, 100));
  }
}
res.send(200);

if (ModID == 0) {
  ModID = "71072";
  botSchema.findOne({ Bot_name: "My Bot" }, function(err, data) {
    for (var i = 0; i < data.Modules.length; i++) {
      var back = data.Modules[i].ModuleResponse;

      if (data.Modules[i].ModuleID === ModID) {
        for (var j = 0; j < back.length; j++) {
          console.log("back", back[j].Response);

          if (back[j].Response === msg || back[j].Response === "-input-") {
            //got to module ModID
            ModID = back[j].TransBotID;
            // console.log("else",ModID);
            // console.log(back[j]);
          }
        }
      }
    }
  }).then(function(data) {
    for (var i = 0; i < data.Modules.length; i++) {
      if (data.Modules[i].ModuleID === ModID) {
        sendText(
          sender,
          data.Modules[i].ModuleStatement.substring(0, 500)
        );
        sendUI(sender,data.Modules[i].FBUI)
        console.log(data.Modules[i].FBUI);

      } else if (ModID === null) {
        console.log(false);
      }
    }
  });;
} else {
  botSchema
    .findOne({ Bot_name: "HIA Airport" }, function(err, data) {
      // console.log(data)
      for (var i = 0; i < data.Modules.length; i++) {
        var back = data.Modules[i].ModuleResponse;
        // console.log(back);
        if (data.Modules[i].ModuleID === ModID && back != null) {
          for (var j = 0; j < back.length; j++) {
            console.log("back 2", back[j].Response);

            if (back[j].Response === msg || back[j].Response === "-input-") {
              ModID = back[j].TransBotID;
              console.log("Go to :", ModID);
            }
          }
        }
      }
    })
    .then(function(data) {
      for (var i = 0; i < data.Modules.length; i++) {
        if (data.Modules[i].ModuleID === ModID) {
          sendText(
            sender,
            data.Modules[i].ModuleStatement.substring(0, 500)
          );
          console.log(data.Modules[i].ModuleStatement);
        } else if (ModID === null) {
          console.log(false);
        }
      }
    });
}
//end if

};
the variables sender and ModID are defined globally i want it to be defined seperately for each new user so that the state of conversation for user B is not dependent on state of conversation for user B, how can i do it? I hope it makes sense, please do ask if you need to know anything further.


问:
Ruby - How do you perform an operation on each item of two (maybe more) arrays and populate them in a new array?
```<code>a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]
</code>```

each of array a's items are divided by each of array b's items and put into a new array called c.

```<code>c = [6, 3, 2, 2, 2]
</code>```

答:
I like mudasobwa's zip/map solution, but here are a couple alternatives:

```<code>a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

c = Array.new(a.size) { |i| a[i] / b[i] }
c = a.map.with_index { |x, i| x / b[i] }
</code>```

In particular, I might prefer the Array.new solution if the arrays aren't guaranteed to be the same length, because you can easily ensure you don't go over bounds:

```<code>c = Array.new([a.size, b.size].min) { |i| a[i] / b[i] }
</code>```

Body:
a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

each of array a's items are divided by each of array b's items and put into a new array called c.

c = [6, 3, 2, 2, 2]

Body:
I like mudasobwa's zip/map solution, but here are a couple alternatives:

a = [6, 7, 8, 9, 10]
b = [1, 2, 3, 4, 5]

c = Array.new(a.size) { |i| a[i] / b[i] }
c = a.map.with_index { |x, i| x / b[i] }

In particular, I might prefer the Array.new solution if the arrays aren't guaranteed to be the same length, because you can easily ensure you don't go over bounds:

c = Array.new([a.size, b.size].min) { |i| a[i] / b[i] }


问:
When printing an image, what determines how large it will appear on a page?
Using Python's Imaging Library I want to create a PNG file.

I would like it if when printing this image, without any scaling, it would always print at a known and consistent 'size' on the printed page.

Is the resolution encoded in the image?

If so, how do I specify it?

And even if it is, does this have any relevance when it goes to the printer?

答:
Both image print size and resolution are relevant to printing an image of a specific scale and quality. Bear in mind that if the image is then included with a desktop publishing workspace (Word, InDesign) or even a web page, the image is then subject to any specified resolution in the parent document -- this won't necessarily alter the relative scale of the image in the case of desktop publishing programs but will alter image quality.

And yes, all images have a resolution property, which answers half your question - I don't know Python...

OwnerDisplayName: carrier

OwnerDisplayName: aesdanae


问:
Is multiple .Where() statements in LINQ a performance issue?
I am wondering if there are performance implications of multiple .Where() statements. For example I could write:

```<code>var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
        )
    .Where(
        c1 =>
            !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
        )
    .Where(
        c1 =>
            !Context.EmployeeTask.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );
</code>```

Or alternatively I could combine them all into the one Where() clause, like so:

```<code>var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
            && !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
            && !Context.Employee_Task.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );
</code>```

Does the chain of Where() clauses hurt performance or are they equivalent?

答:
In LINQ to Objects, there will be a very small performance hit, because basically the iterator chain will be longer - fetching the next element means going up a long chain of MoveNext() calls.

In LINQ to SQL and similar providers, I'd expect the same SQL to be generated either way, so it wouldn't impact performance there.

EDIT: Since writing this I've found out a bit more about the LINQ to Objects implementation - it's a little more complicated...

Body:
I am wondering if there are performance implications of multiple .Where() statements. For example I could write:

var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
        )
    .Where(
        c1 =>
            !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
        )
    .Where(
        c1 =>
            !Context.EmployeeTask.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );

Or alternatively I could combine them all into the one Where() clause, like so:

var contracts =  Context.Contract
    .Where(
        c1 =>
            c1.EmployeeId == employeeId
            && !Context.Contract.Any(
                c2 =>
                    c2.EmployeeId == employeeId
                    && c1.StoreId == c2.StoreId
                    && SqlFunctions.DateDiff("day", c2.TerminationDate.Value, c1.DateOfHire.Value) == 1
                )
            && !Context.Employee_Task.Any(
                t =>
                    t.ContractId == c1.Id
                )
        );

Does the chain of Where() clauses hurt performance or are they equivalent?


问:
Reshaping a broadcasted expression
I would like to make the following broadcasted expression work:

```<code>J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
@. J[:,1] = fx1 + fx2
</code>```

I really want some kind of:

```<code>@. J[:,1] = vec(fx1 + fx2)
</code>```

where this vec is saying it should reshape to be 4x1, but I don't want to have to make this allocating. How could this be generically handled (i.e. no indexing on the fx)?

答:
You can "exempt" vec from the @. macro by protecting it with a $:

```<code>julia> expand(:(@. J[:,1] = $vec(fx1) + $vec(fx2)))
:((Base.broadcast!)(+, (Base.dotview)(J, :, 1), (vec)(fx1), (vec)(fx2)))
</code>```

Title: Reshaping a broadcasted expression

Body:
I would like to make the following broadcasted expression work:

J = rand(4,4)
fx1 = rand(2,2)
fx2 = rand(2,2)
@. J[:,1] = fx1 + fx2

I really want some kind of:

@. J[:,1] = vec(fx1 + fx2)

where this vec is saying it should reshape to be 4x1, but I don't want to have to make this allocating. How could this be generically handled (i.e. no indexing on the fx)?

Body:
You can "exempt" vec from the @. macro by protecting it with a $:

julia> expand(:(@. J[:,1] = $vec(fx1) + $vec(fx2)))
:((Base.broadcast!)(+, (Base.dotview)(J, :, 1), (vec)(fx1), (vec)(fx2)))


问:
Comparing Session Variable to a String C#
```<code>string currentUser;
string currentPassword;
string getUserName;
string getPassword;

getUserName = Convert.ToString(Session["UserName"]);
getPassword = Convert.ToString(Session["Password"]);

currentUser = Convert.ToString(txtUserNameLogIn.Text);
currentPassword = Convert.ToString(txtPasswordLogin.Text);

if ((currentUser == getUserName ) && (currentPassword == getPassword)) {
    currentUser = Convert.ToString(Session["CurrentUser"]);
    currentPassword = Convert.ToString(Session["CurrentPassword"]);
    Response.Redirect("Home.aspx");
} else {
    lblResult.Text = "Invalid Password";

}
</code>```

I have 3 pages. First one for registration, that saves UserName and Password so a Session and then I have login page that should take the UserName and Password sessions and compare them to the current user input on this page. So far I'm not getting any responses.

Edit: The username and password that I put in on previous page gets stored in a Session Variable called "UserName", the person gets re-directed to login page and I simply want to compare what user types in with the Session Variable from previous page and if it's correct, store that information in new Session Variable and re-direct user to home page.

答:
You can do several things here working under the assumption this is a test project and you know Session is not the correct place to store plaintext credentials. Take a look at SimpleMembership for a cleaner approach.

That out of the way I created two extension classes. The first takes care of string security, and the second takes care of Session. You can take this a step further and create constants for the keys or even a SessionUser object. In terms of comparison I just combined both username+password so the logic is short.

```<code> public static class StringExtensions
{
    public static string Encrypt(this string plainText)
    {
        // Replace with your encryption impl
        return plainText;
    }

    public static string Decrypt(this string hiddenText)
    {
        // Replace with your decryption impl
        return hiddenText;
    }
}

public static class SessionExtensions
{
    public static void Set<T>(this HttpSessionState sessionState, string key, T value)
    {
        sessionState[key] = value;
    }

    public static T Get<T>(this HttpSessionState sessionState, string key) where T : class
    {
        return (T)sessionState[key];
    }
}

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session.Set("UserName", "something");
        Session.Set("Password", "something".Encrypt());

        var username = Session.Get<string>("UserName");
        var password = Session.Get<string>("Password").Decrypt();

        var savedUser = $"{username}{password}";
        var currentUser = $"somethingsomething";

        if (currentUser.Equals(savedUser, StringComparison.InvariantCultureIgnoreCase))
        {

        }
        else
        {

        }
    }
}
</code>```

Body:
string currentUser;
string currentPassword;
string getUserName;
string getPassword;

getUserName = Convert.ToString(Session["UserName"]);
getPassword = Convert.ToString(Session["Password"]);

currentUser = Convert.ToString(txtUserNameLogIn.Text);
currentPassword = Convert.ToString(txtPasswordLogin.Text);

if ((currentUser == getUserName ) && (currentPassword == getPassword)) {
    currentUser = Convert.ToString(Session["CurrentUser"]);
    currentPassword = Convert.ToString(Session["CurrentPassword"]);
    Response.Redirect("Home.aspx");
} else {
    lblResult.Text = "Invalid Password";

}

I have 3 pages. First one for registration, that saves UserName and Password so a Session and then I have login page that should take the UserName and Password sessions and compare them to the current user input on this page. So far I'm not getting any responses.

Edit: The username and password that I put in on previous page gets stored in a Session Variable called "UserName", the person gets re-directed to login page and I simply want to compare what user types in with the Session Variable from previous page and if it's correct, store that information in new Session Variable and re-direct user to home page.

Body:
You can do several things here working under the assumption this is a test project and you know Session is not the correct place to store plaintext credentials. Take a look at SimpleMembership for a cleaner approach.

That out of the way I created two extension classes. The first takes care of string security, and the second takes care of Session. You can take this a step further and create constants for the keys or even a SessionUser object. In terms of comparison I just combined both username+password so the logic is short.

 public static class StringExtensions
{
    public static string Encrypt(this string plainText)
    {
        // Replace with your encryption impl
        return plainText;
    }

    public static string Decrypt(this string hiddenText)
    {
        // Replace with your decryption impl
        return hiddenText;
    }
}

public static class SessionExtensions
{
    public static void Set<T>(this HttpSessionState sessionState, string key, T value)
    {
        sessionState[key] = value;
    }

    public static T Get<T>(this HttpSessionState sessionState, string key) where T : class
    {
        return (T)sessionState[key];
    }
}

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session.Set("UserName", "something");
        Session.Set("Password", "something".Encrypt());

        var username = Session.Get<string>("UserName");
        var password = Session.Get<string>("Password").Decrypt();

        var savedUser = $"{username}{password}";
        var currentUser = $"somethingsomething";

        if (currentUser.Equals(savedUser, StringComparison.InvariantCultureIgnoreCase))
        {

        }
        else
        {

        }
    }
}


问:
How to prevent QStringBuilder from outliving the scope it was initialised in
I have been looking at changing some code to make use of QStringBuilder expression template for its purported performance improvements. Unfortunately this resulted in sections of my code starting to crash in places, an example of which follows:

```<code>#define QT_USE_QSTRINGBUILDER
#include <numeric>
#include <vector>
#include <QString>
#include <QStringBuilder>

int main()
{
    std::vector<int> vals = {0, 1, 2, 3, 4};
    QString text = "Values: " + QString::number(vals[0]);
    text = std::accumulate(vals.begin() + 1, vals.end(), text, [](const QString& s, int i)
    {
        return s + ", " + QString::number(i);
    });
}
</code>```

The reason this crashes is because the return type of the lambda expression is deduced to be QStringBuilder<QStringBuilder<QString,const char [3]>,QString> which after being returned attempts to cast to QString to assign to the accumulate result. This cast crashes because it is attempting to use references to objects which were in the scope of the lambda and have now been destroyed. This crash can be fixed by explicitly specifying the return type of the lambda as such [](const QString& s, int i) -> QString which ensures that the cast occurs before the closure is exited.

However the fact that enabling QStringBuilder here caused a crash in previously working code without even emitting a warning means that I will now avoid using it elsewhere unless I can guarantee that this will not happen again. Since in this case RVO could prevent any copying from occurring I don't think the usual technique of disabling copying of the object would work. Is there a way to prevent this occurring in QStringBuilder or similar expression templates or are objects which maintain references to automatic variables always going to be unsafe to use?

答: The clazy code checker provides a check for this scenario.

Body:
I have been looking at changing some code to make use of QStringBuilder expression template for its purported performance improvements. Unfortunately this resulted in sections of my code starting to crash in places, an example of which follows:

#define QT_USE_QSTRINGBUILDER
#include <numeric>
#include <vector>
#include <QString>
#include <QStringBuilder>

int main()
{
    std::vector<int> vals = {0, 1, 2, 3, 4};
    QString text = "Values: " + QString::number(vals[0]);
    text = std::accumulate(vals.begin() + 1, vals.end(), text, [](const QString& s, int i)
    {
        return s + ", " + QString::number(i);
    });
}

The reason this crashes is because the return type of the lambda expression is deduced to be QStringBuilder<QStringBuilder<QString,const char [3]>,QString> which after being returned attempts to cast to QString to assign to the accumulate result. This cast crashes because it is attempting to use references to objects which were in the scope of the lambda and have now been destroyed. This crash can be fixed by explicitly specifying the return type of the lambda as such [](const QString& s, int i) -> QString which ensures that the cast occurs before the closure is exited.

However the fact that enabling QStringBuilder here caused a crash in previously working code without even emitting a warning means that I will now avoid using it elsewhere unless I can guarantee that this will not happen again. Since in this case RVO could prevent any copying from occurring I don't think the usual technique of disabling copying of the object would work. Is there a way to prevent this occurring in QStringBuilder or similar expression templates or are objects which maintain references to automatic variables always going to be unsafe to use?


问:
make don't build file even if dependency is updated
this is my make file:-

```<code>VER = Debug
CC = g++

OBJECTFIELS = main.o Time.o

main: $(OBJECTFIELS)
    $(CC) $(OBJECTFIELS) -o $@

$(OBJECTFILES): Time_.h

clean:
    rm $(OBJECTFIELS) main
</code>```

every time I change the Time_.h file, nothing happens:-

```<code>$ make
make: 'main' is up to date.
$ touch Time_.h
$ make
make: 'main' is up to date.
</code>```

other files compile when changed :-

```<code>$ touch main.o
$ make
g++ main.o Time.o -o main
</code>```

please I am complete noob. Please tell why is this happening

答:
You need to generate new .o files in your rule for Time_.h.

```<code>$(OBJECTFILES): Time_.h
</code>```

This says make should run a command whenever Time_.h is updated, and that the command will generate both main.o and Time.o. But no command is given!

```<code>Time.o: Time_.h
        $(CC) Time_.cpp -o Time.o
</code>```

This is the kind of rule you want. Whenever Time_.h changes, we run $(CC) Time_.cpp -o Time.o, which will generate Time.o. Now if some other rule depends on Time.o, make will know that this command can be used to create Time.o, but that it only needs to be run if Time_.h changed since the last time make was run.

I'm specifying "Time.o" explicitly, since your source filenames don't seem to exactly match the object files you're expecting. (Time.o vs Time_.o)

Body:
this is my make file:-

VER = Debug
CC = g++

OBJECTFIELS = main.o Time.o

main: $(OBJECTFIELS)
    $(CC) $(OBJECTFIELS) -o $@

$(OBJECTFILES): Time_.h

clean:
    rm $(OBJECTFIELS) main

every time I change the Time_.h file, nothing happens:-

$ make
make: 'main' is up to date.
$ touch Time_.h
$ make
make: 'main' is up to date.

other files compile when changed :-

$ touch main.o
$ make
g++ main.o Time.o -o main

please I am complete noob. Please tell why is this happening

Body:
You need to generate new .o files in your rule for Time_.h.

$(OBJECTFILES): Time_.h

This says make should run a command whenever Time_.h is updated, and that the command will generate both main.o and Time.o. But no command is given!

Time.o: Time_.h
        $(CC) Time_.cpp -o Time.o

This is the kind of rule you want. Whenever Time_.h changes, we run $(CC) Time_.cpp -o Time.o, which will generate Time.o. Now if some other rule depends on Time.o, make will know that this command can be used to create Time.o, but that it only needs to be run if Time_.h changed since the last time make was run.

I'm specifying "Time.o" explicitly, since your source filenames don't seem to exactly match the object files you're expecting. (Time.o vs Time_.o)


问:
nUnit tests looking for {assembly-name}.dll.config
I have a PowerShell script that shells-out to nunit-console-x86.exe to run tests in assemblies ( DLLs ) that were built earlier in the script by shelling to MSBuild to compile a VS .sln

```<code>Exec { invoke-expression "$BUILD_DIR\Tools\NUnit.2.5.10.11092\nunit-console-x86.exe  $full_test_assembly_name /xml:test-results/$test_results_file_name" }
</code>```

Some of these tests utilize System.Configuration.ConfigurationManager to load config settings.  nunit-console-x86.exe searches for these config-settings in {$full_test_assembly_name}.dll.config , but this file does not exist as my script does not create it (for reasons explained below).

Each test-project .csproj includes a local App.config file.  When a test-project's tests are run in Visual Studio, nUnit searches for config settings in the local App.config. This behavior is as I expected.

I also have an application .sln with a site/service .csproj as its startup project, plus references to various test-projects.  When I run the application .sln's entire test-suite from Visual Studio, upon running tests for any test-project nUnit searches for config settings in the test-project's local App.config.

This behavior is not as I expected -- I would have thought that nUnit would search the web.config located in the startup site/service .csproj.

As an experiment, I removed App.config from one of the test-projects.  Now when I run its tests in Visual Studio, nUnit throws errors that it can't find {test-project-assembly-name}.dll.config.  So apparently uUnit by default looks for config settings in {test-project-assembly-name}.dll.config.

I want my test-script to invoke nUnit to run test-assembly tests so that any config settings are loaded from web.config ( which my build script copies into the build target dir ).

How can I accomplish this ?  Can I instruct nunit-console-x86.exe to load config-settings from a config-file-path I supply as a parameter ?  Can I structure my .sln and/or .csproj differently so as to cause uUnit to utilize Web.config for config-settings ?

答: Not sure if this still applies to the OP's question , but when you build the test project multiple .dll.config files are copied over . If you need to have custom configuration for the tests , copy the .config into the test project . Then in the Properties pane set Copy to Output Directory to Copy Always , this will overwrite the projects config file .

Body:
I have a PowerShell script that shells-out to nunit-console-x86.exe to run tests in assemblies ( DLLs ) that were built earlier in the script by shelling to MSBuild to compile a VS .sln

Exec { invoke-expression "$BUILD_DIR\Tools\NUnit.2.5.10.11092\nunit-console-x86.exe  $full_test_assembly_name /xml:test-results/$test_results_file_name" }

Some of these tests utilize System.Configuration.ConfigurationManager to load config settings.  nunit-console-x86.exe searches for these config-settings in {$full_test_assembly_name}.dll.config , but this file does not exist as my script does not create it (for reasons explained below).

Each test-project .csproj includes a local App.config file.  When a test-project's tests are run in Visual Studio, nUnit searches for config settings in the local App.config. This behavior is as I expected.

I also have an application .sln with a site/service .csproj as its startup project, plus references to various test-projects.  When I run the application .sln's entire test-suite from Visual Studio, upon running tests for any test-project nUnit searches for config settings in the test-project's local App.config.

This behavior is not as I expected -- I would have thought that nUnit would search the web.config located in the startup site/service .csproj.

As an experiment, I removed App.config from one of the test-projects.  Now when I run its tests in Visual Studio, nUnit throws errors that it can't find {test-project-assembly-name}.dll.config.  So apparently uUnit by default looks for config settings in {test-project-assembly-name}.dll.config.

I want my test-script to invoke nUnit to run test-assembly tests so that any config settings are loaded from web.config ( which my build script copies into the build target dir ).

How can I accomplish this ?  Can I instruct nunit-console-x86.exe to load config-settings from a config-file-path I supply as a parameter ?  Can I structure my .sln and/or .csproj differently so as to cause uUnit to utilize Web.config for config-settings ?