问:
Stoplimit order when orderPrice crosses above/below Close of the bar in quantstrat?
I am trying put a stoplimit order to close my position when a specific order price crosses above or below the Close of the candle.

My rule function as follows:

```<code>add.rule(strategy = strategy.st, name = "ruleSignal",arguments =
list(sigcol = "lenter", sigval = TRUE,TxnFees="fee",replace = FALSE,
orderside = "long", TxnFees = "fee", ordertype = "stoplimit",
orderqty = "all", tmult = TRUE, order.price=quote(myprice),
orderset="ocolong", prefer="Close"), type = "chain", parent =
"longbuy", path.dep=TRUE, label = "stop_loss_long", enabled=TRUE)
</code>```

I tried to change the related part in source file of ruleOrderProc.R:

```<code>if ((orderQty > 0 && orderType != "stoplimit") ||
            (orderQty < 0 && (orderType == "stoplimit"))) {
            if ((has.Lo(mktdata) && orderPrice >
as.numeric(Lo(mktdataTimestamp)[,
              1]))
</code>```

to

```<code> if ((orderQty > 0 && orderType != "stoplimit") ||
            (orderQty < 0 && (orderType == "stoplimit"))) {
            if ((has.Cl(mktdata) && orderPrice >
as.numeric(Cl(mktdataTimestamp)[,
              1]))
</code>```

And I also tried to add "prefer" argument to my rule but it didn't work. Rule still triggers according to Low/High prices of the bar.

Thank you.

Edit for a minimum reproducible example:

```<code>library(quantstrat)

start_date <- as.Date("2018-02-02")
end_date <- as.Date("2018-09-24")
init_date <- as.Date("2018-01-01")
init_equity <- "50000"
adjustment <- TRUE
symbol <- "AAPL"

getSymbols(symbol, src = "yahoo",
       from = start_date, to=end_date,
       adjust = adjustment)

portfolio.st <- "basic_port"
account.st <- "basic_account"
strategy.st <- "basic_strategy"

rm.strat(portfolio.st)
rm.strat(account.st)

stock(symbol, currency = currency("USD"), multiplier = 1)
initPortf(name = portfolio.st, symbols = symbol, initDate =init_date)

initAcct(name = account.st, portfolios = portfolio.st,
         initDate = init_date, initEq =init_equity)
initOrders(portfolio.st, symbol, init_date)
strategy(strategy.st, store = TRUE)

add.indicator(strategy = strategy.st, name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), n=10),
              label ="nFast")

add.indicator(strategy = strategy.st, name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), n=30),
              label = "nSlow")

add.signal(strategy = strategy.st,
           name= "sigCrossover",
           arguments =  list(columns = c("nFast", "nSlow"),
                             relationship = "gte"),
           label = "longenter")

add.signal(strategy = strategy.st,
           name= "sigCrossover",
           arguments =  list(columns = c("nFast",
                                         "nSlow"),
                             relationship = "lt"),
           label = "longexit")

#Add rules for entering positions
#enter long position
add.rule(strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "longenter",
                          sigval = TRUE,
                          orderqty = 100,
                          ordertype = "market",
                          orderside = "long",
                          orderset= "ocolong",
                          prefer = "Close",
                          TxnFees = -.8,
                          replace = FALSE),
         type = "enter",
         label = "EnterLong")

#stoploss long
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "longenter",
                          sigval = TRUE,
                          TxnFees=-.8,
                          replace = FALSE,
                          orderside = "long",
                          ordertype = "stoplimit",
                          orderqty = "all",
                          tmult = TRUE,
                          prefer = "Close",
         order.price=quote(as.numeric(mktdata$AAPL.Low[timestamp])),
                          orderset="ocolong"),
         type = "chain", parent = "EnterLong",
         path.dep=TRUE,
         label = "stop_loss_long",
         enabled=TRUE)

#Apply strategy
applyStrategy(strategy.st, portfolios = portfolio.st,debug = TRUE)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)
</code>```

When we look at the last transaction closed by stop-loss rule, "Close" price of the bar is not below my stop-loss order price which is 47.13 although I add prefer="Close" argument to my stoplimit rule:

```<code>mktdata[, 1:4]["2018-07-30"]

           AAPL.Open AAPL.High AAPL.Low AAPL.Close
2018-07-30  47.80733  47.88207 47.10231   47.31158
</code>```

Normally, I expect that the position should not be closed until the end of the dataset.

```<code>sessionInfo()

R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
system code page: 1254

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods
[7] base

other attached packages:
[1] quantstrat_0.16.9          foreach_1.5.1
[3] blotter_0.15.0             PerformanceAnalytics_2.0.6
[5] FinancialInstrument_1.3.0  quantmod_0.4.18
[7] TTR_0.24.2                 xts_0.12.1.1
[9] zoo_1.8-9

loaded via a namespace (and not attached):
 [1] magrittr_2.0.1    MASS_7.3-54       tidyselect_1.1.1
 [4] lattice_0.20-44   R6_2.5.1          quadprog_1.5-8
 [7] rlang_0.4.11      fansi_0.5.0       dplyr_1.0.7
[10] tools_4.1.1       grid_4.1.1        data.table_1.14.0
[13] utf8_1.2.2        DBI_1.1.1         iterators_1.0.13
[16] ellipsis_0.3.2    assertthat_0.2.1  tibble_3.1.4
[19] lifecycle_1.0.0   crayon_1.4.1      purrr_0.3.4
[22] codetools_0.2-18  vctrs_0.3.8       curl_4.3.2
[25] glue_1.4.2        compiler_4.1.1    pillar_1.6.2
[28] generics_0.1.0    boot_1.3-28       pkgconfig_2.0.3
</code>```

答:
You need to make one more modification in rules.R (on approximately lines 580-590), setting posQty and negQty to the close prices for the stoplimit order type (instead of High and Low prices):

```<code>  if(is.BBO(mktdata)) {
        mktPrices <- list(
          stoplimit = list(
              posQty = mktdata[,has.Ask(mktdata,which=TRUE)[1]],
              negQty = mktdata[,has.Bid(mktdata,which=TRUE)[1]]),
          limit = list(
              posQty = mktdata[,has.Ask(mktdata,which=TRUE)[1]],
              negQty = mktdata[,has.Bid(mktdata,which=TRUE)[1]]),
          stoptrailing = list(
              posQty = getPrice(mktdata, prefer='offer')[,1],
              negQty = getPrice(mktdata, prefer='bid')[,1]))
    } else if (is.OHLC(mktdata)) {
        mktPrices <- list(
          stoplimit = list(
              posQty = mktdata[,has.Cl(mktdata,which=TRUE)[1]], #modified to the close
              negQty = mktdata[,has.Cl(mktdata,which=TRUE)[1]]), #modified to the close
</code>```

This section of the rules.R code is about speeding up the simulation by only checking rows of the market data where there might be an update to an open order. So what you are doing by making this change is effectively saying, find all the rows where the Close price (as opposed to the Low price) for a long stop limit order might cross (below) the stop order price.

With this change the stop order is not triggered on 2018-07-30.

Note that if you go through the code carefully in rules.R you'll see prefer="Close" does not matter in finding the market data rows where the stoplimit might be triggered. prefer can come into play when you're not working with OHLC bar data.

Body:
I am trying put a stoplimit order to close my position when a specific order price crosses above or below the Close of the candle.

My rule function as follows:

add.rule(strategy = strategy.st, name = "ruleSignal",arguments =
list(sigcol = "lenter", sigval = TRUE,TxnFees="fee",replace = FALSE,
orderside = "long", TxnFees = "fee", ordertype = "stoplimit",
orderqty = "all", tmult = TRUE, order.price=quote(myprice),
orderset="ocolong", prefer="Close"), type = "chain", parent =
"longbuy", path.dep=TRUE, label = "stop_loss_long", enabled=TRUE)

I tried to change the related part in source file of ruleOrderProc.R:

if ((orderQty > 0 && orderType != "stoplimit") ||
            (orderQty < 0 && (orderType == "stoplimit"))) {
            if ((has.Lo(mktdata) && orderPrice >
as.numeric(Lo(mktdataTimestamp)[,
              1]))

to

 if ((orderQty > 0 && orderType != "stoplimit") ||
            (orderQty < 0 && (orderType == "stoplimit"))) {
            if ((has.Cl(mktdata) && orderPrice >
as.numeric(Cl(mktdataTimestamp)[,
              1]))

And I also tried to add "prefer" argument to my rule but it didn't work. Rule still triggers according to Low/High prices of the bar.

Thank you.

Edit for a minimum reproducible example:

library(quantstrat)

start_date <- as.Date("2018-02-02")
end_date <- as.Date("2018-09-24")
init_date <- as.Date("2018-01-01")
init_equity <- "50000"
adjustment <- TRUE
symbol <- "AAPL"

getSymbols(symbol, src = "yahoo",
       from = start_date, to=end_date,
       adjust = adjustment)

portfolio.st <- "basic_port"
account.st <- "basic_account"
strategy.st <- "basic_strategy"

rm.strat(portfolio.st)
rm.strat(account.st)

stock(symbol, currency = currency("USD"), multiplier = 1)
initPortf(name = portfolio.st, symbols = symbol, initDate =init_date)

initAcct(name = account.st, portfolios = portfolio.st,
         initDate = init_date, initEq =init_equity)
initOrders(portfolio.st, symbol, init_date)
strategy(strategy.st, store = TRUE)

add.indicator(strategy = strategy.st, name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), n=10),
              label ="nFast")

add.indicator(strategy = strategy.st, name = "SMA",
              arguments = list(x = quote(Cl(mktdata)), n=30),
              label = "nSlow")

add.signal(strategy = strategy.st,
           name= "sigCrossover",
           arguments =  list(columns = c("nFast", "nSlow"),
                             relationship = "gte"),
           label = "longenter")

add.signal(strategy = strategy.st,
           name= "sigCrossover",
           arguments =  list(columns = c("nFast",
                                         "nSlow"),
                             relationship = "lt"),
           label = "longexit")

#Add rules for entering positions
#enter long position
add.rule(strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "longenter",
                          sigval = TRUE,
                          orderqty = 100,
                          ordertype = "market",
                          orderside = "long",
                          orderset= "ocolong",
                          prefer = "Close",
                          TxnFees = -.8,
                          replace = FALSE),
         type = "enter",
         label = "EnterLong")

#stoploss long
add.rule(strategy = strategy.st,
         name = "ruleSignal",
         arguments = list(sigcol = "longenter",
                          sigval = TRUE,
                          TxnFees=-.8,
                          replace = FALSE,
                          orderside = "long",
                          ordertype = "stoplimit",
                          orderqty = "all",
                          tmult = TRUE,
                          prefer = "Close",
         order.price=quote(as.numeric(mktdata$AAPL.Low[timestamp])),
                          orderset="ocolong"),
         type = "chain", parent = "EnterLong",
         path.dep=TRUE,
         label = "stop_loss_long",
         enabled=TRUE)

#Apply strategy
applyStrategy(strategy.st, portfolios = portfolio.st,debug = TRUE)
updatePortf(portfolio.st)
updateAcct(account.st)
updateEndEq(account.st)

When we look at the last transaction closed by stop-loss rule, "Close" price of the bar is not below my stop-loss order price which is 47.13 although I add prefer="Close" argument to my stoplimit rule:

mktdata[, 1:4]["2018-07-30"]

           AAPL.Open AAPL.High AAPL.Low AAPL.Close
2018-07-30  47.80733  47.88207 47.10231   47.31158

Normally, I expect that the position should not be closed until the end of the dataset.

sessionInfo()

R version 4.1.1 (2021-08-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United States.1252
system code page: 1254

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods
[7] base

other attached packages:
[1] quantstrat_0.16.9          foreach_1.5.1
[3] blotter_0.15.0             PerformanceAnalytics_2.0.6
[5] FinancialInstrument_1.3.0  quantmod_0.4.18
[7] TTR_0.24.2                 xts_0.12.1.1
[9] zoo_1.8-9

loaded via a namespace (and not attached):
 [1] magrittr_2.0.1    MASS_7.3-54       tidyselect_1.1.1
 [4] lattice_0.20-44   R6_2.5.1          quadprog_1.5-8
 [7] rlang_0.4.11      fansi_0.5.0       dplyr_1.0.7
[10] tools_4.1.1       grid_4.1.1        data.table_1.14.0
[13] utf8_1.2.2        DBI_1.1.1         iterators_1.0.13
[16] ellipsis_0.3.2    assertthat_0.2.1  tibble_3.1.4
[19] lifecycle_1.0.0   crayon_1.4.1      purrr_0.3.4
[22] codetools_0.2-18  vctrs_0.3.8       curl_4.3.2
[25] glue_1.4.2        compiler_4.1.1    pillar_1.6.2
[28] generics_0.1.0    boot_1.3-28       pkgconfig_2.0.3

Body:
You need to make one more modification in rules.R (on approximately lines 580-590), setting posQty and negQty to the close prices for the stoplimit order type (instead of High and Low prices):

  if(is.BBO(mktdata)) {
        mktPrices <- list(
          stoplimit = list(
              posQty = mktdata[,has.Ask(mktdata,which=TRUE)[1]],
              negQty = mktdata[,has.Bid(mktdata,which=TRUE)[1]]),
          limit = list(
              posQty = mktdata[,has.Ask(mktdata,which=TRUE)[1]],
              negQty = mktdata[,has.Bid(mktdata,which=TRUE)[1]]),
          stoptrailing = list(
              posQty = getPrice(mktdata, prefer='offer')[,1],
              negQty = getPrice(mktdata, prefer='bid')[,1]))
    } else if (is.OHLC(mktdata)) {
        mktPrices <- list(
          stoplimit = list(
              posQty = mktdata[,has.Cl(mktdata,which=TRUE)[1]], #modified to the close
              negQty = mktdata[,has.Cl(mktdata,which=TRUE)[1]]), #modified to the close

This section of the rules.R code is about speeding up the simulation by only checking rows of the market data where there might be an update to an open order. So what you are doing by making this change is effectively saying, find all the rows where the Close price (as opposed to the Low price) for a long stop limit order might cross (below) the stop order price.

With this change the stop order is not triggered on 2018-07-30.

Note that if you go through the code carefully in rules.R you'll see prefer="Close" does not matter in finding the market data rows where the stoplimit might be triggered. prefer can come into play when you're not working with OHLC bar data.


来源: stackexchange

问:
Using cURL to save external files to my Server
I have a website to show opensource movies and videos.

I have saved urls in mysql and linked both videos as well as the images to the content server.

But users are complaining of slow website as images are getting fetched from outside and most of time Internet Explorer is not even displaying the image.

I just learnt about cURL and would like to save images as well as videos to my own server and provide mirror to original website.

I got " curl -O ('') ; " syntax at many places to do the task but don't know how to use it inside my php script.

In short:
I already have my form for url saving in mysql. I wish it to also save save file to a directory on my webserver and save file path to another column in mysql.

Any sort of help is welcome.
Thanx in Advance

答:
```<code>$local_file = "/tmp/filename.flv";//This is the file where we save the information
$remote_file = "http://www.test.com/filename.flv"; //Here is the file we are downloading

$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);
</code>```

I've decided to update this answer almost 7 years later.

For those who have copy() enabled for remote hosts, you can simply use:

```<code>copy("http://www.test.com/filename.flv", "/some/local/path/filename.flv");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
$local_file = "/tmp/filename.flv";//This is the file where we save the information
$remote_file = "http://www.test.com/filename.flv"; //Here is the file we are downloading

$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);

I've decided to update this answer almost 7 years later.

For those who have copy() enabled for remote hosts, you can simply use:

copy("http://www.test.com/filename.flv", "/some/local/path/filename.flv");


问:
AJAX GET Url Parameter and pass to PHP
My user will be access ../verify.php?code=1228119j8dwq8dj218

and i want the 1228119j8dwq8dj218 passed to /verify_action.php

I've tried something like below but it says code is undefined,

when i tried to place my verify-action.php script in the verify.php and change url:"verify-action.php" to url:"verify.php" it working perfectly but causing my success and error message not showing properly

AJAX

```<code><script>
$(document).ready(function(){
        $.ajax({
                url:"verify-action.php",
                method:"GET",
                data:{code:code},
                success:function(data)
                {
                    if(data.error !== '')
                    {
                        $('#message').html(data.error);
                    }
                    if(data.success != '')
                    {
                        $('#message').html(data.success);
                    }
                }
            })
});
</script>
</code>```

PHP

```<code>$error = '';
$success = '';

if(isset($_GET["code"]))
{
    $object->query = "
    UPDATE user_table
    SET email_verify = 'Yes'
    WHERE user_verification_code = '".$_GET["code"]."'
    ";

    $object->execute();

    $success = '<div class="alert alert-success">Your Email has been Verified</div>';
}else{
    $error = '<div class="alert alert-danger">Verify Error. Please Contact Administrator</div>';
}

$output = array(
            'error'     =>  $error,
            'success'   =>  $success
        );
        echo json_encode($output);
?>
</code>```

答:
```<code>const urlParams = new URLSearchParams(window.location.search);
var code = urlParams.get('code');
</code>```

Simple solution is just to get the URL parameter using that script
Thanks to @broomber

ContentLicense: CC BY-SA 4.0

Title: AJAX GET Url Parameter and pass to PHP

Body:
My user will be access ../verify.php?code=1228119j8dwq8dj218

and i want the 1228119j8dwq8dj218 passed to /verify_action.php

I've tried something like below but it says code is undefined,

when i tried to place my verify-action.php script in the verify.php and change url:"verify-action.php" to url:"verify.php" it working perfectly but causing my success and error message not showing properly

AJAX

PHP

$error = '';
$success = '';

if(isset($_GET["code"]))
{
    $object->query = "
    UPDATE user_table
    SET email_verify = 'Yes'
    WHERE user_verification_code = '".$_GET["code"]."'
    ";

    $object->execute();

    $success = '
Your Email has been Verified
';
}else{
    $error = '
Verify Error. Please Contact Administrator
';
}

$output = array(
            'error'     =>  $error,
            'success'   =>  $success
        );
        echo json_encode($output);
?>

Body:
const urlParams = new URLSearchParams(window.location.search);
var code = urlParams.get('code');

Simple solution is just to get the URL parameter using that script
Thanks to @broomber


问:
CreateAt (TImestamp with time zone) issue on retrieve postgressql db using sequelize
In my database, the column CreatedAt (timestamp with timezone) has been saved as 2022-02-04 19:12:01.021+05:30.

But when retrieving using a sequelize query, I get 2022-02-04T13:42:01.021Z which is wrong. how to covert it to '2022-02-04 19:12'

Any solution  will be appreciated.

My config:

```<code>development: {
    username: DB_DEV_USERNAME,
    password: DB_DEV_PASSWORD,
    database: DB_DEV_DATABASE,
    host: DB_DEV_HOST,
    port: DB_DEV_PORT,
    dialect: "postgres",
    MaxConnections: 120,
},
</code>```

答:
Those two times are the same. It's just a difference in formatting. "+05:30" means a 5 and a half hour time zone offset. "Z" means GMT aka UTC time. I suggest you convert on the client side to whatever time zone you want, not rely on the database to do that.

Confusingly, neither timestamp with time zone (aka timestamptz) nor timestamp actually stores a time zone, but that's better really. You should probably use timestamptz; see here.

According to the official Postgres docs: "For timestamp with time zone, the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone." "When a timestamp with time zone value is output, it is always converted from UTC to the current timezone zone, and displayed as local time in that zone. To see the time in another time zone, either change timezone or use the AT TIME ZONE construct (see Section 9.9.3)."

So probably your machine's local timezone is set to UTC.

Body:
In my database, the column CreatedAt (timestamp with timezone) has been saved as 2022-02-04 19:12:01.021+05:30.

But when retrieving using a sequelize query, I get 2022-02-04T13:42:01.021Z which is wrong. how to covert it to '2022-02-04 19:12'

Any solution  will be appreciated.

My config:

development: {
    username: DB_DEV_USERNAME,
    password: DB_DEV_PASSWORD,
    database: DB_DEV_DATABASE,
    host: DB_DEV_HOST,
    port: DB_DEV_PORT,
    dialect: "postgres",
    MaxConnections: 120,
},


问:
I have this where i need to create a class and use setter and getters do do various tasks, i just wanted input on what i was doing wrong
this code is supposed to ask the user for name of an ingredient, the number of cups used in the ingredient, and the unit measurement and calculate the total calories for them it involves alot of validation of user input and i have that part down so far but im just lost at this point. the confusing part is the error i get is that this code doe not have a main method</p>
```<code>package Ingredient;
import java.util.Scanner;
public class V3 {

 //Private Fields: Internal Data

    private String nameOfIngredient;
    private String unitMeasurement;
    private float ingredientAmount;
    private int numberOfCaloriesPerUnit;
    private int numberOfCups;
    private double totalCalories;

//Operations: Public Methods

    //Mutators and Accessors: Set Values at the this. Index and Return the Value

    //Set and Return Name of Ingredient
         public void setNameOfIngredient(String nameOfIngredient) {
            this.nameOfIngredient = nameOfIngredient;
        }
        public String getNameOfIngredient() {
            return nameOfIngredient;
        }

        public void setNumberOfCups(int numberOfcups) {
            this.numberOfCups = numberOfCups;
        }
        public int getNumberOfCups() {
            return numberOfCups;
        }

    //Set and Return Unit Measurement
    public void setUnitMeasurement (String unitMeasurement) {
        this.unitMeasurement = unitMeasurement;
    }

    public String getUnitMeasurement () {
        return unitMeasurement;
    }

    //Set and Return Ingredient Amount
    public void setIngredientAmount(float ingredientAmount) {
        this.ingredientAmount = ingredientAmount;
        }

    public float getIngredientAmount() {
        return ingredientAmount;
        }

    //Set and Return Number of Calories per Unit
    public void setNumberCaloriesPerUnit(int numberCaloriesPerUnit) {
        this.numberOfCaloriesPerUnit = numberCaloriesPerUnit;
        }

    public int getNumberCaloriesPerUnit() {
        return numberOfCaloriesPerUnit;

    }

    //Set and Return Total Calories
    public void setTotalCalories(double totalCalories) {
        this.totalCalories = totalCalories;
        }

    public double getTotalCalories() {
        return totalCalories;
        }

    public void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

    //Use this. pointer to initialize fields (as they share the same name as private/global fields)
        this.nameOfIngredient = "";
        this.numberOfCups = 0;
        this.numberOfCaloriesPerUnit = 0;
        this.totalCalories = 0.0;

    //Prompt user for name of ingredient
        System.out.println("Please Enter Ingredient Name: ");
        if (scnr.hasNextLine())) {
            nameOfIngredient = scnr.nextLine();
        }
        else{
            System.out.println("Please enter a valid name (characters only): ");
        }

    //Prompt user for unit of measurement
        System.out.println("Please Enter Unit of Measurement for this Ingredient. You have the following options: ");
        System.out.println("Cup(s)");
        System.out.println("Tbsp");
        System.out.println("Tsp");
        System.out.println("Gram(s)");

        if (scnr.hasNextLine()) {
            unitMeasurement = scnr.next();

            if ((unitMeasurement == "Cup(s)") || (unitMeasurement == "Tbsp") || (unitMeasurement == "Tsp") || (unitMeasurement == "Gram(s)")) {
                System.out.println("You have selected " + unitMeasurement);
            }

            else {
                System.out.println("Please enter one of the preceding options.");
            }

                else {
            System.out.println("Please enter one of the preceding options.");
            }
                }

    //Prompt user for number of units
        System.out.println("Please enter the number of units of " + nameOfIngredient + " required (between 1 and 100: ");

        if (scnr.hasNextInt()) {
            ingredientAmount = scnr.nextInt();

            if ((ingredientAmount >= 1) && (ingredientAmount <= 100)) {
                System.out.println(ingredientAmount + " is a valid amount!");

                        }else {
            System.out.println(ingredientAmount + " is not a valid amount.");
            System.out.println("Please enter a valid number of units between 1 and 100: ");
                                }
                if ((ingredientAmount >= 1) && (ingredientAmount <= 100)) {
                    System.out.println(numberOfCups + " is a valid amount!");
            }
                else if (ingredientAmount < 1) {
                    System.out.println(ingredientAmount + " is less than 1 unit. Sorry, you are out of attempts.");
            }
                else {
                    System.out.println(ingredientAmount + " is greater than 100 units. Sorry, you are out of attempts.");
            }

        else {
           System.out.println("Error: That is not a number. Try again.");
        }
                }

    //Prompt user for calories per unit
        System.out.println("Please enter the number of calories per unit of " + nameOfIngredient + " (between 1 and 2000): ");

        if (scnr.hasNextInt()) {
            numberOfCaloriesPerUnit = scnr.nextInt();

            if ((numberOfCaloriesPerUnit >= 1) && (numberOfCaloriesPerUnit <= 2000)) {
                System.out.println(numberOfCaloriesPerUnit + " is a valid number of calories!" );

            else {
                System.out.println(numberOfCaloriesPerUnit + " is not a valid number of calories.");
                System.out.println("Please enter a valid number of calories per unit between 1 and 2000: ");

                    if ((numberOfCaloriesPerUnit >= 1) && (numberOfCaloriesPerUnit <= 2000)) {
                        System.out.println(numberOfCaloriesPerUnit + " is a valid number of calories!");
                }
                    else if (numberOfCaloriesPerUnit < 1) {
                        System.out.println(numberOfCaloriesPerUnit + " is less than 1. Sorry, you are out of attempts.");
                }
                    else {
                        System.out.println(numberOfCaloriesPerUnit + " is greater than        2000. Sorry, you are out of attempts.");
                }
                        }

                        else {
                            System.out.println("Error: That is not a number. Try again.");
                        }
                        }

                //Calculate total calories
                totalCalories = ingredientAmount * numberOfCaloriesPerUnit;

                System.out.println(nameOfIngredient + " uses " + ingredientAmount + "    number of " + unitMeasurement + "'s" + " which contains " + totalCalories + " total            calories.");
        System.out.println("Ingredient has been successfully added.");
                        }

                }
            }
</code>```

答:
You are missing the static keyword.

As the error you get points out, you don't have the main method properly defined. You are defining your main method as public void main(String[] args) which should be defined public static void main(String[] args).

Body:
this code is supposed to ask the user for name of an ingredient, the number of cups used in the ingredient, and the unit measurement and calculate the total calories for them it involves alot of validation of user input and i have that part down so far but im just lost at this point. the confusing part is the error i get is that this code doe not have a main method

package Ingredient;
import java.util.Scanner;
public class V3 {

 //Private Fields: Internal Data

    private String nameOfIngredient;
    private String unitMeasurement;
    private float ingredientAmount;
    private int numberOfCaloriesPerUnit;
    private int numberOfCups;
    private double totalCalories;

//Operations: Public Methods

    //Mutators and Accessors: Set Values at the this. Index and Return the Value

    //Set and Return Name of Ingredient
         public void setNameOfIngredient(String nameOfIngredient) {
            this.nameOfIngredient = nameOfIngredient;
        }
        public String getNameOfIngredient() {
            return nameOfIngredient;
        }

        public void setNumberOfCups(int numberOfcups) {
            this.numberOfCups = numberOfCups;
        }
        public int getNumberOfCups() {
            return numberOfCups;
        }

    //Set and Return Unit Measurement
    public void setUnitMeasurement (String unitMeasurement) {
        this.unitMeasurement = unitMeasurement;
    }

    public String getUnitMeasurement () {
        return unitMeasurement;
    }

    //Set and Return Ingredient Amount
    public void setIngredientAmount(float ingredientAmount) {
        this.ingredientAmount = ingredientAmount;
        }

    public float getIngredientAmount() {
        return ingredientAmount;
        }

    //Set and Return Number of Calories per Unit
    public void setNumberCaloriesPerUnit(int numberCaloriesPerUnit) {
        this.numberOfCaloriesPerUnit = numberCaloriesPerUnit;
        }

    public int getNumberCaloriesPerUnit() {
        return numberOfCaloriesPerUnit;

    }

    //Set and Return Total Calories
    public void setTotalCalories(double totalCalories) {
        this.totalCalories = totalCalories;
        }

    public double getTotalCalories() {
        return totalCalories;
        }

    public void main(String[] args) {
        Scanner scnr = new Scanner(System.in);

    //Use this. pointer to initialize fields (as they share the same name as private/global fields)
        this.nameOfIngredient = "";
        this.numberOfCups = 0;
        this.numberOfCaloriesPerUnit = 0;
        this.totalCalories = 0.0;

    //Prompt user for name of ingredient
        System.out.println("Please Enter Ingredient Name: ");
        if (scnr.hasNextLine())) {
            nameOfIngredient = scnr.nextLine();
        }
        else{
            System.out.println("Please enter a valid name (characters only): ");
        }

    //Prompt user for unit of measurement
        System.out.println("Please Enter Unit of Measurement for this Ingredient. You have the following options: ");
        System.out.println("Cup(s)");
        System.out.println("Tbsp");
        System.out.println("Tsp");
        System.out.println("Gram(s)");

        if (scnr.hasNextLine()) {
            unitMeasurement = scnr.next();

            if ((unitMeasurement == "Cup(s)") || (unitMeasurement == "Tbsp") || (unitMeasurement == "Tsp") || (unitMeasurement == "Gram(s)")) {
                System.out.println("You have selected " + unitMeasurement);
            }

            else {
                System.out.println("Please enter one of the preceding options.");
            }

                else {
            System.out.println("Please enter one of the preceding options.");
            }
                }

    //Prompt user for number of units
        System.out.println("Please enter the number of units of " + nameOfIngredient + " required (between 1 and 100: ");

        if (scnr.hasNextInt()) {
            ingredientAmount = scnr.nextInt();

            if ((ingredientAmount >= 1) && (ingredientAmount <= 100)) {
                System.out.println(ingredientAmount + " is a valid amount!");

                        }else {
            System.out.println(ingredientAmount + " is not a valid amount.");
            System.out.println("Please enter a valid number of units between 1 and 100: ");
                                }
                if ((ingredientAmount >= 1) && (ingredientAmount <= 100)) {
                    System.out.println(numberOfCups + " is a valid amount!");
            }
                else if (ingredientAmount < 1) {
                    System.out.println(ingredientAmount + " is less than 1 unit. Sorry, you are out of attempts.");
            }
                else {
                    System.out.println(ingredientAmount + " is greater than 100 units. Sorry, you are out of attempts.");
            }

        else {
           System.out.println("Error: That is not a number. Try again.");
        }
                }

    //Prompt user for calories per unit
        System.out.println("Please enter the number of calories per unit of " + nameOfIngredient + " (between 1 and 2000): ");

        if (scnr.hasNextInt()) {
            numberOfCaloriesPerUnit = scnr.nextInt();

            if ((numberOfCaloriesPerUnit >= 1) && (numberOfCaloriesPerUnit <= 2000)) {
                System.out.println(numberOfCaloriesPerUnit + " is a valid number of calories!" );

            else {
                System.out.println(numberOfCaloriesPerUnit + " is not a valid number of calories.");
                System.out.println("Please enter a valid number of calories per unit between 1 and 2000: ");

                    if ((numberOfCaloriesPerUnit >= 1) && (numberOfCaloriesPerUnit <= 2000)) {
                        System.out.println(numberOfCaloriesPerUnit + " is a valid number of calories!");
                }
                    else if (numberOfCaloriesPerUnit < 1) {
                        System.out.println(numberOfCaloriesPerUnit + " is less than 1. Sorry, you are out of attempts.");
                }
                    else {
                        System.out.println(numberOfCaloriesPerUnit + " is greater than        2000. Sorry, you are out of attempts.");
                }
                        }

                        else {
                            System.out.println("Error: That is not a number. Try again.");
                        }
                        }

                //Calculate total calories
                totalCalories = ingredientAmount * numberOfCaloriesPerUnit;

                System.out.println(nameOfIngredient + " uses " + ingredientAmount + "    number of " + unitMeasurement + "'s" + " which contains " + totalCalories + " total            calories.");
        System.out.println("Ingredient has been successfully added.");
                        }

                }
            }


问:
Spring Boot with spring version 2.5.7 fails repackage with jdk 1.8
When running a maven package goal

mvn clean package

The build throws the error:

goal org.springframework.boot:spring-boot-maven-plugin:3.0.0-M1:repackage failed: Unable to load the mojo 'repackage' in the plugin 'org.springframework.boot:spring-boot-maven-plugin:3.0.0-M1' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/springframework/boot/maven/RepackageMojo has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0

my JAVA_HOME is pointing to jdk1.8.0_73

How can i get spring-boot-maven-plugin running with repackage goal?

Below is the maven build configuration in my module.

```<code><build>
<resources>
    <resource>
        <directory>resources</directory>
    </resource>
</resources>
<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
            <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
            <webResources>
                <resource>
                    <directory>src/main/resources</directory>
                    <include>*.*</include>
                    <targetPath>/WEB-INF/classes</targetPath>
                </resource>
                <resource>
                    <directory>src/main/webapp/errors</directory>
                    <include>*.*</include>
                    <targetPath>/errors/</targetPath>
                </resource>
            </webResources>
        </configuration>
    </plugin>

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <mainClass>com.services.MyAApp</mainClass>
            <layout>war</layout>
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

</plugins>
</code>```

答: Version of 'spring-boot-maven-plugin' plugin used in you pom.xml is 3.0.0-M1, which can be used only with Java 17 or newer. Switch to 2.5.7, if it's really version which you want to use for spring boot project.</p>

Body:
When running a maven package goal

mvn clean package

The build throws the error:

goal org.springframework.boot:spring-boot-maven-plugin:3.0.0-M1:repackage failed: Unable to load the mojo 'repackage' in the plugin 'org.springframework.boot:spring-boot-maven-plugin:3.0.0-M1' due to an API incompatibility: org.codehaus.plexus.component.repository.exception.ComponentLookupException: org/springframework/boot/maven/RepackageMojo has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0

my JAVA_HOME is pointing to jdk1.8.0_73

How can i get spring-boot-maven-plugin running with repackage goal?

Below is the maven build configuration in my module.

<build>
<resources>
    <resource>
        <directory>resources</directory>
    </resource>
</resources>
<plugins>
    <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
        </configuration>
    </plugin>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
            <packagingExcludes>WEB-INF/lib/*.jar</packagingExcludes>
            <webResources>
                <resource>
                    <directory>src/main/resources</directory>
                    <include>*.*</include>
                    <targetPath>/WEB-INF/classes</targetPath>
                </resource>
                <resource>
                    <directory>src/main/webapp/errors</directory>
                    <include>*.*</include>
                    <targetPath>/errors/</targetPath>
                </resource>
            </webResources>
        </configuration>
    </plugin>

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <mainClass>com.services.MyAApp</mainClass>
            <layout>war</layout>
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>repackage</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

</plugins>


问:
Using Source Code Pro ExtraLight in Visual Studio Code
Source Code Pro

How to use ExtraLight in VSC ~?
It seems that the following is not working ...
I'm sure I have the fonts.

Source Code Pro ExtraLight

答:
Use this code snippet for MacOS: Tested 6-Feb-2022 in VS Code.</p>
```<code>"editor.fontFamily": "'SourceCodeRoman-ExtraLight'",
</code>```

Body:
Use this code snippet for MacOS: Tested 6-Feb-2022 in VS Code.

"editor.fontFamily": "'SourceCodeRoman-ExtraLight'",


问:
Discrepancy in Javascript Intl.DateTimeFormat() Outputs for the Islamic (Hijri) Calendar between 'islamic' and 'ar-SA'
The 3rd March 2022 is the end of this Hijri Month (month of Rajab for this year 1443 AH); i.e. 30 Rajab 1443 AH.

The month of Rajab for the year 1443 AH is 30 days in accordance with the Islamic (Hijri) Calendar in accordance with all websites, applications, MS Office, and Windows calendars.

When using the javascript Intl.DateTimeFormat() to display the Islamic (Hijri) date for the 3 March 2022 using the islamic calendar option, it will give the Islamic Hijri Date of (1 Shaʻban 1443 AH). This result is one day after the month of Rajab (i.e. the 1st of the following month) and it calculated the month Rajab to be 29 days rather than 30 days.

However, if the option passed to the Intl.DateTimeFormat() is ar-SA (i.e. arabic-Saudi Arabia), it will give the correct result. This is strange because the ar-SA locale uses the Islamic (Hijri) calendar by default.

Is this an error/bug or is it the correct internal workings of javascript?

Is there a more robust method to get the Islamic Date in Javascript other than using the 'ar-SA' locale (but not using external libraries)?

See the code example below:

I have tested this in node and chrome and it gives the same resulting discrepancy.

let date = new Date("2022-03-03");
let options = {year:'numeric', month:'long',day:'numeric'};

let format = new Intl.DateTimeFormat('ar-SA-u-nu-latn', options);
console.log("3 March 2022 with 'ar-SA'         :"+format.format(date)+ " ==> means: 30 Rajab 1443 AH");

format = new Intl.DateTimeFormat('en-u-ca-islamic-nu-latn', options);
console.log("3 March 2022 with Islamic Calendar: "+format.format(date));```

答:
There are three possible reasons for the "off by one" date problems you're seeing:

Time zone mismatch between date initialization and date formatting

Using the wrong variation of the Islamic calendar (JS implementations typically offer 5 different Islamic calendars!)

Bugs in the ICU library used for JS's calendar calculations

I'll cover each of these below.

1. Time zone mismatch between date initialization and date formatting

The most common reason for off-by-one-day errors is (as @RobG noted in his comments above) a mismatch between the time zone used when declaring the Date value and the time zone used when formatting it in your desired calendar.

When you initialize a Date instance using an ISO 8601 string, the actual value stored in the Date instance is the number of milliseconds since January 1, 1970 UTC. Depending on your system time zone, new Date('2022-02-03') can be February 3 or February 2 in your system time zone. One way to evade this problem is to use UTC when formatting too:

new Date('2022-03-03').toLocaleDateString('en-US');
// outputs '3/2/2022' when run in San Francisco

new Date('2022-03-03').toLocaleDateString('en-US', { timeZone: 'UTC' });
// outputs '3/3/2022' as expected. UTC is used both for declaring and formatting.

new Date('2022-03-03').toLocaleDateString(
  'en-SA-u-ca-islamic-umalqura',
  { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' }
);
// outputs 'Rajab 30, 1443 AH' as expected
```
<p>Note that I'm using <code>Date.toLocaleDateString</code> above, but the result is the same as if you'd used <code>Intl.DateTimeFormat.format</code>. The parameters and implementations are the same for both methods.</p>
<p><strong>2. Using the wrong variation of the Islamic calendar (JS implementations typically offer 5 different Islamic calendars!)</strong></p>
<p>A second and more subtle issue is that multiple variations of islamic calendars are used in JavaScript. The list of supported calendars is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendars. Excerpting from that page, here are the supported Islamic calendar variations:</p>
<blockquote>
<ul>
<li><code>islamic</code>
<ul>
<li>Islamic calendar</li>
</ul>
</li>
<li><code>islamic-umalqura</code>
<ul>
<li>Islamic calendar, Umm al-Qura</li>
</ul>
</li>
<li><code>islamic-tbla</code>
<ul>
<li>Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch)</li>
</ul>
</li>
<li><code>islamic-civil</code>
<ul>
<li>Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch)</li>
</ul>
</li>
<li><code>islamic-rgsa</code>
<ul>
<li>Islamic calendar, Saudi Arabia sighting</li>
</ul>
</li>
</ul>
</blockquote>
<p>(There's also a deprecated <code>islamicc</code> calendar, but <code>islamic-civil</code> should be used instead.)</p>
<p>The default calendar for the <code>ar-SA</code> locale is the <code>islamic-umalqura</code> calendar, not the <code>islamic</code> calendar. To verify:</p>
<pre class="lang-js prettyprint-override"><code>new Intl.DateTimeFormat('ar-SA').resolvedOptions();
// {
//   calendar: "islamic-umalqura"
//   day: "numeric"
//   locale: "ar-SA"
//   month: "numeric"
//   numberingSystem: "arab"
//   timeZone: "America/Los_Angeles"
//   year: "numeric"
// }
</code>```

Different Islamic calendar variations will yield different calendar dates. For example:

calendars = ["islamic", "islamic-umalqura", "islamic-tbla", "islamic-civil", "islamic-rgsa"];
options = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
date = new Date('2022-03-03');
calendars.forEach(calendar => {
  formatted = date.toLocaleDateString(`en-SA-u-ca-${calendar}`, options);
  console.log(`${calendar}: ${formatted}`);
});
// The code above outputs the following:
//   islamic: Shaʻban 1, 1443 AH
//   islamic-umalqura: Rajab 30, 1443 AH
//   islamic-tbla: Rajab 30, 1443 AH
//   islamic-civil: Rajab 29, 1443 AH
//   islamic-rgsa: Shaʻban 1, 1443 AH
```

3. Bugs in the ICU library used for JS's calendar calculations

A third possible reason for unexpected dates is if there's a bug in the calendar calculation code inside the JS engine. As far as I know, all major browsers delegate their calendar calculations to a library called ICU. If you're using the correct time zone and calendar variation and there's still a problem with the calculation, then you may want to try filing an issue in the ICU JIRA site: https://unicode-org.atlassian.net/jira/software/c/projects/ICU/issues/.

BTW, while answering this question I noticed a bug in the MDN documentation for the Intl.DateTimeFormat constructor where the list of supported calendars is wrong. I filed https://github.com/mdn/content/pull/12764 to fix the content. This PR has already been merged, but it may take a while for the production MDN site to be updated with the fixed content.

Body:
There are three possible reasons for the "off by one" date problems you're seeing:

Time zone mismatch between date initialization and date formatting

Using the wrong variation of the Islamic calendar (JS implementations typically offer 5 different Islamic calendars!)

Bugs in the ICU library used for JS's calendar calculations

I'll cover each of these below.

1. Time zone mismatch between date initialization and date formatting

The most common reason for off-by-one-day errors is (as @RobG noted in his comments above) a mismatch between the time zone used when declaring the Date value and the time zone used when formatting it in your desired calendar.

When you initialize a Date instance using an ISO 8601 string, the actual value stored in the Date instance is the number of milliseconds since January 1, 1970 UTC. Depending on your system time zone, new Date('2022-02-03') can be February 3 or February 2 in your system time zone. One way to evade this problem is to use UTC when formatting too:

new Date('2022-03-03').toLocaleDateString('en-US');
// outputs '3/2/2022' when run in San Francisco

new Date('2022-03-03').toLocaleDateString('en-US', { timeZone: 'UTC' });
// outputs '3/3/2022' as expected. UTC is used both for declaring and formatting.

new Date('2022-03-03').toLocaleDateString(
  'en-SA-u-ca-islamic-umalqura',
  { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' }
);
// outputs 'Rajab 30, 1443 AH' as expected

Note that I'm using Date.toLocaleDateString above, but the result is the same as if you'd used Intl.DateTimeFormat.format. The parameters and implementations are the same for both methods.

2. Using the wrong variation of the Islamic calendar (JS implementations typically offer 5 different Islamic calendars!)

A second and more subtle issue is that multiple variations of islamic calendars are used in JavaScript. The list of supported calendars is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendars. Excerpting from that page, here are the supported Islamic calendar variations:

islamic

Islamic calendar

islamic-umalqura

Islamic calendar, Umm al-Qura

islamic-tbla

Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch)

islamic-civil

Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch)

islamic-rgsa

Islamic calendar, Saudi Arabia sighting

(There's also a deprecated islamicc calendar, but islamic-civil should be used instead.)

The default calendar for the ar-SA locale is the islamic-umalqura calendar, not the islamic calendar. To verify:

new Intl.DateTimeFormat('ar-SA').resolvedOptions();
// {
//   calendar: "islamic-umalqura"
//   day: "numeric"
//   locale: "ar-SA"
//   month: "numeric"
//   numberingSystem: "arab"
//   timeZone: "America/Los_Angeles"
//   year: "numeric"
// }

Different Islamic calendar variations will yield different calendar dates. For example:

calendars = ["islamic", "islamic-umalqura", "islamic-tbla", "islamic-civil", "islamic-rgsa"];
options = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
date = new Date('2022-03-03');
calendars.forEach(calendar => {
  formatted = date.toLocaleDateString(`en-SA-u-ca-${calendar}`, options);
  console.log(`${calendar}: ${formatted}`);
});
// The code above outputs the following:
//   islamic: Shaʻban 1, 1443 AH
//   islamic-umalqura: Rajab 30, 1443 AH
//   islamic-tbla: Rajab 30, 1443 AH
//   islamic-civil: Rajab 29, 1443 AH
//   islamic-rgsa: Shaʻban 1, 1443 AH

3. Bugs in the ICU library used for JS's calendar calculations

A third possible reason for unexpected dates is if there's a bug in the calendar calculation code inside the JS engine. As far as I know, all major browsers delegate their calendar calculations to a library called ICU. If you're using the correct time zone and calendar variation and there's still a problem with the calculation, then you may want to try filing an issue in the ICU JIRA site: https://unicode-org.atlassian.net/jira/software/c/projects/ICU/issues/.

BTW, while answering this question I noticed a bug in the MDN documentation for the Intl.DateTimeFormat constructor where the list of supported calendars is wrong. I filed https://github.com/mdn/content/pull/12764 to fix the content. This PR has already been merged, but it may take a while for the production MDN site to be updated with the fixed content.


问:
Bulk Data from Europe PMC annotation api
i have a pmc.txt file which contains atleast 20k pmc ids, and the api will only take i think 1000 request each time. i have written the code for one id, but i'm not able to do for the whole file, below is my main code. Please help.</p>
```<code>if __name__ == '__main__':
URL = 'https://www.ebi.ac.uk/europepmc/annotations_api/annotationsByArticleIds'

article_ids = ['PMC:4771370']

for article_id in article_ids:
  params = {
    'articleIds': article_id,
    'section': 'Abstract',
    'provider': 'Europe PMC',
    'format': 'JSON'
  }
json_data = requests.get(URL, params=params).content
r = json.loads(json_data)
df = json_to_dataframe(r)
print(df)
df.to_csv("data.csv")
</code>```

答:
You can use grequests. You can try setting stream=False in grequests.get, or call explicitly response.close() after reading response.content. It's discussed in detail here

Additionally, you can also test requests-futures. Grequests is faster but brings monkey patching and additional problems with dependencies. requests-futures is several times slower than grequests but simply wrapped requests into ThreadPoolExecutor can be as fast as grequests, but without external dependencies. Reference here.

Body:
i have a pmc.txt file which contains atleast 20k pmc ids, and the api will only take i think 1000 request each time. i have written the code for one id, but i'm not able to do for the whole file, below is my main code. Please help.

if __name__ == '__main__':
URL = 'https://www.ebi.ac.uk/europepmc/annotations_api/annotationsByArticleIds'

article_ids = ['PMC:4771370']

for article_id in article_ids:
  params = {
    'articleIds': article_id,
    'section': 'Abstract',
    'provider': 'Europe PMC',
    'format': 'JSON'
  }
json_data = requests.get(URL, params=params).content
r = json.loads(json_data)
df = json_to_dataframe(r)
print(df)
df.to_csv("data.csv")


问:
Plotly Bars aligned center to the grid
i wonder if there is way to align the bars in Plotly Bar to the center of the grid cell. I am using plotly express bar and the x axis displays date type values. As shown in the picture below.

I would like to have my tick label per day, but the bar should be centered in the day and not across the day tick.
it's possible to reproduce the behavior with few lines of code:

```<code>fig = px.bar(
    x=[datetime.datetime(2022, 3, 1), datetime.datetime(2022, 3, 2), datetime.datetime(2022, 3, 3)],
    y=[2, 4, 5]
)
fig.update_xaxis(dtick=86400000,tickmode='linear',
        ticklabelmode="period")
fig.show()
</code>```

答:
I couldn't control the time series data in express well, so I used graph_objects. go allows you to set the x-axis placement and tick units.

```<code>import plotly.express as px
import plotly.graph_objects as go
import datetime

fig = go.Figure()

fig.add_trace(go.Bar(
    x=[datetime.datetime(2022, 3, 1), datetime.datetime(2022, 3, 2), datetime.datetime(2022, 3, 3)],
    y=[2, 4, 5],
    xperiod=86400000,
    xperiodalignment="middle"
))
#fig.update_xaxes(dtick=86400000,tickmode='linear', ticklabelmode="period")
fig.update_xaxes(tickmode='linear', ticklabelmode="period")

fig.show()
</code>```

Title: Plotly Bars aligned center to the grid

Body:
i wonder if there is way to align the bars in Plotly Bar to the center of the grid cell. I am using plotly express bar and the x axis displays date type values. As shown in the picture below.

I would like to have my tick label per day, but the bar should be centered in the day and not across the day tick.
it's possible to reproduce the behavior with few lines of code:

fig = px.bar(
    x=[datetime.datetime(2022, 3, 1), datetime.datetime(2022, 3, 2), datetime.datetime(2022, 3, 3)],
    y=[2, 4, 5]
)
fig.update_xaxis(dtick=86400000,tickmode='linear',
        ticklabelmode="period")
fig.show()

Body:
I couldn't control the time series data in express well, so I used graph_objects. go allows you to set the x-axis placement and tick units.

import plotly.express as px
import plotly.graph_objects as go
import datetime

fig = go.Figure()

fig.add_trace(go.Bar(
    x=[datetime.datetime(2022, 3, 1), datetime.datetime(2022, 3, 2), datetime.datetime(2022, 3, 3)],
    y=[2, 4, 5],
    xperiod=86400000,
    xperiodalignment="middle"
))
#fig.update_xaxes(dtick=86400000,tickmode='linear', ticklabelmode="period")
fig.update_xaxes(tickmode='linear', ticklabelmode="period")

fig.show()


问:
How can I apply aggregate on array of objects?
I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.

Original Data

[
  {
    "_id": "61ff24b2db73094dd3029c7e",
    "TeamName": "GoodTeam",
    "TeamImage": "Avatar",
    "TeamMember": [
      {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ],
    "createdAt": "2022-02-06T01:30:26.893Z",
    "updatedAt": "2022-02-06T02:23:16.660Z",
    "__v": 0
  }
]
```
<p>Reconstruct Data</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "timezone":"PST",
    "TeamMember":[
       {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
  {
    "timezone":"AKST",
    "TeamMember":[
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ]
  }
]
</code>```

And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?

答:
You can always create a custom transformer for converting one JSON to another JSON and I would suggest you to let the back-end handle this responsibility.

Below is one example using Javascript.

const firstJson = `[
    {
      "_id": "61ff24b2db73094dd3029c7e",
      "TeamName": "GoodTeam",
      "TeamImage": "Avatar",
      "TeamMember": [
        {
          "name": "Aimee",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "test2@gmail.com",
          "timezone": "PST",
          "_id": "61ff25fcd2a0b9e13ee8989c"
        },
        {
          "name": "Kai",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "school021195@gmail.com",
          "timezone": "PST",
          "_id": "61ff3114d3d343bd673f5ad3"
        },
        {
          "name": "Iren",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "test1@gmail.com",
          "timezone": "AKST",
          "_id": "61ff3114d3d343bd673f5ad4"
        }
      ],
      "createdAt": "2022-02-06T01:30:26.893Z",
      "updatedAt": "2022-02-06T02:23:16.660Z",
      "__v": 0
    }
  ]`;

  const firstJsonObj = JSON.parse(firstJson);

  const map = new Map();
  for(let i =0;i<firstJsonObj.length;i++){
    for(let j =0;j<firstJsonObj[i].TeamMember.length;j++){
        let timezone = firstJsonObj[i].TeamMember[j].timezone;
        if(map.has(timezone)){
            const team = map.get(timezone);
            team.push(firstJsonObj[i].TeamMember[j]);
            map.set(timezone,team);
        }
        else{
            map.set(timezone,[firstJsonObj[i].TeamMember[j]])
        }
    }
  }

  const secondJson = Array.from(map,function(element){
      const [key,value] = element;
   return {
        timezone : key,
        TeamMember : value
    }
  });
  console.log(JSON.stringify(secondJson));```
</div>
</div>
</p>
<p><strong>EDIT:</strong>
If you want query data from mongodb itself you can use below query to get the output</p>
``` db.collection.aggregate([
  {
    "$unwind": "$TeamMember"
  },
  {
    "$group": {
      "_id": {
        "timezone": "$TeamMember.timezone"
      },
      "TeamMember": {
        "$push": "$$ROOT.TeamMember"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "timezone": "$_id.timezone",
      "TeamMember": 1
    }
  }
])
```

Body:
I have this complicated data in MongoDB, I want to reconstruct it into something like the second JSON, I tried both MongoDB aggregate and javascript spread, but I couldn't figure it out.

Original Data

[
  {
    "_id": "61ff24b2db73094dd3029c7e",
    "TeamName": "GoodTeam",
    "TeamImage": "Avatar",
    "TeamMember": [
      {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ],
    "createdAt": "2022-02-06T01:30:26.893Z",
    "updatedAt": "2022-02-06T02:23:16.660Z",
    "__v": 0
  }
]

Reconstruct Data

[
  {
    "timezone":"PST",
    "TeamMember":[
       {
        "name": "Aimee",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test2@gmail.com",
        "timezone": "PST",
        "_id": "61ff25fcd2a0b9e13ee8989c"
      },
      {
        "name": "Kai",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "school021195@gmail.com",
        "timezone": "PST",
        "_id": "61ff3114d3d343bd673f5ad3"
      },
  {
    "timezone":"AKST",
    "TeamMember":[
      {
        "name": "Iren",
        "image": "https://i.imgur.com/HeIi0wU.png",
        "email": "test1@gmail.com",
        "timezone": "AKST",
        "_id": "61ff3114d3d343bd673f5ad4"
      }
    ]
  }
]

And how should I deal with this kind of data reconstruction in the front-end or back-end? Which one is better practice?

Body:
You can always create a custom transformer for converting one JSON to another JSON and I would suggest you to let the back-end handle this responsibility.

Below is one example using Javascript.

const firstJson = `[
    {
      "_id": "61ff24b2db73094dd3029c7e",
      "TeamName": "GoodTeam",
      "TeamImage": "Avatar",
      "TeamMember": [
        {
          "name": "Aimee",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "test2@gmail.com",
          "timezone": "PST",
          "_id": "61ff25fcd2a0b9e13ee8989c"
        },
        {
          "name": "Kai",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "school021195@gmail.com",
          "timezone": "PST",
          "_id": "61ff3114d3d343bd673f5ad3"
        },
        {
          "name": "Iren",
          "image": "https://i.imgur.com/HeIi0wU.png",
          "email": "test1@gmail.com",
          "timezone": "AKST",
          "_id": "61ff3114d3d343bd673f5ad4"
        }
      ],
      "createdAt": "2022-02-06T01:30:26.893Z",
      "updatedAt": "2022-02-06T02:23:16.660Z",
      "__v": 0
    }
  ]`;

  const firstJsonObj = JSON.parse(firstJson);

  const map = new Map();
  for(let i =0;i<firstJsonObj.length;i++){
    for(let j =0;j<firstJsonObj[i].TeamMember.length;j++){
        let timezone = firstJsonObj[i].TeamMember[j].timezone;
        if(map.has(timezone)){
            const team = map.get(timezone);
            team.push(firstJsonObj[i].TeamMember[j]);
            map.set(timezone,team);
        }
        else{
            map.set(timezone,[firstJsonObj[i].TeamMember[j]])
        }
    }
  }

  const secondJson = Array.from(map,function(element){
      const [key,value] = element;
   return {
        timezone : key,
        TeamMember : value
    }
  });
  console.log(JSON.stringify(secondJson));

EDIT:
If you want query data from mongodb itself you can use below query to get the output

 db.collection.aggregate([
  {
    "$unwind": "$TeamMember"
  },
  {
    "$group": {
      "_id": {
        "timezone": "$TeamMember.timezone"
      },
      "TeamMember": {
        "$push": "$$ROOT.TeamMember"
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "timezone": "$_id.timezone",
      "TeamMember": 1
    }
  }
])


问:
Tortiose SVN Windows Server 2008 R2 Context Menu
I'm trying to install TortoiseSVN on Windows Server 2008 R2. I have tried the 32bit versions of Tortoise versions 1.6.16 and 1.5.15. I have used two different admin accounts including the local administrator. The problem is tortoise will not display in the context menu. Any suggestion would be much appreciated because I'm all out of ideas.</p>

答:
As said in comment...

Make sure the machine is truely 32bit and not a 64bit OS


问:
'Collection' object is not callable. If you meant to call the 'mapReduce' method on a 'Collection' object it is failing because no such method exists
I'm using pyMongo 1.11 and MongoDB 1.8.2. I'm trying to do a fairly complex Map/Reduce. I prototyped the functions in Mongo and got it working, but when I tried transferring it to Python, I get:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Developer/R-and-D/<ipython-input-71-3c3a43221538> in <module>()
----> 1 results = db.user_actions.mapReduce(map, reduce, "user_entities_interactions")

/Library/Python/2.7/site-packages/pymongo/collection.pyc in __call__(self, *args, **kwargs)
   1099                         "call the '%s' method on a 'Collection' object it is "
   1100                         "failing because no such method exists." %
-> 1101                         self.__name.split(".")[-1])

TypeError: 'Collection' object is not callable. If you meant to call the 'mapReduce' method on a 'Collection' object it is failing because no such method exists.
</code>```

My collection looks like this:

```<code>{ "_id" : ObjectId("..."), "entity_id" : 1556, "user_id" : 466112 }
{ "_id" : ObjectId("..."), "entity_id" : 1366, "user_id" : 10057 }
{ "_id" : ObjectId("..."), "entity_id" : 234, "user_id" : 43650 }
{ "_id" : ObjectId("..."), "entity_id" : 6, "user_id" : 34430 }
{ "_id" : ObjectId("..."), "entity_id" : 461, "user_id" : 3416 }
{ "_id" : ObjectId("..."), "entity_id" : 994, "user_id" : 10057 }
{ "_id" : ObjectId("..."), "entity_id" : 296, "user_id" : 466112 }
</code>```

The code I'm running in Python is:

```<code>map = Code("""function () {
        emit(this.user_id, {
            user_id : this.user_id,
            entity_id : this.entity_id});
    }""")

reduce = Code("""function (key, values) {
        var entities = { user_id : values[0].user_id, entity_id : [ ] };
        for (var i = 0; i < values.length; i++) {
            entities.entity_id[i] = values[i].entity_id;
        }
        return entities;
    }""")
results = db.user_actions.mapReduce(map, reduce, "user_entities_interactions")
</code>```

What the result should look like is:

```<code>{ "_id" : 3416, "value" : { "user_id" : 3416, "entity_id" : 461 } }
{ "_id" : 10057, "value" : { "user_id" : 10057, "entity_id" : [ 1366, 994 ] } }
{ "_id" : 34430, "value" : { "user_id" : 34430, "entity_id" : 6 } }
{ "_id" : 43650, "value" : { "user_id" : 43650, "entity_id" : 234 } }
{ "_id" : 466112, "value" : { "user_id" : 466112, "entity_id" : [ 1556, 296 ] } }
</code>```

I'm not clear on what the problem is. The error says that the 'Collection' object has no mapReduce method, but that's clearly not true as the example at http://api.mongodb.org/python/current/examples/map_reduce.html works and what is 'things' if  not a collection?

Also, in case you're wondering why I'm not doing this with group() it's because I have more than 20000 unique keys.

答:
One update on this, PyMongo 4.0 Removed pymongo.collection.Collection.map_reduce(). Using 4.0+ version of pymongo will give same error for map_reduce method.

Details can be found here

Body:
I'm using pyMongo 1.11 and MongoDB 1.8.2. I'm trying to do a fairly complex Map/Reduce. I prototyped the functions in Mongo and got it working, but when I tried transferring it to Python, I get:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Developer/R-and-D/<ipython-input-71-3c3a43221538> in <module>()
----> 1 results = db.user_actions.mapReduce(map, reduce, "user_entities_interactions")

/Library/Python/2.7/site-packages/pymongo/collection.pyc in __call__(self, *args, **kwargs)
   1099                         "call the '%s' method on a 'Collection' object it is "
   1100                         "failing because no such method exists." %
-> 1101                         self.__name.split(".")[-1])

TypeError: 'Collection' object is not callable. If you meant to call the 'mapReduce' method on a 'Collection' object it is failing because no such method exists.

My collection looks like this:

{ "_id" : ObjectId("..."), "entity_id" : 1556, "user_id" : 466112 }
{ "_id" : ObjectId("..."), "entity_id" : 1366, "user_id" : 10057 }
{ "_id" : ObjectId("..."), "entity_id" : 234, "user_id" : 43650 }
{ "_id" : ObjectId("..."), "entity_id" : 6, "user_id" : 34430 }
{ "_id" : ObjectId("..."), "entity_id" : 461, "user_id" : 3416 }
{ "_id" : ObjectId("..."), "entity_id" : 994, "user_id" : 10057 }
{ "_id" : ObjectId("..."), "entity_id" : 296, "user_id" : 466112 }

The code I'm running in Python is:

map = Code("""function () {
        emit(this.user_id, {
            user_id : this.user_id,
            entity_id : this.entity_id});
    }""")

reduce = Code("""function (key, values) {
        var entities = { user_id : values[0].user_id, entity_id : [ ] };
        for (var i = 0; i < values.length; i++) {
            entities.entity_id[i] = values[i].entity_id;
        }
        return entities;
    }""")
results = db.user_actions.mapReduce(map, reduce, "user_entities_interactions")

What the result should look like is:

{ "_id" : 3416, "value" : { "user_id" : 3416, "entity_id" : 461 } }
{ "_id" : 10057, "value" : { "user_id" : 10057, "entity_id" : [ 1366, 994 ] } }
{ "_id" : 34430, "value" : { "user_id" : 34430, "entity_id" : 6 } }
{ "_id" : 43650, "value" : { "user_id" : 43650, "entity_id" : 234 } }
{ "_id" : 466112, "value" : { "user_id" : 466112, "entity_id" : [ 1556, 296 ] } }

I'm not clear on what the problem is. The error says that the 'Collection' object has no mapReduce method, but that's clearly not true as the example at http://api.mongodb.org/python/current/examples/map_reduce.html works and what is 'things' if  not a collection?

Also, in case you're wondering why I'm not doing this with group() it's because I have more than 20000 unique keys.


问:
laravel echo wont subscribe to private channel even the user is authenticated
I'm using

Laravel: 8.54

Laravel Sanctum: 2.11

Pusher Php Server: 7.0

NuxtJs: 2.15.7

pusher-js: 7.0.4

laravel-echo: 1.11.3

Event Class

```<code>    <?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class RaffleEntriesCreated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $userid;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($userid)
    {
        $this->userid = $userid;
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'private-raffle-entry';
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('RaffleEntry.'.$this->userid);
    }
}
</code>```

On My Channels file

```<code>Broadcast::channel('RaffleEntry.{id}',  function ($user, $id) {
    return (int) $user->id === (int) $id;
});
</code>```

On nuxt plugin

```<code>       import Echo from 'laravel-echo';
        window.Pusher = require('pusher-js');
        export default ({ app }, inject) => {
          const echo = new Echo({
              broadcaster: 'pusher',
              key: "mykey",
              authEndpoint: `http://back.project888.test/api/broadcasting/auth`,
              encrypted: true,
              forceTLS: true,
              cluster: 'ap2',
              authorizer: (channel, options) => {
                return {
                    authorize: (socketId, callback) => {
                        app.$axios.$post('/api/broadcasting/auth', {
                            socket_id: socketId,
                            channel_name: channel.name
                        })
                        .then(response => {
                            callback(false, response.data);
                            console.log('from oklugib ');
                        })
                        .catch(error => {
                            callback(true, error);
                        });
                    }
                };
              }
          });
          inject(

    'echo', echo)
    }
</code>```

Client Code

```<code> this.$echo.private(`RaffleEntry.${this.$auth.user.id}`)
        .listen('.private-raffle-entry', (e) => {
            console.log(e);
        });
</code>```

I can see the broadcast message into pusher dashboard, also the client connection, The user can be authenticated  perfectly, issue is it doesn't subscribe after the auth. Please see these screenshots of the request for authenticating the user before subscribing. Do you have any ideas how i can solve this ?

答:
Okay got this issue resolved, on my nuxt plugin file the authorizer option you just return the response var not respose.data

```<code>import Echo from 'laravel-echo';
        window.Pusher = require('pusher-js');
        export default ({ app }, inject) => {
          const echo = new Echo({
              broadcaster: 'pusher',
              key: "mykey",
              authEndpoint: `http://back.project888.test/api/broadcasting/auth`,
              encrypted: true,
              forceTLS: true,
              cluster: 'ap2',
              authorizer: (channel, options) => {
                return {
                    authorize: (socketId, callback) => {
                        app.$axios.$post('/api/broadcasting/auth', {
                            socket_id: socketId,
                            channel_name: channel.name
                        })
                        .then(response => {
                            callback(false, response);

                        })
                        .catch(error => {
                            callback(true, error);
                        });
                    }
                };
              }
          });
          inject(

    'echo', echo)
    }
</code>```

Body:
I'm using

Laravel: 8.54

Laravel Sanctum: 2.11

Pusher Php Server: 7.0

NuxtJs: 2.15.7

pusher-js: 7.0.4

laravel-echo: 1.11.3

Event Class

    <?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class RaffleEntriesCreated implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $userid;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($userid)
    {
        $this->userid = $userid;
    }

    /**
     * The event's broadcast name.
     *
     * @return string
     */
    public function broadcastAs()
    {
        return 'private-raffle-entry';
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('RaffleEntry.'.$this->userid);
    }
}

On My Channels file

Broadcast::channel('RaffleEntry.{id}',  function ($user, $id) {
    return (int) $user->id === (int) $id;
});

On nuxt plugin

       import Echo from 'laravel-echo';
        window.Pusher = require('pusher-js');
        export default ({ app }, inject) => {
          const echo = new Echo({
              broadcaster: 'pusher',
              key: "mykey",
              authEndpoint: `http://back.project888.test/api/broadcasting/auth`,
              encrypted: true,
              forceTLS: true,
              cluster: 'ap2',
              authorizer: (channel, options) => {
                return {
                    authorize: (socketId, callback) => {
                        app.$axios.$post('/api/broadcasting/auth', {
                            socket_id: socketId,
                            channel_name: channel.name
                        })
                        .then(response => {
                            callback(false, response.data);
                            console.log('from oklugib ');
                        })
                        .catch(error => {
                            callback(true, error);
                        });
                    }
                };
              }
          });
          inject(

    'echo', echo)
    }

Client Code

 this.$echo.private(`RaffleEntry.${this.$auth.user.id}`)
        .listen('.private-raffle-entry', (e) => {
            console.log(e);
        });

I can see the broadcast message into pusher dashboard, also the client connection, The user can be authenticated  perfectly, issue is it doesn't subscribe after the auth. Please see these screenshots of the request for authenticating the user before subscribing. Do you have any ideas how i can solve this ?

Body:
Okay got this issue resolved, on my nuxt plugin file the authorizer option you just return the response var not respose.data

import Echo from 'laravel-echo';
        window.Pusher = require('pusher-js');
        export default ({ app }, inject) => {
          const echo = new Echo({
              broadcaster: 'pusher',
              key: "mykey",
              authEndpoint: `http://back.project888.test/api/broadcasting/auth`,
              encrypted: true,
              forceTLS: true,
              cluster: 'ap2',
              authorizer: (channel, options) => {
                return {
                    authorize: (socketId, callback) => {
                        app.$axios.$post('/api/broadcasting/auth', {
                            socket_id: socketId,
                            channel_name: channel.name
                        })
                        .then(response => {
                            callback(false, response);

                        })
                        .catch(error => {
                            callback(true, error);
                        });
                    }
                };
              }
          });
          inject(

    'echo', echo)
    }


问:
What the logic behind b1 ? b1 : b2 in my coding in if-conditions?
1.Here is the assignment.

Declare a function or that works like ||, but without using the || operator.
/**

@param {any} ??? - the first operand

@param {any} ??? - the second operand

@returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn't understand it ,and haven't found a proper explanation about it online.

```<code>function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}
</code>```

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

```<code>actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 2

```<code>actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 3

```<code>actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

//TEST 4

```<code>actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}
</code>```

答:
b1 ? b1 : b2 is using a Ternary Operation

If you were to write it as a if-else statement it would look like

```<code>if (b1 === true) {
  return b1;
} else {
  return b2;
}
</code>```

Body:
1.Here is the assignment.

Declare a function or that works like ||, but without using the || operator.
/**

@param {any} ??? - the first operand

@param {any} ??? - the second operand

@returns {any} the same result as applying the || operator to the given operands, in order

2.Here is what tried(actually people gave me advice on return b1 ? b1 : b2.But i couldn't understand it ,and haven't found a proper explanation about it online.

function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}

3.Here are the coding tests, and the code above passed all of them. But would anyone tell me the logic of b1 ? b1 : b2. I am a beginner, please help me !

//TEST 1

actual = or("bananas", false);

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 2

actual = or("", "bananas");

expected = "bananas";

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 3

actual = or(true, true);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

//TEST 4

actual = or(true, false);

expected = true;

if (actual === expected) {
  console.log("Yay! Test PASSED.");
} else {
  console.error("Test FAILED. Keep trying!");
  console.log("    actual: ", actual);
  console.log("  expected: ", expected);
}

Body:
b1 ? b1 : b2 is using a Ternary Operation

If you were to write it as a if-else statement it would look like

if (b1 === true) {
  return b1;
} else {
  return b2;
}


问:
__str__ method for Class LinkedList
I have defined the LinkedList class below. I was able to implement all other methods except for the __str__ method, can someone tell me how to define this method. The Node class has already been defined and I can use Node(), get_data(), set_data(), get_next() and set_next()

```<code>class LinkedList:
    def __init__(self):
        self.head = None
        self.count = 0

    def is_empty(self):
        return self.count == 0

    def size(self):
        return self.count

    def add(self, item):
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node
        self.count += 1

    def search(self, item):
        current = self.head
        while current != None:
            if current.get_data() == item:
                return True
            else:
                current = current.get_next()
        return False

    def remove(self, item):
        found = False
        current = self.head
        previous = None
        while current != None and not found:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()
        if found:
            if previous == None:
                self.head = current.get_next()
            else:
                previous.set_next(current.get_next())
            self.count -= 1
        else:
            raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")

    def clear(self):
        while (self.head != None):
            temp = self.head
            self.head = self.head.next
            temp = None

    def __str__(self): #My doubt is here
        current = self.head
        return "Head --> {}".format(current)
        current = current.get_next()
</code>```

Test:

```<code>l_list = LinkedList()
print(l_list)
l_list.add(1)
l_list.add(2)
print(l_list)
</code>```

Output expected:

```<code>Head --> None
Head --> 2 --> 1
</code>```

output received:

```<code>Head --> None
Head --> <__main__.Node object at 0x7f39f7d14b80>
</code>```

Test:

```<code>l_list = LinkedList()
l_list.add("hello")
l_list.add("world")
print(l_list)
l_list.clear()
print(l_list)
</code>```

output expected:

```<code>Head --> world --> hello
Head --> None
</code>```

output recd:

```<code>Head --> <__main__.Node object at 0x7f39f7d7cf10>
Head --> None
</code>```

答:
Here you print the object of Node, For fixing just call get_data method for each Node, and get next Node:

def __str__(self): #My doubt is here
    current = self.head
    s = "Head -->"
    while current:
        s+=" {} -->".format(current.get_data())
        current = current.get_next()
    s += " None"
    return s
```
<p>The output of:</p>
<pre class="lang-python prettyprint-override"><code>l_list = LinkedList()
print(l_list)
l_list.add(1)
l_list.add(2)
print(l_list)
</code>```

will be:

Head --> None
Head --> 2 --> 1 --> None
```

Title: __str__ method for Class LinkedList

Body:
I have defined the LinkedList class below. I was able to implement all other methods except for the __str__ method, can someone tell me how to define this method. The Node class has already been defined and I can use Node(), get_data(), set_data(), get_next() and set_next()

class LinkedList:
    def __init__(self):
        self.head = None
        self.count = 0

    def is_empty(self):
        return self.count == 0

    def size(self):
        return self.count

    def add(self, item):
        new_node = Node(item)
        new_node.set_next(self.head)
        self.head = new_node
        self.count += 1

    def search(self, item):
        current = self.head
        while current != None:
            if current.get_data() == item:
                return True
            else:
                current = current.get_next()
        return False

    def remove(self, item):
        found = False
        current = self.head
        previous = None
        while current != None and not found:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()
        if found:
            if previous == None:
                self.head = current.get_next()
            else:
                previous.set_next(current.get_next())
            self.count -= 1
        else:
            raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")

    def clear(self):
        while (self.head != None):
            temp = self.head
            self.head = self.head.next
            temp = None

    def __str__(self): #My doubt is here
        current = self.head
        return "Head --> {}".format(current)
        current = current.get_next()

Test:

l_list = LinkedList()
print(l_list)
l_list.add(1)
l_list.add(2)
print(l_list)

Output expected:

Head --> None
Head --> 2 --> 1

output received:

Head --> None
Head --> <__main__.Node object at 0x7f39f7d14b80>

Test:

l_list = LinkedList()
l_list.add("hello")
l_list.add("world")
print(l_list)
l_list.clear()
print(l_list)

output expected:

Head --> world --> hello
Head --> None

output recd:

Head --> <__main__.Node object at 0x7f39f7d7cf10>
Head --> None

Body:
Here you print the object of Node, For fixing just call get_data method for each Node, and get next Node:

def __str__(self): #My doubt is here
    current = self.head
    s = "Head -->"
    while current:
        s+=" {} -->".format(current.get_data())
        current = current.get_next()
    s += " None"
    return s

The output of:

l_list = LinkedList()
print(l_list)
l_list.add(1)
l_list.add(2)
print(l_list)

will be:

Head --> None
Head --> 2 --> 1 --> None


答:
```<code>function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}
</code>```

Multiple things are happing Headers. Here, You have a test function with falsy check. Falsy is validateNumber, it can be null, blank string or zero. The condition will always return false. If you really looking to test value with the type you should use === instead.

```<code>console.log(Boolean("")) //false
console.log(Boolean(null))//false

console.log(Boolean(0))//false

console.log(Boolean(" "))//true
console.log(Boolean("1"))//true
</code>```

Title: What the logic behind b1 ? b1 : b2 in my coding in if-conditions?

Body:
function or(b1, b2) {
  if (b1 == false && b2 == false) return false;
  else return b1 ? b1 : b2;
}

Multiple things are happing Headers. Here, You have a test function with falsy check. Falsy is validateNumber, it can be null, blank string or zero. The condition will always return false. If you really looking to test value with the type you should use === instead.

console.log(Boolean("")) //false
console.log(Boolean(null))//false

console.log(Boolean(0))//false

console.log(Boolean(" "))//true
console.log(Boolean("1"))//true


问:
Flutter gif image glitch
I do not know how to correctly explain, but I'll try. On my auth page, at the top of it, I have a GIF logo (without repeat). So auth page works like this:

logo animation running (for around 3 seconds)

after 3 seconds all other content appears (thanks to delayed_display)

And all works fine. But if I logged in to the app, and press log out, I'm redirected back to the same login page (as expected), but GIF not playing again, and simply freezing on the first frame. I can assume it's probably because my GIF set up to not repeat and it cached in flutter??? But if it's cached, why do I see it at the beginning of the animation, but not the final frame???

Also not about how authentication works. I'm using GetX for state management. So basically all is moving around authUser observable from AuthenticationController, and I have a Wrapper page which checks if authUser is not null to show DashboardScreen, otherwise AuthScreen.

Here is the AuthScreen with the gif image itself:

class AuthScreen extends StatelessWidget {
  AuthScreen({Key? key}) : super(key: key);
  final AuthenticationController _authController =
      Get.find<AuthenticationController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
            child: SafeArea(
      child: Column(
        children: [
          Image.asset('assets/images/n2mu_animated_logo.gif'), <=== here is the GIF
          DelayedDisplay(
              delay: const Duration(seconds: 4),
              child: Container(
                margin: const EdgeInsets.only(top: 40, right: 20, left: 20),
                child: Center(
                    child: Column(children: [
                  RichText(
                      text: const TextSpan(children: [
                    TextSpan(
                      text: 'Hey, let verify:',
                      style:
                          TextStyle(fontWeight: FontWeight.bold, fontSize: 22),
                    ),
                  ])),
                  Obx(() => AnimatedSwitcher(
                        duration: const Duration(microseconds: 300),
                        child: (_authController.verificationCodeSent.value ==
                                false)
                            ? PhoneNumberWidget() <== widget to shop phone number input
                            : SmsVerificationWidget(), <== SMS verification widget
                      )),
                ])),
              )),
        ],
      ),
    )));
  }
}
```

答: Found the solution, you should use evict() method of the AssetImage widget. Here is more info https://github.com/flutter/flutter/issues/51775#issuecomment-680997795

Title: Flutter gif image glitch