问:
Organization of work with DataBase
I have some expierence in PHP, but have no one in application architecture

Now I want to orginize my own "bicycle". It's something not useful, maybe mini-framework or mini-application, I want get some exp here.

I need now to write classes for work with database and classese for entities (one of them isUser)

I have following code for database (some cheks and method are omitted to minify this question):

```<code>namespace DataBase;
class DataBase {
    /**
     *
     * @var \PDO $pdo
     */
    public $pdo;
    public function __construct($host, $dbname, $username, $password=''){

        $this->pdo = new \PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password,
            array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

    }
    /**
     *
     * @param string $statement
     * @return Statement
     */
    public function prepare($statement){
        return new Statement($this->pdo->prepare($statement));
    }
}

namespace DataBase;

class Statement {
    private $stmt;

    public function __construct(\PDOStatement $stmt) {
        $this->stmt = $stmt;
    }

    public function query() {
    try {
        $this->stmt->execute();
        return $this; //for chaining
    }

    public function bind($key, $value) {
        $this->stmt->bindValue($key, $value, $this->typeof($value));
        return $this; //for chaining
    }
        //some methods for fetching data(works with fetch,fetchAll, fetchColumn and different PDO::FETCH_ methods

    public function fetchUpdate($obj) {
        $this->stmt->setFetchMode(\PDO::FETCH_INTO, $obj);
        $this->stmt->fetch();
    }

    public function fetchRow() {
        return $this->stmt->fetch(\PDO::FETCH_OBJ);
    }
    public function fetchRowClass($class) {
        return $this->stmt->fetchObject($class);
    }
}
</code>```

And Some dummy for User class

```<code><?php

/**
 * Description of User
 *
 * @author riad
 */
class User {
    private $id;

    private $name = null;

    private $status = null;

    private $hasInfo = false;

    private static $cache=array();
    public function __construct() {

    }
    public function getId() {
        return $this->id;
    }
    public function getName() {
        if(!$this->hasInfo)
            $this->getInfo ();
        return $this->name;
    }
    public function isAuthorized(){
        return $this->status!="noauth";
    }
    public static function createById($id) {
        // I want this method to cerate user from id, then get info only I will use it after that
        if(array_key_exists($id,self::$cache)){
            return self::$cache[$id];
        }
        $user = new User;
        $user->id = $id;
        return $user;
    }
    private function getInfo(){
        try{
            \FrontController::getInstance()->getDB()->
                prepare('SELECT * FROM `users` WHERE `id`=:id')->
                bind('id', $this->id)->query()->fetchUpdate($this);
            $this->hasInfo = true;
        }
        catch(\DataBase\NotFoundException $dbe){
            $this->status = "deleted";
        }
    }
    public static function createFromRequest($request){
        $user = new User;
        try{
            //try get data from cookie
            \FrontController::getInstance()->getDB()->
                prepare('SELECT * FROM `users` WHERE `session` = :session AND `id`= :id')->
                bind('id', $id)->bind('session',$session)->query()->
                fetchUpdate($user);
        }
        catch(... $e){
            $user->status = "noauth";
            $user->id = 0;
            // make it unregged
        }
        return $user;
    }
}

?>
</code>```

I have some problems with it.

I don't want set properties from database, that are not listed in props of class list(is not so important, of course). I know that I can use ```<code>public function __call($name,$value){
//do nothing;
}</code>```

I want to mkae this props private, but want also use $stmt->fetchUpdate($obj) I know I can use ```<code>public function __call($name,$value){
$this->$name=$value;
}</code>```, but it's as declare props public and it is on the road with first point
I can also use ```<code>public function __call($name,$value){
if($name=='id'){
    $this->id=$value;
}
else if($name=='status'){
    $this->status=$value;
}
}</code>``` But it's not comfortable to write it for every entity class and not save as from publicity of this methods

I want to set $this->hasInfo to true when I get this class from database. I know  I can change my Database class to always set some variable to true when by default it's false. But it seems to be not elegant.

I want to update cache when I set id (It maybe used as previos point)

Is it possible to avoid fetchRowClass write direct to props and use setter as with fetchUpdate? Or maybe allow fetchUpdate direct access?

I know I write a lot of code self but I want your opinion:

What should I improve?

What are other/the best possible solution for problems from previos list?

Hope, It's not so hard to read and understand.

Glad to see any suggestions

With regards Alex

答:
Few tips: [based on my own experience and frameworks i already used]

Basically what you should/want/might do is to create a SuperClass for all the clases in you model. This class will contain the reference to the Database Instance, and it will have all the common methods for your model, i.e. getById($id), getAll(),getPaginated(), etc.

The other goal of this SuperClass is to map the results from the database into Instances of your Model's Classes. So in the end, your user class would have only properties, accessors and methods that are specific to the class, like special queries or something like that.

Here's an example of what this could look like:

```<code>Class Model{
    protected function getById($_id){
        $_table = get_class($this);
        $anonymous = $this->_getObjectById($_table,$_id); //this method will execute a query (unsing PDO) and return a StdClass object with the results
        $this->mapTable($anonymous,$_table); //this method will take the StdClass instance and will transform it into a $_table Instance
    }

    private function mapTable($stdInstance,$model_name){
        foreach($stdInstance as $key => $value){
            try{
                if(property_exists($this,$key)){
                    $this->$key = $value; //you could declare the model's properties     as protected... or you could create accessors and call them here
                }
            } catch(Exception $ex) {
                /* something went wrong o_O */
            }
     }

Class User extends Model{
     protected $id;
     protected $name;
     .....
}

Class Controller{
    public function index(){
         $user = new User();
         $user->getById($_GET['id']);
         print_r($user);
         //now you can pass the $user object to the View to display it
    }
}
</code>```

in a few words... the Model class is a very small ORM. You could try to create your own ORM, (like i did) but you'll face a lot of problems when trying to map the relations between objects: Nx1,1xN,NxN,1x1, inheritance, "deeper relations" and the n+1 problem. You'll also need to, somehow, define the model structure so your ORM could understand it, maybe using YAML/XML files or reading the structure directly from the table structure of your databe, or having a naming convention in your properties...

its a really interesting field :)

Hope this helps and Good Luck

Title: Organization of work with DataBase

Body:
I have some expierence in PHP, but have no one in application architecture

Now I want to orginize my own "bicycle". It's something not useful, maybe mini-framework or mini-application, I want get some exp here.

I need now to write classes for work with database and classese for entities (one of them isUser)

I have following code for database (some cheks and method are omitted to minify this question):

namespace DataBase;
class DataBase {
    /**
     *
     * @var \PDO $pdo
     */
    public $pdo;
    public function __construct($host, $dbname, $username, $password=''){

        $this->pdo = new \PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password,
            array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"));
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

    }
    /**
     *
     * @param string $statement
     * @return Statement
     */
    public function prepare($statement){
        return new Statement($this->pdo->prepare($statement));
    }
}

namespace DataBase;

class Statement {
    private $stmt;

    public function __construct(\PDOStatement $stmt) {
        $this->stmt = $stmt;
    }

    public function query() {
    try {
        $this->stmt->execute();
        return $this; //for chaining
    }

    public function bind($key, $value) {
        $this->stmt->bindValue($key, $value, $this->typeof($value));
        return $this; //for chaining
    }
        //some methods for fetching data(works with fetch,fetchAll, fetchColumn and different PDO::FETCH_ methods

    public function fetchUpdate($obj) {
        $this->stmt->setFetchMode(\PDO::FETCH_INTO, $obj);
        $this->stmt->fetch();
    }

    public function fetchRow() {
        return $this->stmt->fetch(\PDO::FETCH_OBJ);
    }
    public function fetchRowClass($class) {
        return $this->stmt->fetchObject($class);
    }
}

And Some dummy for User class

<?php

/**
 * Description of User
 *
 * @author riad
 */
class User {
    private $id;

    private $name = null;

    private $status = null;

    private $hasInfo = false;

    private static $cache=array();
    public function __construct() {

    }
    public function getId() {
        return $this->id;
    }
    public function getName() {
        if(!$this->hasInfo)
            $this->getInfo ();
        return $this->name;
    }
    public function isAuthorized(){
        return $this->status!="noauth";
    }
    public static function createById($id) {
        // I want this method to cerate user from id, then get info only I will use it after that
        if(array_key_exists($id,self::$cache)){
            return self::$cache[$id];
        }
        $user = new User;
        $user->id = $id;
        return $user;
    }
    private function getInfo(){
        try{
            \FrontController::getInstance()->getDB()->
                prepare('SELECT * FROM `users` WHERE `id`=:id')->
                bind('id', $this->id)->query()->fetchUpdate($this);
            $this->hasInfo = true;
        }
        catch(\DataBase\NotFoundException $dbe){
            $this->status = "deleted";
        }
    }
    public static function createFromRequest($request){
        $user = new User;
        try{
            //try get data from cookie
            \FrontController::getInstance()->getDB()->
                prepare('SELECT * FROM `users` WHERE `session` = :session AND `id`= :id')->
                bind('id', $id)->bind('session',$session)->query()->
                fetchUpdate($user);
        }
        catch(... $e){
            $user->status = "noauth";
            $user->id = 0;
            // make it unregged
        }
        return $user;
    }
}

?>

I have some problems with it.

I don't want set properties from database, that are not listed in props of class list(is not so important, of course). I know that I can use
public function __call($name,$value){
//do nothing;
}

I want to mkae this props private, but want also use $stmt->fetchUpdate($obj) I know I can use
public function __call($name,$value){
$this->$name=$value;
}
, but it's as declare props public and it is on the road with first point
I can also use
public function __call($name,$value){
if($name=='id'){
    $this->id=$value;
}
else if($name=='status'){
    $this->status=$value;
}
}
 But it's not comfortable to write it for every entity class and not save as from publicity of this methods

I want to set $this->hasInfo to true when I get this class from database. I know  I can change my Database class to always set some variable to true when by default it's false. But it seems to be not elegant.

I want to update cache when I set id (It maybe used as previos point)

Is it possible to avoid fetchRowClass write direct to props and use setter as with fetchUpdate? Or maybe allow fetchUpdate direct access?

I know I write a lot of code self but I want your opinion:

What should I improve?

What are other/the best possible solution for problems from previos list?

Hope, It's not so hard to read and understand.

Glad to see any suggestions

With regards Alex

Body:
Few tips: [based on my own experience and frameworks i already used]

Basically what you should/want/might do is to create a SuperClass for all the clases in you model. This class will contain the reference to the Database Instance, and it will have all the common methods for your model, i.e. getById($id), getAll(),getPaginated(), etc.

The other goal of this SuperClass is to map the results from the database into Instances of your Model's Classes. So in the end, your user class would have only properties, accessors and methods that are specific to the class, like special queries or something like that.

Here's an example of what this could look like:

Class Model{
    protected function getById($_id){
        $_table = get_class($this);
        $anonymous = $this->_getObjectById($_table,$_id); //this method will execute a query (unsing PDO) and return a StdClass object with the results
        $this->mapTable($anonymous,$_table); //this method will take the StdClass instance and will transform it into a $_table Instance
    }

    private function mapTable($stdInstance,$model_name){
        foreach($stdInstance as $key => $value){
            try{
                if(property_exists($this,$key)){
                    $this->$key = $value; //you could declare the model's properties     as protected... or you could create accessors and call them here
                }
            } catch(Exception $ex) {
                /* something went wrong o_O */
            }
     }

Class User extends Model{
     protected $id;
     protected $name;
     .....
}

Class Controller{
    public function index(){
         $user = new User();
         $user->getById($_GET['id']);
         print_r($user);
         //now you can pass the $user object to the View to display it
    }
}

in a few words... the Model class is a very small ORM. You could try to create your own ORM, (like i did) but you'll face a lot of problems when trying to map the relations between objects: Nx1,1xN,NxN,1x1, inheritance, "deeper relations" and the n+1 problem. You'll also need to, somehow, define the model structure so your ORM could understand it, maybe using YAML/XML files or reading the structure directly from the table structure of your databe, or having a naming convention in your properties...

its a really interesting field :)

Hope this helps and Good Luck


来源: stackexchange

问:
add button should work for each form-holder saparatly
```<code>***<!DOCTYPE html>
<html lang="en">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7     /css/bootstrap.min.css" rel="stylesheet"/>
<div id="order-details-booking">
    <blockquote>Self-order Menu</blockquote>
      <div class="form-holder col-xs-14">
        <div class="input-field col s4">
            <input type="text" id="item-" placeholder="Item Code"/>
        </div>
        <div class="input-field col s2">
            <input type="text" id="item-code" placeholder="Qty" />
        </div>
        <div class="input-field col s5">
            <input type="text" id="item-code" placeholder="Remarks" />
        </div>
        <div class="col s1">
            <i class="material-icons remove">- remove</i>
        </div>
    </div>
      <div class="form-holder-append"></div>
      <div class="row">
                <div class="col-xs-4">
                      <i class="material-icons add">+ add</i>
        </div></div>
</div>
<div id="order-details-booking2">
    <blockquote>Self-order Menu</blockquote>
      <div class="form-holder col-xs-1">

        <div class="input-field col s4">
            <input type="text" id="item-" placeholder="Item Code"/>
        </div>
        <div class="input-field col s2">
            <input type="text" id="item-code" placeholder="Qty" />
        </div>
        <div class="input-field col s5">
            <input type="text" id="item-code" placeholder="Remarks" />
        </div>
        <div class="col s1">
            <i class="material-icons remove">- remove</i>
        </div>
    </div>
      <div class="form-holder-append"></div>
      <div class="row">
                <div class="col-xs-4">
                      <i class="material-icons add">+ add</i>
        </div></div>
</div>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7    /js/bootstrap.min.js"></script>
<script>
var id_count = 1;
$('.add').on('click', function() {
var source = $('.form-holder:first'), clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
  return val + id_count;
});
clone.appendTo('.form-holder-append');
id_count++;
});
//button for add second holder
var id_count2 = 1;
$('.add').on('click', function() {
var source = $('.form-holder:first'), clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
  return val + id_count2;`enter code here`
});
clone.appendTo('.form1-holder-append');
id_count++;
});
// Removing Form Field
$('body').on('click', '.remove', function() {
var closest = $(this).closest('.form-holder').remove();
});
</script>***
</code>```

webpage contain 2 form holder, when ever i click add button the action should be performed to each holder separately, but now the if we press add button, the it add form to both form holder.I shared the code in above, I hope I may get help as soon as possible, Thank for help..

********It looks like your post is mostly code; please add some more details.

答:
if you only have two formholders you can solve this by useing unique classes.

```<code>var id_count = 1;
$('.add1').on('click', function() {
var source = $('.form-holder1:first'), clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
  return val + id_count;
});
clone.appendTo('.form-holder-append1');
id_count++;
});
//button for add second holder
var id_count2 = 1;
$('.add2').on('click', function() {
var source = $('.form-holder2:first'), clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
  return val + id_count2;`enter code here`
});
clone.appendTo('.form-holder-append2');
id_count++;
});
// Removing Form Field
$('body').on('click', '.remove', function() {
var closest = $(this).closest('.form-holder').remove();
});
</code>```

if you have a dynamic amount of formholders you should use a each() function and count the formholders and each element inside with eq(). This results in only one function for all formholders, independently how many.

ContentLicense: CC BY-SA 4.0

Body:
***<!DOCTYPE html>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7     /css/bootstrap.min.css" rel="stylesheet"/>

Self-order Menu

            <input type="text" id="item-" placeholder="Item Code"/>

            <input type="text" id="item-code" placeholder="Qty" />

            <input type="text" id="item-code" placeholder="Remarks" />

            - remove

                      + add

Self-order Menu

            <input type="text" id="item-" placeholder="Item Code"/>

            <input type="text" id="item-code" placeholder="Qty" />

            <input type="text" id="item-code" placeholder="Remarks" />

            - remove

                      + add

***

webpage contain 2 form holder, when ever i click add button the action should be performed to each holder separately, but now the if we press add button, the it add form to both form holder.I shared the code in above, I hope I may get help as soon as possible, Thank for help..

********It looks like your post is mostly code; please add some more details.

Body:
if you only have two formholders you can solve this by useing unique classes.

var id_count = 1;
$('.add1').on('click', function() {
var source = $('.form-holder1:first'), clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
  return val + id_count;
});
clone.appendTo('.form-holder-append1');
id_count++;
});
//button for add second holder
var id_count2 = 1;
$('.add2').on('click', function() {
var source = $('.form-holder2:first'), clone = source.clone();
clone.find(':input').attr('id', function(i, val) {
  return val + id_count2;`enter code here`
});
clone.appendTo('.form-holder-append2');
id_count++;
});
// Removing Form Field
$('body').on('click', '.remove', function() {
var closest = $(this).closest('.form-holder').remove();
});

if you have a dynamic amount of formholders you should use a each() function and count the formholders and each element inside with eq(). This results in only one function for all formholders, independently how many.


问:
How to Capture click event on Page Control swift
I follow a tutorial on how to create  UIPageControl and when I click on the page indicator it do not change the page

```<code>func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
        return nil
    }
    let previousIndex = viewControllerIndex - 1
    // User is on the first view controller and swiped left to loop to
    // the last view controller.
    guard previousIndex >= 0 else {
        return orderedViewControllers.last
        // Uncommment the line below, remove the line above if you don't want the page control to loop.
        // return nil
    }

    guard orderedViewControllers.count > previousIndex else {
        return nil
    }

    return orderedViewControllers[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1
    let orderedViewControllersCount = orderedViewControllers.count
    // User is on the last view controller and swiped right to loop to
    // the first view controller.
    guard orderedViewControllersCount != nextIndex else {
        return orderedViewControllers.first
        // Uncommment the line below, remove the line above if you don't want the page control to loop.
        // return nil
    }

    guard orderedViewControllersCount > nextIndex else {
        return nil
    }

    return orderedViewControllers[nextIndex]
}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 40,width: UIScreen.main.bounds.width,height: 40))
    self.pageControl.numberOfPages = orderedViewControllers.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.gray
    self.pageControl.pageIndicatorTintColor = UIColor.gray
    self.pageControl.currentPageIndicatorTintColor = UIColor.white
    self.view.addSubview(pageControl)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    let pageContentViewController = pageViewController.viewControllers![0]
    self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!

}
</code>```

答:
In my case(Xcode 13), I received previous currentPage.
So use dispatchQueue asyncAfter

```<code>@objc func pageControlSelectionAction(_ sender: UIPageControl) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
       let page: Int? = sender.currentPage
       //scroll
    }
}
</code>```

Also I just tested 'DispatchQueue.main.async' was fine.

Body:
I follow a tutorial on how to create  UIPageControl and when I click on the page indicator it do not change the page

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
        return nil
    }
    let previousIndex = viewControllerIndex - 1
    // User is on the first view controller and swiped left to loop to
    // the last view controller.
    guard previousIndex >= 0 else {
        return orderedViewControllers.last
        // Uncommment the line below, remove the line above if you don't want the page control to loop.
        // return nil
    }

    guard orderedViewControllers.count > previousIndex else {
        return nil
    }

    return orderedViewControllers[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
        return nil
    }

    let nextIndex = viewControllerIndex + 1
    let orderedViewControllersCount = orderedViewControllers.count
    // User is on the last view controller and swiped right to loop to
    // the first view controller.
    guard orderedViewControllersCount != nextIndex else {
        return orderedViewControllers.first
        // Uncommment the line below, remove the line above if you don't want the page control to loop.
        // return nil
    }

    guard orderedViewControllersCount > nextIndex else {
        return nil
    }

    return orderedViewControllers[nextIndex]
}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    pageControl = UIPageControl(frame: CGRect(x: 0,y: UIScreen.main.bounds.maxY - 40,width: UIScreen.main.bounds.width,height: 40))
    self.pageControl.numberOfPages = orderedViewControllers.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.gray
    self.pageControl.pageIndicatorTintColor = UIColor.gray
    self.pageControl.currentPageIndicatorTintColor = UIColor.white
    self.view.addSubview(pageControl)
}
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    let pageContentViewController = pageViewController.viewControllers![0]
    self.pageControl.currentPage = orderedViewControllers.index(of: pageContentViewController)!

}

Body:
In my case(Xcode 13), I received previous currentPage.
So use dispatchQueue asyncAfter

@objc func pageControlSelectionAction(_ sender: UIPageControl) {
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
       let page: Int? = sender.currentPage
       //scroll
    }
}

Also I just tested 'DispatchQueue.main.async' was fine.


问:
WETH Transaction does not appear in the web3.eth.get_transaction
I am trying to understand how can I see the amount of WETH transferred in a transaction. for example on OpenSea. When you go to etherscan you can see the amount. but if you use web3.eth.get_transcation(tx_hash) you will find the value to be 0 ( since its WETH and not ETH).

Any suggestions?

答:
I'm also having trouble with this.
The Phunkbot code is on github (https://github.com/albanow/phunks-nll-twitter-bot/blob/main/bot.py), and this part from the 'input' is interesting:

```<code>bid = "0x6d728796"
sale = "0xf8529df3"
accepted_bid = "0xbad9f860"
</code>```

Somehow the first 10 characters of the 'input' hex is a sign of what kind of transaction it is? Doesn't seem to be the case for the contract I'm trying to monitor but maybe this code will lead you somewhere.

Body:
I'm also having trouble with this.
The Phunkbot code is on github (https://github.com/albanow/phunks-nll-twitter-bot/blob/main/bot.py), and this part from the 'input' is interesting:

bid = "0x6d728796"
sale = "0xf8529df3"
accepted_bid = "0xbad9f860"

Somehow the first 10 characters of the 'input' hex is a sign of what kind of transaction it is? Doesn't seem to be the case for the contract I'm trying to monitor but maybe this code will lead you somewhere.


问:
How can I make my array into a map when saved in Firestore?
I have dynamic text fields that would repeat every time I'll click a button. As of now, the colorList is an array, and this is how it shows in the console I plan to save this in firestore.

console

Firebase

I wanted to store this in Firebase as map so it'll be something like red: 10 since I would be updating these stocks red

Codes

```<code>const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

{colorList.map((singleColor, index) => (
        <div key={index}>
          <div style={{ display: "flex" }}>
            <Grid item>
              <TextField
                label="color"
                name="color"
                type="text"
                id="color"
                required
                value={singleColor.color}
                onChange={(e) => handleColorChange(e, index)}
              />
            </Grid>
            <br />
            <Grid item >
              <TextField
                label="Stocks"
                name="colorStocks"
                type="number"
                id="colorStocks"
                required
                value={singleColor.colorStocks}
                onChange={(e) => handleColorChange(e, index)}
              />
            </Grid>
          </div>
          <br />
           //buttons here to add and remove textfields
        </div>
      ))}
</code>```

答:
You can use Array.prototype.reduce() for this:</p>
```<code>const colorMap = colorList.reduce(function(map, obj) {
   map[obj.color] = obj.colorStocks;
   return map;
}, {});
</code>```

Body:
I have dynamic text fields that would repeat every time I'll click a button. As of now, the colorList is an array, and this is how it shows in the console I plan to save this in firestore.

console

Firebase

I wanted to store this in Firebase as map so it'll be something like red: 10 since I would be updating these stocks red

Codes

const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

{colorList.map((singleColor, index) => (

            <Grid item>
              <TextField
                label="color"
                name="color"
                type="text"
                id="color"
                required
                value={singleColor.color}
                onChange={(e) => handleColorChange(e, index)}
              />
            </Grid>

            <Grid item >
              <TextField
                label="Stocks"
                name="colorStocks"
                type="number"
                id="colorStocks"
                required
                value={singleColor.colorStocks}
                onChange={(e) => handleColorChange(e, index)}
              />
            </Grid>

           //buttons here to add and remove textfields

      ))}

Body:
You can use Array.prototype.reduce() for this:

const colorMap = colorList.reduce(function(map, obj) {
   map[obj.color] = obj.colorStocks;
   return map;
}, {});


问:
(Torch tenor) Subtracting different dimension matrices
```<code>matrice1 = temp.unsqueeze(0)
print(M.shape)
matrice2 = M.permute(1, 0, 2, 3)
print(matrice2.shape)
print( torch.abs(matrice1 - matrice2).shape )

#torch.Size([1, 10, 3, 256])
#torch.Size([10, 1, 3, 256])
#torch.Size([10, 10, 3, 256])
</code>```

I got the outcome above. I am wondering why the subtraction between two different dimension tensors make the outcome the tensor that has the shape as [10,10,3,256].

答: According to the broadcast semantics of PyTorch,The two tensors are "broadcastable" in your case, so they are automatically expanded to the equal size of torch.Size([10, 10, 3, 256]).

Body:
matrice1 = temp.unsqueeze(0)
print(M.shape)
matrice2 = M.permute(1, 0, 2, 3)
print(matrice2.shape)
print( torch.abs(matrice1 - matrice2).shape )

#torch.Size([1, 10, 3, 256])
#torch.Size([10, 1, 3, 256])
#torch.Size([10, 10, 3, 256])

I got the outcome above. I am wondering why the subtraction between two different dimension tensors make the outcome the tensor that has the shape as [10,10,3,256].


问:
SQL update query using joins
I have to update a field with a value which is returned by a join of 3 tables.

Example:

```<code>select
    im.itemid
    ,im.sku as iSku
    ,gm.SKU as GSKU
    ,mm.ManufacturerId as ManuId
    ,mm.ManufacturerName
    ,im.mf_item_number
    ,mm.ManufacturerID
from
    item_master im, group_master gm, Manufacturer_Master mm
where
    im.mf_item_number like 'STA%'
    and im.sku=gm.sku
    and gm.ManufacturerID = mm.ManufacturerID
    and gm.manufacturerID=34
</code>```

I want to update the mf_item_number field values of table item_master with some other value which is joined in the above condition.

How can I do this in MS SQL Server?

答:
I've been trying to do things like this forever and it just occurred to me to try using the following syntax (using tuples)

```<code>update dstTable T
set (T.field1, T.field2, T.field3) =
       (select S.value1, S.value2, S.value3
        from srcTable S
         where S.key = T.Key);
</code>```

And surprisingly it worked.  I'm using Oracle (12c I think).  Is this standard  SQL or Oracle specific?

NB: In my example I'm updating the entire table (filling new columns). The update has no where clause so all rows will be updated. Your fields will be set to NULL when the subquery doesn't return a row. (and it must not return more than one row).

ContentLicense: CC BY-SA 3.0

Title: SQL update query using joins

Body:
I have to update a field with a value which is returned by a join of 3 tables.

Example:

select
    im.itemid
    ,im.sku as iSku
    ,gm.SKU as GSKU
    ,mm.ManufacturerId as ManuId
    ,mm.ManufacturerName
    ,im.mf_item_number
    ,mm.ManufacturerID
from
    item_master im, group_master gm, Manufacturer_Master mm
where
    im.mf_item_number like 'STA%'
    and im.sku=gm.sku
    and gm.ManufacturerID = mm.ManufacturerID
    and gm.manufacturerID=34

I want to update the mf_item_number field values of table item_master with some other value which is joined in the above condition.

How can I do this in MS SQL Server?

Body:
I've been trying to do things like this forever and it just occurred to me to try using the following syntax (using tuples)

update dstTable T
set (T.field1, T.field2, T.field3) =
       (select S.value1, S.value2, S.value3
        from srcTable S
         where S.key = T.Key);

And surprisingly it worked.  I'm using Oracle (12c I think).  Is this standard  SQL or Oracle specific?

NB: In my example I'm updating the entire table (filling new columns). The update has no where clause so all rows will be updated. Your fields will be set to NULL when the subquery doesn't return a row. (and it must not return more than one row).


问:
Drogon: how to use execSqlCoro? What headers to include?
I'm tryin to use the execSqlCoro function of Drogon. However, I am getting an error:

```<code>error: unable to find the promise type for this coroutine
   26 |   auto municipalities = co_await db->execSqlCoro(
</code>```

What headers to I have to include to get the correct promise type?

See tests here. I tried

```<code>#include <drogon/orm/DbClient.h>
#include <drogon/orm/CoroMapper.h>
</code>```

to no avail.

答: Did you enable c++20 when compiling?</p>

Body:
I'm tryin to use the execSqlCoro function of Drogon. However, I am getting an error:

error: unable to find the promise type for this coroutine
   26 |   auto municipalities = co_await db->execSqlCoro(

What headers to I have to include to get the correct promise type?

See tests here. I tried

#include <drogon/orm/DbClient.h>
#include <drogon/orm/CoroMapper.h>

to no avail.

Body: Did you enable c++20 when compiling?


问:
Share external script between VueJS components
I am trying to load the external Stripe script in one component here https://gitlab.com/gadelkareem/skeleton/-/blob/feature/stripe/src/frontend/src/components/payment/PaymentMethods.vue#L167

```<code>      this.includeStripe('js.stripe.com/v3/', function () {
        this.configureStripe()
      }.bind(this))
</code>```

Then I load a dialog inside the same page which also needs the same Stripe() script so I have to load it again here https://gitlab.com/gadelkareem/skeleton/-/blob/feature/stripe/src/frontend/src/components/payment/AddPaymentMethod.vue#L147 with similar duplicated code.

Is there a way to share that script between both components? preferably without making it global.

答:
You can create the init() and configureStripe() method in Vue's global context.

main.js

new Vue({
  ...
  methods: {
    init() {
       this.includeStripe('js.stripe.com/v3/', function () {
        this.configureStripe()
      }.bind(this))
    },
    configureStripe () {
      // eslint-disable-next-line no-undef
      this.stripe = Stripe(this.pk)

      this.elements = this.stripe.elements()
      this.card = this.elements.create('card', {
        hidePostalCode: false,
        style: {
          base: {
            iconColor: '#666EE8',
            color: '#31325F',
            lineHeight: '40px',
            fontWeight: 300,
            fontFamily: 'Helvetica Neue',
            fontSize: '15px',

            '::placeholder': {
              color: '#CFD7E0'
            }
          }
        }
      })

      this.card.mount('#card-element')
    },
  }
  ...
});
```

Body:
I am trying to load the external Stripe script in one component here https://gitlab.com/gadelkareem/skeleton/-/blob/feature/stripe/src/frontend/src/components/payment/PaymentMethods.vue#L167

      this.includeStripe('js.stripe.com/v3/', function () {
        this.configureStripe()
      }.bind(this))

Then I load a dialog inside the same page which also needs the same Stripe() script so I have to load it again here https://gitlab.com/gadelkareem/skeleton/-/blob/feature/stripe/src/frontend/src/components/payment/AddPaymentMethod.vue#L147 with similar duplicated code.

Is there a way to share that script between both components? preferably without making it global.


问:
Freeradius not loading up client conf
this is my clients.conf file

```<code>client localhost {
ipaddr  = 127.0.0.1
netmask= 32
secret  = 'MYSECRET'
}
client adconnector {
ipaddr  = 172.16.0.0
netmask = 16
secret  = 'MYSECRET'
}
</code>```

sudo radiusd -X shows up this

```<code>.

radiusd: #### Loading Clients ####
 client localhost {
 netmask = 32
 require_message_authenticator = no
  limit {
  max_connections = 16
  lifetime = 0
  idle_timeout = 30
  }
 }
No 'ipaddr' or 'ipv4addr' or 'ipv6addr' field found in client localhost. Please fix your configuration
Support for old-style clients will be removed in a future release
/etc/raddb/clients.conf[1]: secret must be at least 1 character long
</code>```

I don't get what am I doing wrong? It says no ippadr is found but it is clearly mentioned in the conf and also with secret length.

答:
I have just pasted your exact clients.conf contents as given in the question into a default install of the latest version, and it works correctly:

```<code>radiusd: #### Loading Clients ####
 client localhost {
    ipaddr = 127.0.0.1
    netmask = 32
    require_message_authenticator = no
    secret = <<< secret >>>
  limit {
    max_connections = 16
    lifetime = 0
    idle_timeout = 30
  }
 }
 client adconnector {
    ipaddr = 172.16.0.0
    netmask = 16
    require_message_authenticator = no
    secret = <<< secret >>>
  limit {
    max_connections = 16
    lifetime = 0
    idle_timeout = 30
  }
 }
</code>```

I suspect that you are either editing the wrong file, or there are suspect characters (UTF-8?) in the file that is confusing the parser.

Check the top of the -X debug output, it will say which file is being read, e.g.

```<code>including configuration file /etc/raddb/clients.conf
</code>```

Ensure this is the file you are editing, and there are no symlinks in the wrong places.

As another note, there is no need to use the old configuration options, or to quote strings unless they contain things that actually need quoting. For example, the following is cleaner and more recent style config:

```<code>client localhost {
  ipv4addr = 127.0.0.1
  secret = MYSECRET
}
client adconnector {
  ipv4addr = 172.16.0.0/16
  secret = MYSECRET
}
</code>```

Title: Freeradius not loading up client conf

Body:
this is my clients.conf file

client localhost {
ipaddr  = 127.0.0.1
netmask= 32
secret  = 'MYSECRET'
}
client adconnector {
ipaddr  = 172.16.0.0
netmask = 16
secret  = 'MYSECRET'
}

sudo radiusd -X shows up this

.

radiusd: #### Loading Clients ####
 client localhost {
 netmask = 32
 require_message_authenticator = no
  limit {
  max_connections = 16
  lifetime = 0
  idle_timeout = 30
  }
 }
No 'ipaddr' or 'ipv4addr' or 'ipv6addr' field found in client localhost. Please fix your configuration
Support for old-style clients will be removed in a future release
/etc/raddb/clients.conf[1]: secret must be at least 1 character long

I don't get what am I doing wrong? It says no ippadr is found but it is clearly mentioned in the conf and also with secret length.

Body:
I have just pasted your exact clients.conf contents as given in the question into a default install of the latest version, and it works correctly:

radiusd: #### Loading Clients ####
 client localhost {
    ipaddr = 127.0.0.1
    netmask = 32
    require_message_authenticator = no
    secret = <<< secret >>>
  limit {
    max_connections = 16
    lifetime = 0
    idle_timeout = 30
  }
 }
 client adconnector {
    ipaddr = 172.16.0.0
    netmask = 16
    require_message_authenticator = no
    secret = <<< secret >>>
  limit {
    max_connections = 16
    lifetime = 0
    idle_timeout = 30
  }
 }

I suspect that you are either editing the wrong file, or there are suspect characters (UTF-8?) in the file that is confusing the parser.

Check the top of the -X debug output, it will say which file is being read, e.g.

including configuration file /etc/raddb/clients.conf

Ensure this is the file you are editing, and there are no symlinks in the wrong places.

As another note, there is no need to use the old configuration options, or to quote strings unless they contain things that actually need quoting. For example, the following is cleaner and more recent style config:

client localhost {
  ipv4addr = 127.0.0.1
  secret = MYSECRET
}
client adconnector {
  ipv4addr = 172.16.0.0/16
  secret = MYSECRET
}


问:
How to use forEach() method in Java 8 loop n+1 time but my list size is random like n, n-1, n-2
How to use forEach() method in Java 8 loop n time but my list size is always random like n-1, n-2, etc.... If list size is less then n number then rest value would be zero/empty of each object value.

Below example I have Data3 object which have ID, year, listOfCompanies and value as per below code  in the end I have list of Data3 object which I want to loop using for each java8 but I want to loop 8 times for list of companies if no value then put Empty value for each object.

I try using IntStream.range function but its not working for me.

```<code>@lombok.Data
@AllArgsConstructor
static class Data3{
    int id;
    int year;
    List<String> listOfCompanies;
    double value;
}

List<String> list1 = new ArrayList<>();
list1.add("TCS"); list1.add("Cognizant");list1.add("Wipro");list1.add("Zensar");
list1.add("IBM");list1.add("Amdocs");
List<String> list2 = new ArrayList<>();
list2.add("TCS");list2.add("Cognizant");list2.add("Wipro");
List<String> list3 = new ArrayList<>();
list3.add("TCS");list3.add("Cognizant");list3.add("Wipro");list3.add("Zensar");
list3.add("IBM");
List<String> list4 = new ArrayList<>();
list4.add("TCS");list4.add("Cognizant");
Data3 d1 = new Data3(1, 1990, list1, 10);
Data3 d2 = new Data3(2, 1991, list2, 20);
Data3 d3 = new Data3(3, 1992, list3, 30);
Data3 d4 = new Data3(4, 1993, list4, 40);

List<Data3> listOfDataValues = new ArrayList<>();
listOfDataValues.add(d1);
listOfDataValues.add(d2);
listOfDataValues.add(d3);
listOfDataValues.add(d4);

listOfDataValues.stream().map(value -> new Data3(value.getId(), value.getYear(), IntStream.range(1, 8).mapToObj(index -> value.getListOfCompanies().get(index).isEmpty() ? "" : value.getListOfCompanies().get(index)), value.getValue()));
</code>```

Expected OP: (result required to loop 8 times list of companies if no
value then put Empty value )

```<code>[Test.Data3(id=1, year=1990, listOfCompanies=[TCS, Cognizant, Wipro, Zensar, IBM, Amdocs,"",""], value=10.0),
Test.Data3(id=2, year=1991, listOfCompanies=[TCS, Cognizant, Wipro,"","","","",""], value=20.0),
Test.Data3(id=3, year=1992, listOfCompanies=[TCS, Cognizant, Wipro, Zensar, IBM,"","",""], value=30.0),`
Test.Data3(id=4, year=1993, listOfCompanies=[TCS, Cognizant,"","","","","",""], value=40.0)]
</code>```

答:
```<code>listOfDataValues.stream().forEach(value -> {
    return IntStream.range(1, 8).mapToObj(new Data3(value.getId(), value.getYear(), value.getListOfCompanies(), value.getValue()));
});
</code>```

The code snippet is wrong for:

1.in forEach you don't need to return anything

2.mapToObj needs IntFunction, so you need to take an Integer as input

Actually you need to complement "" according to the size of listOfCompanies, so getting the quantity to be complemented is the key:

```<code>listOfDataValues.stream().forEach(value -> {
            int size = value.getListOfCompanies().size();
            IntStream.range(0, 8 - size).forEach(index->value.getListOfCompanies().add(""));
        });
</code>```

Body:
How to use forEach() method in Java 8 loop n time but my list size is always random like n-1, n-2, etc.... If list size is less then n number then rest value would be zero/empty of each object value.

Below example I have Data3 object which have ID, year, listOfCompanies and value as per below code  in the end I have list of Data3 object which I want to loop using for each java8 but I want to loop 8 times for list of companies if no value then put Empty value for each object.

I try using IntStream.range function but its not working for me.

@lombok.Data
@AllArgsConstructor
static class Data3{
    int id;
    int year;
    List<String> listOfCompanies;
    double value;
}

List<String> list1 = new ArrayList<>();
list1.add("TCS"); list1.add("Cognizant");list1.add("Wipro");list1.add("Zensar");
list1.add("IBM");list1.add("Amdocs");
List<String> list2 = new ArrayList<>();
list2.add("TCS");list2.add("Cognizant");list2.add("Wipro");
List<String> list3 = new ArrayList<>();
list3.add("TCS");list3.add("Cognizant");list3.add("Wipro");list3.add("Zensar");
list3.add("IBM");
List<String> list4 = new ArrayList<>();
list4.add("TCS");list4.add("Cognizant");
Data3 d1 = new Data3(1, 1990, list1, 10);
Data3 d2 = new Data3(2, 1991, list2, 20);
Data3 d3 = new Data3(3, 1992, list3, 30);
Data3 d4 = new Data3(4, 1993, list4, 40);

List<Data3> listOfDataValues = new ArrayList<>();
listOfDataValues.add(d1);
listOfDataValues.add(d2);
listOfDataValues.add(d3);
listOfDataValues.add(d4);

listOfDataValues.stream().map(value -> new Data3(value.getId(), value.getYear(), IntStream.range(1, 8).mapToObj(index -> value.getListOfCompanies().get(index).isEmpty() ? "" : value.getListOfCompanies().get(index)), value.getValue()));

Expected OP: (result required to loop 8 times list of companies if no
value then put Empty value )

[Test.Data3(id=1, year=1990, listOfCompanies=[TCS, Cognizant, Wipro, Zensar, IBM, Amdocs,"",""], value=10.0),
Test.Data3(id=2, year=1991, listOfCompanies=[TCS, Cognizant, Wipro,"","","","",""], value=20.0),
Test.Data3(id=3, year=1992, listOfCompanies=[TCS, Cognizant, Wipro, Zensar, IBM,"","",""], value=30.0),`
Test.Data3(id=4, year=1993, listOfCompanies=[TCS, Cognizant,"","","","","",""], value=40.0)]

Body:
listOfDataValues.stream().forEach(value -> {
    return IntStream.range(1, 8).mapToObj(new Data3(value.getId(), value.getYear(), value.getListOfCompanies(), value.getValue()));
});

The code snippet is wrong for:

1.in forEach you don't need to return anything

2.mapToObj needs IntFunction, so you need to take an Integer as input

Actually you need to complement "" according to the size of listOfCompanies, so getting the quantity to be complemented is the key:

listOfDataValues.stream().forEach(value -> {
            int size = value.getListOfCompanies().size();
            IntStream.range(0, 8 - size).forEach(index->value.getListOfCompanies().add(""));
        });


问:
Can't resolve errors in React JS project
I keep getting these 3 errors, but as far as I can tell I used the correct path and for the 'react-router-dom' error, I already installed that.

Compiled with problems:

ERROR in ./src/index.js 7:0-44
Module not found: Error: Can't resolve './PortfolioPage' in '/Users/AishaS/Desktop/React Portfolio Project/react-portfolio-project/src'

ERROR in ./src/index.js 10:0-74
Module not found: Error: Can't resolve 'react-router-dom' in '/Users/AishaS/Desktop/React Portfolio Project/react-portfolio-project/src'

ERROR in ./src/index.js 11:0-66
Module not found: Error: Can't resolve './components' in '/Users/AishaS/Desktop/React Portfolio Project/react-portfolio-project/src'

```<code>import React from "react";
import { render } from "react-dom";
import Gallery from "react-photo-gallery";
import { portfolio } from "./PortfolioPage";
import ReactDOM from "react-dom";
import "./index.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import {
  Navigation,
  Footer,
  About,
  Contact
} from "./components";

ReactDOM.render(
  <Router>
    <Navigation />
    <Routes>
      <Route path="/portfoliopage"  />
      <Route path="/about"  />
      <Route path="/contact" />
    </Routes>
    <Footer />
  </Router>,

  document.getElementById("root")
);

function columns(containerWidth) {
  let columns = 1;
  if (containerWidth >= 500) columns = 2;
  if (containerWidth >= 900) columns = 3;
  if (containerWidth >= 1500) columns = 4;
  return columns;
}

const App = () => {
  return (
    <div>
      <Gallery portfolio={portfolio} columns={columns} direction="column" />
    </div>
  );
};

render(<App />, document.getElementById("app"));
</code>```

答:
Your code is unable to locate the files that you are trying to import from. Would you be able to show the file structure of the project? You need to make sure that the files PortfolioPage and the folder components are on the same level as this file.

Also, make sure you have installed react-router-dom properly using npm i react-router-dom. Looks like its not installed properly.

Body:
I keep getting these 3 errors, but as far as I can tell I used the correct path and for the 'react-router-dom' error, I already installed that.

Compiled with problems:

ERROR in ./src/index.js 7:0-44
Module not found: Error: Can't resolve './PortfolioPage' in '/Users/AishaS/Desktop/React Portfolio Project/react-portfolio-project/src'

ERROR in ./src/index.js 10:0-74
Module not found: Error: Can't resolve 'react-router-dom' in '/Users/AishaS/Desktop/React Portfolio Project/react-portfolio-project/src'

ERROR in ./src/index.js 11:0-66
Module not found: Error: Can't resolve './components' in '/Users/AishaS/Desktop/React Portfolio Project/react-portfolio-project/src'

import React from "react";
import { render } from "react-dom";
import Gallery from "react-photo-gallery";
import { portfolio } from "./PortfolioPage";
import ReactDOM from "react-dom";
import "./index.css";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import {
  Navigation,
  Footer,
  About,
  Contact
} from "./components";

ReactDOM.render(
  <Router>
    <Navigation />
    <Routes>
      <Route path="/portfoliopage"  />
      <Route path="/about"  />
      <Route path="/contact" />
    </Routes>

  </Router>,

  document.getElementById("root")
);

function columns(containerWidth) {
  let columns = 1;
  if (containerWidth >= 500) columns = 2;
  if (containerWidth >= 900) columns = 3;
  if (containerWidth >= 1500) columns = 4;
  return columns;
}

const App = () => {
  return (

      <Gallery portfolio={portfolio} columns={columns} direction="column" />

  );
};

render(<App />, document.getElementById("app"));


问:
IF/THEN using IsEmpty
Probably doing something wrong here, so if I am please let me know!

What I'm trying to accomplish:

Loop through the cells in Column C, if there is a 6 digit number in the cell, then I want a formula to be added to the same row in Column U that adds the values in Columns M,N,P and R. If there is not a 6 digit number in the cell of Column C, then leave the cell in Column U alone.

My attempt to translate this into VBA is below. Note, I've added the "This Cell Should Be Empty" string to visualize if this function is doing anything temporarily. I will want to delete that.

Any suggestions to accomplish my intention here?

```<code>Sub IsEmptyRange()

Dim myRange As Range
Dim cell As Range
Dim myOutput As Range

Set myRange = Range("C1:C10")
Set myOutput = Range("U1:U10")

For Each cell In myRange.Cells

    If IsEmpty(cell) Then

    myOutput.Value = "This Cell Should Be Empty"

    ElseIf IsEmpty(cell) = False Then

    myOutput.FormulaR1C1 = "=RC13+RC14+RC16+RC18"
    End If
Next cell

End Sub
</code>```

答:
Look at using the IsNumeric function along with Len ...

```<code>Public Sub TestForSixDigitNumber()
    Dim strValue As String

    strValue = "123456"

    If IsNumeric(strValue) And Len(strValue) = 6 Then
        MsgBox "Is a 6 digit number", vbInformation, "Success"
    Else
        MsgBox "Is NOT a 6 digit number", vbCritical, "Error"
    End If
End Sub
</code>```

A word of caution though, decimal places aren't factored in here.

Alternatively, you could bake it into your formula directly, something along the lines of (changing the reference to A1) ...

```<code>=IF(AND(ISNUMBER(A1), LEN(A1) = 6), Add your values, leave it alone)
</code>```

Adapt as you see fit.

Title: IF/THEN using IsEmpty

Body:
Probably doing something wrong here, so if I am please let me know!

What I'm trying to accomplish:

Loop through the cells in Column C, if there is a 6 digit number in the cell, then I want a formula to be added to the same row in Column U that adds the values in Columns M,N,P and R. If there is not a 6 digit number in the cell of Column C, then leave the cell in Column U alone.

My attempt to translate this into VBA is below. Note, I've added the "This Cell Should Be Empty" string to visualize if this function is doing anything temporarily. I will want to delete that.

Any suggestions to accomplish my intention here?

Sub IsEmptyRange()

Dim myRange As Range
Dim cell As Range
Dim myOutput As Range

Set myRange = Range("C1:C10")
Set myOutput = Range("U1:U10")

For Each cell In myRange.Cells

    If IsEmpty(cell) Then

    myOutput.Value = "This Cell Should Be Empty"

    ElseIf IsEmpty(cell) = False Then

    myOutput.FormulaR1C1 = "=RC13+RC14+RC16+RC18"
    End If
Next cell

End Sub

Body:
Look at using the IsNumeric function along with Len ...

Public Sub TestForSixDigitNumber()
    Dim strValue As String

    strValue = "123456"

    If IsNumeric(strValue) And Len(strValue) = 6 Then
        MsgBox "Is a 6 digit number", vbInformation, "Success"
    Else
        MsgBox "Is NOT a 6 digit number", vbCritical, "Error"
    End If
End Sub

A word of caution though, decimal places aren't factored in here.

Alternatively, you could bake it into your formula directly, something along the lines of (changing the reference to A1) ...

=IF(AND(ISNUMBER(A1), LEN(A1) = 6), Add your values, leave it alone)

Adapt as you see fit.


问:
Initial "jumpy" dragging behavior
The following code creates a background and a rectangle. The rectangle can be dragged:

```<code>var p = {
  x: 0,
  y: 0
}

var width = 400
var height = 400

var svg = d3.select('body').append('svg')
  .attr('width', width)
  .attr('height', height)

svg.append('rect')
  .attr('class', 'bg')
  .attr('width', width)
  .attr('height', height)

var drag = d3.behavior.drag()
  .on('drag', dragmove)

svg.append('rect')
  .attr('class', 'btn')
  .attr('width', 100)
  .attr('height', 50)
  .attr('transform', 'translate(' + p.x + ',' + p.y + ')')
  .call(drag)

function dragmove (d) {
  var x = d3.event.x
  var y = d3.event.y
  d3.select(this)
    .attr('transform', 'translate(' + x + ',' + y + ')')
}
</code>```

The dragging event works, but there's an initial "jump" each time I drag the object (e.g the rectangle starts on the left of the cursor and then suddenly jumps to the right).

You can see it here: https://jsfiddle.net/alexcheninfo/5rnv7ww5/

What is causing it and how to prevent it (make the rectangle being dragged smoothly from the beginning)?

答:
For those who struggling this, my 50 cents. In d3 js v7 there is no event.dx or event.dy properties, instead you have to read event.movementX and event.movementY properties. Here is my working code (I only needed x position). The getTokenizedTransformAttributeValue method is taken from here: https://www.it-swarm-es.com/es/javascript/sustitucion-de-d3.transform-en-d3-v4/825493251/

```<code>self=this;
const consty = 100; //example
let dragHandler = this.d3.drag()
     .on("drag", function() {
          const inputTrasformString = self.d3.select(this).attr("transform");
          var transformObject = self.getTokenizedTransformAttributeValue(inputTrasformString);
          x = event.movementX+parseInt(transformObject.translate[0])

          self.d3.select(this)
              .attr("transform", "translate("+x+","+consty+")");
          }).on("start",function() {
        //something
                }).on("end", function() {
        //something
              });

dragHandler(svg.select(".myclass"));
</code>```

Title: Initial "jumpy" dragging behavior

Body:
The following code creates a background and a rectangle. The rectangle can be dragged:

var p = {
  x: 0,
  y: 0
}

var width = 400
var height = 400

var svg = d3.select('body').append('svg')
  .attr('width', width)
  .attr('height', height)

svg.append('rect')
  .attr('class', 'bg')
  .attr('width', width)
  .attr('height', height)

var drag = d3.behavior.drag()
  .on('drag', dragmove)

svg.append('rect')
  .attr('class', 'btn')
  .attr('width', 100)
  .attr('height', 50)
  .attr('transform', 'translate(' + p.x + ',' + p.y + ')')
  .call(drag)

function dragmove (d) {
  var x = d3.event.x
  var y = d3.event.y
  d3.select(this)
    .attr('transform', 'translate(' + x + ',' + y + ')')
}

The dragging event works, but there's an initial "jump" each time I drag the object (e.g the rectangle starts on the left of the cursor and then suddenly jumps to the right).

You can see it here: https://jsfiddle.net/alexcheninfo/5rnv7ww5/

What is causing it and how to prevent it (make the rectangle being dragged smoothly from the beginning)?

Body:
For those who struggling this, my 50 cents. In d3 js v7 there is no event.dx or event.dy properties, instead you have to read event.movementX and event.movementY properties. Here is my working code (I only needed x position). The getTokenizedTransformAttributeValue method is taken from here: https://www.it-swarm-es.com/es/javascript/sustitucion-de-d3.transform-en-d3-v4/825493251/

self=this;
const consty = 100; //example
let dragHandler = this.d3.drag()
     .on("drag", function() {
          const inputTrasformString = self.d3.select(this).attr("transform");
          var transformObject = self.getTokenizedTransformAttributeValue(inputTrasformString);
          x = event.movementX+parseInt(transformObject.translate[0])

          self.d3.select(this)
              .attr("transform", "translate("+x+","+consty+")");
          }).on("start",function() {
        //something
                }).on("end", function() {
        //something
              });

dragHandler(svg.select(".myclass"));


问:
Facing error while restarting npm , npm start is showing error
I am new to react ,I have tried npm start, after I closed my pc once, after I restarted npm start is showing error, I have tried adding start command to my JSON file , still its not starting, I have googled it , even I tried all the methods mentioned here in stack overflow , but its showing error all the time.

答:
You have 2 package.json file

First under \Covid 19 Tracker folder

Second under \Covid 19 Tracker\Covid_19 folder

Seems like First Package.json doesn't have start script.

If you are trying to start app from wrong package.json, you will get this error. You should cd into the inner folder (if you are trying to start react app).


问:
rails 3 - 'or' scopes
We are updating a rails 2 app. We have happily been using fake_arel which provides a very nice 'or' scope.

Now, with rails 3 I can't find a way to replicate this.

We have code like this:

```<code>scope.or(Event.horse, Event.dog, Event.trap).today
</code>```

The model looks like this:

```<code>class Event < ActiveRecord::Base
 named_scope :horse, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_horse_ids] }}
 named_scope :dog, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_dog_ids] }}
 named_scope :trap, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_trap_ids] }}
end
</code>```

These scopes need to be separate and are used all over the place. This model actually has dozens of scopes on it that are used in combination, so rewriting it all is the last thing we want to do.

It seems strange that you can't 'or' scopes together.

Can someone propose a way to do this as nicely in Rails 3? Even using arel I don't see how to.
We are using meta_where in a different project, but it doesn't offer any such thing either.

答:
I ripped out the 'or' function from fake_arel and got it working with rails 3.0x (not sure if it will work with 3.1 as we don't use that here)

I case anyone is interested I have put it in a gist:

Title: rails 3 - 'or' scopes

Body:
We are updating a rails 2 app. We have happily been using fake_arel which provides a very nice 'or' scope.

Now, with rails 3 I can't find a way to replicate this.

We have code like this:

scope.or(Event.horse, Event.dog, Event.trap).today

The model looks like this:

class Event < ActiveRecord::Base
 named_scope :horse, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_horse_ids] }}
 named_scope :dog, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_dog_ids] }}
 named_scope :trap, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_trap_ids] }}
end

These scopes need to be separate and are used all over the place. This model actually has dozens of scopes on it that are used in combination, so rewriting it all is the last thing we want to do.

It seems strange that you can't 'or' scopes together.

Can someone propose a way to do this as nicely in Rails 3? Even using arel I don't see how to.
We are using meta_where in a different project, but it doesn't offer any such thing either.


问:
What causes this error during our DevOps build
We have a Visual Studio project in Azure Devops. We are using VS2019.

The build was working with this project. However, earlier this week the build stopped working. The error message is below.

I checked the build server. The .Net framework 4 is installed. Also, the project framework has not changed.

It looks like the MSBUILD is trying to use VS2022.

How can I change the build to use the VS2019 MSBUILD? How is this set?

How can I correct the below error?

```<code>##[error]C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1217,5):

Error MSB3644: The reference assemblies for .NETFramework,Version=v4.5 were not found
</code>```

答:
It might be caused by environment variables of Azure Agent server(build serer).

You can review environment variables via

project setting - agent pools - your agent pool - agents tab - agent - capabilities tab

check value of MSBuild variable, to see if it point to "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin"

if so, login Azure Agent server then update MSBuild variable to VS2019.

Body:
We have a Visual Studio project in Azure Devops. We are using VS2019.

The build was working with this project. However, earlier this week the build stopped working. The error message is below.

I checked the build server. The .Net framework 4 is installed. Also, the project framework has not changed.

It looks like the MSBUILD is trying to use VS2022.

How can I change the build to use the VS2019 MSBUILD? How is this set?

How can I correct the below error?

##[error]C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(1217,5):

Error MSB3644: The reference assemblies for .NETFramework,Version=v4.5 were not found


问:
Automate for loop to increase samples selected
I am looking to run a loop that selects 2 rows from a data frame 1000 times > store that into an object >  then run the same loop that selects 3 rows 1000 times > store to object > then 4, and so on. The end goal is to compare the means/variances of the columns when different numbers of rows are randomly selected in the loop.

Code

```<code>iris<- iris

results2<- list()

counter<- 0
for (i in 1:1000) {
  # sample 2 randomly selected rows 1000 times
  tempsample2<- iris[sample(1:nrow(iris), 2, replace=F), ]

  # store results of sampling into the created list
  results2[[i]]= tempsample2

  counter<- counter+1
  print(counter)
}
</code>```

I can manually store all of these loops into separate objects to then make comparisons, but I'm guessing that there is an easier way to do that. Can anyone help me with this? Thanks for your time.

答:
You can use lapply and save the output as nested list.

```<code>select_rows <- 2:4
n_times <- 5
inds <- nrow(iris)

result <- lapply(select_rows, function(x)
                replicate(n_times, iris[sample(inds, x), ], simplify = FALSE))
</code>```

Change select_rows and n_times as per your choice.

Body:
I am looking to run a loop that selects 2 rows from a data frame 1000 times > store that into an object >  then run the same loop that selects 3 rows 1000 times > store to object > then 4, and so on. The end goal is to compare the means/variances of the columns when different numbers of rows are randomly selected in the loop.

Code

iris<- iris

results2<- list()

counter<- 0
for (i in 1:1000) {
  # sample 2 randomly selected rows 1000 times
  tempsample2<- iris[sample(1:nrow(iris), 2, replace=F), ]

  # store results of sampling into the created list
  results2[[i]]= tempsample2

  counter<- counter+1
  print(counter)
}

I can manually store all of these loops into separate objects to then make comparisons, but I'm guessing that there is an easier way to do that. Can anyone help me with this? Thanks for your time.

Body:
You can use lapply and save the output as nested list.

select_rows <- 2:4
n_times <- 5
inds <- nrow(iris)

result <- lapply(select_rows, function(x)
                replicate(n_times, iris[sample(inds, x), ], simplify = FALSE))

Change select_rows and n_times as per your choice.


问:
Getting value of random address location without storing it in a variable
```<code>#include<iostream>
using namespace std;

struct node{
    int data;
    node* l,*r;
};

int main()
{
    node* n1 = new node;
    cout<<(n1->l);
    return 0;
}
</code>```

in the above code I didn't initialize struct data, l and r. so now the address stored in n1->l is CDCDCDCD. Now if I want to see the value stored in that address how to see that without storing the address in a variable.

答:
In general, you can cast any integer to a pointer at your own risk.

node* my_ptr = (node*)0xDEADBEEF;  // Casting to a pointer
node my_node = *(node*)0xDEADBEEF; // Casting to a pointer and dereferencing
```

The second line is what I believe you want to do "without storing the address in a variable". However that's hacky and useful only in specific contexts, such as DLL injection.

Body:
#include<iostream>
using namespace std;

struct node{
    int data;
    node* l,*r;
};

int main()
{
    node* n1 = new node;
    cout<<(n1->l);
    return 0;
}

in the above code I didn't initialize struct data, l and r. so now the address stored in n1->l is CDCDCDCD. Now if I want to see the value stored in that address how to see that without storing the address in a variable.

Body:
In general, you can cast any integer to a pointer at your own risk.

node* my_ptr = (node*)0xDEADBEEF;  // Casting to a pointer
node my_node = *(node*)0xDEADBEEF; // Casting to a pointer and dereferencing

The second line is what I believe you want to do "without storing the address in a variable". However that's hacky and useful only in specific contexts, such as DLL injection.


问:
What IDE should I use for Linux module development?
I have Ubuntu 11.04 and am looking to start developing Linux modules. I use Visual Studio for C development in Windows, but I guess that's not an option for Linux. What would be a good IDE to work Linux modules ?</p>

答: Eclipse (http://eclipse.org/) is a pretty good IDE. I have tried a few other ones such as KDevelop etc, but I have always found Eclipse to be the best and most stable.</p>


问:
Navigation dropdown moving content below not working
I am almost done with my business website https://www.housewashingdelmarva.com/. However, when viewing on my phone and I click the hamburger drop-down menu, the menu goes over my header. I would like it to push the header down when clicked like another website I built https://oceancitymdlawncare.com/. What error did I make?

I am using W3.CSS as my framework.

Thx

```<code><!--Navigation Buttons-->
<div class="w3-top w3-center w3-theme-d5">
    <div class="w3-bar w3-theme-d3 w3-round-xxlarge">
        <a class="w3-bar-item w3-button w3-hover-cyan" href="https://www.housewashingdelmarva.com/"><i class="fa fa-home"></i></a>
        <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Services">Power Washing Services</a>
        <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Testimonials">Testimonials</a>
        <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Gallery">Gallery</a>
        <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#FAQ">FAQ</a>
        <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#About-Us">About Us</a>
        <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Contact-Us">Contact Us</a>
        <a href="javascript:void(0)" class="w3-bar-item w3-button w3-right w3-hide-large w3-hover-cyan w3-hide-medium" onclick="myFunction('demo')">☰</a>
    </div>

<!-- Navbar on small screens (remove the onclick attribute if you want the navbar to always show on top of the content when clicking on the links) -->
    <div id="demo" class="w3-bar-block w3-clear w3-theme-d3 w3-hide w3-hide-medium w3-hide-large">
        <a class="w3-bar-item w3-button w3-hover-cyan" href="https://www.housewashingdelmarva.com/" onclick="myFunction()"><i class="fa fa-home"></i></a>
        <a class="w3-bar-item w3-button w3-hover-cyan" href="#Services">Power Washing Services</a>
        <a class="w3-bar-item w3-button w3-hover-cyan" href="#Testimonials">Testimonials</a>
        <a class="w3-bar-item w3-button w3-hover-cyan" href="#Gallery">Gallery</a>
        <a class="w3-bar-item w3-button w3-hover-cyan" href="#FAQ">FAQ</a>
        <a class="w3-bar-item w3-button w3-hover-cyan" href="#About-Us">About Us</a>
        <a class="w3-bar-item w3-button w3-hover-cyan" href="#Contact-Us">Contact Us</a>
    </div>

</div>
<script>
function myFunction() {
  var x = document.getElementById("demo");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}
</script>

</code>```

答: In the one that's working the div you're adding w3-show class to on click of the menu burger is a sibling of the header element and they're both block elements so they sit on top of one another in normal document flow. In the one that's not working, the element you're adding w3-show to is a child of another div that isn't set to display block, and that other div is the sibling of the header element not the div that's being modified by the click event.</p>

Body:
I am almost done with my business website https://www.housewashingdelmarva.com/. However, when viewing on my phone and I click the hamburger drop-down menu, the menu goes over my header. I would like it to push the header down when clicked like another website I built https://oceancitymdlawncare.com/. What error did I make?

I am using W3.CSS as my framework.

Thx

        Power Washing Services
        Testimonials
        Gallery
        FAQ
        About Us
        Contact Us
        ☰

        Power Washing Services
        Testimonials
        Gallery
        FAQ
        About Us
        Contact Us


问:
Want to add multiple images by extracting one method
I wanted to add 3 circle image picker avatar and wanted to upload 3 different pictures in them but unfortunately not able to do that. I tried to do this by extracting the method and passing the image to the single extracted build method and in result the chosen one image is applied to all three avatars. Kindly help me get through it.

Below are the functions for picking image from gallery and camera :

```<code> File _image;
  final Picker = ImagePicker();
  _imgFromCamera() async {

    final image = await Picker.pickImage(
        source: ImageSource.camera, imageQuality: 50
    );

    setState(() {
      _image = File(image.path);
    });
  }

  _imgFromGallery() async {
     final image = await  Picker.pickImage(
        source: ImageSource.gallery, imageQuality: 50
    );

    setState(() {
      _image = File(image.path);
    });
  }
</code>```

Next is function for bottom sheet for picking the image either from gallery or camera:

```<code>void _showPicker(context) {
showModalBottomSheet(
    context: context,
    builder: (BuildContext bc) {
      return SafeArea(
        child: Container(
          child: new Wrap(
            children: <Widget>[
              new ListTile(
                  leading: new Icon(Icons.photo_library),
                  title: new Text('Photo Library'),
                  onTap: () {
                    _imgFromGallery();
                    Navigator.of(context).pop();
                  }),
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text('Camera'),
                onTap: () {
                  _imgFromCamera();
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        ),
      );
    }
);
</code>```

}

And here is the extracted method that I want to use for once for all three images:

```<code>GestureDetector buildGestureDetector(BuildContext context) {
return GestureDetector(
                    onTap: () {
                      _showPicker(context);
                    },
                    child: CircleAvatar(
                      radius: 53,
                      backgroundColor: Colors.black,
                      child: _image != null
                          ? ClipRRect(
                        borderRadius: BorderRadius.circular(50),
                        child: Image.file(
                          _image,
                          width: 100,
                          height: 100,
                          fit: BoxFit.fitHeight,
                        ),
                      )
                          : Container(
                        decoration: BoxDecoration(
                            color: Colors.grey[200],
                            borderRadius: BorderRadius.circular(50)),
                        width: 100,
                        height: 100,
                        child: Icon(
                          Icons.camera_alt,
                          color: Colors.grey[800],
                        ),
                      ),
                    ),
                  );
</code>```

}
}

And here is that extracted method is called inside widget :

```<code> Row(
                children: [
                  Expanded(
                    child: buildGestureDetector(context),
                  ),
                ],
              ),
</code>```

Kindly help me with applying 3 different pictures using this one extracted method and all the functions used once so that I don't need to go through all this process for all three pictures again and again.

答:
The easiest way to handle this is of course passing "which avatar" info down to _imgFromCamera or _imgFromGallery .
For example, if your 3 images have their own identities like 'A', 'B' and 'C',

```<code>onTap: () {
  _showPicker(context, 'A');
},
</code>```

Then pass it to the _showPicker.

```<code>void _showPicker(context, id) {
...
  onTap: () {
     _imgFromGallery(id);   // Passed 'A' in this example
     Navigator.of(context).pop();
  }),
...
</code>```

Then,

```<code>_imgFromGallery(id) async {
    final image = await  Picker.pickImage(
        source: ImageSource.gallery, imageQuality: 50
    );

    // Depends on the id, decide where and how to save the image.
    switch(id) {
      case 'A': setState(...); break;
      case 'B': saveIntoLocal(...); break;
      case 'C': uploadToServer(...); break;
      ....
    }
  }
</code>```

Body:
I wanted to add 3 circle image picker avatar and wanted to upload 3 different pictures in them but unfortunately not able to do that. I tried to do this by extracting the method and passing the image to the single extracted build method and in result the chosen one image is applied to all three avatars. Kindly help me get through it.

Below are the functions for picking image from gallery and camera :

 File _image;
  final Picker = ImagePicker();
  _imgFromCamera() async {

    final image = await Picker.pickImage(
        source: ImageSource.camera, imageQuality: 50
    );

    setState(() {
      _image = File(image.path);
    });
  }

  _imgFromGallery() async {
     final image = await  Picker.pickImage(
        source: ImageSource.gallery, imageQuality: 50
    );

    setState(() {
      _image = File(image.path);
    });
  }

Next is function for bottom sheet for picking the image either from gallery or camera:

void _showPicker(context) {
showModalBottomSheet(
    context: context,
    builder: (BuildContext bc) {
      return SafeArea(
        child: Container(
          child: new Wrap(
            children: <Widget>[
              new ListTile(
                  leading: new Icon(Icons.photo_library),
                  title: new Text('Photo Library'),
                  onTap: () {
                    _imgFromGallery();
                    Navigator.of(context).pop();
                  }),
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text('Camera'),
                onTap: () {
                  _imgFromCamera();
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
        ),
      );
    }
);

}

And here is the extracted method that I want to use for once for all three images:

GestureDetector buildGestureDetector(BuildContext context) {
return GestureDetector(
                    onTap: () {
                      _showPicker(context);
                    },
                    child: CircleAvatar(
                      radius: 53,
                      backgroundColor: Colors.black,
                      child: _image != null
                          ? ClipRRect(
                        borderRadius: BorderRadius.circular(50),
                        child: Image.file(
                          _image,
                          width: 100,
                          height: 100,
                          fit: BoxFit.fitHeight,
                        ),
                      )
                          : Container(
                        decoration: BoxDecoration(
                            color: Colors.grey[200],
                            borderRadius: BorderRadius.circular(50)),
                        width: 100,
                        height: 100,
                        child: Icon(
                          Icons.camera_alt,
                          color: Colors.grey[800],
                        ),
                      ),
                    ),
                  );

}
}

And here is that extracted method is called inside widget :

 Row(
                children: [
                  Expanded(
                    child: buildGestureDetector(context),
                  ),
                ],
              ),

Kindly help me with applying 3 different pictures using this one extracted method and all the functions used once so that I don't need to go through all this process for all three pictures again and again.

Body:
The easiest way to handle this is of course passing "which avatar" info down to _imgFromCamera or _imgFromGallery .
For example, if your 3 images have their own identities like 'A', 'B' and 'C',

onTap: () {
  _showPicker(context, 'A');
},

Then pass it to the _showPicker.

void _showPicker(context, id) {
...
  onTap: () {
     _imgFromGallery(id);   // Passed 'A' in this example
     Navigator.of(context).pop();
  }),
...

Then,

_imgFromGallery(id) async {
    final image = await  Picker.pickImage(
        source: ImageSource.gallery, imageQuality: 50
    );

    // Depends on the id, decide where and how to save the image.
    switch(id) {
      case 'A': setState(...); break;
      case 'B': saveIntoLocal(...); break;
      case 'C': uploadToServer(...); break;
      ....
    }
  }


问:
Postgres "UPDATE FROM VALUES" with different number of nullable columns?
values() requires each row to have the same number of columns. Sometimes, I want to update different columns for different rows. If the columns weren't nullable, I could do something like:

```<code>update test set
  foo = coalesce(t.foo, foo),
  bar = coalesce(t.bar, bar)
from (values
  (1, 'foo val', null),
  (2, null, 'bar val')
) as t(id, foo, bar)
where t.id = test.id;
</code>```

However, if the columns are nullable, this wouldn't work. Is there a way to make this work for nullable columns?

答:
You might be able to pick some special value which is valid for the type, but will never actually be used in your table.  Then that value could represent "keep old value". If not, then you probably need more columns.

```<code>update test set
  foo = case when not set_foo_null then coalesce(t.foo, test.foo) end,
  bar = case when not set_bar_null then coalesce(t.bar, test.bar) end
from (values
  (1, 'foo val', null, false, true),
  (2, null, 'bar val', false, false)
) as t(id, foo, bar, set_foo_null, set_bar_null)
where t.id = test.id;
</code>```

Of course there are many other ways to formulate, maybe better would be to name the bool "keep_old_foo" then foo = case when keep_old_foo then test.foo else t.foo end

Body:
values() requires each row to have the same number of columns. Sometimes, I want to update different columns for different rows. If the columns weren't nullable, I could do something like:

update test set
  foo = coalesce(t.foo, foo),
  bar = coalesce(t.bar, bar)
from (values
  (1, 'foo val', null),
  (2, null, 'bar val')
) as t(id, foo, bar)
where t.id = test.id;

However, if the columns are nullable, this wouldn't work. Is there a way to make this work for nullable columns?

Body:
You might be able to pick some special value which is valid for the type, but will never actually be used in your table.  Then that value could represent "keep old value". If not, then you probably need more columns.

update test set
  foo = case when not set_foo_null then coalesce(t.foo, test.foo) end,
  bar = case when not set_bar_null then coalesce(t.bar, test.bar) end
from (values
  (1, 'foo val', null, false, true),
  (2, null, 'bar val', false, false)
) as t(id, foo, bar, set_foo_null, set_bar_null)
where t.id = test.id;

Of course there are many other ways to formulate, maybe better would be to name the bool "keep_old_foo" then foo = case when keep_old_foo then test.foo else t.foo end