问:
Create a WooCommerce product with the same name when a custom post type is published
I have a custom post type called Event which I want to sell through woocommerce. So what I want, when I create a Event post, it automatically creates a product under woocommerce with the same name. Is it possible?

I tried the following code found in Create a Woocommerce product when post is created

```<code>add_action( 'save_event', 'auto_create_product_from_post', 100, 2 );
function auto_create_product_from_post($id, $post){
$post_id = wp_insert_post( array(
    //'post_title' => 'Adams Product',
    'post_title' => $post.post_title,
    'post_content' => $post.post_title,
    'post_status' => 'publish',
    'post_type' => "product",
) );
    wp_set_object_terms( $post_id, 'simple', 'product_type' );
    update_post_meta( $post_id, '_visibility', 'visible' );
    update_post_meta( $post_id, '_stock_status', 'instock');
    update_post_meta( $post_id, 'total_sales', '0' );
    update_post_meta( $post_id, '_downloadable', 'no' );
    update_post_meta( $post_id, '_virtual', 'yes' );
    update_post_meta( $post_id, '_regular_price', '' );
    update_post_meta( $post_id, '_sale_price', '' );
    update_post_meta( $post_id, '_purchase_note', '' );
    update_post_meta( $post_id, '_featured', 'no' );
    update_post_meta( $post_id, '_weight', '' );
    update_post_meta( $post_id, '_length', '' );
    update_post_meta( $post_id, '_width', '' );
    update_post_meta( $post_id, '_height', '' );
    update_post_meta( $post_id, '_sku', '' );
    update_post_meta( $post_id, '_product_attributes', array() );
    update_post_meta( $post_id, '_sale_price_dates_from', '' );
    update_post_meta( $post_id, '_sale_price_dates_to', '' );
    update_post_meta( $post_id, '_price', '' );
    update_post_meta( $post_id, '_sold_individually', '' );
    update_post_meta( $post_id, '_manage_stock', 'no' );
    update_post_meta( $post_id, '_backorders', 'no' );
    update_post_meta( $post_id, '_stock', '' );
}
</code>```

But the above code gives me Recoverable fatal error: Object of class WP_Post could not be converted to string error. I changed the action hook to publish_event but my website has gone in to a infinite loop and still creating a lots of products even after I removed the code.

答:
The wrong part is $post.post_title… $post is a WP_Post object so use -> in $post->post_title, to get the post title as . is used for string concatenation in PHP.

So in your code:

```<code>$product = wp_insert_post( array(
    //'post_title' => 'Adams Product',
    'post_title' => $post->post_title, // <=== HERE
    'post_content' => $post->post_content, // <=== Changed
    'post_status' => 'publish',
    'post_type' => "product",
) );
</code>```

This will solve your issue.

A better way: Since WooCommerce 3, you could use CRUD Objects like:

```<code>add_action( 'save_event', 'auto_create_product_from_post', 100, 2 );
function auto_create_product_from_post($id, $post){
    // Create an empty instance of the WC_Product
    $product = new WC_Product_Simple(); // <=== Simple product

    $product->set_name( $post->post_title );
    $product->set_status( $post->post_status );
    $product->set_description( $post->post_content ); // (optional)
    $product->set_short_description( $post->post_excerpt ); // (optional)

    // You can use any available WC_Product methods to set other properties
    // see: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

    $product->save(); // Save (publish) new product
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Body:
I have a custom post type called Event which I want to sell through woocommerce. So what I want, when I create a Event post, it automatically creates a product under woocommerce with the same name. Is it possible?

I tried the following code found in Create a Woocommerce product when post is created

add_action( 'save_event', 'auto_create_product_from_post', 100, 2 );
function auto_create_product_from_post($id, $post){
$post_id = wp_insert_post( array(
    //'post_title' => 'Adams Product',
    'post_title' => $post.post_title,
    'post_content' => $post.post_title,
    'post_status' => 'publish',
    'post_type' => "product",
) );
    wp_set_object_terms( $post_id, 'simple', 'product_type' );
    update_post_meta( $post_id, '_visibility', 'visible' );
    update_post_meta( $post_id, '_stock_status', 'instock');
    update_post_meta( $post_id, 'total_sales', '0' );
    update_post_meta( $post_id, '_downloadable', 'no' );
    update_post_meta( $post_id, '_virtual', 'yes' );
    update_post_meta( $post_id, '_regular_price', '' );
    update_post_meta( $post_id, '_sale_price', '' );
    update_post_meta( $post_id, '_purchase_note', '' );
    update_post_meta( $post_id, '_featured', 'no' );
    update_post_meta( $post_id, '_weight', '' );
    update_post_meta( $post_id, '_length', '' );
    update_post_meta( $post_id, '_width', '' );
    update_post_meta( $post_id, '_height', '' );
    update_post_meta( $post_id, '_sku', '' );
    update_post_meta( $post_id, '_product_attributes', array() );
    update_post_meta( $post_id, '_sale_price_dates_from', '' );
    update_post_meta( $post_id, '_sale_price_dates_to', '' );
    update_post_meta( $post_id, '_price', '' );
    update_post_meta( $post_id, '_sold_individually', '' );
    update_post_meta( $post_id, '_manage_stock', 'no' );
    update_post_meta( $post_id, '_backorders', 'no' );
    update_post_meta( $post_id, '_stock', '' );
}

But the above code gives me Recoverable fatal error: Object of class WP_Post could not be converted to string error. I changed the action hook to publish_event but my website has gone in to a infinite loop and still creating a lots of products even after I removed the code.

Body:
The wrong part is $post.post_title… $post is a WP_Post object so use -> in $post->post_title, to get the post title as . is used for string concatenation in PHP.

So in your code:

$product = wp_insert_post( array(
    //'post_title' => 'Adams Product',
    'post_title' => $post->post_title, // <=== HERE
    'post_content' => $post->post_content, // <=== Changed
    'post_status' => 'publish',
    'post_type' => "product",
) );

This will solve your issue.

A better way: Since WooCommerce 3, you could use CRUD Objects like:

add_action( 'save_event', 'auto_create_product_from_post', 100, 2 );
function auto_create_product_from_post($id, $post){
    // Create an empty instance of the WC_Product
    $product = new WC_Product_Simple(); // <=== Simple product

    $product->set_name( $post->post_title );
    $product->set_status( $post->post_status );
    $product->set_description( $post->post_content ); // (optional)
    $product->set_short_description( $post->post_excerpt ); // (optional)

    // You can use any available WC_Product methods to set other properties
    // see: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

    $product->save(); // Save (publish) new product
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


来源: stackexchange

问:
Is there a way to Debug why my executable JAR of a JavaFX-Project runs on my Computer but not on others ? (Using jdk 1.8._051)
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

```<code>Class-Path: .
Main-Class: proj.view.Launcher

</code>```

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}

```

答:
I figured it out:
It was the User Path variable that pointed to a JDK10 bin.

We changed the Path. Now it works with "java -jar programm.jar"
but not with "java programm.jar"

but not with a Regular click on the file. But we wrote a batchFile that Starts the Application with "java -jar" and it works fine.

Has anyone a explanation for that behavior ?

ContentLicense: CC BY-SA 4.0

Body:
I exportet a Jar of a JavaFX2 Project. It works fine, but when I run it on another machine there will be a
classDefNotFoundExeption: javafx.application.Application

Any hints how to tackle this Problem ?

This is my Manifest:

Class-Path: .
Main-Class: proj.view.Launcher

I also programmed Launcher that starts a Swing GUI in case JavaFX is not found.

Here is my Launcher Class

public class Launcher {

    public static void main(String[] args) {

        try {

            Class c = javafx.application.Application.class;
            proj.main.App.main(args);

        }catch (NoClassDefFoundError e) {
            String[] t = {"Swing Backup","Application start Error"};
            MainFrame.remote(t);

        }

    }

}


问:
How to select image name which is define in CSS Puppeteer/Node.js?
How can I select an image name which is defined in CSS?

I can select that CSS image class using JavaScript, but how can I get the image name inside that class? I want to to do it in Puppeteer/Node.js.

I want to click on this class given below if the image inside the class given below matches paper.gif.

CLASS:

```<code>.height-20 span a {
   background-image: url("paper.gif");
   background-color: #cccccc;
}
</code>```

SELECTOR:

```<code>let elements = document.querySelectorAll('.height-20 span a'); // Select all Products but how to get image inside this selector?
</code>```

CLICKER:

```<code> await page.click(".height-20 span a");
</code>```

What I want to achieve is given below:

```<code>if(css image == paper.gif) {
await page.click(".height-20 span a");
}
</code>```

答:
@Grant Miller is correct, +1. I just wanted to provide a simple getStyleFromElement in TypeScript:

export async function getStyleFromElement(page: Page, elementHandle: ElementHandle, cssProperty: string): Promise<string> {
  // page.evaluate evaluates the given function from inside the browser context
  // so elementHandle and cssProperty are not available in the scope of the function.
  // That is why we pass it. Puppeteer automatically converts the elementHandle
  // into the correct DOM element, though

  return page.evaluate((element, property) =>
    window.getComputedStyle(element).getPropertyValue(property), elementHandle, cssProperty);
}
```

<p>You can now get the <code>background-image</code> by calling:</p>

<blockquote>
  <p>getStyleFromElement(page, element, "background-image");</p>
</blockquote>

<p>And bonus, if you want to extract the URL from inside the <code>url(...)</code> construct:</p>

<pre class="lang-js prettyprint-override"><code>export function getUrlFromBackgroundImage(backgroundImage: string): string | null {
  if (!backgroundImage) return null;
  const match = backgroundImage.match(/url\("(.*)"\)/);
  if (match) {
    return match[1];
  }
  return null;
}
</code>```

Body:
How can I select an image name which is defined in CSS?

I can select that CSS image class using JavaScript, but how can I get the image name inside that class? I want to to do it in Puppeteer/Node.js.

I want to click on this class given below if the image inside the class given below matches paper.gif.

CLASS:

.height-20 span a {
   background-image: url("paper.gif");
   background-color: #cccccc;
}

SELECTOR:

let elements = document.querySelectorAll('.height-20 span a'); // Select all Products but how to get image inside this selector?

CLICKER:

 await page.click(".height-20 span a");

What I want to achieve is given below:

if(css image == paper.gif) {
await page.click(".height-20 span a");
}

Body:
@Grant Miller is correct, +1. I just wanted to provide a simple getStyleFromElement in TypeScript:

export async function getStyleFromElement(page: Page, elementHandle: ElementHandle, cssProperty: string): Promise<string> {
  // page.evaluate evaluates the given function from inside the browser context
  // so elementHandle and cssProperty are not available in the scope of the function.
  // That is why we pass it. Puppeteer automatically converts the elementHandle
  // into the correct DOM element, though

  return page.evaluate((element, property) =>
    window.getComputedStyle(element).getPropertyValue(property), elementHandle, cssProperty);
}

You can now get the background-image by calling:

getStyleFromElement(page, element, "background-image");

And bonus, if you want to extract the URL from inside the url(...) construct:

export function getUrlFromBackgroundImage(backgroundImage: string): string | null {
  if (!backgroundImage) return null;
  const match = backgroundImage.match(/url\("(.*)"\)/);
  if (match) {
    return match[1];
  }
  return null;
}


问:
Wrong local date format saving to SQL Server with Laravel
Our code in Laravel receives a date in Y-M-D format and tries to save it to a SQL Server database.

The code receives these dates via APIs for many tables and we cannot change this functionality everywhere.

SQL Server language is italian and our code is OK with a Y-D-M date.

Is there a way to specify the date format once for all or the locale used in the database connection configuration?
Setting the language via statement doesn't work.

Our code is something like this:

```<code>DB::statement('SET LANGUAGE us_english');
DB::table('tablename')->insert($saveData);
</code>```

答:
I had the same problem writing on SQL Server.
It depends strictly on the language set in the database: https://database.guide/how-to-set-the-current-language-in-sql-server-tsql/

If the problem persists, you must check the user with which the database interacts and check the configuration, if it is different from the Administrator user, execute this command:

```<code>ALTER LOGIN your_login WITH DEFAULT_LANGUAGE = us_english
</code>```

And then:

```<code>Carbon::now()->toDateTimeString();
</code>```

Body:
Our code in Laravel receives a date in Y-M-D format and tries to save it to a SQL Server database.

The code receives these dates via APIs for many tables and we cannot change this functionality everywhere.

SQL Server language is italian and our code is OK with a Y-D-M date.

Is there a way to specify the date format once for all or the locale used in the database connection configuration?
Setting the language via statement doesn't work.

Our code is something like this:

DB::statement('SET LANGUAGE us_english');
DB::table('tablename')->insert($saveData);

Body:
I had the same problem writing on SQL Server.
It depends strictly on the language set in the database: https://database.guide/how-to-set-the-current-language-in-sql-server-tsql/

If the problem persists, you must check the user with which the database interacts and check the configuration, if it is different from the Administrator user, execute this command:

ALTER LOGIN your_login WITH DEFAULT_LANGUAGE = us_english

And then:

Carbon::now()->toDateTimeString();


问:
How to silence 'The last statement should return a value' warning?
Sun Studio 12.1 prints the warning

```<code>Warning: The last statement should return a value.
</code>```

frequently for functions like that:

```<code>int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}
</code>```

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

```<code>// Silence a compiler warning
return 42;
</code>```

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

答:
I don't know of a "recommended" way to deal with it, but to answer your question about coping with more complex types, what about:

```<code>ComplexType foo()
{
    ...
    throw std::runtime( "Error..." );
    return *(ComplexType*)(0);
}
</code>```

This would then work with any return type. I realise it looks evil, but its there just to silence the warning. As you say, this code will never be executed, and it may even be optimised out.

ContentLicense: CC BY-SA 3.0

Body:
Sun Studio 12.1 prints the warning

Warning: The last statement should return a value.

frequently for functions like that:

int f()
{
  /* some code that may return */

  // if we end up here, something is broken
  throw std::runtime_error("Error ...");
}

It is perfectly clear that we do not need a return value at the end of the function. I hesitate to insert something like

// Silence a compiler warning
return 42;

at the end of such a function, since it is dead code anyway. For more complicated return types, it might actually be difficult to construct a 'sensible' bogus value.

What is the recommended way to silence such a warning?

Body:
I don't know of a "recommended" way to deal with it, but to answer your question about coping with more complex types, what about:

ComplexType foo()
{
    ...
    throw std::runtime( "Error..." );
    return *(ComplexType*)(0);
}

This would then work with any return type. I realise it looks evil, but its there just to silence the warning. As you say, this code will never be executed, and it may even be optimised out.


问:
Fisher–Yates shuffle in C#
I have this method Shuffle that supposes to return a set of random numbers which was displayed in the above method but the numbers need to be displayed in a mixed format.
The first method works well since the number are being displayed correctly in the set of range but this method Shuffle is not returning them in a mixed format.

Example:

The first method returned: 1, 2, 3, 4, 5

This method needs to return 2, 1, 4, 5, 3

```<code>    public int[] Shuffle(int[] Sequence)
    {
        int[] Array = new int[Sequence.Length];

        for(int s=0; s < Array.Length-1; s++){
           int GenObj = GenerateAnotherNum (0, Array.Length + 1);

            Array[s] = Sequence[GenObj];
            Sequence[GenObj] = Array[s];
        }
        return Sequence;
    }
</code>```

答:
You have several problems here: all zeroes array, range and swap procedure

Algorithm:

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Code:

```<code>// probably "static" should be added (depends on GenerateAnotherNum routine)
public int[] Shuffle(int[] Sequence)
{
    // public method's arguments validation
    if (null == Sequence)
        throw new ArgumentNullException(nameof(Sequence));

    // No need in Array if you want to modify Sequence

    for(int s = 0; s < Sequence.Length - 1; s++)
    {
        int GenObj = GenerateAnotherNum(s, Sequence.Length); // pleace, note the range

        // swap procedure: note, var h to store initial Sequence[s] value
        var h = Sequence[s];
        Sequence[s] = Sequence[GenObj];
        Sequence[GenObj] = h;
    }

    return Sequence;
}
</code>```

Demo:

```<code>// Random(0) - we want to reproduce the results in the demo
private static Random random = new Random(0);

// Let unknown GenerateAnotherNum be a random
private static int GenerateAnotherNum(int from, int to) => random.Next(from, to);

...

int[] array = new int[] { 1, 2, 3, 4, 5 };

string result = string.Join(", ", Shuffle(array));

Console.Write(result);
</code>```

Outcome:

```<code>4, 5, 2, 3, 1
</code>```

Title: Fisher–Yates shuffle in C#

Body:
I have this method Shuffle that supposes to return a set of random numbers which was displayed in the above method but the numbers need to be displayed in a mixed format.
The first method works well since the number are being displayed correctly in the set of range but this method Shuffle is not returning them in a mixed format.

Example:

The first method returned: 1, 2, 3, 4, 5

This method needs to return 2, 1, 4, 5, 3

    public int[] Shuffle(int[] Sequence)
    {
        int[] Array = new int[Sequence.Length];

        for(int s=0; s < Array.Length-1; s++){
           int GenObj = GenerateAnotherNum (0, Array.Length + 1);

            Array[s] = Sequence[GenObj];
            Sequence[GenObj] = Array[s];
        }
        return Sequence;
    }

Body:
You have several problems here: all zeroes array, range and swap procedure

Algorithm:

https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Code:

// probably "static" should be added (depends on GenerateAnotherNum routine)
public int[] Shuffle(int[] Sequence)
{
    // public method's arguments validation
    if (null == Sequence)
        throw new ArgumentNullException(nameof(Sequence));

    // No need in Array if you want to modify Sequence

    for(int s = 0; s < Sequence.Length - 1; s++)
    {
        int GenObj = GenerateAnotherNum(s, Sequence.Length); // pleace, note the range

        // swap procedure: note, var h to store initial Sequence[s] value
        var h = Sequence[s];
        Sequence[s] = Sequence[GenObj];
        Sequence[GenObj] = h;
    }

    return Sequence;
}

Demo:

// Random(0) - we want to reproduce the results in the demo
private static Random random = new Random(0);

// Let unknown GenerateAnotherNum be a random
private static int GenerateAnotherNum(int from, int to) => random.Next(from, to);

...

int[] array = new int[] { 1, 2, 3, 4, 5 };

string result = string.Join(", ", Shuffle(array));

Console.Write(result);

Outcome:

4, 5, 2, 3, 1


问:
Angular5: Hide ag-gird rows based on condition
I have the below response from the service, when ever the flag is true I have to hide the whole row (total 20 columns I have) else show it. How can I achieve this in ag-grid?

```<code>data = {
    name: "A",
    flag: true
   },
   {
    name: "B",
    flag: false
   },
   {
    name: "C",
    flag: false
   }
</code>```

I did try the useExternalFilter like below and then I got stuck as to how to use this useExternalFilter further. Can any one please guide me through.

```<code>this.filterOptions = {
  useExternalFilter: true
};

this.gridOptions = {
  filterOptions:  this.filterOptions
 };
</code>```

答:
Simplest way to do this is, filter your data first based on the flag value

```<code>const filteredData = this.data.filter(item => !item.flag);
</code>```

Then set this filteredData as grid data

```<code>this.gridOptions.setRowData(this.filteredData);
</code>```

Hope this will do the needful

Body:
I have the below response from the service, when ever the flag is true I have to hide the whole row (total 20 columns I have) else show it. How can I achieve this in ag-grid?

data = {
    name: "A",
    flag: true
   },
   {
    name: "B",
    flag: false
   },
   {
    name: "C",
    flag: false
   }

I did try the useExternalFilter like below and then I got stuck as to how to use this useExternalFilter further. Can any one please guide me through.

this.filterOptions = {
  useExternalFilter: true
};

this.gridOptions = {
  filterOptions:  this.filterOptions
 };

Body:
Simplest way to do this is, filter your data first based on the flag value

const filteredData = this.data.filter(item => !item.flag);

Then set this filteredData as grid data

this.gridOptions.setRowData(this.filteredData);

Hope this will do the needful


问:
Mechanize and Facebook App
I found one script for accessing app info from this forum.Basically, i am accessing facebook apps and may install it automatically.

I tried to see if i get a permission dialog page by following code but it does not return the permission page rather the first page.

what facebook do is multiple redirects or meta or sends few other request and then lands the user to permission page where i need to click allow button. But i am not able to get that final permission page for many apps. Here is the code,

```<code>use strict;
use WWW::Mechanize;
use HTTP::Cookies;

my $url = "http://www.facebook.com";

my $appurl = "http://apps.facebook.com/funmoods/";

my $username = 'mail';
my $password = 'pass';

my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech->get($url);
$mech->form_name('menubar_login');
$mech->field(email => $username);
$mech->field(pass => $password);
$mech->click();
my $facebook_content = $mech->content();
# go to an app url
$mech->get($appurl);
my $app_content = $mech->content();
print "$app_content\n";
</code>```

I don't know why mechanize does not access final loaded page. it took some time to load the permission page but mechanize always returns first source page. How i can tell mechanize to wait till it loads all the pages?

Need help thanks

答:
I think you should use the progress sub inherited from LWP::UserAgent

```<code>$ua->progress( $status, $request_or_response )
</code>```

from the docs:

This is called frequently as the
  response is received regardless of how
  the content is processed. The method
  is called with $status "begin" at the
  start of processing the request and
  with $state "end" before the request
  method returns. In between these
  $status will be the fraction of the
  response currently received or the
  string "tick" if the fraction can't be
  calculated.

When $status is "begin" the second
  argument is the request object,
  otherwise it is the response object.

Title: Mechanize and Facebook App

Body:
I found one script for accessing app info from this forum.Basically, i am accessing facebook apps and may install it automatically.

I tried to see if i get a permission dialog page by following code but it does not return the permission page rather the first page.

what facebook do is multiple redirects or meta or sends few other request and then lands the user to permission page where i need to click allow button. But i am not able to get that final permission page for many apps. Here is the code,

use strict;
use WWW::Mechanize;
use HTTP::Cookies;

my $url = "http://www.facebook.com";

my $appurl = "http://apps.facebook.com/funmoods/";

my $username = 'mail';
my $password = 'pass';

my $mech = WWW::Mechanize->new();
$mech->cookie_jar(HTTP::Cookies->new());
$mech->get($url);
$mech->form_name('menubar_login');
$mech->field(email => $username);
$mech->field(pass => $password);
$mech->click();
my $facebook_content = $mech->content();
# go to an app url
$mech->get($appurl);
my $app_content = $mech->content();
print "$app_content\n";

I don't know why mechanize does not access final loaded page. it took some time to load the permission page but mechanize always returns first source page. How i can tell mechanize to wait till it loads all the pages?

Need help thanks

Body:
I think you should use the progress sub inherited from LWP::UserAgent

$ua->progress( $status, $request_or_response )

from the docs:

This is called frequently as the
  response is received regardless of how
  the content is processed. The method
  is called with $status "begin" at the
  start of processing the request and
  with $state "end" before the request
  method returns. In between these
  $status will be the fraction of the
  response currently received or the
  string "tick" if the fraction can't be
  calculated.

When $status is "begin" the second
  argument is the request object,
  otherwise it is the response object.


问:
Many2one fields and options
Here is the declaration of my field:

```<code>partner_id = fields.Many2one(string="Child", comodel_name="res.partner")
</code>```

I would like to know if it is possible to target another field of the table res.partner besides the "name"?

And why not a field that depends on another field?

It is possible to declared options?

Thanks for your help !

EDIT :

I'm trying to understand one thing.

When I export my partner_id field via the Odoo interface, I do not have a value of type res_partner_5096 but the value of another field which is an external identifier. "N0000542145"
This is what I need to be able to prepare an import file

On the other hand I have a second field "foyer_id" which exports me something of the style "relation_foyer_6055". I understand that it is the identifier that corresponds to registration of this person.
Yet my fields are declared the same way.

```<code>partner_id = fields.Many2one(string="Child", comodel_name="res.partner")
foyer_id = fields.Many2one(string="Foyer", comodel_name="horanet.relation.foyer")
</code>```

I can not understand why this difference when exporting these two fields for the same partner.

An idea ?

答:
I think you exactly looking for the "_rec_name" attribute. Odoo models uses a field as record name to display records in context where a representative “naming” is necessary. If you don't set _rec_name, model uses name field as record name by default.</p>

```<code>Class HoranetRelationFoyer(models.Model):
    # ...
    _rec_name = 'my_field'

    my_field = fields.Char()
</code>```

Title: Many2one fields and options

Body:
Here is the declaration of my field:

partner_id = fields.Many2one(string="Child", comodel_name="res.partner")

I would like to know if it is possible to target another field of the table res.partner besides the "name"?

And why not a field that depends on another field?

It is possible to declared options?

Thanks for your help !

EDIT :

I'm trying to understand one thing.

When I export my partner_id field via the Odoo interface, I do not have a value of type res_partner_5096 but the value of another field which is an external identifier. "N0000542145"
This is what I need to be able to prepare an import file

On the other hand I have a second field "foyer_id" which exports me something of the style "relation_foyer_6055". I understand that it is the identifier that corresponds to registration of this person.
Yet my fields are declared the same way.

partner_id = fields.Many2one(string="Child", comodel_name="res.partner")
foyer_id = fields.Many2one(string="Foyer", comodel_name="horanet.relation.foyer")

I can not understand why this difference when exporting these two fields for the same partner.

An idea ?

Body:
I think you exactly looking for the "_rec_name" attribute. Odoo models uses a field as record name to display records in context where a representative “naming” is necessary. If you don't set _rec_name, model uses name field as record name by default.

Class HoranetRelationFoyer(models.Model):
    # ...
    _rec_name = 'my_field'

    my_field = fields.Char()


问:
javascript SyntaxError: Identifier 'img' has already been declared
I am trying to take a picture from local notebook camera with this code:

```<code>function takePhoto(img)
{
  const img = img || document.querySelector('img');

  imageCapture.takePhoto()
  .then(blob => {
    let url = window.URL.createObjectURL(blob);
    img.src = url;
    window.URL.revokeObjectURL(url);
  })
  .catch(error);
};

takePhoto();
</code>```

but getting the following error:

```<code>SyntaxError: Identifier 'img' has already been declared
</code>```

I checked, there is no any declaration of img in the code above (also tried to rename it to something like image_local, no use). Any ideas how to fix it would be welcome. Thank you.

答:
In the question you mentioned

"there is no any declaration of img in the code above"

...in fact there are two declarations (as per the error message):

1)

```<code>function takePhoto(img)
</code>```

This effectively declares the variable, because it brings it into the scope of the function with that name.

2)

```<code>const img
</code>```

Here you attempt to declare the same variable again.

You can have one declaration of the same variable, at most. Changing

```<code>const img = img || document.querySelector('img');
</code>```

to

```<code>img = img || document.querySelector('img');`
</code>```

will fix it, as it no longer attempts to re-declare the variable, it now merely (potentially) changes its value.

Body:
I am trying to take a picture from local notebook camera with this code:

function takePhoto(img)
{
  const img = img || document.querySelector('img');

  imageCapture.takePhoto()
  .then(blob => {
    let url = window.URL.createObjectURL(blob);
    img.src = url;
    window.URL.revokeObjectURL(url);
  })
  .catch(error);
};

takePhoto();

but getting the following error:

SyntaxError: Identifier 'img' has already been declared

I checked, there is no any declaration of img in the code above (also tried to rename it to something like image_local, no use). Any ideas how to fix it would be welcome. Thank you.

Body:
In the question you mentioned

"there is no any declaration of img in the code above"

...in fact there are two declarations (as per the error message):

1)

function takePhoto(img)

This effectively declares the variable, because it brings it into the scope of the function with that name.

2)

const img

Here you attempt to declare the same variable again.

You can have one declaration of the same variable, at most. Changing

const img = img || document.querySelector('img');

to

img = img || document.querySelector('img');`

will fix it, as it no longer attempts to re-declare the variable, it now merely (potentially) changes its value.


问:
Create custom arrow view
In my android project , I'm trying to create view like this

its not so hard to create something close using bezier path

but what I need is the ability to resize the width of this view without affecting the left side of the arrow ( it will only become smaller arrow like this)

What is the best practice ?

答:
You can use 9 patch image. NinePatch images are PNG images in which we can mark the parts of an image that can be stretched. You can use the WYSIWIG draw9patch.jar tool inside your Android SDK /tools folder to create 9 patch image.

see Android developer user guide

This is also a good tool: click here

Title: Create custom arrow view


问:
Sum big decimals in pyspark and see rhe entire number
I have the following dataframe:

```<code>from pyspark.sql import functions as f
from pyspark.sql import Window

df = spark.createDataFrame(sc.parallelize([["gr1", "1663708559.71"], ["gr1", "123958300.14"],["gr2", "2006101145.31"]]), ["group_col", "numb"])
</code>```

And i want to have a new column with the sum of values grouped by group col. But i don't have a readeble output.

```<code>df.withColumn("sum_gr", f.sum(df["numb"].cast("double"))).over(Window.partitionBy(df["group_col"]))).show(10, False)
</code>```

After i calculate the sum i have to compare that big value with another big value and even if they are equals, i dont get a match.

I have the followig result:
 For gr1: the sum is 1.7876668500001E9
and i have to compare this value with lets say 1787666850000.143.

What is the best approach when working with big float numbers in pyspark? How should i do to have the entire number with all decimals converted into a string?

答:
Try to cast the sum to decimal(38,3). Please adjust precision and scale accordingly.

Here is an example:

```<code>df.groupBy('group_Col').agg(F.sum('numb').cast('decimal(38,3)')).show()

#+---------+--------------------------------+
#|group_Col|CAST(sum(numb) AS DECIMAL(38,3))|
#+---------+--------------------------------+
#|      gr2|                  2006101145.310|
#|      gr1|                  1787666859.850|
#+---------+--------------------------------+
</code>```

Please check syntax of withColumn statement for sum_gr column. It has 2 extra closing brackets ')' in after 'cast'.

Body:
I have the following dataframe:

from pyspark.sql import functions as f
from pyspark.sql import Window

df = spark.createDataFrame(sc.parallelize([["gr1", "1663708559.71"], ["gr1", "123958300.14"],["gr2", "2006101145.31"]]), ["group_col", "numb"])

And i want to have a new column with the sum of values grouped by group col. But i don't have a readeble output.

df.withColumn("sum_gr", f.sum(df["numb"].cast("double"))).over(Window.partitionBy(df["group_col"]))).show(10, False)

After i calculate the sum i have to compare that big value with another big value and even if they are equals, i dont get a match.

I have the followig result:
 For gr1: the sum is 1.7876668500001E9
and i have to compare this value with lets say 1787666850000.143.

What is the best approach when working with big float numbers in pyspark? How should i do to have the entire number with all decimals converted into a string?

Body:
Try to cast the sum to decimal(38,3). Please adjust precision and scale accordingly.

Here is an example:

df.groupBy('group_Col').agg(F.sum('numb').cast('decimal(38,3)')).show()

#+---------+--------------------------------+
#|group_Col|CAST(sum(numb) AS DECIMAL(38,3))|
#+---------+--------------------------------+
#|      gr2|                  2006101145.310|
#|      gr1|                  1787666859.850|
#+---------+--------------------------------+

Please check syntax of withColumn statement for sum_gr column. It has 2 extra closing brackets ')' in after 'cast'.


问:
Java FX: Detected [iscc.exe] version 0 but version 5 is required. Bundler EXE Installer skipped because of a configuration problem
I build a Java FX application, and now trying to convert into execution file.exe
But tried to build it shows the following error in bold. But I have installed Inno Setup 6 software and also set the environment path. But still, error persists.

No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
Detected [iscc.exe] version 0 but version 5 is required.
Bundler EXE Installer skipped because of a configuration problem: Can not find Inno Setup Compiler (iscc.exe).
Advice to fix:   Download Inno Setup 5 or later from http://www.jrsoftware.org and add it to the PATH.
No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
Detected [iscc.exe] version 0 but version 5 is required.
Bundler EXE Installer skipped because of a configuration problem: Can not find Inno Setup Compiler (iscc.exe).
Advice to fix:   Download Inno Setup 5 or later from http://www.jrsoftware.org and add it to the PATH.
```

<p>BUILD.XML</p>

<pre class="lang-xml prettyprint-override"><code><target name="-post-jfx-deploy">
    <fx:deploy width="${javafx.run.width}" height="${javafx.run.height}"
               nativeBundles="exe"
               outdir="${basedir}/${dist.dir}" outfile="${application.title}">
        <fx:application name="${application.title}" mainClass="${javafx.main.class}"/>
        <fx:resources>
            <fx:fileset dir="${basedir}/${dist.dir}" includes="*.jar"/>
            <fx:fileset dir="dist" includes="lib/*.jar"/>
        </fx:resources>
        <fx:info title="${application.title}" vendor="${application.vendor}"/>
    </fx:deploy>
</target>
</code>```

答:
Java FX looks for pattern Inno Setup (\\d+.?\\d*) in iscc /? output.

While Inno Setup 5 prints this:

Inno Setup 5 Command-Line Compiler

Inno Setup 6 before 6.0.3 omitted the version number:

Inno Setup Command-Line Compiler

That's why you get

Detected [iscc.exe] version 0 but version 5 is required.

Make sure you have the latest version of Inno Setup 6, as this got "fixed" in 6.0.3.

Body:
I build a Java FX application, and now trying to convert into execution file.exe
But tried to build it shows the following error in bold. But I have installed Inno Setup 6 software and also set the environment path. But still, error persists.

No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
Detected [iscc.exe] version 0 but version 5 is required.
Bundler EXE Installer skipped because of a configuration problem: Can not find Inno Setup Compiler (iscc.exe).
Advice to fix:   Download Inno Setup 5 or later from http://www.jrsoftware.org and add it to the PATH.
No base JDK. Package will use system JRE.
No base JDK. Package will use system JRE.
Detected [iscc.exe] version 0 but version 5 is required.
Bundler EXE Installer skipped because of a configuration problem: Can not find Inno Setup Compiler (iscc.exe).
Advice to fix:   Download Inno Setup 5 or later from http://www.jrsoftware.org and add it to the PATH.

BUILD.XML

<target name="-post-jfx-deploy">
    <fx:deploy width="${javafx.run.width}" height="${javafx.run.height}"
               nativeBundles="exe"
               outdir="${basedir}/${dist.dir}" outfile="${application.title}">
        <fx:application name="${application.title}" mainClass="${javafx.main.class}"/>
        <fx:resources>
            <fx:fileset dir="${basedir}/${dist.dir}" includes="*.jar"/>
            <fx:fileset dir="dist" includes="lib/*.jar"/>
        </fx:resources>
        <fx:info title="${application.title}" vendor="${application.vendor}"/>
    </fx:deploy>
</target>


问:
Extract images from PDF using python PyPDF2
Is there any way to extract images as stream from pdf document (using PyPDF2 library)?
Also is it possible to replace some images to another (generated with PIL for example or loaded from file)?

I'm able to get EncodedStreamObject from pdf objects tree and get encoded stream (by calling getData() method), but looks like it just raw content w/o any image headers and other meta information.

>>> import PyPDF2
>>> # sample.pdf contains png images
>>> reader = PyPDF2.PdfFileReader(open('sample.pdf', 'rb'))
>>> reader.resolvedObjects[0][9]
{'/BitsPerComponent': 8,
'/ColorSpace': ['/ICCBased', IndirectObject(20, 0)],
'/Filter': '/FlateDecode',
'/Height': 30,
'/Subtype': '/Image',
'/Type': '/XObject',
'/Width': 100}
>>>
>>> reader.resolvedObjects[0][9].__class__
PyPDF2.generic.EncodedStreamObject
>>>
>>> s = reader.resolvedObjects[0][9].getData()
>>> len(s), s[:10]
(9000, '\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc')
```

I've looked across PyPDF2, ReportLab and PDFMiner solutions quite a bit, but haven't found anything like what I'm looking for.

Any code samples and links will be very helpful.

答:
```<code>import fitz
doc = fitz.open(filePath)
for i in range(len(doc)):
    for img in doc.getPageImageList(i):
        xref = img[0]
        pix = fitz.Pixmap(doc, xref)
        if pix.n < 5:       # this is GRAY or RGB
            pix.writePNG("p%s-%s.png" % (i, xref))
        else:               # CMYK: convert to RGB first
            pix1 = fitz.Pixmap(fitz.csRGB, pix)
            pix1.writePNG("p%s-%s.png" % (i, xref))
            pix1 = None
        pix = None
</code>```

Body:
Is there any way to extract images as stream from pdf document (using PyPDF2 library)?
Also is it possible to replace some images to another (generated with PIL for example or loaded from file)?

I'm able to get EncodedStreamObject from pdf objects tree and get encoded stream (by calling getData() method), but looks like it just raw content w/o any image headers and other meta information.

>>> import PyPDF2
>>> # sample.pdf contains png images
>>> reader = PyPDF2.PdfFileReader(open('sample.pdf', 'rb'))
>>> reader.resolvedObjects[0][9]
{'/BitsPerComponent': 8,
'/ColorSpace': ['/ICCBased', IndirectObject(20, 0)],
'/Filter': '/FlateDecode',
'/Height': 30,
'/Subtype': '/Image',
'/Type': '/XObject',
'/Width': 100}
>>>
>>> reader.resolvedObjects[0][9].__class__
PyPDF2.generic.EncodedStreamObject
>>>
>>> s = reader.resolvedObjects[0][9].getData()
>>> len(s), s[:10]
(9000, '\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc\xcc')

I've looked across PyPDF2, ReportLab and PDFMiner solutions quite a bit, but haven't found anything like what I'm looking for.

Any code samples and links will be very helpful.


问:
Test simple Rxjava and gradle code get error?
I wrote a simple Rxjava code with java and gradle, but I got some error, the details as follows:

This is my Simple java source code:

```<code>import rx.functions.Action1;
import rx.Observable;
public class HelloWorld{
    public static void main(String[] args) {
        hello("Wjm");
    }

    public static void hello(String... names){
        Observable.from(names).subscribe(new Action1<String>(){

            @Override
            public void call(String s){
                System.out.println("Hello " +s +"!");
            }
        });
    }
}
</code>```

This is my gradle.build source code:

```<code>apply plugin: 'java'

jar{
    manifest{
        attributes 'Main-Class':'HelloWorld'

    }

}

repositories {
    maven { url 'https://oss.jfrog.org/libs-snapshot' }
}

dependencies {
    compile 'io.reactivex:rxjava:1.1.0'
    runtime 'io.reactivex:rxjava:1.1.0'
}
</code>```

This is my project structure:

```<code>.
├── build
│   ├── classes
│   │   └── main
│   │       ├── HelloWorld$1.class
│   │       └── HelloWorld.class
│   ├── dependency-cache
│   ├── libs
│   │   └── proj1.jar
│   └── tmp
│       ├── compileJava
│       │   └── emptySourcePathRef
│       └── jar
│           └── MANIFEST.MF
├── build.gradle
└── src
    └── main
        └── java
            └── HelloWorld.java
</code>```

I run the command "gradle build" is successful, However,
when i run "java -jar proj1.jar" in the build/libs/ path, and I got the error message as follows:

```<code>Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: rx/functions/Action1
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: rx.functions.Action1
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more
</code>```

I am a fresh in gradle, so i asked, but i do a test in android studio, same java code, and run successful.

答:
My answer is not the best answer but it works for me.

I just downloaded all jar libraries that my project needed and put them in root of my project (or you can create a LIB directory and put them there) and just run the command below in the root of my project :

java -cp *:directory_of_my_jar/my_output_jar.jar Main

where "Main" is the main class of your project. if you put main class in package , write the package and class name , for example : com.example.Main

java -cp *:directory_of_my_jar/my_output_jar.jar com.example.Main

Body:
I wrote a simple Rxjava code with java and gradle, but I got some error, the details as follows:

This is my Simple java source code:

import rx.functions.Action1;
import rx.Observable;
public class HelloWorld{
    public static void main(String[] args) {
        hello("Wjm");
    }

    public static void hello(String... names){
        Observable.from(names).subscribe(new Action1<String>(){

            @Override
            public void call(String s){
                System.out.println("Hello " +s +"!");
            }
        });
    }
}

This is my gradle.build source code:

apply plugin: 'java'

jar{
    manifest{
        attributes 'Main-Class':'HelloWorld'

    }

}

repositories {
    maven { url 'https://oss.jfrog.org/libs-snapshot' }
}

dependencies {
    compile 'io.reactivex:rxjava:1.1.0'
    runtime 'io.reactivex:rxjava:1.1.0'
}

This is my project structure:

.
├── build
│   ├── classes
│   │   └── main
│   │       ├── HelloWorld$1.class
│   │       └── HelloWorld.class
│   ├── dependency-cache
│   ├── libs
│   │   └── proj1.jar
│   └── tmp
│       ├── compileJava
│       │   └── emptySourcePathRef
│       └── jar
│           └── MANIFEST.MF
├── build.gradle
└── src
    └── main
        └── java
            └── HelloWorld.java

I run the command "gradle build" is successful, However,
when i run "java -jar proj1.jar" in the build/libs/ path, and I got the error message as follows:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: rx/functions/Action1
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
    at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
    at java.lang.Class.getMethod0(Class.java:3018)
    at java.lang.Class.getMethod(Class.java:1784)
    at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: rx.functions.Action1
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 7 more

I am a fresh in gradle, so i asked, but i do a test in android studio, same java code, and run successful.


问:
Adding custom primaryMeasureAxis with Flutter charts
I am trying to do TimeSeriesChart with the Y-axis (vertical axis) has custom labels.

I can verify that the strings ('final List<dynamic> string = data.data['options'];') holds the values I expect. And I can even reference them like strings[0], but when I do strings[value.toInt()] it throws a RangeError.

See this piece of code.
Where I initialize 'final label' I have two lines of codes defining a BasicNumericTickFormatterSpec.

The first line is what I am trying to do. I want to use the value to lookup a string in the strings[].

I can do ((num value) =>  'MyValue: ${string[0]}') which works just fine.
I can do ((num value) =>  'MyValue: ${string}') just to output all the values on each "step".

So, basically I can verify that string actually hold the values I expect, and I can access the values, but if I try to lookup a value, ((num value) =>  'MyValue: ${string[value.toInt()]}') then it breaks with this RangeError.

```<code>Widget _buildChart(BuildContext context, DocumentSnapshot data) {
    final List<dynamic> string = data.data['options'];

    final labels =
    charts.BasicNumericTickFormatterSpec((num value) =>  'MyValue: ${string[value.toInt()]}');
    // charts.BasicNumericTickFormatterSpec((num value) =>  'MyValue: ${string[0]}')

    var chart = charts.TimeSeriesChart(seriesList,
        // Sets up a currency formatter for the measure axis.
        primaryMeasureAxis: new charts.NumericAxisSpec(tickFormatterSpec: labels),
        animate: animate,
        // Optionally pass in a [DateTimeFactory] used by the chart. The factory
        // should create the same type of [DateTime] as the data provided. If none
        // specified, the default creates local date time.
        dateTimeFactory: const charts.LocalDateTimeFactory());

    return new Padding(
        padding: new EdgeInsets.all(10.0),
        child: new SizedBox(
          height: 200.0,
          child: chart,
        ));
  }
</code>```

I expected each 'value' that I put into ((num value) => '$strings[value.toInt()]) would return a string from strings[].

Instead I get:

flutter: The following RangeError was thrown during performLayout():
  flutter: RangeError (index): Invalid value: Not in range 0..1,
  inclusive: 2

答:
Try expanding your tick formatter closure so that you get more diagnostics:</p>

```<code>final labels = charts.BasicNumericTickFormatterSpec((num value) {
  var index = value.floor();
  print('--- tick for $value in $string with $index ---');
  return (index < string.length)
      ? 'MyValue: ${string[index]}'
      : 'overflow ${string.length} $index';
});
</code>```

Body:
I am trying to do TimeSeriesChart with the Y-axis (vertical axis) has custom labels.

I can verify that the strings ('final List<dynamic> string = data.data['options'];') holds the values I expect. And I can even reference them like strings[0], but when I do strings[value.toInt()] it throws a RangeError.

See this piece of code.
Where I initialize 'final label' I have two lines of codes defining a BasicNumericTickFormatterSpec.

The first line is what I am trying to do. I want to use the value to lookup a string in the strings[].

I can do ((num value) =>  'MyValue: ${string[0]}') which works just fine.
I can do ((num value) =>  'MyValue: ${string}') just to output all the values on each "step".

So, basically I can verify that string actually hold the values I expect, and I can access the values, but if I try to lookup a value, ((num value) =>  'MyValue: ${string[value.toInt()]}') then it breaks with this RangeError.

Widget _buildChart(BuildContext context, DocumentSnapshot data) {
    final List<dynamic> string = data.data['options'];

    final labels =
    charts.BasicNumericTickFormatterSpec((num value) =>  'MyValue: ${string[value.toInt()]}');
    // charts.BasicNumericTickFormatterSpec((num value) =>  'MyValue: ${string[0]}')

    var chart = charts.TimeSeriesChart(seriesList,
        // Sets up a currency formatter for the measure axis.
        primaryMeasureAxis: new charts.NumericAxisSpec(tickFormatterSpec: labels),
        animate: animate,
        // Optionally pass in a [DateTimeFactory] used by the chart. The factory
        // should create the same type of [DateTime] as the data provided. If none
        // specified, the default creates local date time.
        dateTimeFactory: const charts.LocalDateTimeFactory());

    return new Padding(
        padding: new EdgeInsets.all(10.0),
        child: new SizedBox(
          height: 200.0,
          child: chart,
        ));
  }

I expected each 'value' that I put into ((num value) => '$strings[value.toInt()]) would return a string from strings[].

Instead I get:

flutter: The following RangeError was thrown during performLayout():
  flutter: RangeError (index): Invalid value: Not in range 0..1,
  inclusive: 2

Body:
Try expanding your tick formatter closure so that you get more diagnostics:

final labels = charts.BasicNumericTickFormatterSpec((num value) {
  var index = value.floor();
  print('--- tick for $value in $string with $index ---');
  return (index < string.length)
      ? 'MyValue: ${string[index]}'
      : 'overflow ${string.length} $index';
});


问:
Extract number as an an integer from a string
I have some data which is badly formatted ( inherited) after some manipulation and some concatenation I have  something resembling the following in a string

"SIGNAGE -- 11 Requires door signage. "

My table has to cross reference a some data from a VLOOKUP and then tries to get the first chars in a pattern after the --

My formula is this

```<code>=IF(VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)<>"",LEFT((RIGHT((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)), LEN((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)))-SEARCH("--", (VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)),1)-2)),2),"")
</code>```

This successfully gives me the number 11.

My problem is that the number is being treated as a string and not as a numeric value.

What am I missing?

答:
I often use the trick when getting numbers out of text with LEFT(), MID() or RIGHT() to do a "*1" as the final step.

```<code>=mid(....) *1
</code>```

for example,

So, yours would be :

```<code>=IF(VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)<>"",LEFT((RIGHT((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)), LEN((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)))-SEARCH("--", (VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)),1)-2)),2),"")*1
</code>```

Body:
I have some data which is badly formatted ( inherited) after some manipulation and some concatenation I have  something resembling the following in a string

"SIGNAGE -- 11 Requires door signage. "

My table has to cross reference a some data from a VLOOKUP and then tries to get the first chars in a pattern after the --

My formula is this

=IF(VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)<>"",LEFT((RIGHT((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)), LEN((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)))-SEARCH("--", (VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)),1)-2)),2),"")

This successfully gives me the number 11.

My problem is that the number is being treated as a string and not as a numeric value.

What am I missing?

Body:
I often use the trick when getting numbers out of text with LEFT(), MID() or RIGHT() to do a "*1" as the final step.

=mid(....) *1

for example,

So, yours would be :

=IF(VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)<>"",LEFT((RIGHT((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)), LEN((VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)))-SEARCH("--", (VLOOKUP($C3,DoorCheck!$D3:$AD79,19,FALSE)),1)-2)),2),"")*1


问:
Replace multiple (special) characters - most efficient way?
At the texts that I have, I want to replace the following special characters with a single space:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
</code>```

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

```<code>(Hello World)] *!
</code>```

to become this:

```<code>Hello World
</code>```

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

答:
For an efficient solution you could use str.maketrans for this. Note that once the translation table is defined, it's onle a matter of mapping the characters in the string. Here's how you could do so:

```<code>symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+",
           "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]
</code>```

Start by creating a dictionary from the symbols using dict.fromkeys setting a single space as value for each entry and create a translation table from the dictionary:

```<code>d = dict.fromkeys(''.join(symbols), ' ')
# {'`': ' ', ',': ' ', '~': ' ', '!': ' ', '@': ' '...
t = str.maketrans(d)
</code>```

Then call the string translate method to map the characters in the above dictionary with an empty space:

```<code>s = '~this@is!a^test@'
s.translate(t)
# ' this is a test '
</code>```

Body:
At the texts that I have, I want to replace the following special characters with a single space:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

What is the most efficient way (in terms of time of code execution) to do this?

For example, I want this:

(Hello World)] *!

to become this:

Hello World

The candidate methods seem to be the following:

list comprehension

.replace()

.translate()

regular expressions

Body:
For an efficient solution you could use str.maketrans for this. Note that once the translation table is defined, it's onle a matter of mapping the characters in the string. Here's how you could do so:

symbols = ["`", "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+",
           "=", "{", "[", "]", "}", "|", "\\", ":", ";", "\"", "<", ",", ">", ".", "?", "/"]

Start by creating a dictionary from the symbols using dict.fromkeys setting a single space as value for each entry and create a translation table from the dictionary:

d = dict.fromkeys(''.join(symbols), ' ')
# {'`': ' ', ',': ' ', '~': ' ', '!': ' ', '@': ' '...
t = str.maketrans(d)

Then call the string translate method to map the characters in the above dictionary with an empty space:

s = '~this@is!a^test@'
s.translate(t)
# ' this is a test '


问:
shuffle card deck issues in language agnostic
Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.

Problem 1 :

Product of everything except current

Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]

For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.

IMPORTANT: Your algorithm must run in linear time.

Problem 2 : ( the topic was in one of Jeff posts )

Shuffle card deck evenly

Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).

Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()

What is the complexity of your algorithm (as a function of the number n of cards in the deck)?

Explain how you would test that the cards are evenly shuffled by your method (black box testing).

P.S. I had two hours to code the solutions

答:
Shuffle card deck evenly in C++

```<code>#include <algorithm>

class Deck {
  // each card is 8-bit: 4-bit for suit, 4-bit for value
  // suits and values are extracted using bit-magic
  char cards[52];
  public:
  // ...
  void shuffle() {
    std::random_shuffle(cards, cards + 52);
  }
  // ...
};
</code>```

Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html

Testing:

```<code>  // ...
  int main() {
    typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
    Map freqs;
    Deck d;
    const size_t ntests = 100000;

    // compute frequencies of events: card at position
    for (size_t i = 0; i < ntests; ++i) {
      d.shuffle();
      size_t pos = 0;
      for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
        ++freqs[std::make_pair(pos, *j)];
    }

    // if Deck.shuffle() is correct then all frequencies must be similar
    for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
      std::cout << "pos=" << j->first.first << " card=" << j->first.second
                << " freq=" << j->second << std::endl;
  }
</code>```

As usual, one test is not sufficient.

OwnerDisplayName: Kociub

LastEditorDisplayName: John Nolan

Body:
Shuffle card deck evenly in C++

#include <algorithm>

class Deck {
  // each card is 8-bit: 4-bit for suit, 4-bit for value
  // suits and values are extracted using bit-magic
  char cards[52];
  public:
  // ...
  void shuffle() {
    std::random_shuffle(cards, cards + 52);
  }
  // ...
};

Complexity: Linear in N. Exactly 51 swaps are performed. See http://www.sgi.com/tech/stl/random_shuffle.html

Testing:

  // ...
  int main() {
    typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
    Map freqs;
    Deck d;
    const size_t ntests = 100000;

    // compute frequencies of events: card at position
    for (size_t i = 0; i < ntests; ++i) {
      d.shuffle();
      size_t pos = 0;
      for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos)
        ++freqs[std::make_pair(pos, *j)];
    }

    // if Deck.shuffle() is correct then all frequencies must be similar
    for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
      std::cout << "pos=" << j->first.first << " card=" << j->first.second
                << " freq=" << j->second << std::endl;
  }

As usual, one test is not sufficient.

OwnerDisplayName: YXJuLnphcnQ

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: YXJuLnphcnQ


问:
Does Scala's pattern matching violate the Open/Closed Principle?
If I add a new case class, does that mean I need to search through all of the pattern matching code and find out where the new class needs to be handled?  I've been learning the language recently, and as I read about some of the arguments for and against pattern matching, I've been confused about where it should be used.  See the following:

Pro:
Odersky1 and
Odersky2

Con:
Beust

The comments are pretty good in each case, too.  So is pattern matching something to be excited about or something I should avoid using?  Actually, I imagine the answer is "it depends on when you use it," but what are some positive use cases for it and what are some negative ones?

答:
While I respect Cedric, he's completely wrong on this issue.  Scala's pattern matching can be fully-encapsulated from class changes when desired.  While it is true that a change to a case class would require changing any corresponding pattern matching instances, this is only when using such classes in a naive fashion.

Scala's pattern matching always delegates to the deconstructor of a class's companion object.  With a case class, this deconstructor is automatically generated (along with a factory method in the companion object), though it is still possible to override this auto-generated version.  At all times, you can assert complete control over the pattern matching process, insulating any patterns from potential changes in the class itself.  Thus, pattern matching is simply another way of accessing class data through the safe filter of encapsulation, just like any other method.

So, Dr. Odersky's opinion would be the one to trust here, particularly given the sheer volume of research he has performed in the area of object-oriented programming and design.

As for where it should be used, that is entirely according to taste.  If it makes your code more concise and maintainable, use it!  Otherwise, don't.  For most object-oriented programs, pattern matching is unnecessary.  However, once you begin to integrate more functional idioms (Option, List, etc) I think you'll find that pattern matching will significantly reduce syntactic overhead as well as improving the safety offered by the type system.  In general, any time you want to extract data while simultaneously testing some condition (e.g. extracting a value from Some), pattern matching will likely be of use.

OwnerDisplayName: Jeff

OwnerDisplayName: Daniel Spiewak


问:
C++: Cloud computing library: is there such a library where I don't need to write much network stuff?
I want my server app to be able to send data to be processed by a bunch of various clients, and then have the processed data returned to the server.

Ideally, I'd have some call like some_process = send_to_client_for_calculating(connection, data)

I just need to be able to send a bunch of data to a client, tell the client what to do (preferably in the same message, which can be done with an array [command, data]), and then return the data...

I'm breaking up pieces of a neural network (tis very large), and then assembling them all later.

If I need to be clearer, let me know how.

答: Why don't you have a look at using Apache ActiveMQ?  It's a Java JMS server, but it has C++ bindings, and does what you want with a minimum of writing networking code.  You basically just subscribe to messages, and send responses back.  The MQ server takes care of dispatch and message persistence for you. </p>


问:
Sheets: How to prepend with 1 with us phone number

I have a group of multi format phone numbers in a sheets column. I want to remove all non numeric digits and conditionally add a 1 in front (if its not there already). So far I have:

```<code>=ArrayFormula( (REGEXREPLACE( E1:E , "([^0-9]+)" , "" ) )
</code>```

which removes the non numerics. How do I conditionally prepend with 1?

答:
Since the source data is apparently Plain Text (or easily reformatted as such) a shorter version:

```<code>=ArrayFormula(if(E4:E="","",regexreplace(1&REGEXREPLACE(E4:E,"\D",""),"^11","1")))
</code>```

(Prepends a 1 in all cases, before stripping one 1 where number would otherwise start 11.)

Body:
I have a group of multi format phone numbers in a sheets column. I want to remove all non numeric digits and conditionally add a 1 in front (if its not there already). So far I have:

=ArrayFormula( (REGEXREPLACE( E1:E , "([^0-9]+)" , "" ) )

which removes the non numerics. How do I conditionally prepend with 1?

Body:
Since the source data is apparently Plain Text (or easily reformatted as such) a shorter version:

=ArrayFormula(if(E4:E="","",regexreplace(1&REGEXREPLACE(E4:E,"\D",""),"^11","1")))

(Prepends a 1 in all cases, before stripping one 1 where number would otherwise start 11.)


问:
parsing an array of elements in xml using java
Here, I'm using SAX method for parsing array. I'm facing an issue where I'm not able to write a generic code to parse an array type of xml. I couldn't find a solution for generic way methodology to identify it as an array and iterate over it and store it in List

```<code><bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>
</code>```

Any solution will help. Thanks in advance

答:
I use code below. I got it from: https://github.com/niteshapte/generic-xml-parser</p>

```<code>public class GenericXMLParserSAX extends DefaultHandler {

    private ListMultimap<String, String> listMultimap = ArrayListMultimap.create();
    String tempCharacter;
    private String[] startElements;
    private String[] endElements;

    public void setStartElements(String[] startElements) {
            this.startElements = startElements;
    }

    public String[] getStartElements() {
            return startElements;
    }

    public void setEndElements(String[] endElements) {
            this.endElements = endElements;
    }

    public String[] getEndElements() {
            return endElements;
    }

    public void parseDocument(String xml, String[] startElements, String[] endElements) {
            setStartElements(startElements);
            setEndElements(endElements);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                    SAXParser sp = spf.newSAXParser();
                    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
                    sp.parse(inputStream, this);
            } catch(SAXException se) {
                    se.printStackTrace();
            } catch(ParserConfigurationException pce) {
                    pce.printStackTrace();
            } catch (IOException ie) {
                    ie.printStackTrace();
            }
    }

    public void parseDocument(String xml, String[] endElements) {
            setEndElements(endElements);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                    SAXParser sp = spf.newSAXParser();
                    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
                    sp.parse(inputStream, this);
            } catch(SAXException se) {
                    se.printStackTrace();
            } catch(ParserConfigurationException pce) {
                    pce.printStackTrace();
            } catch (IOException ie) {
                    ie.printStackTrace();
            }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            String[] startElements = getStartElements();

            if(startElements!= null){
                    for(int i = 0; i < startElements.length; i++) {
                            if(qName.startsWith(startElements[i])) {
                                    listMultimap.put(startElements[i], qName);
                            }
                    }
            }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
            tempCharacter = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
            String[] endElements = getEndElements();

            for(int i = 0; i < endElements.length; i++) {
                    if (qName.equalsIgnoreCase(endElements[i])) {
                            listMultimap.put(endElements[i], tempCharacter);
                    }
            }
    }

    public ListMultimap<String, String> multiSetResult() {
            return listMultimap;
    }
}
</code>```

Body:
Here, I'm using SAX method for parsing array. I'm facing an issue where I'm not able to write a generic code to parse an array type of xml. I couldn't find a solution for generic way methodology to identify it as an array and iterate over it and store it in List

<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

Any solution will help. Thanks in advance

Body:
I use code below. I got it from: https://github.com/niteshapte/generic-xml-parser

public class GenericXMLParserSAX extends DefaultHandler {

    private ListMultimap<String, String> listMultimap = ArrayListMultimap.create();
    String tempCharacter;
    private String[] startElements;
    private String[] endElements;

    public void setStartElements(String[] startElements) {
            this.startElements = startElements;
    }

    public String[] getStartElements() {
            return startElements;
    }

    public void setEndElements(String[] endElements) {
            this.endElements = endElements;
    }

    public String[] getEndElements() {
            return endElements;
    }

    public void parseDocument(String xml, String[] startElements, String[] endElements) {
            setStartElements(startElements);
            setEndElements(endElements);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                    SAXParser sp = spf.newSAXParser();
                    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
                    sp.parse(inputStream, this);
            } catch(SAXException se) {
                    se.printStackTrace();
            } catch(ParserConfigurationException pce) {
                    pce.printStackTrace();
            } catch (IOException ie) {
                    ie.printStackTrace();
            }
    }

    public void parseDocument(String xml, String[] endElements) {
            setEndElements(endElements);

            SAXParserFactory spf = SAXParserFactory.newInstance();
            try {
                    SAXParser sp = spf.newSAXParser();
                    InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
                    sp.parse(inputStream, this);
            } catch(SAXException se) {
                    se.printStackTrace();
            } catch(ParserConfigurationException pce) {
                    pce.printStackTrace();
            } catch (IOException ie) {
                    ie.printStackTrace();
            }
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            String[] startElements = getStartElements();

            if(startElements!= null){
                    for(int i = 0; i < startElements.length; i++) {
                            if(qName.startsWith(startElements[i])) {
                                    listMultimap.put(startElements[i], qName);
                            }
                    }
            }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
            tempCharacter = new String(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
            String[] endElements = getEndElements();

            for(int i = 0; i < endElements.length; i++) {
                    if (qName.equalsIgnoreCase(endElements[i])) {
                            listMultimap.put(endElements[i], tempCharacter);
                    }
            }
    }

    public ListMultimap<String, String> multiSetResult() {
            return listMultimap;
    }
}


问:
display of blocks when changing tabs
I have the panel with tabs and a panel with content container.
When switching tabs, only div should be changed, and header should be displayed in all tabs.
I use the event selectedTabChange() that is listened to to check which tab is active and show the necessary div tag. What should I write to selectedTabChange()

.html:

```<code>            <mat-tab label="first"></mat-tab>
            <mat-tab label="second"></mat-tab>
            <mat-tab label="third"></mat-tab>
          </mat-tab-group>
          <div class="container">
            <div class="header">Header</div>
            <div *ngIf="isBlock2! && !isBlock3" class="block1">Text</div>
            <div *ngIf="isBlock1! && !isBlock3" class="block2">Text</div>
            <div *ngIf="isBlock1! && !isBlock2" class="block3">Text</div>
          </div>
</code>```

.ts:

```<code>   public isBlock2 = false;
   public isBlock3 = false;

  changeTabs(event) : void {
      isBlock1 != isBlock1;
  }
</code>```

答:
Here, you can use

ng-template and ng-container

Demo:

Stackblitz Link

```<code>selectedTabChangeEvent(event){
    this.isBlock1 = false;
    this.isBlock2 = false;
    this.isBlock3 = false;
    if(event.index === 0){
        this.isBlock1 = true;
    }else if(event.index === 1){
        this.isBlock2 = true;
    }else {
       this.isBlock3=true;
    }
}
</code>```

Title: display of blocks when changing tabs

Body:
I have the panel with tabs and a panel with content container.
When switching tabs, only div should be changed, and header should be displayed in all tabs.
I use the event selectedTabChange() that is listened to to check which tab is active and show the necessary div tag. What should I write to selectedTabChange()

.html:

            <mat-tab label="first"></mat-tab>
            <mat-tab label="second"></mat-tab>
            <mat-tab label="third"></mat-tab>
          </mat-tab-group>

Header

Text

Text

Text

.ts:

   public isBlock2 = false;
   public isBlock3 = false;

  changeTabs(event) : void {
      isBlock1 != isBlock1;
  }

Body:
Here, you can use

ng-template and ng-container

Demo:

Stackblitz Link

selectedTabChangeEvent(event){
    this.isBlock1 = false;
    this.isBlock2 = false;
    this.isBlock3 = false;
    if(event.index === 0){
        this.isBlock1 = true;
    }else if(event.index === 1){
        this.isBlock2 = true;
    }else {
       this.isBlock3=true;
    }
}


问:
How do I return the result of a recursive fetch?
I have the first asynchronous function

```<code>fetch("https://api.priceapi.com/v2/jobs", {
            body: body,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST"
                }).then((response) => {
                            return response.json();
                        }).then((data) => {

                            return fetchRepeat(data.job_id)
                        })

</code>```

And the second recursive asynchronous function.

```<code>function fetchRepeat(id){

    fetch("https://api.priceapi.com/v2/jobs/"+ id +"/download.json?token=" + priceapisecret.secret)
    .then((response) => {
        return response.json()
    }).then((data) =>{
        if(data.status == "finished"){

            var bookdata = {
                title: data.results[0].content.name,
                price: data.results[0].content.price
            }

            return bookdata;

        }
        else{
            fetchRepeat(id)
        }
    })
}
</code>```

I want to be able to access bookdata in the first async function. How do I do that?

答:
In order to talk about a return your fetchRepeat needs to return the promise. It did not so returning undefined was the result. The last then also didn't return the value of the recursion and thus also resolved to undefined.

Here is a working version:

function fetchRepeat(id) {
    // return the promise
    return fetch(`https://api.priceapi.com/v2/jobs/${id}/download.json?token=${priceapisecret.secret}`)
        .then(response => response.json())
        .then(({ status, results: [{ content: { name: title, price } }] = [{ content: {} }] }) =>
            (status === 'finished' ? { title, price } : fetchRepeat(id))); // return result of recursion
}
```

Now I let ESLint handle the formatting and since I use airbnb it prefers destructuring. The error in the last then was obvious since ELSint complained about consistent return. I urge you to use a linter and an IDE which enforces a coding style to reduce bugs in your code and make it easier for others to read.

Body:
I have the first asynchronous function

fetch("https://api.priceapi.com/v2/jobs", {
            body: body,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: "POST"
                }).then((response) => {
                            return response.json();
                        }).then((data) => {

                            return fetchRepeat(data.job_id)
                        })

And the second recursive asynchronous function.

function fetchRepeat(id){

    fetch("https://api.priceapi.com/v2/jobs/"+ id +"/download.json?token=" + priceapisecret.secret)
    .then((response) => {
        return response.json()
    }).then((data) =>{
        if(data.status == "finished"){

            var bookdata = {
                title: data.results[0].content.name,
                price: data.results[0].content.price
            }

            return bookdata;

        }
        else{
            fetchRepeat(id)
        }
    })
}

I want to be able to access bookdata in the first async function. How do I do that?

Body:
In order to talk about a return your fetchRepeat needs to return the promise. It did not so returning undefined was the result. The last then also didn't return the value of the recursion and thus also resolved to undefined.

Here is a working version:

function fetchRepeat(id) {
    // return the promise
    return fetch(`https://api.priceapi.com/v2/jobs/${id}/download.json?token=${priceapisecret.secret}`)
        .then(response => response.json())
        .then(({ status, results: [{ content: { name: title, price } }] = [{ content: {} }] }) =>
            (status === 'finished' ? { title, price } : fetchRepeat(id))); // return result of recursion
}

Now I let ESLint handle the formatting and since I use airbnb it prefers destructuring. The error in the last then was obvious since ELSint complained about consistent return. I urge you to use a linter and an IDE which enforces a coding style to reduce bugs in your code and make it easier for others to read.


问:
fetch local GIT branch on jenkins build
We are working on multiple feature, one develop, release and master GIT branches. We create separate feature branches for all JIRA development task. I need to have Jenkins build job to poll all feature branch, and build those specific ones which have recent PUSH events. After the build job is initiated, I want that specific GIT feature branch name (i.e. JIRA-1234, not origin/feature/JIRA-1234) to be picked up, included this in artifact file name as APP-0.0.1-JIRA-1234-SNAPSHOT, and save this to Nexus.

NB: POM.XML file is configured with APP-0.0.1-SNAPSHOT.

For each feature branch build, we want separate jar files saved to Nexus. For ex: Development task under JIRA-0101 would build and save jar in nexus as APP-0.0.1-JIRA-0101-SNAPSHOT

I have included ${branch} parameter in POM.xml as shown below:
APP-0.0.1${branch}-SNAPSHOT

and pass this value from Jenkins build command as - mvn clean install -Dbranch=-JIRA-0101

I then parametrised the jenkins build task, after which I can get feature branch name as "origin/feature/JIRA-0101", but I cannot parse this whole string in Jenkins to pick only JIRA task.

Secondly, mvn jgitflow:release-start and mvn jgitflow:release-finish commands would create complications having "APP-0.0.1${branch}-SNAPSHOT" in POM.xml. So, using ${branch} in POM is not effective.

答:
I'm not familiar with the jgitflow process, and I'll try to read up on that and tailor my answer, but for now I wanted to point you to this really great article on doing maven deployments - Maven Release Plugin: Dead and Buried.  The article talks about using an externally set version in their pom file - they embed a 'sane default' property into their codebase.

```<code>    <properties>
        <!-- Sane default when no revision property is passed in from the commandline -->
        <revision>0-SNAPSHOT</revision>
    </properties>
</code>```

They then reference that property in their <build> description

```<code>    <build>
        <plugins>
            <plugin>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.9.4</version>
                <configuration>
                    <tag>${project.artifactId}-${project.version}</tag>
                </configuration>
            </plugin>
        </plugins>
    </build>
</code>```

When invoking maven, they pass a custom parameter to it from their CI server - mvn deploy scm:tag -Drevision=$BUILD_NUMBER

I'm sure that with the jgitflow plugin, you may be able to have an internal property similar to the above configuration, but use it as a part of your jgitflow version with the branch information passed into your build.

--- Response to feedback ---

If you are just trying to extract the last part of the branch identifier, there are several ways you can do it.  If you just want everything after the last /, you could use the basename utility.

```<code>$ BRANCH="origin/feature/JIRA-0101"
$ basename $BRANCH
JIRA-0101
</code>```

You could be more specific with a regular expression that expects the ASDF-1234 style pattern

```<code>$ echo $BRANCH | sed -e 's|.*/\([A-Z]*-[0-9]*\)$|\1|g'
JIRA-0101
</code>```

And if you want to capture the above into a new variable, you can use a subshell, either directly in your call to maven

```<code>mvn clean install -Dbranch=$(echo $BRANCH | sed -e 's|.*/\([A-Z]*-[0-9]*\)$|\1|g')
</code>```

Or storing it in an intermediate variable that you could test to verify is nonzero length

```<code>JIRA_ID=$(echo $BRANCH | sed -e 's|.*/\([A-Z]*-[0-9]*\)$|\1|g')
[[ -z "${JIRA_ID}" ]] && echo "Unable to determine JIRA_ID" && exit 1
mvn clean install -Dbranch=${JIRA_ID}
</code>```

If you need to pass the variable to a different step (if directly using the maven plugin), you will need a plugin similar to the envinject environment injection plugin, described in this answer

Title: fetch local GIT branch on jenkins build

Body:
I'm not familiar with the jgitflow process, and I'll try to read up on that and tailor my answer, but for now I wanted to point you to this really great article on doing maven deployments - Maven Release Plugin: Dead and Buried.  The article talks about using an externally set version in their pom file - they embed a 'sane default' property into their codebase.

    <properties>
        <!-- Sane default when no revision property is passed in from the commandline -->
        <revision>0-SNAPSHOT</revision>
    </properties>

They then reference that property in their <build> description

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-scm-plugin</artifactId>
                <version>1.9.4</version>
                <configuration>
                    <tag>${project.artifactId}-${project.version}</tag>
                </configuration>
            </plugin>
        </plugins>
    </build>

When invoking maven, they pass a custom parameter to it from their CI server - mvn deploy scm:tag -Drevision=$BUILD_NUMBER

I'm sure that with the jgitflow plugin, you may be able to have an internal property similar to the above configuration, but use it as a part of your jgitflow version with the branch information passed into your build.

--- Response to feedback ---

If you are just trying to extract the last part of the branch identifier, there are several ways you can do it.  If you just want everything after the last /, you could use the basename utility.

$ BRANCH="origin/feature/JIRA-0101"
$ basename $BRANCH
JIRA-0101

You could be more specific with a regular expression that expects the ASDF-1234 style pattern

$ echo $BRANCH | sed -e 's|.*/\([A-Z]*-[0-9]*\)$|\1|g'
JIRA-0101

And if you want to capture the above into a new variable, you can use a subshell, either directly in your call to maven

mvn clean install -Dbranch=$(echo $BRANCH | sed -e 's|.*/\([A-Z]*-[0-9]*\)$|\1|g')

Or storing it in an intermediate variable that you could test to verify is nonzero length

JIRA_ID=$(echo $BRANCH | sed -e 's|.*/\([A-Z]*-[0-9]*\)$|\1|g')
[[ -z "${JIRA_ID}" ]] && echo "Unable to determine JIRA_ID" && exit 1
mvn clean install -Dbranch=${JIRA_ID}

If you need to pass the variable to a different step (if directly using the maven plugin), you will need a plugin similar to the envinject environment injection plugin, described in this answer


问:
Is it possible to connect NodeMCU ESP8266 arduino chip control to a windows form application through wifi?
My goal is to make a windows form application that could turn on or off a relay module that is connected to a NodeMCU board with ESP8266 wifi module, that is connected to the same network as my computer.

I managed to control it through USB using SerialPort library, but I have no idea if its even possible to control it through wifi. This is how my arduino code looks like:

```<code>#include <ESP8266WiFi.h>

int Module1 = 0;
int Module2 = 2;
const char* ssid = "Android";
const char* password = "password";

void setup()
{
 Serial.begin(9600);
 pinMode(Module1,OUTPUT);
 pinMode(Module2,OUTPUT);
}
void loop()
{
 char data = Serial.read();
 switch (data){
   case '1' : digitalWrite(Module1,HIGH); ;break;
   case '2' : digitalWrite(Module2,HIGH); ;break;
   case '3' : digitalWrite(Module1,LOW); ;break;
   case '4' : digitalWrite(Module2,LOW); ;break;
   }
}
</code>```

Any way I could do the same but the controls would work through wifi? As in if I would be able to control the relay with a windows form app without connecting the board to the PC? (another power source for example)

答:
Simple answer: Yes.

More long-winded version: You need to either connect your ESP board to a web service like IFTTT (see https://ifttt.com/ ) or write a web service on it that can react to messages from the client (see https://randomnerdtutorials.com/esp8266-web-server-with-arduino-ide/ ).

Body:
My goal is to make a windows form application that could turn on or off a relay module that is connected to a NodeMCU board with ESP8266 wifi module, that is connected to the same network as my computer.

I managed to control it through USB using SerialPort library, but I have no idea if its even possible to control it through wifi. This is how my arduino code looks like:

#include <ESP8266WiFi.h>

int Module1 = 0;
int Module2 = 2;
const char* ssid = "Android";
const char* password = "password";

void setup()
{
 Serial.begin(9600);
 pinMode(Module1,OUTPUT);
 pinMode(Module2,OUTPUT);
}
void loop()
{
 char data = Serial.read();
 switch (data){
   case '1' : digitalWrite(Module1,HIGH); ;break;
   case '2' : digitalWrite(Module2,HIGH); ;break;
   case '3' : digitalWrite(Module1,LOW); ;break;
   case '4' : digitalWrite(Module2,LOW); ;break;
   }
}

Any way I could do the same but the controls would work through wifi? As in if I would be able to control the relay with a windows form app without connecting the board to the PC? (another power source for example)


答:
I would write the delete as:

```<code>delete t
from <table> t join
     (select schemacode, fincode, max(invdate) as max_invdate
      from <table> t2
      group by schemacode, fincode
     ) tt
     on t.schemacode = tt.schemacode and
        t.fincode = tt.fincode and
        t.invdate < tt.max_invdate;
</code>```

Title: how to delete the data from table for each scheme for fincode

Body:
i have table

|Schemecode  | Fincode |Invdate     |
|:-----------|--------:|:----------:|
|1           |    81   |  2019-03-31|
|1           |    81   |  2019-04-30|
|1           |    82   |  2019-04-30|
|4           |    34   |  2019-04-30|
|4           |    35   |  2019-04-30|
|6           |    38   |  2019-04-30|
|6           |    38   |  2019-03-31|
|6           |    81   |  2019-04-30|
|6           |    81   |  2019-03-31|
|6           |    42   |  2019-04-30|

i want to delete
all the duplicate rows having Fincode as duplicate for each Schemecode with Invdate older date i.e (2019-03-31)  Not with 2019-04-30.

i have tried query but unable to do

Expected output :

after delete

|Schemecode  | Fincode |Invdate     |
|:-----------|--------:|:----------:|
|1           |    81   |  2019-04-30|
|1           |    82   |  2019-04-30|
|4           |    34   |  2019-04-30|
|4           |    35   |  2019-04-30|
|6           |    38   |  2019-04-30|
|6           |    81   |  2019-04-30|
|6           |    42   |  2019-04-30|

Body:
I would write the delete as:

delete t
from <table> t join
     (select schemacode, fincode, max(invdate) as max_invdate
      from <table> t2
      group by schemacode, fincode
     ) tt
     on t.schemacode = tt.schemacode and
        t.fincode = tt.fincode and
        t.invdate < tt.max_invdate;


问:
How to loop over query data and insert in structure?
I have query data that should be inserted in the structure. While looping over data each value should be assigned to matching column. Here is example of query data:

```<code>    REC_ID  NAME    STATUS      TYPE    YEAR
1   01      PARIS   Approved    1       2019
2   06      AUSTIN  Inactive    3       2017
3   48      LONDON  Approved    2       2018
4   43      ROME    Inactive    5       2019
5   61      DUBLIN  Inactive    4       2019
</code>```

This data should be organized to look like this:

```<code>1
  REC_ID  01
  NAME    PARIS
  STATUS  Approved
  TYPE    1
  YEAR    2019
2
  REC_ID  06
  NAME    AUSTIN
  STATUS  Inactive
  TYPE    3
  YEAR    2017
3
  REC_ID  48
  NAME    LONDON
  STATUS  Approved
  TYPE    2
  YEAR    2018
4
  REC_ID  43
  NAME    ROME
  STATUS  Inactive
  TYPE    5
  YEAR    2019
5
  REC_ID  61
  NAME    DUBLIN
  STATUS  Inactive
  TYPE    4
  YEAR    2019
</code>```

I tried to get desired data format with this function:

```<code>function formatData(qryData) {
    local.fnResult = structNew();
    local.fnData = structNew();

    if(qryData.recordcount){
        for(row in qryData) {
            for(column in qryData.columnList) {
                local.strRec = structNew();
                structInsert(strRec, column, row[column]);
                local.fnData[qryData.currentrow] = strRec;
            }
        }
    }

    writeDump(fnData);
}
</code>```

Here is how my result looks:

```<code>1
  REC_ID  01
2
  REC_ID  06
3
  REC_ID  48
4
  REC_ID  43
5
  REC_ID  61
</code>```

I use ColdFusion 11 cfscript syntax. If anyone can help me solve this problem please let me know. Thank you.

答:
There is an issue with your column list loop, you are creating a new structure for each column and that get reset in the next loop.

This loop should be changed

```<code>for(column in qryData.columnList) {
    local.strRec = structNew();
    structInsert(strRec, column, row[column]);
    local.fnData[qryData.currentrow] = strRec;
}
</code>```

to look like

```<code>local.strRec = structNew();
for(column in qryData.columnList) {
    structInsert(strRec, column, row[column]);
}
local.fnData[qryData.currentrow] = strRec;
</code>```

Body:
I have query data that should be inserted in the structure. While looping over data each value should be assigned to matching column. Here is example of query data:

    REC_ID  NAME    STATUS      TYPE    YEAR
1   01      PARIS   Approved    1       2019
2   06      AUSTIN  Inactive    3       2017
3   48      LONDON  Approved    2       2018
4   43      ROME    Inactive    5       2019
5   61      DUBLIN  Inactive    4       2019

This data should be organized to look like this:

1
  REC_ID  01
  NAME    PARIS
  STATUS  Approved
  TYPE    1
  YEAR    2019
2
  REC_ID  06
  NAME    AUSTIN
  STATUS  Inactive
  TYPE    3
  YEAR    2017
3
  REC_ID  48
  NAME    LONDON
  STATUS  Approved
  TYPE    2
  YEAR    2018
4
  REC_ID  43
  NAME    ROME
  STATUS  Inactive
  TYPE    5
  YEAR    2019
5
  REC_ID  61
  NAME    DUBLIN
  STATUS  Inactive
  TYPE    4
  YEAR    2019

I tried to get desired data format with this function:

function formatData(qryData) {
    local.fnResult = structNew();
    local.fnData = structNew();

    if(qryData.recordcount){
        for(row in qryData) {
            for(column in qryData.columnList) {
                local.strRec = structNew();
                structInsert(strRec, column, row[column]);
                local.fnData[qryData.currentrow] = strRec;
            }
        }
    }

    writeDump(fnData);
}

Here is how my result looks:

1
  REC_ID  01
2
  REC_ID  06
3
  REC_ID  48
4
  REC_ID  43
5
  REC_ID  61

I use ColdFusion 11 cfscript syntax. If anyone can help me solve this problem please let me know. Thank you.

Body:
There is an issue with your column list loop, you are creating a new structure for each column and that get reset in the next loop.

This loop should be changed

for(column in qryData.columnList) {
    local.strRec = structNew();
    structInsert(strRec, column, row[column]);
    local.fnData[qryData.currentrow] = strRec;
}

to look like

local.strRec = structNew();
for(column in qryData.columnList) {
    structInsert(strRec, column, row[column]);
}
local.fnData[qryData.currentrow] = strRec;