问:
Why does my express-session variable return 'undefined' on a different route?
I have a simple login form which sets a session after the login is successful

```<code>router.post('/', (req, res) => {
  const { username, password } = req.body;

  // TODO: Hash password
  if (username === 'admin' && password === 'test') {
    req.session.user = username;
    res.redirect('/dashboard');
  } else {
    // TODO: Validation
  }
});
</code>```

Before this I set the middleware:

```<code>router.use(sessions({
  secret: 'supersecret',
  resave: false,
  saveUninitialized: false,
  cookie: {
    sameSite: true,
    secure: true,
    expires: false
  }
}));
</code>```

After the session.user is set, the router redirects to /dashboard, but when I try to console.log(req.session.user), it returns undefined, though req.session doesn't.

```<code>router.get('/dashboard', (req, res) => {
  console.log(req.session.user);

  if (req.session.user) {
    Product.find({}, (e, products) => {
      if (e) console.error(e);

      res.render('dashboard', {
        products: products
      });
    });
  } else {
    res.redirect('/');
  }
});
</code>```

Does anyone see what I'm doing wrong here? It might also be worth noting that it does return the correct value inside /.

答: Turns out it didn't work because I set cookie.secure to true. But this only works on https sites, though I'm testing this on my localhost. So the solution is as simple as setting secure: false.

Body:
I have a simple login form which sets a session after the login is successful

router.post('/', (req, res) => {
  const { username, password } = req.body;

  // TODO: Hash password
  if (username === 'admin' && password === 'test') {
    req.session.user = username;
    res.redirect('/dashboard');
  } else {
    // TODO: Validation
  }
});

Before this I set the middleware:

router.use(sessions({
  secret: 'supersecret',
  resave: false,
  saveUninitialized: false,
  cookie: {
    sameSite: true,
    secure: true,
    expires: false
  }
}));

After the session.user is set, the router redirects to /dashboard, but when I try to console.log(req.session.user), it returns undefined, though req.session doesn't.

router.get('/dashboard', (req, res) => {
  console.log(req.session.user);

  if (req.session.user) {
    Product.find({}, (e, products) => {
      if (e) console.error(e);

      res.render('dashboard', {
        products: products
      });
    });
  } else {
    res.redirect('/');
  }
});

Does anyone see what I'm doing wrong here? It might also be worth noting that it does return the correct value inside /.


来源: stackexchange

问:
Getting Error: 'No module named flask' in VSCode even when I have installed flask
I want to debug an application using Python and Flask in VSCode. I have installed Flask and the app runs perfectly fine through cmd. But, when I try to debug it through VSCode, it gives the following error:

```<code>cd 'c:\Users\Aditi\CleanHandymanApp';
${env:FLASK_APP}='NewApp'; ${env:PYTHONIOENCODING}='UTF-8';
${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\Aditi\envs\CleanHandymanApp\Scripts\python.exe'
'c:\Users\Aditi\.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py' '--client' '--host'
'localhost' '--port' '63143' '-m' 'flask' 'run' '--no-debugger' '--no-reload'
No module named flask
</code>```

Can you please help me.

答:
This error message can occur if you installed the python3 version of flask but Visual Studio Code tries to run your project with python2.

Make sure to select the correct version of python in the editor. This can be done by running the command Python: Select Interpreter from the Command Palette (Ctrl+Shift+P).

ContentLicense: CC BY-SA 4.0

Body:
I want to debug an application using Python and Flask in VSCode. I have installed Flask and the app runs perfectly fine through cmd. But, when I try to debug it through VSCode, it gives the following error:

cd 'c:\Users\Aditi\CleanHandymanApp';
${env:FLASK_APP}='NewApp'; ${env:PYTHONIOENCODING}='UTF-8';
${env:PYTHONUNBUFFERED}='1'; & 'C:\Users\Aditi\envs\CleanHandymanApp\Scripts\python.exe'
'c:\Users\Aditi\.vscode\extensions\ms-python.python-2018.10.1\pythonFiles\experimental\ptvsd_launcher.py' '--client' '--host'
'localhost' '--port' '63143' '-m' 'flask' 'run' '--no-debugger' '--no-reload'
No module named flask

Can you please help me.


问:
When to use new keyword?
I am working on a small game in SFML, I created a game class that will store various classes; for example, the player class.

I initialized the class on the heap with "new" keyword, but after hours of trying to figure out why my player class was going null after a certain scope. I decided not to initialize the game on the heap and after I did that, everything was fine.

Can someone please explain why this was happening. By the way, I am not creating the game on the heap anymore, I am showing the code I previously had when I was getting the null reference.

```<code>int main()
{
    sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "Dungeon Run");

    //Asset test;
    //test.CreateAsset("GameAssets/Player.png");

    sf::Event event;
    renderWindow.setKeyRepeatEnabled(true);

    Game* game = new Game(renderWindow);
// Player initialized here.
    game->Initialize();
    while (renderWindow.isOpen())
    {
// Game->Player goes null in here.
        while (renderWindow.pollEvent(event))
        {

            if (event.type == sf::Event::EventType::Closed)
            {
                renderWindow.close();
            }
            //set window to random color to check if working
            if (event.type == sf::Event::EventType::KeyPressed) {
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
                    renderWindow.close();
                }
            }
            else if (event.type == sf::Event::EventType::MouseButtonPressed) {
                if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
                }
                else if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
                }
            }

            renderWindow.clear();
            game->Draw(); // Here player was null when I tried to draw the sprite for the player.
            renderWindow.display();
        }
    }

delete game;
game = nullptr;
}
</code>```

Player class:

```<code>class Player
{
public:
    Player();
    Player(std::string name)
        : name(name)
    {
    }

    std::string name = "";
    double health = 100;
    double stamina = 100;
    int level = 1;
    Asset sprite;

    void attack();

    ~Player();
};

</code>```

Asset class:

```<code>Asset::Asset() {

}

void Asset::CreateAsset(std::string path) {
    if (!texture.loadFromFile(path)) {
        std::cout << "Failed to load texture from file: " << path << std::endl;
    }

    sprite.setTexture(texture);
}

sf::Sprite& Asset::GetSprite() {
    return sprite;
}

Asset::~Asset() {

}

</code>```

Game.h and Game.cpp:

```<code>class Game {
private:
    Player player;
    sf::RenderWindow* window;
public:
    Game(sf::RenderWindow& window);

    void Initialize();
    void Upadte();
    void Draw();

    ~Game();
};

Game::Game(sf::RenderWindow& window) {
    this->window = &window;
    player = Player("Player");
}

void Game::Initialize() {
    player.sprite.CreateAsset("GameAssets/player.png");
}

void Game::Upadte() {
}

void Game::Draw() {
    window->draw(player.sprite.GetSprite()); // Drawing his sprite
}

Game::~Game() {
}

</code>```

答:
in modern c++ you almost never need the new keyword

if you want to create a object on the heap, use a unique_ptr or a shared_ptr

you create your class with

```<code>std::unique_ptr<Game> game = std::make_unique<Game>(renderWindow);
</code>```

this way you do not need a delete as the unique_ptr will take care of that for you when it runs out of scope.

so just replace your new line with the above and remove the line with delete

you may need the following include to use std::unique_ptr

```<code>#include <memory>
</code>```

as for the "why" you had a problem: The code responsible is not posted yet, but i'd assume you have another place where game is deleted or set to nullptr

Title: When to use new keyword?

Body:
I am working on a small game in SFML, I created a game class that will store various classes; for example, the player class.

I initialized the class on the heap with "new" keyword, but after hours of trying to figure out why my player class was going null after a certain scope. I decided not to initialize the game on the heap and after I did that, everything was fine.

Can someone please explain why this was happening. By the way, I am not creating the game on the heap anymore, I am showing the code I previously had when I was getting the null reference.

int main()
{
    sf::RenderWindow renderWindow(sf::VideoMode(640, 480), "Dungeon Run");

    //Asset test;
    //test.CreateAsset("GameAssets/Player.png");

    sf::Event event;
    renderWindow.setKeyRepeatEnabled(true);

    Game* game = new Game(renderWindow);
// Player initialized here.
    game->Initialize();
    while (renderWindow.isOpen())
    {
// Game->Player goes null in here.
        while (renderWindow.pollEvent(event))
        {

            if (event.type == sf::Event::EventType::Closed)
            {
                renderWindow.close();
            }
            //set window to random color to check if working
            if (event.type == sf::Event::EventType::KeyPressed) {
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
                }
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
                    renderWindow.close();
                }
            }
            else if (event.type == sf::Event::EventType::MouseButtonPressed) {
                if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
                }
                else if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) {
                }
            }

            renderWindow.clear();
            game->Draw(); // Here player was null when I tried to draw the sprite for the player.
            renderWindow.display();
        }
    }

delete game;
game = nullptr;
}

Player class:

class Player
{
public:
    Player();
    Player(std::string name)
        : name(name)
    {
    }

    std::string name = "";
    double health = 100;
    double stamina = 100;
    int level = 1;
    Asset sprite;

    void attack();

    ~Player();
};

Asset class:

Asset::Asset() {

}

void Asset::CreateAsset(std::string path) {
    if (!texture.loadFromFile(path)) {
        std::cout << "Failed to load texture from file: " << path << std::endl;
    }

    sprite.setTexture(texture);
}

sf::Sprite& Asset::GetSprite() {
    return sprite;
}

Asset::~Asset() {

}

Game.h and Game.cpp:

class Game {
private:
    Player player;
    sf::RenderWindow* window;
public:
    Game(sf::RenderWindow& window);

    void Initialize();
    void Upadte();
    void Draw();

    ~Game();
};

Game::Game(sf::RenderWindow& window) {
    this->window = &window;
    player = Player("Player");
}

void Game::Initialize() {
    player.sprite.CreateAsset("GameAssets/player.png");
}

void Game::Upadte() {
}

void Game::Draw() {
    window->draw(player.sprite.GetSprite()); // Drawing his sprite
}

Game::~Game() {
}

Body:
in modern c++ you almost never need the new keyword

if you want to create a object on the heap, use a unique_ptr or a shared_ptr

you create your class with

std::unique_ptr<Game> game = std::make_unique<Game>(renderWindow);

this way you do not need a delete as the unique_ptr will take care of that for you when it runs out of scope.

so just replace your new line with the above and remove the line with delete

you may need the following include to use std::unique_ptr

#include <memory>

as for the "why" you had a problem: The code responsible is not posted yet, but i'd assume you have another place where game is deleted or set to nullptr


问:
How to load a file into Elm REPL?
For example:  in this repo, https://github.com/evancz/elm-architecture-tutorial/ , how do I load one of the Elm files into elm repl, so I can evaluate functions, look at type signatures, etc ?

In Haskell I would use :l

答:
This would be better placed as a comment on kaskelotti's good answer above, but in order to have the module in a different folder from where you start the repl, you can update the elm.json file associated with your project, adding "YOUR_DESIRED_DIRECTORY" to the "source-directories" array.

Also note that the filename needs to match the module name in the export and import statements:

so that

```<code>module SomeModule exposing (fun1, fun2)
</code>```

would require a file named SomeModule.elm (at least in my experience)

Title: How to load a file into Elm REPL?

Body:
This would be better placed as a comment on kaskelotti's good answer above, but in order to have the module in a different folder from where you start the repl, you can update the elm.json file associated with your project, adding "YOUR_DESIRED_DIRECTORY" to the "source-directories" array.

Also note that the filename needs to match the module name in the export and import statements:

so that

module SomeModule exposing (fun1, fun2)

would require a file named SomeModule.elm (at least in my experience)


问:
How to choose a split variables for continous features for decision tree
I am currently implementing decision tree algorithm. If I have a continous featured data how do i decide a splitting point. I came across few resources which say to choose mid points between every two points but considering I have 8000 rows of data this would be very time consuming. The output/feature label is having category data. Is any approach where I can perform this operation quicker</p>

答: Decision tree works calculating entropy and information gain to determine the most important feature. Indeed, 8000 row is not too much for decision tree. But generally, Random forest is similar to decision tree. It is working as ensemble. You can review and try it.Moreover,  maybe being slowly is related to another thing.</p>


问:
Finding a float in a python list
I am surprised to see this python behavior, but couldn't understand why? I am not able to search 0.3 in a python list.</p>

```<code>>> import numpy as np
>> Lambdas = np.arange(0.0, 1.05, 0.05)
>> print(Lambdas)
[0.   0.05 0.1  0.15 0.2  0.25 0.3  0.35 0.4  0.45 0.5  0.55 0.6  0.65
 0.7  0.75 0.8  0.85 0.9  0.95 1.  ]
>> print(0.3 in Lambdas)
False
>> print(0.30 in Lambdas)
False
>> print(0.1 in Lambdas)
True
>> print(0.4 in Lambdas)
True
>> print(1 in Lambdas)
True
>> print(1.0 in Lambdas)
True
>> print(0.1 in Lambdas)
True
>>
</code>```

答:
As per Mehdi's comprehensive answer and ruohola's comment, the floating point value stored in the array is likely not to be exactly 0.3

You can try using numpy.allclose(), setting the tolerance for the minimum difference with the atol or rtol arguments - docs here

Title: Finding a float in a python list

Body:
I am surprised to see this python behavior, but couldn't understand why? I am not able to search 0.3 in a python list.

>> import numpy as np
>> Lambdas = np.arange(0.0, 1.05, 0.05)
>> print(Lambdas)
[0.   0.05 0.1  0.15 0.2  0.25 0.3  0.35 0.4  0.45 0.5  0.55 0.6  0.65
 0.7  0.75 0.8  0.85 0.9  0.95 1.  ]
>> print(0.3 in Lambdas)
False
>> print(0.30 in Lambdas)
False
>> print(0.1 in Lambdas)
True
>> print(0.4 in Lambdas)
True
>> print(1 in Lambdas)
True
>> print(1.0 in Lambdas)
True
>> print(0.1 in Lambdas)
True
>>


答:
According to http://0.30000000000000004.com/

Your language isn't broken, it's doing floating point math. Computers can only natively store integers, so they need some way of
  representing decimal numbers. This representation comes with some
  degree of inaccuracy. That's why, more often than not, .1 + .2 != .3.

Why does this happen? It's actually pretty simple. When you have a
  base 10 system (like ours), it can only express fractions that use a
  prime factor of the base. The prime factors of 10 are 2 and 5. So 1/2,
  1/4, 1/5, 1/8, and 1/10 can all be expressed cleanly because the
  denominators all use prime factors of 10. In contrast, 1/3, 1/6, and
  1/7 are all repeating decimals because their denominators use a prime
  factor of 3 or 7. In binary (or base 2), the only prime factor is 2.
  So you can only express fractions cleanly which only contain 2 as a
  prime factor. In binary, 1/2, 1/4, 1/8 would all be expressed cleanly
  as decimals. While, 1/5 or 1/10 would be repeating decimals. So 0.1
  and 0.2 (1/10 and 1/5) while clean decimals in a base 10 system, are
  repeating decimals in the base 2 system the computer is operating in.
  When you do math on these repeating decimals, you end up with
  leftovers which carry over when you convert the computer's base 2
  (binary) number into a more human readable base 10 number.

Title: Finding a float in a python list


问:
Select all / Unselect all in Bootstrap Select plugin
```<code><select id="divRatings" class="selectpicker" multiple title='Choose one of the following...' data-size="5" data-selected-text-format="count>2">
    <option value="All" selected="selected">All Ratings</option>
    <option value="EC">EC (Early Childhood)</option>
    <option value="E">E (Everyone)</option>
    <option value="E10+">E10+ (Everyone 10+)</option>
    <option value="T">T (Teen)</option>
    <option value="M">M (Mature)</option>
    <option value="AO">AO (Adults Only)</option>
</select>
</code>```

In html above there are option with value All. I want to select all items if that option is selected and unselect all if i unselect this option.

I think it will be simple to do, but i can't get why nothing happens on $('#divRatings').change(function(){//some logic});

My function to select/ unselect items:

```<code>function toggleSelectAll(control) {
    if (control.val().indexOf("All,") > -1) {
        control.selectpicker('selectAll');
    } else {
        control.selectpicker('deselectAll');
    }
}
</code>```

JSFiddle example

答:
I started with @glyuck answer but changed it a little bit.  I didn't want the 'All' item to be selected and then have the bootstrap-select show 'N items selected' in which one of them was the 'All' item.  So basically, for me, that item will 'never select', it is more or less just a 'button' to toggle the states.

My markup would look like this:

```<code><select size="4" multiple="multiple" class="form-control selectpicker show-tick select-all" data-selected-text-format="count > 2">
    <option value="[all]" class="select-all">All Items</option>
    <option value="" data-divider="true"></option>
    <option value="0">Members Selected</option>
    <option value="1">Separated Members Selected</option>
    <option value="2">Request Approval</option>
    <option value="3">Approved</option>
    <option value="4">Rejected</option>
</select>
</code>```

Then the code to make it work the way I wanted was:

```<code>$('.selectpicker.select-all').on('change', function () {
    var selectPicker = $(this);
    var selectAllOption = selectPicker.find('option.select-all');
    var checkedAll = selectAllOption.prop('selected');
    var optionValues = selectPicker.find('option[value!="[all]"][data-divider!="true"]');

    if (checkedAll) {
        // Process 'all/none' checking
        var allChecked = selectAllOption.data("all") || false;

        if (!allChecked) {
            optionValues.prop('selected', true).parent().selectpicker('refresh');
            selectAllOption.data("all", true);
        }
        else {
            optionValues.prop('selected', false).parent().selectpicker('refresh');
            selectAllOption.data("all", false);
        }

        selectAllOption.prop('selected', false).parent().selectpicker('refresh');
    }
    else {
        // Clicked another item, determine if all selected
        var allSelected = optionValues.filter(":selected").length == optionValues.length;
        selectAllOption.data("all", allSelected);
    }
}).trigger('change');
</code>```

Thanks @glyuck for the inspiration.

Fiddle: http://jsfiddle.net/3Lr4jsz0/

Body:
<select id="divRatings" class="selectpicker" multiple title='Choose one of the following...' data-size="5" data-selected-text-format="count>2">
    <option value="All" selected="selected">All Ratings</option>
    <option value="EC">EC (Early Childhood)</option>
    <option value="E">E (Everyone)</option>
    <option value="E10+">E10+ (Everyone 10+)</option>
    <option value="T">T (Teen)</option>
    <option value="M">M (Mature)</option>
    <option value="AO">AO (Adults Only)</option>
</select>

In html above there are option with value All. I want to select all items if that option is selected and unselect all if i unselect this option.

I think it will be simple to do, but i can't get why nothing happens on $('#divRatings').change(function(){//some logic});

My function to select/ unselect items:

function toggleSelectAll(control) {
    if (control.val().indexOf("All,") > -1) {
        control.selectpicker('selectAll');
    } else {
        control.selectpicker('deselectAll');
    }
}

JSFiddle example

Body:
I started with @glyuck answer but changed it a little bit.  I didn't want the 'All' item to be selected and then have the bootstrap-select show 'N items selected' in which one of them was the 'All' item.  So basically, for me, that item will 'never select', it is more or less just a 'button' to toggle the states.

My markup would look like this:

<select size="4" multiple="multiple" class="form-control selectpicker show-tick select-all" data-selected-text-format="count > 2">
    <option value="[all]" class="select-all">All Items</option>
    <option value="" data-divider="true"></option>
    <option value="0">Members Selected</option>
    <option value="1">Separated Members Selected</option>
    <option value="2">Request Approval</option>
    <option value="3">Approved</option>
    <option value="4">Rejected</option>
</select>

Then the code to make it work the way I wanted was:

$('.selectpicker.select-all').on('change', function () {
    var selectPicker = $(this);
    var selectAllOption = selectPicker.find('option.select-all');
    var checkedAll = selectAllOption.prop('selected');
    var optionValues = selectPicker.find('option[value!="[all]"][data-divider!="true"]');

    if (checkedAll) {
        // Process 'all/none' checking
        var allChecked = selectAllOption.data("all") || false;

        if (!allChecked) {
            optionValues.prop('selected', true).parent().selectpicker('refresh');
            selectAllOption.data("all", true);
        }
        else {
            optionValues.prop('selected', false).parent().selectpicker('refresh');
            selectAllOption.data("all", false);
        }

        selectAllOption.prop('selected', false).parent().selectpicker('refresh');
    }
    else {
        // Clicked another item, determine if all selected
        var allSelected = optionValues.filter(":selected").length == optionValues.length;
        selectAllOption.data("all", allSelected);
    }
}).trigger('change');

Thanks @glyuck for the inspiration.

Fiddle: http://jsfiddle.net/3Lr4jsz0/


问:
Why does .Net care when an assembly was built?
We had a situation where we were having issues with a DLL that was build in our office which is located in the Central time zone and then deployed onto a server located on the west coast (Pacific time zone).  We'd have issues with "UTCDate out of range" when trying to retrieve embedded resources from our DLL (via WebResource.axd).  Once we discovered this and updated the DLL's file time to match the web server's time, everything worked fine.

My question is: Why does .Net care when an assembly was built?

Thanks.

答: I believe the time the file was created is used to see if the file needs to be replaced when building a solution. Other than that I don't know.</p>

ContentLicense: CC BY-SA 3.0


问:
Session is set, but not working after going to another page just at first time
I have a login.php and a few pages for userarea. After login, it works and it goes to user.php and I use some $_SESSION variables to show the name and username. It works, also my $_SESSION variables are set at first time too and it will stay on the user.php.

But when I go to another page of userarea, it returned me to login.php, but if I login again, then it is OK and no problem and I can go to different pages without problem. Why?

I tried these things:

I changed $_SESSION['log_in'] from boolean to string or use another session like $_SESSION['username'] for !isset($_SESSION['username']) (top of each pages). This username session will be show in the user.php but after that I go to another page doesn't work.

I have session_start() top of every page.

```<code><?php
session_start();
if(!isset($_SESSION['log_in'])){
   header("Location: login.php");
}
// I have this code top of every page.
?>
</code>```

This is login.php:

```<code><?php
   session_start();
   if(isset($_SESSION['log_in'])){
   header("Location:user.php");
}
    if( password_verify($_POST['password'],$user['password'])) {
        $_SESSION['name'] = $user['name'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['username'] = $user['username'];

        //to know is user login or not
        $_SESSION['log_in'] = TRUE;
        echo "<meta http-equiv=Refresh content=2;url=user.php>";
        //if I user header("Location: user.php") it doesn't go to user, but with meta it goes to user.php
?>
</code>```

This is user.php:

```<code><?php
session_start();
if(!isset($_SESSION['log_in'])){
   header("Location: login.php");
}
// this is top of my user.php and top of another pages too.
?>
</code>```

This is logout:

```<code><?php
session_start();
if(isset($_SESSION['log_in'])) {
    session_unset();
    session_destroy();
    header('location: login.php');
} else {
    session_unset();
    session_destroy();
    header('location: http://www.mywebsite.com');
}
// this is my logout.php
?>
</code>```

I don't get any error, and I have another session part too for admins, but I wrote totally different session, for example $_SESSION['admin_log_in'] it has just one page and it works good.

答:
I just spotted the problem - this is an enormously tricky issue to debug.

This is one of your code snippets, with an extra line of code - the exit:

```<code><?php
session_start();
if(!isset($_SESSION['log_in'])){
   header("Location: login.php");
   exit();
}
// this is top of my user.php and top of another pages too.
?>
</code>```

So, what is happening here?

The header() call queues up an HTTP header to be sent to the browser - it may be sent immediately or it may be sent once HTML input is emitted by your program (since you are not explicitly flushing this information, we don't know exactly when it will be sent).

The important thing to note is that when you call header(), your PHP script carries on executing. You have not told it to stop. So, it will do a bunch of things you did not expect.

At some point, the browser will receive the Location header, and will terminate the connection, and in most web server configurations, PHP will stop executing, since your web server is in control of the PHP interpreter. Thus, you have a race condition between the browser terminating the connection and your script getting to the end; what gets executed in the script will probably vary from one run to another. This will depend partly on network latency - a slower network connection will allow the script to get further before it is terminated.

Ensuring that you stop the script immediately after the header call, or at least exiting deliberately and gracefully, will resolve this.

Body:
I have a login.php and a few pages for userarea. After login, it works and it goes to user.php and I use some $_SESSION variables to show the name and username. It works, also my $_SESSION variables are set at first time too and it will stay on the user.php.

But when I go to another page of userarea, it returned me to login.php, but if I login again, then it is OK and no problem and I can go to different pages without problem. Why?

I tried these things:

I changed $_SESSION['log_in'] from boolean to string or use another session like $_SESSION['username'] for !isset($_SESSION['username']) (top of each pages). This username session will be show in the user.php but after that I go to another page doesn't work.

I have session_start() top of every page.

<?php
session_start();
if(!isset($_SESSION['log_in'])){
   header("Location: login.php");
}
// I have this code top of every page.
?>

This is login.php:

<?php
   session_start();
   if(isset($_SESSION['log_in'])){
   header("Location:user.php");
}
    if( password_verify($_POST['password'],$user['password'])) {
        $_SESSION['name'] = $user['name'];
        $_SESSION['email'] = $user['email'];
        $_SESSION['username'] = $user['username'];

        //to know is user login or not
        $_SESSION['log_in'] = TRUE;
        echo "<meta http-equiv=Refresh content=2;url=user.php>";
        //if I user header("Location: user.php") it doesn't go to user, but with meta it goes to user.php
?>

This is user.php:

<?php
session_start();
if(!isset($_SESSION['log_in'])){
   header("Location: login.php");
}
// this is top of my user.php and top of another pages too.
?>

This is logout:

<?php
session_start();
if(isset($_SESSION['log_in'])) {
    session_unset();
    session_destroy();
    header('location: login.php');
} else {
    session_unset();
    session_destroy();
    header('location: http://www.mywebsite.com');
}
// this is my logout.php
?>

I don't get any error, and I have another session part too for admins, but I wrote totally different session, for example $_SESSION['admin_log_in'] it has just one page and it works good.

Body:
I just spotted the problem - this is an enormously tricky issue to debug.

This is one of your code snippets, with an extra line of code - the exit:

<?php
session_start();
if(!isset($_SESSION['log_in'])){
   header("Location: login.php");
   exit();
}
// this is top of my user.php and top of another pages too.
?>

So, what is happening here?

The header() call queues up an HTTP header to be sent to the browser - it may be sent immediately or it may be sent once HTML input is emitted by your program (since you are not explicitly flushing this information, we don't know exactly when it will be sent).

The important thing to note is that when you call header(), your PHP script carries on executing. You have not told it to stop. So, it will do a bunch of things you did not expect.

At some point, the browser will receive the Location header, and will terminate the connection, and in most web server configurations, PHP will stop executing, since your web server is in control of the PHP interpreter. Thus, you have a race condition between the browser terminating the connection and your script getting to the end; what gets executed in the script will probably vary from one run to another. This will depend partly on network latency - a slower network connection will allow the script to get further before it is terminated.

Ensuring that you stop the script immediately after the header call, or at least exiting deliberately and gracefully, will resolve this.


问:
How can I export a table in csv or txt format, with a concatenated name?
I'm using a query to create a table, and then trying to export that table as a CSV file. Working in Access 2007.

I can get it to export as an XLS using the code below, but the named file has long spaces (not dots as shown) and is indented, when you look at it in the folder.

```<code>Example = [………….Factorysvc……….190601...………….]

DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)……
</code>```

I've tried changing the XLS to CSV & TXT but get the following error:

"The format in which you are attempting to output the current object is not available"

dbo_setup contains 2 fields:

droppath = where to put the file

LocationName = Factorysvc

Here is the complete code:

```<code>DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)", DLookup("droppath", "dbo_SetupExp") & DLookup("LocationName", "dbo_SetupExp") & Format(Date, "yymmdd") & ".xls", False, "", 0, acExportQualityPrint
</code>```

Would like to get it to export a csv or text file with the dbo_SetupExp.LocationName and date created combined in the file name.

```<code>Example: FactorySvc190601.csv
</code>```

答:
Without access to the data held in your dbo_SetupExp table, I can't explain the behaviour you are witnessing, however, in an attempt to workaround it I would suggest the following:

DoCmd.OutputTo acOutputTable, "CustItemExp", acFormatXLS, _
    Trim(DFirst("droppath",     "dbo_SetupExp")) & _
    Trim(DFirst("LocationName", "dbo_SetupExp")) & _
    Format(Date, "yymmdd") & ".xls"
```

<p>Aside, since you are not supplying the <code>DLookup</code> function with a <code>criteria</code> argument (and hence the function will return a random record from the table), <code>DFirst</code> seems like a more applicable function for this purpose.</p>

<p>To output the data to a <code>CSV</code> or <code>TXT</code> file instead of <code>XLS</code>, I would suggest using the <code>TransferText</code> method of the <code>DoCmd</code> object, e.g.:</p>

<pre class="lang-vb prettyprint-override"><code>DoCmd.TransferText acExportDelim, , "CustItemExp", _
    Trim(DFirst("droppath",     "dbo_SetupExp")) & _
    Trim(DFirst("LocationName", "dbo_SetupExp")) & _
    Format(Date, "yymmdd") & ".csv", True
</code>```

Body:
I'm using a query to create a table, and then trying to export that table as a CSV file. Working in Access 2007.

I can get it to export as an XLS using the code below, but the named file has long spaces (not dots as shown) and is indented, when you look at it in the folder.

Example = [………….Factorysvc……….190601...………….]

DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)……

I've tried changing the XLS to CSV & TXT but get the following error:

"The format in which you are attempting to output the current object is not available"

dbo_setup contains 2 fields:

droppath = where to put the file

LocationName = Factorysvc

Here is the complete code:

DoCmd.OutputTo acOutputTable, "CustItemExp", "Excel97-Excel2003Workbook(*.xls)", DLookup("droppath", "dbo_SetupExp") & DLookup("LocationName", "dbo_SetupExp") & Format(Date, "yymmdd") & ".xls", False, "", 0, acExportQualityPrint

Would like to get it to export a csv or text file with the dbo_SetupExp.LocationName and date created combined in the file name.

Example: FactorySvc190601.csv

Body:
Without access to the data held in your dbo_SetupExp table, I can't explain the behaviour you are witnessing, however, in an attempt to workaround it I would suggest the following:

DoCmd.OutputTo acOutputTable, "CustItemExp", acFormatXLS, _
    Trim(DFirst("droppath",     "dbo_SetupExp")) & _
    Trim(DFirst("LocationName", "dbo_SetupExp")) & _
    Format(Date, "yymmdd") & ".xls"

Aside, since you are not supplying the DLookup function with a criteria argument (and hence the function will return a random record from the table), DFirst seems like a more applicable function for this purpose.

To output the data to a CSV or TXT file instead of XLS, I would suggest using the TransferText method of the DoCmd object, e.g.:

DoCmd.TransferText acExportDelim, , "CustItemExp", _
    Trim(DFirst("droppath",     "dbo_SetupExp")) & _
    Trim(DFirst("LocationName", "dbo_SetupExp")) & _
    Format(Date, "yymmdd") & ".csv", True


答:
(Posted on behalf of the question author).

I should open my website "www.".

Title: Session is set, but not working after going to another page just at first time


问:
Override the enter key, but keep default behavior for other keys in a wpf datagrid
It really bothers me that the pressing the enter key in a Datagrid moves the selection down one item, I'd like to be able to decide what it does in a normal keydown event.

So what I did was create a new class that inherits DataGrid and override the OnKeyDown event and use that as my datagrid.

This creates a whole new set of problems, since I apparently have to rewrite all the other keypresses (arrow key navigation, shift+arrow key selection, pgup/pgdn, etc..). I've been trying to hack it, but it just seems so pointless spending time rewriting something that has already been written and probably better then whatever I'll come up with.

So how can I make the enter key do what I want without messing with the other default keybindings of the datagrid?

Thanks in advance

答: Just check if the key pressed is enter, if it's not, call the base event handler for KeyDown (something like base.OnKeyDown(sender, args);)


问:
Measuring temperature while benchmarking on Linux
I want to measure the temperature and frequency of a two socket machine while performing the High-Performance Linpack benchmark.

I wrote a shell script sensor.sh that I start in the background with sh sensors.sh &  and then proceed to the benchmark.

```<code>for ((;;))
do
awk 'BEGIN{ORS=" ";} $2=="MHz" {print $4} END {print "\n"}' /proc/cpuinfo >> cpuf.dat

awk 'BEGIN{ORS=" ";} {print $1} END {print "\n"}' /sys/devices/platform/coretemp.?/hwmon/hwmon?/temp*_input >> cput.dat
 sleep .1
done
</code>```

I get my outputfiles, however the timestamps are not 0.1s apart from each other. I guess the system is busy and the shell script process is not executed that often. HPL says it has a runtime of ~1100s, in this time my temperature.dat file generated ~4600 entries.

Is there another way I can measure the temperature and frequency while performing my benchmark program and store the output in a .dat file?

答:
Your script is very inefficient, requiring a lot of separate processes to each get some CPU time before it can run the next sleep  .1 so yes, system load is going to make it run less frequently.

Also, sensors is relatively expensive; maybe use command line options to have it only check CPU temp.  Or I think CPU temp is available from files in /proc or /sys directly.

xargs with no arguments defaults to echo, so it's just an inefficient way to collapse whitespace characters (including newline) to spaces.  (If you use printf '%s\n' foo bar | strace -f xargs you can see it actually does fork + execve /bin/echo instead of simply printing the output itself like you could do with sed or tr.)

you could use more efficient commands for text processing that need less CPU time, and fewer context switches by piping through fewer separate processes.  e.g. sensors piped into just one awk command that does all the text processing.  And sed -n 's/cpu MHz : //p' /proc/cpuinfo >> frequency.dat to avoid a useless use of cat (and xargs).

But that's still going to have some overhead.

You could write one perl script that pipes from sensors, and closes/reopens /proc/cpuinfo.  That would avoid all the system calls that process startup makes.

Instead of sleeping for a fixed time, you can have it check the current time and sleep until the next multiple of 0.1 seconds.  You could do that with bash, too, but that will require running even more commands and you want to cause as few context switches as possible for your benchmark.

You could also or instead label each line with current time, so you know when each sample came from.  To do this without needing to start another external process, use bash's $EPOCHREALTIME.  Like { echo -n "$EPOCHREALTIME  "; awk ...; } >> cpuf.dat if you're still using bash instead of Perl.

Body:
I want to measure the temperature and frequency of a two socket machine while performing the High-Performance Linpack benchmark.

I wrote a shell script sensor.sh that I start in the background with sh sensors.sh &  and then proceed to the benchmark.

for ((;;))
do
awk 'BEGIN{ORS=" ";} $2=="MHz" {print $4} END {print "\n"}' /proc/cpuinfo >> cpuf.dat

awk 'BEGIN{ORS=" ";} {print $1} END {print "\n"}' /sys/devices/platform/coretemp.?/hwmon/hwmon?/temp*_input >> cput.dat
 sleep .1
done

I get my outputfiles, however the timestamps are not 0.1s apart from each other. I guess the system is busy and the shell script process is not executed that often. HPL says it has a runtime of ~1100s, in this time my temperature.dat file generated ~4600 entries.

Is there another way I can measure the temperature and frequency while performing my benchmark program and store the output in a .dat file?


问:
What's going on in this do while loop with break?
I'm trying to understand how this do/while loop with a break statement works. I thought that whenever the break statement is executed (the first two iterations, since the if condition is true those times but not the third time), the for loop is escaped and therefore n isn't incremented. But the line console.log(`n is ${n}`) logs n is 2 n is 2 n is 5 -- how does it jump from 2 to 5? I thought it would be 3 the third time (when the if condition isn't true, since quot is 60 and 60 % 2 does equal 0, and therefore the break statement isn't executed).

```<code>  // newArray = [5, 4, 3, 2, 1];

  var quot = 0;
  var loop = 1;
  var n;

  do {
        quot = newArr[0] * loop * newArr[1];
        for (n = 2; n < newArr.length; n++) {
          if (quot % newArr[n] !== 0) {
            break;
          }
        }

        console.log(`n is ${n}`)

        loop++;
   } while (n !== newArr.length);
</code>```

Here's the full code (a solution for a freeCodeCamp challenge):

```<code>function smallestCommons(arr) {
  // Sort array from greater to lowest
  // This line of code was from Adam Doyle (http://github.com/Adoyle2014)
  arr.sort(function(a, b) {
    return b - a;
  });

  // Create new array and add all values from greater to smaller from the
  // original array.
  var newArr = [];
  for (var i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
  }

  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    console.log(`n is ${n}`)

    loop++;
  } while (n !== newArr.length);

  return quot;
}

// test here
smallestCommons([1,5]);
</code>```

答:
Your array length is 5, so if your if statement and break are not executed, then n will always be 5.

(n = 2; n < newArr.length; n++)

The last time this is executed, n=4, n < newArr.length (which is 5), n++ (now n is 5)

Like you said in your question "the if condition isn't true, since quot is 60 and 60 % 2 does equal 0, and therefore the break statement isn't executed"

Your break statement will only serve to get you out of your for loop early, if your for loop completes it's full cycle then n will always be 5.

Hope that makes sense!

Body:
I'm trying to understand how this do/while loop with a break statement works. I thought that whenever the break statement is executed (the first two iterations, since the if condition is true those times but not the third time), the for loop is escaped and therefore n isn't incremented. But the line console.log(`n is ${n}`) logs n is 2 n is 2 n is 5 -- how does it jump from 2 to 5? I thought it would be 3 the third time (when the if condition isn't true, since quot is 60 and 60 % 2 does equal 0, and therefore the break statement isn't executed).

  // newArray = [5, 4, 3, 2, 1];

  var quot = 0;
  var loop = 1;
  var n;

  do {
        quot = newArr[0] * loop * newArr[1];
        for (n = 2; n < newArr.length; n++) {
          if (quot % newArr[n] !== 0) {
            break;
          }
        }

        console.log(`n is ${n}`)

        loop++;
   } while (n !== newArr.length);

Here's the full code (a solution for a freeCodeCamp challenge):

function smallestCommons(arr) {
  // Sort array from greater to lowest
  // This line of code was from Adam Doyle (http://github.com/Adoyle2014)
  arr.sort(function(a, b) {
    return b - a;
  });

  // Create new array and add all values from greater to smaller from the
  // original array.
  var newArr = [];
  for (var i = arr[0]; i >= arr[1]; i--) {
    newArr.push(i);
  }

  // Variables needed declared outside the loops.
  var quot = 0;
  var loop = 1;
  var n;

  // Run code while n is not the same as the array length.
  do {
    quot = newArr[0] * loop * newArr[1];
    for (n = 2; n < newArr.length; n++) {
      if (quot % newArr[n] !== 0) {
        break;
      }
    }

    console.log(`n is ${n}`)

    loop++;
  } while (n !== newArr.length);

  return quot;
}

// test here
smallestCommons([1,5]);


问:
Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?
Is there a workaround for

'ORA-01795: maximum number of expressions in a list is 1000 error'

I have a query and it is selecting fields based on the value of one field. I am using the in clause and there are 10000+ values

example:

```<code>select field1, field2, field3
from table1
where name in
(
'value1',
'value2',
...
'value10000+'
);
</code>```

Every time I execute the query I get the ORA-01795: maximum number of expressions in a list is 1000 error. I am trying to execute the query in TOAD, no difference, the same error. How would I modify the query to get it to work?

答:
There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

```<code>select * from tableA where id = 1 or id = 2 or id = 3 ...
</code>```

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.

Body:
Is there a workaround for

'ORA-01795: maximum number of expressions in a list is 1000 error'

I have a query and it is selecting fields based on the value of one field. I am using the in clause and there are 10000+ values

example:

select field1, field2, field3
from table1
where name in
(
'value1',
'value2',
...
'value10000+'
);

Every time I execute the query I get the ORA-01795: maximum number of expressions in a list is 1000 error. I am trying to execute the query in TOAD, no difference, the same error. How would I modify the query to get it to work?

Body:
There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.

select * from tableA where id = 1 or id = 2 or id = 3 ...

But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.


问:
How to save the value of a range slider (multiple input form) in Django
I have a range slider as a one file of my form. I can update the value of the item with js.
Sending the checkboxes state works, however, for some reason I cannot get range slider value.

Here's my template:

<form method="POST">
    {% csrf_token %}

        Easy
        <input type="checkbox" name="checks" value="1">

     <input type="range" min="1" max="120" value="120" class="form-control-range" id="time_slider">
      min.
<input type="submit" id="update" name = "update" value="Filter">
</form>

```

<p>and my view.py:</p>

<pre class="lang-py prettyprint-override"><code>def item_list(request):

    items = Items.objects.all()

    if request.POST:
        if 'update' in request.POST:
            check_list = request.POST.getlist('checks')
            time = request.POST.get('slider_value')
            if check_list:
                items=items.filter(level__in=check_list)
            if time:
                items=items.filter(time__lte=time)
</code>```

If I print the check_list there are all the checkboxes I tick. The slider is responsive, script works but no value is send to my view. All I get is "None". Switching get to time_slider is not helping either. What I did wrong?

答:
Give your range input a name attribute. Since you are already checking for slider_valu in your backend code, then you can change your code to be this:

```<code><input name="slider_value" type="range" min="1" max="120" value="120" class="form-control-range" id="time_slider">
</code>```

Body:
I have a range slider as a one file of my form. I can update the value of the item with js.
Sending the checkboxes state works, however, for some reason I cannot get range slider value.

Here's my template:

<form method="POST">
    {% csrf_token %}

        Easy
        <input type="checkbox" name="checks" value="1">

     <input type="range" min="1" max="120" value="120" class="form-control-range" id="time_slider">
      min.
<input type="submit" id="update" name = "update" value="Filter">
</form>

and my view.py:

def item_list(request):

    items = Items.objects.all()

    if request.POST:
        if 'update' in request.POST:
            check_list = request.POST.getlist('checks')
            time = request.POST.get('slider_value')
            if check_list:
                items=items.filter(level__in=check_list)
            if time:
                items=items.filter(time__lte=time)

If I print the check_list there are all the checkboxes I tick. The slider is responsive, script works but no value is send to my view. All I get is "None". Switching get to time_slider is not helping either. What I did wrong?

Body:
Give your range input a name attribute. Since you are already checking for slider_valu in your backend code, then you can change your code to be this:

<input name="slider_value" type="range" min="1" max="120" value="120" class="form-control-range" id="time_slider">


问:
Inkwell not showing ripple when used with Container decoration
I want to add a ripple on an item, it is working fine until I add a gradient on the item using BoxDecoration.

```<code>Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
      child: Material(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0)),
        elevation: 6.0,
        shadowColor: Colors.grey[50],
        child: InkWell(
          onTap: () {},
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: AlignmentDirectional.bottomStart,
                end: AlignmentDirectional.topEnd,
                colors: [
                  Colors.yellow[800],
                  Colors.yellow[700],
                ],
              ),
            ),
            padding: EdgeInsets.all(16.0),
            child: Text(
              widget.title,
              style: TextStyle(
                fontSize: 20.0,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
</code>```

答:
Simple splash effect widget I created that works perfect.</p>

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class SplashEffect extends StatelessWidget {
  final Widget child;
  final Function onTap;

  const SplashEffect({Key key, this.child, this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: InkWell(
        borderRadius: BorderRadius.all(Radius.circular(16)),
        child: child,
        onTap: onTap,
      ),
    );
  }
}
</code>```

Body:
I want to add a ripple on an item, it is working fine until I add a gradient on the item using BoxDecoration.

Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
      child: Material(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0)),
        elevation: 6.0,
        shadowColor: Colors.grey[50],
        child: InkWell(
          onTap: () {},
          child: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: AlignmentDirectional.bottomStart,
                end: AlignmentDirectional.topEnd,
                colors: [
                  Colors.yellow[800],
                  Colors.yellow[700],
                ],
              ),
            ),
            padding: EdgeInsets.all(16.0),
            child: Text(
              widget.title,
              style: TextStyle(
                fontSize: 20.0,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }

Body:
Simple splash effect widget I created that works perfect.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class SplashEffect extends StatelessWidget {
  final Widget child;
  final Function onTap;

  const SplashEffect({Key key, this.child, this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: InkWell(
        borderRadius: BorderRadius.all(Radius.circular(16)),
        child: child,
        onTap: onTap,
      ),
    );
  }
}


问:
How to send data from redis subscriber to express route
I have a redis pubsub client where publisher is in one file and subscriber is in another file working perfectly

I have 2 controllers a home controller that handles '/' route and a data controller that handles '/data' route

Inside my redis subscriber I want to update the state of a variable that I continuously get from publisher

How do I send this state to both controllers when they do a request

I was doing

```<code>app.get('/', (req, res) => {
    c = redis.createClient()
    c.on("message", (channel, message) => {
    // Send data here
    })
})
</code>```

This does not look like a good idea, it is creating a new CLIENT for every request to the '/' endpoint

I want to be able to do

```<code>// home controller file
app.get('/', (req, res) => {
    res.json(state)
})
// data controller file
app.get('/data', (req, res) => {
    res.json(state)
})
</code>```

How to implement this state

答:
After doing some research, I decided to use Node's native events module to solve this. This example uses ioredis rather than node_redis, but the principle is the same.

First, I instantiate three redis clients. One for regular db work, a publisher and a subscriber

```<code>/* redis.js */

const Redis = require('ioredis');

const redis = new Redis();
const publisher = new Redis();
const subscriber = new Redis();

// redis is the defaut export
// publisher and subscriber are "named" exports

const client = (module.exports = redis);
client.publisher = publisher;
client.subscriber = subscriber;
</code>```

Next we create an EventEmitter in node that will emit an event every time the subscriber receives a message from a channel in redis.

```<code>/* emitter.js */

const EventEmitter = require('events');
const { subscriber } = require('./redis');

const eventEmitter = new EventEmitter();

subscriber.subscribe('my-channel', err => {
  if (err) { return console.log('Unable to subscribe to my-event channel') };
  console.log('Subscription to my-event channel successful');
});

subscriber.on('message', (channel, message) => {
  eventEmitter.emit('my-event', message);
});

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

Here we have two routes. The first handles a PUT request that sets a field in redis and then publishes a message to a channel with the key of the hash that was updated. The second route handles a GET request that stays open (as an EventSource for an SSE connection for example). It listens to an event from emitter and then sends the data of the updated key from redis

```<code>/* route.js*/

const express = require('express');
const redis = require('./redis');
const { publisher } = require('./redis');
const { eventEmitter } = require('./emitter');

const router = express.Router();

router.put('/content', async (req, res) => {
  const { key, field, content } = req.body;
  try {
    await redis.hset(key, field, content);
    res.sendStatus(200);
    return publisher.publish('my-channel', key);

  } catch(err) {
     res.status(500).send(err.message);
  }
});

router.get('/content-stream', (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive'
  });

  res.write('\n');

  const handleEvent = async key => {
     try {
      const query = await redis.hgetall(key);
      res.write(`data: ${JSON.stringify(query)}\n\n`);
    } catch(err) {
      console.log('Something went wrong');
    }
  }

  eventEmitter.addListener('my-event', handleEvent);
  req.on('close', eventEmitter.removeListener('my-event', handleEvent));

module.exports = router;

</code>```

This will effectively allow you to avoid instantiating new redis clients with every connection. There may be better ways of doing this, but this is what worked for me.

Body:
I have a redis pubsub client where publisher is in one file and subscriber is in another file working perfectly

I have 2 controllers a home controller that handles '/' route and a data controller that handles '/data' route

Inside my redis subscriber I want to update the state of a variable that I continuously get from publisher

How do I send this state to both controllers when they do a request

I was doing

app.get('/', (req, res) => {
    c = redis.createClient()
    c.on("message", (channel, message) => {
    // Send data here
    })
})

This does not look like a good idea, it is creating a new CLIENT for every request to the '/' endpoint

I want to be able to do

// home controller file
app.get('/', (req, res) => {
    res.json(state)
})
// data controller file
app.get('/data', (req, res) => {
    res.json(state)
})

How to implement this state

Body:
After doing some research, I decided to use Node's native events module to solve this. This example uses ioredis rather than node_redis, but the principle is the same.

First, I instantiate three redis clients. One for regular db work, a publisher and a subscriber

/* redis.js */

const Redis = require('ioredis');

const redis = new Redis();
const publisher = new Redis();
const subscriber = new Redis();

// redis is the defaut export
// publisher and subscriber are "named" exports

const client = (module.exports = redis);
client.publisher = publisher;
client.subscriber = subscriber;

Next we create an EventEmitter in node that will emit an event every time the subscriber receives a message from a channel in redis.

/* emitter.js */

const EventEmitter = require('events');
const { subscriber } = require('./redis');

const eventEmitter = new EventEmitter();

subscriber.subscribe('my-channel', err => {
  if (err) { return console.log('Unable to subscribe to my-event channel') };
  console.log('Subscription to my-event channel successful');
});

subscriber.on('message', (channel, message) => {
  eventEmitter.emit('my-event', message);
});

module.exports = eventEmitter;

Here we have two routes. The first handles a PUT request that sets a field in redis and then publishes a message to a channel with the key of the hash that was updated. The second route handles a GET request that stays open (as an EventSource for an SSE connection for example). It listens to an event from emitter and then sends the data of the updated key from redis

/* route.js*/

const express = require('express');
const redis = require('./redis');
const { publisher } = require('./redis');
const { eventEmitter } = require('./emitter');

const router = express.Router();

router.put('/content', async (req, res) => {
  const { key, field, content } = req.body;
  try {
    await redis.hset(key, field, content);
    res.sendStatus(200);
    return publisher.publish('my-channel', key);

  } catch(err) {
     res.status(500).send(err.message);
  }
});

router.get('/content-stream', (req, res) => {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    Connection: 'keep-alive'
  });

  res.write('\n');

  const handleEvent = async key => {
     try {
      const query = await redis.hgetall(key);
      res.write(`data: ${JSON.stringify(query)}\n\n`);
    } catch(err) {
      console.log('Something went wrong');
    }
  }

  eventEmitter.addListener('my-event', handleEvent);
  req.on('close', eventEmitter.removeListener('my-event', handleEvent));

module.exports = router;

This will effectively allow you to avoid instantiating new redis clients with every connection. There may be better ways of doing this, but this is what worked for me.


问:
Assign the labor sector to a list according to the Occupation / workplace and position of the employee
I have this file with occupation or work places names and the position of the worker and based in that data I need to add a column with the "Labor sector" ex: if the position is Medic or the work place / occupation is doctor then the Labor sector it would be Health.

I tried this:

```<code>=IF(ISNUMBER(SEARCH("Hospital",D2)), "Health","")
</code>```

But this would only work for one labor sector at the time and there are plenty of it on the file and I have to determine the labor sector to 4000 contacts.

So, is there a way to do this more efficiently with VBA, or something else?

Example file!

答:
I'll echo @DarXyde and @Solar Mike: vlookup is the way to go. You'll have to create a second set of data that maps the answers you want, but it sounds like it will be worth the time investment.

Index/match is in some ways more powerful, but also harder to use.

simple explanation

more complex

more complex

Body:
I have this file with occupation or work places names and the position of the worker and based in that data I need to add a column with the "Labor sector" ex: if the position is Medic or the work place / occupation is doctor then the Labor sector it would be Health.

I tried this:

=IF(ISNUMBER(SEARCH("Hospital",D2)), "Health","")

But this would only work for one labor sector at the time and there are plenty of it on the file and I have to determine the labor sector to 4000 contacts.

So, is there a way to do this more efficiently with VBA, or something else?

Example file!


问:
Migrations, and Seeds using a module based folder structure
I want to use /modules/module_name/ structure for my graphql api so I can later on abstract it/take it out and run as a service in the future.

I have looked/searched knex.js website for how to configure it, and couldn't find it.

```<code>module.exports = {
  ...
  development: {
    migrations: {
      sortDirsSeparately: true,
      directory: ["./src/migrations", "./src/modules/**/migration"],
    },
    seeds: {
      directory: "./src/seeds",
    },
  },
  ...
};

</code>```

I have tried this configuration, and have not been able to create it to my needs.

Does such a feature exist in knex.js?

答: While you can provide an array of migration directories as you have discovered, it does not appear to support globs. I think you'd be stuck with adding each new directory to the directory array as you create each module.

Body:
I want to use /modules/module_name/ structure for my graphql api so I can later on abstract it/take it out and run as a service in the future.

I have looked/searched knex.js website for how to configure it, and couldn't find it.

module.exports = {
  ...
  development: {
    migrations: {
      sortDirsSeparately: true,
      directory: ["./src/migrations", "./src/modules/**/migration"],
    },
    seeds: {
      directory: "./src/seeds",
    },
  },
  ...
};

I have tried this configuration, and have not been able to create it to my needs.

Does such a feature exist in knex.js?


问:
Looking for an appropriate synchronization mechanism
Presume I have the following (pseudo) code:

class Cache {
    Entry addIfMissing(String data) {
        // omitted for brevity
    }
    void evictOldEntries() {
        // omitted for brevity
    }
}
```

<pre class="lang-java prettyprint-override"><code>class Program {
    private Cache cache = new Cache();

    doWork() { // called from multiple threads
        var entry = cache.addIfMissing("omitted for brevity");
        // work with entry
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            cache.evictOldEntries();
        }, 10, 10, TimeUnit.MINUTES);
    }
}
</code>```

I want to make sure while the evictOldEntries method is running all the other threads in the program have to wait for it to be done.

Which synchronization mechanism would be appropriate in such a scenario?

答:
Taking a bit of liberty here since your code sample and exact requirements are a bit unclear. But might something like this work? ConcurrentHashMap uses fine-grained locking so you minimize the bottleneck when inserting entries into the cache. The evictor thread can even run concurrently with the inserting threads.

```<code>class Cache<String, CacheEntry> {
    ConcurrentHashMap<String, CacheEntry> map = new ConcurrentHashMap<String, CacheEntry>();

    Entry addIfMissing(String data) {
        map.computeIfAbsent(...);
    }

    void evictOldEntries() {
        Iterator<Map.Entry<String, CacheEntry>> iterator = map.entrySet().iterator();

        while (iterator.hasNext()) {
            CacheEntry entry = iterator.next().getValue();

            if (shouldEvict(entry)) {
                iterator.remove();
            }
        }
    }
}
</code>```

Body:
Presume I have the following (pseudo) code:

class Cache {
    Entry addIfMissing(String data) {
        // omitted for brevity
    }
    void evictOldEntries() {
        // omitted for brevity
    }
}

class Program {
    private Cache cache = new Cache();

    doWork() { // called from multiple threads
        var entry = cache.addIfMissing("omitted for brevity");
        // work with entry
    }

    static {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            cache.evictOldEntries();
        }, 10, 10, TimeUnit.MINUTES);
    }
}

I want to make sure while the evictOldEntries method is running all the other threads in the program have to wait for it to be done.

Which synchronization mechanism would be appropriate in such a scenario?

Body:
Taking a bit of liberty here since your code sample and exact requirements are a bit unclear. But might something like this work? ConcurrentHashMap uses fine-grained locking so you minimize the bottleneck when inserting entries into the cache. The evictor thread can even run concurrently with the inserting threads.

class Cache<String, CacheEntry> {
    ConcurrentHashMap<String, CacheEntry> map = new ConcurrentHashMap<String, CacheEntry>();

    Entry addIfMissing(String data) {
        map.computeIfAbsent(...);
    }

    void evictOldEntries() {
        Iterator<Map.Entry<String, CacheEntry>> iterator = map.entrySet().iterator();

        while (iterator.hasNext()) {
            CacheEntry entry = iterator.next().getValue();

            if (shouldEvict(entry)) {
                iterator.remove();
            }
        }
    }
}


问:
Chrome identifying field as "address" for autofill incorrectly
I have a webform with multiple text inputs, quite recently one specifically started having it's autofill linked to "City" somehow and Chrome is only giving options from the stored addresses in the browser.

The name and type aren't even close to what should match in the specs for the browsers regex I've seen online, and even playing with the "x-autocompletetype" I found on other forums seems to have no impact.

 6. Storage Capacity

<input type="text" class="form-control" id="spec-Storage Capacity" name="spec-Storage Capacity" x-autocompletetype="Storage Capacity">
```

Up until recently, it was storing what we had been filling in here (e.g. "16 GB") but now we just get the city list from the browser.

Also note: I know it's not that the name has spaces because other form elements look just like this and work correctly.

答: The "city" at the end of "Capacity" seems to be triggering the autofill. I guess the regex is aggressive so it can match cases like shipping-city.</p>

Body:
I have a webform with multiple text inputs, quite recently one specifically started having it's autofill linked to "City" somehow and Chrome is only giving options from the stored addresses in the browser.

The name and type aren't even close to what should match in the specs for the browsers regex I've seen online, and even playing with the "x-autocompletetype" I found on other forums seems to have no impact.

 6. Storage Capacity

<input type="text" class="form-control" id="spec-Storage Capacity" name="spec-Storage Capacity" x-autocompletetype="Storage Capacity">

Up until recently, it was storing what we had been filling in here (e.g. "16 GB") but now we just get the city list from the browser.

Also note: I know it's not that the name has spaces because other form elements look just like this and work correctly.


问:
,class varchar(2) NOT NULL error code 1064
ERROR: 16:47:31

```<code>CREATE TABLE orders
(order_id char(5) NOT NULL
,part_id varchar(5) NOT NULL
,order_date DATETIME NOT NULL DEFAULT TIMESTAMP
,class varchar(5) NOT NULL
,comments varchar(75) NOT NULL
,part_description varchar(75) NOT NULL
,customer_id varchar(5) NOT NULL
,CONSTRAINT pk_orderPRIMARY PRIMARY KEY (order_id)
,CONSTRAINT fk_customer_id FOREIGN KEY (customer_id)
REFERENCES customer_id(customer_id))
</code>```

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',class varchar(5) NOT NULL ,comments varchar(75) NOT NULL ,part_description varc' at line 5    0.000 sec

,class varchar(5) NOT NULL ,comments varchar(75) NOT NULL ,part_description

class varchar(5) NOT NULL ,comments varchar(75) NOT NULL ,part_description

MySQL is not running the code due to a varchar error, but the values are defined as "2" and NOT NULL, I do not understand. I expected smooth sailing from defining the varchar as text values, but I seemed to hit a log on the way. Please help!

答:
```<code>CREATE TABLE `orders` (
 `order_id` char(5) NOT NULL,
 `part_id` varchar(5) NOT NULL,
 `order_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `class` varchar(5) NOT NULL,
 `comments` varchar(75) NOT NULL,
 `part_description` varchar(75) NOT NULL,
 `customer_id` varchar(5) NOT NULL
)
</code>```

Body:
ERROR: 16:47:31

CREATE TABLE orders
(order_id char(5) NOT NULL
,part_id varchar(5) NOT NULL
,order_date DATETIME NOT NULL DEFAULT TIMESTAMP
,class varchar(5) NOT NULL
,comments varchar(75) NOT NULL
,part_description varchar(75) NOT NULL
,customer_id varchar(5) NOT NULL
,CONSTRAINT pk_orderPRIMARY PRIMARY KEY (order_id)
,CONSTRAINT fk_customer_id FOREIGN KEY (customer_id)
REFERENCES customer_id(customer_id))

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',class varchar(5) NOT NULL ,comments varchar(75) NOT NULL ,part_description varc' at line 5    0.000 sec

,class varchar(5) NOT NULL ,comments varchar(75) NOT NULL ,part_description

class varchar(5) NOT NULL ,comments varchar(75) NOT NULL ,part_description

MySQL is not running the code due to a varchar error, but the values are defined as "2" and NOT NULL, I do not understand. I expected smooth sailing from defining the varchar as text values, but I seemed to hit a log on the way. Please help!


问:
How could I count bit from large number in javascript?
I have a large number stored in string.

```<code>let txt = '10000000000000041';
</code>```

So how could I count bit presenting in it's a binary format. for example, the binary format of 9 is 1001, and no of 1's is 2.

What I did so far:

const countOne = (num) => {
  let c = 0;
  while (num > 0) {
    num &= num - 1;
    c++;
  }
  return c;
}

console.log(countOne(+'9'));
console.log(countOne(+'10000000000000041'));```

This code is working fine, but not for large value, because Number in JavaScript cannot hold such large value, so it's giving the wrong answer.

I found similar questions but not for large value.

答:
In newer engines (Chrome, FF, Opera, and Node at least, see compatibility table), just cast to a BigInt first:

let txt='10000000000000041';
const countOne = (num) => {
  let c = 0;
  while (num > 0) {
    num &= num - 1n;
    c++;
  }
  return c;
}
console.log(countOne(BigInt(txt)));
console.log(countOne(BigInt(1)));
console.log(countOne(BigInt(2)));
console.log(countOne(BigInt(3)));
console.log(countOne(BigInt(4)));
console.log(countOne(BigInt(5)));
console.log(countOne(BigInt(6)));
console.log(countOne(BigInt(7)));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
try {
  eval('1n');
} catch(e) {
  throw "Your browser doesn't support BigInt syntax yet";
}
</script></code>```

10000000000000041 in binary is 100011100001101111001001101111110000010000000000101001, so 23 is correct:

console.log(
  [...'100011100001101111001001101111110000010000000000101001']
  .reduce((a, b) => a + (b === '1'), 0)
);```

Body:
I have a large number stored in string.

let txt = '10000000000000041';

So how could I count bit presenting in it's a binary format. for example, the binary format of 9 is 1001, and no of 1's is 2.

What I did so far:

const countOne = (num) => {
  let c = 0;
  while (num > 0) {
    num &= num - 1;
    c++;
  }
  return c;
}

console.log(countOne(+'9'));
console.log(countOne(+'10000000000000041'));

This code is working fine, but not for large value, because Number in JavaScript cannot hold such large value, so it's giving the wrong answer.

I found similar questions but not for large value.

Body:
In newer engines (Chrome, FF, Opera, and Node at least, see compatibility table), just cast to a BigInt first:

let txt='10000000000000041';
const countOne = (num) => {
  let c = 0;
  while (num > 0) {
    num &= num - 1n;
    c++;
  }
  return c;
}
console.log(countOne(BigInt(txt)));
console.log(countOne(BigInt(1)));
console.log(countOne(BigInt(2)));
console.log(countOne(BigInt(3)));
console.log(countOne(BigInt(4)));
console.log(countOne(BigInt(5)));
console.log(countOne(BigInt(6)));
console.log(countOne(BigInt(7)));

<script>
try {
  eval('1n');
} catch(e) {
  throw "Your browser doesn't support BigInt syntax yet";
}
</script>

10000000000000041 in binary is 100011100001101111001001101111110000010000000000101001, so 23 is correct:

console.log(
  [...'100011100001101111001001101111110000010000000000101001']
  .reduce((a, b) => a + (b === '1'), 0)
);


问:
How to lock slider and prevent updating of values with mouse into dat.GUI menu
I try to implement a way to prevent the updating of values with mouse (actually when the three.js animation has started, launched with a click on button).

For the moment, I have the following dat.GUI menu:

Once "start" button is clicked, I would like to prevent user from modifying with mouse the parameters "Rotation x" and "Rotation y".

Here is the concerned part of code for this menu:

```<code>// Create GUI
var gui = new dat.GUI({
      autoplace: false,
      width: 350,
          height: 9 * 32 - 1
});

var params = {
      GreatCircle : '',
      Rotationx : torusRotationInitX,
      Rotationy : torusRotationInitY,
      StartingVector : '',
      ComponentVectorTheta : 15.0,
      ComponentVectorPhi : 15.0,
      CovariantDerivativeVector : '',
      ComponentCovariantDerivativeTheta : 15.0,
      ComponentCovariantDerivativePhi : 15.0
};

// Set parameters for GUI
gui.add(params, 'GreatCircle').name('Great Circle ');
controllerRotationx = gui.add(params, 'Rotationx', 0, 2*Math.PI, 0.001).name('Rotation x ');
controllerRotationy = gui.add(params, 'Rotationy', 0, 2*Math.PI, 0.001).name('Rotation y ');
...
</code>```

When I click on reset button, I call the following function:

```<code>  // Reset Button
  resetButton.onclick = function ResetParameters() {

  ...

  // Reinitialize parameters into gui
  params.Rotationx = torusRotationInitX;
  params.Rotationy = torusRotationInitY;

  for (var i in gui.__controllers) {
     gui.__controllers[i].updateDisplay();
  }

render();

}
</code>```

I don't know if there is an option for controller to lock these sliders which usually change their values. Is it possible?

Update 1

Maybe I could wrapper the dat.GUI menu into a div and make this div not clickable, is it a solution?

Update 2

I tried to apply the method used on Method for disabling a button in dat.gui?

Following this solution, I have added the extension into dat.gui, just after:

```<code>dat.controllers.FunctionController = (function (Controller, dom, common) {

...

});
</code>```

The following added code snippet is:

```<code>function blockEvent(event)
{
  event.stopPropagation();
}

Object.defineProperty(dat.controllers.FunctionController.prototype, "disabled", {
  get: function()
  {
    return this.domElement.hasAttribute("disabled");
  },
  set: function(value)
  {
    if (value)
    {
      this.domElement.setAttribute("disabled", "disabled");
      this.domElement.addEventListener("click", blockEvent, true);
    }
    else
    {
      this.domElement.removeAttribute("disabled");
      this.domElement.removeEventListener("click", blockEvent, true);
    }
  },
  enumerable: true
});
</code>```

Is extension code well located into dat.GUI source?

Then, I set the property "disabled" into my code to prevent user from sliding "controllerRotationx" with mouse (once start button is pressed):

```<code>if (animation)
controllerRotationx.__li.disabled = true;
</code>```

Unfortunately, my method doesn't work : when animation is started, I can still move the slider contained into "controllerRotationx".

I saw that above link (Method for disabling a button in dat.gui?), this was about a button and not for a slider, does it change anything for my case?

I didn't find an explicit controller for the slider.

答:
thanks for tips
on my side i hack the Common controller
so able to chainning.

gui.add(this, '_screenW').disable(true);

```<code>  Common.extend(controller,                                   {
    disable: function disable(v) {
      this.domElement.style.pointerEvents = v?"none":"auto";
      this.domElement.style.opacity = v?.5:1;
      return controller;
    },
</code>```

Body:
I try to implement a way to prevent the updating of values with mouse (actually when the three.js animation has started, launched with a click on button).

For the moment, I have the following dat.GUI menu:

Once "start" button is clicked, I would like to prevent user from modifying with mouse the parameters "Rotation x" and "Rotation y".

Here is the concerned part of code for this menu:

// Create GUI
var gui = new dat.GUI({
      autoplace: false,
      width: 350,
          height: 9 * 32 - 1
});

var params = {
      GreatCircle : '',
      Rotationx : torusRotationInitX,
      Rotationy : torusRotationInitY,
      StartingVector : '',
      ComponentVectorTheta : 15.0,
      ComponentVectorPhi : 15.0,
      CovariantDerivativeVector : '',
      ComponentCovariantDerivativeTheta : 15.0,
      ComponentCovariantDerivativePhi : 15.0
};

// Set parameters for GUI
gui.add(params, 'GreatCircle').name('Great Circle ');
controllerRotationx = gui.add(params, 'Rotationx', 0, 2*Math.PI, 0.001).name('Rotation x ');
controllerRotationy = gui.add(params, 'Rotationy', 0, 2*Math.PI, 0.001).name('Rotation y ');
...

When I click on reset button, I call the following function:

  // Reset Button
  resetButton.onclick = function ResetParameters() {

  ...

  // Reinitialize parameters into gui
  params.Rotationx = torusRotationInitX;
  params.Rotationy = torusRotationInitY;

  for (var i in gui.__controllers) {
     gui.__controllers[i].updateDisplay();
  }

render();

}

I don't know if there is an option for controller to lock these sliders which usually change their values. Is it possible?

Update 1

Maybe I could wrapper the dat.GUI menu into a div and make this div not clickable, is it a solution?

Update 2

I tried to apply the method used on Method for disabling a button in dat.gui?

Following this solution, I have added the extension into dat.gui, just after:

dat.controllers.FunctionController = (function (Controller, dom, common) {

...

});

The following added code snippet is:

function blockEvent(event)
{
  event.stopPropagation();
}

Object.defineProperty(dat.controllers.FunctionController.prototype, "disabled", {
  get: function()
  {
    return this.domElement.hasAttribute("disabled");
  },
  set: function(value)
  {
    if (value)
    {
      this.domElement.setAttribute("disabled", "disabled");
      this.domElement.addEventListener("click", blockEvent, true);
    }
    else
    {
      this.domElement.removeAttribute("disabled");
      this.domElement.removeEventListener("click", blockEvent, true);
    }
  },
  enumerable: true
});

Is extension code well located into dat.GUI source?

Then, I set the property "disabled" into my code to prevent user from sliding "controllerRotationx" with mouse (once start button is pressed):

if (animation)
controllerRotationx.__li.disabled = true;

Unfortunately, my method doesn't work : when animation is started, I can still move the slider contained into "controllerRotationx".

I saw that above link (Method for disabling a button in dat.gui?), this was about a button and not for a slider, does it change anything for my case?

I didn't find an explicit controller for the slider.

Body:
thanks for tips
on my side i hack the Common controller
so able to chainning.

gui.add(this, '_screenW').disable(true);

  Common.extend(controller,                                   {
    disable: function disable(v) {
      this.domElement.style.pointerEvents = v?"none":"auto";
      this.domElement.style.opacity = v?.5:1;
      return controller;
    },


问:
Keep column names with mutate_at and lst() instead of funs()
In dplyr 0.8.0, funs() is deprecated, and the new format is to use list() with ~. However, I have noticed that this no longer updates columns using mutate_at() as previously expected.

```<code>> set.seed(5)
> testdf <- data.frame(a = sample(1:9, size = 5, replace = TRUE),
+                      b = 1:5,
+                      c = LETTERS[1:5])
> testdf
  a b c
1 2 1 A
2 7 2 B
3 9 3 C
4 3 4 D
5 1 5 E
</code>```

Example of old code:

```<code>> testdf %>% mutate_at(.vars = c('a','b'), .funs = funs(. + 2))
   a b c
1  4 3 A
2  9 4 B
3 11 5 C
4  5 6 D
5  3 7 E
</code>```

Example of new code:

```<code>> testdf %>% mutate_at(.vars = c('a','b'), .funs = lst(~. + 2))
  a b c a_~. + 2 b_~. + 2
1 2 1 A        4        3
2 7 2 B        9        4
3 9 3 C       11        5
4 3 4 D        5        6
5 1 5 E        3        7
</code>```

EDIT: I just noticed that if I use list() this problem is resolved:

```<code>> testdf %>% mutate_at(.vars = c('a','b'), .funs = list(~. + 2))
   a b c
1  4 3 A
2  9 4 B
3 11 5 C
4  5 6 D
5  3 7 E
</code>```

However, I wish to use lst() because within my code I regularly requiring unquoting variables using !!!, which is not supported by list() (see here)

I'm not sure of the proper way to use lst() while retaining the names.

答:
rlang::list2

is equivalent to list(...) but provides tidy dots semantics:

```<code>>  testdf %>% mutate_at(.vars = c('a','b'), .funs = rlang::list2(~. + 2))
   a b c
1  4 3 A
2  9 4 B
3 11 5 C
4  5 6 D
5  3 7 E
</code>```

Body:
In dplyr 0.8.0, funs() is deprecated, and the new format is to use list() with ~. However, I have noticed that this no longer updates columns using mutate_at() as previously expected.

> set.seed(5)
> testdf <- data.frame(a = sample(1:9, size = 5, replace = TRUE),
+                      b = 1:5,
+                      c = LETTERS[1:5])
> testdf
  a b c
1 2 1 A
2 7 2 B
3 9 3 C
4 3 4 D
5 1 5 E

Example of old code:

> testdf %>% mutate_at(.vars = c('a','b'), .funs = funs(. + 2))
   a b c
1  4 3 A
2  9 4 B
3 11 5 C
4  5 6 D
5  3 7 E

Example of new code:

> testdf %>% mutate_at(.vars = c('a','b'), .funs = lst(~. + 2))
  a b c a_~. + 2 b_~. + 2
1 2 1 A        4        3
2 7 2 B        9        4
3 9 3 C       11        5
4 3 4 D        5        6
5 1 5 E        3        7

EDIT: I just noticed that if I use list() this problem is resolved:

> testdf %>% mutate_at(.vars = c('a','b'), .funs = list(~. + 2))
   a b c
1  4 3 A
2  9 4 B
3 11 5 C
4  5 6 D
5  3 7 E

However, I wish to use lst() because within my code I regularly requiring unquoting variables using !!!, which is not supported by list() (see here)

I'm not sure of the proper way to use lst() while retaining the names.

Body:
rlang::list2

is equivalent to list(...) but provides tidy dots semantics:

>  testdf %>% mutate_at(.vars = c('a','b'), .funs = rlang::list2(~. + 2))
   a b c
1  4 3 A
2  9 4 B
3 11 5 C
4  5 6 D
5  3 7 E


问:
Generating Pyramid to Show Numbers in Module 10
I am trying to generate pyramid starts with the number one (1), in each row the first digit determines the number of row. In addition, the first number in the row also determines the number of numbers in that order (according to module 10). All other numbers in a row we calculate by adding the number from the left and the number above it, according to module 10.

```<code>int n = 12;
int i, j;

for (i = 1; i <= n; i++) {
    for (j = 0; j <= i; j++) {
      int module = i % 10;

      System.out.print(module + " ");

    }

    System.out.println();
  }
}

</code>```

With my implementation, I get

```<code>1 1
2 2 2
3 3 3 3
4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6 6
7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2
</code>```

The actual result should be

```<code>1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
1 1 0 6 4 2 2 0 2 8 4
2 3 4 4 0 4 6 8 8 0 8 2
</code>```

What am I missing?

答:
You need to store your results to use it print next line.</p>

```<code>public class Test {
  public static void main(String[] args) {
    int n = 12;
    int i,j;
    int[][] arr = new int[n][n];

    arr[0][0] = 1;
    System.out.println(arr[0][0]);

    for(i = 1;i<n;i++) {
      for(j=0;j<=i;j++) {
        if(j == 0) {
          arr[i][j] = (i+1)%10;
        }else {
          arr[i][j] = (arr[i][j-1] + arr[i-1][j-1])%10;
        }
        System.out.print(arr[i][j]+" ");
      }
      System.out.println();
    }
  }

}
</code>```

Body:
I am trying to generate pyramid starts with the number one (1), in each row the first digit determines the number of row. In addition, the first number in the row also determines the number of numbers in that order (according to module 10). All other numbers in a row we calculate by adding the number from the left and the number above it, according to module 10.

int n = 12;
int i, j;

for (i = 1; i <= n; i++) {
    for (j = 0; j <= i; j++) {
      int module = i % 10;

      System.out.print(module + " ");

    }

    System.out.println();
  }
}

With my implementation, I get

1 1
2 2 2
3 3 3 3
4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6 6
7 7 7 7 7 7 7 7
8 8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9 9
0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2 2 2 2

The actual result should be

1
2 3
3 5 8
4 7 2 0
5 9 6 8 8
6 1 0 6 4 2
7 3 4 4 0 4 6
8 5 8 2 6 6 0 6
9 7 2 0 2 8 4 4 0
0 9 6 8 8 0 8 2 6 6
1 1 0 6 4 2 2 0 2 8 4
2 3 4 4 0 4 6 8 8 0 8 2

What am I missing?

Body:
You need to store your results to use it print next line.

public class Test {
  public static void main(String[] args) {
    int n = 12;
    int i,j;
    int[][] arr = new int[n][n];

    arr[0][0] = 1;
    System.out.println(arr[0][0]);

    for(i = 1;i<n;i++) {
      for(j=0;j<=i;j++) {
        if(j == 0) {
          arr[i][j] = (i+1)%10;
        }else {
          arr[i][j] = (arr[i][j-1] + arr[i-1][j-1])%10;
        }
        System.out.print(arr[i][j]+" ");
      }
      System.out.println();
    }
  }

}


问:
Image on bootstrap carousel won't stretch
I know this issue seems recurrent, but I've searched through many posts on how to really stretch my image to the full width of it's parent element, but none of them seemed to work.

So, I have a carousel and I want all the images to display at full width. The strange thing is every image appears filling the whole space at the animation of transition time, but it shrinks as soon as the animation ends.

Padding 0 didn't work. Width 100% didn't work. col-12 didn't work. The only thing that works is setting width to a fixed value, but that kills responsiveness.

```<code><div class="position-fixed">
    <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
        <div class="carousel-inner">
            <div class="carousel-item active" data-interval="5000">
                <img src="media/imagens/home1.png" class="d-block w-100" class="img-fluid" alt="Responsive image">
            </div>
            <div class="carousel-item" data-interval="5000">
                <img src="media/imagens/home2.jpg" class="d-block w-100" class="img-fluid" alt="Responsive image">
            </div>
            <div class="carousel-item" data-interval="5000">
                <img src="media/imagens/home3.jpg" class="d-block w-100" class="img-fluid" alt="Responsive image">
            </div>
            <div class="carousel-item" data-interval="5000">
                <img src="media/imagens/home4.jpg" class="d-block w-100" class="img-fluid" alt="Responsive image">
            </div>
            <div class="carousel-item" data-interval="5000">
                <img src="media/imagens/home5.png" class="d-block w-100" class="img-fluid" alt="Responsive image">
            </div>
        </div>
    </div>
</div>
</code>```

答:
Try adding a class of “row” to the outer div so it would be:</p>

```<code><div class="row position-fixed">
</code>```

Body:
Try adding a class of “row” to the outer div so it would be:

<div class="row position-fixed">


问:
VSCode: how to undo split screen and show just current file?
VSCode provides sweet shortcuts for manipulating (splitting and rearranging) screens:

Press Ctrl + \ to split your screen in two.

Press Ctrl + Number to focus on one of the screeens

Press Ctrl + Shift + 0 to change vertical/horizontal split

However, how do I remove all the split screens and just show the currently focused one?

Example: say, I press Ctrl + \ two times (gives me three vertical screens), then press Ctrl + 2 to select middle screen. What should I press now to make left and right screen disappear and middle screen occupy the whole space? In Emacs, that would be Ctrl + X + 1.

答:
See if this keybinding does what you want:

```<code>{
  "key": "alt+q",
  "command": "workbench.action.closeEditorsInOtherGroups"
}
</code>```

There is no default keybinding for the command workbench.action.closeEditorsInOtherGroups so I made up that one.  I think it accomplishes what you want.  It will close the other editor groups and keep you at the focused group.

Body:
See if this keybinding does what you want:

{
  "key": "alt+q",
  "command": "workbench.action.closeEditorsInOtherGroups"
}

There is no default keybinding for the command workbench.action.closeEditorsInOtherGroups so I made up that one.  I think it accomplishes what you want.  It will close the other editor groups and keep you at the focused group.


问:
How to convert IdentityUser to BaseEntity
I have user Model, like this:

```<code>    public class User : IdentityUser<Guid>
    {
        public string FullName { get; set; }
       //... more lines
    }
</code>```

Now I need to use some methods for user, that are made for base entity, so I want to add Base Entity, but it does not work.

```<code>    public class User : IdentityUser<Guid>, BaseEntity
    {
        public string FullName { get; set; }
       //... more lines
    }
</code>```

I tried creating new user with only BaseEntity and then it works, but then I lose all the methods for IdentityUser which I don't want.

答:
Since multiple inheritance is not possible in C#, you could have an IdentityUser as a field and wrap the properties and methods you want (assuming IdentityUser is not your own class):

```<code>public class User : BaseEntity
{
    private readonly IdentityUser<Guid> _identityUser;
    public string FullName { get; set; }

    public string UserName
    {
        get { return _identityUser.UserName; }
        set { _identityUser.UserName = value; }
    }

    public string Id
    {
        get { return _identityUser.Id; }
        set { _identityUser.Id = value ; }
    }

    // ... etc.

    public User(IdentityUser<Guid> identityUser)
    {
        _identityUser = identityUser;
    }
}
</code>```

Body:
I have user Model, like this:

    public class User : IdentityUser<Guid>
    {
        public string FullName { get; set; }
       //... more lines
    }

Now I need to use some methods for user, that are made for base entity, so I want to add Base Entity, but it does not work.

    public class User : IdentityUser<Guid>, BaseEntity
    {
        public string FullName { get; set; }
       //... more lines
    }

I tried creating new user with only BaseEntity and then it works, but then I lose all the methods for IdentityUser which I don't want.

Body:
Since multiple inheritance is not possible in C#, you could have an IdentityUser as a field and wrap the properties and methods you want (assuming IdentityUser is not your own class):

public class User : BaseEntity
{
    private readonly IdentityUser<Guid> _identityUser;
    public string FullName { get; set; }

    public string UserName
    {
        get { return _identityUser.UserName; }
        set { _identityUser.UserName = value; }
    }

    public string Id
    {
        get { return _identityUser.Id; }
        set { _identityUser.Id = value ; }
    }

    // ... etc.

    public User(IdentityUser<Guid> identityUser)
    {
        _identityUser = identityUser;
    }
}


问:
Firebase Cloud Functions deletes nodes directly after rather than 24 hours later
My goal is to delete all the message nodes 24 hours after they were sent using Firebase Cloud Functions and the Realtime Database. I tried copy and pasting the answer from this post however for some reason the messages delete directly after they were created rather than the 24 hours later. If someone could help me solve this problem I would really appreciate it. I have tried multiple different answers based on the same issue and they haven't worked for me.

Here is my index.js file:

```<code>'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.

exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
</code>```

And my database structure is:

答:
In the comments you indicated that you're using Swift. From that and the screenshot it turns out that you're storing the timestamp in seconds since 1970, while the code in your Cloud Functions assumes it is in milliseconds.

The simplest fix is:

```<code>// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.

exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
    const ref = change.after.ref.parent; // reference to the parent
    const now = Date.now();
    const cutoff = (now - CUT_OFF_TIME) / 1000; // convert to seconds
    const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
    const snapshot = await oldItemsQuery.once('value');
    // create a map with all children that need to be removed
    const updates = {};
    snapshot.forEach(child => {
        updates[child.key] = null;
    });
    // execute all updates in one go and return the result to end the function
    return ref.update(updates);
});
</code>```

Also see my answer here: How to remove a child node after a certain date is passed in Firebase cloud functions?

Body:
My goal is to delete all the message nodes 24 hours after they were sent using Firebase Cloud Functions and the Realtime Database. I tried copy and pasting the answer from this post however for some reason the messages delete directly after they were created rather than the 24 hours later. If someone could help me solve this problem I would really appreciate it. I have tried multiple different answers based on the same issue and they haven't worked for me.

Here is my index.js file:

'use strict';

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.

exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
const ref = change.after.ref.parent; // reference to the parent
const now = Date.now();
const cutoff = now - CUT_OFF_TIME;
const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
const snapshot = await oldItemsQuery.once('value');
// create a map with all children that need to be removed
const updates = {};
snapshot.forEach(child => {
updates[child.key] = null;
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});

And my database structure is:

Body:
In the comments you indicated that you're using Swift. From that and the screenshot it turns out that you're storing the timestamp in seconds since 1970, while the code in your Cloud Functions assumes it is in milliseconds.

The simplest fix is:

// Cut off time. Child nodes older than this will be deleted.
const CUT_OFF_TIME = 24 * 60 * 60 * 1000; // 2 Hours in milliseconds.

exports.deleteOldMessages = functions.database.ref('/Message/{chatRoomId}').onWrite(async (change) => {
    const ref = change.after.ref.parent; // reference to the parent
    const now = Date.now();
    const cutoff = (now - CUT_OFF_TIME) / 1000; // convert to seconds
    const oldItemsQuery = ref.orderByChild('seconds').endAt(cutoff);
    const snapshot = await oldItemsQuery.once('value');
    // create a map with all children that need to be removed
    const updates = {};
    snapshot.forEach(child => {
        updates[child.key] = null;
    });
    // execute all updates in one go and return the result to end the function
    return ref.update(updates);
});

Also see my answer here: How to remove a child node after a certain date is passed in Firebase cloud functions?