问:
How can the Dropbox API alert when a token is received?

I am able to log in and do export/import from my Android app using the v2 Dropbox API. The only problem is on first run when a token is requested and the Dropbox app/website is launched - I have to run Auth.startOAuth2Authentication at least twice with a pause in between to be able to read the token with Auth.getOAuth2Token.

Is there anyway to wait() and get notified when startOAuth2Authentication returns after acquiring a token?

```<code>   Auth.startOAuth2Authentication(this, getString(R.string.app_key));
   //wait for response, retry, or time out and finish
   String accessToken = Auth.getOAuth2Token();
   prefs.edit().putString(ACCESS_TOKEN, accessToken).commit();
</code>```

答:
Here is a simple example for implementing the Dropbox Android API:
https://www.sitepoint.com/adding-the-dropbox-api-to-an-android-app/

Now, to get to the point of your question, you will not be able to get a toke immediately after Auth.startOAuth2Authentication(this, getString(R.string.app_key)); is called. After you call this method, the Dropbox login activity is shown, and you can get the token only after the user logs in (which is in no way immediate, and you have no way of telling how long it will take).
After the user logs in successfully your activity will be resumed, and you can see in the example from the tutorial that the Activity's onResume method is overridden a check is performed in there.

I will copy below the LoginActivity from this tutorial. It should be easy enough to start from here:

```<code>public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Button SignInButton = (Button) findViewById(R.id.sign_in_button);
        SignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Auth.startOAuth2Authentication(getApplicationContext(), getString(R.string.APP_KEY));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAccessToken();
    }

    public void getAccessToken() {
        String accessToken = Auth.getOAuth2Token(); //generate Access Token
        if (accessToken != null) {
            //Store accessToken in SharedPreferences
            SharedPreferences prefs = getSharedPreferences("com.example.valdio.dropboxintegration", Context.MODE_PRIVATE);
            prefs.edit().putString("access-token", accessToken).apply();

            //Proceed to MainActivity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        }
    }
}
</code>```

Body:
I am able to log in and do export/import from my Android app using the v2 Dropbox API. The only problem is on first run when a token is requested and the Dropbox app/website is launched - I have to run Auth.startOAuth2Authentication at least twice with a pause in between to be able to read the token with Auth.getOAuth2Token.

Is there anyway to wait() and get notified when startOAuth2Authentication returns after acquiring a token?

   Auth.startOAuth2Authentication(this, getString(R.string.app_key));
   //wait for response, retry, or time out and finish
   String accessToken = Auth.getOAuth2Token();
   prefs.edit().putString(ACCESS_TOKEN, accessToken).commit();

Body:
Here is a simple example for implementing the Dropbox Android API:
https://www.sitepoint.com/adding-the-dropbox-api-to-an-android-app/

Now, to get to the point of your question, you will not be able to get a toke immediately after Auth.startOAuth2Authentication(this, getString(R.string.app_key)); is called. After you call this method, the Dropbox login activity is shown, and you can get the token only after the user logs in (which is in no way immediate, and you have no way of telling how long it will take).
After the user logs in successfully your activity will be resumed, and you can see in the example from the tutorial that the Activity's onResume method is overridden a check is performed in there.

I will copy below the LoginActivity from this tutorial. It should be easy enough to start from here:

public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Button SignInButton = (Button) findViewById(R.id.sign_in_button);
        SignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Auth.startOAuth2Authentication(getApplicationContext(), getString(R.string.APP_KEY));
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAccessToken();
    }

    public void getAccessToken() {
        String accessToken = Auth.getOAuth2Token(); //generate Access Token
        if (accessToken != null) {
            //Store accessToken in SharedPreferences
            SharedPreferences prefs = getSharedPreferences("com.example.valdio.dropboxintegration", Context.MODE_PRIVATE);
            prefs.edit().putString("access-token", accessToken).apply();

            //Proceed to MainActivity
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
        }
    }
}


来源: stackexchange

问:
MySQL - Insert Into 2 Tables on 1 Procedure
I need to create a procedure for inserting records into 2 tables, but on the second table, I want to insert the last ID that was inserted on the first table. Could anyone help me with this?

This is my query

```<code>DELIMITER //
DROP PROCEDURE IF EXISTS ROOM_FEATURE_INSERT;
CREATE PROCEDURE ROOM_FEATURE_INSERT (propID INT, featID INT, featNme VARCHAR(50))
BEGIN
-- BEGIN CHECK
IF NOT EXISTS
(
SELECT rFeatureName FROM COMPANY_T3s71.PROPERTY_RFEATURE PRFE
INNER JOIN COMPANY_T3s71.ROOM_FEATURE RFEA ON PRFE.rFeatureID=RFEA.rFeatureID
WHERE BINARY rFeatureName = featNme AND propertyID = propID
)
AND
(
SELECT rFeatureName FROM COMPANY_T3s71.ROOM_VIEW
WHERE BINARY rFeatureName = featNme
)
THEN
-- IF NOT EXISTS INSERT INTO 1st TABLE
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
END IF;
-- END CHECK

-- BEGIN CHECK 2nd TABLE
IF NOT EXISTS
(
SELECT propertyID, rFeatureID FROM COMPANY_T3s71.PROPERTY_RFEATURE
WHERE rFeatureID = featID AND propertyID = propID
)
THEN
-- IF NOT EXISTS INSERT INTO 2nd TABLE
INSERT INTO COMPANY_T3s71.PROPERTY_RFEATURE (propertyID, rFeatureID) VALUES (propID, featID);
END IF;
-- END CHECK 2nd TABLE

END

DELIMITER ;
</code>```

How do we pass the featID param, when we just inserted it on the first INSERT query?

Thank you before hand.

答:
Use SET featID = LAST_INSERT_ID(); after the first query and then use the variable

```<code>INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
SET featID = LAST_INSERT_ID();
</code>```

However, if the data is not insert at anytime then you  have to make query in the if block to set the value for featID.

ContentLicense: CC BY-SA 3.0

Body:
I need to create a procedure for inserting records into 2 tables, but on the second table, I want to insert the last ID that was inserted on the first table. Could anyone help me with this?

This is my query

DELIMITER //
DROP PROCEDURE IF EXISTS ROOM_FEATURE_INSERT;
CREATE PROCEDURE ROOM_FEATURE_INSERT (propID INT, featID INT, featNme VARCHAR(50))
BEGIN
-- BEGIN CHECK
IF NOT EXISTS
(
SELECT rFeatureName FROM COMPANY_T3s71.PROPERTY_RFEATURE PRFE
INNER JOIN COMPANY_T3s71.ROOM_FEATURE RFEA ON PRFE.rFeatureID=RFEA.rFeatureID
WHERE BINARY rFeatureName = featNme AND propertyID = propID
)
AND
(
SELECT rFeatureName FROM COMPANY_T3s71.ROOM_VIEW
WHERE BINARY rFeatureName = featNme
)
THEN
-- IF NOT EXISTS INSERT INTO 1st TABLE
INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
END IF;
-- END CHECK

-- BEGIN CHECK 2nd TABLE
IF NOT EXISTS
(
SELECT propertyID, rFeatureID FROM COMPANY_T3s71.PROPERTY_RFEATURE
WHERE rFeatureID = featID AND propertyID = propID
)
THEN
-- IF NOT EXISTS INSERT INTO 2nd TABLE
INSERT INTO COMPANY_T3s71.PROPERTY_RFEATURE (propertyID, rFeatureID) VALUES (propID, featID);
END IF;
-- END CHECK 2nd TABLE

END

DELIMITER ;

How do we pass the featID param, when we just inserted it on the first INSERT query?

Thank you before hand.

Body:
Use SET featID = LAST_INSERT_ID(); after the first query and then use the variable

INSERT INTO COMPANY_T3s71.ROOM_FEATURE (rFeatureName) VALUES (featNme);
SET featID = LAST_INSERT_ID();

However, if the data is not insert at anytime then you  have to make query in the if block to set the value for featID.


问:
Windows Task Scheduler Doesn't Run VBScript
I am trying to automate a VBScript by using Windows Task Scheduler. However, I tried to use cscript.exe + "C:\...\script.vbs" but it didn't run. I also tried to directly run the same command in CMD (cscript.exe "C:\...\script.vbs") and it worked.

What might be the problem?

EDIT :

I just tried to switch the setting to "Run only when user is logged on" from "Run whether user is logged on or not" and it worked. I am wondering if there is a way to make my task scheduled run even when the user is logged off.

答: Have experienced more than once that a VBScript running as planned task worked fine for months and years but suddenly would not work any more despite nothing was changed. Have tried to reactive the task using all the recipes given here and elsewhere, but no success. My workaround was to create a new planned task with all settings copied from the original one.

ContentLicense: CC BY-SA 4.0


问:
How can I run sails console without a webserver (using any ports)?
I have a Sails server running, and I want to execute some commands from inside of lifted Sails.

The problem is, then I run sails console - it bootstraps another instance of Sails, and trying to load another webserver next to existing, by default using the same ports.

By some environment limits, I can use only one port at the time. So I cannot load another webserver on the same machine.

Is there a way how to run sails console without using any ports?

Thank you.

答:
Running console without port is I belive not possible at all.

Add inside package json npm script to run console on another port (or if you have sails installed globally just run sails console --port xxxx).

Part of my package json:

```<code>"scripts": {
    "start": "node app.js",
    "console": "sails console --port 1338",
    "test": "mocha",
    "docs": "rimraf public/docs && apidoc -i config/routes -o public/docs"
  },
</code>```

As you can see... npm run console will run sails console on port 1338 while deafult port of my app is 1337...

Body:
Running console without port is I belive not possible at all.

Add inside package json npm script to run console on another port (or if you have sails installed globally just run sails console --port xxxx).

Part of my package json:

"scripts": {
    "start": "node app.js",
    "console": "sails console --port 1338",
    "test": "mocha",
    "docs": "rimraf public/docs && apidoc -i config/routes -o public/docs"
  },

As you can see... npm run console will run sails console on port 1338 while deafult port of my app is 1337...


问:
Does Postgresql 10 query partitions in parallel?
I'm curious if the new feature of Postgresql allows to take advantage of multiple cpus on server. In general there should be some worker that queries partitions and merges the results, and I expect it to be done in parallel. This becomes critical when foreign tables are used, I suppose.</p>

答:
This might be the closest answer for now:

https://www.enterprisedb.com/blog/new-features-coming-postgresql-10
Improved Parallel Query.  While PostgreSQL 9.6 offers parallel query, this feature has been significantly improved in PostgreSQL 10, with new features like Parallel Bitmap Heap Scan, Parallel Index Scan, and others.  Speedups of 2-4x are common with parallel query, and these enhancements should allow those speedups to happen for a wider variety of queries.


问:
How to write an app for kindle 4/5?
Do You know, how to write an app for Kindle 4? Kindle Fire have KDK, but is there a possibility to write an app for Kindle 4?</p>

答:
Kindle 4:

It seams you cannot register as a developer for the old Kindle anymore, so you need to jailbreak it and use a key (that you create yourself) to sign your jars.

You can find instructions what to do and several resources at the URL mentioned below.

There is also a tool to create your own Kindle developer key.

You need to install the public key on your Kindle. To be able to use your jars that you sign with it.

A Hello-World example is also included on the website.

It is also explained how to use retroweaver that makes it possible to use java 1.5 and than convert it to 1.4.

http://cowlark.com/kindle/getting-started.html

P.s.
Please add a comment as soon as you successfully wrote your first app that runs on your kindle.

Title: How to write an app for kindle 4/5?


问:
Convert xml to csv in Power shell
Hello I am new to Powershell, but I have looked all over for an answer to this question, how do I convert XML data to CSV data in powershell?

Here is my xml file:

```<code><users>
     <user>
        <id>"data"</id>
        <name>"data"</name>
        <disabled>"data"</disabled>
        <title>"data"</title>
        <email>"data"</email>
        <role>
             <name>"data"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60019</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data"</name>
        </site>
    </user>
</users>
</code>```

The fields that are multiple layers in the tree are the biggest pain. Here is the script I have come up with so far. I am able to get the basic fields such as name and email. I really need the fields that are labeled custom fields and their subsets.

```<code>#Converts the xml to a CSV file
$samage_users.users.user | select-Object @(
@{l="Email";e={$_.email}},
@{l="Name";e={$_.name}},
@{l="ID";e={$_.ID}},
@{l="Phone";e={$_.phone}},
@{l="Site";e={$_.site.name}},
@{l="Reports_To";e={$_.reports_to.name}},
@{l="Reports_To_Email";e={$_.reports_to.email}})|
export-csv "Samanage_users.csv" -NoTypeInformation -Append
$page ++
start-sleep -s 10
}
While ($page -lt ($pages + 2))
}
Function NewUsers
{
foreach ($user in $new_user)
{
</code>```

CSV output file should look something like this. (see attached)

CSV Output File

Any help is greatly appreciated!

Thanks

答:
Here's my alteration of TheMadTechnician's answer, with necessary explaining comments:

```<code>$RObj = ForEach ($User in $samage_users.users.user) {
  ### calculate basic properties - even those ones absent in XML
  $UObj = $user | Select-Object @(
    @{l="Email";e={$_.email}},
    @{l="Name";e={$_.name}},
    @{l="ID";e={$_.ID}},
    @{l="Phone";e={$_.phone}},
    @{l="Site";e={$_.site.name}},
    @{l="Rs_To";e={$_.reports_to.name}},   # "Rs_To"   cut "Reports_To"
    @{l="Rs_To_E";e={$_.reports_to.email}} # "Rs_To_E" cut "Reports_To_Email"
                                           # cuttings merely for better output readability
  )
  ### add user-dependent properties for each custom field
    $User.custom_fields_values.custom_fields_value |
      ForEach-Object {
        $UObj | Add-Member NoteProperty -Name $_.custom_field_id -Value $_.value
      }
    $UObj     ### add current PSCustomObject to the `$RObj` array
}
### mutually arrange potentially missing user-dependent properties
for ($i = 0; $i -lt $RObj.Count; $i++ ) {
 for ($j = 0; $j -lt $RObj.Count; $j++ ) {
  if ( $i -ne $j ) {
   $RObj[$i] | ForEach-Object { $_.PSObject.Properties.Name } |
    Where-Object { $_ -notin $RObj[$j].PSObject.Properties.Name } |
     ForEach-Object {
        $RObj[$j] | Add-Member -MemberType NoteProperty -Name $_ -Value ''
     }
  }
 }
}
### $RObj | Export-Csv "Samanage_users.csv" -NoTypeInformation
### debugging output instead of `Export-Csv`
$RObj | Format-Table -Property * -AutoSize
</code>```

Input (modified original XML); entered separately to avoid vertical scrolling in above code:

```<code>$samage_users=[xml]@'
<?xml version="1.0" encoding="UTF-8"?>
<users>
        <user>
        <id>"dI"</id>
        <name>"dN"</name>
        <disabled>"dD"</disabled>
        <title>"dT"</title>
        <email>"dE"</email>
        <role>
                <name>"dR"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60044</custom_field_id>
                <value>"dC1"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"dC2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"dC3"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"dSi"</name>
        </site>
    </user>
    <user>
        <id>"d2I"</id>
        <name>"d2N"</name>
        <disabled>"d2D"</disabled>
        <title>"d2T"</title>
        <email>"d2E"</email>
        <role>
                <name>"d2R"</name>
        </role>
        <Reports_To>
            <name>"d2RTn"</name>
            <email>"d2RTe"</email>
        </Reports_To>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"d2C1"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"d2C2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60034</custom_field_id>
                <value>"d2C3"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"d2Si"</name>
        </site>
    </user>
    <user>
        <id>"d3I"</id>
        <name>"d3N"</name>
        <disabled>"d3D"</disabled>
        <title>"d3T"</title>
        <email>"d3E"</email>
        <role>
                <name>"d3R"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60055</custom_field_id>
                <value>"d3C1"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60066</custom_field_id>
                <value>"d3C2"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"d3Si"</name>
        </site>
    </user>
</users>
'@
</code>```

Output:

PS D:\PShell D:\PShell\SO\47660787.ps1

Email Name  ID    Phone Site   Rs_To   Rs_To_E 60044 60021  60018  60034  60055  60066
----- ----  --    ----- ----   -----   ------- ----- -----  -----  -----  -----  -----
"dE"  "dN"  "dI"        "dSi"                  "dC1" "dC2"  "dC3"
"d2E" "d2N" "d2I"       "d2Si" "d2RTn" "d2RTe"       "d2C1" "d2C2" "d2C3"
"d3E" "d3N" "d3I"       "d3Si"                                            "d3C1" "d3C2"
```

<p><strong>Note</strong> in regard of Tomalak's useful comment stating <em>that XML files should always be read using the <code>XmlDocument</code> object's <code>.Load()</code> method</em>.</p>

```###                   $samage_users defined as above i.e. a herestring cast to [xml] type
$xml = New-Object Xml
$xml.Load("Samanage_users.xml")            ### a file containing above herestring content
Compare-Object $samage_users.InnerXml $xml.InnerXml                     ### no difference
```

Title: Convert xml to csv in Power shell

Body:
Hello I am new to Powershell, but I have looked all over for an answer to this question, how do I convert XML data to CSV data in powershell?

Here is my xml file:

<users>
     <user>
        <id>"data"</id>
        <name>"data"</name>
        <disabled>"data"</disabled>
        <title>"data"</title>
        <email>"data"</email>
        <role>
             <name>"data"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60019</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"data"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"data"</name>
        </site>
    </user>
</users>

The fields that are multiple layers in the tree are the biggest pain. Here is the script I have come up with so far. I am able to get the basic fields such as name and email. I really need the fields that are labeled custom fields and their subsets.

#Converts the xml to a CSV file
$samage_users.users.user | select-Object @(
@{l="Email";e={$_.email}},
@{l="Name";e={$_.name}},
@{l="ID";e={$_.ID}},
@{l="Phone";e={$_.phone}},
@{l="Site";e={$_.site.name}},
@{l="Reports_To";e={$_.reports_to.name}},
@{l="Reports_To_Email";e={$_.reports_to.email}})|
export-csv "Samanage_users.csv" -NoTypeInformation -Append
$page ++
start-sleep -s 10
}
While ($page -lt ($pages + 2))
}
Function NewUsers
{
foreach ($user in $new_user)
{

CSV output file should look something like this. (see attached)

CSV Output File

Any help is greatly appreciated!

Thanks

Body:
Here's my alteration of TheMadTechnician's answer, with necessary explaining comments:

$RObj = ForEach ($User in $samage_users.users.user) {
  ### calculate basic properties - even those ones absent in XML
  $UObj = $user | Select-Object @(
    @{l="Email";e={$_.email}},
    @{l="Name";e={$_.name}},
    @{l="ID";e={$_.ID}},
    @{l="Phone";e={$_.phone}},
    @{l="Site";e={$_.site.name}},
    @{l="Rs_To";e={$_.reports_to.name}},   # "Rs_To"   cut "Reports_To"
    @{l="Rs_To_E";e={$_.reports_to.email}} # "Rs_To_E" cut "Reports_To_Email"
                                           # cuttings merely for better output readability
  )
  ### add user-dependent properties for each custom field
    $User.custom_fields_values.custom_fields_value |
      ForEach-Object {
        $UObj | Add-Member NoteProperty -Name $_.custom_field_id -Value $_.value
      }
    $UObj     ### add current PSCustomObject to the `$RObj` array
}
### mutually arrange potentially missing user-dependent properties
for ($i = 0; $i -lt $RObj.Count; $i++ ) {
 for ($j = 0; $j -lt $RObj.Count; $j++ ) {
  if ( $i -ne $j ) {
   $RObj[$i] | ForEach-Object { $_.PSObject.Properties.Name } |
    Where-Object { $_ -notin $RObj[$j].PSObject.Properties.Name } |
     ForEach-Object {
        $RObj[$j] | Add-Member -MemberType NoteProperty -Name $_ -Value ''
     }
  }
 }
}
### $RObj | Export-Csv "Samanage_users.csv" -NoTypeInformation
### debugging output instead of `Export-Csv`
$RObj | Format-Table -Property * -AutoSize

Input (modified original XML); entered separately to avoid vertical scrolling in above code:

$samage_users=[xml]@'
<?xml version="1.0" encoding="UTF-8"?>
<users>
        <user>
        <id>"dI"</id>
        <name>"dN"</name>
        <disabled>"dD"</disabled>
        <title>"dT"</title>
        <email>"dE"</email>
        <role>
                <name>"dR"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60044</custom_field_id>
                <value>"dC1"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"dC2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"dC3"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"dSi"</name>
        </site>
    </user>
    <user>
        <id>"d2I"</id>
        <name>"d2N"</name>
        <disabled>"d2D"</disabled>
        <title>"d2T"</title>
        <email>"d2E"</email>
        <role>
                <name>"d2R"</name>
        </role>
        <Reports_To>
            <name>"d2RTn"</name>
            <email>"d2RTe"</email>
        </Reports_To>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60021</custom_field_id>
                <value>"d2C1"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60018</custom_field_id>
                <value>"d2C2"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60034</custom_field_id>
                <value>"d2C3"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"d2Si"</name>
        </site>
    </user>
    <user>
        <id>"d3I"</id>
        <name>"d3N"</name>
        <disabled>"d3D"</disabled>
        <title>"d3T"</title>
        <email>"d3E"</email>
        <role>
                <name>"d3R"</name>
        </role>
        <custom_fields_values>
            <custom_fields_value>
                <custom_field_id>60055</custom_field_id>
                <value>"d3C1"</value>
            </custom_fields_value>
            <custom_fields_value>
                <custom_field_id>60066</custom_field_id>
                <value>"d3C2"</value>
            </custom_fields_value>
        </custom_fields_values>
        <site>
            <name>"d3Si"</name>
        </site>
    </user>
</users>
'@

Output:

PS D:\PShell D:\PShell\SO\47660787.ps1

Email Name  ID    Phone Site   Rs_To   Rs_To_E 60044 60021  60018  60034  60055  60066
----- ----  --    ----- ----   -----   ------- ----- -----  -----  -----  -----  -----
"dE"  "dN"  "dI"        "dSi"                  "dC1" "dC2"  "dC3"
"d2E" "d2N" "d2I"       "d2Si" "d2RTn" "d2RTe"       "d2C1" "d2C2" "d2C3"
"d3E" "d3N" "d3I"       "d3Si"                                            "d3C1" "d3C2"

Note in regard of Tomalak's useful comment stating that XML files should always be read using the XmlDocument object's .Load() method.

###                   $samage_users defined as above i.e. a herestring cast to [xml] type
$xml = New-Object Xml
$xml.Load("Samanage_users.xml")            ### a file containing above herestring content
Compare-Object $samage_users.InnerXml $xml.InnerXml                     ### no difference


问:
Cannot find reason for Redundant nullcheck of this, which is known to be non-null
In Sonar I see a Redundant nullcheck of this, which is known to be non-null Error, but I can not find the Reason for this.

Hope somone can help me to find the reason.

Thx & Regards

Edit1:

```<code>    public class Filter extends AbstractBaseEntity implements Serializable {
    public Filter() {
        super();
    }
}
</code>```

AbstractBaseEntity  has no implemented constructor

答: The code producing this was generated by AspectJ so it was not visible for me, but visible for sonar...</p>

Body:
In Sonar I see a Redundant nullcheck of this, which is known to be non-null Error, but I can not find the Reason for this.

Hope somone can help me to find the reason.

Thx & Regards

Edit1:

    public class Filter extends AbstractBaseEntity implements Serializable {
    public Filter() {
        super();
    }
}

AbstractBaseEntity  has no implemented constructor


问:
Possible to get name of current class from an uninstantiated object in PHP?
I know you can use get_class($this) normally but I need to get the name of the class in a static function where the object hasn't been instantiated.

See the following code:

```<code>class ExampleClass
{
    static function getClassName()
    {
        echo get_class($this); // doesn't work unless the object is instantiated.
    }
}

$test1 = new ExampleClass();
$test1->getClassName(); // works

ExampleClass::getClassName(); // doesn't work
</code>```

答:
I figured out you can use __CLASS__ to get the class name.  Example:</p>

```<code>class ExampleClass
{
    static function getClassName()
    {
        echo __CLASS__;
    }
}
</code>```

OwnerDisplayName: Andrew G. Johnson

ContentLicense: CC BY-SA 2.5

Body:
I know you can use get_class($this) normally but I need to get the name of the class in a static function where the object hasn't been instantiated.

See the following code:

class ExampleClass
{
    static function getClassName()
    {
        echo get_class($this); // doesn't work unless the object is instantiated.
    }
}

$test1 = new ExampleClass();
$test1->getClassName(); // works

ExampleClass::getClassName(); // doesn't work

Body:
I figured out you can use __CLASS__ to get the class name.  Example:

class ExampleClass
{
    static function getClassName()
    {
        echo __CLASS__;
    }
}

LastEditorDisplayName: Andrew G. Johnson


问:
Existing website on ubuntu that want to change to deploy using gitosis - process?
I have an existing directory on my webserver, currently deployed to by file copy, that I'd like to change to deploying with gitosis. How can I create a new gitosis repository to point to this web directory and then clone it down to my local machine?</p>

答:
Gitosis is not ment to be used for website deployment, in fact gitosis is mostly deprecated now in favor of gitolite but that doesn't do website deployment either.

If you want to use git for website deployment you should either use a tool designed to do it, use a non-bare (from normal git init/git clone) repo on the server, or use a bare (from git init --bare) on the server with hooks to do the deployment (there are many different 'howtos' on the web for doing this but personally I think most of them are bad and don't do it in a way I would consider 'correct').


问:
SharePoint 2013 - Get SPListItem versions via REST
I have a SharePoint 2013 List with versioning enabled.
I need to to get SPListItem versions list via REST.
I can get SPListItem by that request: http://spbreportportal/Projects/_api/lists/getbytitle('Projects')/Items(1)
But I can't find in documentation and in response how to retrieve all versions of this item.
Is it possible?

答:
To add more information reagrding on how to obtain all version history from a SharePoint list: </p>

```<code>//Get ID of the Dossier in SP list
strID = items(i - 1).getAttribute("ows_ID")
Debug.Print strID

//Get all Versions of the ID in SP list as a XML
URL1: https://path to site collection/_vti_bin/owssvr.dll?Cmd=Display&List={LIstID}&XMLDATA=TRUE&Query=*&IncludeVersions=TRUE
XDoc3.Load (URL1 & "&FilterField1=ID&FilterOp1=eq&FilterValue1=" & strID)
Set Item = XDoc3.SelectNodes("//rs:data/*")
Set temp3 = XDoc3.SelectNodes("//rs:data/*")
</code>```

Body:
To add more information reagrding on how to obtain all version history from a SharePoint list:

//Get ID of the Dossier in SP list
strID = items(i - 1).getAttribute("ows_ID")
Debug.Print strID

//Get all Versions of the ID in SP list as a XML
URL1: https://path to site collection/_vti_bin/owssvr.dll?Cmd=Display&List={LIstID}&XMLDATA=TRUE&Query=*&IncludeVersions=TRUE
XDoc3.Load (URL1 & "&FilterField1=ID&FilterOp1=eq&FilterValue1=" & strID)
Set Item = XDoc3.SelectNodes("//rs:data/*")
Set temp3 = XDoc3.SelectNodes("//rs:data/*")


问:
Show direction from the current location to desired location using google maps in asp.net
Currently i'm trying to find code for getting directions from current location to a desired location in google map. Scenario: Onloading my aspx page the map should view my current location and when i click a desired location in the drop down box it should show direction from my current location. I'm just a beginner as a programmer and forgive me if my question is silly..

the code for showing my current location is.....

```<code><html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>Get User Current Location using Google Map Geolocation API Service in asp.net website</title>
    <style type="text/css">
    html { height: 100% }
    body { height: 100%; margin: 0; padding: 0 }
    #map_canvas { height: 100% }
    </style>
    <script type="text/javascript"
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD1axwAuIx3vQ0oIJLxkUg9P1SF38AkT2A&sensor=false">
    </script>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places">
    </script>
    <script type="text/javascript">
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(success);
        } else {
            alert("Geo Location is not supported on your current browser!");
        }
        function success(position) {
            var lat = position.coords.latitude;
            var long = position.coords.longitude;
            var city = position.coords.locality;
            var myLatlng = new google.maps.LatLng(lat, long);
            var myOptions = {
                center: myLatlng,
                zoom: 12,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "lat: " + lat + " long: " + long
            });

            marker.setMap(map);
           // var infowindow = new google.maps.InfoWindow({ content: "<b>User Address</b><br/> Latitude:" + lat + "<br /> Longitude:" + long + "" });
            infowindow.open(map, marker);
        }
    </script>

    </head>
    <body >
    <form id="form1" runat="server">
    <div id="map_canvas" style="width: 500px; height: 400px"></div>
    </form>
    </body>
    </html>
</code>```

答:
```<code>  <script>
   function initMap(){
       var markerArray = [];
       var directionsService = new google.maps.DirectionsService;
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function (position){
            map = new google.maps.Map(document.getElementById('map'),{
                zoom: 17,
                center: {lat: position.coords.latitude, lng:
                 position.coords.longitude}
            });
            var marker = new google.maps.Marker({
                draggable: true,
                position: {lat: position.coords.latitude, lng:
      position.coords.longitude},
                map: map
            });
            directionsDisplay.setMap(map);
        },
        function (){
            alert("unable to get current loaction!");
        });
    }
    else{
        alert("Location service is not support in your web browser!");
    }

    var directionsDisplay = new google.maps.DirectionsRenderer;
    calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map);
    var onChangeHandler = function (){
        calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map);
    };
    document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('end').addEventListener('change', onChangeHandler);
}

function calculateAndDisplayRoute(directionsDisplay, directionsSerivce, markerArray, map){
    directionsSerivce.route({
        origin: document.getElementById('start').value,
        destination: document.getElementById('end').value,
        travelMode: google.maps.TravelMode.DRIVING
    },
    function(response, status){
        if(status === 'OK'){
            document.getElementById('warnings-panel').innerHTML = '<b>' + response.routes[0].warnings + '</b>';
            directionsDisplay.setDirections(response);

        }
        else{
            window.alert('Direction request failed due to ' + status);
        }
    });
}
</code>```

Markup

```<code>      <b>Start: </b>
       <select id="start">
        <option>Select Start Location</option>
        <option value="I-9/2, Islamabad, ICT">I-9/2</option>
        <option value="I-10/2, Islamabad, ICT">I-10/2</option>
        <option value="G-10/1, Islamabad, ICT">G-10/1</option>
        <option value="F-8, Islamabad, ICT">F-8</option>
        <option value="Shah Faisal Mosque, Islamabad, ICT">Faisal
      Masjid</option>
        <option value="I-8/2, Islamabad, ICT">I-8/2</option>
        <option value="F-5, Islamabad, ICT">F-5</option>
        <option value="Zero Point, Islamabad, ICT">Zero Point</option>
        <option value="F-6/7, Islamabad, ICT">F-6/7</option>
        <option value="F-5/1, Islamabad, ICT">F-5/1</option>
        <option value="F-7, Islamabad, ICT">F-7</option>
        <option value="Golra, Islamabad, ICT">Golra Morr</option>
        <option value="Zoo, Islamabad">Zoo</option>
        <option value="Muree, Muree">Muree</option>
       </select>
      <b>End: </b>
      <select id="end">
        <option>Select Distination</option>
        <option value="I-8/2, Islamabad, ICT">I-8/2</option>
        <option value="F-5, Islamabad, ICT">F-5</option>
        <option value="Zero Point, Islamabad, ICT">Zero Point</option>
        <option value="F-6/7, Islamabad, ICT">F-6/7</option>
        <option value="F-5/1, Islamabad, ICT">F-5/1</option>
        <option value="F-7, Islamabad, ICT">F-7</option>
        <option value="Golra, Islamabad, ICT">Golra Morr</option>
        <option value="Zoo, Islamabad">Zoo</option>
        <option value="I-9/2, Islamabad, ICT">I-9/2</option>
        <option value="I-10/2, Islamabad, ICT">I-10/2</option>
        <option value="G-10/1, Islamabad, ICT">G-10/1</option>
        <option value="F-8, Islamabad, ICT">F-8</option>
        <option value="Shah Faisal Mosque, Islamabad, ICT">Faisal
      Masjid</option>
        <option value="Fatima jinah park, Islamabad">Fatima jinah
       park</option>
      </select>
            <div id="map">

            </div>

<div id="warnings-panel"></div>
</code>```

Body:
Currently i'm trying to find code for getting directions from current location to a desired location in google map. Scenario: Onloading my aspx page the map should view my current location and when i click a desired location in the drop down box it should show direction from my current location. I'm just a beginner as a programmer and forgive me if my question is silly..

the code for showing my current location is.....

    <title>Get User Current Location using Google Map Geolocation API Service in asp.net website</title>

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

    </form>

Body:
  <script>
   function initMap(){
       var markerArray = [];
       var directionsService = new google.maps.DirectionsService;
      if(navigator.geolocation){
        navigator.geolocation.getCurrentPosition(function (position){
            map = new google.maps.Map(document.getElementById('map'),{
                zoom: 17,
                center: {lat: position.coords.latitude, lng:
                 position.coords.longitude}
            });
            var marker = new google.maps.Marker({
                draggable: true,
                position: {lat: position.coords.latitude, lng:
      position.coords.longitude},
                map: map
            });
            directionsDisplay.setMap(map);
        },
        function (){
            alert("unable to get current loaction!");
        });
    }
    else{
        alert("Location service is not support in your web browser!");
    }

    var directionsDisplay = new google.maps.DirectionsRenderer;
    calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map);
    var onChangeHandler = function (){
        calculateAndDisplayRoute(directionsDisplay, directionsService, markerArray, map);
    };
    document.getElementById('start').addEventListener('change', onChangeHandler);
    document.getElementById('end').addEventListener('change', onChangeHandler);
}

function calculateAndDisplayRoute(directionsDisplay, directionsSerivce, markerArray, map){
    directionsSerivce.route({
        origin: document.getElementById('start').value,
        destination: document.getElementById('end').value,
        travelMode: google.maps.TravelMode.DRIVING
    },
    function(response, status){
        if(status === 'OK'){
            document.getElementById('warnings-panel').innerHTML = '<b>' + response.routes[0].warnings + '</b>';
            directionsDisplay.setDirections(response);

        }
        else{
            window.alert('Direction request failed due to ' + status);
        }
    });
}

Markup

      <b>Start: </b>
       <select id="start">
        <option>Select Start Location</option>
        <option value="I-9/2, Islamabad, ICT">I-9/2</option>
        <option value="I-10/2, Islamabad, ICT">I-10/2</option>
        <option value="G-10/1, Islamabad, ICT">G-10/1</option>
        <option value="F-8, Islamabad, ICT">F-8</option>
        <option value="Shah Faisal Mosque, Islamabad, ICT">Faisal
      Masjid</option>
        <option value="I-8/2, Islamabad, ICT">I-8/2</option>
        <option value="F-5, Islamabad, ICT">F-5</option>
        <option value="Zero Point, Islamabad, ICT">Zero Point</option>
        <option value="F-6/7, Islamabad, ICT">F-6/7</option>
        <option value="F-5/1, Islamabad, ICT">F-5/1</option>
        <option value="F-7, Islamabad, ICT">F-7</option>
        <option value="Golra, Islamabad, ICT">Golra Morr</option>
        <option value="Zoo, Islamabad">Zoo</option>
        <option value="Muree, Muree">Muree</option>
       </select>
      <b>End: </b>
      <select id="end">
        <option>Select Distination</option>
        <option value="I-8/2, Islamabad, ICT">I-8/2</option>
        <option value="F-5, Islamabad, ICT">F-5</option>
        <option value="Zero Point, Islamabad, ICT">Zero Point</option>
        <option value="F-6/7, Islamabad, ICT">F-6/7</option>
        <option value="F-5/1, Islamabad, ICT">F-5/1</option>
        <option value="F-7, Islamabad, ICT">F-7</option>
        <option value="Golra, Islamabad, ICT">Golra Morr</option>
        <option value="Zoo, Islamabad">Zoo</option>
        <option value="I-9/2, Islamabad, ICT">I-9/2</option>
        <option value="I-10/2, Islamabad, ICT">I-10/2</option>
        <option value="G-10/1, Islamabad, ICT">G-10/1</option>
        <option value="F-8, Islamabad, ICT">F-8</option>
        <option value="Shah Faisal Mosque, Islamabad, ICT">Faisal
      Masjid</option>
        <option value="Fatima jinah park, Islamabad">Fatima jinah
       park</option>
      </select>
            <div id="map">

            </div>

<div id="warnings-panel"></div>


问:
Quine Confusion.What actually does quine prints?
Does a quine print the ACTUAL code of the program i.e not obfuscated or does it print the obfuscated program?</p>

答:
Following is a simple quine code. This source code need to saved as "quine_file.c". Compile and execute.

Here a simple file pointer is taken and it is used to read the source file line by line and print it to the stdout.

```<code>#include <stdio.h>
#include <stdlib.h>

void main()
{
      FILE *fp = NULL;
      char * line = NULL;
      int len = 0;
      int read;
      fp = fopen("quine_file.c","r");
      if(fp == NULL)
           return;
      while ((read = getline(&line, &len, fp)) != -1)
      {
           printf("%s", line);
      }
      fclose(fp);
      if (line)
          free(line);
      exit(EXIT_SUCCESS);
}
</code>```

Body:
Following is a simple quine code. This source code need to saved as "quine_file.c". Compile and execute.

Here a simple file pointer is taken and it is used to read the source file line by line and print it to the stdout.

#include <stdio.h>
#include <stdlib.h>

void main()
{
      FILE *fp = NULL;
      char * line = NULL;
      int len = 0;
      int read;
      fp = fopen("quine_file.c","r");
      if(fp == NULL)
           return;
      while ((read = getline(&line, &len, fp)) != -1)
      {
           printf("%s", line);
      }
      fclose(fp);
      if (line)
          free(line);
      exit(EXIT_SUCCESS);
}


问:
Adding Tix Widget to Tkinter Container
I'm working with Tkinter in Python 2.7 on Windows 7, and found the need to create a popup box with a tree-style list of checkboxes.  I could not find this in Tkinter, or ttk.  I did, however, find it in Tix in the CheckList widget.  I got a working standalone example using Tix, but I cannot figure out how to add my Tix.CheckList to my ttk.Frame that controls my main program.

Surely I am not forced to use Tix framework from the ground up?

```<code>import Tix
import pandas as pd
import Tkinter as tk

class TreeCheckList(object):
    def __init__(self, root):
        self.root = root

        self.cl = Tix.CheckList(self.root)
        self.cl.pack(fill=Tix.BOTH, expand=Tix.YES)
        self.cl.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white', selectforeground='black', drawbranch=True, pady=5)

        self.cl.hlist.add('ALL', text='All Messages')

        self.cl.hlist.add('ALL.First', text='First')
        self.cl.setstatus('ALL.First', "off")

        self.cl.hlist.add('ALL.Second', text='Second')
        self.cl.setstatus('ALL.Second', "off")

        self.cl.autosetmode()

def main():
    root = Tix.Tk()
    top = Tix.Toplevel(root)

    checklist = TreeCheckList(top)
    root.update()
    top.tkraise()
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

The above code works in a standalone program using all Tix widgets.  However, when I try to implement this into my larger program, I receive a TclError: invalid command name "tixCheckList"

To simulate this in the standalone, I changed the lines:

```<code>root = Tix.Tk()
top = Tix.Toplevel(root)
</code>```

to

```<code>root = tk.Tk()
top = tk.Toplevel(root)
</code>```

I was hoping I could just implement a Tix.Toplevel, placing it on a tk.Tk() root, but same issue.

Am I only allowed to use Tix frames when using a Tix widget, or am I misunderstanding something?  If anyone has good Tix documentation, I would LOVE whatever I can get.  It seems good docs on it are few and far between.  Or is this same functionality included in ttk and I've just overlooked it?  It seems to be one of the only things left out.

答:
I have just learned that apparently only root needs to be a Tix class. Since Tk, and therefore ttk, classes appear to be added to the Tix root just fine (since most of them extend the Tkinter classes anyway), this appears to be a "fix".  So my problem may have been solved by changing just

root = tk.Tk()

to

root = Tix.Tk()

This did require that I pull Tix into a part of my program I wasn't wanting for encapsulation purposes, but I guess there's no other way.

Title: Adding Tix Widget to Tkinter Container

Body:
I'm working with Tkinter in Python 2.7 on Windows 7, and found the need to create a popup box with a tree-style list of checkboxes.  I could not find this in Tkinter, or ttk.  I did, however, find it in Tix in the CheckList widget.  I got a working standalone example using Tix, but I cannot figure out how to add my Tix.CheckList to my ttk.Frame that controls my main program.

Surely I am not forced to use Tix framework from the ground up?

import Tix
import pandas as pd
import Tkinter as tk

class TreeCheckList(object):
    def __init__(self, root):
        self.root = root

        self.cl = Tix.CheckList(self.root)
        self.cl.pack(fill=Tix.BOTH, expand=Tix.YES)
        self.cl.hlist.config(bg='white', bd=0, selectmode='none', selectbackground='white', selectforeground='black', drawbranch=True, pady=5)

        self.cl.hlist.add('ALL', text='All Messages')

        self.cl.hlist.add('ALL.First', text='First')
        self.cl.setstatus('ALL.First', "off")

        self.cl.hlist.add('ALL.Second', text='Second')
        self.cl.setstatus('ALL.Second', "off")

        self.cl.autosetmode()

def main():
    root = Tix.Tk()
    top = Tix.Toplevel(root)

    checklist = TreeCheckList(top)
    root.update()
    top.tkraise()
    root.mainloop()

if __name__ == '__main__':
    main()

The above code works in a standalone program using all Tix widgets.  However, when I try to implement this into my larger program, I receive a TclError: invalid command name "tixCheckList"

To simulate this in the standalone, I changed the lines:

root = Tix.Tk()
top = Tix.Toplevel(root)

to

root = tk.Tk()
top = tk.Toplevel(root)

I was hoping I could just implement a Tix.Toplevel, placing it on a tk.Tk() root, but same issue.

Am I only allowed to use Tix frames when using a Tix widget, or am I misunderstanding something?  If anyone has good Tix documentation, I would LOVE whatever I can get.  It seems good docs on it are few and far between.  Or is this same functionality included in ttk and I've just overlooked it?  It seems to be one of the only things left out.


问:
Running SQL query on R for rows with NA
I'm trying to run a sql query in R using SQLDF but it keeps returning the error :  Error in rsqlite_send_query(conn@ptr, statement) : no such column: NA.

The query looks like this:

sqldf("select ID, PhoneNO, type from sdi_update_2 where type = NA limit 20")

Any help will be appreciated.

Thanks

答:
NA isn't a thing in SQL, but NULL is - and sqldf converts R's NAs to SQL nulls. Try:

```<code>sqldf("select ID, PhoneNO, type from sdi_update_2 where type is NULL limit 20")
</code>```

Demo:

```<code>library(sqldf)
x = data.frame(a = c(1, NA))
sqldf("select * from x where a is NULL")
#    a
# 1 NA
</code>```

Title: Running SQL query on R for rows with NA

Body:
NA isn't a thing in SQL, but NULL is - and sqldf converts R's NAs to SQL nulls. Try:

sqldf("select ID, PhoneNO, type from sdi_update_2 where type is NULL limit 20")

Demo:

library(sqldf)
x = data.frame(a = c(1, NA))
sqldf("select * from x where a is NULL")
#    a
# 1 NA


问:
Path to static assets in vue.js application
I am developing a single page application based on the vue-cli webpack template. Since we have to use static assets as well, we need to reference them in our stylesheet.

The official documentation recommends to use an absolute path like the following one:

```<code>background-image: url('/assets/images/lo/example2.svg');
</code>```

The problem is, that static assets won't be processed by the vue-loader and webpack itself, so the urls won't be set correctly in the final output stylesheet. All assets that will be processed by the webpack url-loader will get the correct relative url depending on your publicPath configuration. The same effect is desired for static assets.

Do you have any idea how to use static assets in combination with a vue.js-based application?

Update

After researching and a lot of trial and error I've decided to place the final stylesheet and the script bundle inside the root folder next to the index.html. The generated paths will work properly. Not the most optimal solution, since I prefer subfolders for scripts and stylesheet (despite they contain only one file). But nevertheless I have a build process that generates consistent and valid artifacts.

答:
For "real" static assets, use the static directory.

In comparison, files in static/ are not processed by Webpack at all: they are directly copied to their final destination as-is, with the same filename. You must reference these files using absolute paths, which is determined by joining build.assetsPublicPath and build.assetsSubDirectory in config.js.

You can also overwrite this default path in config/index.js

```<code>module.exports = {
  // ...
  build: {
    assetsPublicPath: '/',
    assetsSubDirectory: 'static'
  }
}
</code>```

Any file placed in static/ should be referenced using the absolute URL /static/[filename]. If you change assetSubDirectory to assets, then these URLs will need to be changed to /assets/[filename].

Body:
I am developing a single page application based on the vue-cli webpack template. Since we have to use static assets as well, we need to reference them in our stylesheet.

The official documentation recommends to use an absolute path like the following one:

background-image: url('/assets/images/lo/example2.svg');

The problem is, that static assets won't be processed by the vue-loader and webpack itself, so the urls won't be set correctly in the final output stylesheet. All assets that will be processed by the webpack url-loader will get the correct relative url depending on your publicPath configuration. The same effect is desired for static assets.

Do you have any idea how to use static assets in combination with a vue.js-based application?

Update

After researching and a lot of trial and error I've decided to place the final stylesheet and the script bundle inside the root folder next to the index.html. The generated paths will work properly. Not the most optimal solution, since I prefer subfolders for scripts and stylesheet (despite they contain only one file). But nevertheless I have a build process that generates consistent and valid artifacts.

Body:
For "real" static assets, use the static directory.

In comparison, files in static/ are not processed by Webpack at all: they are directly copied to their final destination as-is, with the same filename. You must reference these files using absolute paths, which is determined by joining build.assetsPublicPath and build.assetsSubDirectory in config.js.

You can also overwrite this default path in config/index.js

module.exports = {
  // ...
  build: {
    assetsPublicPath: '/',
    assetsSubDirectory: 'static'
  }
}

Any file placed in static/ should be referenced using the absolute URL /static/[filename]. If you change assetSubDirectory to assets, then these URLs will need to be changed to /assets/[filename].


问:
Using strikethrough in ListView using ArrayAdapter
I have added elements in ListView through database using array adapter. Here I want the element to have a strikethrough. How can I do this?

Here is the code I am using:

```<code>String q4 = "select * from todolist;";
Cursor d = database.rawQuery(q4, null);
if(d != null && d.moveToFirst()) {
    do {
        String element =d.getString(d.getColumnIndex("elist"));
        al.add(element);
        ArrayAdapter ad = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,al);
        list.setAdapter(ad);
    } while (d.moveToNext());
}
</code>```

答: For anyone looking for an answer, Array Adapter cannot alter the view of its contents. Using Base adapter is the best option.</p>

Body:
I have added elements in ListView through database using array adapter. Here I want the element to have a strikethrough. How can I do this?

Here is the code I am using:

String q4 = "select * from todolist;";
Cursor d = database.rawQuery(q4, null);
if(d != null && d.moveToFirst()) {
    do {
        String element =d.getString(d.getColumnIndex("elist"));
        al.add(element);
        ArrayAdapter ad = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,al);
        list.setAdapter(ad);
    } while (d.moveToNext());
}


问:
Add text next to a Point in PCL visualizer
I have an application where I successfully plot 2D laser range data from a LiDAR in real-time and run PCL's Euclidean clustering algorithm to paint those cluster points in a different color. I would however like to add a text next to each detected cluster and tell its distance from the sensor. I do have the coordinate of the centroid point of each detected cluster but when I try to use the addText:

bool pcl::visualization::PCLVisualizer::addText (const std::string &    text, int xpos, int ypos,double r,double g,double b,const std::string & id = "")

text: Text to be printed in window

xpos: position in x

ypos: position in y

r: red

g: green

b: blue

id: Text ID tag

It seems like the function addText() puts the text in on PIXEL x- and y-values in stead of real-world values (meters). However, PCLs other method such as "addPoint()", addCircle() etc are indeed placing the data based on real world measurements.

Does anyone have experience with transforming spatial coordinates to pixels in PCL visualizer, or have successfully plotted text in other ways?

Below is a screenshot of my application. Clusters are drawn in red with a white circle around the centroid. At the bottom left I'm printing the distance of each cluster. As can be seen they are just stacked on top of each other instead of being added on top of its own white circle.

Thankful for any help

regards
Screenshot

答:
Okey I got it to work with a function called: pcl::visualization::PCLVisualizer::addText3D.

There is no support for erasing/updating all text fields that have been added over a period of time though, so one always needs to know the ID tags of each respective text and iterate through them to erase/update them.

You can delete texts with function: pcl::visualization::PCLVisualizer::removeText3D

Do however keep in mind that text ID tags share the same memory space as other ID name tags (e.g names you have given circles, clouds or cylinders etc). This means that if you try to add a text of name "abc" they command will fail if there is a circle pressent in your window named "abc".

Below is a visual example of how it looks now.Obstacle distance plotting


问:
Restrict AWS Lambda invocation to a single Alexa skill
I am trying to learn Alexa skill programming as part of which I have set up a skill interface in the Amazon developer portal and the corresponding AWS Lambda function. The skill is functioning fine but I have a question on the security aspect of the Lambda function. I have selected Alexa Skill Kit as the trigger for the Lambda function and am also comparing the application id in the request to the application id of the skill to verify request is intended for the function. (https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/handling-requests-sent-by-alexa).

But even then how do I restrict the Lambda function to be invoked by another skill which gets to know the Lambda arn? Can this not be misused to waste compute resources etc?

答:
You already answered your own question. Since you are checking this specific Alexa skill ID in your lambda function it will be almost impossible to call it from anywhere else then this skill. exmple:

```<code>exports.handler = function(event, context, callback){
  var alexa = Alexa.handler(event, context, callback);
  // security so this set APP_ID from this specific Alexa skill is the onlly one that can execute this code
  alexa.appId = APP_ID;
  alexa.registerHandlers(handlers);
  alexa.execute();
};
</code>```

where APP_ID is the id if you specific Alexa skill that only has the right to execute this function.

hope this helps you forward.

Body:
You already answered your own question. Since you are checking this specific Alexa skill ID in your lambda function it will be almost impossible to call it from anywhere else then this skill. exmple:

exports.handler = function(event, context, callback){
  var alexa = Alexa.handler(event, context, callback);
  // security so this set APP_ID from this specific Alexa skill is the onlly one that can execute this code
  alexa.appId = APP_ID;
  alexa.registerHandlers(handlers);
  alexa.execute();
};

where APP_ID is the id if you specific Alexa skill that only has the right to execute this function.

hope this helps you forward.


问:
How can I test the case where invisible Recaptcha detects a suspicious user?
I plan to use Google's invisible recaptcha to make sure bots don't sign up on my website. I think I followed all the instructions, but I want to test it to make sure it works and see how it looks. But I'm a human, so it just lets me click with no problems. Is there a way to make the invisible recaptcha think I'm a bot so I can test that experience on my site?</p>

答: Try accessing your website through Tor. If you try using Google Search through Tor it will continuously offer you a reCAPTCHA, because bots are often using the IP addresses associated with Tor and Google knows this. I imagine it will work for your website as well.</p>


问:
how to connect two projects Laravel 4.2 and laravel 5.5?
i have a laravel 4.2 project that i want to connect it to laravel 5.5 project

Q1) how to login in the first and and authenticated to the second to so i don't have to login to the second

Q2)how to connect them to the same DB

Q3)let's say i'm in page X in laravel 4.2 and i want to direct it to Y in laravel 5.5 where i should write the route in laravel 4.2 or in 5.5 ?

at the end both of the projects are going to be on the same server and have the same domain if that is going to be helpful

答:
Q1) how to login in the first and and authenticated to the second to so i don't have to login to the second

if the 2 webapp are in the same domain, it should not be an issue
  especially if they use the same database.

Q2)how to connect them to the same DB

just use the same credentials and save it on each env file.

Q3)let's say i'm in page X in laravel 4.2 and i want to direct it to Y in laravel 5.5 where i should write the route in laravel 4.2 or in 5.5 ?

you can use the function route instead use the manual routing like
  to('somepage-on-theother-laravel') this is a tedious work. So i want
  to ask if why are you using the 2 webapp in the same domain instead of
  just using 1 webapp framework. Im thinking that this laravel 4.2 is
  the existing one and you're create a new one and you want to use the
  laravel 5.5 right?


问:
nth-child formula for hover state - all elements except the first one
I want to select all elements except the first one for a hover state. I'm doing this using nth-child() selector.

I'm following this guide: https://css-tricks.com/useful-nth-child-recipies/

It gives a formula for selecting all but the first 5 - the example they give is below:

```<code>li:nth-child(n+6) {
    color: green;
}
</code>```

I want to take this and apply it so that it selects all but the first element. My approach to do that is so:

```<code>li:nth-child(n+1) {
    color: green;
}
</code>```

Is this not correct?

I need to try to apply this to a hover state situation, where it only performs the :hover action all all but the first li. See the embed below:

  li {
    display: inline-block;
  }

  a {
    margin-right: 1.8rem;
      padding-bottom: 23px;
  }

  #login-signup li:nth-child(n+1):hover {
    text-decoration: none;
    border-bottom: 3px solid #292c2e;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
      <li> No Underline</li>
      <li>Log In</li>
      <li>Sign Up</li>
    </ul></code>```

How do you apply the formula for selecting anything but the first element with nth-child? Does :hover not work with nth-child? I can't find any sources that say otherwise.

答:
Personally I prefer to do this without nth child, and just use a simple sibling selector:

li + li:hover {
  text-decoration: underline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul></code>```

Body:
I want to select all elements except the first one for a hover state. I'm doing this using nth-child() selector.

I'm following this guide: https://css-tricks.com/useful-nth-child-recipies/

It gives a formula for selecting all but the first 5 - the example they give is below:

li:nth-child(n+6) {
    color: green;
}

I want to take this and apply it so that it selects all but the first element. My approach to do that is so:

li:nth-child(n+1) {
    color: green;
}

Is this not correct?

I need to try to apply this to a hover state situation, where it only performs the :hover action all all but the first li. See the embed below:

  li {
    display: inline-block;
  }

  a {
    margin-right: 1.8rem;
      padding-bottom: 23px;
  }

  #login-signup li:nth-child(n+1):hover {
    text-decoration: none;
    border-bottom: 3px solid #292c2e;
  }

 No Underline

Log In

Sign Up

How do you apply the formula for selecting anything but the first element with nth-child? Does :hover not work with nth-child? I can't find any sources that say otherwise.

Body:
Personally I prefer to do this without nth child, and just use a simple sibling selector:

li + li:hover {
  text-decoration: underline;
}

<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>


问:
Hibernate EntityManager don't close connection
I have a project using Hibernate JPA with persistence.xml and EntityManager

This is my persitence.xml

```<code>    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="none"/>
         <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
         <property name="hibernate.connection.username" value="*****"/>
         <property name="hibernate.connection.password" value="******"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost/hibernateTest"/>

          <property name="hibernate.c3p0.min_size" value="5"/>
          <property name="hibernate.c3p0.max_size" value="20"/>
          <property name="hibernate.c3p0.timeout" value="20"/>
          <property name="hibernate.c3p0.max_statements" value="50"/>
          <property name="hibernate.c3p0.idle_test_period" value="10"/>

      </properties>
   </persistence-unit>
</persistence>
</code>```

I have a class EMF that is handling the EntityManager and EntityManagerFactory

```<code>package entityManager;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EMF {

    protected EntityManager entityManager;
    protected static EntityManagerFactory entityManagerFactory;
    public EMF ()
    {

        if(entityManagerFactory == null){

            System.out.println("EMF.EMF()");
            entityManagerFactory = Persistence.createEntityManagerFactory("JPAService");
        }

        if(entityManager == null || (!entityManager.isOpen()))
        {

            System.out.println("EMF.EMF().init entityManager");
            entityManager = entityManagerFactory.createEntityManager();
        }

    }

    public EntityManager getEM(){
        return this.entityManager;
    }
    public void close(){

        while(entityManager.isOpen())
        {
            System.out.println("EMF.close()");
            entityManager.close();
        }
        entityManager = null;
    }
}
</code>```

When I need an EntityManager I call it like this:

```<code>  EMF emf =null;
  try{
    emf = new EMF();
    EntityManager entityManager = emf.getEM();

    entityManager.getTransaction().begin();
    entityManager.persist(t);
    entityManager.getTransaction().commit();
   }
   catch(Exception e)
   {
      e.printStackTrace();
   }
   finally(
     if(emf != null)
        emf.close();
   }
</code>```

But this doesn't release the connection to the pool. The Connection runns over the timout and seems to be locked.

When the max_size of 20 is reached hibernate isn't able to connect to the databese.

Can someone find my mistake??

THX

EDIT:  If I remove entityManager.persist(t);  it works!??
EDIT2: this just appears if I have an exception while persist();

Edit3: so I found out that this was because of the exception and I didn't rollback the transaction.

so

emf.getTransaction().rollback(); in the catch block solved my Problem

Body:
I have a project using Hibernate JPA with persistence.xml and EntityManager

This is my persitence.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
         <property name="hibernate.hbm2ddl.auto" value="none"/>
         <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
         <property name="hibernate.connection.username" value="*****"/>
         <property name="hibernate.connection.password" value="******"/>
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost/hibernateTest"/>

          <property name="hibernate.c3p0.min_size" value="5"/>
          <property name="hibernate.c3p0.max_size" value="20"/>
          <property name="hibernate.c3p0.timeout" value="20"/>
          <property name="hibernate.c3p0.max_statements" value="50"/>
          <property name="hibernate.c3p0.idle_test_period" value="10"/>

      </properties>
   </persistence-unit>
</persistence>

I have a class EMF that is handling the EntityManager and EntityManagerFactory

package entityManager;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EMF {

    protected EntityManager entityManager;
    protected static EntityManagerFactory entityManagerFactory;
    public EMF ()
    {

        if(entityManagerFactory == null){

            System.out.println("EMF.EMF()");
            entityManagerFactory = Persistence.createEntityManagerFactory("JPAService");
        }

        if(entityManager == null || (!entityManager.isOpen()))
        {

            System.out.println("EMF.EMF().init entityManager");
            entityManager = entityManagerFactory.createEntityManager();
        }

    }

    public EntityManager getEM(){
        return this.entityManager;
    }
    public void close(){

        while(entityManager.isOpen())
        {
            System.out.println("EMF.close()");
            entityManager.close();
        }
        entityManager = null;
    }
}

When I need an EntityManager I call it like this:

  EMF emf =null;
  try{
    emf = new EMF();
    EntityManager entityManager = emf.getEM();

    entityManager.getTransaction().begin();
    entityManager.persist(t);
    entityManager.getTransaction().commit();
   }
   catch(Exception e)
   {
      e.printStackTrace();
   }
   finally(
     if(emf != null)
        emf.close();
   }

But this doesn't release the connection to the pool. The Connection runns over the timout and seems to be locked.

When the max_size of 20 is reached hibernate isn't able to connect to the databese.

Can someone find my mistake??

THX

EDIT:  If I remove entityManager.persist(t);  it works!??
EDIT2: this just appears if I have an exception while persist();

Edit3: so I found out that this was because of the exception and I didn't rollback the transaction.

so

emf.getTransaction().rollback(); in the catch block solved my Problem


问:
Is there a safe way to use SqlBulkCopy across multiple threads
We've introduced SqlBulkCopy on a batch job that executes across multiple threads but are now getting intermittent deadlocks. We're not using the table lock option. The table being inserted has a clustered index.

Each thread is inserting for a unique PortfolioSnapshotId (with a batch of AssetIds)

Is there any way we can safely use SqlBulkCopy in this scenario?

XML below:

```<code><event name="xml_deadlock_report" package="sqlserver" timestamp="2017-12-06T02:38:31.382Z">
  <data name="xml_report">
    <type name="xml" package="package0" />
    <value>
      <deadlock>
        <victim-list>
          <victimProcess id="process248e1c96108" />
        </victim-list>
        <process-list>
          <process id="process248e1c96108" taskpriority="0" logused="63904" waitresource="PAGE: 14:1:289932632 " waittime="4523" ownerId="2409980792" transactionname="user_transaction" lasttranstarted="2017-12-06T02:38:26.657" XDES="0x2453d39ce58" lockMode="IX" schedulerid="14" kpid="24604" status="suspended" spid="151" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-12-06T02:38:26.657" lastbatchcompleted="2017-12-06T02:38:26.657" lastattention="2017-12-06T02:38:23.760" clientapp="XXXX" hostname="XXXX" hostpid="137000" loginname="XXXX" isolationlevel="read committed (2)" xactid="2409980792" currentdb="14" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
            <executionStack>
              <frame procname="adhoc" line="1" stmtend="1206" sqlhandle="0x020000000f2bea1e535f1cbf04ef8318984df8965399be020000000000000000000000000000000000000000">
unknown    </frame>
            </executionStack>
            <inputbuf>
insert bulk TableName ([AssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [ParentAssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [PortfolioSnapshotId] UniqueIdentifier, [Quantity] Decimal(28,8), [CompressedProperties] VarBinary(max)) with (CHECK_CONSTRAINTS)   </inputbuf>
          </process>
          <process id="process248e1c8cca8" taskpriority="0" logused="67244" waitresource="PAGE: 14:1:289933280 " waittime="4523" ownerId="2409980337" transactionname="user_transaction" lasttranstarted="2017-12-06T02:38:26.220" XDES="0x25e82396e58" lockMode="IX" schedulerid="2" kpid="33292" status="suspended" spid="158" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-12-06T02:38:26.220" lastbatchcompleted="2017-12-06T02:38:26.220" lastattention="2017-12-06T02:38:24.507" clientapp="XXXX" hostname="XXXX" hostpid="137000" loginname="XXXX" isolationlevel="read committed (2)" xactid="2409980337" currentdb="14" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
            <executionStack>
              <frame procname="adhoc" line="1" stmtend="1206" sqlhandle="0x020000000f2bea1e535f1cbf04ef8318984df8965399be020000000000000000000000000000000000000000">
unknown    </frame>
            </executionStack>
            <inputbuf>
insert bulk TableName ([AssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [ParentAssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [PortfolioSnapshotId] UniqueIdentifier, [Quantity] Decimal(28,8), [CompressedProperties] VarBinary(max)) with (CHECK_CONSTRAINTS)   </inputbuf>
          </process>
        </process-list>
        <resource-list>
          <pagelock fileid="1" pageid="289932632" dbid="14" subresource="FULL" objectname="XXXX.dbo.TableName" id="lock247f3004d00" mode="X" associatedObjectId="72057594048872448">
            <owner-list>
              <owner id="process248e1c8cca8" mode="X" />
            </owner-list>
            <waiter-list>
              <waiter id="process248e1c96108" mode="IX" requestType="wait" />
            </waiter-list>
          </pagelock>
          <pagelock fileid="1" pageid="289933280" dbid="14" subresource="FULL" objectname="XXXX.dbo.TableName" id="lock247f4f97c80" mode="X" associatedObjectId="72057594045661184">
            <owner-list>
              <owner id="process248e1c96108" mode="X" />
            </owner-list>
            <waiter-list>
              <waiter id="process248e1c8cca8" mode="IX" requestType="wait" />
            </waiter-list>
          </pagelock>
        </resource-list>
      </deadlock>
    </value>
  </data>
</event>
</code>```

Table:

```<code>CREATE TABLE [dbo].[TableName](
  [AssetId] [nvarchar](255) NOT NULL,
  [ParentAssetId] [nvarchar](255) NULL,
  [PortfolioSnapshotId] [uniqueidentifier] NOT NULL,
  [Quantity] [decimal](28, 8) NULL,
  [CompressedProperties] [varbinary](max) NULL
 CONSTRAINT [PK_TableName] PRIMARY KEY CLUSTERED
(
  [PortfolioSnapshotId] ASC,
  [AssetId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[TableName]  WITH CHECK ADD  CONSTRAINT [FK_TableName_PortfolioSnapshot] FOREIGN KEY([PortfolioSnapshotId])
REFERENCES [dbo].[PortfolioStore_PortfolioSnapshot] ([Id])

CREATE NONCLUSTERED INDEX [IX_TableName_PortfolioSnapshotId] ON [dbo].[TableName]
(
  [PortfolioSnapshotId] ASC
)
INCLUDE (   [AssetId],
  [ParentAssetId],
  [Quantity],
  [Price]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
</code>```

答: The deadlock occurs because of the presence of the NC index (page lock IX->X on two different object Id from the same object name). I don't see the reason for the NC index, considering that the clustered index is on the same key and more selective. I would remove that NC index.</p>

Body:
We've introduced SqlBulkCopy on a batch job that executes across multiple threads but are now getting intermittent deadlocks. We're not using the table lock option. The table being inserted has a clustered index.

Each thread is inserting for a unique PortfolioSnapshotId (with a batch of AssetIds)

Is there any way we can safely use SqlBulkCopy in this scenario?

XML below:

<event name="xml_deadlock_report" package="sqlserver" timestamp="2017-12-06T02:38:31.382Z">
  <data name="xml_report">
    <type name="xml" package="package0" />
    <value>
      <deadlock>
        <victim-list>
          <victimProcess id="process248e1c96108" />
        </victim-list>
        <process-list>
          <process id="process248e1c96108" taskpriority="0" logused="63904" waitresource="PAGE: 14:1:289932632 " waittime="4523" ownerId="2409980792" transactionname="user_transaction" lasttranstarted="2017-12-06T02:38:26.657" XDES="0x2453d39ce58" lockMode="IX" schedulerid="14" kpid="24604" status="suspended" spid="151" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-12-06T02:38:26.657" lastbatchcompleted="2017-12-06T02:38:26.657" lastattention="2017-12-06T02:38:23.760" clientapp="XXXX" hostname="XXXX" hostpid="137000" loginname="XXXX" isolationlevel="read committed (2)" xactid="2409980792" currentdb="14" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
            <executionStack>
              <frame procname="adhoc" line="1" stmtend="1206" sqlhandle="0x020000000f2bea1e535f1cbf04ef8318984df8965399be020000000000000000000000000000000000000000">
unknown    </frame>
            </executionStack>
            <inputbuf>
insert bulk TableName ([AssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [ParentAssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [PortfolioSnapshotId] UniqueIdentifier, [Quantity] Decimal(28,8), [CompressedProperties] VarBinary(max)) with (CHECK_CONSTRAINTS)   </inputbuf>
          </process>
          <process id="process248e1c8cca8" taskpriority="0" logused="67244" waitresource="PAGE: 14:1:289933280 " waittime="4523" ownerId="2409980337" transactionname="user_transaction" lasttranstarted="2017-12-06T02:38:26.220" XDES="0x25e82396e58" lockMode="IX" schedulerid="2" kpid="33292" status="suspended" spid="158" sbid="0" ecid="0" priority="0" trancount="2" lastbatchstarted="2017-12-06T02:38:26.220" lastbatchcompleted="2017-12-06T02:38:26.220" lastattention="2017-12-06T02:38:24.507" clientapp="XXXX" hostname="XXXX" hostpid="137000" loginname="XXXX" isolationlevel="read committed (2)" xactid="2409980337" currentdb="14" lockTimeout="4294967295" clientoption1="671088672" clientoption2="128056">
            <executionStack>
              <frame procname="adhoc" line="1" stmtend="1206" sqlhandle="0x020000000f2bea1e535f1cbf04ef8318984df8965399be020000000000000000000000000000000000000000">
unknown    </frame>
            </executionStack>
            <inputbuf>
insert bulk TableName ([AssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [ParentAssetId] NVarChar(255) COLLATE Latin1_General_CI_AS, [PortfolioSnapshotId] UniqueIdentifier, [Quantity] Decimal(28,8), [CompressedProperties] VarBinary(max)) with (CHECK_CONSTRAINTS)   </inputbuf>
          </process>
        </process-list>
        <resource-list>
          <pagelock fileid="1" pageid="289932632" dbid="14" subresource="FULL" objectname="XXXX.dbo.TableName" id="lock247f3004d00" mode="X" associatedObjectId="72057594048872448">
            <owner-list>
              <owner id="process248e1c8cca8" mode="X" />
            </owner-list>
            <waiter-list>
              <waiter id="process248e1c96108" mode="IX" requestType="wait" />
            </waiter-list>
          </pagelock>
          <pagelock fileid="1" pageid="289933280" dbid="14" subresource="FULL" objectname="XXXX.dbo.TableName" id="lock247f4f97c80" mode="X" associatedObjectId="72057594045661184">
            <owner-list>
              <owner id="process248e1c96108" mode="X" />
            </owner-list>
            <waiter-list>
              <waiter id="process248e1c8cca8" mode="IX" requestType="wait" />
            </waiter-list>
          </pagelock>
        </resource-list>
      </deadlock>
    </value>
  </data>
</event>

Table:

CREATE TABLE [dbo].[TableName](
  [AssetId] [nvarchar](255) NOT NULL,
  [ParentAssetId] [nvarchar](255) NULL,
  [PortfolioSnapshotId] [uniqueidentifier] NOT NULL,
  [Quantity] [decimal](28, 8) NULL,
  [CompressedProperties] [varbinary](max) NULL
 CONSTRAINT [PK_TableName] PRIMARY KEY CLUSTERED
(
  [PortfolioSnapshotId] ASC,
  [AssetId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[TableName]  WITH CHECK ADD  CONSTRAINT [FK_TableName_PortfolioSnapshot] FOREIGN KEY([PortfolioSnapshotId])
REFERENCES [dbo].[PortfolioStore_PortfolioSnapshot] ([Id])

CREATE NONCLUSTERED INDEX [IX_TableName_PortfolioSnapshotId] ON [dbo].[TableName]
(
  [PortfolioSnapshotId] ASC
)
INCLUDE (   [AssetId],
  [ParentAssetId],
  [Quantity],
  [Price]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO


问:
is it possible in Javascript to have a clipped object repeat on the other side of the screen?
I recently got into javascript and was wondering if it was possible to have an object clip off a screen and have the missing part appear on the other end of the screen as if the page was continuous. I attached an illustration below to better explain what I mean.

https://i.stack.imgur.com/DCpZN.jpg

答:
You can use CSS to do this.

#lp{
position:absolute;
left:-120px;
}

#rp{
position:absolute;
right:-330px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

<img id='lp' src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3211/chimp-thinking.jpg">
<img id='rp'  src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3211/chimp-thinking.jpg">

</div></code>```

Body:
You can use CSS to do this.

#lp{
position:absolute;
left:-120px;
}

#rp{
position:absolute;
right:-330px;
}

<div>

<img id='lp' src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3211/chimp-thinking.jpg">
<img id='rp'  src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3211/chimp-thinking.jpg">

</div>


问:
dividing and conquering etree.iterparse using multiprocessing
so let's imagine a large xml document (filesize > 100 mb) that we want to iterparse using cElementTree.iterparse.

but all those cores Intel promised us would be worthwhile, how do we put them to use? here's what I want:

```<code>from itertools import islice
from xml.etree import ElementTree as etree

tree_iter = etree.iterparse(open("large_file.xml", encoding="utf-8"))

first = islice(tree_iter, 0, 10000)
second = islice(tree_iter, 10000)

parse_first()
parse_second()
</code>```

There seems to be several problems with this, not the least being that the iterator returned by iterparse() seems to resist slicing.

Is there any way to divide the parsing workload of a large xml document into two or four separate tasks (without loading the entire document into memory? the purpose being then to execute the tasks on separate processors.

答:
I think you need a good threadpool with a task queue for this. I found (and use) this very good one (it's in python3, but shouldn't be too hard to convert to 2.x):

```<code># http://code.activestate.com/recipes/577187-python-thread-pool/

from queue import Queue
from threading import Thread

class Worker(Thread):
    def __init__(self, tasks):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon = True
        self.start()

    def run(self):
        while True:
            func, args, kargs = self.tasks.get()
            try: func(*args, **kargs)
            except Exception as exception: print(exception)
            self.tasks.task_done()

class ThreadPool:
    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        for _ in range(num_threads): Worker(self.tasks)

    def add_task(self, func, *args, **kargs):
        self.tasks.put((func, args, kargs))

    def wait_completion(self):
        self.tasks.join()
</code>```

Now you can just run the loop on the iterparse and let the threadpool divide the work for you. Using it is a simple as this:

```<code>def executetask(arg):
    print(arg)

workers = threadpool.ThreadPool(4) # 4 is the number of threads
for i in range(100): workers.add_task(executetask, i)

workers.wait_completion() # not needed, only if you need to be certain all work is done before continuing
</code>```

Body:
so let's imagine a large xml document (filesize > 100 mb) that we want to iterparse using cElementTree.iterparse.

but all those cores Intel promised us would be worthwhile, how do we put them to use? here's what I want:

from itertools import islice
from xml.etree import ElementTree as etree

tree_iter = etree.iterparse(open("large_file.xml", encoding="utf-8"))

first = islice(tree_iter, 0, 10000)
second = islice(tree_iter, 10000)

parse_first()
parse_second()

There seems to be several problems with this, not the least being that the iterator returned by iterparse() seems to resist slicing.

Is there any way to divide the parsing workload of a large xml document into two or four separate tasks (without loading the entire document into memory? the purpose being then to execute the tasks on separate processors.

Body:
I think you need a good threadpool with a task queue for this. I found (and use) this very good one (it's in python3, but shouldn't be too hard to convert to 2.x):

# http://code.activestate.com/recipes/577187-python-thread-pool/

from queue import Queue
from threading import Thread

class Worker(Thread):
    def __init__(self, tasks):
        Thread.__init__(self)
        self.tasks = tasks
        self.daemon = True
        self.start()

    def run(self):
        while True:
            func, args, kargs = self.tasks.get()
            try: func(*args, **kargs)
            except Exception as exception: print(exception)
            self.tasks.task_done()

class ThreadPool:
    def __init__(self, num_threads):
        self.tasks = Queue(num_threads)
        for _ in range(num_threads): Worker(self.tasks)

    def add_task(self, func, *args, **kargs):
        self.tasks.put((func, args, kargs))

    def wait_completion(self):
        self.tasks.join()

Now you can just run the loop on the iterparse and let the threadpool divide the work for you. Using it is a simple as this:

def executetask(arg):
    print(arg)

workers = threadpool.ThreadPool(4) # 4 is the number of threads
for i in range(100): workers.add_task(executetask, i)

workers.wait_completion() # not needed, only if you need to be certain all work is done before continuing


问:
Selenium UrlContains in C#
I'm trying to wait for a specific URL to load. However I don´t know the full URL, a dynamic value will be added at the end. Lets say the URL is www.test.com/accepted/?12345, but I only know www.test.com/accepted/

I´m trying to do something like this:

```<code>WebDriverWait wait = new WebDriverWait(Generic.driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.UrlContains("www.test.com/accepted/"));
</code>```

Is there a way to just check for the part that I know?

答:
Here's the code for ExpectedConditions.UrlContains(string) as taken from the Selenium source code

```<code>public static Func<IWebDriver, bool> UrlContains(string fraction)
{
    return (driver) => {
        return driver.Url.ToLowerInvariant().Contains(fraction.ToLowerInvariant());
    };
}
</code>```

As you can see it implements a case insensitive partial match.

This means that if the code shown in your question isn't working it's because the URL absolutely does not contain the provided fraction, or the problem lies elsewhere that we can't see.

Title: Selenium UrlContains in C#

Body:
I'm trying to wait for a specific URL to load. However I don´t know the full URL, a dynamic value will be added at the end. Lets say the URL is www.test.com/accepted/?12345, but I only know www.test.com/accepted/

I´m trying to do something like this:

WebDriverWait wait = new WebDriverWait(Generic.driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.UrlContains("www.test.com/accepted/"));

Is there a way to just check for the part that I know?

Body:
Here's the code for ExpectedConditions.UrlContains(string) as taken from the Selenium source code

public static Func<IWebDriver, bool> UrlContains(string fraction)
{
    return (driver) => {
        return driver.Url.ToLowerInvariant().Contains(fraction.ToLowerInvariant());
    };
}

As you can see it implements a case insensitive partial match.

This means that if the code shown in your question isn't working it's because the URL absolutely does not contain the provided fraction, or the problem lies elsewhere that we can't see.


问:
Equivalent of tf.SparseFeature in tf.data
The neural network I am currently working on is accepting a sparse tensor as input. I am reading my data from a TFRecord as follows:

```<code>_, examples = tf.TFRecordReader(options=options).read_up_to(
    filename_queue, num_records=batch_size)

features = tf.parse_example(examples, features={
          'input_feat': tf.SparseFeature(index_key='input_feat_idx',
                                         value_key='input_feat_values',
                                         dtype=tf.int64,
                                         size=SIZE_FEATURE)})
</code>```

It works like a charm but I was looking at the tf.data API which looks more convenient for a lot of tasks and I am not sure how to read tf.SparseTensor objects like I do with the tf.RecordReader and tf.parse_example(). Any idea?

答:
TensorFlow 1.5 will add native support for tf.SparseTensor in the core transformations. (This is currently available if you pip install tf-nightly, or build from source on the master branch of TensorFlow.) This means that you can write your pipeline as the following:

```<code># Create a dataset of string records from the input files.
dataset = tf.data.TFRecordReader(filenames)

# Convert each string record into a `tf.SparseTensor` representing a single example.
dataset = dataset.map(lambda record: tf.parse_single_example(
    record, features={'input_feat': tf.SparseFeature(index_key='input_feat_idx',
                                                     value_key='input_feat_values',
                                                     dtype=tf.int64,
                                                     size=SIZE_FEATURE)})

# Stack together up to `batch_size` consecutive elements into a `tf.SparseTensor`
# representing a batch of examples.
dataset = dataset.batch(batch_size)

# Create an iterator to access the elements of `dataset` sequentially.
iterator = dataset.make_one_shot_iterator()

# `next_element` is a `tf.SparseTensor`.
next_element = iterator.get_next()
</code>```

Body:
The neural network I am currently working on is accepting a sparse tensor as input. I am reading my data from a TFRecord as follows:

_, examples = tf.TFRecordReader(options=options).read_up_to(
    filename_queue, num_records=batch_size)

features = tf.parse_example(examples, features={
          'input_feat': tf.SparseFeature(index_key='input_feat_idx',
                                         value_key='input_feat_values',
                                         dtype=tf.int64,
                                         size=SIZE_FEATURE)})

It works like a charm but I was looking at the tf.data API which looks more convenient for a lot of tasks and I am not sure how to read tf.SparseTensor objects like I do with the tf.RecordReader and tf.parse_example(). Any idea?

Body:
TensorFlow 1.5 will add native support for tf.SparseTensor in the core transformations. (This is currently available if you pip install tf-nightly, or build from source on the master branch of TensorFlow.) This means that you can write your pipeline as the following:

# Create a dataset of string records from the input files.
dataset = tf.data.TFRecordReader(filenames)

# Convert each string record into a `tf.SparseTensor` representing a single example.
dataset = dataset.map(lambda record: tf.parse_single_example(
    record, features={'input_feat': tf.SparseFeature(index_key='input_feat_idx',
                                                     value_key='input_feat_values',
                                                     dtype=tf.int64,
                                                     size=SIZE_FEATURE)})

# Stack together up to `batch_size` consecutive elements into a `tf.SparseTensor`
# representing a batch of examples.
dataset = dataset.batch(batch_size)

# Create an iterator to access the elements of `dataset` sequentially.
iterator = dataset.make_one_shot_iterator()

# `next_element` is a `tf.SparseTensor`.
next_element = iterator.get_next()


答:
You can also use :not(:first-child) to solve this, so you don't have to care about the formula:

li {
  display: inline-block;
}
a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}
#login-signup li:not(:first-child):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
  <li> No Underline</li>
  <li>Log In</li>
  <li>Sign Up</li>
</ul></code>```

Another solution using the :not:

li {
  display: inline-block;
}
a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}
#login-signup li:not(:nth-child(1)):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul id="login-signup">
  <li> No Underline</li>
  <li>Log In</li>
  <li>Sign Up</li>
</ul></code>```

Title: nth-child formula for hover state - all elements except the first one

Body:
You can also use :not(:first-child) to solve this, so you don't have to care about the formula:

li {
  display: inline-block;
}
a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}
#login-signup li:not(:first-child):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}

<ul id="login-signup">
  <li> <a href="#">No Underline</a></li>
  <li><a href="#">Log In</a></li>
  <li><a href="#">Sign Up</a></li>
</ul>

Another solution using the :not:

li {
  display: inline-block;
}
a {
  margin-right: 1.8rem;
  padding-bottom: 23px;
}
#login-signup li:not(:nth-child(1)):hover {
  text-decoration: none;
  border-bottom: 3px solid #292c2e;
}

<ul id="login-signup">
  <li> <a href="#">No Underline</a></li>
  <li><a href="#">Log In</a></li>
  <li><a href="#">Sign Up</a></li>
</ul>


问:
Linux User space application to access G_zero gadget driver
I am using the USB peripheral mode in Linux board. I have successfully port the g_zero gadget driver on Linux supported board and successfully enumeration with host PC. Now I want to send the raw data of video[camera] using g_zero gadget driver from user space Application.

I have been lot's of searching on Google but i didn't found anything. Please guide me any one who have been done same type of work on gadget driver.

Thanks & Best Regards;
Nikunj Patel

答:
For video streaming you should rather use uvc gadget rather than g_zero (which only can loopback data from host or transfer zeros, depending on configuration).

Also, this github project seem to be complete example for controlling such gadget from user space.


问:
Open remote gzip XML file for use with SimpleXML
I'm having trouble retrieving and decompressing a remote gzip XML file.

To get the file I'm using:

```<code>$url = 'http://www.domain.com/xml.gzip';
$linkToXmlFile = fopen("compress.zlib://$url", "r");
</code>```

Then I've tried:

```<code>try {
    $xml = new SimpleXmlElement($rawFeed);
    ...
}
</code>```

To no avail.

答:
Tried this ?</p>

```<code>$xml = new SimpleXMLElement("compress.zlib://$url", NULL, TRUE);
</code>```

Body:
I'm having trouble retrieving and decompressing a remote gzip XML file.

To get the file I'm using:

$url = 'http://www.domain.com/xml.gzip';
$linkToXmlFile = fopen("compress.zlib://$url", "r");

Then I've tried:

try {
    $xml = new SimpleXmlElement($rawFeed);
    ...
}

To no avail.

Body:
Tried this ?

$xml = new SimpleXMLElement("compress.zlib://$url", NULL, TRUE);