问:
Find the amount of water in ith cup in a pyramid structure?
This question was asked in a forum. Any suggestions?

There is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on..
It looks something like this

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

every cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only from 2 and 3 resp but 5 gets water from both the cups and so on.
Now given C and L .Find the amount of water in ith cup ?

答:
Here is another easy solution that simply pours the water into the current glass and then checks if there is extra water then flows to the next level. Here I have used 2D Mat for pouring the water. Then I have converted the 2D mat to 1D having size equals to ith element/glass which we need to return and return that. Implementation wise this is a very easy solution.</p>

```<code>private double fillWaterInGlasses(double capacity, double water , int glassToFind) {
    int maxLevel = (int)(water/capacity)/2 + 1;
    double[][] glasses = new double[maxLevel][maxLevel];
    // Pour total water in top glass initially.
    glasses[0][0] = water;
    int level=0;
    boolean waterInLevel = true;
    while(waterInLevel) {
        waterInLevel = false;
        // For each glass in the level.
        for(int j=0; j<=level; j++) {
            // If the glass has more liquid then it can store then pour it to glasses under it.
            if(glasses[level][j] > capacity) {
                double extraWater = glasses[level][j] - capacity;
                glasses[level][j] = capacity;
                glasses[level+1][j] += extraWater / 2;
                glasses[level+1][j+1] += extraWater / 2;
                waterInLevel = true;
            }
        }
        level++;
    }
    double res[] = new double[glassToFind];
    int k =0;
    for (int i = 0; i < glasses.length; i++) {
        for (int j = 0; j <= i; j++) {
            res[k] = glasses[i][j];
            if (k == glassToFind-1){
                return res[glassToFind-1];
            }
            k++;
        }
    }
    return res[glassToFind-1];
}
</code>```

Body:
This question was asked in a forum. Any suggestions?

There is a pyramid with 1 cup at level , 2 at level 2 , 3 at level 3 and so on..
It looks something like this

  1
 2 3
4 5 6

every cup has capacity C. you pour L liters of water from top . when cup 1 gets filled , it overflows to cup 2,3 equally, and when they get filled , Cup 4 and 6 get water only from 2 and 3 resp but 5 gets water from both the cups and so on.
Now given C and L .Find the amount of water in ith cup ?

Body:
Here is another easy solution that simply pours the water into the current glass and then checks if there is extra water then flows to the next level. Here I have used 2D Mat for pouring the water. Then I have converted the 2D mat to 1D having size equals to ith element/glass which we need to return and return that. Implementation wise this is a very easy solution.

private double fillWaterInGlasses(double capacity, double water , int glassToFind) {
    int maxLevel = (int)(water/capacity)/2 + 1;
    double[][] glasses = new double[maxLevel][maxLevel];
    // Pour total water in top glass initially.
    glasses[0][0] = water;
    int level=0;
    boolean waterInLevel = true;
    while(waterInLevel) {
        waterInLevel = false;
        // For each glass in the level.
        for(int j=0; j<=level; j++) {
            // If the glass has more liquid then it can store then pour it to glasses under it.
            if(glasses[level][j] > capacity) {
                double extraWater = glasses[level][j] - capacity;
                glasses[level][j] = capacity;
                glasses[level+1][j] += extraWater / 2;
                glasses[level+1][j+1] += extraWater / 2;
                waterInLevel = true;
            }
        }
        level++;
    }
    double res[] = new double[glassToFind];
    int k =0;
    for (int i = 0; i < glasses.length; i++) {
        for (int j = 0; j <= i; j++) {
            res[k] = glasses[i][j];
            if (k == glassToFind-1){
                return res[glassToFind-1];
            }
            k++;
        }
    }
    return res[glassToFind-1];
}


来源: stackexchange

问:
warning message with mutate_at() in dplyr package
I received a warning message when using mutate_at() in dplyr package.

```<code>dt %>%
  mutate_at(
    c(5:43),
    funs(pc = ./Population)
    )
</code>```

```<code>Warning message:
funs() is soft deprecated as of dplyr 0.8.0
Please use a list of either functions or lambdas:

  # Simple named list:
  list(mean = mean, median = median)

  # Auto named with `tibble::lst()`:
  tibble::lst(mean, median)

  # Using lambdas
  list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))
This warning is displayed once per session.
</code>```

Is there any alternative function?

How can I pass this using data.table.

ContentLicense: CC BY-SA 4.0

Body:
I received a warning message when using mutate_at() in dplyr package.

dt %>%
  mutate_at(
    c(5:43),
    funs(pc = ./Population)
    )

Warning message:
funs() is soft deprecated as of dplyr 0.8.0
Please use a list of either functions or lambdas:

  # Simple named list:
  list(mean = mean, median = median)

  # Auto named with `tibble::lst()`:
  tibble::lst(mean, median)

  # Using lambdas
  list(~ mean(., trim = .2), ~ median(., na.rm = TRUE))
This warning is displayed once per session.

Is there any alternative function?

How can I pass this using data.table.

Body:
With the recent versions of dplyr, it would be list

library(dplyr)
dt %>%
  mutate_at(5:43,
         list(pc = ~ ./Population))

Reproducible example

head(mtcars) %>%
       mutate_at(4:5, list(pc = ~ ./wt))
#    mpg cyl disp  hp drat    wt  qsec vs am gear carb    hp_pc   drat_pc
#1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4 41.98473 1.4885496
#2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 38.26087 1.3565217
#3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 40.08621 1.6594828
#4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 34.21462 0.9580093
#5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 50.87209 0.9156977
#6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 30.34682 0.7976879

Warning message is a friendly warning and nothing to worry about

In data.table, we specify it in .SDcols

library(data.table)
setDT(dt)[, paste0(names(dt)[5:43], "_pc") :=
           lapply(.SD, function(x) x/Population), .SDcols = 5:43]

Or using base R

nm1 <- names(dt)[5:43]
dt[paste0(nm1, "_pc")] <- lapply(dt[nm1], `/`, dt[["Population"]])

Or directly

dt[paste0(nm1, "_pc")] <- dt[nm1]/dt[["Population"]]


问:
Is there a keyboard shortcut to switch between dark mode and light mode in iPhone simulator?
I'm using iPhone simulator for my development and most of the ui components are written using swift. Is there an easy way to switch between dark mode and light mode for testing purpose?

I find the enabling and disabling dark mode from settings very time consuming. This shortcut will expedite my testability of both dark mode and light mode.

答:
I think I've read enough Documentation to tell you that(Maybe I'm wrong too.)

According to my knowledge, We don't have a Keyboard Shortcut to toggle(switch) between Dark mode and Light appearance in iOS Simulator We do have shortcut for tvOS though which is Command-Shift-D to toggle but not in the iOS Simulator

Referred Links:

https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/dark-mode/

https://developer.apple.com/documentation/uikit/appearance_customization/adopting_ios_dark_mode

https://developer.apple.com/documentation/xcode/supporting_dark_mode_in_your_interface

I've also research for creating a shortcut (as there is none in existence) with given code in following link
XCode Simulator: how to change its shortcuts?

But I came to know that we can only change only Keyboard shortcuts(can't create one) which are already there in Simulator>Hardware>...(Which are pre-assigned)

Hope , It Helps :)


问:
Trouble Writing back to text file using PHP fwrite from file selected from a dropdown form
I am having trouble writing back to a text file selected from a html form with a dropdown menu, the script is able to read but is unable to write back, returns "Unable to Open File".using PHP fopen and fwrite

This is the index.html code:

```<code><html>
<head></head>
<title>Edit Server Side Text Files</title>
<body>
<form action="function.php" method="post">
<select name="list">
  <option value="./files/banned-kdf.txt">banned-kdf.txt</option>
  <option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>
</body>
</html>
</code>```

And this is the function.php code:

```<code><?php

if(isset($_POST["edit"])) {
   $filename = $_POST["list"];
   global $filename;
//   var_dump($filename);
   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
?>
<html>
<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?

if(isset($filecontent)) { echo $filecontent; }

?>
</textarea>
<br>
<br>
<input type="submit" name="update" value="Update" />
 </textarea>
<?
//write to text file
 if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.
//   echo $_POST["update"];
//   var_dump($filename);
   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
 }
 ?>

 </form>
 <br>
 <br>
<a href="/index.html">Return to List Selection</a>
</html>
</code>```

答: Please check the permission of target file and the folder in this the file is supposed to be.</p>

Body:
I am having trouble writing back to a text file selected from a html form with a dropdown menu, the script is able to read but is unable to write back, returns "Unable to Open File".using PHP fopen and fwrite

This is the index.html code:

<title>Edit Server Side Text Files</title>

<form action="function.php" method="post">
<select name="list">
  <option value="./files/banned-kdf.txt">banned-kdf.txt</option>
  <option value="./files/blackList.txt">blackList.txt</option>
</select>
<input type="submit" name="edit" value="Edit" />
</form>

And this is the function.php code:

<?php

if(isset($_POST["edit"])) {
   $filename = $_POST["list"];
   global $filename;
//   var_dump($filename);
   $myfile = fopen("$filename", "r") or die("Unable to open file!");
   $filecontent =  fread($myfile,filesize("$filename"));
   fclose($myfile);
 }
?>

<form action="<?php echo $PHP_SELF;?>" method="post">
<textarea name="textareaContent" rows="50" cols="100">
<?

if(isset($filecontent)) { echo $filecontent; }

?>
</textarea>

<input type="submit" name="update" value="Update" />
 </textarea>
<?
//write to text file
 if(isset($_POST["update"])) {
// The following two lines are just for troubleshooting and have been commented out.
//   echo $_POST["update"];
//   var_dump($filename);
   $myfile = fopen("$filename", "w") or die("Unable to open file!");
   fwrite($myfile, $_POST["textareaContent"]);
   fclose($myfile);
 }
 ?>

 </form>

Return to List Selection


问:
Do you believe the Firefox project should be forked into a developer targeted version?
I've just got this idea that there is a need for a forked version of Firefox that would provide right out of the box tools for web development. Like FireBug, YSlow, FireCookie, LiveHTTPHeaders, etc.

Maybe the fork should only include those extensions or take a further step and implement them in existing chrome.

The reason I'm thinking about this is that right now I have two Firefox profiles. A "browsing" one which has only one extension and a "development" one which has lots and lots of extensions. The advantage is obviously that the former is faster than the latter. Maybe if aimed from the beginning at developers, a forked version would bring some speed improvements and other niceties.

What do you think? Any volunteers?

答: What advantage would that give over extensions? You don't actually believe, that someone will port code to C?</p>

OwnerDisplayName: Ionut G. Stan

ContentLicense: CC BY-SA 2.5


问:
Adding 20 Byes Offset To Pointer Address
I'm trying to read a value from a pointer address + offset and not getting the correct result.

I have the following (relevant pieces) of code:

```<code>uintptr_t moduleBase = GetModuleBaseAddress(procId, L"ProgramImReading.exe");
uintptr_t pObjectManager = moduleBase + 0x237CB28;
std::vector<unsigned int> countOffset = { 0x20 };

uintptr_t totalObjects = FindDMAAddy(hProcess, pObjectManager, countOffset);
std::cout << "Current objects = " << totalObjects << std::endl;
</code>```

FindDMAAddy:

```<code>    uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets)
{
    uintptr_t   addr = ptr;
    for (unsigned int i = 0; i < offsets.size(); ++i)
    {
        ReadProcessMemory(hProc, (BYTE*)addr, &addr, sizeof(addr), 0);
        addr += offsets[i];
    }
    return addr;
}
</code>```

For some reason this will not work. I can confirm the addresses are correct by opening cheat engine and entering GameAdress + Pointer, then setting the offset + 20 and getting the correct value.

When i run the code above I get a long random value "2596411228208"

I can also find the current dynamic address the pointer is pointing to and read directly from that address, but when I try to read from the pointer + offset It does not work right.

答:
FindDMAAddy returns the final address of the pointer chain.  Your code expects it to contain the value in that address, which it does not.  You need to use ReadProcessMemory to read it.

The correct code is:

uintptr_t moduleBase = GetModuleBaseAddress(procId, L"ProgramImReading.exe");
uintptr_t pObjectManager = moduleBase + 0x237CB28;
std::vector<unsigned int> countOffset = { 0x20 };

uintptr_t addr = FindDMAAddy(hProcess, pObjectManager, countOffset);

int totalObjects = 0;

ReadProcessMemory(hProc, (BYTE*)addr, &totalObjects, sizeof(totalObjects), 0);

std::cout << "Current objects = " << totalObjects << std::endl;
```

Body:
I'm trying to read a value from a pointer address + offset and not getting the correct result.

I have the following (relevant pieces) of code:

uintptr_t moduleBase = GetModuleBaseAddress(procId, L"ProgramImReading.exe");
uintptr_t pObjectManager = moduleBase + 0x237CB28;
std::vector<unsigned int> countOffset = { 0x20 };

uintptr_t totalObjects = FindDMAAddy(hProcess, pObjectManager, countOffset);
std::cout << "Current objects = " << totalObjects << std::endl;

FindDMAAddy:

    uintptr_t FindDMAAddy(HANDLE hProc, uintptr_t ptr, std::vector<unsigned int> offsets)
{
    uintptr_t   addr = ptr;
    for (unsigned int i = 0; i < offsets.size(); ++i)
    {
        ReadProcessMemory(hProc, (BYTE*)addr, &addr, sizeof(addr), 0);
        addr += offsets[i];
    }
    return addr;
}

For some reason this will not work. I can confirm the addresses are correct by opening cheat engine and entering GameAdress + Pointer, then setting the offset + 20 and getting the correct value.

When i run the code above I get a long random value "2596411228208"

I can also find the current dynamic address the pointer is pointing to and read directly from that address, but when I try to read from the pointer + offset It does not work right.


问:
Java date timezone to GMT and convert to another format
I have a list of dates. Example:

```<code>Tue Oct 21 17:05:37 EDT 2014
Tue Oct 22 18:05:37 IST 2014
Tue Oct 23 19:05:37 EST 2014
</code>```

Since all dates are in dfferent timezone, i want to convert all dates to GMT zone and then convert all dates to yyyy-MM-dd'T'HH:mm:ss format. ie, like this 2014-10-21T17:05:37 .

How can i do this?

Thanks

答:
java.time

Use modern java.time classes rather than the troublesome legacy classes seen in the other Answer.  Specifically, the ZonedDateTime class.

By the way, those input string formats are terrible. Especially the use of EDT, IST, and such. Those are not true time zones. These are real time zone names. Those pseudo-zones are not standardized, and are not even unique! So the ZonedDateTime class will take a guess as to what you might mean, but the results may be other than you intended. For example, is IST Irish Standard Time or India Standard Time?

Instead, use only the standard ISO 8601 formats when exchanging date-time values as text.

I fixed your faulty input strings (Tuesday = 21, 22, and 23?).

```<code>List < String > inputs = List.of(
        "Tue Oct 21 17:05:37 EDT 2014" ,
        "Wed Oct 22 18:05:37 IST 2014" ,
        "Thu Oct 23 19:05:37 EST 2014"
);
</code>```

Define a formatting pattern to match your inputs.

```<code>DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" ).withLocale( Locale.US );
</code>```

Loop the inputs, attempting to parse each. Again, no guarantee as to the right time zone being guessed for your pseudo-zones.

```<code>for ( String input : inputs )
{
    ZonedDateTime zdt = ZonedDateTime.parse( input , f );
    System.out.println( "zdt.toString() = " + zdt );
}
</code>```

When run.

zdt.toString() = 2014-10-21T17:05:37-04:00[America/New_York]

zdt.toString() = 2014-10-22T18:05:37Z[Atlantic/Reykjavik]

zdt.toString() = 2014-10-23T19:05:37-04:00[America/New_York]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ContentLicense: CC BY-SA 3.0

Body:
I have a list of dates. Example:

Tue Oct 21 17:05:37 EDT 2014
Tue Oct 22 18:05:37 IST 2014
Tue Oct 23 19:05:37 EST 2014

Since all dates are in dfferent timezone, i want to convert all dates to GMT zone and then convert all dates to yyyy-MM-dd'T'HH:mm:ss format. ie, like this 2014-10-21T17:05:37 .

How can i do this?

Thanks

Body:
java.time

Use modern java.time classes rather than the troublesome legacy classes seen in the other Answer.  Specifically, the ZonedDateTime class.

By the way, those input string formats are terrible. Especially the use of EDT, IST, and such. Those are not true time zones. These are real time zone names. Those pseudo-zones are not standardized, and are not even unique! So the ZonedDateTime class will take a guess as to what you might mean, but the results may be other than you intended. For example, is IST Irish Standard Time or India Standard Time?

Instead, use only the standard ISO 8601 formats when exchanging date-time values as text.

I fixed your faulty input strings (Tuesday = 21, 22, and 23?).

List < String > inputs = List.of(
        "Tue Oct 21 17:05:37 EDT 2014" ,
        "Wed Oct 22 18:05:37 IST 2014" ,
        "Thu Oct 23 19:05:37 EST 2014"
);

Define a formatting pattern to match your inputs.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" ).withLocale( Locale.US );

Loop the inputs, attempting to parse each. Again, no guarantee as to the right time zone being guessed for your pseudo-zones.

for ( String input : inputs )
{
    ZonedDateTime zdt = ZonedDateTime.parse( input , f );
    System.out.println( "zdt.toString() = " + zdt );
}

When run.

zdt.toString() = 2014-10-21T17:05:37-04:00[America/New_York]

zdt.toString() = 2014-10-22T18:05:37Z[Atlantic/Reykjavik]

zdt.toString() = 2014-10-23T19:05:37-04:00[America/New_York]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
How to customize error pages served via the default backend of an nginx ingress controller?
I'm running an Nginx Ingress Controller installed via Helm on my Kubernetes cluster. I would like to change the HTML/CSS in the default backend service for some specific errors (e.g. 404). </p>

<p>This link provides  some general information about the default backend. However, there is no mention of how to actually customize the served HTML/CSS files. </p>

答:
You need to create and deploy custom default backend which will return a custom error page.Follow the doc to deploy a custom default backend and configure nginx ingress controller by modifying the deployment yaml to use this custom default backend.

The deployment yaml for the custom default backend is here and the source code is here.

Body:
I'm running an Nginx Ingress Controller installed via Helm on my Kubernetes cluster. I would like to change the HTML/CSS in the default backend service for some specific errors (e.g. 404).

This link provides  some general information about the default backend. However, there is no mention of how to actually customize the served HTML/CSS files.


问:
Dynamic Prepared Statement Readymade Function that Prepare Statement ONLY ONCE

I want a function that prepare statement only once. ( Not every time whenever function called for the same Query ).

  Because One of Advantage of Prepared Statement is: preparation on the query is done only once (although the statement is executed multiple times)

So whenever I call this Function it will Prepare Statement every time and it's not proper because we will miss taking one of the biggest advantage of Prepared Statement. So that, I put the Condition if( !empty($stmtName) and !isset($GLOBALS[$stmtName]) ) that Check Statement is Already set or not. ( If not then and only then Statement will prepare ) using this we will cover that advantage. But, It generates Binding Parameter failed ERROR.

My Function is here...

```<code>function qryInsert( $stmtName, $table, $field, $params, $formats )
    {

        $query = " INSERT INTO ".$table
                ." ".( (isset($field) and !empty($field)) ? " ( ".(implode(", ",$field))." ) " : " " ). " "
                ." VALUES( ". implode(", ", array_map(function($val) { return "?"; }, $field))." ) ";

        /*if(!isset($con) or empty($con))
        {
            $con = $this->connection();
        }*/

        $a_params = array();

        $a_params = array();

        $param_type = '';
        $n = count($formats);

        for($i = 0; $i < $n; $i++)
        {
            $param_type .= $formats[$i];
        }

        $a_params[] = & $param_type;

        for($i = 0; $i < $n; $i++)
        {
            $a_params[] = & $params[$i];
        }

        if( !empty($stmtName) and !isset($GLOBALS[$stmtName]) )
        {
            $GLOBALS[$stmtName] = $GLOBALS['con']->prepare($query);
            // $stmt = $con->prepare($query);
        }

        if(!($GLOBALS[$stmtName]))
        {
            echo " Prepare failed: (" . $con->errno . ") " . $con->error; // . " <br> Query : <span style='color:tomato;'> ".$query." </span>"
        }
        else
        {

            if(!(call_user_func_array(array($GLOBALS[$stmtName], 'bind_param'), $a_params)))
            {
                echo "Binding parameters failed: (" . $GLOBALS[$stmtName]->errno . ") " . $GLOBALS[$stmtName]->error;
            }
            else
            {
                if(!($GLOBALS[$stmtName]->execute()))
                {
                    echo "Execute failed: (" . $GLOBALS[$stmtName]->errno . ") " . $GLOBALS[$stmtName]->error;
                }
                else
                {
                    if($meta = $GLOBALS[$stmtName]->result_metadata())
                    {
                        while ($field = $meta->fetch_field())
                        {
                            $columns[] = &$row[$field->name];
                        }

                        if(call_user_func_array(array($GLOBALS[$stmtName], 'bind_result'), $columns))
                        {
                            while ($GLOBALS[$stmtName]->fetch())
                            {
                                foreach($row as $key => $val)
                                {
                                    $x[$key] = $val;
                                }
                                $results[] = $x;
                            }
                        }
                        else
                        {
                            echo " Error occur while Bindig Result...";
                        }
                    }
                }
            }
        }

        $GLOBALS[$stmtName]->close();

        return $results;
    }
</code>```

INPUT:

```<code>qryInsert("insStud", "student_master", array("roll_no","name"), array(21,"Mahetab"), array("i","s"));
qryInsert("insStud", "student_master", array("roll_no","name"), array(8,"Sahil"), array("i","s"));
qryInsert("insStud", "student_master", array("roll_no","name"), array(10,"Mahammad"), array("i","s"));
</code>```

OUTPUT:

```<code>First time Record will Insert...
After that raised Binding Parameter failed error...
</code>```

Without this Condition if( !empty($stmtName) and !isset($GLOBALS[$stmtName]) )

My Code is Work Fine... It havn't any issue... Because It will prepare statement everytime

I used $GLOBALS variable so that whenever function called it uses same GLOBALS variable Otherwise function Perform operation with their private variable which doesn't work properly

答:
Problem Solved...

Just wants to remove $GLOBALS[$stmtName]->close(); statement...

Because It closed statement every time function called...

So, that Binding Parameters failed...

Body:
I want a function that prepare statement only once. ( Not every time whenever function called for the same Query ).

  Because One of Advantage of Prepared Statement is: preparation on the query is done only once (although the statement is executed multiple times)

So whenever I call this Function it will Prepare Statement every time and it's not proper because we will miss taking one of the biggest advantage of Prepared Statement. So that, I put the Condition if( !empty($stmtName) and !isset($GLOBALS[$stmtName]) ) that Check Statement is Already set or not. ( If not then and only then Statement will prepare ) using this we will cover that advantage. But, It generates Binding Parameter failed ERROR.

My Function is here...

function qryInsert( $stmtName, $table, $field, $params, $formats )
    {

        $query = " INSERT INTO ".$table
                ." ".( (isset($field) and !empty($field)) ? " ( ".(implode(", ",$field))." ) " : " " ). " "
                ." VALUES( ". implode(", ", array_map(function($val) { return "?"; }, $field))." ) ";

        /*if(!isset($con) or empty($con))
        {
            $con = $this->connection();
        }*/

        $a_params = array();

        $a_params = array();

        $param_type = '';
        $n = count($formats);

        for($i = 0; $i < $n; $i++)
        {
            $param_type .= $formats[$i];
        }

        $a_params[] = & $param_type;

        for($i = 0; $i < $n; $i++)
        {
            $a_params[] = & $params[$i];
        }

        if( !empty($stmtName) and !isset($GLOBALS[$stmtName]) )
        {
            $GLOBALS[$stmtName] = $GLOBALS['con']->prepare($query);
            // $stmt = $con->prepare($query);
        }

        if(!($GLOBALS[$stmtName]))
        {
            echo " Prepare failed: (" . $con->errno . ") " . $con->error; // . "
 Query :  ".$query." "
        }
        else
        {

            if(!(call_user_func_array(array($GLOBALS[$stmtName], 'bind_param'), $a_params)))
            {
                echo "Binding parameters failed: (" . $GLOBALS[$stmtName]->errno . ") " . $GLOBALS[$stmtName]->error;
            }
            else
            {
                if(!($GLOBALS[$stmtName]->execute()))
                {
                    echo "Execute failed: (" . $GLOBALS[$stmtName]->errno . ") " . $GLOBALS[$stmtName]->error;
                }
                else
                {
                    if($meta = $GLOBALS[$stmtName]->result_metadata())
                    {
                        while ($field = $meta->fetch_field())
                        {
                            $columns[] = &$row[$field->name];
                        }

                        if(call_user_func_array(array($GLOBALS[$stmtName], 'bind_result'), $columns))
                        {
                            while ($GLOBALS[$stmtName]->fetch())
                            {
                                foreach($row as $key => $val)
                                {
                                    $x[$key] = $val;
                                }
                                $results[] = $x;
                            }
                        }
                        else
                        {
                            echo " Error occur while Bindig Result...";
                        }
                    }
                }
            }
        }

        $GLOBALS[$stmtName]->close();

        return $results;
    }

INPUT:

qryInsert("insStud", "student_master", array("roll_no","name"), array(21,"Mahetab"), array("i","s"));
qryInsert("insStud", "student_master", array("roll_no","name"), array(8,"Sahil"), array("i","s"));
qryInsert("insStud", "student_master", array("roll_no","name"), array(10,"Mahammad"), array("i","s"));

OUTPUT:

First time Record will Insert...
After that raised Binding Parameter failed error...

Without this Condition if( !empty($stmtName) and !isset($GLOBALS[$stmtName]) )

My Code is Work Fine... It havn't any issue... Because It will prepare statement everytime

I used $GLOBALS variable so that whenever function called it uses same GLOBALS variable Otherwise function Perform operation with their private variable which doesn't work properly


问:
variable decimal places in .Net string formatters?
Fixed decimal places is easy

```<code>String.Format("{0:F1}", 654.321);
</code>```

gives

```<code>654.3
</code>```

How do I feed the number of decimal places in as a parameter like you can in C?
So

```<code>String.Format("{0:F?}", 654.321, 2);
</code>```

gives

```<code>654.32
</code>```

I can't find what should replace the ?

答:
Another option is using interpolated strings like this:

```<code>int prec = 2;
string.Format($"{{0:F{prec}}}", 654.321);
</code>```

Still a mess, but yet more convenient IMHO. Notice that string interpolation replaces double braces, like {{, with a single brace.

Body:
Fixed decimal places is easy

String.Format("{0:F1}", 654.321);

gives

654.3

How do I feed the number of decimal places in as a parameter like you can in C?
So

String.Format("{0:F?}", 654.321, 2);

gives

654.32

I can't find what should replace the ?

Body:
Another option is using interpolated strings like this:

int prec = 2;
string.Format($"{{0:F{prec}}}", 654.321);

Still a mess, but yet more convenient IMHO. Notice that string interpolation replaces double braces, like {{, with a single brace.


问:
How to make regex work on corner case email address

Possible Duplicates:

  Email Validation - Regular Expression

  What is the best regular expression for validating email addresses?

Hi All,

I have an email address roughly like this,

firstname.lastname@4domain.co.nz

Which doesn't work with the regex I have here for email addresses. It doesn't seem to like the 4 at the start of the domain.

```<code>private const string MatchEmailPattern =
        @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
</code>```

Most other corner cases work well with this regex, all of the below are rejected,

```<code>        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));
</code>```

Any other regexes people can suggest for emails that will work with the above?

Also the above regex has the advantage that it works with addresses like this, and a lot of them don't,

firstname.lastname_@gmail.com

答:
http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

If you want to fully implement an e-mail regex, might as well do it right.

</sarcasm>

Given the ludicrous complexity of the e-mail address spec, fully matching compliant addresses while rejecting all non-compliant addresses is rather difficult to do with a regular expression.

The best method of validating an e-mail address is to require simple proper form (meaning, has an @ sign, and after the @ sign, there is atleast a single period) and then just send an e-mail to the address.

Technically speaking, a well-formed address to "example.com" will never be delivered, because "example.com" is a reserved name.  Or sending an e-mail to "askjgdaiuyvbcxakjh.com".  That domain doesn't exist, but your regex check would return valid, while the simple "send a message, click a link" method would successfully reject all e-mail addresses that you can't contact.

Body:
Possible Duplicates:

  Email Validation - Regular Expression

  What is the best regular expression for validating email addresses?

Hi All,

I have an email address roughly like this,

firstname.lastname@4domain.co.nz

Which doesn't work with the regex I have here for email addresses. It doesn't seem to like the 4 at the start of the domain.

private const string MatchEmailPattern =
        @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
        @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
        @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
        @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

Most other corner cases work well with this regex, all of the below are rejected,

        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".a@test.com"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress(".@s.dd"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@988.120.150.10"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("ab@120.256.256.120"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("2@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("-@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("..@bde.cc"));
        Assert.IsFalse(EmailValidator.IsValidEmailAddress("_@bde.cc"));

Any other regexes people can suggest for emails that will work with the above?

Also the above regex has the advantage that it works with addresses like this, and a lot of them don't,

firstname.lastname_@gmail.com


问:
Is it possible to center text in select box?
I tried this: http://jsfiddle.net/ilyaD/KGcC3/

HTML:

<select name="state" class="ddList">
    <option value="">(please select a state)</option>
    <option class="lt" value="--">none</option>
    <option class="lt" value="AL">Alabama</option>
    <option class="lt" value="AK">Alaska</option>
    <option class="lt" value="AZ">Arizona</option>
    <option class="lt" value="AR">Arkansas</option>
    <option class="lt" value="CA">California</option>
    <option class="lt" value="CO">Colorado</option>
</select>
```

<p>CSS:</p>

<pre class="lang-css prettyprint-override"><code>select { width: 400px; text-align: center; }
select .lt { text-align: center; }
</code>```

As you can see, it doesn't work.  Is there a CSS-only way to center text in the select-box?

答:
2020, Im using:</p>

```<code>select {
    text-align: center;
    text-align-last: center;
    -moz-text-align-last: center;
}
</code>```

Body:
I tried this: http://jsfiddle.net/ilyaD/KGcC3/

HTML:

<select name="state" class="ddList">
    <option value="">(please select a state)</option>
    <option class="lt" value="--">none</option>
    <option class="lt" value="AL">Alabama</option>
    <option class="lt" value="AK">Alaska</option>
    <option class="lt" value="AZ">Arizona</option>
    <option class="lt" value="AR">Arkansas</option>
    <option class="lt" value="CA">California</option>
    <option class="lt" value="CO">Colorado</option>
</select>

CSS:

select { width: 400px; text-align: center; }
select .lt { text-align: center; }

As you can see, it doesn't work.  Is there a CSS-only way to center text in the select-box?

Body:
2020, Im using:

select {
    text-align: center;
    text-align-last: center;
    -moz-text-align-last: center;
}


问:
How to get current user data from firebase realtime database in React Native
I'm trying to get current signed user's image and name from the firebase realtime database in which his data was stored when he signup. I want to put these two items in the drawer header. enter image description hereYou can see the attached screenshots.

Here is the current user

here is the data of the current user. I want to get that data on the basis of current user signed in

答:
Try making an async function so you can retrieve data from any user with just the UID like this:

```<code>export async function getUserByUID(UID) {
  return await firebase.database().ref(`Users/${UID}`).once('value');
}
</code>```

Later you can simply pass the UID and get any users' data:

```<code>const getMyData = async () => {
  let UID = firebase.auth().currentUser.uid;
  let userData = await getUserDataByUID(UID);
  // this will be null if there's no user data
  // all users' data will be in userData for example:
  console.log(userData.image) // will log the image url you saved.
}
</code>```

BTW don't forget your firebase database rules! The last thing you want is other seeing those passwords!!

Body:
Try making an async function so you can retrieve data from any user with just the UID like this:

export async function getUserByUID(UID) {
  return await firebase.database().ref(`Users/${UID}`).once('value');
}

Later you can simply pass the UID and get any users' data:

const getMyData = async () => {
  let UID = firebase.auth().currentUser.uid;
  let userData = await getUserDataByUID(UID);
  // this will be null if there's no user data
  // all users' data will be in userData for example:
  console.log(userData.image) // will log the image url you saved.
}

BTW don't forget your firebase database rules! The last thing you want is other seeing those passwords!!


答:
Honestly? I might be unpopular for saying this, but why not just match

.+@.+

Minimalist but functional for 90% of cases.

Title: How to make regex work on corner case email address


问:
How to install free SSL on subdomain lumen/laravel on Cpanel?
I just wanna ask on how can I install a free SSL (wildcard) on my subdomain URL on cPanel that is built on Lumen.

My Subdomain is pointed on path public_html/*lumen_app/public folder and free SSL is requiring to make a .well-known/acme-challenge folder on public_html and when I verify it the page cannot be accessed by the ACME server.

Help is greatly appreciated. TIA!

答:
when you make subdomain in cPanel , cPanel make directory for this in file manager and you must make .well-known/acme-challenge on that directory . this is root directory for your subdomain .

for install free SSL try this site sslforfree and you can install to sub domain in

cPanel - SECURITY - SSL/TLS

but you can install let’s Encrypt extension on cPanel by this command :

```<code>yum -y install letsencrypt-cpanel
</code>```

and install SSL on domain and subdomain in cPanel Simply

Body:
when you make subdomain in cPanel , cPanel make directory for this in file manager and you must make .well-known/acme-challenge on that directory . this is root directory for your subdomain .

for install free SSL try this site sslforfree and you can install to sub domain in

cPanel - SECURITY - SSL/TLS

but you can install let’s Encrypt extension on cPanel by this command :

yum -y install letsencrypt-cpanel

and install SSL on domain and subdomain in cPanel Simply


问:
Convert 3D model (obj or gltf) to < div's> and CSS
Is there any possibility to convert 3D element (obj or gltf details and relevant nodal coordinates) into HTML < div's> and CSS to recreate the same object.</p>

答:
Take a look of this;

https://github.com/lucascassiano/cinema4d-3divs

Cinema4D(Python) Script to export 3D planes as 3D React Components

with some changes it could work.

Body:
Is there any possibility to convert 3D element (obj or gltf details and relevant nodal coordinates) into HTML
 and CSS to recreate the same object.


问:
Is it possible to run multiple web instance in the same AWS EC2?
Background

I have followed this tutorial https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-cli-tutorial-ec2.html, composed a docker compose file, made a website A (compose of 4 containers) up and run serving 1 of my client.

However, now I have another client which I need to host another web site website B using similar strategies as above.

Here is the current running service of ECS / EC2

and here are the containers up and running, serving website A now

Questions & concerns

The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B. I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

And the domain name, through route 53, I have registered a domain www.websiteA.com to serve the 1st website, I have also registered another www.websiteB.com preparing to serve website B, in my case, I guess I need to configure the new domain B pointing to the same EC2 IP?

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

I want to clear all the concepts before kick-starting to deploy the website B, appreciate for any help, thank you

Follow-up actions

I come up decided to use AWS application load balancer to solve my issue, and have the following configurations setup.

I first look into load balancer

And configured as follows

I setup a load balancer which listens for requests using HTTP protocol with incoming port 80, whenever there are users access the web server (i.e.: the frontend container), listener will forward that request to the target group (i.e.: http-port-80-access)

And here is the target group (http-port-80-access) which contains a registered target (currently my ec2 instance running the containers), the host port of the container is 32849 which in turn made used by the associated load balancer (web-access-load-balancer) for dynamic port mapping.

I have also configured 1 more rule on top of the default rule, whenever user access url of websiteA, load balancer will forward the request to the target group (http-port-80-access).

All things set, and the healthy test also passed. I then used the following ecs-cli compose service up command to wire up the load balancer with the service

ecs-cli compose --file ./docker-compose-aws-prod.yml --cluster my-ecs-cluster-name --ecs-profile my-ecs-profile --cluster-config my-cluster --project-name my-project --ecs-params ./ecs-params.yml service up --target-group-arn arn:aws:elasticloadbalancing:us-east-2:xxxxxxxxx:targetgroup/http-port-80-access/xxxxxxxx --container-name frontend --container-port 80
```

where frontend is the service name of the frontend container of website A

However, turn out when I access www.websiteA.com through browser, nothing but ERR_CONNECTION_REFUSED, accessing www.websiteA.com:32849 did accessible, but is not what I desired.

I am wondering which part I configured wrongly

答:
The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

Indeed. However - as you already found out, you have to split the traffic based on something (hostname, path,..). That's where the reverse-proxy comes in play (either managed - ALB, NLB or your own - nginx, haproxy,.. ) .

It's simple for the http traffic (based on the host)

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B.

assuming the ports 27017 and the 3002 are using own binary protocol (not http). You will have handle that.

You can in theory define the port mapping (map different public listening port to these custom ports), but then you need to either use NLB (network load balancer) or expose the ports on hosts public IP. In the latter case I'm not sure with ECS you can guarantee which IP is used (e.g. having multiple worker nodes)

I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

ALB is layer 7 reverse proxy (http), it is imho the best option for the  web access, not for binary protocols.

, I guess I need to configure the new domain B pointing to the same EC2 IP?

that's the plan

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

shouldn't be a problem

Body:
Background

I have followed this tutorial https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-cli-tutorial-ec2.html, composed a docker compose file, made a website A (compose of 4 containers) up and run serving 1 of my client.

However, now I have another client which I need to host another web site website B using similar strategies as above.

Here is the current running service of ECS / EC2

and here are the containers up and running, serving website A now

Questions & concerns

The website A is now situated as 1 of a service in the EC2 under my only cluster, can I use the same EC2 instance and run website B (as another service of the EC2)?

If so, how are the ports / inbound / outbound traffic being managed? Now website A already occupies port 80, 443, 27017 and 3002 of the EC2 instance for inbound traffic, if website B's containers also run in the same EC2 instances, can I still use port 80, 443, 27017 and 3002 for website B. I have read the docs of ALB (Amazon Load Balancer), seems it can fulfill the requirement, am I at the right track?

And the domain name, through route 53, I have registered a domain www.websiteA.com to serve the 1st website, I have also registered another www.websiteB.com preparing to serve website B, in my case, I guess I need to configure the new domain B pointing to the same EC2 IP?

During my deployment of website B, I do not want to affect the availability of website A, can it be maintained during the process of deploying website B's containers?

I want to clear all the concepts before kick-starting to deploy the website B, appreciate for any help, thank you

Follow-up actions

I come up decided to use AWS application load balancer to solve my issue, and have the following configurations setup.

I first look into load balancer

And configured as follows

I setup a load balancer which listens for requests using HTTP protocol with incoming port 80, whenever there are users access the web server (i.e.: the frontend container), listener will forward that request to the target group (i.e.: http-port-80-access)

And here is the target group (http-port-80-access) which contains a registered target (currently my ec2 instance running the containers), the host port of the container is 32849 which in turn made used by the associated load balancer (web-access-load-balancer) for dynamic port mapping.

I have also configured 1 more rule on top of the default rule, whenever user access url of websiteA, load balancer will forward the request to the target group (http-port-80-access).

All things set, and the healthy test also passed. I then used the following ecs-cli compose service up command to wire up the load balancer with the service

ecs-cli compose --file ./docker-compose-aws-prod.yml --cluster my-ecs-cluster-name --ecs-profile my-ecs-profile --cluster-config my-cluster --project-name my-project --ecs-params ./ecs-params.yml service up --target-group-arn arn:aws:elasticloadbalancing:us-east-2:xxxxxxxxx:targetgroup/http-port-80-access/xxxxxxxx --container-name frontend --container-port 80

where frontend is the service name of the frontend container of website A

However, turn out when I access www.websiteA.com through browser, nothing but ERR_CONNECTION_REFUSED, accessing www.websiteA.com:32849 did accessible, but is not what I desired.

I am wondering which part I configured wrongly


问:
Big O of Ugly Numbers Algorithm (Brute force method)
Link to problem: Ugly Numbers

How would you find the Big O of the brute force (Simple Method Approach) solution for Ugly-Numbers.

I see that for this part of the code:

```<code>    /* Function to check if a number is ugly or not */
int isUgly(int no)
{
  no = maxDivide(no, 2);
  no = maxDivide(no, 3);
  no = maxDivide(no, 5);

  return (no == 1)? 1 : 0;
}
</code>```

Each step takes log_2(x) + log_3(x) + log_5(x) steps, where x = no

So this would mean the runtime is (log_2(x) + log_3(x) + log_5(x))n where x is the result of the output. However, the result of an algorithm can't be a part of the Big O notation right? If it can't, this would be reduced to cn right? Where c > result. What is the proper method of proof for this?

答:
The complexity of isUgly method is O(log N), where N is the input. Because the complexity of maxDivide is O(log N) and calling that function a fixed amount of times (3 in this case) does not change the complexity.

However, the result of an algorithm can't be a part of the Big O notation right?

Yes, the result of a function is irrelevant while calculating the complexity of that function.

The time complexity of the getNthUglyNo is unknown or ~infinite! For N=500 it runes 937500 times!

Body:
Link to problem: Ugly Numbers

How would you find the Big O of the brute force (Simple Method Approach) solution for Ugly-Numbers.

I see that for this part of the code:

    /* Function to check if a number is ugly or not */
int isUgly(int no)
{
  no = maxDivide(no, 2);
  no = maxDivide(no, 3);
  no = maxDivide(no, 5);

  return (no == 1)? 1 : 0;
}

Each step takes log_2(x) + log_3(x) + log_5(x) steps, where x = no

So this would mean the runtime is (log_2(x) + log_3(x) + log_5(x))n where x is the result of the output. However, the result of an algorithm can't be a part of the Big O notation right? If it can't, this would be reduced to cn right? Where c > result. What is the proper method of proof for this?


问:
how to general search from [array] of string
I have a mongodb of recipes and I want to dynamically create a general search query resulting in:

```<code>{ $all: [/potato/i, /onion/i, /garlic/i, /chicken/i] }
</code>```

Without quotation marks from a string like:

```<code>const str = 'potato onion garlic chicken'
</code>```

I've attempted:

```<code>const arr = []
str.split(' ').forEach(element => {
  arr.push(`/${element}/i`)
})
console.log(arr)
</code>```

The problem is I end up with strings:

```<code>//[ '/potato/i', '/onion/i', '/garlic/i', '/chicken/i' ]
</code>```

How do can I dynamically create this query without stringifying?

答:
Just a similar version I have tried:

const foodArr = 'potato onion garlic chicken';
queryArr = [];

foodArr.split(' ').forEach(foodElem => {
    queryArr.push(new RegExp(`${foodElem}`, 'i'));
});

console.log(queryArr);```

Body:
I have a mongodb of recipes and I want to dynamically create a general search query resulting in:

{ $all: [/potato/i, /onion/i, /garlic/i, /chicken/i] }

Without quotation marks from a string like:

const str = 'potato onion garlic chicken'

I've attempted:

const arr = []
str.split(' ').forEach(element => {
  arr.push(`/${element}/i`)
})
console.log(arr)

The problem is I end up with strings:

//[ '/potato/i', '/onion/i', '/garlic/i', '/chicken/i' ]

How do can I dynamically create this query without stringifying?


问:
C programming function calling to return values
I'm a college student in my first year of software engineering. I am in the fourth week of my semester and am having trouble in my programming class. Currently, I was given this assignment in which I was given a function called "getNum()" and I had to use it in another function where the program user, would input a number and the function that I program (must be named isOdd()) would determine if the number is odd or even. Then the main function would print whether the number is odd or even. This is the way that my professor worded it:

" Write a program that uses the getNum() function provided to you in Assignment 2 to get anumber from the user (prompting them first, as always). Create and use a function called isOddwith parameters (the number) and return values (1 ifthe number is odd, 0 if the number is evenOR use a bool or boolean data type, your choice) to determine if thenumber is odd. In main(), tell the user (by displaying using printf()or cout) whether the number is evenor odd."

Now, the problem I am having is understanding programming as I am fairly new to it and some words confuse me, such as parameter and return value. To give you and idea of what I have written so far,

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

int isOdd(int numInput);
int getNum(void);

int main(void)
{
    int number = 0;
    while (number > -1)
    {
        if (isOdd(0))
        {
            printf("The number is even.\n");
        }
        else if (isOdd(1))
        {
            printf("The number is odd.\n");
        }
    }

    return 0;
}

int isOdd(int numInput)
{
    int myNumber = 0;
    printf("Please enter a number: ", numInput);
    myNumber = getNum();

    if (myNumber % 2 == 0)
    {
        myNumber == 0;
    }
    else
    {
        myNumber == 1;
    }
    return myNumber;
}

#pragma warning(disable: 4996)
int getNum(void)
{
    /* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
    char record[121] = { 0 }; /* record stores the string */
    int number = 0;
    /* NOTE to student: indent and brace this function consistent with your others */
    /* use fgets() to get a string from the keyboard */
    fgets(record, 121, stdin);
    /* extract the number from the string; sscanf() returns a number
     * corresponding with the number of items it found in the string */
    if (sscanf(record, "%d", &number) != 1)
    {
        /* if the user did not enter a number recognizable by
         * the system, set number to -1 */
        number = -1;
    }
    return number;
}
</code>```

This is what I have written, trying to do things accordingly to my professor's instructions, as I do not yet know how to properly use booleans. As you can see, at the bottom is the getNum() function that my professor has said is mandatory for this assignment. As of now, everything I input, I am told is even. I am not asking for you guys to solve and do everything for me but I want to understand what I am doing wrong, what my thinking is doing wrong and to overall better my understanding for future programming. Thank you

答:
The function:

```<code>int getNum(void)
</code>```

Takes no parameters (void), and returns an integer (int) value.  The function itself accepts input from the standard input (stdin) stream - this is normally from the keyboard.

To complete your assignment you should write a function:

```<code>int isOdd( int value ) ;
</code>```

Where value is an integer parameter and the return value is 1 if value is odd and 0 if it is even.  Alternatively you are allowed to use the Boolean type:

```<code>#include "bool.h"

bool isOdd( int value ) ;
</code>```

In which case you would return true for odd, and false for even.

Your isOdd() includes the getNumber() call and user prompt code.  Not only is that not specified in the assignment, it is poor design making isOdd() difficult to use in more general situations.  The assignment explicitly requires you to pass the value to be tested as a parameter.

The assignment does not require you to iterate the test (the while loop is not needed). The user input prompt and acceptance should be in main as follows:

```<code>int main(void)
{
    printf( "Please enter a number: " ) ;
    fflush( stdin ) ; // you'll may this on some platforms

    int myNumber = getNum();

    if( isOdd( myNumber ) )
    {
        printf("The number is odd.\n");
    }
    else
    {
        printf("The number is even.\n");
    }
}
return 0;
</code>```

}

Note that there are only two possible outcomes, so you do not need an else if( !isOdd( myNumber ) ... - if it is not odd it is implicitly even.

Your isOdd() function will work, but is over complicated.  You are required to return a Boolean (a type with two possible values true/false - or an integer 1/0 which can be implicitly converted to a Boolean), and (myNumber % 2 == 0) is a Boolean expression (an expression with two possible results true or false).  Anywhere you see the pattern:

```<code>if( <boolean expression> )
{
   b = true ;
}
else
{
   b = false ;
}
</code>```

you can simply write:

```<code>b = <boolean expression> ;
</code>```

In your case the Boolean determination of odd-ness is simply value % 2 != 0.  You can return that directly:

```<code>bool isOdd( int value )
{
    return value % 2 != 0 ;
}
</code>```

Body:
I'm a college student in my first year of software engineering. I am in the fourth week of my semester and am having trouble in my programming class. Currently, I was given this assignment in which I was given a function called "getNum()" and I had to use it in another function where the program user, would input a number and the function that I program (must be named isOdd()) would determine if the number is odd or even. Then the main function would print whether the number is odd or even. This is the way that my professor worded it:

" Write a program that uses the getNum() function provided to you in Assignment 2 to get anumber from the user (prompting them first, as always). Create and use a function called isOddwith parameters (the number) and return values (1 ifthe number is odd, 0 if the number is evenOR use a bool or boolean data type, your choice) to determine if thenumber is odd. In main(), tell the user (by displaying using printf()or cout) whether the number is evenor odd."

Now, the problem I am having is understanding programming as I am fairly new to it and some words confuse me, such as parameter and return value. To give you and idea of what I have written so far,

#include <stdio.h>

int isOdd(int numInput);
int getNum(void);

int main(void)
{
    int number = 0;
    while (number > -1)
    {
        if (isOdd(0))
        {
            printf("The number is even.\n");
        }
        else if (isOdd(1))
        {
            printf("The number is odd.\n");
        }
    }

    return 0;
}

int isOdd(int numInput)
{
    int myNumber = 0;
    printf("Please enter a number: ", numInput);
    myNumber = getNum();

    if (myNumber % 2 == 0)
    {
        myNumber == 0;
    }
    else
    {
        myNumber == 1;
    }
    return myNumber;
}

#pragma warning(disable: 4996)
int getNum(void)
{
    /* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
    char record[121] = { 0 }; /* record stores the string */
    int number = 0;
    /* NOTE to student: indent and brace this function consistent with your others */
    /* use fgets() to get a string from the keyboard */
    fgets(record, 121, stdin);
    /* extract the number from the string; sscanf() returns a number
     * corresponding with the number of items it found in the string */
    if (sscanf(record, "%d", &number) != 1)
    {
        /* if the user did not enter a number recognizable by
         * the system, set number to -1 */
        number = -1;
    }
    return number;
}

This is what I have written, trying to do things accordingly to my professor's instructions, as I do not yet know how to properly use booleans. As you can see, at the bottom is the getNum() function that my professor has said is mandatory for this assignment. As of now, everything I input, I am told is even. I am not asking for you guys to solve and do everything for me but I want to understand what I am doing wrong, what my thinking is doing wrong and to overall better my understanding for future programming. Thank you

Body:
The function:

int getNum(void)

Takes no parameters (void), and returns an integer (int) value.  The function itself accepts input from the standard input (stdin) stream - this is normally from the keyboard.

To complete your assignment you should write a function:

int isOdd( int value ) ;

Where value is an integer parameter and the return value is 1 if value is odd and 0 if it is even.  Alternatively you are allowed to use the Boolean type:

#include "bool.h"

bool isOdd( int value ) ;

In which case you would return true for odd, and false for even.

Your isOdd() includes the getNumber() call and user prompt code.  Not only is that not specified in the assignment, it is poor design making isOdd() difficult to use in more general situations.  The assignment explicitly requires you to pass the value to be tested as a parameter.

The assignment does not require you to iterate the test (the while loop is not needed). The user input prompt and acceptance should be in main as follows:

int main(void)
{
    printf( "Please enter a number: " ) ;
    fflush( stdin ) ; // you'll may this on some platforms

    int myNumber = getNum();

    if( isOdd( myNumber ) )
    {
        printf("The number is odd.\n");
    }
    else
    {
        printf("The number is even.\n");
    }
}
return 0;

}

Note that there are only two possible outcomes, so you do not need an else if( !isOdd( myNumber ) ... - if it is not odd it is implicitly even.

Your isOdd() function will work, but is over complicated.  You are required to return a Boolean (a type with two possible values true/false - or an integer 1/0 which can be implicitly converted to a Boolean), and (myNumber % 2 == 0) is a Boolean expression (an expression with two possible results true or false).  Anywhere you see the pattern:

if( <boolean expression> )
{
   b = true ;
}
else
{
   b = false ;
}

you can simply write:

b = <boolean expression> ;

In your case the Boolean determination of odd-ness is simply value % 2 != 0.  You can return that directly:

bool isOdd( int value )
{
    return value % 2 != 0 ;
}


问:
Multi-part identifier error when adding a function to table- SQL Server
Currently I have the following function

```<code>CREATE FUNCTION dbo.CurrentEmpCount()
RETURNS DECIMAL
AS
BEGIN
    DECLARE @RetCount DECIMAL, @Return DECIMAL;

    SELECT @RetCount = COUNT(*)
    FROM Employee
    GROUP BY DepartmentID

    SET @Return = @RetCount

    RETURN  @Return
END
</code>```

When I try to add it to the department table with alter, I get an error:

The multi-part identifier "dbo.CurrentEmpCount" could not be bound.

```<code>ALTER TABLE Department
    ADD WorkStations AS dbo.CurrentEmpCount
GO
</code>```

Could anyone suggest anything to try out? In examples I've seen, they were doing it similarly.

答:
Your function should have an input for the DepartmentID. And you count number of employee for that DepartmentID

```<code>CREATE FUNCTION dbo.CurrentEmpCount
(
    @DepartmentID  INT        -- assuming that ID is INT
)
RETURNS INT                   -- count() returns an INTEGER not DECIMAL
AS
BEGIN
    DECLARE @RetCount INT

    SELECT  @RetCount = COUNT(*)
    FROM    Employee
    WHERE   DepartmentID = @DepartmentID

    RETURN  @RetCount
END
</code>```

Then your Department table should be as follow

```<code>ALTER TABLE Department
    ADD WorkStations AS dbo.CurrentEmpCount(DepartmentID)
</code>```

You need to pass in the DepartmentID of table Department

Alternatively you can just create a VIEW for the Department table

Note : use DECIMAL or NUMERIC if you are storing numbers with decimal places. From Doc Numeric data types that have fixed precision and scale

Body:
Currently I have the following function

CREATE FUNCTION dbo.CurrentEmpCount()
RETURNS DECIMAL
AS
BEGIN
    DECLARE @RetCount DECIMAL, @Return DECIMAL;

    SELECT @RetCount = COUNT(*)
    FROM Employee
    GROUP BY DepartmentID

    SET @Return = @RetCount

    RETURN  @Return
END

When I try to add it to the department table with alter, I get an error:

The multi-part identifier "dbo.CurrentEmpCount" could not be bound.

ALTER TABLE Department
    ADD WorkStations AS dbo.CurrentEmpCount
GO

Could anyone suggest anything to try out? In examples I've seen, they were doing it similarly.

Body:
Your function should have an input for the DepartmentID. And you count number of employee for that DepartmentID

CREATE FUNCTION dbo.CurrentEmpCount
(
    @DepartmentID  INT        -- assuming that ID is INT
)
RETURNS INT                   -- count() returns an INTEGER not DECIMAL
AS
BEGIN
    DECLARE @RetCount INT

    SELECT  @RetCount = COUNT(*)
    FROM    Employee
    WHERE   DepartmentID = @DepartmentID

    RETURN  @RetCount
END

Then your Department table should be as follow

ALTER TABLE Department
    ADD WorkStations AS dbo.CurrentEmpCount(DepartmentID)

You need to pass in the DepartmentID of table Department

Alternatively you can just create a VIEW for the Department table

Note : use DECIMAL or NUMERIC if you are storing numbers with decimal places. From Doc Numeric data types that have fixed precision and scale


问:
Removing all characters that are not digits in a pandas string type series
From the following pandas series below, I want to remove all characters
 that are not digits.

```<code>df = pd.series(['0312861','00','66065','6-0io09in4','.314', '3194890809', ':"<>":', '3456.85236', '3465.2154', '312.724146','300.3634865'], index = [1,2,3,4,5,6,7,8,9,10,11])
</code>```

numbers

0312861

00

66065

6-0io09in4

.314

3194890809

:"<>":

3456.85236

3465.2154

312.724146

300.3634865

For this, I have tried the code:

```<code>df['numbers'] = df['numbers'].str.replace('\D', '', regex=True)
</code>```

I am expecting the output to be:
numbers

0312861

00

66065

6009

314

3194890809

Nan

345685236

34652154

312724146

3003634865

However, I am getting the following output:
 numbers

0312861

00

66065

60094

314

3194890809

Nan

Nan

Nan

Nan

Nan

So it seems that my regex takes the last three entries as floating point numbers so it is removing them. However, I want to just remove the period(.) from the last three entries.

I have tried to find my specific solution but did not find it, so i am posting it here in the hope of getting one.

答:
Why you think so complicated when the answer is so simple. Get all characters one by one and check if is digit.

I do not know to work in pandas, but if I was do then I will make a temporary list and then I will try to get just the items of that list and then I will try to get item one by one and then to chek character one by one to see if is digit, and if not then I will pass.

Example:

```<code>tempList = []

for item in thisList: # thisList will be your list
    tempItem = "" #temporary item
    for character in item:
        # I see you have and some floats there if you want and floats then add that or statement
        if character.isdigit() or character == ".":
            tempItem = f"{tempItem}{character}"
    tempList.append(tempItem)
</code>```

After that I will get a temporary list just with digits items... Yeah that is my stupid answer. Is not an official answer, I was jut try to help.

Body:
From the following pandas series below, I want to remove all characters
 that are not digits.

df = pd.series(['0312861','00','66065','6-0io09in4','.314', '3194890809', ':"<>":', '3456.85236', '3465.2154', '312.724146','300.3634865'], index = [1,2,3,4,5,6,7,8,9,10,11])

numbers

0312861

00

66065

6-0io09in4

.314

3194890809

:"<>":

3456.85236

3465.2154

312.724146

300.3634865

For this, I have tried the code:

df['numbers'] = df['numbers'].str.replace('\D', '', regex=True)

I am expecting the output to be:
numbers

0312861

00

66065

6009

314

3194890809

Nan

345685236

34652154

312724146

3003634865

However, I am getting the following output:
 numbers

0312861

00

66065

60094

314

3194890809

Nan

Nan

Nan

Nan

Nan

So it seems that my regex takes the last three entries as floating point numbers so it is removing them. However, I want to just remove the period(.) from the last three entries.

I have tried to find my specific solution but did not find it, so i am posting it here in the hope of getting one.

Body:
Why you think so complicated when the answer is so simple. Get all characters one by one and check if is digit.

I do not know to work in pandas, but if I was do then I will make a temporary list and then I will try to get just the items of that list and then I will try to get item one by one and then to chek character one by one to see if is digit, and if not then I will pass.

Example:

tempList = []

for item in thisList: # thisList will be your list
    tempItem = "" #temporary item
    for character in item:
        # I see you have and some floats there if you want and floats then add that or statement
        if character.isdigit() or character == ".":
            tempItem = f"{tempItem}{character}"
    tempList.append(tempItem)

After that I will get a temporary list just with digits items... Yeah that is my stupid answer. Is not an official answer, I was jut try to help.


问:
How to check if IMAP Webklex is connected or not connected
I'm having problems catching the error for the email webklex imap. i want to check if connected or not connected. credentials are correct, i only need to catch if the credentials are wrong or not connected.

Thanks.

```<code>$oClient = new Client([
    'host'          => 'imap.gmail.com',
    'port'          => $account_type['port'],
    'encryption'    => 'ssl',
    'validate_cert' => true,
    'username'      => $username,
    'password'      => $password,
    'protocol'      => 'imap'
]);
$oClient->connect();
if(){
//check if connected or not
}
</code>```

答:
Use $oClient->isConnected(); or $oClient->checkConnection();
It really depends on your requirement.

For more information follow the documentation: https://github.com/Webklex/laravel-imap#clientclass

Body:
I'm having problems catching the error for the email webklex imap. i want to check if connected or not connected. credentials are correct, i only need to catch if the credentials are wrong or not connected.

Thanks.

$oClient = new Client([
    'host'          => 'imap.gmail.com',
    'port'          => $account_type['port'],
    'encryption'    => 'ssl',
    'validate_cert' => true,
    'username'      => $username,
    'password'      => $password,
    'protocol'      => 'imap'
]);
$oClient->connect();
if(){
//check if connected or not
}


问:
Confuse with the linus conditions '-z' '-n'
here is my script：

```<code>#!/bin/bash

read -p "para:" teatp

if [ -z $teatp ]; then
    echo '-z is ture'
else
    echo '-z is false'
fi

if [ -n $teatp ]; then
    echo '-n is ture'
else
    echo '-n is false'
fi
</code>```

when I input nothing and press enter, the result is

```<code>para:
-z is ture
-n is ture
</code>```

on the other hand, when I input something and press enter, the result is

```<code>para:qwer1234
-z is false
-n is ture
</code>```

which confused me is the first result -n is ture.
I think the -n and -z are antonyms, but why is the result the same?
There must be something I ignore or misunderstand.
I will be appreciate if someone can point out

答:
the #testp should be quote by double quotation marks?
like:

```<code>[ -n "$teatp" ]
</code>```

Body:
here is my script：

#!/bin/bash

read -p "para:" teatp

if [ -z $teatp ]; then
    echo '-z is ture'
else
    echo '-z is false'
fi

if [ -n $teatp ]; then
    echo '-n is ture'
else
    echo '-n is false'
fi

when I input nothing and press enter, the result is

para:
-z is ture
-n is ture

on the other hand, when I input something and press enter, the result is

para:qwer1234
-z is false
-n is ture

which confused me is the first result -n is ture.
I think the -n and -z are antonyms, but why is the result the same?
There must be something I ignore or misunderstand.
I will be appreciate if someone can point out

Body:
the #testp should be quote by double quotation marks?
like:

[ -n "$teatp" ]


问:
Keep track of progress while precaching assets with the Workbox
Imagine we have N assets that need to be pre-cached with a service-worker once user navigated to the web site. We have appropriate precache-manifest.js with listed N-files and we are using workbox.precaching.precacheAndRoute([...]) to configure needed behavior (default CRA setup)

Is there a way to keep track of precaching progress when using workbox.precaching.precacheAndRoute or workbox.precaching.precache?

I imagine it could be something like passing a parameter-callback function to the workbox.precaching.precacheAndRoute along with the array of entries to precache. And this callback is invoked for each cached entry..

Is there any solution or workaround for this issue?
Thanks!

答:
There is no event or callback provided by workbox to notify if precaching is completed. But here is a workaround i've managed to come up with using postMessage to notify the client that precaching is completed.

```<code>// sw-precache.js
workbox.precaching.precacheAndRoute(self.__precacheManifest)

const interval = setInterval(() => {
    caches.open(workbox.core.cacheNames.precache).then(cache => {
        cache.keys().then(keys => {
            if (keys.length >= self.__precacheManifest.length) {
                clearInterval(interval)
                self.clients.matchAll().then(clients => {
                    clients.forEach(client => client.postMessage('afterPrecache'))
                })
            }
        })
    })
}, 1000)
</code>```

And in your client,

```<code>// index.html
....
navigator.serviceWorker.onmessage = (e) => {
    if (e.data === 'afterPrecache') {
        // precaching completed
    }
}
....
</code>```

You can even tweak the above solution to get track of precaching progress.

Body:
There is no event or callback provided by workbox to notify if precaching is completed. But here is a workaround i've managed to come up with using postMessage to notify the client that precaching is completed.

// sw-precache.js
workbox.precaching.precacheAndRoute(self.__precacheManifest)

const interval = setInterval(() => {
    caches.open(workbox.core.cacheNames.precache).then(cache => {
        cache.keys().then(keys => {
            if (keys.length >= self.__precacheManifest.length) {
                clearInterval(interval)
                self.clients.matchAll().then(clients => {
                    clients.forEach(client => client.postMessage('afterPrecache'))
                })
            }
        })
    })
}, 1000)

And in your client,

// index.html
....
navigator.serviceWorker.onmessage = (e) => {
    if (e.data === 'afterPrecache') {
        // precaching completed
    }
}
....

You can even tweak the above solution to get track of precaching progress.


问:
Can't deploy firebase with a "npm script"?
I can easily deploy my firebase app (an angular app) by going on the command line and doing firebase deploy --only hosting. I want to instead run this via npm run deploy-hosting. But it isn't working, and just error'ing out. Here is my package.json:

```<code>{
    "scripts": {
        "deploy-hosting": "firebase deploy --only hosting"
    }
}
</code>```

Here is the output:

```<code>$ npm run deploy-hosting

> site@ deploy-hosting /Users/me/workspace/site
> firebase deploy --only hosting

Error: An unexpected error has occurred.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! site@ deploy-hosting: `firebase deploy --only hosting`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the site@ deploy-hosting script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2020-02-15T01_55_56_874Z-debug.log
</code>```

And then here is the above debug file:

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'deploy-hosting' ]
2 info using npm@6.13.4
3 info using node@v8.17.0
4 verbose run-script [ 'predeploy-hosting', 'deploy-hosting', 'postdeploy-hosting' ]
5 info lifecycle cryptoCoinSignals@~predeploy-hosting: cryptoCoinSignals@
6 info lifecycle cryptoCoinSignals@~deploy-hosting: cryptoCoinSignals@
7 verbose lifecycle cryptoCoinSignals@~deploy-hosting: unsafe-perm in lifecycle true
8 verbose lifecycle cryptoCoinSignals@~deploy-hosting: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/me/workspace/cryptocoinsignals/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Users/me/workspace/cryptocoinsignals/node_modules/.bin
9 verbose lifecycle cryptoCoinSignals@~deploy-hosting: CWD: /Users/me/workspace/cryptocoinsignals
10 silly lifecycle cryptoCoinSignals@~deploy-hosting: Args: [ '-c', 'firebase deploy --only hosting' ]
11 silly lifecycle cryptoCoinSignals@~deploy-hosting: Returned: code: 2  signal: null
12 info lifecycle cryptoCoinSignals@~deploy-hosting: Failed to exec deploy-hosting script
13 verbose stack Error: cryptoCoinSignals@ deploy-hosting: `firebase deploy --only hosting`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:915:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid cryptoCoinSignals@
15 verbose cwd /Users/me/workspace/cryptocoinsignals
16 verbose Darwin 19.2.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "deploy-hosting"
18 verbose node v8.17.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 2
22 error cryptoCoinSignals@ deploy-hosting: `firebase deploy --only hosting`
22 error Exit status 2
23 error Failed at the cryptoCoinSignals@ deploy-hosting script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]
</code>```

答:
Try the standard rebuild of node modules.

```<code>npm cache --clean force

rm -rf node_modules

rm package.json

npm install
</code>```

That's what I would do personally.

Curious, did you lookup ELIFECYCLE error?

Body:
I can easily deploy my firebase app (an angular app) by going on the command line and doing firebase deploy --only hosting. I want to instead run this via npm run deploy-hosting. But it isn't working, and just error'ing out. Here is my package.json:

{
    "scripts": {
        "deploy-hosting": "firebase deploy --only hosting"
    }
}

Here is the output:

$ npm run deploy-hosting

> site@ deploy-hosting /Users/me/workspace/site
> firebase deploy --only hosting

Error: An unexpected error has occurred.
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! site@ deploy-hosting: `firebase deploy --only hosting`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the site@ deploy-hosting script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/me/.npm/_logs/2020-02-15T01_55_56_874Z-debug.log

And then here is the above debug file:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'run',
1 verbose cli   'deploy-hosting' ]
2 info using npm@6.13.4
3 info using node@v8.17.0
4 verbose run-script [ 'predeploy-hosting', 'deploy-hosting', 'postdeploy-hosting' ]
5 info lifecycle cryptoCoinSignals@~predeploy-hosting: cryptoCoinSignals@
6 info lifecycle cryptoCoinSignals@~deploy-hosting: cryptoCoinSignals@
7 verbose lifecycle cryptoCoinSignals@~deploy-hosting: unsafe-perm in lifecycle true
8 verbose lifecycle cryptoCoinSignals@~deploy-hosting: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/me/workspace/cryptocoinsignals/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Users/me/workspace/cryptocoinsignals/node_modules/.bin
9 verbose lifecycle cryptoCoinSignals@~deploy-hosting: CWD: /Users/me/workspace/cryptocoinsignals
10 silly lifecycle cryptoCoinSignals@~deploy-hosting: Args: [ '-c', 'firebase deploy --only hosting' ]
11 silly lifecycle cryptoCoinSignals@~deploy-hosting: Returned: code: 2  signal: null
12 info lifecycle cryptoCoinSignals@~deploy-hosting: Failed to exec deploy-hosting script
13 verbose stack Error: cryptoCoinSignals@ deploy-hosting: `firebase deploy --only hosting`
13 verbose stack Exit status 2
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:915:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid cryptoCoinSignals@
15 verbose cwd /Users/me/workspace/cryptocoinsignals
16 verbose Darwin 19.2.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "deploy-hosting"
18 verbose node v8.17.0
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 2
22 error cryptoCoinSignals@ deploy-hosting: `firebase deploy --only hosting`
22 error Exit status 2
23 error Failed at the cryptoCoinSignals@ deploy-hosting script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2, true ]

Body:
Try the standard rebuild of node modules.

npm cache --clean force

rm -rf node_modules

rm package.json

npm install

That's what I would do personally.

Curious, did you lookup ELIFECYCLE error?


问:
How to write to a memory address with an offset in a different process
I am making a hack for a game called AssaultCube, and the player base address is 0x0050F4F4 and the "health" address is 0x0050F4F4 + 0xF8, the problem is, I can't write to the address even with Full Access.

My Code:

```<code>#include <Windows.h>
#include <iostream>

using namespace std;

int main() {
    HWND window = FindWindowA(NULL,"AssaultCube");
    int value = 888;
    if(window == NULL) {
        cout << "Can't find window!";
        exit(-1);
    }
    DWORD pid;
    GetWindowThreadProcessId(window,&pid);
    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
    while(true) {
        WriteProcessMemory(handle,reinterpret_cast<LPVOID>(0x0050F4F4 + 0xF8),&value,sizeof(value),0);
        Sleep(750);
    }
}
</code>```

Now in the tool I use to look at memory addresses, Cheat Engine, I can change the value but in my program I can't.

Cheat Engine

Any help would be appreciated.

答:
Your logic is incorrect.

0x0050F4F4 is the pointer to the local player object.

0xF8 is health offset, relative to the local player object.

You are adding them together thinking that is the address of the health variable, which it is not.  You need to ReadProcessMemory on 0x0050F4F4, which will yield you the address of the local player object in your destination buffer.  Then you add 0xF8 to it, this yields the address of the local player health variable.  Then you call WriteProcessMemory on this address and overwrite it.

Body:
I am making a hack for a game called AssaultCube, and the player base address is 0x0050F4F4 and the "health" address is 0x0050F4F4 + 0xF8, the problem is, I can't write to the address even with Full Access.

My Code:

#include <Windows.h>
#include <iostream>

using namespace std;

int main() {
    HWND window = FindWindowA(NULL,"AssaultCube");
    int value = 888;
    if(window == NULL) {
        cout << "Can't find window!";
        exit(-1);
    }
    DWORD pid;
    GetWindowThreadProcessId(window,&pid);
    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,pid);
    while(true) {
        WriteProcessMemory(handle,reinterpret_cast<LPVOID>(0x0050F4F4 + 0xF8),&value,sizeof(value),0);
        Sleep(750);
    }
}

Now in the tool I use to look at memory addresses, Cheat Engine, I can change the value but in my program I can't.

Cheat Engine

Any help would be appreciated.


问:
GregorianCalendar Class in Java
I am trying to get current time in other time zone. I used this code for this:

```<code>GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
    System.out.println(calender.getTime());
</code>```

But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET.
I am confused. Then why there is scope to provide a TimeZone in constructor?

答:
tl;dr

```<code>ZonedDateTime.now( ZoneId.of( "Asia/Bangkok" ) )
</code>```

java.time

The legacy date-time classes you are using are simply terrible, flawed in design and in implementation, built by people who did not understand date-time handling. Avoid those classes entirely.

Use only the modern java.time classes defined in JSR 310.

```<code>ZoneId z = ZoneId.of( "Asia/Bangkok" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
</code>```

Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.

```<code>String output = zdt.toString() ;
</code>```

For other formats, use DateTimeFormatter as seen on hundreds of other Questions and Answers.

See this code run live at IdeOne.com.

2020-02-15T12:27:31.118127+07:00[Asia/Bangkok]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Title: GregorianCalendar Class in Java

Body:
I am trying to get current time in other time zone. I used this code for this:

GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
    System.out.println(calender.getTime());

But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET.
I am confused. Then why there is scope to provide a TimeZone in constructor?

Body:
tl;dr

ZonedDateTime.now( ZoneId.of( "Asia/Bangkok" ) )

java.time

The legacy date-time classes you are using are simply terrible, flawed in design and in implementation, built by people who did not understand date-time handling. Avoid those classes entirely.

Use only the modern java.time classes defined in JSR 310.

ZoneId z = ZoneId.of( "Asia/Bangkok" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.

String output = zdt.toString() ;

For other formats, use DateTimeFormatter as seen on hundreds of other Questions and Answers.

See this code run live at IdeOne.com.

2020-02-15T12:27:31.118127+07:00[Asia/Bangkok]

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later  - Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

Later versions of Android bundle implementations of the java.time classes.

For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
VsCode VIM - How to open "New Untitled File"
In VsCode VIM (vanilla installation), how would you execute Ctrl + N? When inspecting the keyboard shortcut, it looks like this:

I tried the plain way in VIM by running :new, but it opened a new tab within the same editor instead of a whole new tab.

Ideally, I'm looking for a plain way to do this without having to re-map any keys. I'm a big proponent of using vanilla tooling so I can easily transfer machine without having to carry around my re-mappings.

答:
You can try :e

Example

```<code>:e test.js
</code>```

Or install extension like this : https://github.com/dkundel/vscode-new-file

Body:
You can try :e

Example

:e test.js

Or install extension like this : https://github.com/dkundel/vscode-new-file


问:
git repquest aborts with "Your local changes to the following files would be overwritten by merge"
i have a codeigniter project in ubuntu server

i normally upload files to bitbucket. and in ubuntu server i pull the files from bit bucket

but in project, users uploads images in frontend of the website.

And when i pull, git says local contain changes that are not in remote and aborting the pull

so i typed

```<code>git add .
git commit -m "message"
git pull
</code>```

is this the right way to do this?

Do i need to exclude the uploads folder from git..

folder structure

```<code>var/ww/html

application
uploads
.git
</code>```

答:
Typically user uploads should not be considered part of your code repository. You can tell git to ignore that folder by opening .gitignore and adding the line uploads/*

The error you are getting is indicating, however, that your local branch has updates that your remote does not (meaning it is ahead). Assuming no other developers (or users) are editing your remote branch, you can get by this by calling git pull before you make your changes, and then add, commit and push your changes to the remote.

If you have already made changes and then your remote changes, you can get around this by calling git stash to store your changes elsewhere and then git stash apply to bring them back after you have pulled the changes to the remote branch.

If you are working on a project with other developers, you may want to read up on proper team git workflows, particularly how to use feature branches and pull requests.

Body:
i have a codeigniter project in ubuntu server

i normally upload files to bitbucket. and in ubuntu server i pull the files from bit bucket

but in project, users uploads images in frontend of the website.

And when i pull, git says local contain changes that are not in remote and aborting the pull

so i typed

git add .
git commit -m "message"
git pull

is this the right way to do this?

Do i need to exclude the uploads folder from git..

folder structure

var/ww/html

application
uploads
.git


问:
Rails 6: Files with special characters in the name crash app when accessing amazon S3 with active storage
I am uploading to amazon S3 using active storage in a rails 6 web app.  The web app works fine until I upload a file with special characters and then the app crashes when I try and read that file.

I understand that Amazon doesn't accept special characters but I am not sure how to convert the filenames before uploading... From searching forums it seems you can sanitize the filename but I'm not sure where this code would go?

答:
try this</p>

```<code>class Model < ApplicationRecord
  after_create :rename_filename

  def rename_filename
    if active_storage_object.attached?
      active_storage_object.blob.update(filename: "filename.#{active_storage_object.filename.extension}")
    end
  end
end
</code>```

Body:
try this

class Model < ApplicationRecord
  after_create :rename_filename

  def rename_filename
    if active_storage_object.attached?
      active_storage_object.blob.update(filename: "filename.#{active_storage_object.filename.extension}")
    end
  end
end