问:
Express Router redirect after post request gets sent
I have an express route that handles creating new users and I need the page to redirect to /thankyou.html after the user and token get sent.

So I am handling the redirect on the front end but instead of redirecting correctly the browser is showing the JSON user data.

If I test the route through postman everything works as expected on the back end.

I tried redirecting on the express server after the user gets sent and I also tried chaining redirect and send methods. I also added validation to my onreadystatechange to redirect after the proper status code but the page is still redirecting to the JSON data.

Here is my User router.

```<code>const express = require("express");
const router = new express.Router();
const User = require("../models/user");
const client = require("twilio")(process.env.accountSid, process.env.authToken);
const auth = require("../middleware/auth");
const {
  sendWelcomeEmail,
  sendCancellationEmail
} = require("../emails/account");
const multer = require("multer");
const sharp = require("sharp");

router.post("/users", async (req, res) => {
  const user = new User(req.body);
  phone = req.body.phone;
  console.log("Line(18) userRouter req.body", req.body);

  try {
    await user.save();
    sendWelcomeEmail(user.email, user.name);
    const token = await user.generateAuthToken();

    client.calls.create(
      {
        url: "https://example.com/voice/",
        to: phone,
        from: "+17861230774"
      },
      (err, call) => {
        if (!err) {
          process.stdout.write(call.sid);
        }
      }
    );
    res.status(201).send({ user, token });
  } catch (e) {
    res.status(400);
    console.log("User Router Error l:38: ", e);
  }
});

module.exports = router;
</code>```

Here is my Javascript in the front end that is handling the post request.

```<code>// Function to create a new user
const registerButton = document.querySelector("#register");
registerButton.addEventListener("click", event => {
  event.preventDefault();
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

  const firstName = document.querySelector("#firstname").value;
  const lastName = document.querySelector("#lastname").value;

  const email = document.querySelector("#email").value;
  const phone = document.querySelector("#phone").value;
  const streetAddress = document.querySelector("#streetaddress").value;
  const zipcode = document.querySelector("#zipcode").value;
  const monthlyBill = document.querySelector("#monthlybill").value;
  const electricProvider = document.querySelector("#electricprovider").value;
  const homeowner = document.querySelector("#homeowner").value;
  console.log(
    firstName,
    lastName,
    email,
    phone,
    streetAddress,
    zipcode,
    monthlyBill,
    electricProvider,
    homeowner
  );
  if (!firstName || !lastName || !email || !phone) {
    alert("Please fill out all fields.");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else if (phone.length !== 10) {
    alert("Please enter a valid 10 digit phone number");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/users", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(
      JSON.stringify({
        firstName: firstName,
        lastName: lastName,
        email: email,
        phone: phone,
        zipcode: zipcode,
        electricProvider: electricProvider,
        monthlyBill: monthlyBill,
        streetAddress: streetAddress,
        homeowner: homeowner
      })
    );
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 201) {
        console.log(xhr.responseText);
        window.location = "/thankyou.html";
      }
    };
  }
});
</code>```

I was expecting the browser to redirect to /thankyou.html after the user is created but instead the page is redirecting to /users and rendering the user data. Any tips would be greatly appreciated.

答:
Try to replace the location</p>

```<code>window.location.replace("http://localhost/thankyou.html");
</code>```

Body:
I have an express route that handles creating new users and I need the page to redirect to /thankyou.html after the user and token get sent.

So I am handling the redirect on the front end but instead of redirecting correctly the browser is showing the JSON user data.

If I test the route through postman everything works as expected on the back end.

I tried redirecting on the express server after the user gets sent and I also tried chaining redirect and send methods. I also added validation to my onreadystatechange to redirect after the proper status code but the page is still redirecting to the JSON data.

Here is my User router.

const express = require("express");
const router = new express.Router();
const User = require("../models/user");
const client = require("twilio")(process.env.accountSid, process.env.authToken);
const auth = require("../middleware/auth");
const {
  sendWelcomeEmail,
  sendCancellationEmail
} = require("../emails/account");
const multer = require("multer");
const sharp = require("sharp");

router.post("/users", async (req, res) => {
  const user = new User(req.body);
  phone = req.body.phone;
  console.log("Line(18) userRouter req.body", req.body);

  try {
    await user.save();
    sendWelcomeEmail(user.email, user.name);
    const token = await user.generateAuthToken();

    client.calls.create(
      {
        url: "https://example.com/voice/",
        to: phone,
        from: "+17861230774"
      },
      (err, call) => {
        if (!err) {
          process.stdout.write(call.sid);
        }
      }
    );
    res.status(201).send({ user, token });
  } catch (e) {
    res.status(400);
    console.log("User Router Error l:38: ", e);
  }
});

module.exports = router;

Here is my Javascript in the front end that is handling the post request.

// Function to create a new user
const registerButton = document.querySelector("#register");
registerButton.addEventListener("click", event => {
  event.preventDefault();
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

  const firstName = document.querySelector("#firstname").value;
  const lastName = document.querySelector("#lastname").value;

  const email = document.querySelector("#email").value;
  const phone = document.querySelector("#phone").value;
  const streetAddress = document.querySelector("#streetaddress").value;
  const zipcode = document.querySelector("#zipcode").value;
  const monthlyBill = document.querySelector("#monthlybill").value;
  const electricProvider = document.querySelector("#electricprovider").value;
  const homeowner = document.querySelector("#homeowner").value;
  console.log(
    firstName,
    lastName,
    email,
    phone,
    streetAddress,
    zipcode,
    monthlyBill,
    electricProvider,
    homeowner
  );
  if (!firstName || !lastName || !email || !phone) {
    alert("Please fill out all fields.");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else if (phone.length !== 10) {
    alert("Please enter a valid 10 digit phone number");
  } else if (!filter.test(email)) {
    alert("Please provide a valid email address.");
  } else {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/users", true);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.send(
      JSON.stringify({
        firstName: firstName,
        lastName: lastName,
        email: email,
        phone: phone,
        zipcode: zipcode,
        electricProvider: electricProvider,
        monthlyBill: monthlyBill,
        streetAddress: streetAddress,
        homeowner: homeowner
      })
    );
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 201) {
        console.log(xhr.responseText);
        window.location = "/thankyou.html";
      }
    };
  }
});

I was expecting the browser to redirect to /thankyou.html after the user is created but instead the page is redirecting to /users and rendering the user data. Any tips would be greatly appreciated.

Body:
Try to replace the location

window.location.replace("http://localhost/thankyou.html");


来源: stackexchange

答:
Here are two ways of solving your problem.

1. The Easy Way (Using `uvm_analysis_imp_decl Macros)

Simply invoke the macro outside of the component class for each input. The macro declares a special flavour of analysis imp. The argument passed to the macro is used as a suffix within the type name of the imp and the name of the write method. You then instantiate one imp per input and define one method per input. eg:

```<code>`uvm_analysis_imp_decl(_AXI4_S)
`uvm_analysis_imp_decl(_AXI4)
`uvm_analysis_imp_decl(_APB)

class scoreboard extends uvm_scoreboard;

  uvm_analysis_imp_AXI4_S #(AXI4_S_xact, scoreboard) AXI4_S_export;
  uvm_analysis_imp_AXI4   #(AXI4_xact,   scoreboard) AXI4_S_export;
  uvm_analysis_imp_APB    #(APB_xact,    scoreboard) APB_export;
  ...
  function void build_phase(uvm_phase phase);
    AXI4_S_export = new("AXI4_S_export", this);
    AXI4_export   = new("AXI4_export",   this);
    APB_export    = new("APB_export",    this);
  endfunction
  ...
  function void write_AXI4_S(AXI4_S_xact t);
    ...
  endfunction

  function void write_AXI4(AXI4_xact t);
    ...
  endfunction

  function void write_APB(APB_xact t);
    ...
  endfunction
  ...
</code>```

2. The Hard Way (Embedded Subscribers)

Instantiate three subscribers inside your scoreboard. Each is a separate scope, so each can have its own write method.

ContentLicense: CC BY-SA 4.0

Title: What environment architecture to choose to verify multi-interface module

Body:
I'm going to test complex module which have axi4-stream and apb interfaces as inputs and axi4 interface as output.

As I understand, I should build this kind of environment:

                                      |-----------------------------------------------
                                      |                                              |
                             _________|_________           _______________     ______v______
                            |                   |         |               |    |            |
                            |   APB-monitor     |         | AXI4-monitor  |--->|            |
                            |___________________|         |_______________|    |            |
                                       |                          |            |            |
 ____________        ______________    |     _________            |            |            |
|            |      |              |   |    |         |           |            |            |
| APB-seqr   |----->| APB-master   |---*--->|         |           |            |            |
|____________|      |______________|        |         |           |            |            |
                                            |   DUT   |           |            |            |
 ____________        ______________         |         |-----------*----------->| Scoreboard |
|            |      |              |        |         |                        |            |
|AXI4-S-seqr |----->|AXI4-S-master |---*--->|         |                        |            |
|____________|      |______________|   |    |_________|                        |            |
                                       |                                       |            |
                                       |                                       |            |
                             --------------------                              |            |
                            |                    |                             |            |
                            |   AXI4-S-monitor   |---------------------------->|            |
                            |____________________|                             |____________|

Is it correct? If so, how should I send transactions from monitors to scoreboard? I guess I should use analysis_port/imp pair but I can't overload write method in scoreboard class, so as I understand, I can't use three analysis ports in one class.

Can anyone point me to uvm example of such a complex design?

Currently I have this type of error when try to use analysis ports:

#    Time: 0 ps  Iteration: 0  Region: /uvm_pkg::uvm_analysis_imp #(axi4_s_pkg::axi4_s_seq_item, ecaa_pkg::ecaa_scoreboard) File: D:/questasim64_10.4c/win64/../verilog_src/uvm-1.1d/src/uvm_pkg.sv
# ** Error: (vsim-8754) D:/questasim64_10.4c/win64/../verilog_src/uvm-1.1d/src/tlm1/uvm_analysis_port.svh(114): Actual input arg. of type 'class work.axi4_s_pkg::axi4_s_seq_item' for formal 'trans' of 'write' is not compatible with the formal's type 'class work.apb_pkg::apb_seq_item #(3, 2, 32, 32, 4)'.```

Body:
Here are two ways of solving your problem.

1. The Easy Way (Using `uvm_analysis_imp_decl Macros)

Simply invoke the macro outside of the component class for each input. The macro declares a special flavour of analysis imp. The argument passed to the macro is used as a suffix within the type name of the imp and the name of the write method. You then instantiate one imp per input and define one method per input. eg:

`uvm_analysis_imp_decl(_AXI4_S)
`uvm_analysis_imp_decl(_AXI4)
`uvm_analysis_imp_decl(_APB)

class scoreboard extends uvm_scoreboard;

  uvm_analysis_imp_AXI4_S #(AXI4_S_xact, scoreboard) AXI4_S_export;
  uvm_analysis_imp_AXI4   #(AXI4_xact,   scoreboard) AXI4_S_export;
  uvm_analysis_imp_APB    #(APB_xact,    scoreboard) APB_export;
  ...
  function void build_phase(uvm_phase phase);
    AXI4_S_export = new("AXI4_S_export", this);
    AXI4_export   = new("AXI4_export",   this);
    APB_export    = new("APB_export",    this);
  endfunction
  ...
  function void write_AXI4_S(AXI4_S_xact t);
    ...
  endfunction

  function void write_AXI4(AXI4_xact t);
    ...
  endfunction

  function void write_APB(APB_xact t);
    ...
  endfunction
  ...

2. The Hard Way (Embedded Subscribers)

Instantiate three subscribers inside your scoreboard. Each is a separate scope, so each can have its own write method.


问:
Warning: Attempt to present * on * which is already presenting (null)
This is my first application for iOS.

So I have a UIVIewController with a UITableView where I have integrated a UISearchBar and a UISearchController in order to filter TableCells to display

```<code>override func viewDidLoad() {
    menuBar.delegate = self
    table.dataSource = self
    table.delegate = self
    let nib = UINib(nibName: "ItemCellTableViewCell", bundle: nil)
    table.registerNib(nib, forCellReuseIdentifier: "Cell")

    let searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "search:")
    menuBar.topItem?.leftBarButtonItem = searchButton
    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        return controller
    })()
    self.table.reloadData()
}
</code>```

I am using also a modal segue in order to open the element's ViewController where I will display details of the element.

```<code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.index = indexPath.row
    self.performSegueWithIdentifier("ItemDetailFromHome", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "ItemDetailFromHome") {
        let settingsVC = segue.destinationViewController as! ItemDetailViewController
        settingsVC.parent = self
        if self.isSearching == true  && self.searchText != nil && self.searchText != ""  {
            settingsVC.item = self.filteredItems[self.index!]
        } else {
            settingsVC.item = self.items[self.index!]
        }

    }
}
</code>```

That works fine until I try to display the ItemDetailViewController for a filtered element (through the UISearchController).

I have the following message :

```<code>Warning: Attempt to present <ItemDetailViewController: *>  on <HomeViewController: *> which is already presenting (null)
</code>```

At every time I am going to the ItemDetailViewController.viewDidLoad() function but after that when the search is activated I have the previous error.

Any idea ? I have tried to use the following async dispatch but without success

```<code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.index = indexPath.row
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.performSegueWithIdentifier("ItemDetailFromHome", sender: self)
    })
}
</code>```

答:
I got the same issue when i tried to present a VC which called inside the SideMenu(jonkykong).

first i tried inside the SideMenu and i called it from the delegate to the MainVC both had the same issue.

Solution: dismiss the SideMenu first and present the new VC after will works perfectly!.

ContentLicense: CC BY-SA 3.0

Body:
This is my first application for iOS.

So I have a UIVIewController with a UITableView where I have integrated a UISearchBar and a UISearchController in order to filter TableCells to display

override func viewDidLoad() {
    menuBar.delegate = self
    table.dataSource = self
    table.delegate = self
    let nib = UINib(nibName: "ItemCellTableViewCell", bundle: nil)
    table.registerNib(nib, forCellReuseIdentifier: "Cell")

    let searchButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: "search:")
    menuBar.topItem?.leftBarButtonItem = searchButton
    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        return controller
    })()
    self.table.reloadData()
}

I am using also a modal segue in order to open the element's ViewController where I will display details of the element.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.index = indexPath.row
    self.performSegueWithIdentifier("ItemDetailFromHome", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "ItemDetailFromHome") {
        let settingsVC = segue.destinationViewController as! ItemDetailViewController
        settingsVC.parent = self
        if self.isSearching == true  && self.searchText != nil && self.searchText != ""  {
            settingsVC.item = self.filteredItems[self.index!]
        } else {
            settingsVC.item = self.items[self.index!]
        }

    }
}

That works fine until I try to display the ItemDetailViewController for a filtered element (through the UISearchController).

I have the following message :

Warning: Attempt to present <ItemDetailViewController: *>  on <HomeViewController: *> which is already presenting (null)

At every time I am going to the ItemDetailViewController.viewDidLoad() function but after that when the search is activated I have the previous error.

Any idea ? I have tried to use the following async dispatch but without success

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.index = indexPath.row
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.performSegueWithIdentifier("ItemDetailFromHome", sender: self)
    })
}


问:
CSS ::after Adding Ring Shape
I'm looking to add a CSS shape after a div of content.

The shape will be a ring: so, a circle with a hole in the middle.

```<code>.name::after {
    content: '';
    width: 12px;
    height: 12px;
    border-width: 2px;
    border-style: solid;
    border-radius: 12px;
}

.name.track-1::after {
    border-color: #0065FF;
}

.name.track-2::after {
    border-color: #FFC300;
}
</code>```

As you can see, I'm trying to apply a basic style ::after .name then when it's accompanied by additional classes like .track-1 or .track-2 it will be different colors.

I am seeing nothing show up though. I've also tried the CSS2 :after, no luck. I've tried putting border-color into the main .name::after with no luck. Any help would be great, thank you!

EDIT HTML was requested:

```<code><div class="name track-1">This is the name of something here</div>
</code>```

答: You should specify a display: block property on .name::after.

Title: CSS ::after Adding Ring Shape

Body:
I'm looking to add a CSS shape after a div of content.

The shape will be a ring: so, a circle with a hole in the middle.

.name::after {
    content: '';
    width: 12px;
    height: 12px;
    border-width: 2px;
    border-style: solid;
    border-radius: 12px;
}

.name.track-1::after {
    border-color: #0065FF;
}

.name.track-2::after {
    border-color: #FFC300;
}

As you can see, I'm trying to apply a basic style ::after .name then when it's accompanied by additional classes like .track-1 or .track-2 it will be different colors.

I am seeing nothing show up though. I've also tried the CSS2 :after, no luck. I've tried putting border-color into the main .name::after with no luck. Any help would be great, thank you!

EDIT HTML was requested:

This is the name of something here


问:
Why/how is an additional variable needed in matching repeated arbitary character with capture groups?
I'm matching a sequence of a repeating arbitrary character, with a minimum length, using a perl6 regex.

After reading through https://docs.perl6.org/language/regexes#Capture_numbers and tweaking the example given, I've come up with this code using an 'external variable':

```<code>#uses an additional variable $c
perl6 -e '$_="bbaaaaawer"; /((.){} :my $c=$0; ($c)**2..*)/ && print $0';

#Output:  aaaaa
</code>```

To aid in illustrating my question only, a similar regex in perl5:

```<code>#No additional variable needed
perl -e ' $_="bbaaaaawer"; /((.)\2{2,})/ && print $1';
</code>```

Could someone enlighten me on the need/benefit of 'saving' $0 into $c and the requirement of the empty {}? Is there an alternative (better/golfed) perl6 regex that will match?

Thanks in advance.

答:
The reason you have to store the capture into something other than $0 is that every capturing () creates a new set of numbered captures.

So the $0 inside of ($0) can never refer to anything, because you didn't set $0 inside of the ().

(The named captures $<foo> are also affected by this.)

The following has 3 separate $0 “variables”, and one $1 “variable”:

'aabbaabb' ~~ / ^ ( (.)$0 ((.)$0) ) $0 $ /

'aabbaabb' ~~ /
                ^

                # $0 = 'aabb'
                (

                  # $0 = 'a'
                  (.) $0

                  # $1 = 'bb'
                  (

                    # $0 = 'b'
                    (.) $0
                  )
                )

                $0

                $
              /
```

<pre class="lang-none prettyprint-override"><code>｢aabbaabb｣
 0 => ｢aabb｣
  0 => ｢a｣
  1 => ｢bb｣
   0 => ｢b｣
</code>```

Basically the () in the regex DSL act a bit like {} in normal Perl6.

A fairly direct if simplified translation of the above regex to “regular” Perl6 code follows.

(Pay attention to the 3 lines with my $/ = [];)

(Also the / ^ / style comments refer to the regex code for ^ and such above)

given 'aabbaabb' {
    my $/ = [];      # give assignable storage for $0, $1 etc.
    my $pos = 0;     # position counter
    my $init = $pos; # initial position

    # / ^ /
    fail unless $pos == 0;

    # / ( /
    $0 = do {
        my $/ = [];
        my $init = $pos;

        # / (.) $0 /
        $0 = .substr($pos,1); # / (.) /
        $pos += $0.chars;
        fail unless .substr($pos,$0.chars) eq $0; # / $0 /
        $pos += $0.chars;

        # / ( /
        $1 = do {
            my $/ = [];
            my $init = $pos;

            # / (.) $0 /
            $0 = .substr($pos,1); # / (.) /
            $pos += $0.chars;
            fail unless .substr($pos,$0.chars) eq $0; # / $0 /
            $pos += $0.chars;

        # / ) /
            # the returned value (becomes $1 in outer scope)
           .substr($init, $pos - $init)
        }

    # / ) /
        # the returned value (becomes $0 in outer scope)
        .substr($init, $pos - $init)
    }

    # / $0 /
    fail unless .substr($pos,$0.chars) eq $0;
    $pos += $0.chars;

    # / $ /
    fail unless $pos = .chars;

    # the returned value
    .substr($init, $pos - $init)
}
```

<hr>

<p>TLDR;</p>

<p>Just remove the <code>()</code> surrounding <code>($c)</code> / <code>($0)</code>.<br>
(Assuming you didn't need the capture for something else.)</p>

<pre class="lang-perl6 prettyprint-override"><code>/((.) $0**2..*)/
</code>```

perl6 -e '$_="bbaaaaawer"; /((.) $0**2..*)/ && put $0';
```

Body:
I'm matching a sequence of a repeating arbitrary character, with a minimum length, using a perl6 regex.

After reading through https://docs.perl6.org/language/regexes#Capture_numbers and tweaking the example given, I've come up with this code using an 'external variable':

#uses an additional variable $c
perl6 -e '$_="bbaaaaawer"; /((.){} :my $c=$0; ($c)**2..*)/ && print $0';

#Output:  aaaaa

To aid in illustrating my question only, a similar regex in perl5:

#No additional variable needed
perl -e ' $_="bbaaaaawer"; /((.)\2{2,})/ && print $1';

Could someone enlighten me on the need/benefit of 'saving' $0 into $c and the requirement of the empty {}? Is there an alternative (better/golfed) perl6 regex that will match?

Thanks in advance.

Body:
The reason you have to store the capture into something other than $0 is that every capturing () creates a new set of numbered captures.

So the $0 inside of ($0) can never refer to anything, because you didn't set $0 inside of the ().

(The named captures $<foo> are also affected by this.)

The following has 3 separate $0 “variables”, and one $1 “variable”:

'aabbaabb' ~~ / ^ ( (.)$0 ((.)$0) ) $0 $ /

'aabbaabb' ~~ /
                ^

                # $0 = 'aabb'
                (

                  # $0 = 'a'
                  (.) $0

                  # $1 = 'bb'
                  (

                    # $0 = 'b'
                    (.) $0
                  )
                )

                $0

                $
              /

｢aabbaabb｣
 0 => ｢aabb｣
  0 => ｢a｣
  1 => ｢bb｣
   0 => ｢b｣

Basically the () in the regex DSL act a bit like {} in normal Perl6.

A fairly direct if simplified translation of the above regex to “regular” Perl6 code follows.

(Pay attention to the 3 lines with my $/ = [];)

(Also the / ^ / style comments refer to the regex code for ^ and such above)

given 'aabbaabb' {
    my $/ = [];      # give assignable storage for $0, $1 etc.
    my $pos = 0;     # position counter
    my $init = $pos; # initial position

    # / ^ /
    fail unless $pos == 0;

    # / ( /
    $0 = do {
        my $/ = [];
        my $init = $pos;

        # / (.) $0 /
        $0 = .substr($pos,1); # / (.) /
        $pos += $0.chars;
        fail unless .substr($pos,$0.chars) eq $0; # / $0 /
        $pos += $0.chars;

        # / ( /
        $1 = do {
            my $/ = [];
            my $init = $pos;

            # / (.) $0 /
            $0 = .substr($pos,1); # / (.) /
            $pos += $0.chars;
            fail unless .substr($pos,$0.chars) eq $0; # / $0 /
            $pos += $0.chars;

        # / ) /
            # the returned value (becomes $1 in outer scope)
           .substr($init, $pos - $init)
        }

    # / ) /
        # the returned value (becomes $0 in outer scope)
        .substr($init, $pos - $init)
    }

    # / $0 /
    fail unless .substr($pos,$0.chars) eq $0;
    $pos += $0.chars;

    # / $ /
    fail unless $pos = .chars;

    # the returned value
    .substr($init, $pos - $init)
}

TLDR;

Just remove the () surrounding ($c) / ($0).

(Assuming you didn't need the capture for something else.)

/((.) $0**2..*)/

perl6 -e '$_="bbaaaaawer"; /((.) $0**2..*)/ && put $0';


问:
Validate Microsoft Graph acces token
I've implemented Azure AD authentication from my PHP app, using adal.js and the MS PHP SDK.

Everything works except I can't decode the access token to check if it is expired/ should be renewed.

I uploaded a certificate in the Azure Portal, but when trying to decode the access token I get a 'Signature verification failed' error.

Any hints where to look?

答: The access token you receive from Azure AD should have an expiresOn attribute that is the time the token expires. In my applications, I store that data and simply check if the current time is past the expireOn time</p>

Title: Validate Microsoft Graph acces token


问:
How do I properly make images for a website?
I know this seems like a simple question, but I'm really stuck. I am developing a website and Firefox is altering the image colors for the site.  The issue is stemming from Firefox's use of ICC color profiles (I think).

I've done tons of research on the topic, and most of it boils down to sRGB when saving in Photoshop, but the color profiles are already set to sRGB.

These are the color settings I use when I save:
http://i.stack.imgur.com/jLJ5g.png

http://i.stack.imgur.com/OAx88.png - How it looks in Firefox 3, Chrome, and IE

http://i.stack.imgur.com/B7bcC.png - How it looks in Firefox 4

I can disable Firefox 4's color management through

about:config / gfx.color_management.enabled = 0,

but that is not a correct solution.

Wat do?

URL: http://development.smgwebdesign.com/riley

Thanks guys.

答:
Well to help keep the colours correct, don't use an image to create the background.

As it is only one colour just set the background colour using css.

It accepts hexidecimal values.

eg #15253c would be your colour.

You can find different ones in photoshop by going to the colour selector tool.

It shows what the colour is in lots of different ways.

Then make the background of the logo transparent so there are no colour issues there.

I can't see how you're colouring the nav menu, but if you can use css and background colours directly,
as apposed to images, it will work better.

Use css wherever you can, it will work better and your website will load faster.

Check out http://www.w3schools.com/css/default.asp for help with CSS.

Also, for the images you do have to use, try the 'save for web' option in photoshop.


问:
Deploying multiple divs based on number input
I'm trying to display multiple divs based on what on the user's number input. For example if user picks 3 then 3 divs are displayed.

I managed to get it working but I need to set IDs for each div dynamically for the returned values, and to set number next to the word car for example Car 1 Car 2 Car 3.

```<code>        <div class="col-md-12">
            <div id="content"></div>
            <script>
                function myFunction(){
                var n = Number(document.getElementById("nbchambre").value);
                var content = document.getElementById('content');
                content.innerHTML="";
                for(var count = 1; count < n+1; count++){
                var div = document.createElement('div');
                div.innerHTML = 'Car : <input type="date" name="bday">';
                content.appendChild(div);
                    }
                }
            </script>
        </div>
</code>```

Out come should be if user puts 3
car 1:
car 2:
car 3:

答:
You can do it by simply appending the count in the string

function myFunction() {
  var n = Number(document.getElementById("nbchambre").value);
  var content = document.getElementById('content');
  content.innerHTML = "";
  for (var count = 1; count < n + 1; count++) {
    var div = document.createElement('div');
    div.innerHTML = `Car ${count}: <input type="date" name="bday">`;
    content.appendChild(div);
  }
}

document.querySelector('#nbchambre').addEventListener("input", myFunction)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="nbchambre">
<div class="col-md-12">
  <div id="content"></div>
</div></code>```

Body:
I'm trying to display multiple divs based on what on the user's number input. For example if user picks 3 then 3 divs are displayed.

I managed to get it working but I need to set IDs for each div dynamically for the returned values, and to set number next to the word car for example Car 1 Car 2 Car 3.

Out come should be if user puts 3
car 1:
car 2:
car 3:

Body:
You can do it by simply appending the count in the string

function myFunction() {
  var n = Number(document.getElementById("nbchambre").value);
  var content = document.getElementById('content');
  content.innerHTML = "";
  for (var count = 1; count < n + 1; count++) {
    var div = document.createElement('div');
    div.innerHTML = `Car ${count}: <input type="date" name="bday">`;
    content.appendChild(div);
  }
}

document.querySelector('#nbchambre').addEventListener("input", myFunction)

<input id="nbchambre">
<div class="col-md-12">
  <div id="content"></div>
</div>


问:
How to get table name for a simple Sequel Dataset object?
Ie, given a dataset object ds = DB[:transactions].where{updated_at > 1.day.ago} - no funny joins and stuff going on - how could I fetch the table name (:transactions) ?

答:
Based on the example provided, I would do something like this.

```<code>ds.klass.name
</code>```

That will return a string with the name of your table.

Body:
Based on the example provided, I would do something like this.

ds.klass.name

That will return a string with the name of your table.


问:
How to convert a byte array to float in Python
I have a byte array, which originally was converted from a float array in Scala. I need to convert it back to a float array in Python.

This is the code I used to convert the float array in Scala:

val float_ary_len = float_ary.size
val bb = java.nio.ByteBuffer.allocate(float_ary_len * 4)
for(each_float <- float_ary){
    bb.putFloat(each_folat)
}
val bytes_ary = bb.array()
```

<p>Then in Python, I can get this byte array and I need to convert it back to a float array.</p>

<p>I have tried the following code in Python, but it didn't give me the right float. </p>

<pre class="lang-py prettyprint-override"><code>print(list(bytes_ary[0:4]))
#['\xc2', '\xda', 't', 'Z']

struct.unpack('f', bytes_ary[0:4])
# it gave me 1.7230105268977664e+16, but it should be -109.22725
</code>```

Please let me know how should I get the right float?

答:
It could be because of the endian encoding.

You should try big endian:

```<code>struct.unpack('>f', bytes_ary[0:4])
</code>```

or little endian:

```<code>struct.unpack('<f', bytes_ary[0:4])
</code>```

Body:
I have a byte array, which originally was converted from a float array in Scala. I need to convert it back to a float array in Python.

This is the code I used to convert the float array in Scala:

val float_ary_len = float_ary.size
val bb = java.nio.ByteBuffer.allocate(float_ary_len * 4)
for(each_float <- float_ary){
    bb.putFloat(each_folat)
}
val bytes_ary = bb.array()

Then in Python, I can get this byte array and I need to convert it back to a float array.

I have tried the following code in Python, but it didn't give me the right float.

print(list(bytes_ary[0:4]))
#['\xc2', '\xda', 't', 'Z']

struct.unpack('f', bytes_ary[0:4])
# it gave me 1.7230105268977664e+16, but it should be -109.22725

Please let me know how should I get the right float?

Body:
It could be because of the endian encoding.

You should try big endian:

struct.unpack('>f', bytes_ary[0:4])

or little endian:

struct.unpack('<f', bytes_ary[0:4])


问:
how to append nil to dynamic type slice by reflect.Append
Code below will raise a runtime error when append reflect.Value of nil:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var list []interface{}
    v := reflect.ValueOf(list)
    v = reflect.Append(v, reflect.ValueOf(1))   // [1]
    v = reflect.Append(v, reflect.ValueOf("1")) // [1, 1]
    v = reflect.Append(v, reflect.ValueOf(nil)) // runtime error
    fmt.Println(v)
}
```

So

why there is a runtime error?

how can I use reflect.Append to add a nil to interface{} slice?

答:
interface{} is an interface type, and they are "tricky". They are wrappers around a concrete value and the concrete type, schematically a (value, type) pair.

So when you pass a concrete value to a function that expects an interface{} value, the concrete value will be wrapped in an interface{} value automatically, implicitly. If you pass a nil to such a function, the interface value itself will be nil. If you pass a nil pointer to it, such as (*int)(nil), the interface value will not be nil but an interface value holding "(nil, *int)".

If you pass nil to reflect.ValueOf(), it results in a "zero" reflect.Value which represents no value at all. If you pass this to reflect.Append(), it will not have the type information, it will not know what you want to append to the slice.

It is possible to create a value that represents the nil interface value.

To do that, we may start from the type descriptor of a value of an interface pointer (pointers to interface rarely makes sense, but this is one of them). We navigate to the type descriptor of the pointed type, which is interface{}. We obtain a zero value of this type (using reflect.Zero()), which is nil (zero value of interface types is nil).

Zero returns a Value representing the zero value for the specified type. The result is different from the zero value of the Value struct, which represents no value at all.

So this is how it looks like:

```<code>typeOfEmptyIface := reflect.TypeOf((*interface{})(nil)).Elem()
valueOfZeroEmptyIface := reflect.Zero(typeOfEmptyIface)
v = reflect.Append(v, valueOfZeroEmptyIface)
</code>```

Or as a single line:

```<code>v = reflect.Append(v, reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem()))
</code>```

To check the results, let's use:

```<code>fmt.Printf("%#v\n", v)
</code>```

And also let's type-assert back the slice, and add a nil value using the builtin append() function:

```<code>list = v.Interface().([]interface{})
list = append(list, nil)
fmt.Printf("%#v\n", list)
</code>```

Let's do an explicit, extra check if the elements are nil (compare them to nil). Although using %#v verb this is redundant, %v likes to print non-nil interfaces holding nil concrete values just as nil (the same as if the interface value itself would be nil).

```<code>fmt.Println(list[2] == nil, list[3] == nil)
</code>```

Ouptut will be (try it on the Go Playground):

```<code>[]interface {}{1, "1", interface {}(nil)}
[]interface {}{1, "1", interface {}(nil), interface {}(nil)}
true true
</code>```

See related question: Hiding nil values, understanding why golang fails here

Also: The Go Blog: The Laws of Reflection

Body:
Code below will raise a runtime error when append reflect.Value of nil:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var list []interface{}
    v := reflect.ValueOf(list)
    v = reflect.Append(v, reflect.ValueOf(1))   // [1]
    v = reflect.Append(v, reflect.ValueOf("1")) // [1, 1]
    v = reflect.Append(v, reflect.ValueOf(nil)) // runtime error
    fmt.Println(v)
}

So

why there is a runtime error?

how can I use reflect.Append to add a nil to interface{} slice?

Body:
interface{} is an interface type, and they are "tricky". They are wrappers around a concrete value and the concrete type, schematically a (value, type) pair.

So when you pass a concrete value to a function that expects an interface{} value, the concrete value will be wrapped in an interface{} value automatically, implicitly. If you pass a nil to such a function, the interface value itself will be nil. If you pass a nil pointer to it, such as (*int)(nil), the interface value will not be nil but an interface value holding "(nil, *int)".

If you pass nil to reflect.ValueOf(), it results in a "zero" reflect.Value which represents no value at all. If you pass this to reflect.Append(), it will not have the type information, it will not know what you want to append to the slice.

It is possible to create a value that represents the nil interface value.

To do that, we may start from the type descriptor of a value of an interface pointer (pointers to interface rarely makes sense, but this is one of them). We navigate to the type descriptor of the pointed type, which is interface{}. We obtain a zero value of this type (using reflect.Zero()), which is nil (zero value of interface types is nil).

Zero returns a Value representing the zero value for the specified type. The result is different from the zero value of the Value struct, which represents no value at all.

So this is how it looks like:

typeOfEmptyIface := reflect.TypeOf((*interface{})(nil)).Elem()
valueOfZeroEmptyIface := reflect.Zero(typeOfEmptyIface)
v = reflect.Append(v, valueOfZeroEmptyIface)

Or as a single line:

v = reflect.Append(v, reflect.Zero(reflect.TypeOf((*interface{})(nil)).Elem()))

To check the results, let's use:

fmt.Printf("%#v\n", v)

And also let's type-assert back the slice, and add a nil value using the builtin append() function:

list = v.Interface().([]interface{})
list = append(list, nil)
fmt.Printf("%#v\n", list)

Let's do an explicit, extra check if the elements are nil (compare them to nil). Although using %#v verb this is redundant, %v likes to print non-nil interfaces holding nil concrete values just as nil (the same as if the interface value itself would be nil).

fmt.Println(list[2] == nil, list[3] == nil)

Ouptut will be (try it on the Go Playground):

[]interface {}{1, "1", interface {}(nil)}
[]interface {}{1, "1", interface {}(nil), interface {}(nil)}
true true

See related question: Hiding nil values, understanding why golang fails here

Also: The Go Blog: The Laws of Reflection


问:
Changing product name on checkout and order on WooCommerce with WPML
I am using WooCommerce with WPML plugin. I want to implement a feature on checkout when a customer under certain conditions can have an upgrade of his product but keeping the old product price.

The products are variable with many variable attributes.
So, more specifically, what I want is if a customer has selected a specific product variation with x price on checkout (under a certain condition) I could change his cart item with another product's variation but keep the x price.

What I tried first is to change only the name of the product using woocommerce_order_item_name hook but the change doesn't follow on the order. This is important because some order data are then sent to an API.

Afterwards I used "Changing WooCommerce cart item names" answer code, which worked perfectly for my purpose until I installed WPML. For some reason the WC_Cart method set_name() doesn't work with WPML. I opened a support thread but they still can't find a solution.

Can anyone suggest any other solution?

Update

I have tried an approach where I remove the product item on cart and then I add the one I need. After I use set_price() to change the price of the newly added item. The removal/addition seems to be working but the price is not changed on one language and it is not applied on both languages after placing order.
This is the code I use:

```<code>function berrytaxiplon_change_product_name( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {

                $new_product = wc_get_product( 82 );
                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

                foreach ( WC()->cart->get_cart() as $new_item ) {

                    $new_item['data']->set_price( $cart_item['s-fare'] );
                }
            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {

                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( $cart_item['s-fare']);
                }

            }
        }

    }

}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

</code>```

Any idea why the set_price() method is not applied?

Update 2

WPMl uses 'woocommerce_before_calculate_totals' and overrides the action added on functions.php

WPML support provided a solution using 3 filters:

https://wpml.org/forums/topic/cant-use-set_name-method-for-the-product-object-on-checkout/#post-3977153

答:
The code provided from Faham is very helpful but the page-template that leads to checkout is already over-complicated so I focused to use his logic on the 'woocommerce_before_calculate_totals' hook I am trying all along.
So instead of trying to change the name I remove the item and add the new one. Then calling a new loop I set the price to be of the item that was removed.

```<code>function berrytaxiplon_change_product_name( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {
            // SET THE NEW NAME
            $new_product = wc_get_product( 82 );

            $atrributes = $product->get_attributes('view');
            foreach ($atrributes as $atrribute_key => $atrribute_value) {
                $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
            }
            $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
            $cart->remove_cart_item( $cart_item_key );
            $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

            foreach ( WC()->cart->get_cart() as $new_item ) {
                $new_item['data']->set_price( get_post_meta( $cart_item['variation_id'], '_price', true ) );
            }

            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {
                // SET THE NEW NAME
                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( get_post_meta( $cart_item['variation_id'], '_price', true ) );
                }

               }
        }

    }
}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );
</code>```

I use the function below to match the attributes taken from the question WooCommerce: Get Product Variation ID from Matching Attributes

```<code>function find_matching_product_variation_id($product_id, $attributes)
{
    return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
        new \WC_Product($product_id),
        $attributes
    );
}
</code>```

I am a little skeptical using add_to_cart() and a second foreach() inside the $cart_item. But I tested and it seems to work without errors.

Update

Actually there is an issue with this code (or with WPML again). It seems that set_price() is not applied on the secondary language. Yet if I reload the checkout page an send the data again the new price is applied.

Body:
I am using WooCommerce with WPML plugin. I want to implement a feature on checkout when a customer under certain conditions can have an upgrade of his product but keeping the old product price.

The products are variable with many variable attributes.
So, more specifically, what I want is if a customer has selected a specific product variation with x price on checkout (under a certain condition) I could change his cart item with another product's variation but keep the x price.

What I tried first is to change only the name of the product using woocommerce_order_item_name hook but the change doesn't follow on the order. This is important because some order data are then sent to an API.

Afterwards I used "Changing WooCommerce cart item names" answer code, which worked perfectly for my purpose until I installed WPML. For some reason the WC_Cart method set_name() doesn't work with WPML. I opened a support thread but they still can't find a solution.

Can anyone suggest any other solution?

Update

I have tried an approach where I remove the product item on cart and then I add the one I need. After I use set_price() to change the price of the newly added item. The removal/addition seems to be working but the price is not changed on one language and it is not applied on both languages after placing order.
This is the code I use:

function berrytaxiplon_change_product_name( $cart ) {

if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {

                $new_product = wc_get_product( 82 );
                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

                foreach ( WC()->cart->get_cart() as $new_item ) {

                    $new_item['data']->set_price( $cart_item['s-fare'] );
                }
            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {

                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( $cart_item['s-fare']);
                }

            }
        }

    }

}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

Any idea why the set_price() method is not applied?

Update 2

WPMl uses 'woocommerce_before_calculate_totals' and overrides the action added on functions.php

WPML support provided a solution using 3 filters:

https://wpml.org/forums/topic/cant-use-set_name-method-for-the-product-object-on-checkout/#post-3977153

Body:
The code provided from Faham is very helpful but the page-template that leads to checkout is already over-complicated so I focused to use his logic on the 'woocommerce_before_calculate_totals' hook I am trying all along.
So instead of trying to change the name I remove the item and add the new one. Then calling a new loop I set the price to be of the item that was removed.

function berrytaxiplon_change_product_name( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $product_id = method_exists( $product, 'get_parent_id' ) ? $product->get_parent_id() : $product->post->post_parent;

        if ( ICL_LANGUAGE_CODE == 'en') {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 12) {
            // SET THE NEW NAME
            $new_product = wc_get_product( 82 );

            $atrributes = $product->get_attributes('view');
            foreach ($atrributes as $atrribute_key => $atrribute_value) {
                $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
            }
            $new_variation_id = find_matching_product_variation_id(82, $new_attributes);
            $cart->remove_cart_item( $cart_item_key );
            $cart->add_to_cart( 82, 1, $new_variation_id, $new_attributes, $cart_item );

            foreach ( WC()->cart->get_cart() as $new_item ) {
                $new_item['data']->set_price( get_post_meta( $cart_item['variation_id'], '_price', true ) );
            }

            }
        } else {
            if (isset($cart_item['s-member-level']) && $cart_item['s-member-level'] == 3 && $product_id == 282) {
                // SET THE NEW NAME
                $new_product = wc_get_product( 303 );

                $atrributes = $product->get_attributes('view');
                foreach ($atrributes as $atrribute_key => $atrribute_value) {
                    $new_attributes['attribute_' . $atrribute_key] = strtolower($atrribute_value);
                }
                $new_variation_id = find_matching_product_variation_id(303, $new_attributes);
                $cart->remove_cart_item( $cart_item_key );
                $cart->add_to_cart( 303, 1, $new_variation_id, $new_attributes, $cart_item );
                foreach ( WC()->cart->get_cart() as $new_item ) {
                    $new_item['data']->set_price( get_post_meta( $cart_item['variation_id'], '_price', true ) );
                }

               }
        }

    }
}
add_action( 'woocommerce_before_calculate_totals', 'berrytaxiplon_change_product_name', 10, 1 );

I use the function below to match the attributes taken from the question WooCommerce: Get Product Variation ID from Matching Attributes

function find_matching_product_variation_id($product_id, $attributes)
{
    return (new \WC_Product_Data_Store_CPT())->find_matching_product_variation(
        new \WC_Product($product_id),
        $attributes
    );
}

I am a little skeptical using add_to_cart() and a second foreach() inside the $cart_item. But I tested and it seems to work without errors.

Update

Actually there is an issue with this code (or with WPML again). It seems that set_price() is not applied on the secondary language. Yet if I reload the checkout page an send the data again the new price is applied.


问:
Index error: index 14285 is out of bounds for axis 0 with size 14285
I am trying to write a dataframe to a csv file.
when I run this command df.to_csv("somefile.csv").
I am getting below error:

IndexError: index 14285 is out of bounds for axis 0 with size 14285

I checked length of index and data, both are same.

```<code>df = pd.DataFrame(preds,columns = ['PA','PB','PC','PD','PE','PF','PG'], index =[X_valid_full['ID']])

len(preds)

len(X_valid_full['ID'].unique())

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-69-4113bef3e95d> in <module>
----> 1 df.to_csv("somefile.csv")

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\core\generic.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote, escapechar, decimal)
   3018                                  doublequote=doublequote,
   3019                                  escapechar=escapechar, decimal=decimal)
-> 3020         formatter.save()
   3021
   3022         if path_or_buf is None:

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\io\formats\csvs.py in save(self)
    170                 self.writer = UnicodeWriter(f, **writer_kwargs)
    171
--> 172             self._save()
    173
    174         finally:

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\io\formats\csvs.py in _save(self)
    286                 break
    287
--> 288             self._save_chunk(start_i, end_i)
    289
    290     def _save_chunk(self, start_i, end_i):

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\io\formats\csvs.py in _save_chunk(self, start_i, end_i)
    313
    314         libwriters.write_csv_rows(self.data, ix, self.nlevels,
--> 315                                   self.cols, self.writer)

pandas\_libs\writers.pyx in pandas._libs.writers.write_csv_rows()

IndexError: index 14285 is out of bounds for axis 0 with size 14285
</code>```

答:
It looks like you may be passing the dataframe constructor argument, index, a list with a series instead of just the raw index. This has the effect

In [22]: df = pd.DataFrame(preds,columns = ['PA','PB','PC','PD','PE','PF','PG','PH','PI','PJ'], index = [X_valid_full['ID']])

In [23]: df
Out[23]:

```<code>    PA  PB  PC  PD  PE  PF  PG  PH  PI  PJ
ID
0    0   1   2   3   4   5   6   7   8   9
1   10  11  12  13  14  15  16  17  18  19
2   20  21  22  23  24  25  26  27  28  29
3   30  31  32  33  34  35  36  37  38  39
4   40  41  42  43  44  45  46  47  48  49
5   50  51  52  53  54  55  56  57  58  59
6   60  61  62  63  64  65  66  67  68  69
7   70  71  72  73  74  75  76  77  78  79
8   80  81  82  83  84  85  86  87  88  89
9   90  91  92  93  94  95  96  97  98  99
</code>```

But I am still able to get to_csv to write the csv file. What I think may be happening is that there are duplicate id's in your 'ID' column.

Because you are using unique in len(X_valid_full['ID'].unique()), you are getting the same size as preds.

A way to address this may be to use X_valid_full.set_index('ID',inplace=True) either before calling the DataFrame constructor or in the constructor without inplace=True. You can also use X_valid_full['ID'].unique() as your index as it appears to be the same size as your preds 1st dimension.

Body:
I am trying to write a dataframe to a csv file.
when I run this command df.to_csv("somefile.csv").
I am getting below error:

IndexError: index 14285 is out of bounds for axis 0 with size 14285

I checked length of index and data, both are same.

df = pd.DataFrame(preds,columns = ['PA','PB','PC','PD','PE','PF','PG'], index =[X_valid_full['ID']])

len(preds)

len(X_valid_full['ID'].unique())

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-69-4113bef3e95d> in <module>
----> 1 df.to_csv("somefile.csv")

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\core\generic.py in to_csv(self, path_or_buf, sep, na_rep, float_format, columns, header, index, index_label, mode, encoding, compression, quoting, quotechar, line_terminator, chunksize, tupleize_cols, date_format, doublequote, escapechar, decimal)
   3018                                  doublequote=doublequote,
   3019                                  escapechar=escapechar, decimal=decimal)
-> 3020         formatter.save()
   3021
   3022         if path_or_buf is None:

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\io\formats\csvs.py in save(self)
    170                 self.writer = UnicodeWriter(f, **writer_kwargs)
    171
--> 172             self._save()
    173
    174         finally:

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\io\formats\csvs.py in _save(self)
    286                 break
    287
--> 288             self._save_chunk(start_i, end_i)
    289
    290     def _save_chunk(self, start_i, end_i):

c:\users\appdata\local\programs\python\python37\lib\site-packages\pandas\io\formats\csvs.py in _save_chunk(self, start_i, end_i)
    313
    314         libwriters.write_csv_rows(self.data, ix, self.nlevels,
--> 315                                   self.cols, self.writer)

pandas\_libs\writers.pyx in pandas._libs.writers.write_csv_rows()

IndexError: index 14285 is out of bounds for axis 0 with size 14285

Body:
It looks like you may be passing the dataframe constructor argument, index, a list with a series instead of just the raw index. This has the effect

In [22]: df = pd.DataFrame(preds,columns = ['PA','PB','PC','PD','PE','PF','PG','PH','PI','PJ'], index = [X_valid_full['ID']])

In [23]: df
Out[23]:

    PA  PB  PC  PD  PE  PF  PG  PH  PI  PJ
ID
0    0   1   2   3   4   5   6   7   8   9
1   10  11  12  13  14  15  16  17  18  19
2   20  21  22  23  24  25  26  27  28  29
3   30  31  32  33  34  35  36  37  38  39
4   40  41  42  43  44  45  46  47  48  49
5   50  51  52  53  54  55  56  57  58  59
6   60  61  62  63  64  65  66  67  68  69
7   70  71  72  73  74  75  76  77  78  79
8   80  81  82  83  84  85  86  87  88  89
9   90  91  92  93  94  95  96  97  98  99

But I am still able to get to_csv to write the csv file. What I think may be happening is that there are duplicate id's in your 'ID' column.

Because you are using unique in len(X_valid_full['ID'].unique()), you are getting the same size as preds.

A way to address this may be to use X_valid_full.set_index('ID',inplace=True) either before calling the DataFrame constructor or in the constructor without inplace=True. You can also use X_valid_full['ID'].unique() as your index as it appears to be the same size as your preds 1st dimension.


问:
how to copy values from one sheet where the values are starting from a specific row
I want to copy values from sheet named "Price Schedule" where the values which I want to start copying from "Row 10" and ONLY "Column D" and "Column F" should be copied. And paste it into another sheet named "Sheet1". It should start pasting values from "row 25" and paste under "Column H" and "Column I".

I want to put a condition statement where I want to copy only the rows which have the value grater than "zero" in "Column D" in sheet "Price Schedule" and paste it in "sheet1" under Column"H" and Column "I" starting from "row 25".

```<code>Private Sub CommandButton1_Click()

a = Worksheets("PRICE SCHEDULE").Cells(Rows.Count, 1).End(xlUp).Row

For I = 2 To a
    If Worksheets("PRICE SCHEDULE").Cells(I, 4).Value = ">0" Then
        Worksheets("PRICE SCHEDULE").Rows(I).Copy
        Worksheets("Sheet1").Activate

        b = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
        ActiveSheet.Paste

        Worksheets("PRICE SCHEDULE").Activate
    End If
Next

End Sub
</code>```

I tried doing this and passed a msgbox to see the results but it shows no results of the copied data.

Please see the images for better understanding.

答:
I'd use a filter for this task, like so:</p>

```<code>Sub tgr()

    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsDest As Worksheet
    Dim rDest As Range

    Set wb = ActiveWorkbook
    Set wsData = wb.Worksheets("Price Schedule")
    Set wsDest = wb.Worksheets("Sheet1")
    Set rDest = wsDest.Cells(wsDest.Rows.Count, "H").End(xlUp).Offset(1)
    If rDest.Row < 25 Then Set rDest = wsDest.Range("H25")

    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    With wsData.Range("D9:F" & wsData.Cells(wsData.Rows.Count, "D").End(xlUp).Row)
        If .Row < 9 Then GoTo CleanExit     'No data
        .AutoFilter 1, ">0", xlFilterValues 'Filter on column D for values >0
        Intersect(.Worksheet.Range("D:D,F:F"), .Offset(1)).Copy 'Copy filtered values in columns D and F only
        rDest.PasteSpecial xlPasteValues    'Paste values only to destination
        .AutoFilter 'Clear filter
    End With

CleanExit:
    With Application
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub
</code>```

Body:
I want to copy values from sheet named "Price Schedule" where the values which I want to start copying from "Row 10" and ONLY "Column D" and "Column F" should be copied. And paste it into another sheet named "Sheet1". It should start pasting values from "row 25" and paste under "Column H" and "Column I".

I want to put a condition statement where I want to copy only the rows which have the value grater than "zero" in "Column D" in sheet "Price Schedule" and paste it in "sheet1" under Column"H" and Column "I" starting from "row 25".

Private Sub CommandButton1_Click()

a = Worksheets("PRICE SCHEDULE").Cells(Rows.Count, 1).End(xlUp).Row

For I = 2 To a
    If Worksheets("PRICE SCHEDULE").Cells(I, 4).Value = ">0" Then
        Worksheets("PRICE SCHEDULE").Rows(I).Copy
        Worksheets("Sheet1").Activate

        b = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
        ActiveSheet.Paste

        Worksheets("PRICE SCHEDULE").Activate
    End If
Next

End Sub

I tried doing this and passed a msgbox to see the results but it shows no results of the copied data.

Please see the images for better understanding.

Body:
I'd use a filter for this task, like so:

Sub tgr()

    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsDest As Worksheet
    Dim rDest As Range

    Set wb = ActiveWorkbook
    Set wsData = wb.Worksheets("Price Schedule")
    Set wsDest = wb.Worksheets("Sheet1")
    Set rDest = wsDest.Cells(wsDest.Rows.Count, "H").End(xlUp).Offset(1)
    If rDest.Row < 25 Then Set rDest = wsDest.Range("H25")

    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    With wsData.Range("D9:F" & wsData.Cells(wsData.Rows.Count, "D").End(xlUp).Row)
        If .Row < 9 Then GoTo CleanExit     'No data
        .AutoFilter 1, ">0", xlFilterValues 'Filter on column D for values >0
        Intersect(.Worksheet.Range("D:D,F:F"), .Offset(1)).Copy 'Copy filtered values in columns D and F only
        rDest.PasteSpecial xlPasteValues    'Paste values only to destination
        .AutoFilter 'Clear filter
    End With

CleanExit:
    With Application
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub


问:
If cell is "SU" COUNTA previous 6 cells
How I can input to formula condition when Excel can recognize that it is cell with value "SU" and if it is perform =COUNTA(previous 6 cells on row 11) operation?

Then I can drag that cell with formula below so it will work for the whole range.

In this case it will be false as TH is empty, otherwise if TH will be not empty it should perform calculation.

```<code>=IF(O11="SU";IF(COUNTA(previous 6 cells on row 11)<6;50;70))
</code>```

So when this formula will reach U11 COUNTA range should be O11:T11, when formula will reach AB11 COUNTA range should be V11:AA11 etc.

答:
Your question is really unclear.

As I understand, you want to count the number of non-empty cells in the last 6 cells when the day is Sunday. And fill blank if it not Sunday.

The formula for above would be:

```<code>=IF(O9="SU",COUNTA(I11:N11),"")
</code>```

You can drag this formula horizontally.

**Although COUNTA counts formulas i.e. if a cell contains formula that returns blank then COUNTA would count that as well.

If you have only numbers in the previous 6 cells, then you change COUNTA to COUNT and the above problem will be taken care of.

Title: If cell is "SU" COUNTA previous 6 cells

Body:
How I can input to formula condition when Excel can recognize that it is cell with value "SU" and if it is perform =COUNTA(previous 6 cells on row 11) operation?

Then I can drag that cell with formula below so it will work for the whole range.

In this case it will be false as TH is empty, otherwise if TH will be not empty it should perform calculation.

=IF(O11="SU";IF(COUNTA(previous 6 cells on row 11)<6;50;70))

So when this formula will reach U11 COUNTA range should be O11:T11, when formula will reach AB11 COUNTA range should be V11:AA11 etc.

Body:
Your question is really unclear.

As I understand, you want to count the number of non-empty cells in the last 6 cells when the day is Sunday. And fill blank if it not Sunday.

The formula for above would be:

=IF(O9="SU",COUNTA(I11:N11),"")

You can drag this formula horizontally.

**Although COUNTA counts formulas i.e. if a cell contains formula that returns blank then COUNTA would count that as well.

If you have only numbers in the previous 6 cells, then you change COUNTA to COUNT and the above problem will be taken care of.


问:
Realm db in lib + Realm db in app using the lib is conflicting with each other
I have created an SDK which uses Realm db to store data. see code below how i have initialized my sdk db

```<code>  Realm.init(application);
  config = new RealmConfiguration.Builder().name("sdk.db")
            .schemaVersion(1)
            .deleteRealmIfMigrationNeeded()
            .build();
  Realm.setDefaultConfiguration(config);
</code>```

Similarly for App in the application class.

First app db is created and initialized and the sdk method is called,which internally creates and initializes sdk.db.

But when i run the app i get following error

io.realm.exceptions.RealmException: Async transaction failed

Caused by: io.realm.exceptions.RealmException: 'class com.models.db.FavouriteIdsModel' is not part of the schema for this Realm.

at io.realm.internal.RealmProxyMediator.getMissingProxyClassException(RealmProxyMediator.java:234)
          at io.realm.DefaultRealmModuleMediator.getSimpleClassNameImpl(DefaultRealmModuleMediator.java:82)
          at io.realm.internal.RealmProxyMediator.getSimpleClassName(RealmProxyMediator.java:72)
          at io.realm.RealmSchema.getTable(RealmSchema.java:177)
          at io.realm.Realm.delete(Realm.java:1689)
          at com.jiostb.jiogames.databaserealm.FavouriteMethod$4.execute(FavouriteMethod.java:79)
          at io.realm.Realm$1.run(Realm.java:1601)
          at io.realm.internal.async.BgPriorityRunnable.run(BgPriorityRunnable.java:34)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
          at java.lang.Thread.run(Thread.java:764)

and when i see db files, i am getting strange things

sdk.db data is store in app.db and sdk.db also has the same data

答:
There's a chance that the SDK is overriding the default configuration, instead of using its own internal RealmConfiguration.

Also, if a library module wants to expose its schema for another module, you must use @RealmModule annotation with library = true, and specify that on the configuration.

Body:
I have created an SDK which uses Realm db to store data. see code below how i have initialized my sdk db

  Realm.init(application);
  config = new RealmConfiguration.Builder().name("sdk.db")
            .schemaVersion(1)
            .deleteRealmIfMigrationNeeded()
            .build();
  Realm.setDefaultConfiguration(config);

Similarly for App in the application class.

First app db is created and initialized and the sdk method is called,which internally creates and initializes sdk.db.

But when i run the app i get following error

io.realm.exceptions.RealmException: Async transaction failed

Caused by: io.realm.exceptions.RealmException: 'class com.models.db.FavouriteIdsModel' is not part of the schema for this Realm.

at io.realm.internal.RealmProxyMediator.getMissingProxyClassException(RealmProxyMediator.java:234)
          at io.realm.DefaultRealmModuleMediator.getSimpleClassNameImpl(DefaultRealmModuleMediator.java:82)
          at io.realm.internal.RealmProxyMediator.getSimpleClassName(RealmProxyMediator.java:72)
          at io.realm.RealmSchema.getTable(RealmSchema.java:177)
          at io.realm.Realm.delete(Realm.java:1689)
          at com.jiostb.jiogames.databaserealm.FavouriteMethod$4.execute(FavouriteMethod.java:79)
          at io.realm.Realm$1.run(Realm.java:1601)
          at io.realm.internal.async.BgPriorityRunnable.run(BgPriorityRunnable.java:34)
          at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
          at java.util.concurrent.FutureTask.run(FutureTask.java:266)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
          at java.lang.Thread.run(Thread.java:764)

and when i see db files, i am getting strange things

sdk.db data is store in app.db and sdk.db also has the same data


问:
URI has disallowed characters in... IE
I have this new problem with IE, it keeps getting this URI disallowed characters error in Internet explorer.

The calls are made through AJAX and it works fine in the LOCALHOST, but on the server, it doesn't work at all.

Examples of the url called (sorry, had to xxxx some parts for disclosure issues)

```<code>http://sandbox.xxxxxxxxx.pt/beta1/gestao/xxxxxxx_ctr/?%23&_=1302607702688 (this one doesn't work in IE)

http://localhost/xxxxxxxxx/gestao/xxxxxxx_ctr/?%23&_=1302608090193 (this one does)
</code>```

These permitted uri chars work like a charm for the "good" browsers.

```<code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\+\-';
</code>```

Does anyone happens to know the solution to this problem and would be kind enough to help me?

Thank you.

答:
Solved it.

the ?# was being added because the "cache" option was set to false in the jQuery ajax request, so the IE caching didn't kicked in.

Simply removed the cache preventing option in the AJAX request and added a "random" number to be sent via post, to prevent IE cache.

At least for now it's working fine.

Thank you guys for the time spent trying to help me.

Title: URI has disallowed characters in... IE

Body:
I have this new problem with IE, it keeps getting this URI disallowed characters error in Internet explorer.

The calls are made through AJAX and it works fine in the LOCALHOST, but on the server, it doesn't work at all.

Examples of the url called (sorry, had to xxxx some parts for disclosure issues)

http://sandbox.xxxxxxxxx.pt/beta1/gestao/xxxxxxx_ctr/?%23&_=1302607702688 (this one doesn't work in IE)

http://localhost/xxxxxxxxx/gestao/xxxxxxx_ctr/?%23&_=1302608090193 (this one does)

These permitted uri chars work like a charm for the "good" browsers.

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\+\-';

Does anyone happens to know the solution to this problem and would be kind enough to help me?

Thank you.


问:
Perl : Get offset between gmtime and localtime when input time in seconds since epoch which considers daylight savings time
I want to get the offset in hours between localtime and gmtime given microseconds since epoch. What I have so far is something like this

```<code># Microseconds since Epoch
my $msec = 555329743301750;

# Convert to seconds
my $sec = $msec/1000000;

my $val = (POSIX::mktime(localtime $sec) - POSIX::mktime(gmtime $sec)) / 60 / 60;

print "$val\n";
</code>```

1) The output I get is -6.(CST localtime) However I am expecting -5. The behavior I am expecting is something similar to the result from running bash command

```<code>`date -d 20190514 "+%z"`;
</code>```

2) Long story short, how do I compute offset similar to the date -d 20190514 "+%z" in perl?

答:
Using the core Time::Piece:

```<code>use strict;
use warnings;
use Time::Piece;

# Microseconds since Epoch
my $usec = 555329743301750;

# Convert to seconds
my $sec = $usec/1000000;

my $offset = localtime($sec)->tzoffset / 3600;
</code>```

Time::Moment and DateTime can also return this value, if you construct them as I showed on your other question.

```<code>my $offset = $time_moment->offset / 60;

my $offset = $datetime->offset / 3600;
</code>```

You can also create these objects from dates, but it will of course give you the offset at midnight (local time) on that day.

```<code>use Time::Piece;
my $time = localtime->strptime('20190514', '%Y%m%d');

use Time::Moment;
use Role::Tiny ();
my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
my $time = $class->new(year => 2019, month => 5, day => 14)->with_system_offset_same_local;

use DateTime;
my $time = DateTime->new(year => 2019, month => 5, day => 14, time_zone => 'local');
</code>```

Body:
I want to get the offset in hours between localtime and gmtime given microseconds since epoch. What I have so far is something like this

# Microseconds since Epoch
my $msec = 555329743301750;

# Convert to seconds
my $sec = $msec/1000000;

my $val = (POSIX::mktime(localtime $sec) - POSIX::mktime(gmtime $sec)) / 60 / 60;

print "$val\n";

1) The output I get is -6.(CST localtime) However I am expecting -5. The behavior I am expecting is something similar to the result from running bash command

`date -d 20190514 "+%z"`;

2) Long story short, how do I compute offset similar to the date -d 20190514 "+%z" in perl?

Body:
Using the core Time::Piece:

use strict;
use warnings;
use Time::Piece;

# Microseconds since Epoch
my $usec = 555329743301750;

# Convert to seconds
my $sec = $usec/1000000;

my $offset = localtime($sec)->tzoffset / 3600;

Time::Moment and DateTime can also return this value, if you construct them as I showed on your other question.

my $offset = $time_moment->offset / 60;

my $offset = $datetime->offset / 3600;

You can also create these objects from dates, but it will of course give you the offset at midnight (local time) on that day.

use Time::Piece;
my $time = localtime->strptime('20190514', '%Y%m%d');

use Time::Moment;
use Role::Tiny ();
my $class = Role::Tiny->create_class_with_roles('Time::Moment', 'Time::Moment::Role::TimeZone');
my $time = $class->new(year => 2019, month => 5, day => 14)->with_system_offset_same_local;

use DateTime;
my $time = DateTime->new(year => 2019, month => 5, day => 14, time_zone => 'local');


问:
"pip install selenium" not working // using python 3 // windows 10
I cannot install selenium. I have python 3.7 and window 10.

These are some of the things i have tried and the outcome:

C:\Users\dani>pip install selenium
'pip' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>sudo pip install selenium
'sudo' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>pip3 install selenium
'pip3' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>conda install selenium
'conda' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\dani>pip install -U selenium
'pip' is not recognized as an internal or external command,
operable program or batch file.

答: Probably when you were installing your python you didn't click the checkbox for python PATH. Delete python and install it again and click the checkbox.</p>


问:
Comparing a wrapped function whether it is instance of a decorator
I have decorator1 and decorator2 functions. And I am using these to decorate a function.

```<code>@decorator1("some", "args")
@decorator2(1,2)
@decorator1()
def my_func(): print("my func")
</code>```

When I call wrapped functions iteratively over and over again, output becomes like this:

for my_func.__wrapped__:

```<code>decorator1
decorator2
decorator1
my func
</code>```

for my_func.__wrapped__.__wrapped__():

```<code>decorator2
decorator1
my func
</code>```

Problem is every wrapped function's name is my_func. I want to check if a function in this chain is instance of lets say decorator1. I want to know this because I will use arguments of decorators. (I already know them by using __closure__ cells.)

Clarification

I decided to give and example to show my purpose.

```<code>@route("/index")
def index(): pass

@route("/settings")
@need_permission("admin")
def settings: pass

@route("/blog")
@need_permission("admin", "user")
def blog(): pass
</code>```

I can get all these route functions somewhere else, and I want to extract which one needs which permissions.

Here my findings:

```<code>>>> blog()
route blog
permissions admin user
>>> blog.__closure__[0].cell_contents
('/blog',)
>>> blog.__closure__[1].cell_contents()
permissions admin user
>>> blog.__closure__[0].cell_contents.__closure__[0].cell_contents
('admin', 'user')
>>> blog.__closure__[0].cell_contents.__closure__[1].cell_contents()
>>>
</code>```

I just want to extract the tuples that hold permissions. I can apply my decorators in some specific order and extract easily or I need to implement my DecoratorApplier function as @Poolka pointed out. If there is no way of knowing like first option, i will follow second.

答:
instance of a decorator - decorators implemented with functions and regular functions are all just functions of type function.

Not sure what exactly you wanna get. The code below is how I would approach the problem. Basically I add attribute primal_type to all the functions involved into decoration carnival to store the name of the functions/decorators. I do this with another decorator named DecoratorApplier. The code seems to perform something related to the issue in the question.

EDIT

Added clarification didn't make everything clear. I guess it's not good practrice to mix function and decorator logics in that way. Maybe there is another option to get desired info inside the function? Anyway two modified versions of my original approach below (oda stands for optional decorator arguments).

(1) - with DecoratorApplier

```<code>import functools

def decorator_1(*d1_args, **d1_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_1', d1_args, d1_kwargs)
            return func(*args, **kwargs)
        return wrapped
    return decorator

def decorator_2(*d2_args, **d2_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_2', d2_args, d2_kwargs)
            return func(*args, **kwargs)
        return wrapped
    return decorator

class DecoratorApplier:

    def __init__(self, *decorators):
        self.decorators = decorators

    def __call__(self, func):
        func.oda = dict()
        for decorator in self.decorators:
            func = decorator[0](*decorator[1], **decorator[2])(func)
            (
                func
                .oda
                .setdefault(decorator[0].__name__, list())
                .extend([decorator[1], decorator[2]])
            )
        return func

@DecoratorApplier(
    (decorator_1, (1, 2), {'x': 10, 'y': 20}),
    (decorator_2, tuple(), dict()))
def f_1():
    print('inside f_1')
    print(f_1.oda)
    return

if __name__ == '__main__':

    f_1()
</code>```

(2) - with modifying original decorators

```<code>import functools

def decorator_1(*d1_args, **d1_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_1', d1_args, d1_kwargs)
            (
                kwargs
                .setdefault('oda', dict())
                .setdefault('decorator_1', list())
                .extend([d1_args, d1_kwargs])
            )
            return func(*args, **kwargs)
        return wrapped
    return decorator

def decorator_2(*d2_args, **d2_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_2', d2_args, d2_kwargs)
            (
                kwargs
                .setdefault('oda', dict())
                .setdefault('decorator_2', list())
                .extend([d2_args, d2_kwargs])
            )
            return func(*args, **kwargs)
        return wrapped
    return decorator

@decorator_1(1, 2, x=10, y=20)
@decorator_2()
def f_1(oda=None):
    print('inside f_1')
    print('    oda', oda)
    return

if __name__ == '__main__':

    f_1()
</code>```

Body:
I have decorator1 and decorator2 functions. And I am using these to decorate a function.

@decorator1("some", "args")
@decorator2(1,2)
@decorator1()
def my_func(): print("my func")

When I call wrapped functions iteratively over and over again, output becomes like this:

for my_func.__wrapped__:

decorator1
decorator2
decorator1
my func

for my_func.__wrapped__.__wrapped__():

decorator2
decorator1
my func

Problem is every wrapped function's name is my_func. I want to check if a function in this chain is instance of lets say decorator1. I want to know this because I will use arguments of decorators. (I already know them by using __closure__ cells.)

Clarification

I decided to give and example to show my purpose.

@route("/index")
def index(): pass

@route("/settings")
@need_permission("admin")
def settings: pass

@route("/blog")
@need_permission("admin", "user")
def blog(): pass

I can get all these route functions somewhere else, and I want to extract which one needs which permissions.

Here my findings:

>>> blog()
route blog
permissions admin user
>>> blog.__closure__[0].cell_contents
('/blog',)
>>> blog.__closure__[1].cell_contents()
permissions admin user
>>> blog.__closure__[0].cell_contents.__closure__[0].cell_contents
('admin', 'user')
>>> blog.__closure__[0].cell_contents.__closure__[1].cell_contents()
>>>

I just want to extract the tuples that hold permissions. I can apply my decorators in some specific order and extract easily or I need to implement my DecoratorApplier function as @Poolka pointed out. If there is no way of knowing like first option, i will follow second.

Body:
instance of a decorator - decorators implemented with functions and regular functions are all just functions of type function.

Not sure what exactly you wanna get. The code below is how I would approach the problem. Basically I add attribute primal_type to all the functions involved into decoration carnival to store the name of the functions/decorators. I do this with another decorator named DecoratorApplier. The code seems to perform something related to the issue in the question.

EDIT

Added clarification didn't make everything clear. I guess it's not good practrice to mix function and decorator logics in that way. Maybe there is another option to get desired info inside the function? Anyway two modified versions of my original approach below (oda stands for optional decorator arguments).

(1) - with DecoratorApplier

import functools

def decorator_1(*d1_args, **d1_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_1', d1_args, d1_kwargs)
            return func(*args, **kwargs)
        return wrapped
    return decorator

def decorator_2(*d2_args, **d2_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_2', d2_args, d2_kwargs)
            return func(*args, **kwargs)
        return wrapped
    return decorator

class DecoratorApplier:

    def __init__(self, *decorators):
        self.decorators = decorators

    def __call__(self, func):
        func.oda = dict()
        for decorator in self.decorators:
            func = decorator[0](*decorator[1], **decorator[2])(func)
            (
                func
                .oda
                .setdefault(decorator[0].__name__, list())
                .extend([decorator[1], decorator[2]])
            )
        return func

@DecoratorApplier(
    (decorator_1, (1, 2), {'x': 10, 'y': 20}),
    (decorator_2, tuple(), dict()))
def f_1():
    print('inside f_1')
    print(f_1.oda)
    return

if __name__ == '__main__':

    f_1()

(2) - with modifying original decorators

import functools

def decorator_1(*d1_args, **d1_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_1', d1_args, d1_kwargs)
            (
                kwargs
                .setdefault('oda', dict())
                .setdefault('decorator_1', list())
                .extend([d1_args, d1_kwargs])
            )
            return func(*args, **kwargs)
        return wrapped
    return decorator

def decorator_2(*d2_args, **d2_kwargs):
    def decorator(func):
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            print('inside decorator_2', d2_args, d2_kwargs)
            (
                kwargs
                .setdefault('oda', dict())
                .setdefault('decorator_2', list())
                .extend([d2_args, d2_kwargs])
            )
            return func(*args, **kwargs)
        return wrapped
    return decorator

@decorator_1(1, 2, x=10, y=20)
@decorator_2()
def f_1(oda=None):
    print('inside f_1')
    print('    oda', oda)
    return

if __name__ == '__main__':

    f_1()


答:
Apparently the Scala code that encodes the value uses a different byte order than the Python code that decodes it.

Make sure you use the same byte order (endianness) in both programs.

In Python, you can change the byte order used to decode the value by using >f or <f instead of f. See https://docs.python.org/3/library/struct.html#struct-alignment.

```<code>>>> b = b'\xc2\xdatZ'
>>> struct.unpack('f', b)   # native byte order (little-endian on my machine)
(1.7230105268977664e+16,)
>>> struct.unpack('>f', b)  # big-endian
(-109.22724914550781,)
</code>```

Title: How to convert a byte array to float in Python

Body:
I have a byte array, which originally was converted from a float array in Scala. I need to convert it back to a float array in Python.

This is the code I used to convert the float array in Scala:

val float_ary_len = float_ary.size
val bb = java.nio.ByteBuffer.allocate(float_ary_len * 4)
for(each_float <- float_ary){
    bb.putFloat(each_folat)
}
val bytes_ary = bb.array()

Then in Python, I can get this byte array and I need to convert it back to a float array.

I have tried the following code in Python, but it didn't give me the right float.

print(list(bytes_ary[0:4]))
#['\xc2', '\xda', 't', 'Z']

struct.unpack('f', bytes_ary[0:4])
# it gave me 1.7230105268977664e+16, but it should be -109.22725

Please let me know how should I get the right float?

Body:
Apparently the Scala code that encodes the value uses a different byte order than the Python code that decodes it.

Make sure you use the same byte order (endianness) in both programs.

In Python, you can change the byte order used to decode the value by using >f or <f instead of f. See https://docs.python.org/3/library/struct.html#struct-alignment.

>>> b = b'\xc2\xdatZ'
>>> struct.unpack('f', b)   # native byte order (little-endian on my machine)
(1.7230105268977664e+16,)
>>> struct.unpack('>f', b)  # big-endian
(-109.22724914550781,)


问:
Duplicates in javascript fix
In an arrangement I am adding the id that is currently in the for cycle, going through a query, but I do not want duplicate values to be added, as I can know that an id has already been added to the array in order to put a conditional and not add it, or what is the best way to do it

let values = []
values.push({
    "id": id
});```

答:
Even though this question is very off topic, I will still give you an answer:

All you have to do before adding the ID to the array is to check if the array includes it, like this:

```<code>let ids = ["123", "321", "123"];
let values = [];
for (id : ids) {
    if (values.includes(id) == false) {
        values.push(id);
    }
}
// values will be ["123", "321"]
</code>```

Your question is off topic because this is something which can easily be solved by a quick google search, and is not really a coding problem that you need help with.

Title: Duplicates in javascript fix

Body:
Even though this question is very off topic, I will still give you an answer:

All you have to do before adding the ID to the array is to check if the array includes it, like this:

let ids = ["123", "321", "123"];
let values = [];
for (id : ids) {
    if (values.includes(id) == false) {
        values.push(id);
    }
}
// values will be ["123", "321"]

Your question is off topic because this is something which can easily be solved by a quick google search, and is not really a coding problem that you need help with.


问:
Git force commit and push , when getting "nothing to commit"
I need to force commit and push file , as each commit trigger some external event in the application , this is when the file i committing is same as in the remote
now i do :

```<code>git automation commit -am "testing"
</code>```

and it gives me :

```<code>On branch develop
Your branch is up-to-date with 'origin/develop'.
nothing to commit, working tree clean
</code>```

it cancel the commit ...

how i force the commit and push ?
so it will update the file in the remote

答:
To add an empty commit... git commit --allow-empty -m "testing". Then push normally.

Side note, you may way to look into other means to trigger an event. This will clutter your history.

Body:
I need to force commit and push file , as each commit trigger some external event in the application , this is when the file i committing is same as in the remote
now i do :

git automation commit -am "testing"

and it gives me :

On branch develop
Your branch is up-to-date with 'origin/develop'.
nothing to commit, working tree clean

it cancel the commit ...

how i force the commit and push ?
so it will update the file in the remote


问:
CheckWeb Global.asax.cs 'TemplatePagesFeature' does not contain a definition for 'TemplatesAdminRole'
```<code>Plugins.Add(new TemplatePagesFeature
            {
                MetadataDebugAdminRole = RoleNames.AllowAnyUser,
                TemplatesAdminRole = RoleNames.AllowAnon,
            });
</code>```

Error   CS0117  'TemplatePagesFeature' does not contain a definition for 'TemplatesAdminRole'   CheckWeb    ..\ServiceStack-master\tests\CheckWeb\Global.asax.cs

答:
CheckWeb is a test project in ServiceStack's GitHub Repo which is where I'm assuming where you've got this error. If you've upgraded the dependencies on that project, TemplatePagesFeature has since been renamed to SharpPagesFeature in the latest v5.5 of ServiceStack which is now:

```<code>Plugins.Add(new SharpPagesFeature
{
    MetadataDebugAdminRole = RoleNames.AllowAnyUser,
    ScriptAdminRole = RoleNames.AllowAnon,
});
</code>```

Or you can download the latest master of ServiceStack which has these changes.

Body:
Plugins.Add(new TemplatePagesFeature
            {
                MetadataDebugAdminRole = RoleNames.AllowAnyUser,
                TemplatesAdminRole = RoleNames.AllowAnon,
            });

Error   CS0117  'TemplatePagesFeature' does not contain a definition for 'TemplatesAdminRole'   CheckWeb    ..\ServiceStack-master\tests\CheckWeb\Global.asax.cs

Body:
CheckWeb is a test project in ServiceStack's GitHub Repo which is where I'm assuming where you've got this error. If you've upgraded the dependencies on that project, TemplatePagesFeature has since been renamed to SharpPagesFeature in the latest v5.5 of ServiceStack which is now:

Plugins.Add(new SharpPagesFeature
{
    MetadataDebugAdminRole = RoleNames.AllowAnyUser,
    ScriptAdminRole = RoleNames.AllowAnon,
});

Or you can download the latest master of ServiceStack which has these changes.