问:
Java Mutithreading Ball Animation
My issue here with ball animation is that the ball is moving in a straight line leaving behind a trail. My expected output is that there should be no trail of the ball.

The code determines the movement of the ball in just one direction along X axis.

```<code>public class App extends JFrame implements Runnable{

    int x=0,y=250;

    public void run() {
      for(;;) {
        try {
          repaint();
          x++;
          Thread.sleep(10);
        } catch(Exception e){}
      }
    }

    public void paint(Graphics g) {
      g.drawOval(x,y,30,30);
    }

    public static void main(String[] args) {
        App frame= new App();
        frame.setTitle("Bounce");
        frame.setSize(400, 450);
        frame.setVisible(true);
        Thread t1 = new Thread(frame);
        t1.start();
    }
}
</code>```

答:
You missed to call super.paint in your paint method:

```<code>public void paint(Graphics g) {
  super.paint(g);
  g.drawOval(x,y,30,30);
}
</code>```

Title: Java Mutithreading Ball Animation

Body:
My issue here with ball animation is that the ball is moving in a straight line leaving behind a trail. My expected output is that there should be no trail of the ball.

The code determines the movement of the ball in just one direction along X axis.

public class App extends JFrame implements Runnable{

    int x=0,y=250;

    public void run() {
      for(;;) {
        try {
          repaint();
          x++;
          Thread.sleep(10);
        } catch(Exception e){}
      }
    }

    public void paint(Graphics g) {
      g.drawOval(x,y,30,30);
    }

    public static void main(String[] args) {
        App frame= new App();
        frame.setTitle("Bounce");
        frame.setSize(400, 450);
        frame.setVisible(true);
        Thread t1 = new Thread(frame);
        t1.start();
    }
}

Body:
You missed to call super.paint in your paint method:

public void paint(Graphics g) {
  super.paint(g);
  g.drawOval(x,y,30,30);
}


来源: stackexchange

问:
How to Mass Delete Files in Windows using batch
I recently refreshed my PC and upon finally finishing, I realized a pesky file named thumbs.db had been left in every folder and directory. I'm trying to find a simple way to DELETE ALL thumbs.db from my ENTIRE C: drive.

Code I've tried (Only removed thumbs.db from desktop)

```<code>dir thumbs.db /a /b /s
del thumbs.db /a /s
</code>```

PS: I'm open to any Power Shell Ideas Also.

答:
You can achieve this by running:

```<code>C:
cd /
del /s /q /f /a:h Thumbs.db
</code>```

The first line sets the drive you want to run it on.
The second line points to the root directory of the drive.
The third line force deletes (/f) hidden (/a:h) thumbs.db without prompting (/q) in all subfolders (/s)

ContentLicense: CC BY-SA 3.0

Body:
I recently refreshed my PC and upon finally finishing, I realized a pesky file named thumbs.db had been left in every folder and directory. I'm trying to find a simple way to DELETE ALL thumbs.db from my ENTIRE C: drive.

Code I've tried (Only removed thumbs.db from desktop)

dir thumbs.db /a /b /s
del thumbs.db /a /s

PS: I'm open to any Power Shell Ideas Also.

Body:
You can achieve this by running:

C:
cd /
del /s /q /f /a:h Thumbs.db

The first line sets the drive you want to run it on.
The second line points to the root directory of the drive.
The third line force deletes (/f) hidden (/a:h) thumbs.db without prompting (/q) in all subfolders (/s)


问:
NaN result when summing two tensors which individually are both real numbers
So I've been playing with this interesting application of tensorflow: TensorKart

The full source code is here: https://github.com/kevinhughes27/TensorKart

I'm getting a NaN result in my loss calculation and it's totally stumped me. The problem lies in this line of code:

```<code>loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y))) + tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * L2NormConst
</code>```

When I evaluate the first part:

```<code>tf.reduce_mean(tf.square(tf.sub(model.y_, model.y)))
</code>```

I get values around 0.8
When I evaluate the second part:

```<code>tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * L2NormConst
</code>```

I get values around 3.1

BUT when I sum the two parts I get NaN?!?!

I've checked the shape and types and they both come back as: Tensor("Shape:0", shape=(0,), dtype=int32)

Things that I have tried: using tf.reduce_sum instead of tf.add_n, casting them to tf.float32, summing them with tf.add....

Does anyone have any insights?

答:
So after having gone through every operation leading up to the calculation of the loss value, it turns out there were NaN values in my input data. Converting them to zero resolved the issue of getting a NaN result in the final loss value calculation.

What I haven't figured out till now is why I was only getting an error at the point I sum the two parts of the loss value but not while calculating the parts individually.

Utterly bizarre.

Body:
So I've been playing with this interesting application of tensorflow: TensorKart

The full source code is here: https://github.com/kevinhughes27/TensorKart

I'm getting a NaN result in my loss calculation and it's totally stumped me. The problem lies in this line of code:

loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y))) + tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * L2NormConst

When I evaluate the first part:

tf.reduce_mean(tf.square(tf.sub(model.y_, model.y)))

I get values around 0.8
When I evaluate the second part:

tf.add_n([tf.nn.l2_loss(v) for v in train_vars]) * L2NormConst

I get values around 3.1

BUT when I sum the two parts I get NaN?!?!

I've checked the shape and types and they both come back as: Tensor("Shape:0", shape=(0,), dtype=int32)

Things that I have tried: using tf.reduce_sum instead of tf.add_n, casting them to tf.float32, summing them with tf.add....

Does anyone have any insights?


问:
How to toggle add/remove when adding html into a textarea?
When I click on the button ADD, it should be adding all the html into the textarea, and works fine. However, If I click again I should be removing that from the text area.
An idea maybe is by pushing the inserted html into an array?

$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="row">
     <div class="col-xs-12 col-md-6">
      <div class="thumbnail">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/3fJjajItnEQ?rel=0&modestbranding=1" frameborder="0" allowfullscreen=""></iframe></div><div class="caption">
          <p>Duration: <span class="video-time">31:54</span></p>
          <button type="button" class="btn btn-danger btn-block btn_video"><strong>ADD</strong></button>
        </div>
      </div>
    </div>
    <div class="col-xs-12 col-md-6">
      <div class="thumbnail">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/3fJjajItnEQ?rel=0&modestbranding=1" frameborder="0" allowfullscreen=""></iframe></div><div class="caption">
          <p>Duration: <span class="video-time">31:54</span></p>
          <button type="button" class="btn btn-danger btn-block btn_video"><strong>ADD</strong></button>
        </div>
      </div>
    </div>
  </div>
</div>

<textarea name="usp-custom-5" id="usp-custom-5" data-required="false" placeholder="Example Input 5" data-richtext="false" class="usp-input usp-textarea usp-form-16" rows="5" cols="30" style="margin: 0px; height: 266px; width: 996px;"></textarea></code>```

Here it is a Fiddle.

```<code>$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});
</code>```

答:
Updated fiddle.

You could use a helper class selected for this and add/remove it by click :

```<code>$('body').on('click', '.btn_video', function() {
  var content = "";

  if($(this).text()=="ADD")
  {
    $(this).text("REMOVE");
    $(this).parents(".thumbnail").parent().addClass('selected');
  }else{
    $(this).text("ADD");
    $(this).parents(".thumbnail").parent().removeClass('selected');
  }

  $('.selected').each(function(){
    content += $(this).prop('outerHTML');
  });

  $('#usp-custom-5').val(content);
});
</code>```

Hope this helps.

Body:
When I click on the button ADD, it should be adding all the html into the textarea, and works fine. However, If I click again I should be removing that from the text area.
An idea maybe is by pushing the inserted html into an array?

$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Duration: 31:54

          <button type="button" class="btn btn-danger btn-block btn_video">ADD</button>

Duration: 31:54

          <button type="button" class="btn btn-danger btn-block btn_video">ADD</button>

<textarea name="usp-custom-5" id="usp-custom-5" data-required="false" placeholder="Example Input 5" data-richtext="false" class="usp-input usp-textarea usp-form-16" rows="5" cols="30" style="margin: 0px; height: 266px; width: 996px;"></textarea>

Here it is a Fiddle.

$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});

Body:
Updated fiddle.

You could use a helper class selected for this and add/remove it by click :

$('body').on('click', '.btn_video', function() {
  var content = "";

  if($(this).text()=="ADD")
  {
    $(this).text("REMOVE");
    $(this).parents(".thumbnail").parent().addClass('selected');
  }else{
    $(this).text("ADD");
    $(this).parents(".thumbnail").parent().removeClass('selected');
  }

  $('.selected').each(function(){
    content += $(this).prop('outerHTML');
  });

  $('#usp-custom-5').val(content);
});

Hope this helps.


问:
Can I retrain an old model with new data using TensorFlow?
I am new to TensorFlow and I am just trying to see if my idea is even possible.

I have trained a model with multi class classifier. Now I can classify a sentence in input, but I would like to change the result of CNN, for example, to improve the score of classification or change the classification.

I want to try to train just a single sentence with its class on a trained model, is this possible?

答:
If I understand your question correctly, you are trying to reload a previously trained model either to run it through further iterations, test it on a new sentence, or fine tune the model a bit. If this is the case, yes you can do this. Look into saving and restoring models (https://www.tensorflow.org/api_guides/python/state_ops#Saving_and_Restoring_Variables).

To give you a rough outline, when you initially train your model, after setting up the network architecture, set up a saver:

```<code>trainable_var = tf.trainable_variables()
sess = tf.Session()
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer

# Run/train your model until some completion criteria is reached
#....
#....

saver.save(sess, 'model.ckpt')
</code>```

Now, to reload your model:

```<code>saver = tf.train.import_meta_graph('model.ckpt.meta')
saver.restore('model.ckpt')
#Note: if you have already defined all variables before restoring the model, import_meta_graph is not necessary
</code>```

This will give you access to all the trained variables and you can now feed in whatever new sentence you have. Hope this helps.

Body:
If I understand your question correctly, you are trying to reload a previously trained model either to run it through further iterations, test it on a new sentence, or fine tune the model a bit. If this is the case, yes you can do this. Look into saving and restoring models (https://www.tensorflow.org/api_guides/python/state_ops#Saving_and_Restoring_Variables).

To give you a rough outline, when you initially train your model, after setting up the network architecture, set up a saver:

trainable_var = tf.trainable_variables()
sess = tf.Session()
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer

# Run/train your model until some completion criteria is reached
#....
#....

saver.save(sess, 'model.ckpt')

Now, to reload your model:

saver = tf.train.import_meta_graph('model.ckpt.meta')
saver.restore('model.ckpt')
#Note: if you have already defined all variables before restoring the model, import_meta_graph is not necessary

This will give you access to all the trained variables and you can now feed in whatever new sentence you have. Hope this helps.


问:
Pandas dataframe indexes
Lets say I am working with a dataset which has 10 columns.
Now, the Label column for my 'Y' is 1.
How do I set my X and Y.
This is what I have done so far.

```<code>array = dataframe. values
X = array[:,0:2:32]   #I know this isn't the right way to do this.
Y = array[:,1]
</code>```

Yes, we can assign names to columns and omit the column with name=label, but I am trying to find a straight forward approach based on indexes. Any leads?

答:
You can do this:</p>

```<code>Y = df.loc[:,1].values
cols = list(df.loc[:,:0]) + list(df.loc[:,2:32])
X = df[cols].values
</code>```

Title: Pandas dataframe indexes

Body:
Lets say I am working with a dataset which has 10 columns.
Now, the Label column for my 'Y' is 1.
How do I set my X and Y.
This is what I have done so far.

array = dataframe. values
X = array[:,0:2:32]   #I know this isn't the right way to do this.
Y = array[:,1]

Yes, we can assign names to columns and omit the column with name=label, but I am trying to find a straight forward approach based on indexes. Any leads?

Body:
You can do this:

Y = df.loc[:,1].values
cols = list(df.loc[:,:0]) + list(df.loc[:,2:32])
X = df[cols].values


问:
How do I specify dependencies in a .NET Standard Class Library?
A .NET Standard Class Library doesn't use a .nuspec file; there is a "Package" tab in the project settings where you enter all the metadata for the NuGet package. These go in the .csproj file.

I want to create a solution with projects A and B, where project B depends on project A. Both need to go on NuGet as separate packages. But if someone installs the NuGet package for B, it should also install the package for A.

How do you specify this simple dependency for a .NET Standard Class Library? I'm not assuming that adding a reference will be enough to do this.

答: From what I have found it is not yet supported in .csproj files and you should use .nuspec to specify dependencies. Have a look how they do it in xUnit, for example.</p>


答: This is not a multi-threading issue, you just never "erase" the ovals you draw for the previous x. Your paint method needs to call super.paint() in order to clear the previous ovals. This is explained here with almost the same code as you but without your issue!

Title: Java Mutithreading Ball Animation


问:
Doctrine QueryBuilder > Working with ManyToMany relationships
I have been struggling with this issue for a while and all relevant topics does not match my specific needs. I am building a "dashboard" that provides system oversight on a wide range of entities. For obvious reasons I would like to keep my queries as few and as efficient as possible. Therefor I am trying to limit my queries to 1 per entity where I retrieve all the relevant info.

My problem comes in when I need to extract specific data from ManyToMany (or OneToMany) relational entities.

For example, in the following case I am trying to find the amount of accounts that do not have any invoices linked to them.

```<code>    $qb = $this->getDoctrine()->getManager()->createQueryBuilder();
    $qb->select(array(
        'COUNT(account) as totalAccounts',
        'SUM(account.active) as activeAccounts',
        'SUM(account.approved) as approvedAccounts',
        'SUM(account.reverted) as revertedAccounts',
        'SUM(account.approvalRequested) as pendingApprovalAccounts',
        "SUM(CASE WHEN COUNT(account.invoices) = 0 THEN 1 ELSE 0 END) as testAccounts"
    ))
    ->from('AppBundle:Account', 'account');
</code>```

I receive a the following error:
QueryException: [Semantical Error] line 0, col 252 near 'invoices) = 0': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

In the following example I am trying to find the number of users that have unpaid invoices attached to them. I tried a different approach by joining user.invoices.

```<code>    $qb = $this->getDoctrine()->getManager()->createQueryBuilder();
    $qb->select(array(
        'COUNT(user) as totalUsers',
        'SUM(user.active) as activeUsers',
        "SUM(CASE WHEN user.userType = 'MONTHLY' AND user.active = true THEN 1 ELSE 0 END) as monthlyUsers",
        "SUM(CASE WHEN user.userType = 'PAYG' AND user.active = true THEN 1 ELSE 0 END) as paygUsers",
        "SUM(CASE WHEN user.noticeType = 'SWITCH' AND user.active = true THEN 1 ELSE 0 END) as noticeUsersPayg",
        "SUM(CASE WHEN user.noticeType = 'DISABLE' AND user.active = true THEN 1 ELSE 0 END) as noticeUsersDisable",
        "SUM(CASE WHEN SUM(CASE WHEN invoices.datePaid is null THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) as suspendedUsers",
    ))
    ->from('AppBundle:User', 'user')
    ->leftJoin('user.invoices', 'invoices');
</code>```

In this case I get the error:
SQLSTATE[HY000]: General error: 1111 Invalid use of group function

I can easily build the right query with all the necessary SELECT subqueries in SQL, but I am trying to do this the right way by using QueryBuilder. QueryBuilder also does not seem to accept or allow SELECT subqueries. I know that I am probably doing a few (or many) things wrong, and that is why I am posting this question. I think others can greatly benefit if this question is answered properly, as queries where relational entities affects returned data is an issue that we have all encountered and I could not find any proper content that addresses this matter.

答:
You are mostly fighting the ORM now, and I think this is one of the cases where you are better of using native queries. You are basically returning scalar values for reporting only, there are not that many advantages of using the ORM for that.

See http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html

Body:
I have been struggling with this issue for a while and all relevant topics does not match my specific needs. I am building a "dashboard" that provides system oversight on a wide range of entities. For obvious reasons I would like to keep my queries as few and as efficient as possible. Therefor I am trying to limit my queries to 1 per entity where I retrieve all the relevant info.

My problem comes in when I need to extract specific data from ManyToMany (or OneToMany) relational entities.

For example, in the following case I am trying to find the amount of accounts that do not have any invoices linked to them.

    $qb = $this->getDoctrine()->getManager()->createQueryBuilder();
    $qb->select(array(
        'COUNT(account) as totalAccounts',
        'SUM(account.active) as activeAccounts',
        'SUM(account.approved) as approvedAccounts',
        'SUM(account.reverted) as revertedAccounts',
        'SUM(account.approvalRequested) as pendingApprovalAccounts',
        "SUM(CASE WHEN COUNT(account.invoices) = 0 THEN 1 ELSE 0 END) as testAccounts"
    ))
    ->from('AppBundle:Account', 'account');

I receive a the following error:
QueryException: [Semantical Error] line 0, col 252 near 'invoices) = 0': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.

In the following example I am trying to find the number of users that have unpaid invoices attached to them. I tried a different approach by joining user.invoices.

    $qb = $this->getDoctrine()->getManager()->createQueryBuilder();
    $qb->select(array(
        'COUNT(user) as totalUsers',
        'SUM(user.active) as activeUsers',
        "SUM(CASE WHEN user.userType = 'MONTHLY' AND user.active = true THEN 1 ELSE 0 END) as monthlyUsers",
        "SUM(CASE WHEN user.userType = 'PAYG' AND user.active = true THEN 1 ELSE 0 END) as paygUsers",
        "SUM(CASE WHEN user.noticeType = 'SWITCH' AND user.active = true THEN 1 ELSE 0 END) as noticeUsersPayg",
        "SUM(CASE WHEN user.noticeType = 'DISABLE' AND user.active = true THEN 1 ELSE 0 END) as noticeUsersDisable",
        "SUM(CASE WHEN SUM(CASE WHEN invoices.datePaid is null THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END) as suspendedUsers",
    ))
    ->from('AppBundle:User', 'user')
    ->leftJoin('user.invoices', 'invoices');

In this case I get the error:
SQLSTATE[HY000]: General error: 1111 Invalid use of group function

I can easily build the right query with all the necessary SELECT subqueries in SQL, but I am trying to do this the right way by using QueryBuilder. QueryBuilder also does not seem to accept or allow SELECT subqueries. I know that I am probably doing a few (or many) things wrong, and that is why I am posting this question. I think others can greatly benefit if this question is answered properly, as queries where relational entities affects returned data is an issue that we have all encountered and I could not find any proper content that addresses this matter.


问:
SQLite reader.read() always returning false when executed from Task Scheduler
I have a C# program that uses a SQLite database to read/write data.  This program requires UAC elevation and I require it to be running at all times.  When I run this program manually, which I have to 'Run as admin', my SQLite database functions normally, able to read/write data to the database file.  However, my issue is when I try to have this program execute automatically when the computer starts.

As I mentioned earlier, I require this program to execute at all times. So, I have put a couple things in place that re-executes the program in the event it crashes (which works great).  However, I also need this to begin executing when the computer restarts.  Normally this isn't a problem, but the program requires UAC and I will rarely be around to click Yes on the UAC dialog, so I read around and it seems the only way to do this was to set up a task in Task Scheduler.  So, I have set up a task to run this at startup.  Upon testing, the program does execute but not functioning correctly.  Upon further debugging, I've found that each time my code reaches a SQLiteDataReader.read() line, it always seems to return false even though I know there are records there, but this only happens when the program is executed thru Task Scheduler.  No errors seem to be coming from SQLite.  I suspect file permissions to be the issue, but do not know how to resolve.

A couple things to note of what I've tried already.
1) In the Task Scheduler, I've set this up to execute using the same user account as I've been using to run it manually, which is also a Domain Admin, Admin, and a local Admin account.
2) The task is set to "run with highest privileges"
3) I've changed the security permissions to Full Control for just about every object I can think of (Admins, Domain Admins, Users, , Everyone, etc) on both the root folder of the program AND the SQLite database file.
4) I've even tried moving the entire application outside of the Program Files folder in case there was some sort of restricted access involved there as well.

I'm at my wits end trying to figure this out.  Any ideas on what to try next?  Or other solutions to get this to execute correctly at startup without user interaction?

答: I'm a bit late on reporting back on this issue.  Stupid on my part... The task scheduler simply needed to include the applications file folder path as the Startup path.  So it wasn't finding the database file as my path is using relative paths to reference.  I personally don't understand why this shouldn't always just default to the app's folder, but you live and you learn and bang your head on everything in between.</p>


问:
Steam API call failed to open stream
Hello I'm just working on a private Webpage for fun. I make a call to get a json from the steam API so that I can get the avatar of a user. Here's my code.

```<code>function getSteamImage() {
    $key = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
    $json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$key&steamids=76561197960435530');
    $json_array = json_decode($json,true);
    $image = $json_array["response"]["players"]["avatar"];
    return $image;
}

<li><img src="<?= getSteamImage() ?>"></li>
</code>```

But now im getting this error:

file_get_contents(http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXXXXXXXXXXX&steamids=76561197960435530):
  failed to open stream: A connection attempt failed because the
  connected party did not properly respond after a period of time, or
  established connection failed because connected host has failed to
  respond.

BTW the Steam key I used here isn't the one I'm using in the script!

答:
Found the problem but its not really my fault.

```<code>//Instead of this
$json_array["response"]["players"]["avatar"];

//It has to be this
$json_array["response"]["players"][0]["avatar"];
</code>```

In players there is an array with index 0.

Title: Steam API call failed to open stream

Body:
Hello I'm just working on a private Webpage for fun. I make a call to get a json from the steam API so that I can get the avatar of a user. Here's my code.

function getSteamImage() {
    $key = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";
    $json = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$key&steamids=76561197960435530');
    $json_array = json_decode($json,true);
    $image = $json_array["response"]["players"]["avatar"];
    return $image;
}

<img src="<?= getSteamImage() ?>">

But now im getting this error:

file_get_contents(http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXXXXXXXXXXX&steamids=76561197960435530):
  failed to open stream: A connection attempt failed because the
  connected party did not properly respond after a period of time, or
  established connection failed because connected host has failed to
  respond.

BTW the Steam key I used here isn't the one I'm using in the script!

Body:
Found the problem but its not really my fault.

//Instead of this
$json_array["response"]["players"]["avatar"];

//It has to be this
$json_array["response"]["players"][0]["avatar"];

In players there is an array with index 0.


问:
Get a Javascript variable on the click of button
That's my code:

```<code>afficherListe();
function afficherListe()
{
 $.post('afficher_liste.php', function(data)
 {
    var obj = jQuery.parseJSON(data);

    if(data!="")
    {
        $.each(obj, function(index, value){
            $('<li><button onclick="supprimer_article()">X</button>'+value.nomArticle+' '+value.prixArticle+'</li>').insertAfter($('#liste_boissons'));
        });
    }
    else
    {
        alert('no data');
    }
 });
}

function supprimer_article(article_selectionne)
{
    alert(article_selectionne);
}
</code>```

Problem : I want to put my variable in supprimer_article() function, to have it in parameter and to continue my work in the function.
Example : If I click on "X" Vodka button (view picture), I would find inalert(article_selectionne); "Vodka"

In a primary step, I've put the variable like that :
$('
<buttononclick="supprimer_article('+value.prixArticle+')">X</button>'+value.nomArticle+' '+value.prixArticle+'
').insertAfter($('#liste_boissons'));

But, the result in alert(article_selectionne); was : UNDEFINED

If you think you have the solution, it would be very nice and helpful to share it for me !

To have an idea of what do this function now (the final goal is that this function will remove the selected article from the DB after the onclick event....) :

答:
You need to add name to function arguments when calling. Replace the line

```<code>$('<li><button onclick="supprimer_article()">X</button>'+value.nomArticle+' '+value.prixArticle+'</li>').insertAfter($('#liste_boissons'));
</code>```

with the following code:

```<code>$('<li><button onclick="supprimer_article(\'' + value.nomArticle + '\')">X</button>'+value.nomArticle+' '+value.prixArticle+'</li>').insertAfter($('#liste_boissons'));
</code>```

Body:
That's my code:

afficherListe();
function afficherListe()
{
 $.post('afficher_liste.php', function(data)
 {
    var obj = jQuery.parseJSON(data);

    if(data!="")
    {
        $.each(obj, function(index, value){
            $('
<button onclick="supprimer_article()">X</button>'+value.nomArticle+' '+value.prixArticle+'
').insertAfter($('#liste_boissons'));
        });
    }
    else
    {
        alert('no data');
    }
 });
}

function supprimer_article(article_selectionne)
{
    alert(article_selectionne);
}

Problem : I want to put my variable in supprimer_article() function, to have it in parameter and to continue my work in the function.
Example : If I click on "X" Vodka button (view picture), I would find inalert(article_selectionne); "Vodka"

In a primary step, I've put the variable like that :
$('
<buttononclick="supprimer_article('+value.prixArticle+')">X</button>'+value.nomArticle+' '+value.prixArticle+'
').insertAfter($('#liste_boissons'));

But, the result in alert(article_selectionne); was : UNDEFINED

If you think you have the solution, it would be very nice and helpful to share it for me !

To have an idea of what do this function now (the final goal is that this function will remove the selected article from the DB after the onclick event....) :

Body:
You need to add name to function arguments when calling. Replace the line

$('<li><button onclick="supprimer_article()">X</button>'+value.nomArticle+' '+value.prixArticle+'</li>').insertAfter($('#liste_boissons'));

with the following code:

$('<li><button onclick="supprimer_article(\'' + value.nomArticle + '\')">X</button>'+value.nomArticle+' '+value.prixArticle+'</li>').insertAfter($('#liste_boissons'));


问:
Are acceptance criteria needed in stories that result from a breakdown of a main story?
When a Product Owner creates a story, as well as acceptance criteria, what needs to happen if the team decides to break down the story? Should the team decide on the acceptance criteria, as long as the acceptance criteria of the main story are met?

What if the new stories that are created after breaking down the main story are purely technical?

答:
The simple answer to this questions is you add acceptance criteria if you find them useful.

This is not a procedural thing. The idea of acceptance criteria came about because teams found them useful when it came to implementing stories. If you find acceptance criteria useful on stories that you have broken down from larger stories then use them.

What if the new stories that are created after breaking down the main story are purely technical?

Well then they are no longer stories, they are technical tasks.

A user story is a requirement described from the point of view of an end-user of the feature.

It is a common practice among Scrum teams to break stories down in to one or more technical tasks during sprint planning.


问:
how can i creat a list of clickable images on android
i am reallly new on android , what can i use to creat a list of images that when i click on one of them i add it to another list like this : enter image description here

i just want an idea like , do i need listview or something else becaus i dont know how can make 3 images in one line in a list view or use a grid of images but how can i hide the grid and only show it when i chose the list i want to show because i will have about 4 grid of images
like this when i click fruit et légumes it shows a list of images and then when i click viandes et piosson it shows antoher list of iamges
enter image description here

this what i have tried making a list with only strings that i add by clicking a button and know i want to devlope this like the image

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_interface);

        mShoppingList = (ListView) findViewById(R.id.shopping_listView);
        mItemEdit = (EditText) findViewById(R.id.item_editText);
        mAddButton = (Button) findViewById(R.id.add_button);

        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        mShoppingList.setAdapter(mAdapter);

        mAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String item = mItemEdit.getText().toString();
                final String Art=item;
                mAdapter.add(item);
                mAdapter.notifyDataSetChanged();
                mItemEdit.setText("");
</code>```

答:
What you are looking for is a RecyclerView and a GridLayoutManager. This will get you the correct view that you want.

Here is a link that demonstrates these two views working together RecyclerView with GridLayoutManager

As for clicking on one and removing it from the list, that is something you will need to handle inside of the Adapter.

Body:
i am reallly new on android , what can i use to creat a list of images that when i click on one of them i add it to another list like this : enter image description here

i just want an idea like , do i need listview or something else becaus i dont know how can make 3 images in one line in a list view or use a grid of images but how can i hide the grid and only show it when i chose the list i want to show because i will have about 4 grid of images
like this when i click fruit et légumes it shows a list of images and then when i click viandes et piosson it shows antoher list of iamges
enter image description here

this what i have tried making a list with only strings that i add by clicking a button and know i want to devlope this like the image

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_interface);

        mShoppingList = (ListView) findViewById(R.id.shopping_listView);
        mItemEdit = (EditText) findViewById(R.id.item_editText);
        mAddButton = (Button) findViewById(R.id.add_button);

        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        mShoppingList.setAdapter(mAdapter);

        mAddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String item = mItemEdit.getText().toString();
                final String Art=item;
                mAdapter.add(item);
                mAdapter.notifyDataSetChanged();
                mItemEdit.setText("");


问:
Load an embedded animated Cursor from the Resource
I have an animated Cursor file (*.ani) in the resources and want to show it as a cursor in my application. How can I load it from the resources?

I looked up in the Internet, but there are only ways to show it when u have a real file and if it is not embedded in the resources.

答:
// from resources modification here is : byte[] variable resource in the call

// modified class by Yvan Genesse

```<code>public class AdvancedCursorsFromEmbededResources

{

// modified by Yvan Genesse November 29 2010

// C# example tested in MS Visual Studio 2010 Ultimate version
// University Student in E-Business @ Laurentian University

// in your form code
/*
try
{
// from file
//this.Cursor = AdvancedCursors.Create(Path.Combine(Application.StartupPath, "flower_anim.ani"));
// from resouces   modification here is :   byte[] resource in the call
byte[] Embeded_Cursor_Resource = Properties.Resources.flower_anim;  // the animate cursor desired
this.Cursor = AdvancedCursorsFromEmbededResources.Create(Embeded_Cursor_Resource);

// or this way also works
this.Cursor = AdvancedCursorsFromEmbededResources.Create(Properties.Resources.flower_anim);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

*/

[DllImport("user32.dll")]
static extern IntPtr CreateIconFromResource(byte[] presbits, uint dwResSize, bool fIcon, uint dwVer);

// modification here is :   byte[] resource in the call
public static Cursor Create( byte[] resource)
{
    IntPtr myNew_Animated_hCursor;

    //byte[] resource = Properties.Resources.flower_anim;

        myNew_Animated_hCursor = CreateIconFromResource(resource, (uint)resource.Length, false, 0x00030000);

    if (!IntPtr.Zero.Equals(hCursor))
        {
            // all is good
                return new Cursor(myNew_Animated_hCursor);
       }
        else
       {  // resource wrong type or memory error occurred
    // normally this resource exists since you had to put  Properties.Resources. and a resource would appear and you selected it
    // the animate cursor desired  is the error generator since this call is not required for simple cursors

          throw new ApplicationException("Could not create cursor from Embedded resource ");
        }
}

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
// from resources modification here is : byte[] variable resource in the call

// modified class by Yvan Genesse

public class AdvancedCursorsFromEmbededResources

{

// modified by Yvan Genesse November 29 2010

// C# example tested in MS Visual Studio 2010 Ultimate version
// University Student in E-Business @ Laurentian University

// in your form code
/*
try
{
// from file
//this.Cursor = AdvancedCursors.Create(Path.Combine(Application.StartupPath, "flower_anim.ani"));
// from resouces   modification here is :   byte[] resource in the call
byte[] Embeded_Cursor_Resource = Properties.Resources.flower_anim;  // the animate cursor desired
this.Cursor = AdvancedCursorsFromEmbededResources.Create(Embeded_Cursor_Resource);

// or this way also works
this.Cursor = AdvancedCursorsFromEmbededResources.Create(Properties.Resources.flower_anim);
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}

*/

[DllImport("user32.dll")]
static extern IntPtr CreateIconFromResource(byte[] presbits, uint dwResSize, bool fIcon, uint dwVer);

// modification here is :   byte[] resource in the call
public static Cursor Create( byte[] resource)
{
    IntPtr myNew_Animated_hCursor;

    //byte[] resource = Properties.Resources.flower_anim;

        myNew_Animated_hCursor = CreateIconFromResource(resource, (uint)resource.Length, false, 0x00030000);

    if (!IntPtr.Zero.Equals(hCursor))
        {
            // all is good
                return new Cursor(myNew_Animated_hCursor);
       }
        else
       {  // resource wrong type or memory error occurred
    // normally this resource exists since you had to put  Properties.Resources. and a resource would appear and you selected it
    // the animate cursor desired  is the error generator since this call is not required for simple cursors

          throw new ApplicationException("Could not create cursor from Embedded resource ");
        }
}

}


问:
Write formatted JSON in Node.js
I'm using Node.js to POST JSON to PostBin but the data is being wrongly formated (as you can see here: http://www.postbin.org/1cpndqw).

This is the code I'm using for tesT:

```<code>var http = require('http');

var options = {
  host: 'www.postbin.org',
  port: 80,
  path: '/1cpndqw',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.write(JSON.stringify({ a:1, b:2, c:3 }, null, 4));
req.end();
</code>```

答:
I used a two step process that I found to work: </p>

```<code>var output = JSON.parse(insert_json_here);
var print_to_file = JSON.stringify(output, null, "\t")
</code>```

Title: Write formatted JSON in Node.js

Body:
I'm using Node.js to POST JSON to PostBin but the data is being wrongly formated (as you can see here: http://www.postbin.org/1cpndqw).

This is the code I'm using for tesT:

var http = require('http');

var options = {
  host: 'www.postbin.org',
  port: 80,
  path: '/1cpndqw',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.write(JSON.stringify({ a:1, b:2, c:3 }, null, 4));
req.end();

Body:
I used a two step process that I found to work:

var output = JSON.parse(insert_json_here);
var print_to_file = JSON.stringify(output, null, "\t")


问:
Does anyone see the error in this simple Ruby function?
This function is supposed to take a string and return the characters in reverse order.

```<code>def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end
</code>```

however all the tests return false:

```<code>puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)
</code>```

Does anyone see what the problem is?

答:
The problem is your function isn't returning its result, it's printing it. It needs to return reversedString.

As a rule of thumb, functions should return their result. Another function should format and print it.

```<code>def reverse(string)
    reversedString = "";

    i = string.length - 1
    while i >= 0
        reversedString = reversedString + string[i]
        i -= 1
    end

    return reversedString
end
</code>```

Note: This was probably an exercise, but Ruby already has String#reverse.

It's good that you're writing tests, but the way you're writing them it's hard to tell what went wrong. Look into a Ruby testing framework like MiniTest.

```<code>require "minitest/autorun"

class TestReverse < Minitest::Test
    def test_reverse
        assert_equal "cba", reverse("abc")
        assert_equal "a", reverse("a")
        assert_equal "", reverse("")
    end
end
</code>```

That would have told you that your function is returning nil.

```<code>  1) Failure:
TestReverse#test_reverse [test.rb:16]:
Expected: "cba"
  Actual: nil
</code>```

Body:
This function is supposed to take a string and return the characters in reverse order.

def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end

however all the tests return false:

puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)

Does anyone see what the problem is?

Body:
The problem is your function isn't returning its result, it's printing it. It needs to return reversedString.

As a rule of thumb, functions should return their result. Another function should format and print it.

def reverse(string)
    reversedString = "";

    i = string.length - 1
    while i >= 0
        reversedString = reversedString + string[i]
        i -= 1
    end

    return reversedString
end

Note: This was probably an exercise, but Ruby already has String#reverse.

It's good that you're writing tests, but the way you're writing them it's hard to tell what went wrong. Look into a Ruby testing framework like MiniTest.

require "minitest/autorun"

class TestReverse < Minitest::Test
    def test_reverse
        assert_equal "cba", reverse("abc")
        assert_equal "a", reverse("a")
        assert_equal "", reverse("")
    end
end

That would have told you that your function is returning nil.

  1) Failure:
TestReverse#test_reverse [test.rb:16]:
Expected: "cba"
  Actual: nil


问:
integer overflow in kernel -- possible?
I have to do integer arithmetic in kernel, specifically I need to increment a size_t object by some delta, and this will happen quite often. So I'm wondering if I need to guard against possible integer overflows in the kernel, and if so, does the kernel provide macros or APIs for this?

答:
size_t doesn't overflow; it is an unsigned type, with well-defined "wraparound" semantics. Incrementing the highest value of a size_t results in
zero.

In the specific case of size_t, in simple operations on size_t, like adding two sizes together, it is usually enough to just check whether the resulting operand is larger than one of the two source operands. If (size3 = size1 + size2) < size1), you have a wrap.

If an unsigned type is used as a clock value which goes around a "wheel", there are macros for doing "time before" calculations correctly. For instance, we want the time 0xFFFFFFFE to be treated as being a few time units in the past w.r.t. the time 0x00000003. If you're using the "jiffies" time in the kernel, then you can use the time_before inline function, and others in that family.  (Note that there are "classic jiffies" (my term) represented as long and 64 bit jiffies represented as u64, with separate functions like time_before versus time_before64).

But are there some general macros for doing math with overflow checks? Casually combing through a kernel tree (3.18.31 that I have at my convenience), it doesn't appear that way. grep -i overflow on the include subtree doesn't come up with anything and similar searches in code areas like fs reveal the use of ad hoc locally coded overflow checks. It's a shame, really; you'd think the problem of "if I add these two int values together, is there a problem" is common enough that there would be a solution in place that everyone can just use like some addv(x_int, y_int, &overflow_flag) or whatever.

Title: integer overflow in kernel -- possible?


问:
How to generate a string of given length which contains English alphabets, numbers and Spaces?
I know RandomStringUtils.random(4000, true, true) will generate a string with alphabets and numbers. But,the generated string doesn't contain space. How can I get a string which contains space as well?

答:
As already pointed out, the random method is overloaded and supports what you want. For example in this way

```<code>    StringBuilder tmp = new StringBuilder();
    for (char c = '0'; c <= '9'; c++)
        tmp.append(c);
    for (char c = 'a'; c <= 'z'; c++)
        tmp.append(c);
    for (char c = 'A'; c <= 'Z'; c++) // if you wish upper case
        tmp.append(c);
    tmp.append(' ');
    char[] chars = tmp.toString().toCharArray();
    String s = RandomStringUtils.random(4000, chars);
    System.out.println(s);
</code>```

If you will use this multiple times, make sure to store the char array and only calculate it once.

EDIT: Answer without for loops

```<code>char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
            's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '1','2','3','4','5','6','7','8','9','0',' '
};
String s2 = RandomStringUtils.random(4000, chars);
</code>```

Body:
As already pointed out, the random method is overloaded and supports what you want. For example in this way

    StringBuilder tmp = new StringBuilder();
    for (char c = '0'; c <= '9'; c++)
        tmp.append(c);
    for (char c = 'a'; c <= 'z'; c++)
        tmp.append(c);
    for (char c = 'A'; c <= 'Z'; c++) // if you wish upper case
        tmp.append(c);
    tmp.append(' ');
    char[] chars = tmp.toString().toCharArray();
    String s = RandomStringUtils.random(4000, chars);
    System.out.println(s);

If you will use this multiple times, make sure to store the char array and only calculate it once.

EDIT: Answer without for loops

char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
            's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '1','2','3','4','5','6','7','8','9','0',' '
};
String s2 = RandomStringUtils.random(4000, chars);


问:
Angular 1 directive component has different behavior in modal and out of the modal
I am really struggling with the issue with custom directive component. I have created TreeView dropdown component based on Angular ivh-treeview angular-ivh-treeview. Becasue ivh-treeview by default does not have recommended functionality and stylig I have extend it. But now I am facing an issue I haven't seen before and I would be really thankful for your help. The component works absolutelly OK in the modal. When you click on the checkboxes it reacts pretty fast and everything looks great. But when I use the same component on any other  page (not in the modal) it has really strange behavior. When you select any checkbox, it does not update immediatelly, you have to click somewhere else on the page, or close and open dropdown to see changes. I have no clue what is going on there and why the same component works in the modal. Maybe it's because modalInstance has different scope but I am done.

Here you can see and play with an example (Page 1 - modal, Page 2 - no modal): DEMO

This is just a fragment of the code I had to include to be able to link here DEMO on Plunkr

```<code><ivh-dropdown ivh-model="treeStructureFinal" selected-array="formData.casinos" is-disabled="inReadMode" placeholder="Select casinos"></ivh-dropdown>
</code>```

Thank you everyone!

答:
When this kind of thing happens I always think about $scope.$apply().

So I did a minor modification and now the directive works fine, just by adding a scope.$apply at the end of the click handler:

```<code>        $document.bind('click', function (event) {
            var isClickedElementChildOfPopup = element.find(
                    event.target).length > 0;
            if (!isClickedElementChildOfPopup
                && element[0].children[1].classList.contains("show")) {
                element[0].children[1].classList.toggle("show");
            }
            scope.$apply();
        });
</code>```

Take a look at it working:
https://plnkr.co/edit/s1UNCXNCZ46zXjte9lpZ?p=preview

Hope that helps.

Body:
I am really struggling with the issue with custom directive component. I have created TreeView dropdown component based on Angular ivh-treeview angular-ivh-treeview. Becasue ivh-treeview by default does not have recommended functionality and stylig I have extend it. But now I am facing an issue I haven't seen before and I would be really thankful for your help. The component works absolutelly OK in the modal. When you click on the checkboxes it reacts pretty fast and everything looks great. But when I use the same component on any other  page (not in the modal) it has really strange behavior. When you select any checkbox, it does not update immediatelly, you have to click somewhere else on the page, or close and open dropdown to see changes. I have no clue what is going on there and why the same component works in the modal. Maybe it's because modalInstance has different scope but I am done.

Here you can see and play with an example (Page 1 - modal, Page 2 - no modal): DEMO

This is just a fragment of the code I had to include to be able to link here DEMO on Plunkr

<ivh-dropdown ivh-model="treeStructureFinal" selected-array="formData.casinos" is-disabled="inReadMode" placeholder="Select casinos"></ivh-dropdown>

Thank you everyone!

Body:
When this kind of thing happens I always think about $scope.$apply().

So I did a minor modification and now the directive works fine, just by adding a scope.$apply at the end of the click handler:

        $document.bind('click', function (event) {
            var isClickedElementChildOfPopup = element.find(
                    event.target).length > 0;
            if (!isClickedElementChildOfPopup
                && element[0].children[1].classList.contains("show")) {
                element[0].children[1].classList.toggle("show");
            }
            scope.$apply();
        });

Take a look at it working:
https://plnkr.co/edit/s1UNCXNCZ46zXjte9lpZ?p=preview

Hope that helps.


问:
Finding MIN Invoice Number Per Customer and Removing All Rows That Don't Match
I have an Excel file that shows online sales data. There are multiple columns, as you would expect, two of which are Customer ID and Invoice Number.

My aim is to only keep rows where the Invoice Number is the first (or MIN) Invoice Number for each Customer.

On a duplicate tab, we want the same thing, but only for the second Invoice Number per Customer (i.e. the second purchase).

On a side note, there can be multiple rows for the same Customer ID and same Invoice Number because the rows are at Item level, so it may look like this:

```<code>Row 1: Customer ID = 24; Invoice Number = 1014; Item = Jelly Beans
Row 2: Customer ID = 24; Invoice Number = 1014; Item = Candy Bars
</code>```

So, that's okay. We just want to make sure any rows where the Customer's Invoice Number does not reflect their first purchase (or second purchase, in the second instance) is removed from the spreadsheet.

Is there a VBA (or even just functions) to achieve this? Even in steps: such as first highlighting those rows and then using another VBA to delete rows that are highlighted?

Again, in a nutshell I'm looking to only keep rows with the MIN(Invoice Number) per Customer ID.

答:
Use COUNTIFS to count the number of times the customer number has appeared. Use a reference that is anchored to the first cell and changes as you drag down.

Assuming your customer numbers are in column A, insert this into B1 and copy down:

```<code>=COUNTIFS($A$1:A1,A1)
</code>```

Filter on 1 or 2 accordingly.

Edit:

I didn't realise that you only wanted the first row. You can exploit the fact that MATCH will return the first result and check if it equals the row number:

```<code>=MATCH(A1,A:A,0)=ROW(A1)
</code>```

Note that you may need to offset MATCH slightly if your data doesn't start from row 1. For example, if your data starts in row 3, you will need to offset your MATCH result by 2:

```<code>=MATCH(A1,A:A,0)+2=ROW(A1)
</code>```

Now you can filter on the first column equalling 1 or 2 and the second column equalling TRUE.

Body:
I have an Excel file that shows online sales data. There are multiple columns, as you would expect, two of which are Customer ID and Invoice Number.

My aim is to only keep rows where the Invoice Number is the first (or MIN) Invoice Number for each Customer.

On a duplicate tab, we want the same thing, but only for the second Invoice Number per Customer (i.e. the second purchase).

On a side note, there can be multiple rows for the same Customer ID and same Invoice Number because the rows are at Item level, so it may look like this:

Row 1: Customer ID = 24; Invoice Number = 1014; Item = Jelly Beans
Row 2: Customer ID = 24; Invoice Number = 1014; Item = Candy Bars

So, that's okay. We just want to make sure any rows where the Customer's Invoice Number does not reflect their first purchase (or second purchase, in the second instance) is removed from the spreadsheet.

Is there a VBA (or even just functions) to achieve this? Even in steps: such as first highlighting those rows and then using another VBA to delete rows that are highlighted?

Again, in a nutshell I'm looking to only keep rows with the MIN(Invoice Number) per Customer ID.

Body:
Use COUNTIFS to count the number of times the customer number has appeared. Use a reference that is anchored to the first cell and changes as you drag down.

Assuming your customer numbers are in column A, insert this into B1 and copy down:

=COUNTIFS($A$1:A1,A1)

Filter on 1 or 2 accordingly.

Edit:

I didn't realise that you only wanted the first row. You can exploit the fact that MATCH will return the first result and check if it equals the row number:

=MATCH(A1,A:A,0)=ROW(A1)

Note that you may need to offset MATCH slightly if your data doesn't start from row 1. For example, if your data starts in row 3, you will need to offset your MATCH result by 2:

=MATCH(A1,A:A,0)+2=ROW(A1)

Now you can filter on the first column equalling 1 or 2 and the second column equalling TRUE.


问:
list of file owners in folder on linux
I have a folder with many files. The files have been created by many different users. I do not know about shell scripting.

I need to get the list of the username (only) of the owners of the files.

I may save the output of ls -l and then parse it using perl python etc...

But how can i do this using shell scripting?

答:
The two solutions so far are good, but have their limitations.

This should guarantee you properly and recursively search every file in a directory tree.

```<code>sudo find /some/dir/ -exec stat -c "%U" {} + | sort | uniq
</code>```

In other words, recursively search for files in /some/dir, and execute stat -c "%U" (print username) on the files, in as few invocations of stat as possible (-exec <cmd> {} + syntax), then of course sort the list of usernames, and in turn cull them to just the unique set of usernames.

To limit the search to just regular files, then add the -type f clause:

```<code>sudo find /some/dir/ -type f -exec stat -c "%U" {} + | sort | uniq
                     _______
</code>```

Title: list of file owners in folder on linux

Body:
The two solutions so far are good, but have their limitations.

This should guarantee you properly and recursively search every file in a directory tree.

sudo find /some/dir/ -exec stat -c "%U" {} + | sort | uniq

In other words, recursively search for files in /some/dir, and execute stat -c "%U" (print username) on the files, in as few invocations of stat as possible (-exec <cmd> {} + syntax), then of course sort the list of usernames, and in turn cull them to just the unique set of usernames.

To limit the search to just regular files, then add the -type f clause:

sudo find /some/dir/ -type f -exec stat -c "%U" {} + | sort | uniq
                     _______

ContentLicense: CC BY-SA 4.0


问:
How to load svm trained files by android NDK?
I have trained pictures using c++ opencv code but know i want to save those files somewhere in app and load those SVM trained files using the load method of SVM in opencv c++ code.First i thought i am going to save trained files in assets folder  and retrieve the files from assets but there is no absoulute path to assets folder in android apk file because the assets is zipped into apk file.
 The second choice is to save it in the android internal storage but there is also another drawback to this method i can't save large amount of data in the android internal storage.

What is the best method to save files  and load them using android ndk?

答: Internal storage.  You're right, assets is only an option for read-only files shipped with the apk.  You could use eternal storage, on old versions of android there was a significant difference, not so much these days, almost nobody has an external sd card.</p>


问:
Is it possible to pull all messages contained in an Azure Servicebus Topic into an app?
The only method I see to pull messages from a topic is SubscriptionClient.OnMessage(), which seems to only trigger if the topic receives a new message.

Queues have the QueueClient.Receive() method for this purpose, but topics don't seem to have this capability.

Am I missing something?

答: Looks like SubscriptionClient.OnMessage() actually does go through all existing messages on the topic.


问:
How to modify the HTTP::Response after it has been written to
I'm trying to write some tooling for Crystal (specifically Kemal) where I can see if the response content type is text/html and modify the response body thats has already been written to the HTTP::Response before it is sent to the client by injecting an HTML element into the existing html response body.

I've noticed that HTTP::Server::Response is write-only, but things like Gzip::Writer are able to modify the body.

How can I modify the HTTP::Server::Response html body before it is sent to the client?

答:
It's written in Crystal, so let's just take a look at the source on how others do this.

Taking the CompressHandler as an example, the basic idea is to replace the response's IO with something that allows the desired control:

```<code>context.response.output = Gzip::Writer.new(context.response.output, sync_close: true)
# ...
call_next(context)
</code>```

So how can we make use of that to modify the response that's being written?

A naive (and slow) example would be to just keep hold of the original output and provide a IO::Memory instead:

```<code>client = context.response.output
io = IO::Memory.new
context.response.output = io

call_next(context)

body = io.to_s
new_body = inject_html(body)
client.print new_body
</code>```

Of course that would only work when this handler comes before any handler that turns the response into non-plaintext (like the above CompressHandler).

A smarter solution would provide a custom IO implementation that just wraps the original IO, watching what's written to it and inject whatever it wants to inject at the right point. Examples of such wrapping IOs can be found at IO::Delimited, IO::Sized and IO::MultieWriter among others, the pattern is really common to prevent unnecessary allocations.

Body:
It's written in Crystal, so let's just take a look at the source on how others do this.

Taking the CompressHandler as an example, the basic idea is to replace the response's IO with something that allows the desired control:

context.response.output = Gzip::Writer.new(context.response.output, sync_close: true)
# ...
call_next(context)

So how can we make use of that to modify the response that's being written?

A naive (and slow) example would be to just keep hold of the original output and provide a IO::Memory instead:

client = context.response.output
io = IO::Memory.new
context.response.output = io

call_next(context)

body = io.to_s
new_body = inject_html(body)
client.print new_body

Of course that would only work when this handler comes before any handler that turns the response into non-plaintext (like the above CompressHandler).

A smarter solution would provide a custom IO implementation that just wraps the original IO, watching what's written to it and inject whatever it wants to inject at the right point. Examples of such wrapping IOs can be found at IO::Delimited, IO::Sized and IO::MultieWriter among others, the pattern is really common to prevent unnecessary allocations.


问:
Android: How to rotate a bitmap on a center point
I've been looking for over a day for a solution to this problem but nothing helps, even the answers here. Documentation doesn't explain anything too.

I am simply trying to get a rotation in the direction of another object. The problem is that the bitmap is not rotated around a fixed point, but rather around the bitmaps (0,0).

Here is the code I am having troubles with:

```<code>  Matrix mtx = new Matrix();
  mtx.reset();
  mtx.preTranslate(-centerX, -centerY);
  mtx.setRotate((float)direction, -centerX, -centerY);
  mtx.postTranslate(pivotX, pivotY);
  Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, spriteWidth, spriteHeight, mtx, true);
  this.bitmap = rotatedBMP;
</code>```

The weird part is, it doesn't matter how I change the values within pre/postTranslate() and the float arguments in setRotation(). Can someone please help and push me in the right direction? :)

答:
You can also rotate the ImageView using a RotateAnimation:

```<code>RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);

imageView.startAnimation(rotateAnimation);
</code>```

Body:
I've been looking for over a day for a solution to this problem but nothing helps, even the answers here. Documentation doesn't explain anything too.

I am simply trying to get a rotation in the direction of another object. The problem is that the bitmap is not rotated around a fixed point, but rather around the bitmaps (0,0).

Here is the code I am having troubles with:

  Matrix mtx = new Matrix();
  mtx.reset();
  mtx.preTranslate(-centerX, -centerY);
  mtx.setRotate((float)direction, -centerX, -centerY);
  mtx.postTranslate(pivotX, pivotY);
  Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, spriteWidth, spriteHeight, mtx, true);
  this.bitmap = rotatedBMP;

The weird part is, it doesn't matter how I change the values within pre/postTranslate() and the float arguments in setRotation(). Can someone please help and push me in the right direction? :)

Body:
You can also rotate the ImageView using a RotateAnimation:

RotateAnimation rotateAnimation = new RotateAnimation(from, to,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setDuration(ANIMATION_DURATION);
rotateAnimation.setFillAfter(true);

imageView.startAnimation(rotateAnimation);


问:
Regex - Find Name With No Middle Initial
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

答:
You don't need a regular expression.  How about this?

```<code>where name like '% %' and name not like '% % %'
</code>```

This just looks for two spaces in the name.

If you really wanted just middle initials, then:

```<code>where name not like '% _ %' and name not like '% _. %'
</code>```

Body:
You don't need a regular expression.  How about this?

where name like '% %' and name not like '% % %'

This just looks for two spaces in the name.

If you really wanted just middle initials, then:

where name not like '% _ %' and name not like '% _. %'


问:
How to stub a function IN a Helper during test
Take a look at this helper function:

```<code>def show_welcome_banner?
  (controller_name == 'competition' && action_name == 'index') ||
  (controller_name == 'submissions' && action_name == 'show')
end
</code>```

It expects the controller_name and action_name functions to be defined.

I tried to use this in my RSpec matcher:

```<code>describe PageHelper do
  it "should know when the welcome banner is to be shown" do
    helper.stub!(:controller_name).and_return('index')
    show_welcome_banner?.should == false
  end
end
</code>```

But this won't really work.

How could I stub the functions INSIDE the helper? Perhaps using instance_eval?
Thanks!

EDIT,
tried to use

```<code>controller.stub!(:controller_name).and_return('index')
</code>```

but got

```<code>  1) PageHelper should know when the welcome banner is to be shown
     Failure/Error: show_welcome_banner?.should == false
     NameError:
       undefined local variable or method `controller_name' for #<RSpec::Core::ExampleGroup::Nested_1:0x1059a10b8>
     # ./app/helpers/page_helper.rb:16:in `show_welcome_banner?'
     # ./spec/helpers/page_helper_spec.rb:7
</code>```

The helper is put in spec/helper/page_helper_spec.rb..

答:
rspec-rails 3.5</p>

```<code>allow(helper).to receive(:controller_name) { 'submissions' }
</code>```

Body:
Take a look at this helper function:

def show_welcome_banner?
  (controller_name == 'competition' && action_name == 'index') ||
  (controller_name == 'submissions' && action_name == 'show')
end

It expects the controller_name and action_name functions to be defined.

I tried to use this in my RSpec matcher:

describe PageHelper do
  it "should know when the welcome banner is to be shown" do
    helper.stub!(:controller_name).and_return('index')
    show_welcome_banner?.should == false
  end
end

But this won't really work.

How could I stub the functions INSIDE the helper? Perhaps using instance_eval?
Thanks!

EDIT,
tried to use

controller.stub!(:controller_name).and_return('index')

but got

  1) PageHelper should know when the welcome banner is to be shown
     Failure/Error: show_welcome_banner?.should == false
     NameError:
       undefined local variable or method `controller_name' for #<RSpec::Core::ExampleGroup::Nested_1:0x1059a10b8>
     # ./app/helpers/page_helper.rb:16:in `show_welcome_banner?'
     # ./spec/helpers/page_helper_spec.rb:7

The helper is put in spec/helper/page_helper_spec.rb..

Body:
rspec-rails 3.5

allow(helper).to receive(:controller_name) { 'submissions' }


问:
How to use String in switch?
IDE throws an NullPointerException when I'm trying to do this. I want to have only 2 genders to choose

```<code>public  String typeOfGender
    {
        switch (typeOfGender)
        {
            case "Male":
                    typeOfGender = "Male";
                    break;
            case "Female":
                    typeOfGender = "Female";
                    break;
            default:
                    System.out.println(" Unrecognized gender." );
        }
    }
</code>```

答:
You have not initialized typeOfGender. It is null. That is why. Try

```<code>typeOfGender="Male";
</code>```

By the way your code does not make sense. If typeOfGender equals "Male", you assign "Male" to it??

Title: How to use String in switch?

Body:
IDE throws an NullPointerException when I'm trying to do this. I want to have only 2 genders to choose

public  String typeOfGender
    {
        switch (typeOfGender)
        {
            case "Male":
                    typeOfGender = "Male";
                    break;
            case "Female":
                    typeOfGender = "Female";
                    break;
            default:
                    System.out.println(" Unrecognized gender." );
        }
    }

Body:
You have not initialized typeOfGender. It is null. That is why. Try

typeOfGender="Male";

By the way your code does not make sense. If typeOfGender equals "Male", you assign "Male" to it??


问:
How can I "migrate to the Java 2 security model instead"?
I use a JAVA applet which upload files from the browser with drag and drop. I know that is a signed Applet. Yesterday I uploaded some files, but today I give an error in the console:

```<code>Netscape security model is no longer supported.
Please migrate to the Java 2 security model instead
</code>```

I never upgrade JRE an I'm almost sure that the java version was always 1.6.0_22.

Is it possible ?

I'm not a Java programmer but I must edit the code to let the applet work. This applet simply access to the filesystem to create a folder, resize some image in that folder and upload the resized images and communicate with JS to send some messages to the web page.

I've found only this code related to security:

```<code>import netscape.security.PrivilegeManager;
import java.text.DateFormat;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;

public void init() {
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalJavaPermissions");
        ...
    } catch (JSException e1) {
        ...
    }
}
</code>```

And I found in a readme file how to sign the compiled applet:

```<code>keytool -export -alias signFiles -file myCert.crt -storepass mypass
javac -cp C:\Programmi\Java\jdk1.6.0_18\jre\lib\plugin.jar; .\MyApplet.java -Xlint:unchecked
jar -cvf MyApplet.jar test
jarsigner MyApplet.jar signFiles
</code>```

Can you give some feedback to resources that can help me to understand how to migrate to "Java 2 security model" ?

Is there a simple method to avoid this error without edit and recompile the source code (for example to force the old security model) ?

Any idea that can help me to approach the problem is really appreciated

答:
netscape.security.PrivilegeManager.enablePrivilege("UniversalJavaPermissions");

Just remove that and follow the instructions for signing the applet.

Body:
I use a JAVA applet which upload files from the browser with drag and drop. I know that is a signed Applet. Yesterday I uploaded some files, but today I give an error in the console:

Netscape security model is no longer supported.
Please migrate to the Java 2 security model instead

I never upgrade JRE an I'm almost sure that the java version was always 1.6.0_22.

Is it possible ?

I'm not a Java programmer but I must edit the code to let the applet work. This applet simply access to the filesystem to create a folder, resize some image in that folder and upload the resized images and communicate with JS to send some messages to the web page.

I've found only this code related to security:

import netscape.security.PrivilegeManager;
import java.text.DateFormat;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.security.PrivilegedActionException;

public void init() {
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalJavaPermissions");
        ...
    } catch (JSException e1) {
        ...
    }
}

And I found in a readme file how to sign the compiled applet:

keytool -export -alias signFiles -file myCert.crt -storepass mypass
javac -cp C:\Programmi\Java\jdk1.6.0_18\jre\lib\plugin.jar; .\MyApplet.java -Xlint:unchecked
jar -cvf MyApplet.jar test
jarsigner MyApplet.jar signFiles

Can you give some feedback to resources that can help me to understand how to migrate to "Java 2 security model" ?

Is there a simple method to avoid this error without edit and recompile the source code (for example to force the old security model) ?

Any idea that can help me to approach the problem is really appreciated


问:
Changing Stripe param keys for mass assignment in Rails
I'm integrating Stripe into a Rails app. Right now Stripe Checkout returns a params hash with key-value pairs like:

```<code>"stripeShippingAddressZip"=>"80205"
</code>```

and

```<code>"stripeShippingAddressState"=>"CO"
</code>```

I also have a method called order_params which calls params.permit to prevent mass assignment vulnerabilities.

I'd like to do the following:

current_user.orders.build(order_params)

Essentially mass assignment.

However, my orders model has attributes like shipping_zip rather than stripeShippingAddressZip.

How can I use the params hash and still do mass assignment given that the hash keys don't match the attributes of the model?

Is there are "Rails way" of doing this?

答:
There are multiple ways you can do this, but I like to do the mapping like so:

```<code>def order_params
  {
    shipping_zip: params[:stripeShippingAddressZip],
    # more here
  }
end
</code>```

After this you can just do:

```<code>Orders.create(order_params)
</code>```

I hope this helps!

Body:
I'm integrating Stripe into a Rails app. Right now Stripe Checkout returns a params hash with key-value pairs like:

"stripeShippingAddressZip"=>"80205"

and

"stripeShippingAddressState"=>"CO"

I also have a method called order_params which calls params.permit to prevent mass assignment vulnerabilities.

I'd like to do the following:

current_user.orders.build(order_params)

Essentially mass assignment.

However, my orders model has attributes like shipping_zip rather than stripeShippingAddressZip.

How can I use the params hash and still do mass assignment given that the hash keys don't match the attributes of the model?

Is there are "Rails way" of doing this?

Body:
There are multiple ways you can do this, but I like to do the mapping like so:

def order_params
  {
    shipping_zip: params[:stripeShippingAddressZip],
    # more here
  }
end

After this you can just do:

Orders.create(order_params)

I hope this helps!


问:
How to populate AndroidManifest meta-data value programatically?
I understand the AndroidManifest.xml is prepared at compile time and not runtime, is there any other way to populate metadata in the manifest without relying on hard coded strings? Maybe populating it somehow at compile time?

I currently have the following on my AndroidManifest.xml

```<code><application
    android:allowBackup="true"
    android:icon="@drawable/dt_icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="DataPath"
        android:value=""
     /> ...
</code>```

I don't want to hard code the value and instead populate it somehow with the results from:

Environment.getExternalStorageDirectory()

Another application will later retrieve the value of DataPath by utilizing the ApplicationInfo's metaData property.

答:
I believe i read somewhere that its possible to assign the value at compile time but still not hard coding it

The best you can do is to assign a value from gradle via manifest placeholders.

Example:

```<code>android {
    defaultConfig {
        manifestPlaceholders = [hostName:"www.example.com"]
    }
    ...
}

<intent-filter ... >
    <data android:scheme="http" android:host="${hostName}" ... />
    ...
</intent-filter>
</code>```

Body:
I understand the AndroidManifest.xml is prepared at compile time and not runtime, is there any other way to populate metadata in the manifest without relying on hard coded strings? Maybe populating it somehow at compile time?

I currently have the following on my AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@drawable/dt_icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">

    <meta-data
        android:name="DataPath"
        android:value=""
     /> ...

I don't want to hard code the value and instead populate it somehow with the results from:

Environment.getExternalStorageDirectory()

Another application will later retrieve the value of DataPath by utilizing the ApplicationInfo's metaData property.

Body:
I believe i read somewhere that its possible to assign the value at compile time but still not hard coding it

The best you can do is to assign a value from gradle via manifest placeholders.

Example:

android {
    defaultConfig {
        manifestPlaceholders = [hostName:"www.example.com"]
    }
    ...
}

<intent-filter ... >
    <data android:scheme="http" android:host="${hostName}" ... />
    ...
</intent-filter>


答:
try this

```<code>\w{2,} \w{2,}
</code>```

two words, space separated, at least two chars each.

Title: Regex - Find Name With No Middle Initial

Body:
I'm doing a query on an SQL database and need to write a regular expression to find names with no middle initial.

For example.

Michael J. Fox - Should fail

Michael J Fox - Should fail

Michael Fox - Should pass

Full names in the database are stored in a single string for reference.

Body:
try this

\w{2,} \w{2,}

two words, space separated, at least two chars each.


问:
Is it possible to programmatically uninstall a package in Android
Can a package uninstall itself?  Can a package uninstall another package if they share the same userId and signature?</p>

答:
Third Party app cannot Uninstall App Silently!

Either you need to become System App to get DELETE_PACKAGES Permission else you need to show Uninstall Popup  (User Confirmation)

Alternatively, you can take Accessibility permission and then by showing an Accessibility Overlay you can tell your service to click on Uninstall button! But that will be privacy violation.


问:
If "NULL" then use 0 in shell scripting
I am using a shell script to query a hive table

```<code>last_val="`hive -e "select max(id) from ${hivedatabase}.${table}"`"

echo var1="$last_val"
</code>```

When the last_val = "NULL" then I want the last_val to be zero

I have tried like below but still I am getting Null

```<code>function value
{
   if [ "$last_val" = "NULL" ];then
        echo "0"
   elif [ "$last_val" != "NULL" ];then
        echo "$last_val"
   fi
}

echo var2="$(value)"
</code>```

I want to use this value in for incremental imports using sqoop like

```<code>select * from testing.1234abc check column id > value
</code>```

How can I achieve that in shell scripting

答:
I'm using this approach, try it:</p>

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

hivedatabase=mydb
table=mytable
default_value="ZERO"

last_val=$(hive -e "set hive.cli.print.header=false; select max(id) from ${hivedatabase}.${table};")

if [[ "$last_val" == "NULL" ]] ; then
  last_val="$default_value"
fi

echo "$last_val"
</code>```

Title: If "NULL" then use 0 in shell scripting

Body:
I am using a shell script to query a hive table

last_val="`hive -e "select max(id) from ${hivedatabase}.${table}"`"

echo var1="$last_val"

When the last_val = "NULL" then I want the last_val to be zero

I have tried like below but still I am getting Null

function value
{
   if [ "$last_val" = "NULL" ];then
        echo "0"
   elif [ "$last_val" != "NULL" ];then
        echo "$last_val"
   fi
}

echo var2="$(value)"

I want to use this value in for incremental imports using sqoop like

select * from testing.1234abc check column id > value

How can I achieve that in shell scripting

Body:
I'm using this approach, try it:

#!/bin/bash

hivedatabase=mydb
table=mytable
default_value="ZERO"

last_val=$(hive -e "set hive.cli.print.header=false; select max(id) from ${hivedatabase}.${table};")

if [[ "$last_val" == "NULL" ]] ; then
  last_val="$default_value"
fi

echo "$last_val"


问:
bash script grep the etc file for user information
I am trying to write a script in bash to read in arguments (usernames) and then return information about that username by searching the /etc/passwd file. I am not the root on the server that I am scripting this on, but I don't need to be. Here is the code that I have so far, but I dont think I am using the grep command right. </p>

```<code>#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
        UNAME=$1 #set arg to var UNAME
        grep UNAME=$(grep $/etc/passwd)
        if [ $UNAME == /etc/passwd ]; then #if UNAME exists then display info below
                echo "-------------------------------------------"
                echo "Username:       $(grep UNAME/etc/passwd/ $f1) "
                echo "User ID (UID):  $(grep UNAME/etc/passwd/) "
                echo "Group ID (GID): $(grep UNAME/etc/passwd/) "
                echo "User info:      $(grep UNAME/etc/passwd/) "
                echo "Home directory: $(grep UNAME/etc/passwd/) "
                echo "Command shell:  $(grep UNAME/etc/passwd/) "
                echo "-------------------------------------------"
        else #if UNAME is nonexistant then display this error message
                echo "-------------------------------------------"
                echo ""$UNAME" does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi
</code>```

答:
You're doing too much.  grep is the wrong tool for the type of parsing you are trying to do.  The solution given here is pretty sloppy since it reads the passwd file once for each user you are querying instead of reporting everything in one pass, but it's not unreasonable:</p>

```<code>#!/bin/sh

for UNAME; do
        while IFS=: read login passwd uid gid name home shell; do
                if test "$login" = "$UNAME"; then
                        echo "-------------------------------------------"
                        echo "Username:       $login"
                        echo "User ID (UID):  $uid"
                        echo "Group ID (GID): $gid"
                        echo "User info:      $name"
                        echo "Home directory: $home"
                        echo "Command shell:  $shell"
                        echo "-------------------------------------------"
                        continue 2
                fi
        done < /etc/passwd
        echo "No entry for user $UNAME" >&2
done
</code>```

Body:
I am trying to write a script in bash to read in arguments (usernames) and then return information about that username by searching the /etc/passwd file. I am not the root on the server that I am scripting this on, but I don't need to be. Here is the code that I have so far, but I dont think I am using the grep command right.

#!/bin/bash
if [ $# -eq 1 ]; then #if num of args =1; then continue on
        UNAME=$1 #set arg to var UNAME
        grep UNAME=$(grep $/etc/passwd)
        if [ $UNAME == /etc/passwd ]; then #if UNAME exists then display info below
                echo "-------------------------------------------"
                echo "Username:       $(grep UNAME/etc/passwd/ $f1) "
                echo "User ID (UID):  $(grep UNAME/etc/passwd/) "
                echo "Group ID (GID): $(grep UNAME/etc/passwd/) "
                echo "User info:      $(grep UNAME/etc/passwd/) "
                echo "Home directory: $(grep UNAME/etc/passwd/) "
                echo "Command shell:  $(grep UNAME/etc/passwd/) "
                echo "-------------------------------------------"
        else #if UNAME is nonexistant then display this error message
                echo "-------------------------------------------"
                echo ""$UNAME" does not exist."
                echo "-------------------------------------------"
        fi
fi
if [ $# -eq 0 ]; then #if num of args =0; then display this
        echo "Not enough arguments provided."
        echo "USAGE: $0 <user_name> [user_name] ..."
        exit 1
fi

Body:
You're doing too much.  grep is the wrong tool for the type of parsing you are trying to do.  The solution given here is pretty sloppy since it reads the passwd file once for each user you are querying instead of reporting everything in one pass, but it's not unreasonable:

#!/bin/sh

for UNAME; do
        while IFS=: read login passwd uid gid name home shell; do
                if test "$login" = "$UNAME"; then
                        echo "-------------------------------------------"
                        echo "Username:       $login"
                        echo "User ID (UID):  $uid"
                        echo "Group ID (GID): $gid"
                        echo "User info:      $name"
                        echo "Home directory: $home"
                        echo "Command shell:  $shell"
                        echo "-------------------------------------------"
                        continue 2
                fi
        done < /etc/passwd
        echo "No entry for user $UNAME" >&2
done


问:
Permutation predicate in Prolog
I have written the following in Prolog (I am using version 7.4.0-rc1), trying to define a predicate insertPermutation/2 which is true if and only if both arguments are lists, one a permutation of the other.

```<code>delete(X,[X|T],T). % Base case, element equals head.
delete(X,[A|B],[A|C]) :- delete(X,B,C). % And/or repeat for the tail.

insert(X,Y,Z) :- delete(X,Z,Y). % Inserting is deletion in reverse.

insertPermutation([],[]). % Base case.
insertPermutation([H|T],P) :- insertPermutation(Q,T), insert(H,Q,P). % P permutation of T, H inserted.
</code>```

I have already been made aware that delete is not a good name for the above helper predicate. We are required to write these predicates, and we cannot use the built-in predicates. This is why I wrote the above code in this way, and I chose the name I did (because I first wrote it to delete an element). It is true if and only if the third argument is a list, equal to the list in the second argument with the first instance of the first argument removed.

The insertPermutation predicate recursively tests if P equals a permutation of the tail of the first list, with the head added in any position in the permutation. This way it works to the base case of both being empty lists.

However, the permutation predicate does not behave the way I want it to. For instance, to the query

```<code>?- insertPermutation([1,2,2],[1,2,3]).
</code>```

Prolog does not return false, but freezes. To the query

```<code>?- insertPermutation(X,[a,b,c]).
</code>```

Prolog responds with

```<code>X = [a, b, c] ;
X = [b, a, c] ;
X = [c, a, b] ;
X = [a, c, b] ;
X = [b, c, a] ;
X = [c, b, a] ;
</code>```

after which it freezes again. I see these problems are related, but not how. Can someone point out what case I am missing?

Edit: Two things, this is homework, and I need to solve this problem using an insert predicate. I wrote this one.

答:
The answer is to change the last line

```<code>% P permutation of T, H inserted.
insertPermutation([H|T],P) :-
    insertPermutation(Q,T),
    insert(H,Q,P).

% P permutation of T, H inserted.
insertPermutation(P,[H|T]) :-
    insertPermutation(Q,T),
    insert(H,Q,P).
</code>```

The use cases only needed to check if the first element is a permutation of the latter, not the other way around (or vice versa). Anti-climatic, but the answer to my problem.

Title: Permutation predicate in Prolog

Body:
I have written the following in Prolog (I am using version 7.4.0-rc1), trying to define a predicate insertPermutation/2 which is true if and only if both arguments are lists, one a permutation of the other.

delete(X,[X|T],T). % Base case, element equals head.
delete(X,[A|B],[A|C]) :- delete(X,B,C). % And/or repeat for the tail.

insert(X,Y,Z) :- delete(X,Z,Y). % Inserting is deletion in reverse.

insertPermutation([],[]). % Base case.
insertPermutation([H|T],P) :- insertPermutation(Q,T), insert(H,Q,P). % P permutation of T, H inserted.

I have already been made aware that delete is not a good name for the above helper predicate. We are required to write these predicates, and we cannot use the built-in predicates. This is why I wrote the above code in this way, and I chose the name I did (because I first wrote it to delete an element). It is true if and only if the third argument is a list, equal to the list in the second argument with the first instance of the first argument removed.

The insertPermutation predicate recursively tests if P equals a permutation of the tail of the first list, with the head added in any position in the permutation. This way it works to the base case of both being empty lists.

However, the permutation predicate does not behave the way I want it to. For instance, to the query

?- insertPermutation([1,2,2],[1,2,3]).

Prolog does not return false, but freezes. To the query

?- insertPermutation(X,[a,b,c]).

Prolog responds with

X = [a, b, c] ;
X = [b, a, c] ;
X = [c, a, b] ;
X = [a, c, b] ;
X = [b, c, a] ;
X = [c, b, a] ;

after which it freezes again. I see these problems are related, but not how. Can someone point out what case I am missing?

Edit: Two things, this is homework, and I need to solve this problem using an insert predicate. I wrote this one.

Body:
The answer is to change the last line

% P permutation of T, H inserted.
insertPermutation([H|T],P) :-
    insertPermutation(Q,T),
    insert(H,Q,P).

% P permutation of T, H inserted.
insertPermutation(P,[H|T]) :-
    insertPermutation(Q,T),
    insert(H,Q,P).

The use cases only needed to check if the first element is a permutation of the latter, not the other way around (or vice versa). Anti-climatic, but the answer to my problem.


问:
Does ASP.NET Core support SQL Server CE now?
If supported, which package should I install in order to use SQL Server CE?
Thanks.

Package Microsoft.SqlServer.Compact 4.0.8876.1 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0).

Package EntityFrameworkCore.SqlServerCompact40 1.0.0.3 is not compatible with netcoreapp1.0 (.NETCoreApp,Version=v1.0).

答:
EF Core will handle it.

Use the SQLite / SQL Server Compact Toolbox extension for Visual Studio 2017 by ErikEJ.

"EF Core, released simultaneously with .NET Core, is a lightweight and extensible version of Entity Framework that works on both .NET Core and .NET Framework. It has support for Microsoft SQL Server, SQLite, PostgreSQL, MySQL, Microsoft SQL Server Compact Edition, and IBM DB2 with more to come, such as Oracle." (https://blogs.msdn.microsoft.com/dotnet/2016/11/09/net-core-data-access)


答:
The NullPointerExeption is caused because your string is null.

However, for future reference, here's an example of as switch-case with a string:

```<code>    String string = "foo";
    switch (string) {
        case "foo":
            System.out.println("foo");
            break;
        case "bar":
            System.out.println("bar");
            break;
        default:
            System.out.println("Mushroom Stew!");
            break;
    }
</code>```

Title: How to use String in switch?

Body:
The NullPointerExeption is caused because your string is null.

However, for future reference, here's an example of as switch-case with a string:

    String string = "foo";
    switch (string) {
        case "foo":
            System.out.println("foo");
            break;
        case "bar":
            System.out.println("bar");
            break;
        default:
            System.out.println("Mushroom Stew!");
            break;
    }


问:
What is the proper syntax to combine text with HTML?
I have a C# foreach loop with the following:

```<code>lblCheckedNodes.Text += node.Text + "&#x25BA< br />";
</code>```

That displays like this: myCheckedNodeText►
 .  Which shows the line break characters instead of actually doing the line break, but if I do:

```<code>lblCheckedNodes.Text += node.Text + "<br />";
</code>```

the line return works, but i can't seem to get both working.

答:
I think you are just missing a semicolon.
Try this</p>

```<code>lblCheckedNodes.Text += node.Text + "►<br />";
</code>```

Body:
I have a C# foreach loop with the following:

lblCheckedNodes.Text += node.Text + "&#x25BA
";

That displays like this: myCheckedNodeText►
 .  Which shows the line break characters instead of actually doing the line break, but if I do:

lblCheckedNodes.Text += node.Text + "
";

the line return works, but i can't seem to get both working.

Body:
I think you are just missing a semicolon.
Try this

lblCheckedNodes.Text += node.Text + "&#x25BA;<br />";


答:
I use them often with no problems, example below. The only reason yours would throw that is if you are passing null to it.</p>

```<code>private string GetMailBody(string regionCode)
{
    switch(regionCode)
    {
        case "qc":
            //Do some stuff
            break;

        default:
            //If not specified, we assume US, so we do that.
            break;
    }

    return "String we should have edited above";
}
</code>```

Title: How to use String in switch?

Body:
IDE throws an NullPointerException when I'm trying to do this. I want to have only 2 genders to choose

public  String typeOfGender
    {
        switch (typeOfGender)
        {
            case "Male":
                    typeOfGender = "Male";
                    break;
            case "Female":
                    typeOfGender = "Female";
                    break;
            default:
                    System.out.println(" Unrecognized gender." );
        }
    }

Body:
I use them often with no problems, example below. The only reason yours would throw that is if you are passing null to it.

private string GetMailBody(string regionCode)
{
    switch(regionCode)
    {
        case "qc":
            //Do some stuff
            break;

        default:
            //If not specified, we assume US, so we do that.
            break;
    }

    return "String we should have edited above";
}


问:
Oracle query for selecting sampling of number values from a table
I have a data field in my Oracle DB Table whose datatype is NUMBER. I have tried a query below using order by.

```<code>SELECT Value
  FROM Table
 ORDER BY value;
</code>```

I am getting the result as

```<code>Value |
------|
1     |
1     |
2     |
2     |
3     |
3     |
4     |
4     |
5     |
5     |
6     |
6     |
</code>```

Instead I want a result as

```<code>Value |
------|
1     |
2     |
3     |
4     |
5     |
6     |
1     |
2     |
3     |
4     |
5     |
6     |
</code>```

答:
1 Value | ------| 1 | 1 | 2 | 2 | 3 | 3 | 4 | 4 | 5 | 5 | 6 | 6 |

```<code>SELECT ROW_NUMBER() OVER (PARTITION BY VALUE ORDER BY VALUE) AS RN, TABLE  .* FROM TABLE
</code>```

2 Value | ------| 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 |

```<code>SELECT ROWNUM,TABLE.* FROM TABLE
</code>```

Body:
I have a data field in my Oracle DB Table whose datatype is NUMBER. I have tried a query below using order by.

SELECT Value
  FROM Table
 ORDER BY value;

I am getting the result as

Value |
------|
1     |
1     |
2     |
2     |
3     |
3     |
4     |
4     |
5     |
5     |
6     |
6     |

Instead I want a result as

Value |
------|
1     |
2     |
3     |
4     |
5     |
6     |
1     |
2     |
3     |
4     |
5     |
6     |

Body:
1 Value | ------| 1 | 1 | 2 | 2 | 3 | 3 | 4 | 4 | 5 | 5 | 6 | 6 |

SELECT ROW_NUMBER() OVER (PARTITION BY VALUE ORDER BY VALUE) AS RN, TABLE  .* FROM TABLE

2 Value | ------| 1 | 2 | 3 | 4 | 5 | 6 | 1 | 2 | 3 | 4 | 5 | 6 |

SELECT ROWNUM,TABLE.* FROM TABLE