问:
How to arrange the item position in ngFor
positionDetails: [
            {
                position: 20,
                positionType: "ABC"
            },
            {
                position: 1000,
                positionType: "XYZ"
            }]

```<code>        <div *ngFor="let pos of element.positionDetails" [ngSwitch]="pos.positionType">

        <span *ngSwitchCase="'XYZ'"> {{pos?.position }} {{pos?.positionType}}</span>

        <span *ngSwitchCase="'ABC'">{{pos?.position }} {{pos?.positionType}}  </span>

        </div>
</code>```

expected result: 1000 XYZ 20 ABC

答:
Try with a nested span for the ngSwitch like this:

```<code><div *ngFor="let pos of element.positionDetails">
    <span [ngSwitch]="pos.positionType">
        <span *ngSwitchCase="'XYZ'" class="base-points"> {{ pos?.position }} {{ pos?.positionType }} </span>
        <span *ngSwitchCase="'ABC'"> {{ pos?.position }} {{pos?.positionType }} / </span>
    </span>
</div>
</code>```

stackblitz DEMO: https://stackblitz.com/edit/angular-b2mqnc

Body:
positionDetails: [
            {
                position: 20,
                positionType: "ABC"
            },
            {
                position: 1000,
                positionType: "XYZ"
            }]

         {{pos?.position }} {{pos?.positionType}}

        {{pos?.position }} {{pos?.positionType}}

expected result: 1000 XYZ 20 ABC

Body:
Try with a nested span for the ngSwitch like this:

<div *ngFor="let pos of element.positionDetails">
    <span [ngSwitch]="pos.positionType">
        <span *ngSwitchCase="'XYZ'" class="base-points"> {{ pos?.position }} {{ pos?.positionType }} </span>
        <span *ngSwitchCase="'ABC'"> {{ pos?.position }} {{pos?.positionType }} / </span>
    </span>
</div>

stackblitz DEMO: https://stackblitz.com/edit/angular-b2mqnc


来源: stackexchange

问:
How to Map JSON data from a REST API to Azure SQL using Data Factory
I have a new pipeline in azure data factory.
I created the dataset, one from the rest api (a public one):
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo

and then I created an azure sql table with columns shown in the screenshot

The problem, is that I dont know how to do the mapping, as this is a complex JSON object, I am limited with the Mapping Designer:

How do I map the date?

答:
Does the data have a structure? If so, you can generate a dummy file, place it in sink and do a one time mapping. If not, you can Lookup on the file, iterate over the content in a For Each Loop Container and insert details on to a SQL table.

E.g.

```<code>insert <<your table>>
select '@item().name', '@item().address.city', @item().value
</code>```

The important thing to remember is to iterate at the correct array. Let me know if it's not clear. Not in front of a system right now, so can't add screenshots.

ContentLicense: CC BY-SA 4.0

Body:
Does the data have a structure? If so, you can generate a dummy file, place it in sink and do a one time mapping. If not, you can Lookup on the file, iterate over the content in a For Each Loop Container and insert details on to a SQL table.

E.g.

insert <<your table>>
select '@item().name', '@item().address.city', @item().value

The important thing to remember is to iterate at the correct array. Let me know if it's not clear. Not in front of a system right now, so can't add screenshots.


问:
How to import Angular Material in project?
I have installed Angular Material Design. Now I try to add this in app.module.ts file:

import { MaterialModule } from '@angular/material';
```

What I should decify in section: imports: []? that to load all material entities.

I tried: imports: ['MaterialModule'] but it is deprecated

答:
Starting from Angular version 9:

Breaking changes:

Components can no longer be imported through "@angular/material". Use
  the individual secondary entry-points, such as
  @angular/material/button.

This means that:

import { MatInputModule, MatCardModule } from "@angular/material";
```

<p>becomes:</p>

<pre class="lang-js prettyprint-override"><code>import { MatInputModule } from "@angular/material/input";
import { MatCardModule } from "@angular/material/card";
</code>```

Body:
I have installed Angular Material Design. Now I try to add this in app.module.ts file:

import { MaterialModule } from '@angular/material';

What I should decify in section: imports: []? that to load all material entities.

I tried: imports: ['MaterialModule'] but it is deprecated

Body:
Starting from Angular version 9:

Breaking changes:

Components can no longer be imported through "@angular/material". Use
  the individual secondary entry-points, such as
  @angular/material/button.

This means that:

import { MatInputModule, MatCardModule } from "@angular/material";

becomes:

import { MatInputModule } from "@angular/material/input";
import { MatCardModule } from "@angular/material/card";


问:
How to read excel file into json and send to CFC for database insertion?
I am reading an excel file using "xlsx.full.min.js" plugin and getting the file data into JSON object.Then I am sending this JSON object to Coldfusion Component (CFC) using jQuery Ajax , but it gives me an error as '400 Bad request'. The CFC is not getting the JSON data that I am trying to send. What is wrong in my code?

```<code>var selectedFile = evt.target.files[0];
                    var reader = new FileReader();

                    reader.onload = function(event) {

                          var data = event.target.result;
                          var workbook = XLSX.read(data, {
                              type: 'binary'
                          });

                          workbook.SheetNames.forEach(function(sheetName) {
                                 var excel_json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);

                                var json_object = JSON.stringify(excel_json);

                                $.ajax({
                                    url:"maps.cfc",
                                    dataType: "json",
                                    data: {
                                        method:"updateFuelPrices",
                                        jsstruct:json_object
                                    },

                                    success: function(data) {
                                        console.log(data);
                                        console.log("update successful");
                                    },
                                    error: function(xhr, textStatus, errorThrown) {
                                        console.log(textStatus);
                                        console.log(errorThrown);
                                        console.log("Something went wrong! Please refresh the page and try again.");
                                    }
                                })
                            })
                    };

                    reader.onerror = function(event) {
                      console.error("File could not be read! Code " + event.target.error.code);
                    };

                    reader.readAsBinaryString(selectedFile);
              });
</code>```

And my CFC function is:

```<code><cffunction name="updateFuelPrices"  output="false" access="remote" returnformat="json" returntype="string">
        <cfargument name="jsstruct" type='string' required="true">
        <cfset returntext = 'json sent successfully...'>
        <cfdump var="#ARGUMENTS.jsstruct#">
         <!--- DB insert query to go here --->
        <cfreturn returntext>
    </cffunction>
</code>```

答: Update: I solved this error by using the deserializeJSON() method in my CFC to decode the json received from javascript.</p>

Body:
I am reading an excel file using "xlsx.full.min.js" plugin and getting the file data into JSON object.Then I am sending this JSON object to Coldfusion Component (CFC) using jQuery Ajax , but it gives me an error as '400 Bad request'. The CFC is not getting the JSON data that I am trying to send. What is wrong in my code?

var selectedFile = evt.target.files[0];
                    var reader = new FileReader();

                    reader.onload = function(event) {

                          var data = event.target.result;
                          var workbook = XLSX.read(data, {
                              type: 'binary'
                          });

                          workbook.SheetNames.forEach(function(sheetName) {
                                 var excel_json = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);

                                var json_object = JSON.stringify(excel_json);

                                $.ajax({
                                    url:"maps.cfc",
                                    dataType: "json",
                                    data: {
                                        method:"updateFuelPrices",
                                        jsstruct:json_object
                                    },

                                    success: function(data) {
                                        console.log(data);
                                        console.log("update successful");
                                    },
                                    error: function(xhr, textStatus, errorThrown) {
                                        console.log(textStatus);
                                        console.log(errorThrown);
                                        console.log("Something went wrong! Please refresh the page and try again.");
                                    }
                                })
                            })
                    };

                    reader.onerror = function(event) {
                      console.error("File could not be read! Code " + event.target.error.code);
                    };

                    reader.readAsBinaryString(selectedFile);
              });

And my CFC function is:

<cffunction name="updateFuelPrices"  output="false" access="remote" returnformat="json" returntype="string">
        <cfargument name="jsstruct" type='string' required="true">
        <cfset returntext = 'json sent successfully...'>
        <cfdump var="#ARGUMENTS.jsstruct#">

        <cfreturn returntext>
    </cffunction>


问:
How to write outer join function in Flink using connect?
I want to act outer join on 2 data streams, and it is better not to put them in a window(I've seen Cogroup always comes with a window).

I tried this:

```<code>    val controlStream = Flink.flinkEnv.fromElements(
      (1, "mex1", "stream1_feat1"),
      (1, "mex2", "stream1_feat2")
    ).keyBy(x => (x._1, x._2))

    val wordStream = Flink.flinkEnv.fromElements(
      (1, "mex1", "stream2_feat1"),
      (1, "mex3", "stream2_feat3")
    ).keyBy(x => (x._1, x._2))

    val filteredStream = controlStream
        .connect(wordStream)
        .flatMap(new ControlFunction)

////////////////////////////////////////////////////////////////////////

class ControlFunction extends RichCoFlatMapFunction[
    (Int, String, String),
    (Int, String, String),
    (Int, String, String, String)] {

    // outer join
    private var state1: ValueState[(Int, String, String)] = _
    private var state2: ValueState[(Int, String, String)] = _

    override def open(parameters: Configuration): Unit = {
      state1 = getRuntimeContext.getState(
        new ValueStateDescriptor[(Int, String, String)]("s1", createTypeInformation[(Int, String, String)]))

      state2 = getRuntimeContext.getState(
        new ValueStateDescriptor[(Int, String, String)]("s2", createTypeInformation[(Int, String, String)]))

    }

    override def flatMap1(value: (Int, String, String),
                          out: Collector[(Int, String, String, String)]): Unit = {

      val state2Value = state2.value

      if (state2Value != null) {
        println("inside map1 not null")
        state2.clear()
        out.collect((value._1, value._2, value._3, state2Value._3))
      } else {
        println("inside map1 null")
        state1.update(value)
        out.collect((value._1, value._2, value._3, "NA"))
      }
    }

    override def flatMap2(value: (Int, String, String),
                          out: Collector[(Int, String, String, String)]): Unit = {

      val state1Value = state1.value

      if (state1Value != null) {
        println("inside map2 not null")
        state1.clear()
        out.collect((value._1, value._2, state1Value._3, value._3))
      } else {
        println("inside map2 null")
        state2.update(value)
        out.collect((value._1, value._2, "NA", value._3))
      }
    }

  }

</code>```

Which gave me:

```<code>5> (1,mex2,stream1_feat2,NA)
8> (1,mex1,stream1_feat1,NA)
2> (1,mex3,NA,stream2_feat3)
8> (1,mex1,stream1_feat1,stream2_feat1)
</code>```

Where record (1,mex1,stream1_feat1,NA) should not be produced.
The result that I want to achieve is an outer join:

```<code>5> (1,mex2,stream1_feat2,NA)
2> (1,mex3,NA,stream2_feat3)
8> (1,mex1,stream1_feat1,stream2_feat1)

</code>```

By getting the print statement, I found that the 2 flapMaps were passed in sequence, which made mex1 produced twice, anyway to resolve this?

Thanks in advance!

答:
You can't expect a streaming outer join to behave the same way as a batch outer join. A batch outer join can fully scan both input tables, and will only produce output rows containing nulls when matching records do not exist. With a streaming implementation, you can not know whether if by waiting you might eventually receive a matching record.

Because they can not access the future, stream processing applications are often forced to produce as output a stream that contains results that are being updated as more information becomes available.

One thing you could do would be to wait for some time to see if emitting a result containing an NA would be mistake, but eventually you'd have to stop waiting and produce a result.

Note that Flink's Table API has an outer join, but you'll notice it's marked as "Result Updating" for the reasons explained above.

Body:
I want to act outer join on 2 data streams, and it is better not to put them in a window(I've seen Cogroup always comes with a window).

I tried this:

    val controlStream = Flink.flinkEnv.fromElements(
      (1, "mex1", "stream1_feat1"),
      (1, "mex2", "stream1_feat2")
    ).keyBy(x => (x._1, x._2))

    val wordStream = Flink.flinkEnv.fromElements(
      (1, "mex1", "stream2_feat1"),
      (1, "mex3", "stream2_feat3")
    ).keyBy(x => (x._1, x._2))

    val filteredStream = controlStream
        .connect(wordStream)
        .flatMap(new ControlFunction)

////////////////////////////////////////////////////////////////////////

class ControlFunction extends RichCoFlatMapFunction[
    (Int, String, String),
    (Int, String, String),
    (Int, String, String, String)] {

    // outer join
    private var state1: ValueState[(Int, String, String)] = _
    private var state2: ValueState[(Int, String, String)] = _

    override def open(parameters: Configuration): Unit = {
      state1 = getRuntimeContext.getState(
        new ValueStateDescriptor[(Int, String, String)]("s1", createTypeInformation[(Int, String, String)]))

      state2 = getRuntimeContext.getState(
        new ValueStateDescriptor[(Int, String, String)]("s2", createTypeInformation[(Int, String, String)]))

    }

    override def flatMap1(value: (Int, String, String),
                          out: Collector[(Int, String, String, String)]): Unit = {

      val state2Value = state2.value

      if (state2Value != null) {
        println("inside map1 not null")
        state2.clear()
        out.collect((value._1, value._2, value._3, state2Value._3))
      } else {
        println("inside map1 null")
        state1.update(value)
        out.collect((value._1, value._2, value._3, "NA"))
      }
    }

    override def flatMap2(value: (Int, String, String),
                          out: Collector[(Int, String, String, String)]): Unit = {

      val state1Value = state1.value

      if (state1Value != null) {
        println("inside map2 not null")
        state1.clear()
        out.collect((value._1, value._2, state1Value._3, value._3))
      } else {
        println("inside map2 null")
        state2.update(value)
        out.collect((value._1, value._2, "NA", value._3))
      }
    }

  }

Which gave me:

5> (1,mex2,stream1_feat2,NA)
8> (1,mex1,stream1_feat1,NA)
2> (1,mex3,NA,stream2_feat3)
8> (1,mex1,stream1_feat1,stream2_feat1)

Where record (1,mex1,stream1_feat1,NA) should not be produced.
The result that I want to achieve is an outer join:

5> (1,mex2,stream1_feat2,NA)
2> (1,mex3,NA,stream2_feat3)
8> (1,mex1,stream1_feat1,stream2_feat1)

By getting the print statement, I found that the 2 flapMaps were passed in sequence, which made mex1 produced twice, anyway to resolve this?

Thanks in advance!


问:
Login only if user is active using Laravel
I'm currently working on my Laravel app and to prevent spam I decided that only active users are able to login.
I'm currently using Laravel's login system just like in Laravel's official website tutorial, here's my form action:

```<code><form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">
</code>```

This works completely fine, however I'd like to check the user's active, if not active it would be redirected to the activation page, otherwise it would login.
Is there a simple way to do this or am I obligated to make a new controller, routes and more verifications? Thank you.

Edit: Forgot to mention that I have a 'active' column in my database.

答:
Laravel 6.6 tested. Overwrite validateLogin in your LoginController.php

```<code>use Illuminate\Http\Request;
use App\User;
use Illuminate\Validation\ValidationException;
</code>```

......

```<code>/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 *
 * @throws \Illuminate\Validation\ValidationException
 */
protected function validateLogin(Request $request)
{
    // Get the user details from database and check if user is exist and active.
    $user = User::where('email',$request->email)->first();
    if( $user && !$user->activation){
        throw ValidationException::withMessages([$this->username() => __('User has been desactivated.')]);
    }

    // Then, validate input.
    return $request->validate([
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently working on my Laravel app and to prevent spam I decided that only active users are able to login.
I'm currently using Laravel's login system just like in Laravel's official website tutorial, here's my form action:

<form class="form-horizontal" role="form" method="POST" action="{{ url('/auth/login') }}">

This works completely fine, however I'd like to check the user's active, if not active it would be redirected to the activation page, otherwise it would login.
Is there a simple way to do this or am I obligated to make a new controller, routes and more verifications? Thank you.

Edit: Forgot to mention that I have a 'active' column in my database.

Body:
Laravel 6.6 tested. Overwrite validateLogin in your LoginController.php

use Illuminate\Http\Request;
use App\User;
use Illuminate\Validation\ValidationException;

......

/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 *
 * @throws \Illuminate\Validation\ValidationException
 */
protected function validateLogin(Request $request)
{
    // Get the user details from database and check if user is exist and active.
    $user = User::where('email',$request->email)->first();
    if( $user && !$user->activation){
        throw ValidationException::withMessages([$this->username() => __('User has been desactivated.')]);
    }

    // Then, validate input.
    return $request->validate([
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}


问:
PUT request returning '200 - updated' or '200 - partially updated' but not updating in PHP cURL
I am having some trouble making a PUT call to an external API using cURL PHP, the response I am getting all the time is {"status":1,"info":"Updated"}Status code: 200 which should mean that the changes have been properly saved onto the API. But everytime I check, there has not been any change at all.

For your better understanding, this is the process I am following:

The API holds documents such as bills and so, at this moment, I am using two different documents. First, I get one of them and extract the information to store it inside an array. Next, I do the same with the second document to finally do an array_push and annex one array to the other.

My ultimate goal here was to update one of the original documents maintaining its data while adding info from another different document. I can't just create a new document nor delete the existing one and post a new one. The only other option the API gives is by using put.

At first the only answer I got was the one I wrote above. Then, inspecting more carefully the documentation, I saw that there are discrepancies between how some things  are called.

This is a sample test document I am using to try things out:

```<code>{
    "id": "5e4cf5676a97281ab7116036",
    "contact": "5db0745c6a972835922bfac9",
    "contactName": "Tiempos mejores vendrán",
    "desc": "TEST",
    "date": 1580979341,
    "dueDate": null,
    "notes": "hola",
    "tags": [
        "cp"
    ],
    "products": [
        {
            "name": "hola",
            "desc": "IVA",
            "price": 200,
            "units": 1,
            "tax": 10,
            "taxes": [
                "s_iva_10"
            ],
            "tags": [],
            "discount": 0,
            "retention": 0,
            "weight": 0,
            "costPrice": 0,
            "sku": 0,
            "account": "5cd98e656a9728325261db7a"
        }
    ],
    "tax": 20,
    "subtotal": 200,
    "discount": 0,
    "total": 220,
    "language": "es",
    "status": 0,
</code>```

And here is the Ajax example found inside the documentation which actually works when done from postman (I am using this as my document 2 data):

```<code>"date": 1580979341,
"items": [
    {
        "name": "hola",
        "desc": "IVA",
        "subtotal": 200,
        "taxes": [
            "s_iva_10"
        ],
        "units": 1
    }
]
</code>```

As you might notice, the API returns products while the example says it's items. Since that is the only part I really need to update, I started wrapping my array with another one like this:

$receipt = fetchCoSalesReceipt($receiptId, $uri4, $token);
array_push($receipt['products'], $items);
$arrayItems['items'] = $receipt['products'];
```

<p>Where <code>$items</code> is the array containing the information of the document 1. I created <code>$arrayItems</code> to just store and update that part as the API described.</p>

<p>The thing is, now that I've done so, the response I am getting has become: <code>{"status":1,"info":"Updated partially. Sku's not founds: 0, 0, 0, 0, 0, "}Status code: 200 int(1</code></p>

<p>With this being the json I am passing to the <code>put</code> function:</p>

<pre class="lang-php prettyprint-override"><code>{
    "items": [
        {
            "name": "hola",
            "desc": "IVA",
            "price": 200,
            "units": 1,
            "tax": 10,
            "taxes": [
                "s_iva_10"
            ],
            "tags": [],
            "discount": 0,
            "retention": 0,
            "weight": 0,
            "costPrice": 0,
            "sku": 0,
            "account": "5cd98e656a9728325261db7a"
        },
        [
            {
                "name": "Llamadas Fijos nacionales",
                "subtotal": "374.776444",
                "tax": 21
            },
            {
                "name": "Llamadas Moviles nacionales",
                "subtotal": "460.440000",
                "tax": 21
            },
            {
                "name": "Llamadas Premium 902 Nivel 1",
                "subtotal": "87.301236",
                "tax": 21
            }
        ]
    ]
}
</code>```

As you see, I maintain the original data stored, only to add some new info. Once again, in the documentation there is a dummy code which you can use to try, and inside items, there is this thing called sku. But leaving it empty or 0 works fine there, I don't really know what could this be, what could I have done wrong or why. I've been trying all day to get past this issue, but to no avail.

This first pic shows the items structure:

Here is a piece of the API's documentation code where you can see the json has the same format as the one I am using. In fact, all the json fragments I am posting seem to be like the one I am using. But here, the code works and updates as it should:

Lastly. here is the function:

function updateReceipt($receiptId, $uri4, $arrayItems, $token){
    $ch = curl_init();

    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $uri4.$receiptId,
        CURLOPT_CUSTOMREQUEST => 'PUT',
        CURLOPT_POSTFIELDS => json_encode($arrayItems),
        CURLOPT_HTTPHEADER => array("Content-Type: application/json", "key: ".$token)
    );
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    echo "Status code: $http_code ";

    curl_close($ch);

    return $response;
}

```

As I said, I don't know why sometimes it can update, why others not

答:
The answer to this question lies completely inside the way the API works, so there is little to explain here.

As I said, I kinda had to merge two documents already existing, but the api returned an array where some of the keys were not the same as the ones you have to use to upload:

API returned array['price'], but for updating or posting, that same key would become array['subtotal']. And there were a few more like this one.

In the end, I managed to change the key values from a GET to the posting ones. That was the solution.

Body:
I am having some trouble making a PUT call to an external API using cURL PHP, the response I am getting all the time is {"status":1,"info":"Updated"}Status code: 200 which should mean that the changes have been properly saved onto the API. But everytime I check, there has not been any change at all.

For your better understanding, this is the process I am following:

The API holds documents such as bills and so, at this moment, I am using two different documents. First, I get one of them and extract the information to store it inside an array. Next, I do the same with the second document to finally do an array_push and annex one array to the other.

My ultimate goal here was to update one of the original documents maintaining its data while adding info from another different document. I can't just create a new document nor delete the existing one and post a new one. The only other option the API gives is by using put.

At first the only answer I got was the one I wrote above. Then, inspecting more carefully the documentation, I saw that there are discrepancies between how some things  are called.

This is a sample test document I am using to try things out:

{
    "id": "5e4cf5676a97281ab7116036",
    "contact": "5db0745c6a972835922bfac9",
    "contactName": "Tiempos mejores vendrán",
    "desc": "TEST",
    "date": 1580979341,
    "dueDate": null,
    "notes": "hola",
    "tags": [
        "cp"
    ],
    "products": [
        {
            "name": "hola",
            "desc": "IVA",
            "price": 200,
            "units": 1,
            "tax": 10,
            "taxes": [
                "s_iva_10"
            ],
            "tags": [],
            "discount": 0,
            "retention": 0,
            "weight": 0,
            "costPrice": 0,
            "sku": 0,
            "account": "5cd98e656a9728325261db7a"
        }
    ],
    "tax": 20,
    "subtotal": 200,
    "discount": 0,
    "total": 220,
    "language": "es",
    "status": 0,

And here is the Ajax example found inside the documentation which actually works when done from postman (I am using this as my document 2 data):

"date": 1580979341,
"items": [
    {
        "name": "hola",
        "desc": "IVA",
        "subtotal": 200,
        "taxes": [
            "s_iva_10"
        ],
        "units": 1
    }
]

As you might notice, the API returns products while the example says it's items. Since that is the only part I really need to update, I started wrapping my array with another one like this:

$receipt = fetchCoSalesReceipt($receiptId, $uri4, $token);
array_push($receipt['products'], $items);
$arrayItems['items'] = $receipt['products'];

Where $items is the array containing the information of the document 1. I created $arrayItems to just store and update that part as the API described.

The thing is, now that I've done so, the response I am getting has become: {"status":1,"info":"Updated partially. Sku's not founds: 0, 0, 0, 0, 0, "}Status code: 200 int(1

With this being the json I am passing to the put function:

{
    "items": [
        {
            "name": "hola",
            "desc": "IVA",
            "price": 200,
            "units": 1,
            "tax": 10,
            "taxes": [
                "s_iva_10"
            ],
            "tags": [],
            "discount": 0,
            "retention": 0,
            "weight": 0,
            "costPrice": 0,
            "sku": 0,
            "account": "5cd98e656a9728325261db7a"
        },
        [
            {
                "name": "Llamadas Fijos nacionales",
                "subtotal": "374.776444",
                "tax": 21
            },
            {
                "name": "Llamadas Moviles nacionales",
                "subtotal": "460.440000",
                "tax": 21
            },
            {
                "name": "Llamadas Premium 902 Nivel 1",
                "subtotal": "87.301236",
                "tax": 21
            }
        ]
    ]
}

As you see, I maintain the original data stored, only to add some new info. Once again, in the documentation there is a dummy code which you can use to try, and inside items, there is this thing called sku. But leaving it empty or 0 works fine there, I don't really know what could this be, what could I have done wrong or why. I've been trying all day to get past this issue, but to no avail.

This first pic shows the items structure:

Here is a piece of the API's documentation code where you can see the json has the same format as the one I am using. In fact, all the json fragments I am posting seem to be like the one I am using. But here, the code works and updates as it should:

Lastly. here is the function:

function updateReceipt($receiptId, $uri4, $arrayItems, $token){
    $ch = curl_init();

    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $uri4.$receiptId,
        CURLOPT_CUSTOMREQUEST => 'PUT',
        CURLOPT_POSTFIELDS => json_encode($arrayItems),
        CURLOPT_HTTPHEADER => array("Content-Type: application/json", "key: ".$token)
    );
    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);
    $response = json_decode($response, true);

    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    echo "Status code: $http_code ";

    curl_close($ch);

    return $response;
}

As I said, I don't know why sometimes it can update, why others not


问:
C#: How do I call a static method of a base class from a static method of a derived class?
In C#, I have base class Product and derived class Widget.

Product contains a static method MyMethod().

I want to call static method Product.MyMethod() from static method Widget.MyMethod().

I can't use the base keyword, because that only works with instance methods.

I can call Product.MyMethod() explicitly, but if I later change Widget to derive from another class, I have to revise the method.

Is there some syntax in C# similar to base that allows me to call a static method from a base class from a static method of a derived class?

答:
Static methods are not polymorphic, so what you want to do is impossible.

Trying to find a way to treat static methods as polymorphic is possible but dangerous, because the language itself doesn't support it.

Some suggestions:

Reflection

Aliasing the base class (such as Mehrdad's example)

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Michael Meadows


问:
How to map over Applicative form?
I want to map over Applicative form.

The type of map-like function would be like below:

```<code>mapX :: (Applicative f) => (f a -> f b) -> f [a] -> f [b]
</code>```

used as:

```<code>result :: (Applicative f) => f [b]
result = mapX f xs
  where f  :: f a -> f b
        f = ...
        xs :: f[a]
        xs = ...
</code>```

As the background of this post, I try to write fluid simulation program using Applicative style referring to Paul Haduk's "The Haskell School of Expression", and I want to express the simulation with Applicative style as below:

```<code>x, v, a :: Sim VArray
x = x0 +: integral (v * dt)
v = v0 +: integral (a * dt)
a = (...calculate acceleration with x v...)

instance Applicative Sim where
  ...
</code>```

where Sim type means the process of simulation computation and VArray means Array of Vector (x,y,z). X, v a are the arrays of position, velocity and acceleration, respectively.

Mapping over Applicative form comes when definining a.

I've found one answer to my question.

After all, my question is "How to lift high-order functions (like map
:: (a -> b) -> [a] -> [b]) to the Applicative world?" and the answer
I've found is "To build them using lifted first-order functions."

For example, the "mapX" is defined with lifted first-order functions
(headA, tailA, consA, nullA, condA) as below:

```<code>mapX :: (f a -> f b) -> f [a] -> f [b]
mapX f xs0 = condA (nullA xs0) (pure []) (consA (f x) (mapA f xs))
 where
   x = headA xs0
   xs = tailA xs0

headA = liftA head

tailA = liftA tail

consA = liftA2 (:)

nullA = liftA null

condA b t e = liftA3 aux b t e
  where aux b t e = if b then t else e
</code>```

答:
First, I don't think your proposed type signature makes much sense. Given an applicative list f [a] there's no general way to turn that into [f a] -- so there's no need for a function of type f a -> f b. For the sake of sanity, we'll reduce that function to a -> f b (to transform that into the other is trivial, but only if f is a monad).

So now we want:

```<code>mapX :: (Applicative f) => (a -> f b) -> f [a] -> f [b]
</code>```

What immediately comes to mind now is traverse which is a generalization of mapM. Traverse, specialized to lists:

```<code>traverse :: (Applicative f) => (a -> f b) -> [a] -> f [b]
</code>```

Close, but no cigar. Again, we can lift traverse to the required type signature, but this requires a monad constraint: mapX f xs = xs >>= traverse f.

If you don't mind the monad constraint, this is fine (and in fact you can do it more straightforwardly just with mapM). If you need to restrict yourself to applicative, then this should be enough to illustrate why you proposed signature isn't really possible.

Edit: based on further information, here's how I'd start to tackle the underlying problem.

```<code>-- your sketch
a = liftA sum $ mapX aux $ liftA2 neighbors (x!i) nbr
   where aux :: f Int -> f Vector3
   -- the type of "liftA2 neighbors (x!i) nbr" is "f [Int]

-- my interpretation
a = liftA2 aux x v
    where
       aux :: VArray -> VArray -> VArray
       aux xi vi = ...
</code>```

If you can't write aux like that -- as a pure function from the positions and velocities at one point in time to the accelerations, then you have bigger problems...

Here's an intuitive sketch as to why. The stream applicative functor takes a value and lifts it into a value over time -- a sequence or stream of values. If you have access to a value over time, you can derive properties of it. So velocity can be defined in terms of acceleration, position can be defined in terms of velocity, and soforth. Great! But now you want to define acceleration in terms of position and velocity. Also great! But you should not need, in this instance, to define acceleration in terms of velocity over time. Why, you may ask? Because velocity over time is all acceleration is to begin with. So if you define a in terms of dv, and v in terms of integral(a) then you've got a closed loop, and your equations are not propertly determined -- either there are, even given initial conditions, infinitely many solutions, or there are no solutions at all.

Title: How to map over Applicative form?

Body:
I want to map over Applicative form.

The type of map-like function would be like below:

mapX :: (Applicative f) => (f a -> f b) -> f [a] -> f [b]

used as:

result :: (Applicative f) => f [b]
result = mapX f xs
  where f  :: f a -> f b
        f = ...
        xs :: f[a]
        xs = ...

As the background of this post, I try to write fluid simulation program using Applicative style referring to Paul Haduk's "The Haskell School of Expression", and I want to express the simulation with Applicative style as below:

x, v, a :: Sim VArray
x = x0 +: integral (v * dt)
v = v0 +: integral (a * dt)
a = (...calculate acceleration with x v...)

instance Applicative Sim where
  ...

where Sim type means the process of simulation computation and VArray means Array of Vector (x,y,z). X, v a are the arrays of position, velocity and acceleration, respectively.

Mapping over Applicative form comes when definining a.

I've found one answer to my question.

After all, my question is "How to lift high-order functions (like map
:: (a -> b) -> [a] -> [b]) to the Applicative world?" and the answer
I've found is "To build them using lifted first-order functions."

For example, the "mapX" is defined with lifted first-order functions
(headA, tailA, consA, nullA, condA) as below:

mapX :: (f a -> f b) -> f [a] -> f [b]
mapX f xs0 = condA (nullA xs0) (pure []) (consA (f x) (mapA f xs))
 where
   x = headA xs0
   xs = tailA xs0

headA = liftA head

tailA = liftA tail

consA = liftA2 (:)

nullA = liftA null

condA b t e = liftA3 aux b t e
  where aux b t e = if b then t else e

Body:
First, I don't think your proposed type signature makes much sense. Given an applicative list f [a] there's no general way to turn that into [f a] -- so there's no need for a function of type f a -> f b. For the sake of sanity, we'll reduce that function to a -> f b (to transform that into the other is trivial, but only if f is a monad).

So now we want:

mapX :: (Applicative f) => (a -> f b) -> f [a] -> f [b]

What immediately comes to mind now is traverse which is a generalization of mapM. Traverse, specialized to lists:

traverse :: (Applicative f) => (a -> f b) -> [a] -> f [b]

Close, but no cigar. Again, we can lift traverse to the required type signature, but this requires a monad constraint: mapX f xs = xs >>= traverse f.

If you don't mind the monad constraint, this is fine (and in fact you can do it more straightforwardly just with mapM). If you need to restrict yourself to applicative, then this should be enough to illustrate why you proposed signature isn't really possible.

Edit: based on further information, here's how I'd start to tackle the underlying problem.

-- your sketch
a = liftA sum $ mapX aux $ liftA2 neighbors (x!i) nbr
   where aux :: f Int -> f Vector3
   -- the type of "liftA2 neighbors (x!i) nbr" is "f [Int]

-- my interpretation
a = liftA2 aux x v
    where
       aux :: VArray -> VArray -> VArray
       aux xi vi = ...

If you can't write aux like that -- as a pure function from the positions and velocities at one point in time to the accelerations, then you have bigger problems...

Here's an intuitive sketch as to why. The stream applicative functor takes a value and lifts it into a value over time -- a sequence or stream of values. If you have access to a value over time, you can derive properties of it. So velocity can be defined in terms of acceleration, position can be defined in terms of velocity, and soforth. Great! But now you want to define acceleration in terms of position and velocity. Also great! But you should not need, in this instance, to define acceleration in terms of velocity over time. Why, you may ask? Because velocity over time is all acceleration is to begin with. So if you define a in terms of dv, and v in terms of integral(a) then you've got a closed loop, and your equations are not propertly determined -- either there are, even given initial conditions, infinitely many solutions, or there are no solutions at all.


问:
How do I make a while loop to ask the user if they want to restart the program
I'm trying to create a text  to speech program that keeps looping until the user decides to quit; here's my code:</p>

```<code># IMPORT
import gtts as gTTS
import os

# TTS
myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

# Restart
restart = False
while restart == False:
    question = raw_input(input("Do you want to continue yes / no ? ")
if question = "yes"
    print(myText)
else:
    quit

</code>```

答:
You can use exit(), or quit(), or import os; os._exit(0) that forcefully exits the program, or import  sys; sys.exit([error message]) that raises SystemExit.

import gtts as gTTS
import os

myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

restart = False
while not restart:
    question = input("Do you want to continue yes / no ? ")
    if question == "yes":  # error was here
        print(myText)
    else:
        os._exit(0)
        # Or even just set restart to True and the loop will break
        # restart = True
```

Body:
I'm trying to create a text  to speech program that keeps looping until the user decides to quit; here's my code:

# IMPORT
import gtts as gTTS
import os

# TTS
myText = input("Enter your text: ")

language = 'en'

output = gTTS.gTTS(text=myText, lang=language, slow=False,)

output.save("output.mp3")

os.system("start output.mp3")

# Restart
restart = False
while restart == False:
    question = raw_input(input("Do you want to continue yes / no ? ")
if question = "yes"
    print(myText)
else:
    quit


问:
How to fetch images from database in base64_encode in php
Thank you all in advance....
I am doing a project in which I have a field to store the image. In that form, the image uploaded is completed with croppie plugin. and I stored the data in base 64 encodings. But I cannot fetch it to a page called view.php but the images are fetched to the form after cropping.

Please help me to figure it out the mistake that I have done

```<code><tbody>
    <?php
    $no = 1;
    $data = mysqli_query($con, "SELECT * FROM `register`  WHERE app_registration IS NULL   ORDER BY `app_id` DESC ");
    while ($row = mysqli_fetch_assoc($data)) {
    ?>
        <tr>
            <td><?php echo $row['app_id'] ?></td>
            <?php if (!empty($row['image_reference_id'])) {
                $data1 = mysqli_query($con, "SELECT * FROM `photo_table`  WHERE image_unique_id = '" . $row['image_reference_id'] . "'");
                $row1 = mysqli_fetch_assoc($data1)
                ?>
                <td><img src="data:image/jpg;base64,'.base64_encode($row['images']).'"/></td>
            <?php } else {
                ?>
                <td><img src="../images/<?php echo $row['app_image'] ?>" style="width: 100px;     height: 100px;"></td>
            <?php } ?>
            <td><?php echo $row['app_name'] ?></td>
            <td><?php echo $row['app_mobile_no_1'] ?></td>
        </tr>
    <?php } ?>
</tbody>
</code>```

Note: In db the images are in Long Blob

答:
You will need to change the following:

```<code><img src="data:image/jpg;base64,'.base64_encode($row['images']).'"  />
</code>```

to

```<code><img src="data:image/jpg;base64, <?php base64_encode($row['images']);?>"  />
</code>```

Body:
Thank you all in advance....
I am doing a project in which I have a field to store the image. In that form, the image uploaded is completed with croppie plugin. and I stored the data in base 64 encodings. But I cannot fetch it to a page called view.php but the images are fetched to the form after cropping.

Please help me to figure it out the mistake that I have done

    <?php
    $no = 1;
    $data = mysqli_query($con, "SELECT * FROM `register`  WHERE app_registration IS NULL   ORDER BY `app_id` DESC ");
    while ($row = mysqli_fetch_assoc($data)) {
    ?>

            <?php echo $row['app_id'] ?>
            <?php if (!empty($row['image_reference_id'])) {
                $data1 = mysqli_query($con, "SELECT * FROM `photo_table`  WHERE image_unique_id = '" . $row['image_reference_id'] . "'");
                $row1 = mysqli_fetch_assoc($data1)
                ?>

            <?php } else {
                ?>
                <img src="../images/<?php echo $row['app_image'] ?>" style="width: 100px;     height: 100px;">
            <?php } ?>
            <?php echo $row['app_name'] ?>
            <?php echo $row['app_mobile_no_1'] ?>

    <?php } ?>

Note: In db the images are in Long Blob

Body:
You will need to change the following:

<img src="data:image/jpg;base64,'.base64_encode($row['images']).'"  />

to

<img src="data:image/jpg;base64, <?php base64_encode($row['images']);?>"  />


问:
Static function leading to more static functions
I have a class that has a few functions that are useful on their own, which are static. Now these functions depend on other functions that are not useful on their own (but don't interact with class member variables) but are also static, so they are private. Now I have a class with many non-static functions, and couple of static public functions and a few static private functions.

Is this good practice? (should I be making this a community wiki?)

答:
That sounds good, and would work well. There are some things to consider though.

It may be possible to make the private static functions even more private. If you just placed them in the .cpp file as free functions (not in a class, but ideally in an 'unnamed namespace'), then they wouldn't make an appearance in the .h file. This would be advantageous because another .cpp file that uses your class wouldn't see these private static variables. That would make the compile time quicker. Also, it would leave you free to alter the functions in the .cpp file, and if you made any changes, other files using the .h file wouldn't need to be recompiled on every change because you wouldn't have to change the .h file to change these functions.

Secondly, sometimes static functions can cause the writing of unit tests to be trickier. If you have a class X that uses these static functions, it's tricky to isolate class X from the static functions if you want to test class X. If instead, you used non static methods and defined an interface class that the class you're writing derives from, you could more easily use 'inversion of control' and 'dependency injection' techniques to write unit tests for your classes. I won't explain those techniques here, as there are plenty of good descriptions already floating about the internet.


问:
Illegal redeclaration of 'synaptic_core'
I am compiling an SNN simulator named "ODIN" in Xilinx. for the name of the module i get this error. Can you help me with this?

Illegal redeclaration of 'synaptic_core'

```<code>module synaptic_core #(
parameter N = 256,
parameter M = 8
)(

// Global inputs ------------------------------------------
input  wire           RSTN_syncn,
input  wire           CLK,

// Inputs from SPI configuration registers ----------------
input  wire           SPI_GATE_ACTIVITY_sync,
input  wire [  N-1:0] SPI_SYN_SIGN,
input  wire           SPI_UPDATE_UNMAPPED_SYN,

// Inputs from controller ---------------------------------
input  wire [    7:0] CTRL_PRE_EN,
input  wire           CTRL_BIST_REF,
input  wire           CTRL_SYNARRAY_WE,
input  wire [   12:0] CTRL_SYNARRAY_ADDR,
input  wire           CTRL_SYNARRAY_CS,
input  wire [2*M-1:0] CTRL_PROG_DATA,
input  wire [2*M-1:0] CTRL_SPI_ADDR,

// Inputs from neurons ------------------------------------
input  wire [  N-1:0] NEUR_V_UP,
input  wire [  N-1:0] NEUR_V_DOWN,

// Outputs ------------------------------------------------
output wire [   31:0] SYNARRAY_RDATA,
output wire [   31:0] SYNARRAY_WDATA,
output wire           SYN_SIGN
</code>```

);

答:
You probably declared the 'synaptic_core' somewhere before in the code.

From the https://www.xilinx.com/support/answers/18361.html :

Examine your Verilog code prior to the line number listed in the error to see where the name listed has been declared. The name might have been used in a different manner (as a module name, parameter, task, function, etc.) or referenced in a different file (accessed by an "include statement," for example).

Body:
I am compiling an SNN simulator named "ODIN" in Xilinx. for the name of the module i get this error. Can you help me with this?

Illegal redeclaration of 'synaptic_core'

module synaptic_core #(
parameter N = 256,
parameter M = 8
)(

// Global inputs ------------------------------------------
input  wire           RSTN_syncn,
input  wire           CLK,

// Inputs from SPI configuration registers ----------------
input  wire           SPI_GATE_ACTIVITY_sync,
input  wire [  N-1:0] SPI_SYN_SIGN,
input  wire           SPI_UPDATE_UNMAPPED_SYN,

// Inputs from controller ---------------------------------
input  wire [    7:0] CTRL_PRE_EN,
input  wire           CTRL_BIST_REF,
input  wire           CTRL_SYNARRAY_WE,
input  wire [   12:0] CTRL_SYNARRAY_ADDR,
input  wire           CTRL_SYNARRAY_CS,
input  wire [2*M-1:0] CTRL_PROG_DATA,
input  wire [2*M-1:0] CTRL_SPI_ADDR,

// Inputs from neurons ------------------------------------
input  wire [  N-1:0] NEUR_V_UP,
input  wire [  N-1:0] NEUR_V_DOWN,

// Outputs ------------------------------------------------
output wire [   31:0] SYNARRAY_RDATA,
output wire [   31:0] SYNARRAY_WDATA,
output wire           SYN_SIGN

);


问:
Nodejs - Variable initialized inside a function is undefined outside it
I have a nodejs module which is supposed to convert a csv file to json, however the variable which is supposed to hold the json array is undefined outside the function, even though it's declared outside.

const csvFilePath='data.csv'
const csv=require('csvtojson')
let userDB;

const loadUserDB = async() => {
  userDB = await csv().fromFile(csvFilePath);
  console.log(userDB[0]);
  return userDB;
};

console.log(userDB[0]);

module.exports = {
  loadUserDB,
  userDB
}```

I'm new to nodejs so I couldn't figure it out, any ideas?

答: You should probably wait for the asynchronous function to run before you access the variable (or remove the async). Edit: And you never call loadUserDB, at least not in this code. I suggest that, instead of using a wider scoped variable, you simply await the result of your function.

Body:
I have a nodejs module which is supposed to convert a csv file to json, however the variable which is supposed to hold the json array is undefined outside the function, even though it's declared outside.

const csvFilePath='data.csv'
const csv=require('csvtojson')
let userDB;

const loadUserDB = async() => {
  userDB = await csv().fromFile(csvFilePath);
  console.log(userDB[0]);
  return userDB;
};

console.log(userDB[0]);

module.exports = {
  loadUserDB,
  userDB
}

I'm new to nodejs so I couldn't figure it out, any ideas?


问:
How add values in different objects in an array?
How can I access only the first @NOTIFICATION_OPENED key?

How can I sum both values of @NOTIFICATION_OPENED?

This is my AJAX request:

```<code>$.getJSON("myapiurl", function(notificationData) {
  $.each(notificationData.data, function(index, value) {
    if (value["@NOTIFICATION_OPENED"]) {
      var notificationOpened = value["@NOTIFICATION_OPENED"]
    } else
      notificationOpened = 0;

    var val = {
      "notificationOpened": notificationOpened
    }
    _data.push(val)
  });
}
</code>```

This is the data I retrieve from the API using the above request:

```<code>{
  "data": [{
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  }, {
    "date": 1577923200000,
    "@NOTIFICATION_OPENED": 734
  }]
</code>```

答:
I have added a square bracket to make it valid JSON:

```<code>const data =
[
  {
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  },
  {
   "date": 1577923200000,
   "@NOTIFICATION_OPENED": 734
  }
 ]

let nSent   = data[0]["@NOTIFICATION_SENT"]
let nOpened = data[0]["@NOTIFICATION_OPENED"]
let mySum   = nSent+nOpened

alert(mySum)
</code>```

This will produce an alert with the sum 63033

Body:
How can I access only the first @NOTIFICATION_OPENED key?

How can I sum both values of @NOTIFICATION_OPENED?

This is my AJAX request:

$.getJSON("myapiurl", function(notificationData) {
  $.each(notificationData.data, function(index, value) {
    if (value["@NOTIFICATION_OPENED"]) {
      var notificationOpened = value["@NOTIFICATION_OPENED"]
    } else
      notificationOpened = 0;

    var val = {
      "notificationOpened": notificationOpened
    }
    _data.push(val)
  });
}

This is the data I retrieve from the API using the above request:

{
  "data": [{
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  }, {
    "date": 1577923200000,
    "@NOTIFICATION_OPENED": 734
  }]

Body:
I have added a square bracket to make it valid JSON:

const data =
[
  {
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  },
  {
   "date": 1577923200000,
   "@NOTIFICATION_OPENED": 734
  }
 ]

let nSent   = data[0]["@NOTIFICATION_SENT"]
let nOpened = data[0]["@NOTIFICATION_OPENED"]
let mySum   = nSent+nOpened

alert(mySum)

This will produce an alert with the sum 63033


Title: Sort an array that has highest point?

Body:
How do I sort array that has highest point from 15.00 key?

I have an array look like this:

Array
(

    [9] => Array
        (
            [15.00] => 3.0
            [20.00] => 8.0
            [25.00] => 10.5
        )

    [2] => Array
        (
            [15.00] => 2.0
            [20.00] => 5.0
            [25.00] => 2.5
        )

    [4] => Array
        (
            [15.00] => 6.0
            [25.00] => 4.0
            [30.00] => 6.0
        )
)

In order it should be: 4, 9 and 2

Body:
You want uasort():

function cmp($a, $b) {
  if ($a[15.00] < $b[15.00]) return 1;
  if ($a[15.00] > $b[15.00]) return -1;
  return 0;
}

uasort($data, "cmp");


问:
How can I disable some dates range in a fullcalendar?
I want to disable days before and after dates range, anybody know how can I do that? (sorry for my english).

Hernan

答:
In fullCalendar v3 we can use selectConstraint

```<code>selectConstraint: {
   start: moment().format('YYYY-MM-DD'),
   end: '2200-01-01'
},
</code>```

if you don't want an event to be droppable in past days you can use

```<code>eventConstraint: {
  start: moment().format('YYYY-MM-DD'),
  end: '2200-01-01'
},
</code>```

Body:
In fullCalendar v3 we can use selectConstraint

selectConstraint: {
   start: moment().format('YYYY-MM-DD'),
   end: '2200-01-01'
},

if you don't want an event to be droppable in past days you can use

eventConstraint: {
  start: moment().format('YYYY-MM-DD'),
  end: '2200-01-01'
},


问:
Can I create a thumbnail from a PDF file with Filestack?
I am using Filestack to manage image files on a project I am working on. Can I create a thumbnail using Filestack's API, and how do I do it?</p>

答:
It's actually pretty easy. You can use their file conversions api for this, check https://www.filestack.com/docs/api/processing/

There are a lot of options, you can choose which page(s), output format, etc.

So for example if you uploaded a pdf to filestack with handle abcd1234 you can get a quick jpg thumbnail by using https://cdn.filestackcontent.com/output=format:jpg/abcd1234


问:
Optimize query with many AND statements in WHERE clause
is it possible to optimize this sql query in order to have better execution time in case of big sized tables</p>

```<code>SELECT X.id,X.id2
FROM Table X, Table Y, Table Z, Table W
WHERE  Y.id = 1
        AND Y.dt = Z.dty
        AND Z.el = 2
        AND Z.id = W.idz
        AND W.idx = X.id
</code>```

答:
Use proper standard explicit JOIN Syntax instead of commas:

```<code>SELECT X.id, X.id2
FROM Table X INNER JOIN
     Table W
     ON W.idx = X.id INNER JOIN
     Table Z
     ON Z.id = W.idz INNER JOIN
     Table Y
     ON Y.dt = Z.dty
WHERE Y.id = 1 AND Z.el = 2;
</code>```

Just make sure you will have indexes on X(ID), W(idx), Z(id,dty,el), Y(dt,id)

Body:
is it possible to optimize this sql query in order to have better execution time in case of big sized tables

SELECT X.id,X.id2
FROM Table X, Table Y, Table Z, Table W
WHERE  Y.id = 1
        AND Y.dt = Z.dty
        AND Z.el = 2
        AND Z.id = W.idz
        AND W.idx = X.id

Body:
Use proper standard explicit JOIN Syntax instead of commas:

SELECT X.id, X.id2
FROM Table X INNER JOIN
     Table W
     ON W.idx = X.id INNER JOIN
     Table Z
     ON Z.id = W.idz INNER JOIN
     Table Y
     ON Y.dt = Z.dty
WHERE Y.id = 1 AND Z.el = 2;

Just make sure you will have indexes on X(ID), W(idx), Z(id,dty,el), Y(dt,id)


问:
There is a problem in pipelines file as it is not fetching the book name. instead saving one random image with None.jpg for each crawl
items.py file. as i was aware of the image_urls and images field. It didn't create any problem.

```<code>import scrapy
from scrapy.loader.processors import TakeFirst

class BooksToScrapeItem(scrapy.Item):
    image_urls = scrapy.Field()
    images = scrapy.Field()
    book_name = scrapy.Field(
        output_processor = TakeFirst()
    )
</code>```

pipelines.py file. I think there must be a problem in the get_media_request method as it is not fetching the book_name from items file

```<code>from scrapy.pipelines.images import ImagesPipeline
from scrapy import Request

class BooksToScrapeImagePipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        return [Request(x,meta={'bookname': item.get('book_name')}) for x in item.get(self.images_urls_field, [])] #i think that the problem is in this line

    def file_path(self, request, response=None, info=None):

        return 'full/%s.jpg' % (request.meta['bookname'])
</code>```

spider file which I user for scraping.It worked when i didnt customized the pipeline file.

```<code>import scrapy
from scrapy.loader import ItemLoader
from books_to_scrape.items import BooksToScrapeItem

class ImgscrapeSpider(scrapy.Spider):
    name = 'imgscrape'
    allowed_domains = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com']

    def parse(self, response):
        for article in response.xpath("//article[@class='product_pod']"):
            loader = ItemLoader(item=BooksToScrapeItem(),selector=article)
            relative_url = article.xpath(".//div/a/img[@class='thumbnail']/@src").extract_first()
            abs_url = response.urljoin(relative_url)
            loader.add_value('image_urls',abs_url)
            loader.add_xpath('book_name',".//article[@class='product_pod']/h3/a/text()")
            yield loader.load_item()
</code>```

答:
Your problem is in relative xpath

```<code>loader.add_xpath('book_name', ".//article[@class='product_pod']/h3/a/text()")
</code>```

Loader uses xpath("//article[@class='product_pod']") as selector

```<code>   for article in response.xpath("//article[@class='product_pod']"):
        loader = ItemLoader(item=BooksToScrapeItem(), selector=article)
</code>```

so all relative xpaths are relative to "//article[@class='product_pod']" and they don't need "//article[@class='product_pod']" in xpath.

Using relative xpath ".//article[@class='product_pod']/h3/a/text()" it couldn't find title so book_name was empty for all items and for all items it used None as title - and it used the same name None.jpg for all images.

It has to be

```<code>loader.add_xpath('book_name', ".//h3/a/text()")  # title with `...`
</code>```

BTW: text() doesn't have full title but with .... To get full title you has to get attribute title=

```<code>loader.add_xpath('book_name', ".//h3/a/@title")  # full title
</code>```

I created version with all code in one file to run it without creating project.

Everyone can copy it to single file and run to test it.

```<code>import scrapy
from scrapy.loader.processors import TakeFirst

class BooksToScrapeItem(scrapy.Item):
    image_urls = scrapy.Field()
    images = scrapy.Field()
    book_name = scrapy.Field(
        output_processor = TakeFirst()
    )

from scrapy import Request
from scrapy.pipelines.images import ImagesPipeline

class BooksToScrapeImagePipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        return [Request(x, meta={'bookname': item.get('book_name')}) for x in item.get(self.images_urls_field, [])] #i think that the problem is in this line

    def file_path(self, request, response=None, info=None):
        return 'full/%s.jpg' % request.meta['bookname']

from scrapy.loader import ItemLoader

class ImgscrapeSpider(scrapy.Spider):
    name = 'imgscrape'
    allowed_domains = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com']

    def parse(self, response):
        for article in response.xpath("//article[@class='product_pod']"):

            loader = ItemLoader(item=BooksToScrapeItem(),selector=article)

            relative_url = article.xpath(".//div/a/img[@class='thumbnail']/@src").extract_first()
            abs_url = response.urljoin(relative_url)

            loader.add_value('image_urls', abs_url)
            #loader.add_xpath('book_name',".//article[@class='product_pod']/h3/a/text()")  # wrong relative xpath
            #loader.add_xpath('book_name', ".//h3/a/text()")  # only partial title
            loader.add_xpath('book_name', ".//h3/a/@title")  # full title

            yield loader.load_item()

# -----------------------------------------------------------------------------

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',

    # save in file CSV, JSON or XML
    'FEED_FORMAT': 'csv',     # csv, json, xml
    'FEED_URI': 'output.csv', #

    # download images to `IMAGES_STORE/full` (standard folder) and convert to JPG (even if it is already JPG)
    # it needs `yield {'image_urls': [url]}` in `parse()` and both ITEM_PIPELINES and IMAGES_STORE to work

    'ITEM_PIPELINES': {'__main__.BooksToScrapeImagePipeline': 1},            # used Pipeline create in current file (needs __main___)
    'IMAGES_STORE': '.',                   # this folder has to exist before downloading

})
c.crawl(ImgscrapeSpider)
c.start()
</code>```

Body:
items.py file. as i was aware of the image_urls and images field. It didn't create any problem.

import scrapy
from scrapy.loader.processors import TakeFirst

class BooksToScrapeItem(scrapy.Item):
    image_urls = scrapy.Field()
    images = scrapy.Field()
    book_name = scrapy.Field(
        output_processor = TakeFirst()
    )

pipelines.py file. I think there must be a problem in the get_media_request method as it is not fetching the book_name from items file

from scrapy.pipelines.images import ImagesPipeline
from scrapy import Request

class BooksToScrapeImagePipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        return [Request(x,meta={'bookname': item.get('book_name')}) for x in item.get(self.images_urls_field, [])] #i think that the problem is in this line

    def file_path(self, request, response=None, info=None):

        return 'full/%s.jpg' % (request.meta['bookname'])

spider file which I user for scraping.It worked when i didnt customized the pipeline file.

import scrapy
from scrapy.loader import ItemLoader
from books_to_scrape.items import BooksToScrapeItem

class ImgscrapeSpider(scrapy.Spider):
    name = 'imgscrape'
    allowed_domains = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com']

    def parse(self, response):
        for article in response.xpath("//article[@class='product_pod']"):
            loader = ItemLoader(item=BooksToScrapeItem(),selector=article)
            relative_url = article.xpath(".//div/a/img[@class='thumbnail']/@src").extract_first()
            abs_url = response.urljoin(relative_url)
            loader.add_value('image_urls',abs_url)
            loader.add_xpath('book_name',".//article[@class='product_pod']/h3/a/text()")
            yield loader.load_item()

Body:
Your problem is in relative xpath

loader.add_xpath('book_name', ".//article[@class='product_pod']/h3/a/text()")

Loader uses xpath("//article[@class='product_pod']") as selector

   for article in response.xpath("//article[@class='product_pod']"):
        loader = ItemLoader(item=BooksToScrapeItem(), selector=article)

so all relative xpaths are relative to "//article[@class='product_pod']" and they don't need "//article[@class='product_pod']" in xpath.

Using relative xpath ".//article[@class='product_pod']/h3/a/text()" it couldn't find title so book_name was empty for all items and for all items it used None as title - and it used the same name None.jpg for all images.

It has to be

loader.add_xpath('book_name', ".//h3/a/text()")  # title with `...`

BTW: text() doesn't have full title but with .... To get full title you has to get attribute title=

loader.add_xpath('book_name', ".//h3/a/@title")  # full title

I created version with all code in one file to run it without creating project.

Everyone can copy it to single file and run to test it.

import scrapy
from scrapy.loader.processors import TakeFirst

class BooksToScrapeItem(scrapy.Item):
    image_urls = scrapy.Field()
    images = scrapy.Field()
    book_name = scrapy.Field(
        output_processor = TakeFirst()
    )

from scrapy import Request
from scrapy.pipelines.images import ImagesPipeline

class BooksToScrapeImagePipeline(ImagesPipeline):

    def get_media_requests(self, item, info):
        return [Request(x, meta={'bookname': item.get('book_name')}) for x in item.get(self.images_urls_field, [])] #i think that the problem is in this line

    def file_path(self, request, response=None, info=None):
        return 'full/%s.jpg' % request.meta['bookname']

from scrapy.loader import ItemLoader

class ImgscrapeSpider(scrapy.Spider):
    name = 'imgscrape'
    allowed_domains = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com']

    def parse(self, response):
        for article in response.xpath("//article[@class='product_pod']"):

            loader = ItemLoader(item=BooksToScrapeItem(),selector=article)

            relative_url = article.xpath(".//div/a/img[@class='thumbnail']/@src").extract_first()
            abs_url = response.urljoin(relative_url)

            loader.add_value('image_urls', abs_url)
            #loader.add_xpath('book_name',".//article[@class='product_pod']/h3/a/text()")  # wrong relative xpath
            #loader.add_xpath('book_name', ".//h3/a/text()")  # only partial title
            loader.add_xpath('book_name', ".//h3/a/@title")  # full title

            yield loader.load_item()

# -----------------------------------------------------------------------------

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'USER_AGENT': 'Mozilla/5.0',

    # save in file CSV, JSON or XML
    'FEED_FORMAT': 'csv',     # csv, json, xml
    'FEED_URI': 'output.csv', #

    # download images to `IMAGES_STORE/full` (standard folder) and convert to JPG (even if it is already JPG)
    # it needs `yield {'image_urls': [url]}` in `parse()` and both ITEM_PIPELINES and IMAGES_STORE to work

    'ITEM_PIPELINES': {'__main__.BooksToScrapeImagePipeline': 1},            # used Pipeline create in current file (needs __main___)
    'IMAGES_STORE': '.',                   # this folder has to exist before downloading

})
c.crawl(ImgscrapeSpider)
c.start()


问:
Apache-camel: How to process a json object (sent by curl) into headers?
I have a springboot application with apache camel. In it I have a camel-context.
I am trying to send json through curl with a key pair value and processing it through a route.

Sending the data:

```<code>curl --header "Content-Type: application/json" -X POST -d '{"msgId=EB2C7265-EF68-4F8F-A709-BEE2C52E842B", "ticket":"ERR001"}' http://lcalhost:8888/api/erroradmin
</code>```

Camel-context.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
        <camelContext xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true">
            <properties>
                <property key="CamelLogEipName" value="ThisLogger"/>
            </properties>
            <dataFormats>
                <!-- here we define a Json data format with the id jack and that it should use the TestPojo as the class type when
                     doing unmarshal. The unmarshalTypeName is optional, if not provided Camel will use a Map as the type -->
                <json id="jack" library="Jackson" unmarshalTypeName="java.util.HashMap"/>
            </dataFormats>

            <restConfiguration component="jetty" port="8888" bindingMode="json">
                <dataFormatProperty key="prettyPrint" value="true"/>
            </restConfiguration>

            <rest path="/api/erroradmin">
                <get uri="{id}">
                    <to uri="direct:processErrorAdminGet"/>
                </get>
                <post>
                    <to uri="direct:processErrorAdminPost"/>
                </post>
            </rest>

            <route id="processErrorAdminPost">
                <from uri="direct:processErrorAdminPost"/>
                <log message="Route(processErrorAdminPost): ${body}"/>
                <unmarshal>
                    <custom ref="jack"/>
                </unmarshal>
                <log message="Route(processErrorAdminPost): ${body}"/>

            </route>
        </camelContext>
    </beans>
</code>```

I am getting the following Stacktrace:

org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001} of type: java.util.LinkedHashMap on: HttpMessage@0x28c1a31a. Caused by: No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}. Exchange[09395660-c947-47f1-b00f-d0d3030a39d1]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}]

答:
After searching and reading for a while, I have found the solution.

The way to do this is by using JsonPath. Now in Java DSL there are many examples, but in XML DSL, there is not much. I finally found a working example.

My camel context looks now like this:

```<code><camelContext xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true" streamCache="true">
    <properties>
        <property key="CamelLogEipName" value="SomeLogger"/>
    </properties>

     <dataFormats>
            <json id="json" library="Jackson"/>
     </dataFormats>

    <restConfiguration component="jetty" port="9090" >
        <dataFormatProperty key="prettyPrint" value="true"/>
    </restConfiguration>

    <rest path="/api/erroradmin">
        <post>
            <to uri="direct:error" />
        </post>
    </rest>

    <route id="error">
        <from uri="direct:error"/>
        <log message="Route(error): ${body}"/>

        <setHeader headerName="errMessageId">
            <jsonpath suppressExceptions="true">$[0].msgId</jsonpath>
        </setHeader>
        <setHeader headerName="errTicket">
            <jsonpath suppressExceptions="true">$[0].ticket</jsonpath>
        </setHeader>
        <setHeader headerName="errHandled">
            <jsonpath suppressExceptions="true">$[0].handled</jsonpath>
        </setHeader>

        <log message="Route(error): Header name: errMessageId -> ${header[errMessageId]}"/>
        <log message="Route(error): Header name: errTicket -> ${header[errTicket]}"/>
        <log message="Route(error): Header name: errHandled -> ${header[errHandled]}"/>
    </route>
</camelContext>
</code>```

When accessing the key of the corresponding node I get the value in my newly set header.

The JSON is sent in like this:
So you send in:

curl -XPOST http://localhost:9090/api/erroradmin -d '[{"var1": 10,"var2": 20}]' --header "Content-Type: application/json"

The dependencies I am using:

```<code>    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-jackson</artifactId>
        <version>${camel.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-jsonpath</artifactId>
        <version>${camel.version}</version>
    </dependency>
  </dependencies>
</code>```

Hope this benefits someone in the future!

EDIT: Make sure to use camel 2.25.0 and higher. Apparently when using camel-json 2.24.1 along with same core version, the camel-json will download an outdated dependency called json-smart, which misses some classes for JsonPath to work correctly.

Body:
I have a springboot application with apache camel. In it I have a camel-context.
I am trying to send json through curl with a key pair value and processing it through a route.

Sending the data:

curl --header "Content-Type: application/json" -X POST -d '{"msgId=EB2C7265-EF68-4F8F-A709-BEE2C52E842B", "ticket":"ERR001"}' http://lcalhost:8888/api/erroradmin

Camel-context.xml:

<?xml version="1.0" encoding="utf-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
        <camelContext xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true">
            <properties>
                <property key="CamelLogEipName" value="ThisLogger"/>
            </properties>
            <dataFormats>

                <json id="jack" library="Jackson" unmarshalTypeName="java.util.HashMap"/>
            </dataFormats>

            <restConfiguration component="jetty" port="8888" bindingMode="json">
                <dataFormatProperty key="prettyPrint" value="true"/>
            </restConfiguration>

            <rest path="/api/erroradmin">
                <get uri="{id}">
                    <to uri="direct:processErrorAdminGet"/>
                </get>
                <post>
                    <to uri="direct:processErrorAdminPost"/>
                </post>
            </rest>

            <route id="processErrorAdminPost">
                <from uri="direct:processErrorAdminPost"/>
                <log message="Route(processErrorAdminPost): ${body}"/>
                <unmarshal>
                    <custom ref="jack"/>
                </unmarshal>
                <log message="Route(processErrorAdminPost): ${body}"/>

            </route>
        </camelContext>
    </beans>

I am getting the following Stacktrace:

org.apache.camel.InvalidPayloadException: No body available of type: java.io.InputStream but has value: {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001} of type: java.util.LinkedHashMap on: HttpMessage@0x28c1a31a. Caused by: No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}. Exchange[09395660-c947-47f1-b00f-d0d3030a39d1]. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: java.util.LinkedHashMap to the required type: java.io.InputStream with value {msgId=D507B9EE-176D-4F3C-88E7-9E36CC2B9731, ticket=ERR001}]

Body:
After searching and reading for a while, I have found the solution.

The way to do this is by using JsonPath. Now in Java DSL there are many examples, but in XML DSL, there is not much. I finally found a working example.

My camel context looks now like this:

<camelContext xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true" streamCache="true">
    <properties>
        <property key="CamelLogEipName" value="SomeLogger"/>
    </properties>

     <dataFormats>
            <json id="json" library="Jackson"/>
     </dataFormats>

    <restConfiguration component="jetty" port="9090" >
        <dataFormatProperty key="prettyPrint" value="true"/>
    </restConfiguration>

    <rest path="/api/erroradmin">
        <post>
            <to uri="direct:error" />
        </post>
    </rest>

    <route id="error">
        <from uri="direct:error"/>
        <log message="Route(error): ${body}"/>

        <setHeader headerName="errMessageId">
            <jsonpath suppressExceptions="true">$[0].msgId</jsonpath>
        </setHeader>
        <setHeader headerName="errTicket">
            <jsonpath suppressExceptions="true">$[0].ticket</jsonpath>
        </setHeader>
        <setHeader headerName="errHandled">
            <jsonpath suppressExceptions="true">$[0].handled</jsonpath>
        </setHeader>

        <log message="Route(error): Header name: errMessageId -> ${header[errMessageId]}"/>
        <log message="Route(error): Header name: errTicket -> ${header[errTicket]}"/>
        <log message="Route(error): Header name: errHandled -> ${header[errHandled]}"/>
    </route>
</camelContext>

When accessing the key of the corresponding node I get the value in my newly set header.

The JSON is sent in like this:
So you send in:

curl -XPOST http://localhost:9090/api/erroradmin -d '[{"var1": 10,"var2": 20}]' --header "Content-Type: application/json"

The dependencies I am using:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-jackson</artifactId>
        <version>${camel.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>
    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-jsonpath</artifactId>
        <version>${camel.version}</version>
    </dependency>
  </dependencies>

Hope this benefits someone in the future!

EDIT: Make sure to use camel 2.25.0 and higher. Apparently when using camel-json 2.24.1 along with same core version, the camel-json will download an outdated dependency called json-smart, which misses some classes for JsonPath to work correctly.


问:
This script is always returning unknown. Even if there are files and directory inside my root folder?
```<code>for item in os.listdir("/root"):
    if os.path.isfile(item):
        print(item + "is a file")
    elif os.path.isdir(item):
        print(item + "is a dir")
    else:
        print("Unknown")
</code>```

答:
According to the for loop, you are trying to check every file from the /root directory, not from the current one. But os.listdir("/root) returns only the filenames of files that are in the /root directory without their full paths (e.g. "my_file.txt" instead of "/root/my_file.txt"). And os.path.isfile(...) and os.path.isdir(...) require the full paths as their args. So, when you call os.path.isfile(item) or os.path.isdir(item) it checks whether the item exists in the current directory, not the /root directory.

Use os.path.join(path, *paths) to get the full paths for your items, store it in the full_path variable inside the loop and throw it to the os.path.isdir(...) and os.path.isfile(...) instead of the item.
Here is an example:

```<code>for item in os.listdir("/root"):
    full_path = os.path.join("/root", item)
    if os.path.isfile(full_path):
        print(item + " is a file")
    elif os.path.isdir(full_path):
        print(item + " is a dir")
    else:
        print("Unknown")
</code>```

Body:
According to the for loop, you are trying to check every file from the /root directory, not from the current one. But os.listdir("/root) returns only the filenames of files that are in the /root directory without their full paths (e.g. "my_file.txt" instead of "/root/my_file.txt"). And os.path.isfile(...) and os.path.isdir(...) require the full paths as their args. So, when you call os.path.isfile(item) or os.path.isdir(item) it checks whether the item exists in the current directory, not the /root directory.

Use os.path.join(path, *paths) to get the full paths for your items, store it in the full_path variable inside the loop and throw it to the os.path.isdir(...) and os.path.isfile(...) instead of the item.
Here is an example:

for item in os.listdir("/root"):
    full_path = os.path.join("/root", item)
    if os.path.isfile(full_path):
        print(item + " is a file")
    elif os.path.isdir(full_path):
        print(item + " is a dir")
    else:
        print("Unknown")


问:
Capture "clicking of reply/reply all" events in Outlook VSTO C#
currently I am working with creating add-in's for VSTO Outlook using C# language.

I learnt some basics from Microsoft's Walkthrough: Create your first VSTO Add-in for Outlook, where I learnt to add some text to mail body whenever user composes a new mail.

I want to do the same(adding text to mail body) for both reply and reply all events.

I searched through the Outlook Object model, but found nothing useful.
Can anybody help me with this?

答:
Use Explorer.SelectionChange event to set up event sinks on the selected items (Explorer object can come from the Application.ActiveExplorer property), then track the MailItem.Reply / ReplyAll events.

If you don't care about the old item, you can simply use Inspectors.NewInspector event.


问:
Jest error Could not locate module .... mapped as:
I try use Jest with VueJS and Quasar framework. I write simple test:

```<code>import { GetUserDictionaryDataComponent, Component } from '@/pages/configurations/components/';

describe('GetUserDictionaryDataComponent', () => {
  it('should get correct type', () => {
    const component = new GetUserDictionaryDataComponent(undefined);
    expect(component.getComponentType()).toBe(Component.LEAF);
  });
});
</code>```

But It not work correctly. When I try run my test, I get error:

```<code>Test suite failed to run

    Configuration error:

    Could not locate module @/pages/configurations/components/ mapped as:
    /home/user/git/my_project/client/src/pages/configurations/components/.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^@\/(.*)$/": "/home/user/git/my_project/client/src/$1"
      },
      "resolver": null
    }

    > 1 | import { GetUserDictionaryDataComponent, Component } from '@/pages/configurations/components/';
        | ^
      2 |
      3 | describe('GetUserDictionaryDataComponent', () => {
      4 |   it('should get correct type', () => {

      at createNoMappedModuleFoundError (node_modules/@jest/core/node_modules/jest-resolve/build/index.js:472:17)
      at Object.<anonymous> (src/tests/pages/configurations/components/GetUserDictionaryDataComponent.spec.js:1:1)
</code>```

But, I don't uderstand, why I get this error. I checked, path /home/user/git/my_project/client/src/pages/configurations/components/ is correct, my classes there.

答:
For me it was the simplest typo. I was using

"\\.(css|less)$": "<rootDir>/__mocks__/styleMocks.js"
but my file was named styleMock.js

Hope this helps anyone

Body:
I try use Jest with VueJS and Quasar framework. I write simple test:

import { GetUserDictionaryDataComponent, Component } from '@/pages/configurations/components/';

describe('GetUserDictionaryDataComponent', () => {
  it('should get correct type', () => {
    const component = new GetUserDictionaryDataComponent(undefined);
    expect(component.getComponentType()).toBe(Component.LEAF);
  });
});

But It not work correctly. When I try run my test, I get error:

Test suite failed to run

    Configuration error:

    Could not locate module @/pages/configurations/components/ mapped as:
    /home/user/git/my_project/client/src/pages/configurations/components/.

    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^@\/(.*)$/": "/home/user/git/my_project/client/src/$1"
      },
      "resolver": null
    }

    > 1 | import { GetUserDictionaryDataComponent, Component } from '@/pages/configurations/components/';
        | ^
      2 |
      3 | describe('GetUserDictionaryDataComponent', () => {
      4 |   it('should get correct type', () => {

      at createNoMappedModuleFoundError (node_modules/@jest/core/node_modules/jest-resolve/build/index.js:472:17)
      at Object.<anonymous> (src/tests/pages/configurations/components/GetUserDictionaryDataComponent.spec.js:1:1)

But, I don't uderstand, why I get this error. I checked, path /home/user/git/my_project/client/src/pages/configurations/components/ is correct, my classes there.


问:
How to create static(hard coded) nested Array data in Typescript
I want to create multilevel dropdown list in Angular. For that I need static data of type below

```<code>Item1
Item2
    SubItem1
    SubItem2
Item3
Item4
    SubItem14
    SubItem15
Item5
</code>```

I Typescript, how can I create this data(hard coded) using array?

I have tried like this

```<code>public arrayname: string[] = ["Item1", "Item2", "Item3"];
</code>```

but that is not nested.

答:
You can use a sub array in a recursive manner: </p>

```<code>type Item = {
    name: string,
    subArray?: Item[]
}

type Dropdown = Item[];

const dropdownArray: Dropdown = [
    {
        name: "Item1",
    },
    {
        name: "Item2",
        subArray: [
            {
                name: "SubItem1"
            },
            {
                name: "SubItem2"
            }
        ]
    },
    {
        name: "Item3"
    },
    {
        name: "Item4",
        subArray: [
            {
                name: "SubItem14"
            },
            {
                name: "SubItem15"
            }
        ]
    },
    {
        name: "Item5"
    }
]
</code>```

Body:
I want to create multilevel dropdown list in Angular. For that I need static data of type below

Item1
Item2
    SubItem1
    SubItem2
Item3
Item4
    SubItem14
    SubItem15
Item5

I Typescript, how can I create this data(hard coded) using array?

I have tried like this

public arrayname: string[] = ["Item1", "Item2", "Item3"];

but that is not nested.

Body:
You can use a sub array in a recursive manner:

type Item = {
    name: string,
    subArray?: Item[]
}

type Dropdown = Item[];

const dropdownArray: Dropdown = [
    {
        name: "Item1",
    },
    {
        name: "Item2",
        subArray: [
            {
                name: "SubItem1"
            },
            {
                name: "SubItem2"
            }
        ]
    },
    {
        name: "Item3"
    },
    {
        name: "Item4",
        subArray: [
            {
                name: "SubItem14"
            },
            {
                name: "SubItem15"
            }
        ]
    },
    {
        name: "Item5"
    }
]


问:
python class inheritance from different files
I am learning python and encountered a problem that I don't understand.
I have created a class called Person in a file classes_parent.py

```<code>class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

x = Person('John', 'Doe')
x.printname()
</code>```

I have created a subclass called Student in file classes_child.py:

```<code>from classes_parent import Person

class Student(Person):
    pass

s = Student('Alex', 'Doe')
s.printname()
</code>```

The problem is that the output when I run classes_child.py is this:

```<code>John Doe
Alex Doe
</code>```

Why I get both names and not just the student name, i.e. Alex Doe?

答:
This is why the "if name equals main" boilerplate exists: so you can separate a module's library and main functionality. Change your files like this:

classes_parent.py

```<code>class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

if __name__ == '__main__':
    x = Person('John', 'Doe')
    x.printname()
</code>```

classes_child.py

```<code>from classes_parent import Person

class Student(Person):
    pass

if __name__ == '__main__':
    s = Student('Alex', 'Doe')
    s.printname()
</code>```

Now when you run classes_child.py, it won't run the main code from classes_parent.py, and you'll just get Alex Doe as output.

For more details see:

What does if __name__ == "__main__": do?

How do I find the current module name? (Python FAQ)

Body:
I am learning python and encountered a problem that I don't understand.
I have created a class called Person in a file classes_parent.py

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

x = Person('John', 'Doe')
x.printname()

I have created a subclass called Student in file classes_child.py:

from classes_parent import Person

class Student(Person):
    pass

s = Student('Alex', 'Doe')
s.printname()

The problem is that the output when I run classes_child.py is this:

John Doe
Alex Doe

Why I get both names and not just the student name, i.e. Alex Doe?

Body:
This is why the "if name equals main" boilerplate exists: so you can separate a module's library and main functionality. Change your files like this:

classes_parent.py

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname

    def printname(self):
        print(self.firstname, self.lastname)

if __name__ == '__main__':
    x = Person('John', 'Doe')
    x.printname()

classes_child.py

from classes_parent import Person

class Student(Person):
    pass

if __name__ == '__main__':
    s = Student('Alex', 'Doe')
    s.printname()

Now when you run classes_child.py, it won't run the main code from classes_parent.py, and you'll just get Alex Doe as output.

For more details see:

What does if __name__ == "__main__": do?

How do I find the current module name? (Python FAQ)


问:
Foreach Loop container in SSIS suggestion
I have for-each loop container in my SSIS master package
           There is 'Execute Package Task'
              under this  'Execute SQL Server Agent Job Task' is there.(It has 35 steps)

Problem:
SSIS master package is starting next iteration without completion of all the steps in 'Execute SQL Server Agent Job Task'.

Please suggest an approach to start the next iteration after completion of all the steps only.

Thanks in advance :)

答:
I know I keep throwing C# solutions at SSIS problems but this is exactly what I do to prevent a job/process to run while a job is running.

I have a function that does this check and returns a boolean true/false. Use that result to determine whether to start the job or not.

```<code>    public static bool isDatabaseUpdating()
    {
        List<string> jobs = new List<string>();

        jobs.Add("[Insert name of Job here]");
        jobs.Add("[Insert another job and so on here]");

        string sql = "exec msdb.dbo.sp_help_job @execution_status = 1";

        using (OleDbConnection conn = new OleDbConnection(cstr))
        {
            using (OleDbCommand cmd = new OleDbCommand(sql, conn))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection.Open();
                OleDbDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    if (jobs.Contains(rdr["name"].ToString())) return true;
                }
            }
        }

        return false;
    }
</code>```

To use it set a SSIS Variable like this:

```<code>Dts.Variables["@variableName"].Value = isDatabaseUpdating();
</code>```

And then in control flow set expression on path appropriately.

The real key to understanding this function is the SQL.

```<code>exec msdb.dbo.sp_help_job @execution_status = 1
</code>```

That returns a dataset of jobs that are currently running.

Enhancement to your application

This is what your control flow will look like:

Body:
I know I keep throwing C# solutions at SSIS problems but this is exactly what I do to prevent a job/process to run while a job is running.

I have a function that does this check and returns a boolean true/false. Use that result to determine whether to start the job or not.

    public static bool isDatabaseUpdating()
    {
        List<string> jobs = new List<string>();

        jobs.Add("[Insert name of Job here]");
        jobs.Add("[Insert another job and so on here]");

        string sql = "exec msdb.dbo.sp_help_job @execution_status = 1";

        using (OleDbConnection conn = new OleDbConnection(cstr))
        {
            using (OleDbCommand cmd = new OleDbCommand(sql, conn))
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection.Open();
                OleDbDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    if (jobs.Contains(rdr["name"].ToString())) return true;
                }
            }
        }

        return false;
    }

To use it set a SSIS Variable like this:

Dts.Variables["@variableName"].Value = isDatabaseUpdating();

And then in control flow set expression on path appropriately.

The real key to understanding this function is the SQL.

exec msdb.dbo.sp_help_job @execution_status = 1

That returns a dataset of jobs that are currently running.

Enhancement to your application

This is what your control flow will look like:


问:
how to change default parameter values at pipeline level dynamically in azure data factory while moving from dev to prod
I have few parameters specified at pipeline level in ADF and i have used default values in dev environment.Now i want to move this pipeline to prod environment and want to change the parameter values according to the production.

Earlier is SSIS we used to have configurations(sql,xml...) to do such changes without changing anything in the SSIS package.

can we do the same thing in ADF i:e without changing the default values manually in the package,can we use values stored in sql table to pass as pipeline parameters.

答:
You don't need to worry about the values defined in a pipeline parameter as long as you are going to have a trigger on it. Just make sure to publish different versions of triggers in dev and prod repositories and pass different values to the pipeline parameters.

If however you want to change parameters, you can do so by invoking the pipeline from a parent pipeline through an execute pipeline activity. The values you pass as parameters to the execute pipeline activity can be coming from a lookup (over some configuration file or table).


问:
Can I have multiple packages inside a single go module? How?
I have a Go module whose name is 'tatata'. It is only developed in my machine and thus it does not contain any path to any URL in the module name.

If I have only one main package in my module it works correctly.
However, if I create two packages in the module, I am experiencing some problems.

This is the tree:

```<code>./|
  |- go.mod
  |-src
     |- main
     |   | - main.go
     |
     |- api
         | - api.go

</code>```

The content of the files:

go.mod

```<code>module tatata

go 1.13
</code>```

main.go

```<code>package main

import "fmt"
import "tatata/api"

func main() {
  fmt.Println("Hello world")
  api.Test1()
}
</code>```

api.go

```<code>package api

import "fmt"
func Test1() {
   fmt.Println("Testing API")
}
</code>```

When I try to build, I issue go build ./src/main and I get the following error:
build tatata/src/main: cannot load tatata/api: malformed module path "tatata/api": missing dot in first path element

Now, if I try to put a dummy dot, like renaming the module to tatata.com I get the error build tatata.com/src/main: cannot load tatata.com/api: cannot find module providing package tatata.com/api as obviously my package/module is not available in that URL.

GOPATH is empty, i.e. not set.

Questions:

a) What is the right way, i.e. naming of modules and imports when using multiple packages inside a single Go module?

b) Is it impossible to have a Go module without dots in its name?!

c) Can you point me to any working example that has a building set-up with a single go module and multiple packages in the module?

答:
I found the problem.
The go.mod file has to be in the folder that contains the packages. In my case it was in the parent of that folder.
Now working.

Body:
I have a Go module whose name is 'tatata'. It is only developed in my machine and thus it does not contain any path to any URL in the module name.

If I have only one main package in my module it works correctly.
However, if I create two packages in the module, I am experiencing some problems.

This is the tree:

./|
  |- go.mod
  |-src
     |- main
     |   | - main.go
     |
     |- api
         | - api.go

The content of the files:

go.mod

module tatata

go 1.13

main.go

package main

import "fmt"
import "tatata/api"

func main() {
  fmt.Println("Hello world")
  api.Test1()
}

api.go

package api

import "fmt"
func Test1() {
   fmt.Println("Testing API")
}

When I try to build, I issue go build ./src/main and I get the following error:
build tatata/src/main: cannot load tatata/api: malformed module path "tatata/api": missing dot in first path element

Now, if I try to put a dummy dot, like renaming the module to tatata.com I get the error build tatata.com/src/main: cannot load tatata.com/api: cannot find module providing package tatata.com/api as obviously my package/module is not available in that URL.

GOPATH is empty, i.e. not set.

Questions:

a) What is the right way, i.e. naming of modules and imports when using multiple packages inside a single Go module?

b) Is it impossible to have a Go module without dots in its name?!

c) Can you point me to any working example that has a building set-up with a single go module and multiple packages in the module?