问:
Check if all values are unique in a div using jquery
I have select box which no select generates number of textboxes in a div.
Now there are three field

display_name[], user_name[], and user_password[]

The code for that is :

```<code><select name="license" id="dropdown" class="form-control" required="required">
  <option  value="default" >Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<script type="text/javascript">
    $(document).ready(function() {
        $("#dropdown").change(function() {
            var selVal = $(this).val();
            $("#pttuserdiv").html('');
            if(selVal > 0) {
                for(var i = 1; i<= selVal; i++) {
                    $("#pttuserdiv").append(`
                    <div class="col-sm-3 col-sm-offset-1">
                        <div class="form-group label-floating">
                            <label class="control-label">Display Name</label>
                            <input type="text" class="form-control" name="display_name[]" required >
                        </div>
                    </div>
                    <div class="col-sm-3 col-sm-offset-1">
                        <div class="form-group label-floating">
                            <label class="control-label">Username</label>
                            <input type="text" class="form-control validateLocation"  name="user_name[]" id="user_name" required >
                        </div>
                    </div>
                    <div class="col-sm-3 col-sm-offset-1">
                        <div class="form-group label-floating">
                            <label class="control-label">Password</label>
                            <input type="password" class="form-control" name="user_password[]" required >
                        </div>
                    </div>`);
                }
            }
        });
    });
</script>

<div class="row">
<div id="pttuserdiv">

</div>
</div>
</code>```

Now I want the user_name[] field to be unique.

How do I do that ?
I want to display error or alert if user input same username again in user_name[].

答:
Try the following approach

Bind keyup event and check user's input for the current input box.

Check if the current input value is same as other username values

If yes, then highlight the input box.

Demo

$(document).ready(function() {
  $("#dropdown").change(function() {
    var selVal = $(this).val();
    $("#pttuserdiv").html('');
    if (selVal > 0) {
      for (var i = 1; i <= selVal; i++) {
        $("#pttuserdiv").append('

Display Name<input type="text" class="form-control" name="display_name[]" required >

Username<input type="text" class="form-control validateLocation"  name="user_name[]" id="user_name" required >

Password<input type="password" class="form-control" name="user_password[]" required >

');
      }
      $( "[name='user_name[]']" ).off( "keyup" );
      $( "[name='user_name[]']" ).on( "keyup", function(){
          var isFound = false;
          var value = $(this).val();
          $( "[name='user_name[]']" ).not(this).each( function(){
               if ( this.value == value )
               {
                   isFound = true;
               }
          });
          $(this).toggleClass( "highlight", isFound );
      });
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.highlight
{
   border-color : red;
}</code>```

<select name="license" id="dropdown" class="form-control" required="required">
  <option  value="default" >Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

```

Note - Id doesn't play any role in my code, but as a good practice keep the ids of all elements unique.

Body:
I have select box which no select generates number of textboxes in a div.
Now there are three field

display_name[], user_name[], and user_password[]

The code for that is :

<select name="license" id="dropdown" class="form-control" required="required">
  <option  value="default" >Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

Now I want the user_name[] field to be unique.

How do I do that ?
I want to display error or alert if user input same username again in user_name[].

Body:
Try the following approach

Bind keyup event and check user's input for the current input box.

Check if the current input value is same as other username values

If yes, then highlight the input box.

Demo

$(document).ready(function() {
  $("#dropdown").change(function() {
    var selVal = $(this).val();
    $("#pttuserdiv").html('');
    if (selVal > 0) {
      for (var i = 1; i <= selVal; i++) {
        $("#pttuserdiv").append('<div class="col-sm-3 col-sm-offset-1"><div class="form-group label-floating"><label class="control-label">Display Name</label><input type="text" class="form-control" name="display_name[]" required ></div></div><div class="col-sm-3 col-sm-offset-1"><div class="form-group label-floating"><label class="control-label">Username</label><input type="text" class="form-control validateLocation"  name="user_name[]" id="user_name" required ></div></div> <div class="col-sm-3 col-sm-offset-1"><div class="form-group label-floating"><label class="control-label">Password</label><input type="password" class="form-control" name="user_password[]" required ></div></div>');
      }
      $( "[name='user_name[]']" ).off( "keyup" );
      $( "[name='user_name[]']" ).on( "keyup", function(){
          var isFound = false;
          var value = $(this).val();
          $( "[name='user_name[]']" ).not(this).each( function(){
               if ( this.value == value )
               {
                   isFound = true;
               }
          });
          $(this).toggleClass( "highlight", isFound );
      });
    }
  });
});

.highlight
{
   border-color : red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="license" id="dropdown" class="form-control" required="required">
  <option  value="default" >Select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<script type="text/javascript">
</script>

<div class="row">
  <div id="pttuserdiv">

  </div>
</div>

Note - Id doesn't play any role in my code, but as a good practice keep the ids of all elements unique.


来源: stackexchange

问:
Sql Joining 3 Tables Query for Loan Total Result
I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.

```<code>SELECT
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) +
  ISNULL(AS2.NewGivenLoan, 0) -
  ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan
    FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
(SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
    FROM
       Given_Loan NGL
    GROUP BY
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
   (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id
</code>```

Here Is a picture of my two results:

When I get NULL Customer IDs

When I don't get All the Customers

答:
Here is My answer with the help of @Ab Bennett</p>

```<code>Select *
  From
  (
   SELECT
     C.C_Name AS [Customer ID],
     ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
     ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
     ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
     (ISNULL(AS1.OldCustomerLoan, 0) +
     ISNULL(AS2.NewGivenLoan, 0) -
     ISNULL(AS3.LoanPaid,0) ) AS Total
   FROM
    Customer C
    LEFT OUTER JOIN
     (SELECT
        MOC.C_ID,
        SUM(MOC.Quantity) AS OldCustomerLoan
   FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
     (SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
       FROM
       Given_Loan NGL
    GROUP BY
    NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
    LEFT OUTER JOIN
     (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
   ON c.C_Id = AS3.C_Id) ilv
   Where not ([Old Loan] = 0 and [New Given Loan]=0 and PaidLoanAmount =0 )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.

SELECT
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) +
  ISNULL(AS2.NewGivenLoan, 0) -
  ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan
    FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
(SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
    FROM
       Given_Loan NGL
    GROUP BY
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
   (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id

Here Is a picture of my two results:

When I get NULL Customer IDs

When I don't get All the Customers

Body:
Here is My answer with the help of @Ab Bennett

Select *
  From
  (
   SELECT
     C.C_Name AS [Customer ID],
     ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
     ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
     ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
     (ISNULL(AS1.OldCustomerLoan, 0) +
     ISNULL(AS2.NewGivenLoan, 0) -
     ISNULL(AS3.LoanPaid,0) ) AS Total
   FROM
    Customer C
    LEFT OUTER JOIN
     (SELECT
        MOC.C_ID,
        SUM(MOC.Quantity) AS OldCustomerLoan
   FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
     (SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
       FROM
       Given_Loan NGL
    GROUP BY
    NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
    LEFT OUTER JOIN
     (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
   ON c.C_Id = AS3.C_Id) ilv
   Where not ([Old Loan] = 0 and [New Given Loan]=0 and PaidLoanAmount =0 )


问:
bash : how to wait some time to avoid simultaneous run of a script?
My problem :

Each night, my crontab launches several nightly tests on a supercomputer working with PBS under CentOS 6.5. When launched, the jobs wait in the queue. When the scheduler allow to run, my jobs start. It is quite common than the scheduler launch all the jobs exaclty at the same time (even if my crontab lauched them at separated moments).

I can't modify the main part of the job (but I can add things before). Each job starts with an update of a common SVN repository. But, when the jobs start simultaneously, I have an error due to concurrent updates on the same repository. I want to avoid that.

What I expect :

When launched by the scheduler, the job could wait some seconds before starting. A solution could be wait a random time before starting, but the risk to have the same random time grow fast with the number of tests I perform in parallel. If I reduce this risk by choosing a big random number, I have to wait too long (locking unused resources on the supercomputer).

I suppose it's possible to store the information of "I will launch now, others have to wait for 1 minute" for each job, in a multi-thread-safe manner, but I don't know how. What I imagine is a kind of mutex but inducing only a delay and not a lock waiting the end.

A solution without MPI is prefered.

Of course, I'm open to other solutions. Any help is welcome.

答:
Here is a solution by using GNU parallel

It might seem a bit counter-intuitive at first to use this tool, but if you set the maximum number of jobs to run at a time to 1, it can simulate a job queue that runs multiple jobs in sequence without any overlaps.

You can observe the desired effect of this command by using this example

```<code>seq 1 5 | parallel -j1 -k 'echo {}; sleep 1'
</code>```

-j1 sets max jobs running at a time to 1 while -k preserves the order.

To apply this to your original problem, we can create say a file such that it contains a list of script files line by line. We can then pipe the content of that file to parallel to make multiple scripts run in sequence and in order.

```<code>cat file | parallel -j1 -k bash {}
</code>```

Body:
Here is a solution by using GNU parallel

It might seem a bit counter-intuitive at first to use this tool, but if you set the maximum number of jobs to run at a time to 1, it can simulate a job queue that runs multiple jobs in sequence without any overlaps.

You can observe the desired effect of this command by using this example

seq 1 5 | parallel -j1 -k 'echo {}; sleep 1'

-j1 sets max jobs running at a time to 1 while -k preserves the order.

To apply this to your original problem, we can create say a file such that it contains a list of script files line by line. We can then pipe the content of that file to parallel to make multiple scripts run in sequence and in order.

cat file | parallel -j1 -k bash {}


问:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo
I was trying to run a sample code
While launching the application in the android 1.5 emulator , I got these errors....
Any one have some hint..?

ERROR from LogCat:

```<code>01-13 02:28:08.392: ERROR/AndroidRuntime(2888): FATAL EXCEPTION: main
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.s.android.test/com.s.android.test.MainActivity}: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Looper.loop(Looper.java:123)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invoke(Method.java:507)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.NativeStart.main(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): Caused by: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     ... 11 more
01-13 02:28:08.407: WARN/ActivityManager(112):   Force finishing activity com.s.android.test/.MainActivity
</code>```

Edit
This error happens to most of the beginners, the thing is that you have to add all your activities in the Manifest file.

答:
As suggested by djjeck in comment in this answer I missed to put public modifier for my class.

It should be

```<code>public class MyActivity extends AppCompatActivity {
</code>```

It may help some like me.

Body:
I was trying to run a sample code
While launching the application in the android 1.5 emulator , I got these errors....
Any one have some hint..?

ERROR from LogCat:

01-13 02:28:08.392: ERROR/AndroidRuntime(2888): FATAL EXCEPTION: main
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.s.android.test/com.s.android.test.MainActivity}: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1544)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1638)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:928)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.os.Looper.loop(Looper.java:123)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.main(ActivityThread.java:3647)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.reflect.Method.invoke(Method.java:507)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.NativeStart.main(Native Method)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888): Caused by: java.lang.ClassNotFoundException: com.s.android.test.MainActivity in loader dalvik.system.PathClassLoader[/data/app/com.s.android.test-2.apk]
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1536)
01-13 02:28:08.392: ERROR/AndroidRuntime(2888):     ... 11 more
01-13 02:28:08.407: WARN/ActivityManager(112):   Force finishing activity com.s.android.test/.MainActivity

Edit
This error happens to most of the beginners, the thing is that you have to add all your activities in the Manifest file.

Body:
As suggested by djjeck in comment in this answer I missed to put public modifier for my class.

It should be

public class MyActivity extends AppCompatActivity {

It may help some like me.


问:
How to write a loader that depends on some value in another module but still outputs all modules
(I'm using Webpack 3.8.1)

I have a repo with the code shown in this question:

https://github.com/leoasis/webpack-loader-issue

I'm trying to write a webpack loader that process the contents of the source and generates some value. If the source has dependencies on other resources, I need to load them inside the loader to calculate that value, since it depends on the dependencies' values. To do this I use this.loadModule and access the value as soon as the module is loaded.

However, this seems to fail when I have dependencies of the dependencies, as they don't seem to be included in the final bundle, causing an error.

Here's a reduced example to reproduce the case:

```<code>// webpack.config.js

const path = require('path');

module.exports = {
  entry: './a.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: './foo-loader'
      }
    ]
  }
};

// a.js
import './b';
console.log('Hello from a');

// b.js
import './c';
console.log('Hello from b');

// c.js
console.log('Hello from c');
</code>```

And finally, the loader:

```<code>// foo-loader.js

module.exports = function (content) {
  this.async();
  const dep = content.split('\n')[0].split('\'')[1];
  this._module.someValue = dep.charCodeAt(2); // gets the 'a' from './a'

  if (dep[0] !== '.') {
    this.callback(null, content + 'console.log("the value is", ' + this._module.someValue + ')');
    return;
  }

  this.loadModule(dep, (err, source, sourceMap, module) => {
    if (err) {
      this.callback(err);
      return;
    }

    this._module.someValue += module.someValue;
    console.log(this.resourcePath, this._module.someValue);
    this.callback(null, content + 'console.log("the value is", ' + this._module.someValue + ')');
  });
}
</code>```

This is the resulting bundle:

```<code>/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
throw new Error("Cannot find module \"./c\"");

console.log('Hello from b');
console.log("the value is", 207)

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__b__ = __webpack_require__(0);

console.log('Hello from a');
console.log("the value is", 305)

/***/ })
/******/ ]);
</code>```

Notice how there's an error saying that it can't find module ./c

This works perfectly fine if I changed the loader to be the identity one:

```<code>  module.exports = function (content) {
      return content;
    }
</code>```

It even fails with a trivial loader that just calls this.loadModule and does nothing with the response.

```<code>module.exports = function (content) {
  const dep = content.split('\n')[0].split('\'')[1];

  if (dep[0] !== '.') {
    return content;
  }

  this.loadModule(dep, () => { console.log('loading', dep); });
  return content;
}
</code>```

Does anybody know what could be going on? Is this an expected behavior of this.loadModule? Is this a bug? If it's not a bug, how can I load a module but still make it part of the bundle?

答:
Ok after some research I found this issue https://github.com/webpack/webpack/issues/4959 in the Webpack repo which talks about this same thing. The problem is that loadModule does not load modules' dependencies recursively. Ideally this should be supported in the loadModule function in webpack, perhaps with an option in loadModule, but for now the work-around is to copy the code that defines the loadModule method from Webpack (https://github.com/webpack/webpack/blob/master/lib/dependencies/LoaderPlugin.js) and change the flag to load modules recursively to true, as in https://github.com/MortenHoustonLudvigsen/ts-css-loader/blob/master/src/loadModuleRecursive.ts.

Basically, change this:

```<code>compilation.addModuleDependencies(module, [
    [dep]
], true, "lm", false, (err) => {
</code>```

To this:

```<code>compilation.addModuleDependencies(module, [
    [dep]
], true, "lm", true, (err) => {
</code>```

I'm still not very convinced this solution is the right one, especially since I'm not very familiar with Webpack's codebase, but it works for my use case, so I'll mark it as accepted answer until a better solution appears.

Body:
(I'm using Webpack 3.8.1)

I have a repo with the code shown in this question:

https://github.com/leoasis/webpack-loader-issue

I'm trying to write a webpack loader that process the contents of the source and generates some value. If the source has dependencies on other resources, I need to load them inside the loader to calculate that value, since it depends on the dependencies' values. To do this I use this.loadModule and access the value as soon as the module is loaded.

However, this seems to fail when I have dependencies of the dependencies, as they don't seem to be included in the final bundle, causing an error.

Here's a reduced example to reproduce the case:

// webpack.config.js

const path = require('path');

module.exports = {
  entry: './a.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: './foo-loader'
      }
    ]
  }
};

// a.js
import './b';
console.log('Hello from a');

// b.js
import './c';
console.log('Hello from b');

// c.js
console.log('Hello from c');

And finally, the loader:

// foo-loader.js

module.exports = function (content) {
  this.async();
  const dep = content.split('\n')[0].split('\'')[1];
  this._module.someValue = dep.charCodeAt(2); // gets the 'a' from './a'

  if (dep[0] !== '.') {
    this.callback(null, content + 'console.log("the value is", ' + this._module.someValue + ')');
    return;
  }

  this.loadModule(dep, (err, source, sourceMap, module) => {
    if (err) {
      this.callback(err);
      return;
    }

    this._module.someValue += module.someValue;
    console.log(this.resourcePath, this._module.someValue);
    this.callback(null, content + 'console.log("the value is", ' + this._module.someValue + ')');
  });
}

This is the resulting bundle:

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
throw new Error("Cannot find module \"./c\"");

console.log('Hello from b');
console.log("the value is", 207)

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__b__ = __webpack_require__(0);

console.log('Hello from a');
console.log("the value is", 305)

/***/ })
/******/ ]);

Notice how there's an error saying that it can't find module ./c

This works perfectly fine if I changed the loader to be the identity one:

  module.exports = function (content) {
      return content;
    }

It even fails with a trivial loader that just calls this.loadModule and does nothing with the response.

module.exports = function (content) {
  const dep = content.split('\n')[0].split('\'')[1];

  if (dep[0] !== '.') {
    return content;
  }

  this.loadModule(dep, () => { console.log('loading', dep); });
  return content;
}

Does anybody know what could be going on? Is this an expected behavior of this.loadModule? Is this a bug? If it's not a bug, how can I load a module but still make it part of the bundle?

Body:
Ok after some research I found this issue https://github.com/webpack/webpack/issues/4959 in the Webpack repo which talks about this same thing. The problem is that loadModule does not load modules' dependencies recursively. Ideally this should be supported in the loadModule function in webpack, perhaps with an option in loadModule, but for now the work-around is to copy the code that defines the loadModule method from Webpack (https://github.com/webpack/webpack/blob/master/lib/dependencies/LoaderPlugin.js) and change the flag to load modules recursively to true, as in https://github.com/MortenHoustonLudvigsen/ts-css-loader/blob/master/src/loadModuleRecursive.ts.

Basically, change this:

compilation.addModuleDependencies(module, [
    [dep]
], true, "lm", false, (err) => {

To this:

compilation.addModuleDependencies(module, [
    [dep]
], true, "lm", true, (err) => {

I'm still not very convinced this solution is the right one, especially since I'm not very familiar with Webpack's codebase, but it works for my use case, so I'll mark it as accepted answer until a better solution appears.


问:
JTable extended from AbtractTableModel is not updating GUI when i add row
This my new MyJtable

```<code>public void addWidget(Book w) {
    datalist.add(w);
    fireTableRowsInserted(datalist.size()-1, datalist.size()-1);

   }
</code>```

calling class

```<code>  MyJtable tv = new MyJtable(a);
        table = new JTable(tv);
        //tv.addWidget(b3);
        JScrollPane pane2 = new JScrollPane(table);
</code>```

button CLick function

```<code> public void actionPerformed(ActionEvent e)
   {
    MyJtable tv1 = new MyJtable();
    Book b3 = new Book ("Java nutshell-299", "Ajfdfdfdingya2") ;
    if("Add".equals(e.getActionCommand()))
  {
  JOptionPane.showMessageDialog(null,"Add button is clicked");
  tv1.addWidget(b3);
  }
</code>```

when i click button then i don't see any GUI chnage but if call

```<code>tv1.addWidget(b3);

   }
</code>```

before , i mean on load then i can see the new book but not on button click

答: I think Andreas_D has identified a core issue.  You might also have problems because you are overriding AbstractTableModel instead of DefaultTableModel.  The DefaultTableModel has many of the event firing methods already completed.

Body:
This my new MyJtable

public void addWidget(Book w) {
    datalist.add(w);
    fireTableRowsInserted(datalist.size()-1, datalist.size()-1);

   }

calling class

  MyJtable tv = new MyJtable(a);
        table = new JTable(tv);
        //tv.addWidget(b3);
        JScrollPane pane2 = new JScrollPane(table);

button CLick function

 public void actionPerformed(ActionEvent e)
   {
    MyJtable tv1 = new MyJtable();
    Book b3 = new Book ("Java nutshell-299", "Ajfdfdfdingya2") ;
    if("Add".equals(e.getActionCommand()))
  {
  JOptionPane.showMessageDialog(null,"Add button is clicked");
  tv1.addWidget(b3);
  }

when i click button then i don't see any GUI chnage but if call

tv1.addWidget(b3);

   }

before , i mean on load then i can see the new book but not on button click

ContentLicense: CC BY-SA 2.5


问:
SAP B1 - using stanard dll's in a SOAP web service
Currently, I am working with SAP Business One SDK. I took some project from another team. This project is a SOAP web service. It has been written in ASPX technology, anyway another team used standard DI API library. This is the main problem with this solution because it causes a lot of problems with memory leaks.

In source code after every operation when DI API is called I try to use Garbage Collector, but unfortunately, it is not enough.

The web service is hosted on IIS and I had to set an option that for some time restart it. I know it is not the best solution, but it works. Obviously, that way generates many problems.

I have a question about it. Does any reasonable solution exist? Or I will have to rewrite source code using DI Server?

I have read a lot about this, I found some articles on the Internet. Please do not put any links in comments, because I am quite sure that I have read them.

答:
Every time you use a DI API object you have to release it. Otherwise, it will stay in memory and it will cause the memory leak you mentioned.

The correct way to release them is to use ReleaseComObject. Remember that if the object is null you will get an exception so check it first.

```<code>if (oDocuments != null)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocuments);
</code>```

Body:
Every time you use a DI API object you have to release it. Otherwise, it will stay in memory and it will cause the memory leak you mentioned.

The correct way to release them is to use ReleaseComObject. Remember that if the object is null you will get an exception so check it first.

if (oDocuments != null)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocuments);


问:
How to create a TCP Server in Python?
I started learning networking with python can somebody help me out with this code as I am unable to connect more than 5 clients at a time. Can someone please suggest me a solution for this?</p>

```<code>def main():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', listening_port))
        s.listen(5)
        print "[*] Initializing Sockets ... Done"
        print "[*] Sockets Binded Successfully ..."
        print("[*] Server Started Successfully [%d]\n" % (listening_port))
    except Exception, e:
        print e
        sys.exit(2)
    while 1:
        try:
            conn, addr = s.accept()
            data = conn.recv(buffer_size)
            start_new_thread(conn_string, (conn, data, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, data, addr):
    print conn
    print addr
    print data
</code>```

答:
The accepted answer is incorrect. I'll try to explain you why.

listen takes an argument of queued connections. That means, how many new connections can be put into the queue. That's why even in the documentation it's specified 5, while obviously servers serves more than 5 concurrent clients usually.

Once a socket is created (accepted) it is being forwarded to another thread, which performs the actual work. This allows to the listening thread moves back to listening mode and wait for more clients.

The problem with your code is, your main thread which is the listening thread actually reads data from buffer, where it shouldn't. The recv() function blocks (read more about I/O stream blocking)

You need to move the reading process from the listening thread to the worker; and make sure to close() the socket when it's done. The code would look something like this:

```<code>def main():
    try:
        ...
        s.listen(5)
    except Exception, e:
        ...
    while 1:
        try:
            conn, addr = s.accept()
            start_new_thread(conn_string, (conn, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, addr):
    data = conn.recv(buffer_size)
    print conn
    print addr
    print data
    conn.close()
</code>```

Title: How to create a TCP Server in Python?

Body:
I started learning networking with python can somebody help me out with this code as I am unable to connect more than 5 clients at a time. Can someone please suggest me a solution for this?

def main():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', listening_port))
        s.listen(5)
        print "[*] Initializing Sockets ... Done"
        print "[*] Sockets Binded Successfully ..."
        print("[*] Server Started Successfully [%d]\n" % (listening_port))
    except Exception, e:
        print e
        sys.exit(2)
    while 1:
        try:
            conn, addr = s.accept()
            data = conn.recv(buffer_size)
            start_new_thread(conn_string, (conn, data, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, data, addr):
    print conn
    print addr
    print data

Body:
The accepted answer is incorrect. I'll try to explain you why.

listen takes an argument of queued connections. That means, how many new connections can be put into the queue. That's why even in the documentation it's specified 5, while obviously servers serves more than 5 concurrent clients usually.

Once a socket is created (accepted) it is being forwarded to another thread, which performs the actual work. This allows to the listening thread moves back to listening mode and wait for more clients.

The problem with your code is, your main thread which is the listening thread actually reads data from buffer, where it shouldn't. The recv() function blocks (read more about I/O stream blocking)

You need to move the reading process from the listening thread to the worker; and make sure to close() the socket when it's done. The code would look something like this:

def main():
    try:
        ...
        s.listen(5)
    except Exception, e:
        ...
    while 1:
        try:
            conn, addr = s.accept()
            start_new_thread(conn_string, (conn, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, addr):
    data = conn.recv(buffer_size)
    print conn
    print addr
    print data
    conn.close()


问:
How to find difference of same column in foreach loop
I am take all field in for-each loop and take the difference of each two column

enter image description here

The above image 'tech_strt_km' is field name and take the difference of 122-22 and 200-122 how find these difference and store there values in another variyable i am using foreach loop for print these numbers

```<code><?php
foreach($pexpn as $row) {
    echo $row->tech_strt_km;  ?><br>
} ?>
</code>```

Any way to find the difference of same column
please help me !!

答:
This should work fine. We add one to the current key to get the next value so we can subtract it from the current value, then we save these differences in an array diff for later usage.

```<code>$arr = array('22', '122', '200');
$diff = array();
foreach ($arr as $k => $v) {
    if (!isset($arr[$k + 1])) {
        // if we don't have a next item we are done
        // break from foreach
        break;
    }
    // abs only necessary if we expect negative differences and
    // if we don't want that --- store differences in array
    // for later usage
    $diff[] = abs($arr[$k + 1] - $v);
}
print_r($diff);
</code>```

Body:
I am take all field in for-each loop and take the difference of each two column

enter image description here

The above image 'tech_strt_km' is field name and take the difference of 122-22 and 200-122 how find these difference and store there values in another variyable i am using foreach loop for print these numbers

<?php
foreach($pexpn as $row) {
    echo $row->tech_strt_km;  ?>

} ?>

Any way to find the difference of same column
please help me !!

Body:
This should work fine. We add one to the current key to get the next value so we can subtract it from the current value, then we save these differences in an array diff for later usage.

$arr = array('22', '122', '200');
$diff = array();
foreach ($arr as $k => $v) {
    if (!isset($arr[$k + 1])) {
        // if we don't have a next item we are done
        // break from foreach
        break;
    }
    // abs only necessary if we expect negative differences and
    // if we don't want that --- store differences in array
    // for later usage
    $diff[] = abs($arr[$k + 1] - $v);
}
print_r($diff);


问:
R How to change the scale of graph in R
I was wondering how I can change my x axis from what it currently is (Number of measurements) to just time, as it's clear from my code I have the x axis going from 0 to 300000 when I would much rather have it going from 0 to 30.

```<code>install.packages("smfsb")
library(smfsb)
out = gillespied(LV,T=30,dt=0.0001)
#Plot of 5 realisations of the prey# #First way#
M1 <- out[,1]
for (i in 1:4)  {
        out = gillespied(LV, T=30, dt=0.0001)
        M1 = cbind(M1,out[,1])
}
matplot(M1, type="l", pch="", col="grey",xlab="No. of
measurements",ylab="No. of Prey", ylim=c(-100,600))
</code>```

So as it shows in the picture, I would like the change the x axis scales. I was wondering if there is a function which can easily do this for me.

Thanks

Edit: Unfortunately I am unable to embed the picture associated with this question, but as I said, the x axis goes from 0 to 300000 instead I want 0 to 30

This is the graph of what I get : https://gyazo.com/f015f9fbf2f6fc3beb7675be488578bc

答:
You haven't provided sample data but you are using matplot so here is an example:

some matrix:

```<code>   mat <- matrix(rnorm(20), 5)
</code>```

plot without axes

```<code>matplot(mat, type="l", axes = F)
</code>```

add manual axes

```<code>axis(side = 1, at = 1:5, labels = c("a", "b", "c", "D" ,"oh man"))
</code>```

result:

using:

```<code>matplot(mat, type = "l", xaxt = 'n')
</code>```

will just remove the x axis

```<code>axis(side = 1, at = 1:5, labels = c("a", "b", "c", "D" ,"oh man"))
</code>```

additional example:

```<code>mat <- matrix(rnorm(10000), 5000)
matplot(mat, type="l", xaxt = 'n')
axis(side = 1, at = (0:10)*1000, labels = 0:10)
</code>```

Title: R How to change the scale of graph in R

Body:
I was wondering how I can change my x axis from what it currently is (Number of measurements) to just time, as it's clear from my code I have the x axis going from 0 to 300000 when I would much rather have it going from 0 to 30.

install.packages("smfsb")
library(smfsb)
out = gillespied(LV,T=30,dt=0.0001)
#Plot of 5 realisations of the prey# #First way#
M1 <- out[,1]
for (i in 1:4)  {
        out = gillespied(LV, T=30, dt=0.0001)
        M1 = cbind(M1,out[,1])
}
matplot(M1, type="l", pch="", col="grey",xlab="No. of
measurements",ylab="No. of Prey", ylim=c(-100,600))

So as it shows in the picture, I would like the change the x axis scales. I was wondering if there is a function which can easily do this for me.

Thanks

Edit: Unfortunately I am unable to embed the picture associated with this question, but as I said, the x axis goes from 0 to 300000 instead I want 0 to 30

This is the graph of what I get : https://gyazo.com/f015f9fbf2f6fc3beb7675be488578bc

Body:
You haven't provided sample data but you are using matplot so here is an example:

some matrix:

   mat <- matrix(rnorm(20), 5)

plot without axes

matplot(mat, type="l", axes = F)

add manual axes

axis(side = 1, at = 1:5, labels = c("a", "b", "c", "D" ,"oh man"))

result:

using:

matplot(mat, type = "l", xaxt = 'n')

will just remove the x axis

axis(side = 1, at = 1:5, labels = c("a", "b", "c", "D" ,"oh man"))

additional example:

mat <- matrix(rnorm(10000), 5000)
matplot(mat, type="l", xaxt = 'n')
axis(side = 1, at = (0:10)*1000, labels = 0:10)


问:
Failed to resolve: android.arch.lifecycle:extensions:1.0.0-alpha1 android studio 3.0
I am building a project in android studio 3.0 with android plugin 'com.android.tools.build:gradle:3.0.0-alpha1' and gradle version gradle-4.0-milestone-1-all.zip.

Used maven repo as well:

```<code>maven {
            url 'https://maven.google.com'
      }
</code>```

Also, Using android Room persistence and lifecycle in my project. Already declared below dependencies in my app gradle file:

```<code>compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
</code>```

When Sync and build the project it's showing below error:

Failed to resolve: android.arch.lifecycle:extensions:1.0.0-alpha1

Am I missing something or any other solution for this issue.

答: Just add maven { url 'https://maven.google.com' } to your project gradle

Body:
I am building a project in android studio 3.0 with android plugin 'com.android.tools.build:gradle:3.0.0-alpha1' and gradle version gradle-4.0-milestone-1-all.zip.

Used maven repo as well:

maven {
            url 'https://maven.google.com'
      }

Also, Using android Room persistence and lifecycle in my project. Already declared below dependencies in my app gradle file:

compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"

When Sync and build the project it's showing below error:

Failed to resolve: android.arch.lifecycle:extensions:1.0.0-alpha1

Am I missing something or any other solution for this issue.


问:
Response.Flush() only works with Firefox
I am trying to send some content to the client before doing some lengthy work:

```<code>Response.Write("Processing...");
Response.Flush();
System.Threading.Thread.Sleep(5000);
Response.Write("Finish");
Response.End();
</code>```

In Firefox it works as expected but in IE8, Safari and Chrome it waits until all the code is processed and then shows the whole text.

I have tried sending a better formed HTML like the below sample but I get the same results:

```<code>Response.Write("<html><head><title>test</title></head><body>Processing...</body></html>");
Response.Flush();
System.Threading.Thread.Sleep(5000);
Response.Write("Finish");
Response.End();
</code>```

Thank you!

答:
I think browsers get and use the content based on its length, so you may try padding 1000 chars or so. For example:

string myVeryShortMessage = "Processing...";

Response.Write(myVeryShortMessage.PadRight(1000));
Response.Flush();

System.Threading.Thread.Sleep(5000);

Response.Write("Finish".PadRight(1000));
Response.Flush();

Body:
I am trying to send some content to the client before doing some lengthy work:

Response.Write("Processing...");
Response.Flush();
System.Threading.Thread.Sleep(5000);
Response.Write("Finish");
Response.End();

In Firefox it works as expected but in IE8, Safari and Chrome it waits until all the code is processed and then shows the whole text.

I have tried sending a better formed HTML like the below sample but I get the same results:

Response.Write("<title>test</title>Processing...");
Response.Flush();
System.Threading.Thread.Sleep(5000);
Response.Write("Finish");
Response.End();

Thank you!


问:
How to delete firebase items that are "expired" or past the current date on Android Studio?
Hello I am creating an Android app that lists local events happening around my campus. Each "event" has children for storing the title, image, category, info, and date. I was wondering what the best way would be to delete events that are past the current date. The date is formatted mm/dd/yy. I don't have much experience with using date functions in Java, and could use some advice.

Here is an example of an event. Here is the source code for reference. Any help is greatly appreciated.

答:
You can filter the fire base response on date itself </p>

<p>ex: </p>

```<code>DatabaseReference mDatabaseReference =FirebaseDatabase.getInstance().getReference().child("table name");
ref.orderByChild("date").startAt(startDate).endAt(endDate).on("child_added", function(snapshot){
console.log("got the data!", snapshot);
});
</code>```

Body:
You can filter the fire base response on date itself

ex:

DatabaseReference mDatabaseReference =FirebaseDatabase.getInstance().getReference().child("table name");
ref.orderByChild("date").startAt(startDate).endAt(endDate).on("child_added", function(snapshot){
console.log("got the data!", snapshot);
});


问:
Parse nested data using SCALA
I have the dataframe as follows :

```<code>ColA  ColB     ColC
1     [2,3,4] [5,6,7]
</code>```

I need to convert it to the below

```<code>ColA ColB ColC
1    2    5
1    3    6
1    4    7
</code>```

Can someone please help with the Code in SCALA?

答:
The idea I am presenting here is a bit complex which requires you to use map to combine the two arrays of ColB and ColC. Then use the explode function to explode the combined array. and finally extract the exploded combined array to different columns.

```<code>import org.apache.spark.sql.functions._
val tempDF = df.map(row => {
  val colB = row(1).asInstanceOf[mutable.WrappedArray[Int]]
  val colC = row(2).asInstanceOf[mutable.WrappedArray[Int]]
  var array = Array.empty[(Int, Int)]
  for(loop <- 0 to colB.size-1){
    array = array :+ (colB(loop), colC(loop))
  }
  (row(0).asInstanceOf[Int], array)
})
  .toDF("ColA", "ColB")
  .withColumn("ColD", explode($"ColB"))

tempDF.withColumn("ColB", $"ColD._1").withColumn("ColC", $"ColD._2").drop("ColD").show(false)
</code>```

this would give you result as

```<code>+----+----+----+
|ColA|ColB|ColC|
+----+----+----+
|1   |2   |5   |
|1   |3   |6   |
|1   |4   |7   |
+----+----+----+
</code>```

Title: Parse nested data using SCALA

Body:
I have the dataframe as follows :

ColA  ColB     ColC
1     [2,3,4] [5,6,7]

I need to convert it to the below

ColA ColB ColC
1    2    5
1    3    6
1    4    7

Can someone please help with the Code in SCALA?

Body:
The idea I am presenting here is a bit complex which requires you to use map to combine the two arrays of ColB and ColC. Then use the explode function to explode the combined array. and finally extract the exploded combined array to different columns.

import org.apache.spark.sql.functions._
val tempDF = df.map(row => {
  val colB = row(1).asInstanceOf[mutable.WrappedArray[Int]]
  val colC = row(2).asInstanceOf[mutable.WrappedArray[Int]]
  var array = Array.empty[(Int, Int)]
  for(loop <- 0 to colB.size-1){
    array = array :+ (colB(loop), colC(loop))
  }
  (row(0).asInstanceOf[Int], array)
})
  .toDF("ColA", "ColB")
  .withColumn("ColD", explode($"ColB"))

tempDF.withColumn("ColB", $"ColD._1").withColumn("ColC", $"ColD._2").drop("ColD").show(false)

this would give you result as

+----+----+----+
|ColA|ColB|ColC|
+----+----+----+
|1   |2   |5   |
|1   |3   |6   |
|1   |4   |7   |
+----+----+----+


问:
How do I write a conditional (IF DATA EXISTS) LINQ statement without repetition?
I need to write a Linq query where the condition like this:

when data exists then the join will be  INNER JOIN

when data is not exists then the join will be  LEFT JOIN.

```<code>bool ifexists =  db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
    query=my inner join linq;
    query = from s in query select s;
    return query.ToList();
}
else
{
    query=my left join linq;
    query = from s in query select s;
    return query.ToList();
}
</code>```

Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?

答:
```<code>   First create object of of database Context named **Objcontext**
    now hold the variable in var the query would be like following

 var Result = from a in Objcontext.tbl1  where !Objcontext.tbl2.Any(m=>(m.sid==a.aid)&&(m.mid==80))
    select a;

 If data is exists in the databse it will cheack using !Objcontext
    I hope it will helpfull
</code>```

Body:
I need to write a Linq query where the condition like this:

when data exists then the join will be  INNER JOIN

when data is not exists then the join will be  LEFT JOIN.

bool ifexists =  db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
    query=my inner join linq;
    query = from s in query select s;
    return query.ToList();
}
else
{
    query=my left join linq;
    query = from s in query select s;
    return query.ToList();
}

Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?


问:
How to get Parent Work Item from a Test Case?
I need to get obtain information from Test Cases that are only associated with Parent Work Items that have a particular FieldDefinition value.

What I've been trying to do, is get a list of projects from the Test Management Service, iterating through all the Test Cases, and from there, hopefully, find the Parent Work Item associated with the Test Case and see if it has the FieldDefinition value I'm looking for. Here is what I have so far, but once I get my hands on the Test Cases, I don't know where to go from there to A) get the Parent Work Item and B) query the FieldDefinitions to find the FieldDefinition value I'm looking for. The documentation is pretty murky:

```<code> public class TfsTest
  {
     private TfsTeamProjectCollection teamProjectCollection;
     private WorkItemStore workItemStore;
     private delegate void Execute();

     public void GenerateReport()
     {
        TeamProjectPicker teamProjectPicker = new TeamProjectPicker(TeamProjectPickerMode.NoProject, false);
         teamProjectPicker.ShowDialog();
        if (teamProjectPicker.SelectedTeamProjectCollection != null)
        {
           this.teamProjectCollection = teamProjectPicker.SelectedTeamProjectCollection;
           ITestManagementService testManagementService = (ITestManagementService)this.teamProjectCollection.GetService(typeof(ITestManagementService));

           this.workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));

           foreach (Project project in workItemStore.Projects)
           {
              ITestManagementTeamProject _testproject = testManagementService.GetTeamProject(project.Name);
              GetTestPlans(_testproject);
           }
        }
     }

     void GetTestPlans(ITestManagementTeamProject testProject)
      {
        ITestPlanCollection plans = testProject.TestPlans.Query("Select * From TestPlan");

        foreach (ITestPlan plan in plans)
        {
           var planName = plan.Name;
           var testPlanType = ItemTypes.TestPlan;

           Console.WriteLine(string.Format("* {0} ({1})", plan.Name, testPlanType));

           if (plan.RootSuite != null && plan.RootSuite.Entries.Count > 0)
           {
              GetPlanSuites(plan.RootSuite.Entries, testProject);
           }
        }
     }

     void GetPlanSuites(ITestSuiteEntryCollection suites, ITestManagementTeamProject testProject)
     {
        foreach (ITestSuiteEntry suite_entry in suites)
        {
           IStaticTestSuite suite = suite_entry.TestSuite as IStaticTestSuite;
           if (suite != null)
           {

              // Test suites...
              var suiteTitle = suite.Title;
              var testSuiteType = ItemTypes.TestSuite;

              Console.WriteLine(string.Format("\t- {0} ({1})", suiteTitle, testSuiteType));

              GetTestCases(suite, testProject);
           }
        }
     }

     void GetTestCases(IStaticTestSuite suite, ITestManagementTeamProject testProject)
      {
        // iterate each test case
        foreach (ITestSuiteEntry suiteEntry in suite.TestCases)
        {
           if (suiteEntry.Id == 73649)
           {
              Console.WriteLine("Found it!");
           }

           var testResults = testProject.TestResults.ByTestId(suiteEntry.TestCase.Id);

           // iterate each result for the case
           foreach (ITestCaseResult result in testResults)
           {
              for (int actionIndex = 0; actionIndex < suiteEntry.TestCase.Actions.Count; actionIndex++)
              {
                 var action = suiteEntry.TestCase.Actions[actionIndex];
                 if (!(action is ITestStep))
                 {
                    continue;
                 }

                 var step = action as ITestStep;

                 var topIteration = result.Iterations.FirstOrDefault();
                 if (topIteration == null)
                 {
                    continue;
                 }

                 var actionCount = topIteration.Actions.Count();
                 if (actionCount == 0 || actionIndex > (actionCount - 1))
                 {
                    continue;
                 }

                 var actionResult = topIteration.Actions[actionIndex];

                 string comment = actionResult.Comment;

                 var testCaseItemType = ItemTypes.TestCase;

                 // TODO: Find the parent and query
                 // Parent.Store.FieldDefinitions for
                 // FieldDefinigion.Name.Contains("Client(s)"))
                 // Where value == "OHIO"

                 Console.WriteLine(string.Format("\t\t- Action: {0} ({1})", step.Title, testCaseItemType));
                 Console.WriteLine(string.Format("\t\t- Expected Result: {0}", step.ExpectedResult));

                 foreach (var attachment in actionResult.Attachments)
                 {
                     //attachment.DownloadToFile(Path.Combine("C:\attachments", attachment.Name));
                 }
              }
           }
        }
     }
  }

  var tfsTest = new TfsTest();
  tfsTest.GenerateReport();

  Console.WriteLine();
  Console.WriteLine("Done.");
  Console.WriteLine("Press any key to exit...");
  Console.ReadKey();
</code>```

答:
The simplest way is using WIQL. You can query for any of work items, and links between work items by using one of the WorkItemStore.Query methods or a Query object. These queries use the work item query language (WIQL), which resembles Transact-SQL. A code snippet as below:

```<code>   TfsTeamProjectCollection teamProjectCollection =
               new TfsTeamProjectCollection(collectionUri);
WorkItemStore workItemStore = teamProjectCollection.GetService<WorkItemStore>();

string queryString = "select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = 'YourTeamProjectName' and [System.WorkItemType] <> '' and [System.ChangedDate] >= @today - 30 order by [System.Id]";

// Create and run the query.
Query query = new Query(workItemStore, queryString);
WorkItemCollection witCollection = query.RunQuery();

foreach (WorkItem workItem in witCollection)
{

      foreach (WorkItemLink wiLink in workItem.WorkItemLinks)

      {
             //find if the link type is parent/chind
            if (wiLink.LinkTypeEnd.Name.Equals("Parent")|| wiLink.LinkTypeEnd.Name.Equals("Child"))
             {
                       .......
             }
       }
 }
</code>```

You could  change the queryString according to your request such as for a specific test case work item and have a particular FieldDefinition value.  For more details, you could also have a look at answers in this question: Retrieving work items and their linked work items in a single query using the TFS APIs

Body:
I need to get obtain information from Test Cases that are only associated with Parent Work Items that have a particular FieldDefinition value.

What I've been trying to do, is get a list of projects from the Test Management Service, iterating through all the Test Cases, and from there, hopefully, find the Parent Work Item associated with the Test Case and see if it has the FieldDefinition value I'm looking for. Here is what I have so far, but once I get my hands on the Test Cases, I don't know where to go from there to A) get the Parent Work Item and B) query the FieldDefinitions to find the FieldDefinition value I'm looking for. The documentation is pretty murky:

 public class TfsTest
  {
     private TfsTeamProjectCollection teamProjectCollection;
     private WorkItemStore workItemStore;
     private delegate void Execute();

     public void GenerateReport()
     {
        TeamProjectPicker teamProjectPicker = new TeamProjectPicker(TeamProjectPickerMode.NoProject, false);
         teamProjectPicker.ShowDialog();
        if (teamProjectPicker.SelectedTeamProjectCollection != null)
        {
           this.teamProjectCollection = teamProjectPicker.SelectedTeamProjectCollection;
           ITestManagementService testManagementService = (ITestManagementService)this.teamProjectCollection.GetService(typeof(ITestManagementService));

           this.workItemStore = (WorkItemStore)teamProjectCollection.GetService(typeof(WorkItemStore));

           foreach (Project project in workItemStore.Projects)
           {
              ITestManagementTeamProject _testproject = testManagementService.GetTeamProject(project.Name);
              GetTestPlans(_testproject);
           }
        }
     }

     void GetTestPlans(ITestManagementTeamProject testProject)
      {
        ITestPlanCollection plans = testProject.TestPlans.Query("Select * From TestPlan");

        foreach (ITestPlan plan in plans)
        {
           var planName = plan.Name;
           var testPlanType = ItemTypes.TestPlan;

           Console.WriteLine(string.Format("* {0} ({1})", plan.Name, testPlanType));

           if (plan.RootSuite != null && plan.RootSuite.Entries.Count > 0)
           {
              GetPlanSuites(plan.RootSuite.Entries, testProject);
           }
        }
     }

     void GetPlanSuites(ITestSuiteEntryCollection suites, ITestManagementTeamProject testProject)
     {
        foreach (ITestSuiteEntry suite_entry in suites)
        {
           IStaticTestSuite suite = suite_entry.TestSuite as IStaticTestSuite;
           if (suite != null)
           {

              // Test suites...
              var suiteTitle = suite.Title;
              var testSuiteType = ItemTypes.TestSuite;

              Console.WriteLine(string.Format("\t- {0} ({1})", suiteTitle, testSuiteType));

              GetTestCases(suite, testProject);
           }
        }
     }

     void GetTestCases(IStaticTestSuite suite, ITestManagementTeamProject testProject)
      {
        // iterate each test case
        foreach (ITestSuiteEntry suiteEntry in suite.TestCases)
        {
           if (suiteEntry.Id == 73649)
           {
              Console.WriteLine("Found it!");
           }

           var testResults = testProject.TestResults.ByTestId(suiteEntry.TestCase.Id);

           // iterate each result for the case
           foreach (ITestCaseResult result in testResults)
           {
              for (int actionIndex = 0; actionIndex < suiteEntry.TestCase.Actions.Count; actionIndex++)
              {
                 var action = suiteEntry.TestCase.Actions[actionIndex];
                 if (!(action is ITestStep))
                 {
                    continue;
                 }

                 var step = action as ITestStep;

                 var topIteration = result.Iterations.FirstOrDefault();
                 if (topIteration == null)
                 {
                    continue;
                 }

                 var actionCount = topIteration.Actions.Count();
                 if (actionCount == 0 || actionIndex > (actionCount - 1))
                 {
                    continue;
                 }

                 var actionResult = topIteration.Actions[actionIndex];

                 string comment = actionResult.Comment;

                 var testCaseItemType = ItemTypes.TestCase;

                 // TODO: Find the parent and query
                 // Parent.Store.FieldDefinitions for
                 // FieldDefinigion.Name.Contains("Client(s)"))
                 // Where value == "OHIO"

                 Console.WriteLine(string.Format("\t\t- Action: {0} ({1})", step.Title, testCaseItemType));
                 Console.WriteLine(string.Format("\t\t- Expected Result: {0}", step.ExpectedResult));

                 foreach (var attachment in actionResult.Attachments)
                 {
                     //attachment.DownloadToFile(Path.Combine("C:\attachments", attachment.Name));
                 }
              }
           }
        }
     }
  }

  var tfsTest = new TfsTest();
  tfsTest.GenerateReport();

  Console.WriteLine();
  Console.WriteLine("Done.");
  Console.WriteLine("Press any key to exit...");
  Console.ReadKey();

Body:
The simplest way is using WIQL. You can query for any of work items, and links between work items by using one of the WorkItemStore.Query methods or a Query object. These queries use the work item query language (WIQL), which resembles Transact-SQL. A code snippet as below:

   TfsTeamProjectCollection teamProjectCollection =
               new TfsTeamProjectCollection(collectionUri);
WorkItemStore workItemStore = teamProjectCollection.GetService<WorkItemStore>();

string queryString = "select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = 'YourTeamProjectName' and [System.WorkItemType] <> '' and [System.ChangedDate] >= @today - 30 order by [System.Id]";

// Create and run the query.
Query query = new Query(workItemStore, queryString);
WorkItemCollection witCollection = query.RunQuery();

foreach (WorkItem workItem in witCollection)
{

      foreach (WorkItemLink wiLink in workItem.WorkItemLinks)

      {
             //find if the link type is parent/chind
            if (wiLink.LinkTypeEnd.Name.Equals("Parent")|| wiLink.LinkTypeEnd.Name.Equals("Child"))
             {
                       .......
             }
       }
 }

You could  change the queryString according to your request such as for a specific test case work item and have a particular FieldDefinition value.  For more details, you could also have a look at answers in this question: Retrieving work items and their linked work items in a single query using the TFS APIs


问:
A jpeg image uploaded from an iPhone to S3 is not readable. But works on photoshop
I'm trying to upload a jpeg image from an iOS device to S3 using a presigned url. Here's what I'm doing:

```<code>const file = {
  uri: imageURL,
  type: 'image/jpeg'
};

const formData = new FormData();
formData.append('photo', file);
formData.append('Content-Type', 'image/jpeg');

const response = await axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  url: s3PreSignedURL,
  data: formData
});
</code>```

(The app is in react native and I use react-native-camera to take the photo.)

The problem is the image gets uploaded. When I download it and try to view on my mac it says The file could not be opened. But if I open it in Photoshop it works. Any idea what's going on?

You can find a sample image here: https://s3-ap-southeast-1.amazonaws.com/eyesnapdev/scans/1509856619481-71809992-b818-4637-93f1-9a75b6588c2c.jpg

答:
Your uploaded image is saving whole multipart form data and contains the following information as well (Open your s3 jpg image in a text editor to see):

--K_B9dYtGXt4.LjeMIncq0ajcL6vDRYqD1hRiwoIOJzPKYTVi8jTYT_f07RZw37Om1NJwGi
content-disposition: form-data; name="photo"
content-type: image/jpeg

s3  upload expects only data of file to be uploaded in post not a multipart form.

After digging through React native core, I think following code should work. I haven't tried it myself yet though:

```<code>fetch(s3PreSignedURL,{
    method:"PUT",
    headers: {
      'Content-Type': 'image/jpg'
    },
    body:{uri:imageURL}
});
</code>```

or using axios:

```<code>axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'image/jpg'
  },
  url: s3PreSignedURL,
  body:{uri:imageURL}
});
</code>```

Body:
I'm trying to upload a jpeg image from an iOS device to S3 using a presigned url. Here's what I'm doing:

const file = {
  uri: imageURL,
  type: 'image/jpeg'
};

const formData = new FormData();
formData.append('photo', file);
formData.append('Content-Type', 'image/jpeg');

const response = await axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  url: s3PreSignedURL,
  data: formData
});

(The app is in react native and I use react-native-camera to take the photo.)

The problem is the image gets uploaded. When I download it and try to view on my mac it says The file could not be opened. But if I open it in Photoshop it works. Any idea what's going on?

You can find a sample image here: https://s3-ap-southeast-1.amazonaws.com/eyesnapdev/scans/1509856619481-71809992-b818-4637-93f1-9a75b6588c2c.jpg

Body:
Your uploaded image is saving whole multipart form data and contains the following information as well (Open your s3 jpg image in a text editor to see):

--K_B9dYtGXt4.LjeMIncq0ajcL6vDRYqD1hRiwoIOJzPKYTVi8jTYT_f07RZw37Om1NJwGi
content-disposition: form-data; name="photo"
content-type: image/jpeg

s3  upload expects only data of file to be uploaded in post not a multipart form.

After digging through React native core, I think following code should work. I haven't tried it myself yet though:

fetch(s3PreSignedURL,{
    method:"PUT",
    headers: {
      'Content-Type': 'image/jpg'
    },
    body:{uri:imageURL}
});

or using axios:

axios({
  method: 'PUT',
  headers: {
    'Content-Type': 'image/jpg'
  },
  url: s3PreSignedURL,
  body:{uri:imageURL}
});


问:
Sending email via GMAIL using Powershell in VSTS
I want to send an email at the end of a VSTS release with some additional data. I am using a powershell release task and am using the Gmail SMTP server. The powershell script is as follows:

```<code>$b = Invoke-WebRequest "http://mywebsite" -usebasicparsing
$message = New-Object System.Net.Mail.MailMessage
$message.subject =  "Swagger"
$message.body = $b
$message.to.add("me@hotmail.com")
$message.from = "source@gmail.com"
$smtp = New-Object System.Net.Mail.SmtpClient("smtp.gmail.com", "587");
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, "apppassword");
$smtp.send($message)
</code>```

Since I am using 2 factor authentication, I am using an app password in the code above. This works fine when I run it from my local machine. However, as part of the release process, it gives me the following error:

"The SMTP server requires a secure connection or the client was not
  authenticated. The server response was: 5.5.1 Authentication Required"

Can anyone point me in the right direction? Thanks!

答:
Could you please try this: </p>

```<code>$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "username@gmail.com"
$Password = "password"
$to = "username_to_send@gmail.com"
#$cc = "username@gmail.com"
$subject = "Email Subject"
$body = "Insert body text here"
#$attachment = "C:\attachedFile.txt"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
#$message.cc.add($cc)
$message.from = $username
#$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent successfully using GMAIL"
</code>```

Body:
I want to send an email at the end of a VSTS release with some additional data. I am using a powershell release task and am using the Gmail SMTP server. The powershell script is as follows:

$b = Invoke-WebRequest "http://mywebsite" -usebasicparsing
$message = New-Object System.Net.Mail.MailMessage
$message.subject =  "Swagger"
$message.body = $b
$message.to.add("me@hotmail.com")
$message.from = "source@gmail.com"
$smtp = New-Object System.Net.Mail.SmtpClient("smtp.gmail.com", "587");
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, "apppassword");
$smtp.send($message)

Since I am using 2 factor authentication, I am using an app password in the code above. This works fine when I run it from my local machine. However, as part of the release process, it gives me the following error:

"The SMTP server requires a secure connection or the client was not
  authenticated. The server response was: 5.5.1 Authentication Required"

Can anyone point me in the right direction? Thanks!

Body:
Could you please try this:

$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "username@gmail.com"
$Password = "password"
$to = "username_to_send@gmail.com"
#$cc = "username@gmail.com"
$subject = "Email Subject"
$body = "Insert body text here"
#$attachment = "C:\attachedFile.txt"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
#$message.cc.add($cc)
$message.from = $username
#$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent successfully using GMAIL"


问:
Dividing a Joda Time Period into intervals of desired size?
I have a "period" (P) of time that is represented by a start time (S) and an end time (E).
I want to divide P into C chunks of size D. That is,

P = C * D + R, where R is the remainder or leftover time.

eg.

```<code>S = NOW, E = 10 sec after NOW, D = 3 sec.
Therefore, P = 10 sec, C = 3, R = 1 sec.
</code>```

I want to store and display all the chunks C with their start times, end times and sizes.
Finally, I want to store and display the remainder. How do I do this using Joda Time ?

Does the API provide simple methods and classes to do this or I will have to figure a way out ?

This question is a small part of another question I have posted here

答:
In Case some is looking equal denominator between given time here is code </p>

<p>`</p>

```<code>private List<Interval> splitDateTime(long start, long end, int intervalNo) {
        long interval = (end - start) / intervalNo;
        List<Interval> list = new ArrayList<Interval>();
        for (long i = start + interval; i < end; i += interval) {
            list.add(new Interval(start, i));
            start=start + interval;
        }
        list.add(new Interval(start, end));
        return list;
    }
</code>```

<p>` </p>

Body:
I have a "period" (P) of time that is represented by a start time (S) and an end time (E).
I want to divide P into C chunks of size D. That is,

P = C * D + R, where R is the remainder or leftover time.

eg.

S = NOW, E = 10 sec after NOW, D = 3 sec.
Therefore, P = 10 sec, C = 3, R = 1 sec.

I want to store and display all the chunks C with their start times, end times and sizes.
Finally, I want to store and display the remainder. How do I do this using Joda Time ?

Does the API provide simple methods and classes to do this or I will have to figure a way out ?

This question is a small part of another question I have posted here

Body:
In Case some is looking equal denominator between given time here is code

`

private List<Interval> splitDateTime(long start, long end, int intervalNo) {
        long interval = (end - start) / intervalNo;
        List<Interval> list = new ArrayList<Interval>();
        for (long i = start + interval; i < end; i += interval) {
            list.add(new Interval(start, i));
            start=start + interval;
        }
        list.add(new Interval(start, end));
        return list;
    }

`


问:
React Native - Debugger Worker error
I get this error Uncaught SyntaxError: Unexpected token < when use Debug JS Remotely. This error is from debuggerWorker.js <!doctype html>
Cached Bundles
.

答: I had the very same issue after upgrading to 0.50.3 of react native.  I fought for a day, but than the problem suddenly disappeared.  Did multiply things, but it probably was reloading the chrome tab/restarting chrome ;-)</p>

Title: React Native - Debugger Worker error


问:
The condition `WHERE Id = 14317961` in my query is invalid
```<code>var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}
</code>```

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?

答:
missing space after " WHERE "</p>

```<code>var report = AdWordsApp.report(
       'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
       'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
       'WHERE ' +  <----- space was missing
       'Id = 14317961 ' +
       'DURING LAST_7_DAYS ');
</code>```

Body:
var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?

Body:
missing space after " WHERE "

var report = AdWordsApp.report(
       'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
       'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
       'WHERE ' +  <----- space was missing
       'Id = 14317961 ' +
       'DURING LAST_7_DAYS ');


问:
EF4 Unable to load one or more of the requested types on test server
I developed an ASP.NET v4 application using Entity Framework 4. I'm deploying it to the test server (Windows 2008 R2 with .NET Framework 4 installed).

The application throws this error:

[ReflectionTypeLoadException: Unable
  to load one or more of the requested
  types. Retrieve the LoaderExceptions
  property for more information.]

  System.Reflection.RuntimeModule.GetTypes(RuntimeModule
  module) +0

  System.Reflection.Assembly.GetTypes()
  +144    System.Data.Metadata.Edm.ObjectItemConventionAssemblyLoader.LoadTypesFromAssembly()
  +45    System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
  +34    System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly
  assembly, Boolean
  loadReferencedAssemblies,
  ObjectItemLoadingSessionData
  loadingData) +130

  System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly
  assembly, Boolean
  loadReferencedAssemblies,
  KnownAssembliesSet knownAssemblies,
  EdmItemCollection edmItemCollection,
  Action1 logLoadMessage, Object&
  loaderCookie, Dictionary2&
  typesInLoading, List1& errors) +248

  System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection
  objectItemCollection, Assembly
  assembly, Boolean
  loadReferencedAssemblies,
  EdmItemCollection edmItemCollection,
  Action1 logLoadMessage) +580

  System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type
  type, EdmItemCollection
  edmItemCollection) +121

  System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type
  type, Assembly callingAssembly) +178

  System.Data.Objects.ObjectContext.GetTypeUsage(Type
  entityCLRType) +49

  System.Data.Objects.ObjectContext.CreateObjectSet(String
  entitySetName) +163

  PageManager.FetchDefaultPage()
  +114

When I look on my development PC I see this directory with assemblies:

C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.0

But on the server the whole .NETFramework directory is missing, there is just a v3.0 and v3.5 directory. I assume the server is using the assembly from one of these directories which are version 3.5.0.0 and not 4.0.0.0 (what my app is referencing).

What do I need to install? .NET 4 is installed on the server i'm 100% sure.

答:
The problem was nothing to do with .NET 4. I caught the ReflectionTypeLoadException and looped the LoaderExceptions. References to Microsoft.SyncronisationFramework were missing.

Perhaps a direct message in the exception with a list of missing references would be nice.


问:
How to automatically adjust plotly Y range on price chart
I plot a price chart.  The Y-axis scale is set for the minimum and maximum price over the entire price range.

When I decrease the range, for example when I display the last hour, the Y axis does not scale and the same range is given. How can I do so that the Y axis automatically scales to a visible price range?

This is my layout

layout = go.Layout(
        title=title,
        legend=dict(orientation="h"),
        xaxis=dict(
            rangeselector=dict(
                buttons=list([
                    dict(count=1,
                         label='1h',
                         step='hour',
                         stepmode='backward'),
                    dict(count=3,
                         label='3h',
                         step='hour',
                         stepmode='backward'),
                    dict(count=6,
                         label='6h',
                         step='hour',
                         stepmode='backward'),
                    dict(count=1,
                         label='1d',
                         step='day',
                         stepmode='backward'),
                    dict(count=3,
                         label='3d',
                         step='day',
                         stepmode='backward'),
                    dict(step='all')
                ])
            ),
            rangeslider=dict(),
            type='date'
        ),
        yaxis=dict(
            title=y_axis_label,
            showticklabels= not seperate_y_axis,
            autorange=True,
            type='linear'
        )
    )```

答:
I don't think it is possible right now in plotly (see https://community.plot.ly/t/range-slider-and-selector-in-plotly-js-without-fixed-y-axis/1475, https://community.plot.ly/t/autoscaling-the-y-axis-when-using-rangeslider/1456)

Do you have to use rangeslider? Perhaps a different layout would work.