问:
Selecting an option element from a dropdown by its text value
Given an HTML form element like:

```<code><select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>
</code>```

I know I can select the first option with

```<code>document.getElementById("mydropdown").value='foo'
</code>```

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

答:
If you want to get an option by its innertext and not by the value you can do this:</p>

```<code>function go(){
    var dropdown = document.getElementById('mydropdown');
    var textSelected = 'Spam';

    for(var i=0, max=dropdown.children.length; i<max; i++) {
        if(textSelected == dropdown.children[i].innerHTML){
            alert(textSelected);
            return;
        }
    }
}
</code>```

Body:
Given an HTML form element like:

<select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>

I know I can select the first option with

document.getElementById("mydropdown").value='foo'

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

Body:
If you want to get an option by its innertext and not by the value you can do this:

function go(){
    var dropdown = document.getElementById('mydropdown');
    var textSelected = 'Spam';

    for(var i=0, max=dropdown.children.length; i<max; i++) {
        if(textSelected == dropdown.children[i].innerHTML){
            alert(textSelected);
            return;
        }
    }
}


来源: stackexchange

问:
.autocomplete is not a function Error
below is my My Code

```<code><link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</code>```

And my Html code is

```<code><div class="ui-widget">
<input name="searcharea" class="selectarea" id="searcharea" type="text" value="" placeholder="Area">
</div>
</code>```

And my Function is

```<code><script>
$(function(){
    $( "#searcharea" ).autocomplete({
        source: "suggestions.php"
    });
    $( "#searchcat" ).autocomplete({
        source: "suggestions1.php"
    });
});
</script>
</code>```

I have included this page into a seperate file with search code of my website and I have embeded it on various pages, On my index page, it is suggesting me values from source files, but on other pages it is giving me typerror on line

```<code>$( "#searcharea" ).autocomplete({
</code>```

My website link is:
http://www.jodhpuryp.in/

This is source of my autosuggestion box
http://api.jqueryui.com/autocomplete/

Can anybody tell me, why I am getting this error on other pages of my website while its working on index page.Any help is appreciated.Thanks

答:
This is embarrassing but it held me up for a while so I figured I would post it here.

I did not have jQuery UI installed, only classic jQuery, which does not include autocomplete (apparently).  Adding the following tags enabled autocomplete via jQuery UI.

```<code><link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
</code>```

and

```<code><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</code>```

Of note, the HTML value autocomplete="off" for either the form or form block will prevent the brower from performing the method .autocomplete(), but will not block the jQuery UI function.

ContentLicense: CC BY-SA 3.0

Title: .autocomplete is not a function Error

Body:
below is my My Code

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

And my Html code is

<input name="searcharea" class="selectarea" id="searcharea" type="text" value="" placeholder="Area">

And my Function is

I have included this page into a seperate file with search code of my website and I have embeded it on various pages, On my index page, it is suggesting me values from source files, but on other pages it is giving me typerror on line

$( "#searcharea" ).autocomplete({

My website link is:
http://www.jodhpuryp.in/

This is source of my autosuggestion box
http://api.jqueryui.com/autocomplete/

Can anybody tell me, why I am getting this error on other pages of my website while its working on index page.Any help is appreciated.Thanks

Body:
This is embarrassing but it held me up for a while so I figured I would post it here.

I did not have jQuery UI installed, only classic jQuery, which does not include autocomplete (apparently).  Adding the following tags enabled autocomplete via jQuery UI.

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

and

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

Of note, the HTML value autocomplete="off" for either the form or form block will prevent the brower from performing the method .autocomplete(), but will not block the jQuery UI function.

ContentLicense: CC BY-SA 4.0


问:
Retrieve Service and use it in some arbitrary class in net core
There are plenty of examples how to set controllers to use services etc. But what about plain old class? Lets use some simple configuration service

JSON

```<code>{
  ....,
  "AppSettings": {
    "SchemaFile": "some file name.xml"
  }
}
</code>```

POCO

public class AppSettings
{
    public string SchemaFile { get;set; }
}
```

<p>In startup.cs</p>

<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
    IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);
  . . . .
}
</code>```

This is the point where all examples move directly to the controller. But we are going to have plenty of code outside controller. What I need is to access this service using provider.GetService(typeof(T)) or provider.GetRequiredService(typeof(T)), from, lets say a static class

internal static MyClass
{
    internal static void DosomeThing()
    {
        // acquire my service
        // use it to retrieve some value
        // continue with my logic

    }
}
```

Thanks

答:
You should pass AppSettings as parameter from the caller method

```<code>public class HomeController : Controller
{
   public HomeController(AppSettings settings)
   {
      this.Settings = settings;
   }

   private AppSettings Settings { get; }

   public IActionResult Index()
   {
      MyClass.DosomeThing(this.Settings);
   }
}

internal static MyClass
{
    internal static void DosomeThing(AppSettings settings)
    {
        // acquire my service
        // use it to retrieve some value
        // continue with my logic

    }
}
</code>```

Body:
There are plenty of examples how to set controllers to use services etc. But what about plain old class? Lets use some simple configuration service

JSON

{
  ....,
  "AppSettings": {
    "SchemaFile": "some file name.xml"
  }
}

POCO

public class AppSettings
{
    public string SchemaFile { get;set; }
}

In startup.cs

public void ConfigureServices(IServiceCollection services)
{
    IConfigurationSection appSettingsSection = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);
  . . . .
}

This is the point where all examples move directly to the controller. But we are going to have plenty of code outside controller. What I need is to access this service using provider.GetService(typeof(T)) or provider.GetRequiredService(typeof(T)), from, lets say a static class

internal static MyClass
{
    internal static void DosomeThing()
    {
        // acquire my service
        // use it to retrieve some value
        // continue with my logic

    }
}

Thanks

Body:
You should pass AppSettings as parameter from the caller method

public class HomeController : Controller
{
   public HomeController(AppSettings settings)
   {
      this.Settings = settings;
   }

   private AppSettings Settings { get; }

   public IActionResult Index()
   {
      MyClass.DosomeThing(this.Settings);
   }
}

internal static MyClass
{
    internal static void DosomeThing(AppSettings settings)
    {
        // acquire my service
        // use it to retrieve some value
        // continue with my logic

    }
}


问:
How to redirect using htaccess and regex the middle part of URLs leaving the dynamic end as is?
I need to redirect a lot of URLs by changing just some part that is in the middle or at the end of the URL. If that part is in the middle, the end must stay the same.

I need to accomplish this by using htaccess and regex.

I found a lot of examples online, but most of the are one on one redirection, and not covering enough dynamic websites. Also I haven't found answer to this in other questions here.

I have URL:

www.domain.com/something (alone)  OR URLS like

www.domain.com/something-aaa-bbb-ccc OR only

www.domain.com/something-aaa

How to make it:

www.domain.com/somethingELSE but ALSO:

www.domain.com/somethingELSE-aaa-bbb-ccc

(KEEP aaa-bbb or whatever goes at the end the same)

To make this more human readable, let's say these are shops with a lot of locations:

www.domain.com/my-shop - Without anything else after OR:

www.domain.com/my-shop-belgrade  ... or

www.domain.com/my-shop-new-york ... or  ... shop-wherever-wherever-wherever

TO BE:

www.domain.com/my-office - Without anything else after OR:

www.domain.com/my-office-belgrade  ... or

www.domain.com/my-office-new-york ... or  ... my-office-wherever-wherever-wherever

The following was my urgent solution, but it's not dynamic, and it only covers 2 examples, but I need solution for the dynamic website, the solution that covers all the above.

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    Redirect 301 /my-shop /my-office
    Redirect 301 /my-shop-new-york /my-office-new-york
</IfModule>
</code>```

答:
This is the solution that worked out for me.

In order to replace the leading /my-shop with /my-office and leave everything afterwards as is, I used a capturing group:

```<code>(.*)
</code>```

and replaced it with $1:

```<code>RedirectMatch 301 /my-shop(.*) /my-office$1
</code>```

Body:
I need to redirect a lot of URLs by changing just some part that is in the middle or at the end of the URL. If that part is in the middle, the end must stay the same.

I need to accomplish this by using htaccess and regex.

I found a lot of examples online, but most of the are one on one redirection, and not covering enough dynamic websites. Also I haven't found answer to this in other questions here.

I have URL:

www.domain.com/something (alone)  OR URLS like

www.domain.com/something-aaa-bbb-ccc OR only

www.domain.com/something-aaa

How to make it:

www.domain.com/somethingELSE but ALSO:

www.domain.com/somethingELSE-aaa-bbb-ccc

(KEEP aaa-bbb or whatever goes at the end the same)

To make this more human readable, let's say these are shops with a lot of locations:

www.domain.com/my-shop - Without anything else after OR:

www.domain.com/my-shop-belgrade  ... or

www.domain.com/my-shop-new-york ... or  ... shop-wherever-wherever-wherever

TO BE:

www.domain.com/my-office - Without anything else after OR:

www.domain.com/my-office-belgrade  ... or

www.domain.com/my-office-new-york ... or  ... my-office-wherever-wherever-wherever

The following was my urgent solution, but it's not dynamic, and it only covers 2 examples, but I need solution for the dynamic website, the solution that covers all the above.

<IfModule mod_rewrite.c>
    RewriteEngine On
    Redirect 301 /my-shop /my-office
    Redirect 301 /my-shop-new-york /my-office-new-york
</IfModule>

Body:
This is the solution that worked out for me.

In order to replace the leading /my-shop with /my-office and leave everything afterwards as is, I used a capturing group:

(.*)

and replaced it with $1:

RedirectMatch 301 /my-shop(.*) /my-office$1


问:
Using reduce to delete even numbers in an object
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.

```<code>A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }

//counts -> { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;
</code>```

Must return the key of the odd count.

SOLUTION:

```<code>function findOdd(A) {
  const counts = {};
  for (let i = 0; i < A.length; i++) {
    let num = A[i];
    counts[num] = counts[num] ? counts[num] + 1 : 1;
  }
  Object.keys(counts).forEach(key => {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}
</code>```

答:
function findOdd(arr) {
  const counts = {}; // `const` declared objects/arrays are not immutable
  for(let i = 0; i < arr.length; i++) {
    counts[arr[i]] = counts[arr[i]] || 0;
    counts[arr[i]]++;
  }
  Object.keys(counts).forEach(key => {
    if(counts[key] % 2 === 0) {
      delete counts[key];
    }
  });
  return counts;
}

const array = [1, 2, 3, 4, 5, 6, 1, 1, 4, 5, 4, 9];
// 1:3, 2:1, 3:1, 4:3, 6:1, 9:1
// Does not show a `5` key due to there being an even number of fives in `array`

console.log(findOdd(array));```

Yes, I know delete is inefficient, but that shouldn't matter, unless it is a requirement for being quick. I believe you can just set counts[key] = undefined or counts[key] = null, you can see the benchmarks here

Body:
I'm given an array of numbers. I have created an object named counts, whose keys are the numbers and values the amount of times those numbers appear in the array. Can't work out how to use reduce to delete the even counts of the numbers.

A =  [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5 ]

n =  5

function findOdd(A) {

  let counts = {};

  for (let i = 0; i  { '1': 2, '2': 2, '3': 2, '4': 2, '5': 3, '20': 2, '-1': 2, '-2': 2 }

  const answer = Object.keys(counts).reduce((object, key) => {
    if (key % 2 !== 0) {
      object[key] = counts[key];
    }
    return object;
  }, {})

  return answer;

Must return the key of the odd count.

SOLUTION:

function findOdd(A) {
  const counts = {};
  for (let i = 0; i  {
    if(counts[key] % 2 === 0) {
    delete counts[key];
    }
  });
  return Number(Object.keys(counts));
}

Body:
function findOdd(arr) {
  const counts = {}; // `const` declared objects/arrays are not immutable
  for(let i = 0; i < arr.length; i++) {
    counts[arr[i]] = counts[arr[i]] || 0;
    counts[arr[i]]++;
  }
  Object.keys(counts).forEach(key => {
    if(counts[key] % 2 === 0) {
      delete counts[key];
    }
  });
  return counts;
}

const array = [1, 2, 3, 4, 5, 6, 1, 1, 4, 5, 4, 9];
// 1:3, 2:1, 3:1, 4:3, 6:1, 9:1
// Does not show a `5` key due to there being an even number of fives in `array`

console.log(findOdd(array));

Yes, I know delete is inefficient, but that shouldn't matter, unless it is a requirement for being quick. I believe you can just set counts[key] = undefined or counts[key] = null, you can see the benchmarks here


答:
Just as the services can be injected into controllers, so too can they be injected into other classes.

static classes however to not lend themselves well to dependency injection by default.

Instead of using a static class, make a regular class and explicitly depend on the desired service via constructor injection

```<code>internal class MyClass : IMyService {
    readonly AppSettings settings;

    public MyClass(AppSettings settings) {
        this.settings = settings;
    }

    internal void DosomeThing() {
        // retrieve some value from settings
        // continue with my logic
    }
}
</code>```

You can then register your desired POCO and utilities with the service container

```<code>public void ConfigureServices(IServiceCollection services) {
    AppSettings appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
    services.AddSingleton(appSettings);
    services.AddSingleton<IMyService, MyClass>();
    //. . . .
}
</code>```

Inject your service where it is needed and it will have access to the POCO when being resolved for injection.

There really is no need to be passing IServiceProvider around as that can be seen as a code smell.

Simplifying your design to follow explicit dependency principle should make your code more SOLID and easier to follow and maintain.

Title: Retrieve Service and use it in some arbitrary class in net core

Body:
Just as the services can be injected into controllers, so too can they be injected into other classes.

static classes however to not lend themselves well to dependency injection by default.

Instead of using a static class, make a regular class and explicitly depend on the desired service via constructor injection

internal class MyClass : IMyService {
    readonly AppSettings settings;

    public MyClass(AppSettings settings) {
        this.settings = settings;
    }

    internal void DosomeThing() {
        // retrieve some value from settings
        // continue with my logic
    }
}

You can then register your desired POCO and utilities with the service container

public void ConfigureServices(IServiceCollection services) {
    AppSettings appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
    services.AddSingleton(appSettings);
    services.AddSingleton<IMyService, MyClass>();
    //. . . .
}

Inject your service where it is needed and it will have access to the POCO when being resolved for injection.

There really is no need to be passing IServiceProvider around as that can be seen as a code smell.

Simplifying your design to follow explicit dependency principle should make your code more SOLID and easier to follow and maintain.


问:
How to remove a cloned row
Trying to make a shopping cart. I've created a table containing products (each row contains an item, its price, and a button to select it). With js, when you click on a button of an item it clones the entire row of this item and put the clone in a second table (which is the shopping basket). I would like to remove a cloned row of the second table when clicking on its button. It's not about remove the DOM parent, because the button parent is a td and not the entire tr which I would like to delete.

let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
  button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
  let td = e.target.parentNode;
  let tr = td.parentNode;
  let clone = tr.cloneNode(true);
  basket.appendChild(clone);
  clone.querySelector('.item_button').textContent = "-";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>CHOOSE</h1>

<table id="starters">
  <tr>
    <th>PRODUCT</th>
    <th>PRICE</th>
    <th>ADD TO CART</th>
  </tr>
  <tr>
    <td>Cherry</td>
    <td>6</td>
    <td><button class="item_button">+</button></td>
  </tr>
  <tr>
    <td>Peach</td>
    <td>8</td>
    <td><button class="item_button">+</button></td>
  </tr>
  <tr>
    <td>Strawberry</td>
    <td>12</td>
    <td><button class="item_button">+</button></td>
  </tr>

</table>

<h1>YOUR CHOICE</h1>

<table id="products_cart">

</table></code>```

答:
let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
  button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
  let td = e.target.parentNode;
  let tr = td.parentNode;
  let clone = tr.cloneNode(true);
  basket.appendChild(clone);
  clone.querySelector('.item_button').textContent = "-";
  clone.querySelector('.item_button').addEventListener("click", function(){
    basket.removeChild(clone);
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>CHOOSE</h1>

<table id="starters">
  <tr>
    <th>PRODUCT</th>
    <th>PRICE</th>
    <th>ADD TO CART</th>
  </tr>
  <tr>
    <td>Cherry</td>
    <td>6</td>
    <td><button class="item_button">+</button></td>
  </tr>
  <tr>
    <td>Peach</td>
    <td>8</td>
    <td><button class="item_button">+</button></td>
  </tr>
  <tr>
    <td>Strawberry</td>
    <td>12</td>
    <td><button class="item_button">+</button></td>
  </tr>

</table>

<h1>YOUR CHOICE</h1>

<table id="products_cart">

</table></code>```

Title: How to remove a cloned row

Body:
Trying to make a shopping cart. I've created a table containing products (each row contains an item, its price, and a button to select it). With js, when you click on a button of an item it clones the entire row of this item and put the clone in a second table (which is the shopping basket). I would like to remove a cloned row of the second table when clicking on its button. It's not about remove the DOM parent, because the button parent is a td and not the entire tr which I would like to delete.

let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
  button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
  let td = e.target.parentNode;
  let tr = td.parentNode;
  let clone = tr.cloneNode(true);
  basket.appendChild(clone);
  clone.querySelector('.item_button').textContent = "-";
}

CHOOSE

    PRODUCT
    PRICE
    ADD TO CART

    Cherry
    6
    <button class="item_button">+</button>

    Peach
    8
    <button class="item_button">+</button>

    Strawberry
    12
    <button class="item_button">+</button>

YOUR CHOICE

Body:
let basket = document.getElementById("products_cart")

let buttons = document.querySelectorAll('.item_button');

for (button of buttons) {
  button.addEventListener('click', cloneLine);
}

function cloneLine(e) {
  let td = e.target.parentNode;
  let tr = td.parentNode;
  let clone = tr.cloneNode(true);
  basket.appendChild(clone);
  clone.querySelector('.item_button').textContent = "-";
  clone.querySelector('.item_button').addEventListener("click", function(){
    basket.removeChild(clone);
  });
}

<h1>CHOOSE</h1>

<table id="starters">
  <tr>
    <th>PRODUCT</th>
    <th>PRICE</th>
    <th>ADD TO CART</th>
  </tr>
  <tr>
    <td>Cherry</td>
    <td>6</td>
    <td><button class="item_button">+</button></td>
  </tr>
  <tr>
    <td>Peach</td>
    <td>8</td>
    <td><button class="item_button">+</button></td>
  </tr>
  <tr>
    <td>Strawberry</td>
    <td>12</td>
    <td><button class="item_button">+</button></td>
  </tr>

</table>

<h1>YOUR CHOICE</h1>

<table id="products_cart">

</table>


问:
Java: How to create new child class instance from abstract parent class?
Here is the gist of what I am trying to do:

```<code>abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}
</code>```

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

答:
You can remove the static keyword from the signature of the function and define the fromInput method as abstract --

```<code>abstract class Animal<T> {
    abstract T fromInput(String input);

    List<T> makeFive() {
        List<T> animals = new ArrayList<>();
        animals.add(fromInput("Input 1"));
        animals.add(fromInput("Input 2"));
        animals.add(fromInput("Input 3"));
        animals.add(fromInput("Input 4"));
        animals.add(fromInput("Input 5"));
        return animals;
    }
}

class Dog extends Animal<Dog> {
    @Override
    Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal<Cat> {
    @Override
    Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}
</code>```

You can then use it to implement the invocation as follows --

```<code>public class Solution {

    public static void main(String[] args) {
        /*
         * Dog(s)
         */
        List<Dog> dogs = new Dog().makeFive();
        for (Dog dog : dogs) {
            System.err.println(dog.getClass());
        }

        /*
         * Cat(s)
         */
        List<Cat> cats = new Cat().makeFive();
        for (Cat cat : cats) {
            System.err.println(cat.getClass());
        }
    }

}
</code>```

Body:
Here is the gist of what I am trying to do:

abstract class Animal {
    abstract static Animal fromInput(String input); // <- error

    static List<Animal> makeFive() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(Animal.fromInput("Input 1"));
        animals.add(Animal.fromInput("Input 2"));
        animals.add(Animal.fromInput("Input 3"));
        animals.add(Animal.fromInput("Input 4"));
        animals.add(Animal.fromInput("Input 5"));
        return animals;
    }
    // ^^^ how to this rewrite this so Dog.makeFive() ^^^ //
    // ^^^ makes Dogs and Cat.makeFive() makes Cats?  ^^^ //
}

class Dog extends Animal {
    @Override static Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal {
    @Override static Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}

How to write this correctly?

I want to be able to call Dog.makeFive() to give me a List<Dog> or Cat.makeFive() to give me a List<Cat> without having to re-define makeFive() in Dog, Cat, and every other animal class.

EDIT: I know the use of static within an abstract class is wrong. My question is how to work around that so one is able to call Dog.makeFive() or Cat.makeFive() while only defining makeFive() once.

Body:
You can remove the static keyword from the signature of the function and define the fromInput method as abstract --

abstract class Animal<T> {
    abstract T fromInput(String input);

    List<T> makeFive() {
        List<T> animals = new ArrayList<>();
        animals.add(fromInput("Input 1"));
        animals.add(fromInput("Input 2"));
        animals.add(fromInput("Input 3"));
        animals.add(fromInput("Input 4"));
        animals.add(fromInput("Input 5"));
        return animals;
    }
}

class Dog extends Animal<Dog> {
    @Override
    Dog fromInput(String input) {
        Dog dog = new Dog();
        // do some initial dog stuff with input
        return dog;
    }
}

class Cat extends Animal<Cat> {
    @Override
    Cat fromInput(String input) {
        Cat cat = new Cat();
        // do some initial cat stuff with input
        return cat;
    }
}

You can then use it to implement the invocation as follows --

public class Solution {

    public static void main(String[] args) {
        /*
         * Dog(s)
         */
        List<Dog> dogs = new Dog().makeFive();
        for (Dog dog : dogs) {
            System.err.println(dog.getClass());
        }

        /*
         * Cat(s)
         */
        List<Cat> cats = new Cat().makeFive();
        for (Cat cat : cats) {
            System.err.println(cat.getClass());
        }
    }

}


问:
WordPress Metabox saves on Update or Publish, but not on Saving Draft
I have created custom post types that also have custom meta_boxes I've created.  Currently, they save when I publish or update a post, but they don't save when I'm in draft mode making changes.

```<code>add_action('save_post', 'save_details');

function save_details($post_id){
    global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
    return $post_id;
}
if ($post->post_type == 'events') { // Check to see if Event Type.
    update_post_meta($post->ID, "event_featuring", $_POST["event_featuring"]);
    update_post_meta($post->ID, "event_time", $_POST["event_time"]);
    update_post_meta($post->ID, "event_date", $_POST["event_date"]);
    update_post_meta($post->ID, "event_end_date", $_POST["event_end_date"]);
    update_post_meta($post->ID, "event_location", $_POST["event_location"]);
    update_post_meta($post->ID, "empid", $_POST["empid"]);
    update_post_meta($post->ID, "bhs_event", $_POST["bhs_event"]);
}
}
</code>```

I tried using wp_insert_post_data instead of save_post, but then I had the opposite problem.  It would save on Drafts, but publishing the post no longer worked.  I tried calling both at the same time, same issue.  What do I need to do differently so I can update a draft (before publishing) and it will save?  I'm pretty sure this was working fine before I switched to 3.1.

答:
save_post is called no matter what, be it a draft post, or a published post, so I am surprised that is not working.  I do see a few oddities with your code though.

Considering you have the $post_ID, I would favor using that over the global $post.  Also, I prefer the following method of detecting auto-drafts (I ripped it straight from wp-includes/post.php, I favor examining the Wordpress codebase and emulating their methods whenever possible).

Please try the following refactored code and let me know if this resolves your issue.

```<code>add_action("save_post", "save_details");

function save_details($post_ID = 0) {
    $post_ID = (int) $post_ID;
    $post_type = get_post_type( $post_ID );
    $post_status = get_post_status( $post_ID );
    if ( "events" == $post_type && "auto-draft" != $post_status ) {
        update_post_meta($post_ID, "event_featuring", $_POST["event_featuring"]);
        update_post_meta($post_ID, "event_time", $_POST["event_time"]);
        update_post_meta($post_ID, "event_date", $_POST["event_date"]);
        update_post_meta($post_ID, "event_end_date", $_POST["event_end_date"]);
        update_post_meta($post_ID, "event_location", $_POST["event_location"]);
        update_post_meta($post_ID, "empid", $_POST["empid"]);
        update_post_meta($post_ID, "bhs_event", $_POST["bhs_event"]);
    }
    return $post_ID;
}
</code>```

Body:
I have created custom post types that also have custom meta_boxes I've created.  Currently, they save when I publish or update a post, but they don't save when I'm in draft mode making changes.

add_action('save_post', 'save_details');

function save_details($post_id){
    global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
    return $post_id;
}
if ($post->post_type == 'events') { // Check to see if Event Type.
    update_post_meta($post->ID, "event_featuring", $_POST["event_featuring"]);
    update_post_meta($post->ID, "event_time", $_POST["event_time"]);
    update_post_meta($post->ID, "event_date", $_POST["event_date"]);
    update_post_meta($post->ID, "event_end_date", $_POST["event_end_date"]);
    update_post_meta($post->ID, "event_location", $_POST["event_location"]);
    update_post_meta($post->ID, "empid", $_POST["empid"]);
    update_post_meta($post->ID, "bhs_event", $_POST["bhs_event"]);
}
}

I tried using wp_insert_post_data instead of save_post, but then I had the opposite problem.  It would save on Drafts, but publishing the post no longer worked.  I tried calling both at the same time, same issue.  What do I need to do differently so I can update a draft (before publishing) and it will save?  I'm pretty sure this was working fine before I switched to 3.1.

Body:
save_post is called no matter what, be it a draft post, or a published post, so I am surprised that is not working.  I do see a few oddities with your code though.

Considering you have the $post_ID, I would favor using that over the global $post.  Also, I prefer the following method of detecting auto-drafts (I ripped it straight from wp-includes/post.php, I favor examining the Wordpress codebase and emulating their methods whenever possible).

Please try the following refactored code and let me know if this resolves your issue.

add_action("save_post", "save_details");

function save_details($post_ID = 0) {
    $post_ID = (int) $post_ID;
    $post_type = get_post_type( $post_ID );
    $post_status = get_post_status( $post_ID );
    if ( "events" == $post_type && "auto-draft" != $post_status ) {
        update_post_meta($post_ID, "event_featuring", $_POST["event_featuring"]);
        update_post_meta($post_ID, "event_time", $_POST["event_time"]);
        update_post_meta($post_ID, "event_date", $_POST["event_date"]);
        update_post_meta($post_ID, "event_end_date", $_POST["event_end_date"]);
        update_post_meta($post_ID, "event_location", $_POST["event_location"]);
        update_post_meta($post_ID, "empid", $_POST["empid"]);
        update_post_meta($post_ID, "bhs_event", $_POST["bhs_event"]);
    }
    return $post_ID;
}


问:
Issue inserting String into StringBuffer/StringBuilder with stream/parallelStream
I was trying to insert Strings into StringBuffer using foreach method of parallelStream(), created from a Set collection.
The problem is every time I execute the code, the final String (StringBuffer.toString()) has 1 less element of the total (random element every time I try).

I also change the StringBuffer to StringBuilder, the parallelStream() to stream(), but always has 1 less element.

I am using:
- Java version: java 1.8_121
- Server: Weblogic 12.2.1.2 (I don't think this is relevant to the problem)
- Spring boot 2.0.2.RELEASE (I don't think this is relevant to the problem)

NOTE: I used a Map to keep the pdfs I should sign later on the process (in another HTTP request).

Map<String, ClientPdf> dataToEncript = new HashMap<>(); // pdf name it will be the key for this map (it is unique in the sql query)

List<Client> listClients = // list of clients from database
Set<ClientPdf> clientsPdf = new HashSet<>();
for (Client client : listClients) {
    clientsPdf.add(client.clientPdf()); // clientPdf() generate a new object ClientPdf, which is similar to Client class, but with less fields (essential for the Set)
}

log.debug("Generating documents");
clientsPdf.parallelStream().forEach(pdf -> {
    // some code to generate pdf

    log.debug("Inserting pdf: {}", pdf); // this log print, for example, 27.000 lines
    dataToEncript.put(pdf.getPdfName(), pdf);
});

StringBuffer sb = new StringBuffer(); // StringBuffer or StringBuilder, the same problem
for (ClientPdf clientPdf : dataToEncript.values()) {
    sb.append(clientPdf.getPdfName() + ";" + clientPdf.getRut() + "\n"); // appending all values of de map dataToEncript, it will append 26.669 (1 less)
}
```

答:
```<code>clientsPdf.parallelStream().forEach(pdf -> {
    // ...
    dataToEncript.put(pdf.getPdfName(), pdf);
});
</code>```

dataToEncript is not a thread-safe data structure, so this is likely to cause ridiculous and weird bugs like the one you're observing

In general, using forEach is often a bad sign, and you should almost always be using a Collector or some other method.  For example, here you should probably use

```<code>clientsPdf.parallelStream()
   .collect(Collectors.toConcurrentMap(Pdf::getPdfName, pdf -> pdf));
</code>```

to get a correct map out.

Even better, you could write

```<code>clientsPdf.parallelStream()
    .map(clientPdf -> clientPdf.getPdfName() + ";" + clientPdf.getRut() + "\n")
    .collect(Collectors.joining())
</code>```

to get the final String out without any manual management of StringBuffer or the like.

Body:
clientsPdf.parallelStream().forEach(pdf -> {
    // ...
    dataToEncript.put(pdf.getPdfName(), pdf);
});

dataToEncript is not a thread-safe data structure, so this is likely to cause ridiculous and weird bugs like the one you're observing

In general, using forEach is often a bad sign, and you should almost always be using a Collector or some other method.  For example, here you should probably use

clientsPdf.parallelStream()
   .collect(Collectors.toConcurrentMap(Pdf::getPdfName, pdf -> pdf));

to get a correct map out.

Even better, you could write

clientsPdf.parallelStream()
    .map(clientPdf -> clientPdf.getPdfName() + ";" + clientPdf.getRut() + "\n")
    .collect(Collectors.joining())

to get the final String out without any manual management of StringBuffer or the like.


问:
I can't understand "String.format() function in this example any help ?"
this an example to get mac address form my machine but i can't understand the syntax of sting.format function
here is the example.

public String getMACIdentifier(NetworkInterface network)
{
    StringBuilder identifier = new StringBuilder();
    try {
        byte[] macBuffer = network.getHardwareAddress();
        if (macBuffer != null) {
            for (int i = 0; i < macBuffer.length; i++) {
                identifier.append(
                    String.format("%02X%s",macBuffer[i],
                    (i < macBuffer.length - 1) ? "-" : ""));
            }
        } else {
            return "---";
        }
    } catch (SocketException ex) {
        ex.printStackTrace();
    }

    return identifier.toString();
}
```

答:
Formatted strings are a common feature of programming languages. I would recommend reading up on how they work in Java.

In your specific example, the format string "%02X%s" will print a hexadecimal number (represented by %02X) next to a string (represented by "%s"). The hex number will be printed using at least 2 characters; if the number is representable with just one character, then the empty space will be "padded" with a '0' character. This is coded "%02X". The string character will be either "-" or "" (empty), depending on the result of the ternary operator (test ? true_value : false_value).


问:
Using sed to replace only first ocurrence while using variable and "/" in variable
I have a file that looks like this

```<code>I/am/a/string
I'm/still/a/string
Always/a/string
</code>```

I'm trying to use sed to replace the first occurrence of "string" with a variable that contains "/" like

```<code>x=ive/been/replaced
</code>```

So the output of sed would be

```<code>I/am/a/ive/been/replaced
</code>```

Because i only want the first occurrence and i'm using a variable typically you use

```<code>sed -i "0,/string/s//$x/" file
</code>```

However in this case because the variable has "/" i have to use a different separator like

```<code>sed "0,|string|s||$x|" file
</code>```

But this does not work.

what am i missing?

NOTE:

I would like to accomplish this in sed

答:
If you are ok using awk: you can print and exit after first replacement.

```<code>awk -v x="${x}" '{gsub(/string/,x);print ;exit}' file
I/am/a/ive/been/replaced
</code>```

sed version: This will exit after first match, note that search string "string" is still inside / / whereas substitution part is using different separator.

```<code>sed -n   "0,/string/ s|string|$x|p"
I/am/a/ive/been/replaced
</code>```

Body:
I have a file that looks like this

I/am/a/string
I'm/still/a/string
Always/a/string

I'm trying to use sed to replace the first occurrence of "string" with a variable that contains "/" like

x=ive/been/replaced

So the output of sed would be

I/am/a/ive/been/replaced

Because i only want the first occurrence and i'm using a variable typically you use

sed -i "0,/string/s//$x/" file

However in this case because the variable has "/" i have to use a different separator like

sed "0,|string|s||$x|" file

But this does not work.

what am i missing?

NOTE:

I would like to accomplish this in sed

Body:
If you are ok using awk: you can print and exit after first replacement.

awk -v x="${x}" '{gsub(/string/,x);print ;exit}' file
I/am/a/ive/been/replaced

sed version: This will exit after first match, note that search string "string" is still inside / / whereas substitution part is using different separator.

sed -n   "0,/string/ s|string|$x|p"
I/am/a/ive/been/replaced


问:
How to indent a few lines in Markdown markup?
I want to write a few lines of text. They should be formatted normally except each line should start at the 6th column. I.e. I don't want the code block formatting rule to make this chunk of text look like code as I'll use other formatting like bold face, etc. How to do that in Markdown?</p>

答:
On gitlab.com a single en space (U+2002) followed by a single em space (U+2003) works decently.

Presumably other repetitions or combinations of not-exactly-accounted-for space characters would also suffice.


问:
Labview - Increasing Array Index with Array Size Limiting
I'm working with a labview XY line plot that uses a random number generator for y values and the while loop count for x values. Upon reaching a threshold x value, say 1000, I'd like to be able to iterate across the past 1000 values and display only every 10th (This has the effect of de-cluttering the plot). Ideally the method for achieving this would be expandable for higher threshold values so that the plot has the following format:

Every 1,000 values, step size is 10

Every 10,000 values, step size is 100

Every 100,000, step size is 1,000

etc.

Below is the code I've been working with, and a picture of the VI. My question is, is there a better way to achieve this effect without having to delete values from the arrays as I am currently doing (inside the for loop)?

Code

Virtual Instrument

答:
What you are referring to is called "decimation" (literally here i think, as you are breaking it down by 10s). There is a function in LabVIEW for decimating arrays, more info on that can be found here.

This seems like a simplified version of what you are trying to do using the decimate VI

There are configurable decimating VIs that can be used from the Signal Operations palette that can do the decimation with a decimation factor, see here or from 3rd party packages. MGI has one on one of their palettes called MGI Decimate Array with Offset. You can replace the decimate function in the code above with any of those and change the decimation factor based on the size of the array coming in.

EDIT: @JonathanVahala was asking about using configurable decimation below. See this image which shows a way to do this:

You can replace the case structure with this one to decimate this way.


问:
Is there any database model having these "no-sql", "schema free" & "relational" ? is it support c++?
I need schema free db with relational features for my C++ application.

I already using PostgreSQL and Mysql in my project.

I want to store data relationally in document and need CRUD using SQL.

答:
The actual answer to your specific question based on your parameters:

Schema free

CRUD support

SQL "like", aka Relational

C++ support

is ArangoDB.


问:
Laravel Auth return to index
Can I redirect to the previous page someone if not logged in? Also, is it possible to create a hierarchy system for users?

I tried this:

```<code>if(!(Auth::check())) {
            header("Location: {{ route('cooperado.index') }});
}
</code>```

But i not even got an error message, just doesn't work. I'm starting at laravel so it's kind of hard to fully understand how it works.

答:
You can use this. Is the easiest way to do this.
And you can also pass message, will displayed on when user redirect back from main page.</p>

```<code>if(!Auth::check) {
      return Redirect::back()->with('error','Please Login');
}
</code>```

Title: Laravel Auth return to index

Body:
Can I redirect to the previous page someone if not logged in? Also, is it possible to create a hierarchy system for users?

I tried this:

if(!(Auth::check())) {
            header("Location: {{ route('cooperado.index') }});
}

But i not even got an error message, just doesn't work. I'm starting at laravel so it's kind of hard to fully understand how it works.

Body:
You can use this. Is the easiest way to do this.
And you can also pass message, will displayed on when user redirect back from main page.

if(!Auth::check) {
      return Redirect::back()->with('error','Please Login');
}


问:
How come my code only returns the first element from my list?
How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?</p>

```<code>def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))
</code>```

答:
You could try this instead:

```<code>def show_magicians(magicians):

    for magician in magicians:
        yield(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
for mag in show_magicians(magicians):
    print(mag, end=' ')
</code>```

Instead of running through the loop and returning the first iteration this will turn your code into a generator that you can put in another loop like shown.  Using yield instead of return will return each item in the list then continue to the next item then return that and the next and so on and so on.

Just in case you don't know the end=' ' in the print function is what is used to separate each item as it is returned.  Play with it by replacing ' ' with ',' or '\n' etc for different results.  You can even append the results to a new list and print that instead like sarkamedo showed you but, again, you'll just end up with a copy of the original list.

Body:
How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?

def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))

Body:
You could try this instead:

def show_magicians(magicians):

    for magician in magicians:
        yield(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
for mag in show_magicians(magicians):
    print(mag, end=' ')

Instead of running through the loop and returning the first iteration this will turn your code into a generator that you can put in another loop like shown.  Using yield instead of return will return each item in the list then continue to the next item then return that and the next and so on and so on.

Just in case you don't know the end=' ' in the print function is what is used to separate each item as it is returned.  Play with it by replacing ' ' with ',' or '\n' etc for different results.  You can even append the results to a new list and print that instead like sarkamedo showed you but, again, you'll just end up with a copy of the original list.


问:
Visual Studio 2017 Git extension counting fetching others' work as a merge to same branch
A friend and I are simultaneously working on a Github repository. We both are using Visual Studio 2017 with the Git extension installed and both have write access to the repository.

If I push a commit to the repository and he syncs it, his next push will contain an extra merge commit that contained the prior work that I fetched. If I fetch something he has pushed and later push a commit, the same thing happens.

Here is an example of a resulting merge that was caused after I received his changes and pushed code to the repository.

Why is this happening, and how can we avoid this from happening every time we push code to the repository?

答:
You could also set this in Visual Studio itself

In the team Explorer, Go to Settings, then "global settings":

and enable "Rebase local branch when pulling"


问:
S3Client::GetObject with SetRange returns wrong data?
I am attempting to read a segment of a large AWS S3 Object starting with the first 1048576 bytes.  I specify the range of bytes that I want to read but I do not receive those bytes.  The length returned is correct.

I am fairly new at this so I'm probably doing something wrong and being a C programmer instead of C++ has not helped a lot.

Here's a sample of my code:

```<code>int   start=0, rbytes=0;

Aws::S3::S3Client  s3_client;
Aws::S3::Model::GetObjectRequest read_object_request;
sprintf(range,"bytes=%lld-%lld",start,start+1048575);

read_object_request.SetBucket(container_name);
read_object_request.SetKey(object_name);
read_object_request.SetRange(range);
auto results = s3_client.GetObject(read_object_request);
if (results.IsSuccess())
{
   rbytes = results.GetResult().GetContentLength();
   std::cout << rbytes << " bytes read" << std::endl;
}
memcpy(bdata,results.GetResult().GetBody().rdbuf(),rbytes);
</code>```

I then dump the bdata buffer and it is not what I expected.  When I repeat the execution of the code, a new instance, it returns different data.

Though I don't show it the   bdata  buffer is pre-allocated 2 megabytes.

Any ideas that would point me in the right direction would be appreciated.

Thanks in advance.

答:
Here's my final code for anyone who's interested.  I would also appreciate any comments you see fit to make.

```<code>#include <streambuf>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/s3/model/HeadObjectResult.h>
#include <aws/s3/model/Object.h>

long scanObject(Aws::String region,
                Aws::String bucket_name,
                Aws::String object_name);

int main(int argc, char** argv)
{
   long scanned=0;

   if (argc < 4){ return(1); }
   Aws::String region = argv[1];
   Aws::String bucket_name = argv[2];
   Aws::String object_name = argv[3];

   Aws::SDKOptions options;
   Aws::InitAPI(options);

   scanned = scanObject(region,bucket_name,object_name);
   printf("Scanned %d bytes of object\n",scanned);

   Aws::ShutdownAPI(options);

   return(0);
}

long scanObject(Aws::String region,
                Aws::String bucket_name,
                Aws::String object_name)
{
   int   rbytes, nbytes;
   char range[48], *buffer;
   long filesize, bytesleft, start;

   Aws::Client::ClientConfiguration cconfig;
   cconfig.region = region;
   Aws::S3::S3Client s3_client(cconfig);

   Aws::S3::Model::HeadObjectRequest head_object_request;
   head_object_request.WithBucket(bucket_name).WithKey(object_name);
   Aws::S3::Model::HeadObjectOutcome head_object;
   head_object = s3_client.HeadObject(head_object_request);
   if (!head_object.IsSuccess())
   {
      printf("AWS Object, /%s/%s, failed to locate\n",
             region.c_str(),object_name.c_str());
      return(-1);
   }

   filesize = head_object.GetResult().GetContentLength();
   bytesleft = filesize;

   start = 0;
   nbytes = 1048576;
   buffer = (char*)malloc(nbytes*2);

   Aws::S3::Model::GetObjectRequest read_request;
   while(bytesleft > 0)
   {
      if (bytesleft > 1048576){ nbytes = 1048576; }else{ nbytes = bytesleft; }

      sprintf(range,"bytes=%d-%d",start,start+nbytes-1);

      read_request.SetBucket(bucket_name);
      read_request.SetKey(object_name);
      read_request.SetRange(range);

      auto results = s3_client.GetObject(read_request);

      if (!results.IsSuccess())
      {
         printf("\nUnable to fetch object range %s from s3 bucket.\n",range);
         return(-1);
      }
      rbytes = results.GetResult().GetContentLength();

      std::streambuf* body = results.GetResult().GetBody().rdbuf();
      body->sgetn(buffer,rbytes);

      start += rbytes;
      bytesleft -= rbytes;
   }

   return(filesize);
}
</code>```

I'm sure this could be done in a more efficient manner and hopefully I will learn that as I go along.

Body:
I am attempting to read a segment of a large AWS S3 Object starting with the first 1048576 bytes.  I specify the range of bytes that I want to read but I do not receive those bytes.  The length returned is correct.

I am fairly new at this so I'm probably doing something wrong and being a C programmer instead of C++ has not helped a lot.

Here's a sample of my code:

int   start=0, rbytes=0;

Aws::S3::S3Client  s3_client;
Aws::S3::Model::GetObjectRequest read_object_request;
sprintf(range,"bytes=%lld-%lld",start,start+1048575);

read_object_request.SetBucket(container_name);
read_object_request.SetKey(object_name);
read_object_request.SetRange(range);
auto results = s3_client.GetObject(read_object_request);
if (results.IsSuccess())
{
   rbytes = results.GetResult().GetContentLength();
   std::cout << rbytes << " bytes read" << std::endl;
}
memcpy(bdata,results.GetResult().GetBody().rdbuf(),rbytes);

I then dump the bdata buffer and it is not what I expected.  When I repeat the execution of the code, a new instance, it returns different data.

Though I don't show it the   bdata  buffer is pre-allocated 2 megabytes.

Any ideas that would point me in the right direction would be appreciated.

Thanks in advance.

Body:
Here's my final code for anyone who's interested.  I would also appreciate any comments you see fit to make.

#include <streambuf>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/s3/model/HeadObjectResult.h>
#include <aws/s3/model/Object.h>

long scanObject(Aws::String region,
                Aws::String bucket_name,
                Aws::String object_name);

int main(int argc, char** argv)
{
   long scanned=0;

   if (argc < 4){ return(1); }
   Aws::String region = argv[1];
   Aws::String bucket_name = argv[2];
   Aws::String object_name = argv[3];

   Aws::SDKOptions options;
   Aws::InitAPI(options);

   scanned = scanObject(region,bucket_name,object_name);
   printf("Scanned %d bytes of object\n",scanned);

   Aws::ShutdownAPI(options);

   return(0);
}

long scanObject(Aws::String region,
                Aws::String bucket_name,
                Aws::String object_name)
{
   int   rbytes, nbytes;
   char range[48], *buffer;
   long filesize, bytesleft, start;

   Aws::Client::ClientConfiguration cconfig;
   cconfig.region = region;
   Aws::S3::S3Client s3_client(cconfig);

   Aws::S3::Model::HeadObjectRequest head_object_request;
   head_object_request.WithBucket(bucket_name).WithKey(object_name);
   Aws::S3::Model::HeadObjectOutcome head_object;
   head_object = s3_client.HeadObject(head_object_request);
   if (!head_object.IsSuccess())
   {
      printf("AWS Object, /%s/%s, failed to locate\n",
             region.c_str(),object_name.c_str());
      return(-1);
   }

   filesize = head_object.GetResult().GetContentLength();
   bytesleft = filesize;

   start = 0;
   nbytes = 1048576;
   buffer = (char*)malloc(nbytes*2);

   Aws::S3::Model::GetObjectRequest read_request;
   while(bytesleft > 0)
   {
      if (bytesleft > 1048576){ nbytes = 1048576; }else{ nbytes = bytesleft; }

      sprintf(range,"bytes=%d-%d",start,start+nbytes-1);

      read_request.SetBucket(bucket_name);
      read_request.SetKey(object_name);
      read_request.SetRange(range);

      auto results = s3_client.GetObject(read_request);

      if (!results.IsSuccess())
      {
         printf("\nUnable to fetch object range %s from s3 bucket.\n",range);
         return(-1);
      }
      rbytes = results.GetResult().GetContentLength();

      std::streambuf* body = results.GetResult().GetBody().rdbuf();
      body->sgetn(buffer,rbytes);

      start += rbytes;
      bytesleft -= rbytes;
   }

   return(filesize);
}

I'm sure this could be done in a more efficient manner and hopefully I will learn that as I go along.


问:
how to solve problem with loading large amount of data in django?
I'm trying to write an app like imdb for my work project. in this app i need to store 8700 of imdb movies and also about 40k directors and actors/actresses in mysql database,

when i was trying to post a new movie, the movie creation page took a long time (about 20s) to render.

first, i did make a model named "persons" with person name, gender, "is_director" and "is_actor" boolean fields.

then, i did create a model named "movies" with 2 ManyToManyFields for is_director and is_actor persons.

after that, i did import about 40k persons to my database with django fixture.
my problem started from here. when i was trying to post a new movie from django admin, the movie creation page took a long time (about 10s) to render.
I know this is for a large amount of persons data. i did use django built-in autocomplete but the problem was still there.

I'm new to Python/Django. so I think I'm doing this in a wrong way.
maybe my database structure is wrong or my model has a problem, i don't know how to solve it!

```<code># Person Model:
class Person(models.Model):
    name = models.CharField(_('Person Name'), max_length=100)
    is_actor = models.BooleanField(_('is actor'), default=True)
    is_director = models.BooleanField(_('is director'), default=False)
    MALE = 'male'
    FEMALE = 'female'
    PERSON_GENDER = [(MALE, _('Male')), (FEMALE, _('Female'))]
    gender = models.CharField(
        _('Gender'),
        max_length=6,
        choices=PERSON_GENDER,
        default=MALE
    )

# Movies Model:
class Movies(models.Model):
    title = models.CharField(_('Movie Name'), max_length=250)
    genre = models.ManyToManyField(Genre, verbose_name=_('genre'))
    director = models.ManyToManyField(
        Person, verbose_name=_('director'), related_name=_('director'),limit_choices_to={'is_director': True},blank=True)
    actors = models.ManyToManyField(
        Person, verbose_name=_('actors'), related_name=_('actors'),limit_choices_to={'is_actor': True},blank=True)
</code>```

1- is there a problem with my code?

2- am I doing this in a wrong way?

3- am I picked the wrong framework?

4- I'm Familiar with asp.net core and laravel. is it better to write this kind of app with them? language is no problem, I only need performance.

答:
I guess your admin page contains your 40k persons list twice.
Try to use raw_id_fields in the admin for your director and actors fields.

Please see Django documentation
and this article about very long list (with an example with ForeignKey but it should also work with ManyToManyField)

Body:
I'm trying to write an app like imdb for my work project. in this app i need to store 8700 of imdb movies and also about 40k directors and actors/actresses in mysql database,

when i was trying to post a new movie, the movie creation page took a long time (about 20s) to render.

first, i did make a model named "persons" with person name, gender, "is_director" and "is_actor" boolean fields.

then, i did create a model named "movies" with 2 ManyToManyFields for is_director and is_actor persons.

after that, i did import about 40k persons to my database with django fixture.
my problem started from here. when i was trying to post a new movie from django admin, the movie creation page took a long time (about 10s) to render.
I know this is for a large amount of persons data. i did use django built-in autocomplete but the problem was still there.

I'm new to Python/Django. so I think I'm doing this in a wrong way.
maybe my database structure is wrong or my model has a problem, i don't know how to solve it!

# Person Model:
class Person(models.Model):
    name = models.CharField(_('Person Name'), max_length=100)
    is_actor = models.BooleanField(_('is actor'), default=True)
    is_director = models.BooleanField(_('is director'), default=False)
    MALE = 'male'
    FEMALE = 'female'
    PERSON_GENDER = [(MALE, _('Male')), (FEMALE, _('Female'))]
    gender = models.CharField(
        _('Gender'),
        max_length=6,
        choices=PERSON_GENDER,
        default=MALE
    )

# Movies Model:
class Movies(models.Model):
    title = models.CharField(_('Movie Name'), max_length=250)
    genre = models.ManyToManyField(Genre, verbose_name=_('genre'))
    director = models.ManyToManyField(
        Person, verbose_name=_('director'), related_name=_('director'),limit_choices_to={'is_director': True},blank=True)
    actors = models.ManyToManyField(
        Person, verbose_name=_('actors'), related_name=_('actors'),limit_choices_to={'is_actor': True},blank=True)

1- is there a problem with my code?

2- am I doing this in a wrong way?

3- am I picked the wrong framework?

4- I'm Familiar with asp.net core and laravel. is it better to write this kind of app with them? language is no problem, I only need performance.


问:
Bash: use an alias in a filepath
I cannot seem to figure out how to use an alias for a filename in a path. For example:

```<code>alias a="ls /tmp/ -tr | tail -n 1"
cat /tmp/a
</code>```

The alias gives me the name of the most recent file written in /tmp/. Then I try to cat that file and I get cat: /tmp/a: No such file or directory.

When I just type a I get the right thing, for instance some_log_I_just_wrote_to.log.

Obviously what I want is for cat /tmp/a to be translated into cat /tmp/some_log_I_just_wrote_to.log so that I can see the log.

Any ideas on what the right way to do this is? I sometimes get tangled up in bash with when to use aliases and symlinks and just plain variables, etc.

Thanks!

答:
Create the alias with </p>

```<code>alias a='ls /tmp/ -tr | tail -n 1'
</code>```

<p>Use the alias with cat </p>

```<code>cat $(echo -n /tmp/ && a)
</code>```

Title: Bash: use an alias in a filepath

Body:
I cannot seem to figure out how to use an alias for a filename in a path. For example:

alias a="ls /tmp/ -tr | tail -n 1"
cat /tmp/a

The alias gives me the name of the most recent file written in /tmp/. Then I try to cat that file and I get cat: /tmp/a: No such file or directory.

When I just type a I get the right thing, for instance some_log_I_just_wrote_to.log.

Obviously what I want is for cat /tmp/a to be translated into cat /tmp/some_log_I_just_wrote_to.log so that I can see the log.

Any ideas on what the right way to do this is? I sometimes get tangled up in bash with when to use aliases and symlinks and just plain variables, etc.

Thanks!

Body:
Create the alias with

alias a='ls /tmp/ -tr | tail -n 1'

Use the alias with cat

cat $(echo -n /tmp/ && a)


问:
PHP Echo within paragraph doesn't work with all records
I have a simple form, like this;

        <form action="column1.php" method="post">
        <input type="text" placeholder="URL:" name="url" required="">

        <input type="text" placeholder="Job Title:" name="title" required="">

        <input type="text" placeholder="Job Site & Additional Details" name="details">

        <input type="submit">

        </form>

```
</div>
</div>
</p>

<p>That form is then handled by <code>column1.php</code> which contains the following PHP;</p>

```<?php
$url = $_POST["url"];
$title = $_POST["title"];
$details = $_POST ["details"];
$timestamp =date('l jS \of F Y h:i:s A');
$text = "{$title}

 ".($details)."
 At: {$timestamp}

 \n";
$file = fopen("./data/column1.html","a+ \n");
 fwrite($file, $text);
 fclose($file);
?>
```

<p>Then on the page I want to show the submissions I use this;</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <p class="linktext"><?php echo file_get_contents("./data/column1.html"); ?></p></code>```

The CSS for my linktext class is this;

.linktext {
    font-family: 'Roboto', serif;
    font-size: 1vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 2vh;
    padding-right: 2vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}

@media only screen and (max-width: 500px) {
.linktext {
    font-family: 'Roboto', serif;
    font-size: 4vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 1vh;
    padding-right: 1vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}
}```
</div>
</div>
</p>

<p>For some reason the echo works fine for the first result but as soon as the second submission is sent, it won't be displayed correctly.</p>

<p>The file containing the responses looks like this after two submissions;</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Job Title 1<br><br> Job Details <br> At: Thursday 30th of May 2019 10:33:47 PM <br><br><hr><br>
Job Title 2<br><br> Job Details <br> At: Thursday 30th of May 2019 10:34:00 PM <br><br><hr><br> </code>```

But shows this;

I don't know why this has decided to not work given in other places, with the same type of form, the styling has worked just fine.

Any help would be appreciated on this because I'm stuck.

答:
Some notes for this code part:

```<code>$file = fopen("./data/column1.html","a+ \n");
fwrite($file, $text);
fclose($file);
</code>```

Attribute "a+ \n" is invalid. Use "a+" instead. And here you only writing. So "a" is perfect.

You do not any error management like

```<code>$file = fopen("./data/column1.html","a");
if (!$file)
{
    // error handling
}
else
{
    fwrite($file,$text);
    fclose($file);
}
</code>```

If using file_put_contents() the code becomes shorter:

```<code>if ( file_put_contents( "./data/column1.html", $text, FILE_APPEND ) === false )
{
    // error handling
}
</code>```

Body:
I have a simple form, like this;

        <form action="column1.php" method="post">
        <input type="text" placeholder="URL:" name="url" required="">

        <input type="text" placeholder="Job Title:" name="title" required="">

        <input type="text" placeholder="Job Site & Additional Details" name="details">

        <input type="submit">

        </form>

That form is then handled by column1.php which contains the following PHP;

<?php
$url = $_POST["url"];
$title = $_POST["title"];
$details = $_POST ["details"];
$timestamp =date('l jS \of F Y h:i:s A');
$text = "{$title}

 ".($details)."
 At: {$timestamp}

 \n";
$file = fopen("./data/column1.html","a+ \n");
 fwrite($file, $text);
 fclose($file);
?>

Then on the page I want to show the submissions I use this;

<?php echo file_get_contents("./data/column1.html"); ?>

The CSS for my linktext class is this;

.linktext {
    font-family: 'Roboto', serif;
    font-size: 1vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 2vh;
    padding-right: 2vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}

@media only screen and (max-width: 500px) {
.linktext {
    font-family: 'Roboto', serif;
    font-size: 4vw;
    text-align: center;
    margin-top: 0px;
    margin-bottom: 0px;
    color: #FFFFFF;
    padding-left: 1vh;
    padding-right: 1vh;
    padding-bottom: 0.5vh;
    line-height: 1em;
}
}

For some reason the echo works fine for the first result but as soon as the second submission is sent, it won't be displayed correctly.

The file containing the responses looks like this after two submissions;

Job Title 1

 Job Details
 At: Thursday 30th of May 2019 10:33:47 PM

Job Title 2

 Job Details
 At: Thursday 30th of May 2019 10:34:00 PM

But shows this;

I don't know why this has decided to not work given in other places, with the same type of form, the styling has worked just fine.

Any help would be appreciated on this because I'm stuck.

Body:
Some notes for this code part:

$file = fopen("./data/column1.html","a+ \n");
fwrite($file, $text);
fclose($file);

Attribute "a+ \n" is invalid. Use "a+" instead. And here you only writing. So "a" is perfect.

You do not any error management like

$file = fopen("./data/column1.html","a");
if (!$file)
{
    // error handling
}
else
{
    fwrite($file,$text);
    fclose($file);
}

If using file_put_contents() the code becomes shorter:

if ( file_put_contents( "./data/column1.html", $text, FILE_APPEND ) === false )
{
    // error handling
}


问:
In Vivado, how to instantiate a user defined "Block Diagram" inside of the top-level "Block Diagram"?
I've imported my VHDL code into a user defined Block Design, and I exported my I/O interfaces from this block design, now I need to instantiate this Block Design in the top level Block Design that contains the Xilinx Zynq Arm core and AXI interconnect.  When I right click on the Top-level Block Diagram, I see two choices:

"Add Module"
"Add IP"

neither of these two options lists the Block Design that I created to instantiate my VHDL code.  Any ideas on how to get this to work?

If you create a user defined Block Design, how can you instantiate it inside of another Block Design, specifically the top-level Block Design.

答: Compared to https://www.xilinx.com/support/answers/59355.html, it seems to now be in tools/create or package new ip/next/package a block design from the current project/...</p>


问:
Syntax Error (Expected an assignment or function call and instead saw an expression)
I've tried running the code:

```<code>var DETAIL_IMAGE_SELECTOR '[data-image-role="target"]';
var DETAIL_TITLE_SELECTOR '[data-image-role="title"]';
var THUMBNAIL_LINK_SELECTOR '[data-image-role="trigger"]';
</code>```

running it through JSHint and it says:

```<code>15  Missing semicolon.
15  Expected an assignment or function call and instead saw an expression.
16  Missing semicolon.
16  Expected an assignment or function call and instead saw an expression.
17  Missing semicolon.
17  Expected an assignment or function call and instead saw an expression.
</code>```

There's a semicolon after all the statements..... what gives?

答:
You need to assign the values to the variables:

(ie. use the = sign)

```<code>var DETAIL_IMAGE_SELECTOR = '[data-image-role="target"]';

var DETAIL_TITLE_SELECTOR = '[data-image-role="title"]';

var THUMBNAIL_LINK_SELECTOR = '[data-image-role="trigger"]';
</code>```

Body:
I've tried running the code:

var DETAIL_IMAGE_SELECTOR '[data-image-role="target"]';
var DETAIL_TITLE_SELECTOR '[data-image-role="title"]';
var THUMBNAIL_LINK_SELECTOR '[data-image-role="trigger"]';

running it through JSHint and it says:

15  Missing semicolon.
15  Expected an assignment or function call and instead saw an expression.
16  Missing semicolon.
16  Expected an assignment or function call and instead saw an expression.
17  Missing semicolon.
17  Expected an assignment or function call and instead saw an expression.

There's a semicolon after all the statements..... what gives?

Body:
You need to assign the values to the variables:

(ie. use the = sign)

var DETAIL_IMAGE_SELECTOR = '[data-image-role="target"]';

var DETAIL_TITLE_SELECTOR = '[data-image-role="title"]';

var THUMBNAIL_LINK_SELECTOR = '[data-image-role="trigger"]';


问:
Brain.js NaN training result
I am trying to train a network which as input takes a certain string that contains some predefined values which later i will pull from database or JSON.
I normalize the data by dividing the ACII value of each char by 1000 which leaves me with an array of values between 0 and 1 of each char of the input string. The error is that when i start the training i get training error : NaN, and the strange thing is that it work if i have only one input, bellow is the code.

```<code>var brain = require('brain.js');

function normalize(string){
  var input = [];
  for(let i=0; i<string.length; i++){
    input.push(string.charCodeAt(i)/1000);
  }
  return input;
}

function convert_ascii(ascii){
  var string = '';
  for(let i=0; i<ascii.length;i++){
    string += String.fromCharCode(ascii[i]*1000);
  }
  return string;
}

var string1 = normalize('Invoice Number IN-7688998788963');
var string2 = normalize('Invoice Date April 19, 2019');
var string3 =  normalize('Due Date May 3, 2019');
var string4 = normalize('Total Due $104.50');
var string5 = normalize('Sub Total $95.00');
var string6 = normalize('Tax $9.50');
const net = new brain.NeuralNetwork();
net.train([
  { input: string1, output: { invoice_num: 1 } },
  { input: string2, output: { date: 1 } },
  { input: string3, output: { due_date: 1 } },
  { input: string4, output: { total_due: 1 } },
  { input: string5, output: { sub_total: 1 } },
  { input: string6, output: { tax: 1 } }
], {
  log: detail => console.log(detail), iterations: 1500
});

let output = net.run(normalize('Invoice Number 1241341'));

console.log(output);
</code>```

Bellow code works:

```<code>var brain = require('brain.js');

function normalize(string){
  var input = [];
  for(let i=0; i<string.length; i++){
    input.push(string.charCodeAt(i)/1000);
  }
  return input;
}

function convert_ascii(ascii){
  var string = '';
  for(let i=0; i<ascii.length;i++){
    string += String.fromCharCode(ascii[i]*1000);
  }
  return string;
}

var string1 = normalize('Invoice Number IN-7688998788963');
var string2 = normalize('Invoice Date April 19, 2019');
var string3 =  normalize('Due Date May 3, 2019');
var string4 = normalize('Total Due $104.50');
var string5 = normalize('Sub Total $95.00');
var string6 = normalize('Tax $9.50');
const net = new brain.NeuralNetwork();
net.train([
  { input: string1, output: { invoice_num: 1 } }
], {
  log: detail => console.log(detail), iterations: 1500
});

let output = net.run(normalize('Invoice Number 1241341'));

console.log(output);
</code>```

答:
did you ever solve the NaN issue.  I am getting the same in the net.biases, net.changes, net.deltas etc... after training, and after run I always get NaN.

I am converting my string to numbers and then buffering the arrays to make them all the same length. I've seen examples where the text, as object key values, just gets sent straight into the train, but as soon as I come away from the example given and try my own data, NaN.

Interesting that in your 2nd example you are including the title in the normalized string, not just the data value. How does that effect things?

I realise this was some time ago, and you've probably moved on since then, but just perhaps you can shed some light and push me in the right direction before I go mad :-)

Title: Brain.js NaN training result

Body:
I am trying to train a network which as input takes a certain string that contains some predefined values which later i will pull from database or JSON.
I normalize the data by dividing the ACII value of each char by 1000 which leaves me with an array of values between 0 and 1 of each char of the input string. The error is that when i start the training i get training error : NaN, and the strange thing is that it work if i have only one input, bellow is the code.

var brain = require('brain.js');

function normalize(string){
  var input = [];
  for(let i=0; i<string.length; i++){
    input.push(string.charCodeAt(i)/1000);
  }
  return input;
}

function convert_ascii(ascii){
  var string = '';
  for(let i=0; i<ascii.length;i++){
    string += String.fromCharCode(ascii[i]*1000);
  }
  return string;
}

var string1 = normalize('Invoice Number IN-7688998788963');
var string2 = normalize('Invoice Date April 19, 2019');
var string3 =  normalize('Due Date May 3, 2019');
var string4 = normalize('Total Due $104.50');
var string5 = normalize('Sub Total $95.00');
var string6 = normalize('Tax $9.50');
const net = new brain.NeuralNetwork();
net.train([
  { input: string1, output: { invoice_num: 1 } },
  { input: string2, output: { date: 1 } },
  { input: string3, output: { due_date: 1 } },
  { input: string4, output: { total_due: 1 } },
  { input: string5, output: { sub_total: 1 } },
  { input: string6, output: { tax: 1 } }
], {
  log: detail => console.log(detail), iterations: 1500
});

let output = net.run(normalize('Invoice Number 1241341'));

console.log(output);

Bellow code works:

var brain = require('brain.js');

function normalize(string){
  var input = [];
  for(let i=0; i<string.length; i++){
    input.push(string.charCodeAt(i)/1000);
  }
  return input;
}

function convert_ascii(ascii){
  var string = '';
  for(let i=0; i<ascii.length;i++){
    string += String.fromCharCode(ascii[i]*1000);
  }
  return string;
}

var string1 = normalize('Invoice Number IN-7688998788963');
var string2 = normalize('Invoice Date April 19, 2019');
var string3 =  normalize('Due Date May 3, 2019');
var string4 = normalize('Total Due $104.50');
var string5 = normalize('Sub Total $95.00');
var string6 = normalize('Tax $9.50');
const net = new brain.NeuralNetwork();
net.train([
  { input: string1, output: { invoice_num: 1 } }
], {
  log: detail => console.log(detail), iterations: 1500
});

let output = net.run(normalize('Invoice Number 1241341'));

console.log(output);


问:
How to compare time between two variables
I am trying to compare the time difference between two variables.  $dt is a string pulled from the text of a log file.  $curtime is pulled from the current date and time.

If I output $dt, it displays correctly the date and time from the log files.  If I output $curtime, it displays correctly the date and time from the workstation.

But when I try and run New-TimeSpan and output the difference, my response is always "02:24:12".

Here is the code I am using:

```<code>New-TimeSpan $dt $curtime | Set-Variable -Name $TimeDiff
if ($TimeDiff.Seconds -lt 0) }
    $Hrs = ($TimeDiff.Hours) + 23
    $Mins = ($TimeDiff.Minutes) + 59
    $Secs = ($TimeDiff.Seconds) + 59 }
else {
    $Hrs = $TimeDiff.Hours
    $Mins = $TimeDiff.Minutes
    $Secs = $TimeDiff.Seconds }
$Difference = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs
$Difference
</code>```

答:
Unless he datetime from the logs are from a very narrow timespan,

it makes IMO no sense to manipulate by adding 23:59:59.

Better take the integer part from .TotalHours

Here returning hours > 24/99

```<code>$dt       = "05/26/19 08:23:37"
$LogDT    = [datetime]::parseexact($dt,"MM/dd/yy HH:mm:ss",[cultureInfo]::Invariantculture)
$TimeDiff = [datetime]::now - $LogDT
$Difference = '{0:00}:{1:00}:{2:00}' -f ([math]::floor($Timediff.TotalHours)),
                                        $Timediff.Minutes,$Timediff.Seconds
</code>```

Sample output:

```<code>> $Difference
111:16:17
</code>```

Body:
I am trying to compare the time difference between two variables.  $dt is a string pulled from the text of a log file.  $curtime is pulled from the current date and time.

If I output $dt, it displays correctly the date and time from the log files.  If I output $curtime, it displays correctly the date and time from the workstation.

But when I try and run New-TimeSpan and output the difference, my response is always "02:24:12".

Here is the code I am using:

New-TimeSpan $dt $curtime | Set-Variable -Name $TimeDiff
if ($TimeDiff.Seconds -lt 0) }
    $Hrs = ($TimeDiff.Hours) + 23
    $Mins = ($TimeDiff.Minutes) + 59
    $Secs = ($TimeDiff.Seconds) + 59 }
else {
    $Hrs = $TimeDiff.Hours
    $Mins = $TimeDiff.Minutes
    $Secs = $TimeDiff.Seconds }
$Difference = '{0:00}:{1:00}:{2:00}' -f $Hrs,$Mins,$Secs
$Difference

Body:
Unless he datetime from the logs are from a very narrow timespan,

it makes IMO no sense to manipulate by adding 23:59:59.

Better take the integer part from .TotalHours

Here returning hours > 24/99

$dt       = "05/26/19 08:23:37"
$LogDT    = [datetime]::parseexact($dt,"MM/dd/yy HH:mm:ss",[cultureInfo]::Invariantculture)
$TimeDiff = [datetime]::now - $LogDT
$Difference = '{0:00}:{1:00}:{2:00}' -f ([math]::floor($Timediff.TotalHours)),
                                        $Timediff.Minutes,$Timediff.Seconds

Sample output:

> $Difference
111:16:17


问:
redirect to CSS/JS files with partially known / partially unknown file names
Trying to use htaccess to redirect Googlebot from an incoming URL file request of this form:

v_3099_0726dd5b5e8dd67a214c0c243436d131_all.css

to a file of this form, where the four digits at 5028 are not known but are always four digits.

v_5028_0726dd5b5e8dd67a214c0c243436d131_all.css

I don't think this is possible with regex, because a catchcall regex for those four characters cannot be used in the target path.  In other words, Rewrite cannot be told, "go look in directory ____ for a file name that matches everything literally except those four characters, and match them with a regex catchall."

In RewriteCond, pattern matching with regex is only available in the right-hand side, in CondPattern, not in the left-hand side (test string) where one could have the false hope of using regex to match a file name on the server with -f flag and then using that regex grouping in a backreference in RewriteRule to accomplish the goal.  That strategy won't work.

In RewriteRule, pattern matching with regex is only available on the left-hand side, in Pattern of the incoming URL, so can't be used on the right-hand side to say, "go look in the directory ____ for a file that is the same except for these four unknown digits, and redirect to that file."  That strategy won't work, either.

Any ideas how to accomplish the goal stated at the top?  Thank you.

答:
I can't think of a way to do this in .htaccess alone. The file that you want to redirect/rewrite to must be "known". There's no way (in .htaccess) that I can see to scan a particular directory for a file that matches a particular pattern and return that instead (without the help of an external script).

(Aside: MultiViews allows a file with an essentially unknown extension to be served - but that's not the case here.)

You can potentially "test" the existence of various files before redirecting/rewriting to one of them, but with what looks like a "random" 4-digit number - that would be hopelessly inefficient.

However, what you could do is internally rewrite the request for such a file (that does not exist) to a server-side script (such as PHP). It would then be trivial (assuming there is just 1 file that should match this pattern) for this script to check for the "current" file and either redirect or return this file instead.

The .htaccess portion of this would be something like:

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^v_\d{4}_[0-9a-f]{32}_all\.css$ return-current-file.php [L]
</code>```

Body:
I can't think of a way to do this in .htaccess alone. The file that you want to redirect/rewrite to must be "known". There's no way (in .htaccess) that I can see to scan a particular directory for a file that matches a particular pattern and return that instead (without the help of an external script).

(Aside: MultiViews allows a file with an essentially unknown extension to be served - but that's not the case here.)

You can potentially "test" the existence of various files before redirecting/rewriting to one of them, but with what looks like a "random" 4-digit number - that would be hopelessly inefficient.

However, what you could do is internally rewrite the request for such a file (that does not exist) to a server-side script (such as PHP). It would then be trivial (assuming there is just 1 file that should match this pattern) for this script to check for the "current" file and either redirect or return this file instead.

The .htaccess portion of this would be something like:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^v_\d{4}_[0-9a-f]{32}_all\.css$ return-current-file.php [L]


问:
What is the correct HTML tag for content that has changed (but not added/deleted)?
I know I can use  to identify added content and  to identify deleted content. But what should I use to mark content that has changed, without further details on what was added or deleted?

For example:

Providing both added and deleted content (del/ins):

Cost: $10$20.
```

<p>Providing only new content, what to use to indicate that it has changed?</p>

<pre class="lang-html prettyprint-override"><code>Cost: <?>$20</?>.
</code>```

I thought about , but that does not quite work as  adds semantics not intended by the original author, but in this case I do intend to mark it as changed when authoring.

答:
The s element represents contents that are no longer accurate or no
  longer relevant.

From https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-s-element

Buy our Iced Tea and Lemonade!

<s>Recommended retail price: $3.99 per bottle</s>

Now selling for just $2.99 a bottle!
```

The s element is not appropriate when indicating document edits; to
  mark a span of text as having been removed from a document, use the
  del element.

Body:
I know I can use  to identify added content and  to identify deleted content. But what should I use to mark content that has changed, without further details on what was added or deleted?

For example:

Providing both added and deleted content (del/ins):

Cost: $10$20.

Providing only new content, what to use to indicate that it has changed?

Cost: <?>$20</?>.

I thought about , but that does not quite work as  adds semantics not intended by the original author, but in this case I do intend to mark it as changed when authoring.

Body:
The s element represents contents that are no longer accurate or no
  longer relevant.

From https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-s-element

<p>Buy our Iced Tea and Lemonade!</p>
<p><s>Recommended retail price: $3.99 per bottle</s></p>
<p><strong>Now selling for just $2.99 a bottle!</strong></p>

The s element is not appropriate when indicating document edits; to
  mark a span of text as having been removed from a document, use the
  del element.


问:
java-jwt with public/private keys
Auth0 provides two JWT libraries, one for Node: node-jsonwebtoken, and one for Java: java-jwt.

I created the private/public key pair, and used it successfully in Node with node-jsonwebtoken:

```<code>var key = fs.readFileSync('private.key');
var pem = fs.readFileSync('public.pem');

var header = {...};
var payload = {...};

header.algorithm = "RS256";
var message = jsonwebtoken.sign(payload, key, header);
var decoded = jsonwebtoken.verify(message, pem, {algorithm: "RS256"});
</code>```

But I found no way of doing the same in Java with java-jwt.

Anyone has a working example of how to use private/public keys for JWT in Java?

答:
Recent versions (since 3.0.0) of the auth0 java-jwt library supports RSA and ECDSA for signing JWT tokens using a public/private key pair.

Example of signing a JWT using java-jwt (based on the documentation).

```<code>import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

class JwtPKSigningExample {
    public static void main(String[] args) throws Exception {
        Map<String, Object> keys = generateRSAKeys();

        String token = null;
        try {
            RSAPrivateKey privateKey = (RSAPrivateKey) keys.get("private");
            Algorithm algorithm = Algorithm.RSA256(null, privateKey);
            token = JWT.create()
                    .withIssuer("pk-signing-example")
                    .sign(algorithm);
        } catch (JWTCreationException x) {
            throw x;
        }

        try {
            RSAPublicKey publicKey = (RSAPublicKey) keys.get("public");
            Algorithm algorithm = Algorithm.RSA256(publicKey, null);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("pk-signing-example")
                    .build();
            DecodedJWT jwt = verifier.verify(token);

            System.out.println(jwt.getToken());
        } catch (JWTVerificationException x) {
            throw x;
        }
    }

    private static Map<String, Object> generateRSAKeys() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return Map.of("private", keyPair.getPrivate(), "public", keyPair.getPublic());
    }
}
</code>```

Title: java-jwt with public/private keys

Body:
Auth0 provides two JWT libraries, one for Node: node-jsonwebtoken, and one for Java: java-jwt.

I created the private/public key pair, and used it successfully in Node with node-jsonwebtoken:

var key = fs.readFileSync('private.key');
var pem = fs.readFileSync('public.pem');

var header = {...};
var payload = {...};

header.algorithm = "RS256";
var message = jsonwebtoken.sign(payload, key, header);
var decoded = jsonwebtoken.verify(message, pem, {algorithm: "RS256"});

But I found no way of doing the same in Java with java-jwt.

Anyone has a working example of how to use private/public keys for JWT in Java?

Body:
Recent versions (since 3.0.0) of the auth0 java-jwt library supports RSA and ECDSA for signing JWT tokens using a public/private key pair.

Example of signing a JWT using java-jwt (based on the documentation).

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

class JwtPKSigningExample {
    public static void main(String[] args) throws Exception {
        Map<String, Object> keys = generateRSAKeys();

        String token = null;
        try {
            RSAPrivateKey privateKey = (RSAPrivateKey) keys.get("private");
            Algorithm algorithm = Algorithm.RSA256(null, privateKey);
            token = JWT.create()
                    .withIssuer("pk-signing-example")
                    .sign(algorithm);
        } catch (JWTCreationException x) {
            throw x;
        }

        try {
            RSAPublicKey publicKey = (RSAPublicKey) keys.get("public");
            Algorithm algorithm = Algorithm.RSA256(publicKey, null);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("pk-signing-example")
                    .build();
            DecodedJWT jwt = verifier.verify(token);

            System.out.println(jwt.getToken());
        } catch (JWTVerificationException x) {
            throw x;
        }
    }

    private static Map<String, Object> generateRSAKeys() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return Map.of("private", keyPair.getPrivate(), "public", keyPair.getPublic());
    }
}


问:
How to join two queries while keeping "City" as common filter for first column
I am trying to join these two separate queries. Each of them on its own works. One is for 2019 and one is for 2018.. I am trying to have 7 total columns. The first being "city" which is where the two queries both share and then 6 more columns (3 for 2019 & 3 for 2018). Thank you for your help!

I've tried using join and union, but I believe my syntax is off

```<code>select  coalesce(city, 'Total') as "City",
    sum(reservations.number_of_nights) as "2019 AAA",
    sum(reservations.accommodation_fare+reservations.cleaning_fee)/sum(reservations.number_of_nights) as "2019 BBB",
    sum(reservations.accommodation_fare+reservations.cleaning_fee) as "2019 CCC"
    from reservations
        join listings on reservations.listings_id = listings.id
        where status = 'YYYY'
        and city <> 'XXXX'
        and reservations.deleted_at is null
            group by rollup(city)
            order by city asc;

select  coalesce(city, 'Total') as "City",
    sum(reservations.number_of_nights) as "2018 AAA",
    sum(reservations.accommodation_fare+reservations.cleaning_fee)/sum(reservations.number_of_nights) as "2018 BBB",
    sum(reservations.accommodation_fare+reservations.cleaning_fee) as "2018 CCC"
    from reservations
        join listings on reservations.listings_id = listings.id
        where guesty_status = 'YYYY'
        and city <> 'XXXX'
        and reservations.deleted_at is null
            group by rollup(city)
            order by city asc;
</code>```

答:
So the two queries are essentially the same, except that one has data for 2018 and one has data for 2019.  I would suggest adding the year as a column (and removing the year from your existing column names) and then performing a UNION ALL to join them.

```<code>SELECT [City], 2018 as [Year of Data], [AAA], [BBB], [CCC]
FROM ...  -- finish this with the 2018 query stuff.

UNION ALL

SELECT [City], 2019 as [Year of Data], [AAA], [BBB], [CCC]
FROM ...  -- finish this with the 2019 query stuff.
</code>```

Now, I suspect that these two queries can actually be rewritten as a single query, but since I don't actually see any difference in the two queries except the artificial column naming ([2018 AAA] vs [2019 AAA]) I can't be certain that you're not running this query against two separate databases; one for 2018 and one for 2019.

Body:
I am trying to join these two separate queries. Each of them on its own works. One is for 2019 and one is for 2018.. I am trying to have 7 total columns. The first being "city" which is where the two queries both share and then 6 more columns (3 for 2019 & 3 for 2018). Thank you for your help!

I've tried using join and union, but I believe my syntax is off

select  coalesce(city, 'Total') as "City",
    sum(reservations.number_of_nights) as "2019 AAA",
    sum(reservations.accommodation_fare+reservations.cleaning_fee)/sum(reservations.number_of_nights) as "2019 BBB",
    sum(reservations.accommodation_fare+reservations.cleaning_fee) as "2019 CCC"
    from reservations
        join listings on reservations.listings_id = listings.id
        where status = 'YYYY'
        and city <> 'XXXX'
        and reservations.deleted_at is null
            group by rollup(city)
            order by city asc;

select  coalesce(city, 'Total') as "City",
    sum(reservations.number_of_nights) as "2018 AAA",
    sum(reservations.accommodation_fare+reservations.cleaning_fee)/sum(reservations.number_of_nights) as "2018 BBB",
    sum(reservations.accommodation_fare+reservations.cleaning_fee) as "2018 CCC"
    from reservations
        join listings on reservations.listings_id = listings.id
        where guesty_status = 'YYYY'
        and city <> 'XXXX'
        and reservations.deleted_at is null
            group by rollup(city)
            order by city asc;

Body:
So the two queries are essentially the same, except that one has data for 2018 and one has data for 2019.  I would suggest adding the year as a column (and removing the year from your existing column names) and then performing a UNION ALL to join them.

SELECT [City], 2018 as [Year of Data], [AAA], [BBB], [CCC]
FROM ...  -- finish this with the 2018 query stuff.

UNION ALL

SELECT [City], 2019 as [Year of Data], [AAA], [BBB], [CCC]
FROM ...  -- finish this with the 2019 query stuff.

Now, I suspect that these two queries can actually be rewritten as a single query, but since I don't actually see any difference in the two queries except the artificial column naming ([2018 AAA] vs [2019 AAA]) I can't be certain that you're not running this query against two separate databases; one for 2018 and one for 2019.


问:
Get word before and after dash '-' for multiple occurrences in a string
I am trying to parse foreign (Korean) addresses. Often the address would look like something like

```<code>Seoul, Gangnam-gu, South Korea
</code>```

I want to be able to extract out: Gangnam-gu - Basically the word preceeding and proceeding the dash.

But there are times when there may be something like this

```<code>Seoul, Itaewon-dong, Gangnam-gu, South Korea
</code>```

So in this case, I would want to be able to extract out BOTH: Itaewon-dong AND Gangnam-gu

I know that with REGEX I could pull out both words around the dash (-), though Im not sure how. And on top of that I dont know how to pull all the occurences.

答:
this could serve:

```<code>([a-zA-Z]+)-([a-zA-Z]+)
</code>```

Cheers

Body:
I am trying to parse foreign (Korean) addresses. Often the address would look like something like

Seoul, Gangnam-gu, South Korea

I want to be able to extract out: Gangnam-gu - Basically the word preceeding and proceeding the dash.

But there are times when there may be something like this

Seoul, Itaewon-dong, Gangnam-gu, South Korea

So in this case, I would want to be able to extract out BOTH: Itaewon-dong AND Gangnam-gu

I know that with REGEX I could pull out both words around the dash (-), though Im not sure how. And on top of that I dont know how to pull all the occurences.

Body:
this could serve:

([a-zA-Z]+)-([a-zA-Z]+)

Cheers


答:
To assign a value to a variable you must use the equal sign ('=').

For example :

```<code>var a = 'hello world!';
</code>```

Also, you should consider using 'let' and 'const' instead of 'var'. Finally, although it's not a mistake, you should generally use camelCase in JS.

Title: Syntax Error (Expected an assignment or function call and instead saw an expression)

Body:
To assign a value to a variable you must use the equal sign ('=').

For example :

var a = 'hello world!';

Also, you should consider using 'let' and 'const' instead of 'var'. Finally, although it's not a mistake, you should generally use camelCase in JS.