问:
Opencart Empty Cart Problem When İ Log in the site
I m adding some product to cart but my problem is starting when i log in the site my cart is empty</p>

答:
So the issue is with your session in system/library/cart/cart.php

After you have logged in, the customer class is initiated and the __construct method runs.

on line 22 of the file system/library/cart/cart.php you can see how it works:

// this code queries the current cart of your session id. so before you were logged int, your cart was saved to the database under a session id.
$cart_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "cart WHERE api_id = '0' AND customer_id = '0' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");

//after it finds your card products, it adds them to your CUSTOMER id.
foreach ($cart_query->rows as $cart) {
    $this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart['cart_id'] . "'");

    // The advantage of using $this->add is that it will check if the products already exist and increaser the quantity if necessary.
    $this->add($cart['product_id'], $cart['quantity'], json_decode($cart['option']), $cart['recurring_id']);
}
```

<p>So the reason for not populating your cart after login is because in that session. It could be that some part of your code deletes the $this->session->getId() so the script can't find any products in cart.</p>

<p>To debug this just print_r the session_id and the results like this</p>

<pre class="lang-php prettyprint-override"><code>//print out the session id.
print_r($this->session->getId());
$cart_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "cart WHERE api_id = '0' AND customer_id = '0' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");

//print out the result of the query
print_r($cart_query->rows);
foreach ($cart_query->rows as $cart) {
    $this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart['cart_id'] . "'");

    // The advantage of using $this->add is that it will check if the products already exist and increaser the quantity if necessary.
    $this->add($cart['product_id'], $cart['quantity'], json_decode($cart['option']), $cart['recurring_id']);
}

</code>```

to see that is in there. if it is empty, you will need to dig deeper to see who is deleting it.

if it is populated, visit the phpmyadmin table oc_cart to check to find the records of the session_id=$this->session->getId() and try to find out why it is not returning the cart products.

hope this helps.

Body:
So the issue is with your session in system/library/cart/cart.php

After you have logged in, the customer class is initiated and the __construct method runs.

on line 22 of the file system/library/cart/cart.php you can see how it works:

// this code queries the current cart of your session id. so before you were logged int, your cart was saved to the database under a session id.
$cart_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "cart WHERE api_id = '0' AND customer_id = '0' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");

//after it finds your card products, it adds them to your CUSTOMER id.
foreach ($cart_query->rows as $cart) {
    $this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart['cart_id'] . "'");

    // The advantage of using $this->add is that it will check if the products already exist and increaser the quantity if necessary.
    $this->add($cart['product_id'], $cart['quantity'], json_decode($cart['option']), $cart['recurring_id']);
}

So the reason for not populating your cart after login is because in that session. It could be that some part of your code deletes the $this->session->getId() so the script can't find any products in cart.

To debug this just print_r the session_id and the results like this

//print out the session id.
print_r($this->session->getId());
$cart_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "cart WHERE api_id = '0' AND customer_id = '0' AND session_id = '" . $this->db->escape($this->session->getId()) . "'");

//print out the result of the query
print_r($cart_query->rows);
foreach ($cart_query->rows as $cart) {
    $this->db->query("DELETE FROM " . DB_PREFIX . "cart WHERE cart_id = '" . (int)$cart['cart_id'] . "'");

    // The advantage of using $this->add is that it will check if the products already exist and increaser the quantity if necessary.
    $this->add($cart['product_id'], $cart['quantity'], json_decode($cart['option']), $cart['recurring_id']);
}

to see that is in there. if it is empty, you will need to dig deeper to see who is deleting it.

if it is populated, visit the phpmyadmin table oc_cart to check to find the records of the session_id=$this->session->getId() and try to find out why it is not returning the cart products.

hope this helps.


来源: stackexchange

问:
How to make Vue material select box showing option when the default value is empty?
I am using the vuematerial for material design framework under vue.js.

For normal HTML, let say I have a selection box like this:

<select>
    <option value="">You should initially see this</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>```
</div>
</div>
</p>

<p>When you run the script, initially you should see a selection box with the
text "You should initially see this"</p>

<p>However, when I am using vuematerial to do something similar:</p>

```<template>

        <md-field>
          <md-select v-model="movie" name="movie" id="movie">
            <md-option value="">Default film</md-option>
            <md-option value="fight-club">Fight Club</md-option>
            <md-option value="godfather">Godfather</md-option>
            <md-option value="godfather-ii">Godfather II</md-option>
            <md-option value="godfather-iii">Godfather III</md-option>
            <md-option value="godfellas">Godfellas</md-option>
            <md-option value="pulp-fiction">Pulp Fiction</md-option>
            <md-option value="scarface">Scarface</md-option>
          </md-select>
        </md-field>

</template>

```

Demo link

I would expect to see a select box with "Default film" chosen, instead of a blank select box. I noticed that by setting the value of the first option box to be something other then an empty string (e.g. -1) solves the problem, but for my actual case I need the default value to be an empty string, so this workaround is not applicable to me. With that in mind, is there a way I can make the value to be shown initially?

答:
That's not how it works with vue-mdc.
According to the docs on https://stasson.github.io/vue-mdc-adapter/#/component/select
you need to set the label prop of md-select to display a default</p>

ContentLicense: CC BY-SA 4.0

Body:
I am using the vuematerial for material design framework under vue.js.

For normal HTML, let say I have a selection box like this:

<select>
    <option value="">You should initially see this</option>
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

When you run the script, initially you should see a selection box with the
text "You should initially see this"

However, when I am using vuematerial to do something similar:

<template>

        <md-field>
          <md-select v-model="movie" name="movie" id="movie">
            <md-option value="">Default film</md-option>
            <md-option value="fight-club">Fight Club</md-option>
            <md-option value="godfather">Godfather</md-option>
            <md-option value="godfather-ii">Godfather II</md-option>
            <md-option value="godfather-iii">Godfather III</md-option>
            <md-option value="godfellas">Godfellas</md-option>
            <md-option value="pulp-fiction">Pulp Fiction</md-option>
            <md-option value="scarface">Scarface</md-option>
          </md-select>
        </md-field>

</template>

Demo link

I would expect to see a select box with "Default film" chosen, instead of a blank select box. I noticed that by setting the value of the first option box to be something other then an empty string (e.g. -1) solves the problem, but for my actual case I need the default value to be an empty string, so this workaround is not applicable to me. With that in mind, is there a way I can make the value to be shown initially?


问:
How to install the Inspect tool on Windows 10?
Is Inspect a part of the Windows 10 standalone SDK?

Is there any alternative application to "inspect" for windows 10?
I want to install "inspect" tool on my machine running windows 10 build 10586 (for testing purpose).
According to Inspect documentation on MSDN it is not described if it is a part of win 10 sdk also or only upto win 8.1.
Also is there any alternative tool for "Inspect" to debug on windows 10?

答: Inspect is available here: C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64. Based on version changes you can find it in one of the versions under the x64 folder.

ContentLicense: CC BY-SA 3.0


问:
Retrieving the Legal prose attached with a contract
How the legal prose attached with contract can be retrieved from the receiving node side</p>

答:
Assuming you have attached a file to a transaction that you want to open on the side of the receiving node, you can use the following code:</p>

```<code>val ids: List<AttachmentId> = serviceHub.attachments.queryAttachments(
  AttachmentQueryCriteria.AttachmentsQueryCriteria(
    filenameCondition = Builder.equal("some name")
  )
)
val attachments: List<Attachment?> = ids.map { id -> serviceHub.attachments.openAttachment(id) }
</code>```

Body:
Assuming you have attached a file to a transaction that you want to open on the side of the receiving node, you can use the following code:

val ids: List<AttachmentId> = serviceHub.attachments.queryAttachments(
  AttachmentQueryCriteria.AttachmentsQueryCriteria(
    filenameCondition = Builder.equal("some name")
  )
)
val attachments: List<Attachment?> = ids.map { id -> serviceHub.attachments.openAttachment(id) }


问:
How can I create and alter a new string[][] without altering the original?
I know this is an issue being caused by passing by reference rather than value, but I'm not sure what I need to do to fix it.

I have a field variable string[][] _cubeState which represents the state of a 2x2 Rubiks cube. This jagged array represents the state of the cube before any rotations take place and should be updated after every rotation, but only after my rotate method has returned and overwritten it.

What is actually happening is that when I get to the newCube[0][index] = _cubeState[0][index + 10]; line, this line updates both my newCube array and my original _cubeState array. Since the newCube is referencing cubeState it's also updating the original. How do I fix this so that the cubeState will only update after the method has returned?

```<code>private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}
</code>```

答:
You can't copy a jagged array like this:

```<code>string[][] newCube = { _cubeState[0], _cubeState[1] };
</code>```

You are not actually copying the inner arrays.

To copy the inner arrays, you can use Array.Copy. One way to do this is this:

```<code>var newCubeState = new string[_cubeState.Length][];
for (int i = 0 ; i < _cubeState.Length ; i++) {
    string[] inner = new string[_cubeState[i].Length];
    Array.Copy(_cubeState[i], inner, _cubeState[i].Length);
    newCubeState[i] = inner;
}
</code>```

Body:
I know this is an issue being caused by passing by reference rather than value, but I'm not sure what I need to do to fix it.

I have a field variable string[][] _cubeState which represents the state of a 2x2 Rubiks cube. This jagged array represents the state of the cube before any rotations take place and should be updated after every rotation, but only after my rotate method has returned and overwritten it.

What is actually happening is that when I get to the newCube[0][index] = _cubeState[0][index + 10]; line, this line updates both my newCube array and my original _cubeState array. Since the newCube is referencing cubeState it's also updating the original. How do I fix this so that the cubeState will only update after the method has returned?

private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}

Body:
You can't copy a jagged array like this:

string[][] newCube = { _cubeState[0], _cubeState[1] };

You are not actually copying the inner arrays.

To copy the inner arrays, you can use Array.Copy. One way to do this is this:

var newCubeState = new string[_cubeState.Length][];
for (int i = 0 ; i < _cubeState.Length ; i++) {
    string[] inner = new string[_cubeState[i].Length];
    Array.Copy(_cubeState[i], inner, _cubeState[i].Length);
    newCubeState[i] = inner;
}


问:
How do you format a Date/Time in TypeScript?
I've been having some trouble trying to get a Date object in TypeScript to format the way I want it to.

I have a class Module which is defined as:

```<code>export class Module {

    constructor(public id: number, public name: string, public description: string,
                 public lastUpdated: Date, public owner: string) { }

    getNiceLastUpdatedTime(): String {

        let options: Intl.DateTimeFormatOptions = {
            day: "numeric", month: "numeric", year: "numeric",
            hour: "2-digit", minute: "2-digit"
        };

        return this.lastUpdated.toLocaleDateString("en-GB", options) + " " + this.lastUpdated.toLocaleTimeString("en-GB", options);
    }
}
</code>```

When I call the method with the following code:

```<code>    let date = new Date(1478708162000); // 09/11/2016 16:16pm (GMT)
    let module = new Module(1, "Test", "description", date, "test owner");
    console.log(module.getNiceLastUpdatedTime());
</code>```

I end up with the following printed in the console:

```<code>'9 November 2016 16:16:02 GMT'
</code>```

What I want to see is:

```<code>09/11/2015 16:16
</code>```

I've had a look at the documentation at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString  and I still can't see what I'm doing wrong (I know this is a JavaScript API documentation but I'm pretty sure that's what TypeScript is using under the hood).

答:
```<code>function _formatDatetime(date: Date, format: string) {
   const _padStart = (value: number): string => value.toString().padStart(2, '0');
return format
    .replace(/yyyy/g, _padStart(date.getFullYear()))
    .replace(/dd/g, _padStart(date.getDate()))
    .replace(/mm/g, _padStart(date.getMonth() + 1))
    .replace(/hh/g, _padStart(date.getHours()))
    .replace(/ii/g, _padStart(date.getMinutes()))
    .replace(/ss/g, _padStart(date.getSeconds()));
}
function isValidDate(d: Date): boolean {
    return !isNaN(d.getTime());
}
export function formatDate(date: any): string {
    var datetime = new Date(date);
    return isValidDate(datetime) ? _formatDatetime(datetime, 'yyyy-mm-dd hh:ii:ss') : '';
}
</code>```

Body:
I've been having some trouble trying to get a Date object in TypeScript to format the way I want it to.

I have a class Module which is defined as:

export class Module {

    constructor(public id: number, public name: string, public description: string,
                 public lastUpdated: Date, public owner: string) { }

    getNiceLastUpdatedTime(): String {

        let options: Intl.DateTimeFormatOptions = {
            day: "numeric", month: "numeric", year: "numeric",
            hour: "2-digit", minute: "2-digit"
        };

        return this.lastUpdated.toLocaleDateString("en-GB", options) + " " + this.lastUpdated.toLocaleTimeString("en-GB", options);
    }
}

When I call the method with the following code:

    let date = new Date(1478708162000); // 09/11/2016 16:16pm (GMT)
    let module = new Module(1, "Test", "description", date, "test owner");
    console.log(module.getNiceLastUpdatedTime());

I end up with the following printed in the console:

'9 November 2016 16:16:02 GMT'

What I want to see is:

09/11/2015 16:16

I've had a look at the documentation at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString  and I still can't see what I'm doing wrong (I know this is a JavaScript API documentation but I'm pretty sure that's what TypeScript is using under the hood).


问:
Does redux thunk wait until all earlier dispatched actions modified the store?
```<code>handleDeleteClick = propertyName => () => {
  this.props.clearFilterOption(propertyName, this.props.filtersPropertyName);
  this.props.onFilterClear();
};
</code>```

handleDeleteClick function is a button handler. My first redux action clearFilterOption modifies the store. The second action onFilterClear is the asynchronous action that maps filter params from redux-thunk's getState and calls api. My question is - does redux thunk wait for earlier dispatched action that modifies the store? In other words - do I have a certainty that the second action will fire with the most recent store version?

For now it works as expected. The second action fires with cleared filter option. But I don't know if it's because I'm using redux-thunk, or because clearFilterOption for now, is a low cost function.

答:
The Thunk middleware doesn't 'wait' as such, all it does is looks at the action that's been dispatched, and if it's a function it calls it.

The order that your store is modified is governed by your actions and whether they're asynchronous or not.

In your case, if your first action clearFilterOption is synchronous then it will always update the store before the second action is dispatched. If it isn't synchronous then it depends on the timings of whatever is happening within your Thunks.

If you always need one thing to occur before the other you should chain your actions (as Thunks) rather than dispatching them sequentially in your handleDeleteClick.

Body:
handleDeleteClick = propertyName => () => {
  this.props.clearFilterOption(propertyName, this.props.filtersPropertyName);
  this.props.onFilterClear();
};

handleDeleteClick function is a button handler. My first redux action clearFilterOption modifies the store. The second action onFilterClear is the asynchronous action that maps filter params from redux-thunk's getState and calls api. My question is - does redux thunk wait for earlier dispatched action that modifies the store? In other words - do I have a certainty that the second action will fire with the most recent store version?

For now it works as expected. The second action fires with cleared filter option. But I don't know if it's because I'm using redux-thunk, or because clearFilterOption for now, is a low cost function.


问:
programming a contest based on cupon codes in drupal
Is there any module that can ask upon user registration so that the user can have a cupon code?
I want to use them later to draw prizes.
Just like a lottery</p>

答: Have you give a try to Registration code? It sounds like it could do the job that you are asking for.</p>


问:
Reset progress bar after form submit using jQuery
I have a progress bar on a form which works fine but I need to reset its value after the file as been upload.

My code:

```<code><div class="bar-position">
  <div class="col-md-14 col-md-14 progress-container">
    <div class="progress progress-striped active">
      <div class="progress-bar progress-bar-success" style="width:0%"></div>
    </div>
  </div>
</div>
</code>```

I have tried using this after the file upload but it does not work:

```<code>$('.progress').val(0);
</code>```

Where am I going wrong? I have looked at a number of posts but I can't find a solution that will work with my code.

答:
You can simply do that:

```<code>$('.progress-bar').attr('style', "width: 0%");
</code>```

Here the snippet:

$('#reset').on('click', function (e) {
    $('.progress-bar').attr('style', "width: 0%");
});
$('#upload').on('click', function (e) {
    $('.progress-bar').attr('style', "width: 100%");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    margin: 10px;
}</code>```

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

  <button id="upload" type="button" class="btn btn-primary">Upload</button>
  <button id="reset" type="button" class="btn btn-primary">Reset</button>

```

Body:
I have a progress bar on a form which works fine but I need to reset its value after the file as been upload.

My code:

I have tried using this after the file upload but it does not work:

$('.progress').val(0);

Where am I going wrong? I have looked at a number of posts but I can't find a solution that will work with my code.

Body:
You can simply do that:

$('.progress-bar').attr('style', "width: 0%");

Here the snippet:

$('#reset').on('click', function (e) {
    $('.progress-bar').attr('style', "width: 0%");
});
$('#upload').on('click', function (e) {
    $('.progress-bar').attr('style', "width: 100%");
});

body {
    margin: 10px;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bar-position">
  <div class="col-md-14 col-md-14 progress-container">
    <div class="progress progress-striped active">
      <div class="progress-bar progress-bar-success" style="width:100%"></div>
    </div>
  </div>
  <button id="upload" type="button" class="btn btn-primary">Upload</button>
  <button id="reset" type="button" class="btn btn-primary">Reset</button>
</div>


问:
Azure App Service - bandwidth limitations?
In our development environment (in Azure) we are experiencing an issue which we are sure could be due to bandwidth limitations of the underlying VM. By scaling our App Service up a pricing level (from Basic to Standard), the issue stops occurring. Utilisation of the CPU, memory, connection, threads, are all very low.

What are the actual network/bandwidth limitations for the different Azure App Service tiers?

These pages provide nothing on the matter:

Azure Web App sandbox

Azure subscription and service limits, quotas, and constraints

答: Less than 200MB daily, about 5GB per month</p>


问:
Starting value in optimization algorithms
I am trying to use the L-BFGS solver in Accord.net maths package in C#.
However, I cannot find how to define the starting value of the optimization.
How can we define it ?

According to official examples, the following syntax defines the initial value of x in the optimization process. However it does not work properly in the following example - as if another starting point was used by the algorithm.

```<code>
//Target function to minimize;
public double f(double[] x) {
   double z = Math.Cos(x[0])-0.2*x[0] + x[1] * x[1]; //Function with multiple local minima : x ~ { (2n+1)pi , 0 }
   return z;
  }

//Gradient
  public double[] g(double[] x) {
      double[] grad = {-Math.Sin(x[0])-0.2 , 2 * x[1]};
      return grad;
  }

  double[] x = {3*3.141592,0}; // Starting value (local minimum, -2.88)

  var lbfgs = new BroydenFletcherGoldfarbShanno(numberOfVariables: 2, function: f, gradient: g);

  bool success = lbfgs.Minimize();
  double minValue = lbfgs.Value;
  double[] solution = lbfgs.Solution; // {3.34,0} This solution is a local min that has a higher value (-1.65) than the local min next to which we started !!
</code>```

答:
The syntax is simply:
lbfgs.Minimize(x);
Thank you "500 - Internal Server Error" !</p>

Body:
I am trying to use the L-BFGS solver in Accord.net maths package in C#.
However, I cannot find how to define the starting value of the optimization.
How can we define it ?

According to official examples, the following syntax defines the initial value of x in the optimization process. However it does not work properly in the following example - as if another starting point was used by the algorithm.

//Target function to minimize;
public double f(double[] x) {
   double z = Math.Cos(x[0])-0.2*x[0] + x[1] * x[1]; //Function with multiple local minima : x ~ { (2n+1)pi , 0 }
   return z;
  }

//Gradient
  public double[] g(double[] x) {
      double[] grad = {-Math.Sin(x[0])-0.2 , 2 * x[1]};
      return grad;
  }

  double[] x = {3*3.141592,0}; // Starting value (local minimum, -2.88)

  var lbfgs = new BroydenFletcherGoldfarbShanno(numberOfVariables: 2, function: f, gradient: g);

  bool success = lbfgs.Minimize();
  double minValue = lbfgs.Value;
  double[] solution = lbfgs.Solution; // {3.34,0} This solution is a local min that has a higher value (-1.65) than the local min next to which we started !!


问:
Connect on-prem jypyter notebook to mlflow tracking server in Azure
Is it possible to connect a notebook running in premises to an mlflow Tracking server that is part of an Azure Databricks workspace? Have all the local logging and tracking saved in Azure?</p>

答:
I had a similar problem, used python and solved it with the following steps:

Install mlflow and datbricks-cli libraries.

Define the following env variables : DATABRICKS_HOST (databricks workspace url: https://region.azuredatabricks.net) and DATABRICKS_TOKEN

Define mlflow client:

mlflow_client = mlflow.tracking.MlflowClient(tracking_uri='databricks')
```

Use mlflow_client client for logging, saving and etc..

for more reference you can look at the "Log to a tracking server from a notebook" section here

Body:
I had a similar problem, used python and solved it with the following steps:

Install mlflow and datbricks-cli libraries.

Define the following env variables : DATABRICKS_HOST (databricks workspace url: https://region.azuredatabricks.net) and DATABRICKS_TOKEN

Define mlflow client:

mlflow_client = mlflow.tracking.MlflowClient(tracking_uri='databricks')

Use mlflow_client client for logging, saving and etc..

for more reference you can look at the "Log to a tracking server from a notebook" section here


问:
What are the ways to pass threadpoolexecutor to CompletableFuture?
I have been working on Java CompletableFuture lately and found , we should always use customized Threadpool. With it, I found two ways of passing threadpool to existing code. Like below

This is my ThreadPool in configuration file

```<code>@Override
@Bean(name = "commonThreadPool")
public Executor getAsyncExecutor() {
  return new ThreadPoolTaskExecutor();
}
</code>```

1. Passing existingThreadPool in argument.

```<code> @Autowired
 @Qualifier("commonThreadPool")
 TaskExecutor existingThreadPool;
 CompletableFuture.runAsync(() -> executeTask(),existingThreadPool);
</code>```

2. Using async like below

```<code>@Async("commonThreadPool")
public void executeTask() {
// Execute Some Task
}
</code>```

is there any third way where I can write CompletableFuture Handler or Override its existing behaviour at single place where I can pass custom Threadpool. And after that wherever I use below code, it should pick my existing ThreadPool instead of forkJoin pool.

```<code> CompletableFuture.runAsync(() -> executeTask());
</code>```

答:
There is no standard way for replacing the default executor for all CompletableFuture instances. But since Java 9, you can define a default executor for subclasses. E.g. with

```<code>public class MyCompletableFuture<T> extends CompletableFuture<T> {
    static final Executor EXEC = r -> {
        System.out.println("executing "+r);
        new Thread(r).start();
    };

    @Override
    public Executor defaultExecutor() {
        return EXEC;
    }

    @Override
    public <U> CompletableFuture<U> newIncompleteFuture() {
        return new MyCompletableFuture<>();
    }

    public static CompletableFuture<Void> runAsync(Runnable runnable) {
        Objects.requireNonNull(runnable);
        return supplyAsync(() -> {
            runnable.run();
            return null;
        });
    }

    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return new MyCompletableFuture<U>().completeAsync(supplier);
    }
}
</code>```

you did all necessary steps for defining the default executor for all chained stages of the MyCompletableFuture. The executor hold in EXEC only serves as an example, producing a printout when used, so when you use that example class like

```<code>MyCompletableFuture.supplyAsync(() -> "test")
    .thenApplyAsync(String::toUpperCase)
    .thenAcceptAsync(System.out::println);
</code>```

it will print

```<code>executing java.util.concurrent.CompletableFuture$AsyncSupply@65ab7765
executing java.util.concurrent.CompletableFuture$UniApply@119d7047
executing java.util.concurrent.CompletableFuture$UniAccept@404b9385
TEST
</code>```

Body:
I have been working on Java CompletableFuture lately and found , we should always use customized Threadpool. With it, I found two ways of passing threadpool to existing code. Like below

This is my ThreadPool in configuration file

@Override
@Bean(name = "commonThreadPool")
public Executor getAsyncExecutor() {
  return new ThreadPoolTaskExecutor();
}

1. Passing existingThreadPool in argument.

 @Autowired
 @Qualifier("commonThreadPool")
 TaskExecutor existingThreadPool;
 CompletableFuture.runAsync(() -> executeTask(),existingThreadPool);

2. Using async like below

@Async("commonThreadPool")
public void executeTask() {
// Execute Some Task
}

is there any third way where I can write CompletableFuture Handler or Override its existing behaviour at single place where I can pass custom Threadpool. And after that wherever I use below code, it should pick my existing ThreadPool instead of forkJoin pool.

 CompletableFuture.runAsync(() -> executeTask());

Body:
There is no standard way for replacing the default executor for all CompletableFuture instances. But since Java 9, you can define a default executor for subclasses. E.g. with

public class MyCompletableFuture<T> extends CompletableFuture<T> {
    static final Executor EXEC = r -> {
        System.out.println("executing "+r);
        new Thread(r).start();
    };

    @Override
    public Executor defaultExecutor() {
        return EXEC;
    }

    @Override
    public <U> CompletableFuture<U> newIncompleteFuture() {
        return new MyCompletableFuture<>();
    }

    public static CompletableFuture<Void> runAsync(Runnable runnable) {
        Objects.requireNonNull(runnable);
        return supplyAsync(() -> {
            runnable.run();
            return null;
        });
    }

    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return new MyCompletableFuture<U>().completeAsync(supplier);
    }
}

you did all necessary steps for defining the default executor for all chained stages of the MyCompletableFuture. The executor hold in EXEC only serves as an example, producing a printout when used, so when you use that example class like

MyCompletableFuture.supplyAsync(() -> "test")
    .thenApplyAsync(String::toUpperCase)
    .thenAcceptAsync(System.out::println);

it will print

executing java.util.concurrent.CompletableFuture$AsyncSupply@65ab7765
executing java.util.concurrent.CompletableFuture$UniApply@119d7047
executing java.util.concurrent.CompletableFuture$UniAccept@404b9385
TEST


问:
How to generate unique QR codes with Google Authenticator in PHP?
want for each of the user on our PHP system to have a unique QR code. I have implemented the Google Authenticator system but it only generates the same QR code for each user and one user can use their code to log-in to another user's account.

How do I get Google Authenticator to generate a unique code for each user? What value/variable do I need to pass onto Google Authenticator for it to come up with a unique code for each user account on our system?

We have tried passing the email address or username of the user but the Authenticator sends back the same QR code despite the email addresses being unique.

[1]using username , username variable name is $name

```<code>public function getQR($name, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer='.urlencode($title));
        }

        return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
    }

    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }
</code>```

[2]using email , email variable name is $email

```<code>public function getQR($email, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/'.$email.'?secret='.$secret.'');
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer='.urlencode($title));
        }

        return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
    }

    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }
</code>```

I want for the code to generate a unique QR code for each user so each user have their own authentication codes in the Google Authenticator app on their phones.

答:
The secret is nothing more than a random base32 string.
So can be done as simple as

```<code> substr( str_shuffle( "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" ), 0, 32 );
</code>```

Where "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" is the base32 alphabet

Body:
want for each of the user on our PHP system to have a unique QR code. I have implemented the Google Authenticator system but it only generates the same QR code for each user and one user can use their code to log-in to another user's account.

How do I get Google Authenticator to generate a unique code for each user? What value/variable do I need to pass onto Google Authenticator for it to come up with a unique code for each user account on our system?

We have tried passing the email address or username of the user but the Authenticator sends back the same QR code despite the email addresses being unique.

[1]using username , username variable name is $name

public function getQR($name, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer='.urlencode($title));
        }

        return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
    }

    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }

[2]using email , email variable name is $email

public function getQR($email, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/'.$email.'?secret='.$secret.'');
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer='.urlencode($title));
        }

        return 'https://chart.googleapis.com/chart?chs='.$width.'x'.$height.'&chld='.$level.'|0&cht=qr&chl='.$urlencoded.'';
    }

    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }

I want for the code to generate a unique QR code for each user so each user have their own authentication codes in the Google Authenticator app on their phones.

Body:
The secret is nothing more than a random base32 string.
So can be done as simple as

 substr( str_shuffle( "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" ), 0, 32 );

Where "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" is the base32 alphabet


问:
Images stretched in flex container but cannot use align-self-center
I have the following markup (Bootstrap 4):

```<code><div class="col-3 d-flex flex-column">
    <img class="align-self-center" src="#"/>
</div>
</code>```

Since the container is flexed, the images are stretching. I'm aware align-self-center will resolve the issue, however, I don't want the image to be centered. I want the image to be align-self-left (left aligned rather than centered), but this stretched the image again.

Any way around this?

答: It would be align-self-start. Bootstrap flex doesn't use term left

Body:
I have the following markup (Bootstrap 4):

Since the container is flexed, the images are stretching. I'm aware align-self-center will resolve the issue, however, I don't want the image to be centered. I want the image to be align-self-left (left aligned rather than centered), but this stretched the image again.

Any way around this?


问:
Php scripts (jobs) architecture. Is cron the ideal solution?
I am using crontab as the manager for administrative scripts and set up each job manually. Which seem to be very straight forward and perhaps ideal solution.

Problem that I realized is, that I don't have any unified and automated control whether those scripts run fine all the time. Some of them are quite old... some are configured to send emails if problem occurs, others writes to custom error logs...

My plan is to unify all job scripts to strictly return correct status codes so I can just analyze crontab log (or custom log via "2>") for issues. Perhaps even write some very simple job framework which will assert the unification and automate things for my needs...

Would you suggest some best practices? Or anything else? Or something to read about the topic before I start?

Thanks

答:
Cron tables are in deed the appropriate solution. Rewriting crontable in PHP would be both painful and uncertain on scheduling, unless you choose to use the fork functions, making it even more painful to write.

Launching the PHP script is pretty straight forward with wget, which gives you a bunch of logging utilities. Themselves being log rotatable for instance.

You should definitely share some job-tools.sh among your jobs scripts to always report their malfunctions, step by step.

Concerning the PHP script execution itself, you'd better rely on your standard PHP error log, which you probably already watch.

Cheers,


问:
0 Pad Day and Month in a Date String using JavaScript
Using JavaScript is there a way to take a Date string like this 9/17/2014 and modify it so that the day and month values are always padded with a 0 if they are single digit in length?

The catch is that the delimiter / can be anything.  Generally it would be - or / so if it only looked for those 2 would be fine to.

Also the order of the day, month, and year can be in any position.

My end goal is to take a date string and make it so that the Date portion is always 10 characters in length so that I can then grab the remaining characters is they exist and always assume they are the Time portion of the DateTime string.

If I get a string like this though 9/17/2014 then the Date portion is only 9 long and if the day was single digit like 9/7/2014 then it would only be 8 long.

I am working on this JavaScript function to convert a Date string into a JS Date object.  It allows any style delimiter and any order for the day, month, and year parts.

My goal is to modify it to also allow Date strings that can have a Time after the Date part and parse them into time pieces.

If the string has the Time parts, I will assume time delimiter will always be :.

The separator between the Date and a Time in the string could be either:

space like 04/04/2016 12:23:12

T like 04/04/2016T12:23:12

Also the time may or may not have the ending am or pm.

My issue at the moment is the Date part sometimes not being the 10 character length so if I could auto 0 pad single digit day and months it might help in the end goal.

Any help with any of this goal appreciated though, thanks

```<code>  // Convert Date String into JS Date Object
  // Can parse multiple Date formats
  // stringToDate("17/9/2014", "dd/MM/yyyy", "/");
  // stringToDate("9/17/2014", "mm/dd/yyyy", "/");
  // stringToDate("9-17-2014", "mm-dd-yyyy", "-");
  stringToDate: function(d, _format, _delimiter) {
    if((d instanceof Date)){
      return d;
    }
    if(d.length > 10){
      // it might have a Time string at the end
      var dateString = d.substring(0, 10);
      console.log(dateString);
    }

    var formatLowerCase = _format.toLowerCase();
    var formatItems = formatLowerCase.split(_delimiter);
    var dateItems = d.split(_delimiter);
    var monthIndex = formatItems.indexOf("mm");
    var dayIndex = formatItems.indexOf("dd");
    var yearIndex = formatItems.indexOf("yyyy");
    var month = parseInt(dateItems[monthIndex]);
    month -= 1;
    var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex]);
    return formatedDate;
  },
</code>```

答:
please note that when padding, the number could be a string or a number, so this needs to be checked first to get the correct result</p>

```<code>pad(n){
    if(typeof n.length != 'undefined'){ // string
      return (n.length == 1) ? "0"+n : n;
    }
    else { // number
      if (n < 10) {
        return "0" + n;
      }
      return n;
    }
  }
</code>```

Body:
Using JavaScript is there a way to take a Date string like this 9/17/2014 and modify it so that the day and month values are always padded with a 0 if they are single digit in length?

The catch is that the delimiter / can be anything.  Generally it would be - or / so if it only looked for those 2 would be fine to.

Also the order of the day, month, and year can be in any position.

My end goal is to take a date string and make it so that the Date portion is always 10 characters in length so that I can then grab the remaining characters is they exist and always assume they are the Time portion of the DateTime string.

If I get a string like this though 9/17/2014 then the Date portion is only 9 long and if the day was single digit like 9/7/2014 then it would only be 8 long.

I am working on this JavaScript function to convert a Date string into a JS Date object.  It allows any style delimiter and any order for the day, month, and year parts.

My goal is to modify it to also allow Date strings that can have a Time after the Date part and parse them into time pieces.

If the string has the Time parts, I will assume time delimiter will always be :.

The separator between the Date and a Time in the string could be either:

space like 04/04/2016 12:23:12

T like 04/04/2016T12:23:12

Also the time may or may not have the ending am or pm.

My issue at the moment is the Date part sometimes not being the 10 character length so if I could auto 0 pad single digit day and months it might help in the end goal.

Any help with any of this goal appreciated though, thanks

  // Convert Date String into JS Date Object
  // Can parse multiple Date formats
  // stringToDate("17/9/2014", "dd/MM/yyyy", "/");
  // stringToDate("9/17/2014", "mm/dd/yyyy", "/");
  // stringToDate("9-17-2014", "mm-dd-yyyy", "-");
  stringToDate: function(d, _format, _delimiter) {
    if((d instanceof Date)){
      return d;
    }
    if(d.length > 10){
      // it might have a Time string at the end
      var dateString = d.substring(0, 10);
      console.log(dateString);
    }

    var formatLowerCase = _format.toLowerCase();
    var formatItems = formatLowerCase.split(_delimiter);
    var dateItems = d.split(_delimiter);
    var monthIndex = formatItems.indexOf("mm");
    var dayIndex = formatItems.indexOf("dd");
    var yearIndex = formatItems.indexOf("yyyy");
    var month = parseInt(dateItems[monthIndex]);
    month -= 1;
    var formatedDate = new Date(dateItems[yearIndex], month, dateItems[dayIndex]);
    return formatedDate;
  },

Body:
please note that when padding, the number could be a string or a number, so this needs to be checked first to get the correct result

pad(n){
    if(typeof n.length != 'undefined'){ // string
      return (n.length == 1) ? "0"+n : n;
    }
    else { // number
      if (n < 10) {
        return "0" + n;
      }
      return n;
    }
  }


问:
.child-div overflows .parent-div
guys!

I'm making an own portfolio website. The idea is to make full height pages. So regarding this, I got 2 questions.

How can I make .child-div not larger than its .parent-div?

How can I make p-elements height not larger than its .child-div?

Thinking that there is some (maybe the same) solution to both problems.

Overflow is not an option, because it just hide the rest of element.

I tried to set .parent as display: table and .child as display: table-cell but I didn't succeed.
UPD: Also tried to make an table-row div between .parent and. child width width: 100% and height: 33%. Unfortunately without expected result..

Here is the example how it should look like, but .child overflows the .parent.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: 100%;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
  <div class="child-70 left"></div>
  <div class="child-30 right"></div>
  <div class="child-30 left"></div>
  <div class="child-70 right"></div>
</div></code>```

And here is the link how it should look like with paragraphs

Same problem here

答:
I have an answer to the first question:

@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: calc(100% - 20px);}
}
```

Why width: calc(100% - 20px)? Because you use margin for .child-30 and .child-70 (margin: 10px is margin-top, margin-right, margin-bottom, margin-left = 10px and on width's summed margin-right and margin-left -> so 20 pixels.

Title: .child-div overflows .parent-div

Body:
guys!

I'm making an own portfolio website. The idea is to make full height pages. So regarding this, I got 2 questions.

How can I make .child-div not larger than its .parent-div?

How can I make p-elements height not larger than its .child-div?

Thinking that there is some (maybe the same) solution to both problems.

Overflow is not an option, because it just hide the rest of element.

I tried to set .parent as display: table and .child as display: table-cell but I didn't succeed.
UPD: Also tried to make an table-row div between .parent and. child width width: 100% and height: 33%. Unfortunately without expected result..

Here is the example how it should look like, but .child overflows the .parent.

html {
  height: 100%;
}
body {
  height: 100%;
  max-width: 960px;
  margin: 15px auto;
}
.parent {
  height: 100%;
  border: 1px solid red;
}
.child-30 {
  min-height: calc(100%/3);
  width: 27%;
  margin: 10px;
  border: 1px solid green;
}
.child-70 {
  min-height: calc(100%/3);
  width: 67%;
  margin: 10px;
  border: 1px solid green;
}
.left {
  float: left;
}
.right {
  float: right;
}
@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: 100%;}
}

And here is the link how it should look like with paragraphs

Same problem here

Body:
I have an answer to the first question:

@media only screen and (max-width: 750px) {
  .child-30, .child-70 {float: left; width: calc(100% - 20px);}
}

Why width: calc(100% - 20px)? Because you use margin for .child-30 and .child-70 (margin: 10px is margin-top, margin-right, margin-bottom, margin-left = 10px and on width's summed margin-right and margin-left -> so 20 pixels.


问:
Why i am not able to cast pointer to the class structure
I have a Geometry class

```<code>class Geometry
{
public:
    std::string stdstrType;
    bool bValid;
public:
    Geometry()

    Geometry( std::string strType , bool bValue )

    Geometry(const Geometry &g)

    ~Geometry()
    virtual void draw();
    bool isValid();
    void setValidState(bool bState);
    virtual void Init();
    std::string GetName();
};
</code>```

Which is the base class for Geometry objects like in this case for Sphere class

```<code>class Sph : public Geometry
{
public:
    Sph( float radius , float segments );
    ~Sph();
    void init();
    void CleanUp();
    void draw();

private:
    float fRadius, fSegments;
    bool isInited;
    unsigned int m_VAO, m_VBO;
    int iNumsToDraw;
    SumShader shader;
    bool isChanged;
};
</code>```

I have a Tree structure holding different Container objects and Geometry is a data type in the Container object.

```<code>class Container
{
private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry Geom;
}
</code>```

Since each item in the tree can hold a circle sphere or rectangle so I would like to use the draw function of geometry to draw the Geometry object types.
For this when I try to cast any Geometry Object type to Geometry I get an error.

```<code>Sph sphere(0.1 , 32);
Geometry *geom = &sphere;
Container cont("Sphere" , "SPHERE" , *geometry );
myModel->SetContainer(child, cont);
</code>```

The Constructor for Container

```<code> Container::Container( std::string strName, std::string strType, const
 Geometry& geometry) : Geom(geometry)
  {
     stdstrContainerName = strName;
     stdstrPluginType = strType;
  }

 void  TreeModel::SetContainer(const QModelIndex &index, Container Cont)
  {
    TreeItem *item = getItem(index);
    item->setContainer(Cont);
  }

  class TreeItem
   {
    public:
     // Functions here
   private:
     QList<TreeItem*> childItems;
     Container itemData;
     TreeItem* parentItem;
   };
</code>```

1) Is this the correct approach?

2) How can I cast the Geometry objects to the Geometry pointer?

答:
The minimal code that works and implements an idea in the question:

```<code>#include <iostream>

class Geometry
{
public:
    Geometry(const std::string type) { stdstrType = type; }
    std::string GetName() { return stdstrType; }
    virtual void draw() {} ;
private:
    std::string stdstrType;
};

class Sphere : public Geometry
{
public:
    Sphere(float radius): Geometry("Sphere ") { fRadius = radius; }
    virtual void draw() { std::cout << GetName() << fRadius << "\n";}
private:
    float fRadius;
};

class Container
{
public:
    Container(std::string strName, Geometry* g)
    {
        stdstrContainerName = strName;
        geometry = g;
    }
    void draw() { geometry->draw(); }
private:
    std::string stdstrContainerName;
    Geometry *geometry;
};

int main(int argc, const char * argv[]) {
    Sphere sphere(0.1);
    Geometry *geom = &sphere;
    Container cont("Sphere container", geom);
    cont.draw();
    return 0;
}
</code>```

Xcode 10.2.1: No Buildtime/Runtime Issues. Output:

Sphere 0.1
Program ended with exit code: 0
```

Body:
I have a Geometry class

class Geometry
{
public:
    std::string stdstrType;
    bool bValid;
public:
    Geometry()

    Geometry( std::string strType , bool bValue )

    Geometry(const Geometry &g)

    ~Geometry()
    virtual void draw();
    bool isValid();
    void setValidState(bool bState);
    virtual void Init();
    std::string GetName();
};

Which is the base class for Geometry objects like in this case for Sphere class

class Sph : public Geometry
{
public:
    Sph( float radius , float segments );
    ~Sph();
    void init();
    void CleanUp();
    void draw();

private:
    float fRadius, fSegments;
    bool isInited;
    unsigned int m_VAO, m_VBO;
    int iNumsToDraw;
    SumShader shader;
    bool isChanged;
};

I have a Tree structure holding different Container objects and Geometry is a data type in the Container object.

class Container
{
private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry Geom;
}

Since each item in the tree can hold a circle sphere or rectangle so I would like to use the draw function of geometry to draw the Geometry object types.
For this when I try to cast any Geometry Object type to Geometry I get an error.

Sph sphere(0.1 , 32);
Geometry *geom = &sphere;
Container cont("Sphere" , "SPHERE" , *geometry );
myModel->SetContainer(child, cont);

The Constructor for Container

 Container::Container( std::string strName, std::string strType, const
 Geometry& geometry) : Geom(geometry)
  {
     stdstrContainerName = strName;
     stdstrPluginType = strType;
  }

 void  TreeModel::SetContainer(const QModelIndex &index, Container Cont)
  {
    TreeItem *item = getItem(index);
    item->setContainer(Cont);
  }

  class TreeItem
   {
    public:
     // Functions here
   private:
     QList<TreeItem*> childItems;
     Container itemData;
     TreeItem* parentItem;
   };

1) Is this the correct approach?

2) How can I cast the Geometry objects to the Geometry pointer?

Body:
The minimal code that works and implements an idea in the question:

#include <iostream>

class Geometry
{
public:
    Geometry(const std::string type) { stdstrType = type; }
    std::string GetName() { return stdstrType; }
    virtual void draw() {} ;
private:
    std::string stdstrType;
};

class Sphere : public Geometry
{
public:
    Sphere(float radius): Geometry("Sphere ") { fRadius = radius; }
    virtual void draw() { std::cout << GetName() << fRadius << "\n";}
private:
    float fRadius;
};

class Container
{
public:
    Container(std::string strName, Geometry* g)
    {
        stdstrContainerName = strName;
        geometry = g;
    }
    void draw() { geometry->draw(); }
private:
    std::string stdstrContainerName;
    Geometry *geometry;
};

int main(int argc, const char * argv[]) {
    Sphere sphere(0.1);
    Geometry *geom = &sphere;
    Container cont("Sphere container", geom);
    cont.draw();
    return 0;
}

Xcode 10.2.1: No Buildtime/Runtime Issues. Output:

Sphere 0.1
Program ended with exit code: 0


问:
'dict' object has no attribute 'has_key'
While traversing a graph in Python, a I'm receiving this error:

'dict' object has no attribute 'has_key'

Here is my code:

```<code>def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None
</code>```

The code aims to find the paths from one node to others. Code source: http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html

Why am I getting this error and how can I fix it?

答:
In python3, has_key(key) is replaced by __contains__(key)

Tested in python3.7:

```<code>a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))
</code>```

Body:
While traversing a graph in Python, a I'm receiving this error:

'dict' object has no attribute 'has_key'

Here is my code:

def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None

The code aims to find the paths from one node to others. Code source: http://cs.mwsu.edu/~terry/courses/4883/lectures/graphs.html

Why am I getting this error and how can I fix it?

Body:
In python3, has_key(key) is replaced by __contains__(key)

Tested in python3.7:

a = {'a':1, 'b':2, 'c':3}
print(a.__contains__('a'))


问:
Are the default CryptoJS AES params secure?
The default params used for AES encryption with CryptoJS are:

Cypher: AES-256

Mode: cbc

Key Derivation: evpkdf (OpenSSL custom, MD5, 1 iteration)

Are these safe to use?

Related: What are the AES parameters used and steps performed internally by crypto-js while encrypting a message with a password?

答:
Answering my own question; NO! ABSOLUTELY NOT!

CryptoJS by default does only a single iteration of MD5 hashing over the password, which is extremely weak unless the password is extremely strong!

Correct key derivation of arbitrary passwords should do key derivation with something along the 30k iterations!


问:
Issue with Pip installation
Two Issues:

First one is that am trying to call a JSON API using python for which I used 'Import Request' in my code. But got an error stating : No module named 'requests'

Secondly when i try to install pip,on cmd, i get an error that states - Could not fetch URL https://pypi.org/simple/pip:

My code might be wrong. Please help to get this resolved.

Error on Command prompt:

C:\Users\MEIPE\Desktop>python get-pip.py
  Collecting pip
    Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None))
   after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError
  (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping  Could not find a version that satisfies the requirement pip (from versions: )No matching distribution found for pip Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping

Code:

```<code>import urllib.parse
import requests

main_api = 'http://nagiosdatagateway.vestas.net/esq/ITE1452552/logstash-?'

date = '2018.12.16'
url = main_api + urllib.parse.urlencode({'date':date})

json_date = requests.get(url).json()

print(json_data)
</code>```

Want to call a dynamically changing JSON API url and store the data in a SQL Server table. This would help me to schedule a python script to be executed daily to get JSON data and then from the SQL table, i will get monthly reports.

答:
Following command can fix this:

```<code>python get-pip.py --trusted-host=files.pythonhosted.org --trusted-host=pypi.org
</code>```

Run as administrator in windows

Title: Issue with Pip installation

Body:
Two Issues:

First one is that am trying to call a JSON API using python for which I used 'Import Request' in my code. But got an error stating : No module named 'requests'

Secondly when i try to install pip,on cmd, i get an error that states - Could not fetch URL https://pypi.org/simple/pip:

My code might be wrong. Please help to get this resolved.

Error on Command prompt:

C:\Users\MEIPE\Desktop>python get-pip.py
  Collecting pip
    Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None))
   after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/pip/  Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError
  (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping  Could not find a version that satisfies the requirement pip (from versions: )No matching distribution found for pip Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping

Code:

import urllib.parse
import requests

main_api = 'http://nagiosdatagateway.vestas.net/esq/ITE1452552/logstash-?'

date = '2018.12.16'
url = main_api + urllib.parse.urlencode({'date':date})

json_date = requests.get(url).json()

print(json_data)

Want to call a dynamically changing JSON API url and store the data in a SQL Server table. This would help me to schedule a python script to be executed daily to get JSON data and then from the SQL table, i will get monthly reports.

Body:
Following command can fix this:

python get-pip.py --trusted-host=files.pythonhosted.org --trusted-host=pypi.org

Run as administrator in windows


问:
MonoTouch and Xcode 4
Now that the Xcode 4 GM seed has been released, will MonoDevelop eventually interact with it somehow for XIB editing?  I'm currently manually setting the "Open With..." on each of my XIBs to the old Interface Builder, but there are two problems with this: I have to remember to do it; and any XIB editing enhancements Apple makes in Xcode 4 aren't available.</p>

答: Adding outlets and actions is no longer there. XCode 4 now integrates these in code directly, but that is Objective C only, not C#.</p>

ContentLicense: CC BY-SA 2.5

Title: MonoTouch and Xcode 4


问:
How to show recent items first?
I've a long list that holds some data, and whenever i add a new item to the list, the item added to the "end of the line".

How do i show the last added  item first?

Something like show recent items first

答:
You need to add the item at 0 index, so use List.insert method.

```<code>setState(() {
  yourList.insert(0, yourItem);
});
</code>```

And yes, there is difference between List.add() and List.insert(), the former adds the item to the end of the list and later allows you to add the item at some specified index.

Title: How to show recent items first?

Body:
You need to add the item at 0 index, so use List.insert method.

setState(() {
  yourList.insert(0, yourItem);
});

And yes, there is difference between List.add() and List.insert(), the former adds the item to the end of the list and later allows you to add the item at some specified index.


问:
even_Sn_not_even_n - apply 1 hypothesis in another
Unfortunately I got stuck again:

```<code>Inductive even : nat > Prop :=
| ev_0 : even 0
| ev_SS (n : nat) (H : even n) : even (S (S n)).

Lemma even_Sn_not_even_n : forall n,
    even (S n) <-> not (even n).
Proof.
  intros n. split.
  + intros H. unfold not. intros H1. induction H1 as [|n' E' IHn].
    - inversion H.
    - inversion_clear H. apply IHn in H0. apply H0.
  + intros H. induction n as [|n' IHn].
    - exfalso. apply H. apply ev_0.
    - apply evSS_inv'.
</code>```

Here is the result:

```<code>1 subgoal (ID 179)

n' : nat
H : ~ even (S n')
IHn : ~ even n' -> even (S n')
============================
even n'
</code>```

As far I could prove it in words:

(n' + 1) is not even according to H. Therefore according to IHn, it is not true that n' is not even (double negation):

```<code>IHn : ~ ~ even n'
</code>```

Unfolding double negation, we conclude that n' is even.

But how to write it in coq?

答:
The usual way to strip double negation is to introduce the "excluded middle" axiom, which is defined under the name classic in Coq.Logic.Classical_Prop, and apply the lemma NNPP.

However, in this particular case, you can use the technique called reflection by showing that the Prop is consistent with a boolean function (you might remember the evenb function introduced earlier in the book).

(Assuming you're at the beginning of IndProp) You'll soon see the following definition later in that chapter:

```<code>Inductive reflect (P : Prop) : bool -> Prop :=
| ReflectT (H : P) : reflect P true
| ReflectF (H : ~ P) : reflect P false.
</code>```

You can prove the statement

```<code>Lemma even_reflect : forall n : nat, reflect (even n) (evenb n).
</code>```

and then use it to move between a Prop and a boolean (which contain the same information i.e. the (non-)evenness of n) at the same time. This also means that you can do classical reasoning on that particular property without using the classic axiom.

I suggest to complete the exercises under Reflection section in IndProp, and then try the following exercises. (Edit: I uploaded the full answer here.)

```<code>(* Since `evenb` has a nontrivial recursion structure, you need the following lemma: *)
Lemma nat_ind2 :
  forall P : nat -> Prop,
  P 0 -> P 1 -> (forall n : nat, P n -> P (S (S n))) -> forall n : nat, P n.
Proof. fix IH 5. intros. destruct n as [| [| ]]; auto.
  apply H1. apply IH; auto. Qed.

(* This is covered in an earlier chapter *)
Lemma negb_involutive : forall x : bool, negb (negb x) = x.
Proof. intros []; auto. Qed.

(* This one too. *)
Lemma evenb_S : forall n : nat, evenb (S n) = negb (evenb n).
Proof. induction n.
  - auto.
  - rewrite IHn. simpl. destruct (evenb n); auto. Qed.

(* Exercises. *)
Lemma evenb_even : forall n : nat, evenb n = true -> even n.
Proof. induction n using nat_ind2.
  (* Fill in here *) Admitted.

Lemma evenb_odd : forall n : nat, evenb n = false -> ~ (even n).
Proof. induction n using nat_ind2.
  (* Fill in here *) Admitted.

Lemma even_reflect : forall n : nat, reflect (even n) (evenb n).
Proof. (* Fill in here. Hint: You don't need induction. *) Admitted.

Lemma even_iff_evenb : forall n, even n <-> evenb n = true.
Proof. (* Fill in here. Hint: use `reflect_iff` from IndProp. *) Admitted.

Theorem reflect_iff_false : forall P b, reflect P b -> (~ P <-> b = false).
Proof. (* Fill in here. *) Admitted.

Lemma n_even_iff_evenb : forall n, ~ (even n) <-> evenb n = false.
Proof. (* Fill in here. *) Admitted.

Lemma even_Sn_not_even_n : forall n,
    even (S n) <-> not (even n).
Proof. (* Fill in here.
  Hint: Now you can convert all the (non-)evenness properties to booleans,
  and then work with boolean logic! *) Admitted.
</code>```

Body:
Unfortunately I got stuck again:

Inductive even : nat > Prop :=
| ev_0 : even 0
| ev_SS (n : nat) (H : even n) : even (S (S n)).

Lemma even_Sn_not_even_n : forall n,
    even (S n) <-> not (even n).
Proof.
  intros n. split.
  + intros H. unfold not. intros H1. induction H1 as [|n' E' IHn].
    - inversion H.
    - inversion_clear H. apply IHn in H0. apply H0.
  + intros H. induction n as [|n' IHn].
    - exfalso. apply H. apply ev_0.
    - apply evSS_inv'.

Here is the result:

1 subgoal (ID 179)

n' : nat
H : ~ even (S n')
IHn : ~ even n' -> even (S n')
============================
even n'

As far I could prove it in words:

(n' + 1) is not even according to H. Therefore according to IHn, it is not true that n' is not even (double negation):

IHn : ~ ~ even n'

Unfolding double negation, we conclude that n' is even.

But how to write it in coq?

Body:
The usual way to strip double negation is to introduce the "excluded middle" axiom, which is defined under the name classic in Coq.Logic.Classical_Prop, and apply the lemma NNPP.

However, in this particular case, you can use the technique called reflection by showing that the Prop is consistent with a boolean function (you might remember the evenb function introduced earlier in the book).

(Assuming you're at the beginning of IndProp) You'll soon see the following definition later in that chapter:

Inductive reflect (P : Prop) : bool -> Prop :=
| ReflectT (H : P) : reflect P true
| ReflectF (H : ~ P) : reflect P false.

You can prove the statement

Lemma even_reflect : forall n : nat, reflect (even n) (evenb n).

and then use it to move between a Prop and a boolean (which contain the same information i.e. the (non-)evenness of n) at the same time. This also means that you can do classical reasoning on that particular property without using the classic axiom.

I suggest to complete the exercises under Reflection section in IndProp, and then try the following exercises. (Edit: I uploaded the full answer here.)

(* Since `evenb` has a nontrivial recursion structure, you need the following lemma: *)
Lemma nat_ind2 :
  forall P : nat -> Prop,
  P 0 -> P 1 -> (forall n : nat, P n -> P (S (S n))) -> forall n : nat, P n.
Proof. fix IH 5. intros. destruct n as [| [| ]]; auto.
  apply H1. apply IH; auto. Qed.

(* This is covered in an earlier chapter *)
Lemma negb_involutive : forall x : bool, negb (negb x) = x.
Proof. intros []; auto. Qed.

(* This one too. *)
Lemma evenb_S : forall n : nat, evenb (S n) = negb (evenb n).
Proof. induction n.
  - auto.
  - rewrite IHn. simpl. destruct (evenb n); auto. Qed.

(* Exercises. *)
Lemma evenb_even : forall n : nat, evenb n = true -> even n.
Proof. induction n using nat_ind2.
  (* Fill in here *) Admitted.

Lemma evenb_odd : forall n : nat, evenb n = false -> ~ (even n).
Proof. induction n using nat_ind2.
  (* Fill in here *) Admitted.

Lemma even_reflect : forall n : nat, reflect (even n) (evenb n).
Proof. (* Fill in here. Hint: You don't need induction. *) Admitted.

Lemma even_iff_evenb : forall n, even n <-> evenb n = true.
Proof. (* Fill in here. Hint: use `reflect_iff` from IndProp. *) Admitted.

Theorem reflect_iff_false : forall P b, reflect P b -> (~ P <-> b = false).
Proof. (* Fill in here. *) Admitted.

Lemma n_even_iff_evenb : forall n, ~ (even n) <-> evenb n = false.
Proof. (* Fill in here. *) Admitted.

Lemma even_Sn_not_even_n : forall n,
    even (S n) <-> not (even n).
Proof. (* Fill in here.
  Hint: Now you can convert all the (non-)evenness properties to booleans,
  and then work with boolean logic! *) Admitted.


问:
How to add margin to SVG Circle's stroke for a simple donut
I'm trying to build a very simple donut chart.

Here's the working code :

const countries = [
{'percent': 2,colour: 'red'},
{'percent': 28,colour: 'blue'},
{'percent': 36,colour: 'yellow'},
{'percent': 34,colour: 'orange'}
];

const donutData = countries.map((country, index) => {
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0),
    dashArray: [country.percent, 100 - country.percent]
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="2.3"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')```

https://jsfiddle.net/miladhi/1dxnkjht/1/

Above works fine, but try adding stroke-linecap="round" to the <circle> and it goes pare shaped, the strokes are on top of each other.

As you can see here https://jsfiddle.net/miladhi/x8w4kgdv/.

I can understand the problem, but don't know how to add a little bit of margin between the strokes to avoid the ugly stacking.

I appreciate any suggestion.

答:
Is this what you wanted?

Just subtract the radius of the round endcaps (one for each end) from the dash length.

As long as the circle radius is not extremely small, the round caps should just touch each other neatly.

const countries = [
{'percent': 10,colour: 'red'},
{'percent': 20,colour: 'blue'},
{'percent': 36,colour: 'yellow'},
{'percent': 34,colour: 'orange'}
];

const STROKE_WIDTH = 2.3;

const donutData = countries.map((country, index) => {
  // Subtract the radius of the round cap, twice.
  const dashLength = country.percent - STROKE_WIDTH;
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0),
    dashArray: [dashLength, 100 - dashLength]
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="${STROKE_WIDTH}"
    stroke-linecap="round"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')```
</div>
</div>
</p>

<p><strong>Update</strong></p>

<p>A version which somewhat gracefully handles short line lengths.</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-js lang-js prettyprint-override"><code>const countries = [
{'percent': 10, colour: 'red'},
{'percent': 20, colour: 'blue'},
{'percent': 36, colour: 'yellow'},
{'percent': 33, colour: 'orange'},
{'percent': 1,  colour: 'green'},
];

const STROKE_WIDTH = 2.3;

const donutData = countries.map((country, index) => {
  let dashLength, offsetAdjust, caps;
  if (country.percent >= STROKE_WIDTH) {
    // Subtract the radius of the round cap, twice.
    dashLength = country.percent - STROKE_WIDTH;
    offsetAdjust = STROKE_WIDTH / 2;
    caps = "round";
  } else {
    dashLength = country.percent;
    offsetAdjust = 0;
    caps = "butt";
  }
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0) - offsetAdjust,
    dashArray: [dashLength, 100 - dashLength],
    caps: caps
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="${STROKE_WIDTH}"
    stroke-linecap="${item.caps}"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')</code>```

Body:
I'm trying to build a very simple donut chart.

Here's the working code :

const countries = [
{'percent': 2,colour: 'red'},
{'percent': 28,colour: 'blue'},
{'percent': 36,colour: 'yellow'},
{'percent': 34,colour: 'orange'}
];

const donutData = countries.map((country, index) => {
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0),
    dashArray: [country.percent, 100 - country.percent]
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="2.3"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')

https://jsfiddle.net/miladhi/1dxnkjht/1/

Above works fine, but try adding stroke-linecap="round" to the <circle> and it goes pare shaped, the strokes are on top of each other.

As you can see here https://jsfiddle.net/miladhi/x8w4kgdv/.

I can understand the problem, but don't know how to add a little bit of margin between the strokes to avoid the ugly stacking.

I appreciate any suggestion.

Body:
Is this what you wanted?

Just subtract the radius of the round endcaps (one for each end) from the dash length.

As long as the circle radius is not extremely small, the round caps should just touch each other neatly.

const countries = [
{'percent': 10,colour: 'red'},
{'percent': 20,colour: 'blue'},
{'percent': 36,colour: 'yellow'},
{'percent': 34,colour: 'orange'}
];

const STROKE_WIDTH = 2.3;

const donutData = countries.map((country, index) => {
  // Subtract the radius of the round cap, twice.
  const dashLength = country.percent - STROKE_WIDTH;
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0),
    dashArray: [dashLength, 100 - dashLength]
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="${STROKE_WIDTH}"
    stroke-linecap="round"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')

Update

A version which somewhat gracefully handles short line lengths.

const countries = [
{'percent': 10, colour: 'red'},
{'percent': 20, colour: 'blue'},
{'percent': 36, colour: 'yellow'},
{'percent': 33, colour: 'orange'},
{'percent': 1,  colour: 'green'},
];

const STROKE_WIDTH = 2.3;

const donutData = countries.map((country, index) => {
  let dashLength, offsetAdjust, caps;
  if (country.percent >= STROKE_WIDTH) {
    // Subtract the radius of the round cap, twice.
    dashLength = country.percent - STROKE_WIDTH;
    offsetAdjust = STROKE_WIDTH / 2;
    caps = "round";
  } else {
    dashLength = country.percent;
    offsetAdjust = 0;
    caps = "butt";
  }
  return {
    stroke: country.colour,
    dashoffset: 25 - countries.slice(0, index).reduce((a, b) => a + b.percent, 0) - offsetAdjust,
    dashArray: [dashLength, 100 - dashLength],
    caps: caps
  }
});
const div = document.createElement('div');
div.innerHTML = '<svg id="donut" width="100%" height="100%" viewBox="3 3 36 36"></svg>';
document.body.appendChild(div);
document.querySelector('#donut').innerHTML= donutData.reduce((a, item) => {
  return a +
    `<circle
   cx="21"
    cy="21"
    fill="transparent"
    r="15.91549430918954"
    stroke-width="${STROKE_WIDTH}"
    stroke-linecap="${item.caps}"
    stroke="${item.stroke}"
    stroke-dasharray="${item.dashArray[0]} ${item.dashArray[1]}"
    stroke-dashoffset="${item.dashoffset}"></circle>
`;
}, '')


问:
Steps to be followed for creating a build.gradle file in corda project
What documentation should we follow for creating a build.gradle file in corda project if the project is created from scratch rather than using templates available in github</p>

答:
I recommend using one of the templates, to be honest. But, documentation on this subject can be found here:

https://docs.corda.net/cordapp-build-systems.html


问:
Activate the Workbook containing the code
Trying to activate active workbook after UNAPP macros, but (if many workbooks are opened) activating always last opened workbook and every time is toggling (last workbook to Activeworkbook), I need to activate ALWAYS the workbook from which code is called.</p>

```<code>Sub App()
    With Application
      .ScreenUpdating = False
      .DisplayAlerts = False
      .EnableEvents = False
      .Calculation = xlManual
      .Visible = False
    End With
End Sub

Sub unApp()
    With Application
      .ScreenUpdating = True
      .DisplayAlerts = True
      .EnableEvents = True
      .Calculation = xlCalculationAutomatic
      .Visible = True
    End With
End Sub

Sub testActivate()
    Set wbT = ThisWorkbook
    App
    unApp
    wbT.Activate
End Sub
</code>```

答:
Application affects all workbooks within the current Application so I assume you have multiple Applications open and want to refer to the one where the code is running?

If so you can use

```<code>With ThisWorkbook.Application
</code>```

(which is good practice anyway)

Body:
Trying to activate active workbook after UNAPP macros, but (if many workbooks are opened) activating always last opened workbook and every time is toggling (last workbook to Activeworkbook), I need to activate ALWAYS the workbook from which code is called.

Sub App()
    With Application
      .ScreenUpdating = False
      .DisplayAlerts = False
      .EnableEvents = False
      .Calculation = xlManual
      .Visible = False
    End With
End Sub

Sub unApp()
    With Application
      .ScreenUpdating = True
      .DisplayAlerts = True
      .EnableEvents = True
      .Calculation = xlCalculationAutomatic
      .Visible = True
    End With
End Sub

Sub testActivate()
    Set wbT = ThisWorkbook
    App
    unApp
    wbT.Activate
End Sub

Body:
Application affects all workbooks within the current Application so I assume you have multiple Applications open and want to refer to the one where the code is running?

If so you can use

With ThisWorkbook.Application

(which is good practice anyway)


问:
Is there a technology stack that makes connecting android applications easily?
I'm creating an android application. Most of the functionality will be done offline, however I need to build some dependency between users of the application, such as being able to see peoples "high scores" and to communicate between users, and sending each other in-app messages.

Therefore, I'll need a webserver which the app can connect to in order to store such information. I imagine the app will make REST calls to get high scores.

I'm trying to avoid the overhead of having to create a fully functional web application (SpringMVC for example). Is there any application that makes this simpler?

What is a good, simple web stack I could use for this?

答: We use the Java RESTlet framework for creating RESTful interfaces for our mobile apps, and deploy via Google AppEngine.  I shared a series of screencasts on YouTube demonstrating this approach that you might find useful.  The RESTlet framework used in the screencasts is a few versions old, but this should help you get up to speed fairly quickly.  We like this particular approach because it's straightforward for Android developers (who are already proficient in Java), scales well, and its free until you hit Google's quotas. </p>


问:
why is the button for the about page not showing in the navbar?
I am learning about ruby-on-rails , and setting up a user based web page . At the moment I am trying to add a default bootstrap navbar , but the right side button , which should be the button to the About page is not showing

I have tried to add the class="active" tu the  where the about button is , but still no success

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Saasapp</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <link href="https://fonts.googleapis.com/css?
    family=Open+Sans:400,700,800" rel="stylesheet">
    <%= stylesheet_link_tag 'application', media: 'all', 'data-
    turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-
    track': 'reload' %>

    <nav class="navbar navbar-default navbar-static-top"
    role="navigation">
        <div class='container'>
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-
            toggle="collapse" data-target="#main-nav-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a href="/" class="navbar-brand">DevMatch</a>
          </div>
          <div class="collapse navbar-collapse" id="main-nav-
          collapse">
            <ul class="nav navbar-nav navbar-right ">
              <li><a href="/about">About</a></li>
            </ul>
          </div><!-- /.navbar-collapse -->
        </div>

    </nav>

  </head>

  <body>
    <div class="container">
    <%= yield %>
    </div>
  </body>
</html>
</code>```

答:
It is showing (as a regular link) on my test page.

If you want it to be a button add classes btn btn-default:

About

```

<p>or in the Rails' way:</p>

<pre class="lang-rb prettyprint-override"><code><li><%= link_to 'About', about_path, class: 'btn btn-default' %></li>
</code>```

Body:
I am learning about ruby-on-rails , and setting up a user based web page . At the moment I am trying to add a default bootstrap navbar , but the right side button , which should be the button to the About page is not showing

I have tried to add the class="active" tu the  where the about button is , but still no success

<!DOCTYPE html>

    <title>Saasapp</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <link href="https://fonts.googleapis.com/css?
    family=Open+Sans:400,700,800" rel="stylesheet">
    <%= stylesheet_link_tag 'application', media: 'all', 'data-
    turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-
    track': 'reload' %>

            <button type="button" class="navbar-toggle" data-
            toggle="collapse" data-target="#main-nav-collapse">
              Toggle navigation

            </button>
            DevMatch

About

    <%= yield %>

Body:
It is showing (as a regular link) on my test page.

If you want it to be a button add classes btn btn-default:

<li><a class="btn btn-default" href="/about">About</a></li>

or in the Rails' way:

<li><%= link_to 'About', about_path, class: 'btn btn-default' %></li>


问:
If statement within look error 13 - type error
I have boolean or #N/A values in column DO. If a True boolean is within the DO column range, I wish for the corresponding cell in range r3FTop to be changed to the colour as per my code. My thinking is that DO2 cell corresponds to X5, and the D03 to X2.

When i run this code with

```<code>Set rRng = Worksheets("mapOut").Range("DO2:DO2") and
Set r3FTop = Worksheets("mapOut").Range("X5")
</code>```

the code works fine (cells turn to orange when the cell value at DO2 is True and don't when the cell value is False or #N/A). However upon adding the next cell in each range (DO3 and X2) I keep getting the type 13 error.

I've tried the bottom on the first row and it colours the cell at X5 perfectly. I run into problems when I try and add a second cell to the range.

For ease of use I have opted to batch the cell references I wish to colour in a group as they appear on screen.

```<code>Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range

' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")

Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
        r3FTop.Interior.Color = RGB(237, 125, 49)

    Else
        GoTo Continue

    End If

Continue:

    Next rCell

End Sub
</code>```

My actual column range is DO2:DO90 and I have corresponding cell values for r3FTop variable too. I wish for the code to go though and disregard and #N/A or False values and only change corresponding cell colors when a True boolean is found.

I've tried rewriting the above code so that the True boolean is dealt with first as so with dealing with blanks (using application.worksheet.isna(rRng).

Any pointers would be greatly appreciated.

答:
Try this </p>

```<code>Set r3FTop = Worksheets("mapOut").Range("X5, X2")
</code>```

Body:
I have boolean or #N/A values in column DO. If a True boolean is within the DO column range, I wish for the corresponding cell in range r3FTop to be changed to the colour as per my code. My thinking is that DO2 cell corresponds to X5, and the D03 to X2.

When i run this code with

Set rRng = Worksheets("mapOut").Range("DO2:DO2") and
Set r3FTop = Worksheets("mapOut").Range("X5")

the code works fine (cells turn to orange when the cell value at DO2 is True and don't when the cell value is False or #N/A). However upon adding the next cell in each range (DO3 and X2) I keep getting the type 13 error.

I've tried the bottom on the first row and it colours the cell at X5 perfectly. I run into problems when I try and add a second cell to the range.

For ease of use I have opted to batch the cell references I wish to colour in a group as they appear on screen.

Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range

' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")

Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
        r3FTop.Interior.Color = RGB(237, 125, 49)

    Else
        GoTo Continue

    End If

Continue:

    Next rCell

End Sub

My actual column range is DO2:DO90 and I have corresponding cell values for r3FTop variable too. I wish for the code to go though and disregard and #N/A or False values and only change corresponding cell colors when a True boolean is found.

I've tried rewriting the above code so that the True boolean is dealt with first as so with dealing with blanks (using application.worksheet.isna(rRng).

Any pointers would be greatly appreciated.

Body:
Try this

Set r3FTop = Worksheets("mapOut").Range("X5, X2")


问:
If feature 1 and feature 2 are using data driven and, feature 1 fails for one data, how to ignore the run for feature 2 for same data
In Karate API automation ,in Feature A , which is running through data driven , if the scenario fails for one data (say DATA ONE), how to stop a subsequent feature B, that has dependency on feature A(i.e,the functionality of what is done by feature A, for example,let's assume that feature A is for customer creation and feature B is for ticket booking, if Feature A fails for dataOne, I don't want the ticket booking to happen for dataOne), from running for the data (DATA ONE)

Feature A - should run first and uses Data driven

Sample data used in Feature A(EX: CustomerCreation.feature):

DATA ONE - Scenario fails
DATA TWO  - Pass
DATA THREE - Pass

Feature B - should run second and uses Data driven

Sample data used in Feature B (EX: TicketBooking.feature):

DATA ONE - should not run
DATA TWO  - Should Pass
DATA THREE - Should Pass

答:
Regardless of what I explained in comment, since you edited your question, maybe I can give you some answer.

If you create Customers 1 2 and 3 in feature A.
Let's say Customer 1 isn't created, but 2 and 3 are
In feature B, before you try to book a ticket for each Customer, you should simply check if that Customer exists, with a GET request for example.