问:
Symfony 4 - Manually Form
I'm creating my first project in Symfony framework.
I chose 4.0 version. I have a question about creating forms.

config/routes.yaml

```<code>home:
    path: /
    controller: App\Controller\HomeController::index
    methods: [GET]

login:
    path: /login
    controller: App\Controller\HomeController::login
    methods: [POST]

register:
    path: /register
    controller: App\Controller\HomeController::register
    methods: [POST]

timeline:
    path: /timeline
    controller: App\Controller\TimelineController::index
    methods: [GET]
</code>```

src/Entity/User.php

```<code>//

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $lastName;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
    }

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }
}
</code>```

src/Controller/HomeController.php

```<code><?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\User;

class HomeController extends Controller
{
    public function index() {
        return $this->render('home/index.html.twig');
    }

    public function login(Request $request) {
        // ?????
    }

    public function register(Request $request) {
        $user = new User();
        // ?????
    }
}
</code>```

templates/home/index.html.twig

```<code>...

<form action="{{ path('login') }}" id="signInForm" role="form"
      method="POST" class="visible">
                        <h2>Sign In</h2>
                        <hr class="colorgraph">
                        <div class="form-group">
                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address">
                        </div>
                        <div class="form-group">
                            <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password">
                        </div>
                        <span class="button-checkbox">
                            <button type="button" class="btn btn-info active" data-color="info">
                                <i class="state-icon glyphicon glyphicon-check"></i> Remember Me</button>
                           <input type="checkbox" name="remember_me" id="remember_me" class="hidden">
                            <a href="" class="btn btn-link pull-right">Forgot Password?</a>
                        </span>
                        <hr class="colorgraph">
                        <div class="row">
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                  <input type="submit" class="btn btn-lg btn-success btn-block" value="Sign In">
                            </div>
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                <a id="registerBtn" href="#" class="btn btn-lg btn-block btn-toggle">To Register</a>
                            </div>
                        </div>
                    </form>
                    <form action="{{ path('register') }}" id="registerForm" role="form" method="POST">
                        <h2>
                            Please Sign Up
                            <small>It's free and always will be.</small>
                        </h2>
                        <hr class="colorgraph">
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <input type="text" name="display_name" id="display_name" class="form-control input-lg" placeholder="Display Name" tabindex="3">
                        </div>
                        <div class="form-group">
                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">
                        </div>
                        <div class="row">
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">
                                </div>
                            </div>
                            <div class="col-xs-12 col-sm-6 col-md-6">
                                <div class="form-group">
                                    <input type="password" name="password_confirmation" id="password_confirmation" class="form-control input-lg" placeholder="Confirm Password"
                                        tabindex="6">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-xs-4 col-sm-3 col-md-3">
                                <span class="button-checkbox">
                                    <button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
                                    <input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">
                                </span>
                            </div>
                            <div class="col-xs-8 col-sm-9 col-md-9">
                                By clicking
                                <strong class="label label-primary">Register</strong>, you agree to the
                                <a href="#" data-toggle="modal" data-target="#t_and_c_m">Terms and Conditions</a> set out by this site, including our Cookie Use.
                            </div>
                        </div>

                        <hr class="colorgraph">
                        <div class="row">
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                <input type="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="7">
                            </div>
                            <div class="col-xs-6 col-sm-6 col-md-6">
                                <a id="signInBtn" href="#" class="btn btn-block btn-lg btn-toggle">To Sign In</a>
                            </div>
                        </div>
                    </form>
...
</code>```

What should be in the controller in the login() and register() methods?
I've read about creating forms in Symfony, but I want to use the form from a view done manually.

Should it look like this?

```<code>public function login(Request $request) {
        $email = $request->get('email');
        $password = $request->get('password');

        $repository = $this->getDoctrine()->getRepository(User::class);
        $user = $repository->findOneBy([
            'email' => $email,
            'password' => $password
        ]);

        if($user) {
            // TODO: Set session
            return $this->redirectToRoute('timeline');
        }

        return $this->redirectToRoute('home');
    }

    public function register(Request $request) {
        $user = new User();

        $firstName = $request->get('first_name');
        $lastName = $request->get('last_name');
        $nickname = $request->get('display_name');
        $email = $request->get('email');
        $password = $request->get('password');
        $password2 = $request->get('password_confirmation');

        // VALIDATION

        return $this->render('message.html.twig', [
            'header' => 'Congratulations',
            'title' => 'Welcome <b>'. ucfirst($firstName) .' '. ucfirst($lastName) .'</b>!',
            'message' => 'The registration process completed correctly!
            An activation link has been sent to your e-mail address.',
            'button' => [
                'href' => $this->generateUrl('home'),
                'text' => 'To Sign In'
            ]
        ]);
    }
</code>```

答:
I have implemented a small and simple login & reset password actions without fosuserbundle in Symfony 4. This is not so complicated to do:

Configure your security:

```<code># config/packages/security.yaml
security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt

    providers:
        our_db_provider: # Arbitrary name
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern:    ^/
            provider: our_db_provider # Use any declared provider above
            form_login:
                login_path: login
                check_path: login
                default_target_path: /
            anonymous: true
            logout:
                path:   /logout
                target: /
            remember_me:
                secret:   '%env(APP_SECRET)%'
                lifetime: 604800 # 1 week in seconds
                path:     /

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_USER }
</code>```

The login action:

```<code>// src/Controller/Security/SecurityController.php
namespace App\Controller\Security;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends Controller
{
    public function login(Request $request, AuthenticationUtils $authUtils)
    {
        $error = $authUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('Security/login.html.twig', [
            'error' => $error,
            'last_username' => $lastUsername,
        ]);
    }
}
</code>```

The login template

```<code># templates/Security/login.html.twig
{% block body %}
    <h1>Login</h1>

    <div class="login-page">
        <div class="form">

            {% if error %}
                <div class="error">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
            {% endif %}

            <form action="{{ path('login') }}" method="post">

                <div>
                    <label for="username">Email:</label>
                    <input type="text" id="username" name="_username" value="{{ last_username }}" />
                </div>
                <div>
                    <label for="password">Password:</label>
                    <input type="password" id="password" name="_password" />
                </div>
                <div class="cta">
                    <div>
                        <input type="checkbox" id="remember_me" name="_remember_me" checked />
                        <label for="remember_me">Keep me logged in</label>
                    </div>
                    <div>
                        <button type="submit">Connexion</button>
                    </div>
                </div>
            </form>
            <a href="{{ path('request_password') }}">Forgot password ?</a>
        </div>
    </div>
{% endblock %}
</code>```

The User Manager:

```<code># src/Manager/UserManager.php
use App\Entity\User;
use App\Util\PasswordUpdater;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * Class UserManager
 * @package App\Manager
 */
class UserManager
{
    /** @var EntityManagerInterface  */
    private $em;

    /** @var PasswordUpdater  */
    private $passwordUpdater;

    /**
     * UserManager constructor.
     *
     * @param EntityManagerInterface $em
     * @param PasswordUpdater $passwordUpdater
     */
    public function __construct(EntityManagerInterface $em, PasswordUpdater $passwordUpdater)
    {
        $this->em = $em;
        $this->passwordUpdater = $passwordUpdater;
    }

    /**
     * Find a user by his username
     *
     * @param string $username
     *
     * @return \App\Entity\User|null
     */
    public function findUserByUsername($username)
    {
        $user = $this->em->getRepository('App\Entity\User')->findOneBy(['username' => $username]);

        return $user;
    }

    /**
     * Update a user
     *
     * @param AdvancedUserInterface $user
     *
     * @param bool $andFlush
     */
    public function updateUser(AdvancedUserInterface $user, $andFlush = true)
    {
        $this->em->persist($user);

        if ($andFlush) {
            $this->em->flush();
        }
    }

    /**
     * Find a user by his confirmationToken
     *
     * @param $confirmationToken
     *
     * @return \App\Entity\User|null
     */
    public function findUserByConfirmationToken($confirmationToken)
    {
        $user = $this->em->getRepository('App\Entity\User')->findOneBy(['confirmationToken' => $confirmationToken]);

        return $user;
    }

    /**
     * Encode & update user password
     *
     * @param User $user
     */
    public function updateUserPassword(User $user)
    {
        $this->passwordUpdater->hashPassword($user);
        $user->setConfirmationToken(null);
        $user->setPasswordRequestedAt(null);
    }
}
</code>```

And the User Entity:

```<code># src/Entity/User.php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=100, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * Random string sent to the user email address in order to verify it.
     *
     * @var string
     *
     * @ORM\Column(type="string", length=180, nullable=true)
     */
    protected $confirmationToken;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $passwordRequestedAt;

    /**
     * User constructor.
     */
    public function __construct()
    {
        $this->isActive = true;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getSalt()
    {
        return null;
    }

    public function setSalt($salt)
    {
        return null;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;
        $this->username = $email;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param mixed $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @return mixed
     */
    public function isActive()
    {
        return $this->isActive;
    }

    /**
     * @param mixed $isActive
     * @return User
     */
    public function setActive($isActive)
    {
        $this->isActive = $isActive;
        return $this;
    }

    public function getRoles()
    {
        return array('ROLE_USER');
    }

    public function eraseCredentials()
    {
    }

    public function isAccountNonExpired()
    {
        return true;
    }

    public function isAccountNonLocked()
    {
        return true;
    }

    public function isCredentialsNonExpired()
    {
        return true;
    }

    public function isEnabled()
    {
        return $this->isActive;
    }

    /**
     * @return string
     */
    public function getConfirmationToken()
    {
        return $this->confirmationToken;
    }

    /**
     * @param $confirmationToken
     *
     * @return $this
     */
    public function setConfirmationToken($confirmationToken)
    {
        $this->confirmationToken = $confirmationToken;

        return $this;
    }

    /**
     * @param \DateTime|null $date
     *
     * @return $this
     */
    public function setPasswordRequestedAt(\DateTime $date = null)
    {
        $this->passwordRequestedAt = $date;

        return $this;
    }

    /**
     * Gets the timestamp that the user requested a password reset.
     *
     * @return null|\DateTime
     */
    public function getPasswordRequestedAt()
    {
        return $this->passwordRequestedAt;
    }

    /**
     * @param $ttl
     *
     * @return bool
     */
    public function isPasswordRequestNonExpired($ttl)
    {
        return $this->getPasswordRequestedAt() instanceof \DateTime &&
            $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->email,
            $this->username,
            $this->password,
            $this->isActive,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->email,
            $this->username,
            $this->password,
            $this->isActive,
            ) = unserialize($serialized);
    }
}
</code>```

This is the way I deal with it. This is problably not perfect, but it works fine. You can find sources here : https://github.com/matthieuleorat/documentManager

Hope this will help you.

Title: Symfony 4 - Manually Form

Body:
I'm creating my first project in Symfony framework.
I chose 4.0 version. I have a question about creating forms.

config/routes.yaml

home:
    path: /
    controller: App\Controller\HomeController::index
    methods: [GET]

login:
    path: /login
    controller: App\Controller\HomeController::login
    methods: [POST]

register:
    path: /register
    controller: App\Controller\HomeController::register
    methods: [POST]

timeline:
    path: /timeline
    controller: App\Controller\TimelineController::index
    methods: [GET]

src/Entity/User.php

//

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="users")
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $lastName;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function getFirstName()
    {
        return $this->firstName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;
    }

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }
}

src/Controller/HomeController.php

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Entity\User;

class HomeController extends Controller
{
    public function index() {
        return $this->render('home/index.html.twig');
    }

    public function login(Request $request) {
        // ?????
    }

    public function register(Request $request) {
        $user = new User();
        // ?????
    }
}

templates/home/index.html.twig

...

<form action="{{ path('login') }}" id="signInForm" role="form"
      method="POST" class="visible">

Sign In

                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address">

                            <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password">

                            <button type="button" class="btn btn-info active" data-color="info">
                                 Remember Me</button>
                           <input type="checkbox" name="remember_me" id="remember_me" class="hidden">
                            Forgot Password?

                                  <input type="submit" class="btn btn-lg btn-success btn-block" value="Sign In">

                                To Register

                    </form>
                    <form action="{{ path('register') }}" id="registerForm" role="form" method="POST">

                            Please Sign Up
                            It's free and always will be.

                                    <input type="text" name="first_name" id="first_name" class="form-control input-lg" placeholder="First Name" tabindex="1">

                                    <input type="text" name="last_name" id="last_name" class="form-control input-lg" placeholder="Last Name" tabindex="2">

                            <input type="text" name="display_name" id="display_name" class="form-control input-lg" placeholder="Display Name" tabindex="3">

                            <input type="email" name="email" id="email" class="form-control input-lg" placeholder="Email Address" tabindex="4">

                                    <input type="password" name="password" id="password" class="form-control input-lg" placeholder="Password" tabindex="5">

                                    <input type="password" name="password_confirmation" id="password_confirmation" class="form-control input-lg" placeholder="Confirm Password"
                                        tabindex="6">

                                    <button type="button" class="btn" data-color="info" tabindex="7">I Agree</button>
                                    <input type="checkbox" name="t_and_c" id="t_and_c" class="hidden" value="1">

                                By clicking
                                Register, you agree to the
                                Terms and Conditions set out by this site, including our Cookie Use.

                                <input type="submit" value="Register" class="btn btn-primary btn-block btn-lg" tabindex="7">

                                To Sign In

                    </form>
...

What should be in the controller in the login() and register() methods?
I've read about creating forms in Symfony, but I want to use the form from a view done manually.

Should it look like this?

public function login(Request $request) {
        $email = $request->get('email');
        $password = $request->get('password');

        $repository = $this->getDoctrine()->getRepository(User::class);
        $user = $repository->findOneBy([
            'email' => $email,
            'password' => $password
        ]);

        if($user) {
            // TODO: Set session
            return $this->redirectToRoute('timeline');
        }

        return $this->redirectToRoute('home');
    }

    public function register(Request $request) {
        $user = new User();

        $firstName = $request->get('first_name');
        $lastName = $request->get('last_name');
        $nickname = $request->get('display_name');
        $email = $request->get('email');
        $password = $request->get('password');
        $password2 = $request->get('password_confirmation');

        // VALIDATION

        return $this->render('message.html.twig', [
            'header' => 'Congratulations',
            'title' => 'Welcome '. ucfirst($firstName) .' '. ucfirst($lastName) .'!',
            'message' => 'The registration process completed correctly!
            An activation link has been sent to your e-mail address.',
            'button' => [
                'href' => $this->generateUrl('home'),
                'text' => 'To Sign In'
            ]
        ]);
    }

Body:
I have implemented a small and simple login & reset password actions without fosuserbundle in Symfony 4. This is not so complicated to do:

Configure your security:

# config/packages/security.yaml
security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt

    providers:
        our_db_provider: # Arbitrary name
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            pattern:    ^/
            provider: our_db_provider # Use any declared provider above
            form_login:
                login_path: login
                check_path: login
                default_target_path: /
            anonymous: true
            logout:
                path:   /logout
                target: /
            remember_me:
                secret:   '%env(APP_SECRET)%'
                lifetime: 604800 # 1 week in seconds
                path:     /

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: ROLE_USER }

The login action:

// src/Controller/Security/SecurityController.php
namespace App\Controller\Security;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends Controller
{
    public function login(Request $request, AuthenticationUtils $authUtils)
    {
        $error = $authUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('Security/login.html.twig', [
            'error' => $error,
            'last_username' => $lastUsername,
        ]);
    }
}

The login template

# templates/Security/login.html.twig
{% block body %}
    <h1>Login</h1>

    <div class="login-page">
        <div class="form">

            {% if error %}
                <div class="error">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
            {% endif %}

            <form action="{{ path('login') }}" method="post">

                <div>
                    <label for="username">Email:</label>
                    <input type="text" id="username" name="_username" value="{{ last_username }}" />
                </div>
                <div>
                    <label for="password">Password:</label>
                    <input type="password" id="password" name="_password" />
                </div>
                <div class="cta">
                    <div>
                        <input type="checkbox" id="remember_me" name="_remember_me" checked />
                        <label for="remember_me">Keep me logged in</label>
                    </div>
                    <div>
                        <button type="submit">Connexion</button>
                    </div>
                </div>
            </form>
            <a href="{{ path('request_password') }}">Forgot password ?</a>
        </div>
    </div>
{% endblock %}

The User Manager:

# src/Manager/UserManager.php
use App\Entity\User;
use App\Util\PasswordUpdater;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * Class UserManager
 * @package App\Manager
 */
class UserManager
{
    /** @var EntityManagerInterface  */
    private $em;

    /** @var PasswordUpdater  */
    private $passwordUpdater;

    /**
     * UserManager constructor.
     *
     * @param EntityManagerInterface $em
     * @param PasswordUpdater $passwordUpdater
     */
    public function __construct(EntityManagerInterface $em, PasswordUpdater $passwordUpdater)
    {
        $this->em = $em;
        $this->passwordUpdater = $passwordUpdater;
    }

    /**
     * Find a user by his username
     *
     * @param string $username
     *
     * @return \App\Entity\User|null
     */
    public function findUserByUsername($username)
    {
        $user = $this->em->getRepository('App\Entity\User')->findOneBy(['username' => $username]);

        return $user;
    }

    /**
     * Update a user
     *
     * @param AdvancedUserInterface $user
     *
     * @param bool $andFlush
     */
    public function updateUser(AdvancedUserInterface $user, $andFlush = true)
    {
        $this->em->persist($user);

        if ($andFlush) {
            $this->em->flush();
        }
    }

    /**
     * Find a user by his confirmationToken
     *
     * @param $confirmationToken
     *
     * @return \App\Entity\User|null
     */
    public function findUserByConfirmationToken($confirmationToken)
    {
        $user = $this->em->getRepository('App\Entity\User')->findOneBy(['confirmationToken' => $confirmationToken]);

        return $user;
    }

    /**
     * Encode & update user password
     *
     * @param User $user
     */
    public function updateUserPassword(User $user)
    {
        $this->passwordUpdater->hashPassword($user);
        $user->setConfirmationToken(null);
        $user->setPasswordRequestedAt(null);
    }
}

And the User Entity:

# src/Entity/User.php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=100, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * Random string sent to the user email address in order to verify it.
     *
     * @var string
     *
     * @ORM\Column(type="string", length=180, nullable=true)
     */
    protected $confirmationToken;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $passwordRequestedAt;

    /**
     * User constructor.
     */
    public function __construct()
    {
        $this->isActive = true;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function getSalt()
    {
        return null;
    }

    public function setSalt($salt)
    {
        return null;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     * @return User
     */
    public function setEmail($email)
    {
        $this->email = $email;
        $this->username = $email;

        return $this;
    }

    /**
     * @return mixed
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * @param mixed $password
     * @return User
     */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @return mixed
     */
    public function isActive()
    {
        return $this->isActive;
    }

    /**
     * @param mixed $isActive
     * @return User
     */
    public function setActive($isActive)
    {
        $this->isActive = $isActive;
        return $this;
    }

    public function getRoles()
    {
        return array('ROLE_USER');
    }

    public function eraseCredentials()
    {
    }

    public function isAccountNonExpired()
    {
        return true;
    }

    public function isAccountNonLocked()
    {
        return true;
    }

    public function isCredentialsNonExpired()
    {
        return true;
    }

    public function isEnabled()
    {
        return $this->isActive;
    }

    /**
     * @return string
     */
    public function getConfirmationToken()
    {
        return $this->confirmationToken;
    }

    /**
     * @param $confirmationToken
     *
     * @return $this
     */
    public function setConfirmationToken($confirmationToken)
    {
        $this->confirmationToken = $confirmationToken;

        return $this;
    }

    /**
     * @param \DateTime|null $date
     *
     * @return $this
     */
    public function setPasswordRequestedAt(\DateTime $date = null)
    {
        $this->passwordRequestedAt = $date;

        return $this;
    }

    /**
     * Gets the timestamp that the user requested a password reset.
     *
     * @return null|\DateTime
     */
    public function getPasswordRequestedAt()
    {
        return $this->passwordRequestedAt;
    }

    /**
     * @param $ttl
     *
     * @return bool
     */
    public function isPasswordRequestNonExpired($ttl)
    {
        return $this->getPasswordRequestedAt() instanceof \DateTime &&
            $this->getPasswordRequestedAt()->getTimestamp() + $ttl > time();
    }

    /** @see \Serializable::serialize() */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->email,
            $this->username,
            $this->password,
            $this->isActive,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized)
    {
        list (
            $this->id,
            $this->email,
            $this->username,
            $this->password,
            $this->isActive,
            ) = unserialize($serialized);
    }
}

This is the way I deal with it. This is problably not perfect, but it works fine. You can find sources here : https://github.com/matthieuleorat/documentManager

Hope this will help you.


来源: stackexchange

问:
Split a single commit to multiple commits by filename without manually going through all files
I have a commit that has changes to 100 files. I want to split that commit to 100 commits with one commit by filename.

Currently I do git rebase -i <startpoint> then mark the commit I want to edit with e and reset HEAD^1 followed by series of git add && git commit -m <filename>. This becomes tedious with multiple files.

Preferably in one line of bash without scripts. Also it should be readable enough for memorization.

Update: Ended up using ElpieKay's solution with

```<code>git reset HEAD^ --soft
git diff --cached --name-only --relative | while read f; do git commit -m "$f" -- "$f"; done
</code>```

答:
Suppose it is the last commit and the commit id is abc123.

Try

```<code>git reset abc123 --hard
git reset abc123^ --soft
git diff --cached --name-only | while read f;do git commit -m "$f" -- "$f";done
</code>```

If anything goes wrong, run git reset abc123 --hard to restore.

ContentLicense: CC BY-SA 3.0

Body:
I have a commit that has changes to 100 files. I want to split that commit to 100 commits with one commit by filename.

Currently I do git rebase -i <startpoint> then mark the commit I want to edit with e and reset HEAD^1 followed by series of git add && git commit -m <filename>. This becomes tedious with multiple files.

Preferably in one line of bash without scripts. Also it should be readable enough for memorization.

Update: Ended up using ElpieKay's solution with

git reset HEAD^ --soft
git diff --cached --name-only --relative | while read f; do git commit -m "$f" -- "$f"; done

Body:
Suppose it is the last commit and the commit id is abc123.

Try

git reset abc123 --hard
git reset abc123^ --soft
git diff --cached --name-only | while read f;do git commit -m "$f" -- "$f";done

If anything goes wrong, run git reset abc123 --hard to restore.


问:
ESLint - "window" is not defined. How to allow global variables in package.json
I am assigning a property to the global window object, but when I run eslint, I get this:

"window" is not defined

I see this here in the eslint docs:

the following defines window as a global variable for code that should not trigger the rule being tested:

```<code>valid: [
  {
    code: "window.alert()",
    globals: [ "window" ]
  }
]
</code>```

I've tried adding something like this to the package.json file to have eslint allow "window" as a global variable, but I must be doing something wrong.  From the docs it seems like I might need to do something like this in a separate file, but is there a way to define some allowed global variables right in the package.json file?

答:
Your .eslintrc.json should contain the text below.

This way ESLint knows about your global variables.

```<code>{
  "env": {
    "browser": true,
    "node": true
  }
}
</code>```

Body:
I am assigning a property to the global window object, but when I run eslint, I get this:

"window" is not defined

I see this here in the eslint docs:

the following defines window as a global variable for code that should not trigger the rule being tested:

valid: [
  {
    code: "window.alert()",
    globals: [ "window" ]
  }
]

I've tried adding something like this to the package.json file to have eslint allow "window" as a global variable, but I must be doing something wrong.  From the docs it seems like I might need to do something like this in a separate file, but is there a way to define some allowed global variables right in the package.json file?

Body:
Your .eslintrc.json should contain the text below.

This way ESLint knows about your global variables.

{
  "env": {
    "browser": true,
    "node": true
  }
}

ContentLicense: CC BY-SA 4.0


问:
mod_perl server events for client
What is a good way to implement server to client callbacks (events) with a web service?

We already have a SOAP-based API exposed by mod_perl running on Apache, but it is one way client to server.  We need to notify the client of certain changes on the server by other clients.

What is a good way to make this work?  Available modules for perl?

One thing we thought of was to make a long running web request that would finally respond when an event occurred, but this would seem to keep too many mod_perl processes running if many clients were connected.

答:
Have you actually tried your first approach ? How many max concurrent clients would that be? A few dozens should be manageable by apache. Just guessing.

Have you tried this low-tech method "Watching long processes through CGI", or is it what you wanted to get rid of in the first place?

ContentLicense: CC BY-SA 2.5

Title: mod_perl server events for client


问:
Index find position for matching string
Consider following example

```<code>index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index
</code>```

I want to find the position of 'a' in the index "index_id". How do I do that. Trying

```<code>index_id.index('a')
</code>```

does not work (error 'Index' object has no attribute 'index'). Thanks a lot

答:
If I understand you correctly, this may be what you want:

```<code>print(df.ix['a'].index.tolist())
</code>```

Output:

```<code>[0]
</code>```

Title: Index find position for matching string

Body:
Consider following example

index_abcd = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
data = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
df = pd.DataFrame(data, index=index_abcd)
index_id= df.index

I want to find the position of 'a' in the index "index_id". How do I do that. Trying

index_id.index('a')

does not work (error 'Index' object has no attribute 'index'). Thanks a lot

Body:
If I understand you correctly, this may be what you want:

print(df.ix['a'].index.tolist())

Output:

[0]


问:
Check if there is someone logged in Django
I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code:

```<code>def home(request):
    if not request.user:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)
</code>```

It works if there is a user logged in but doesnt work if there is no user logged in...

答:
Django provides a decorator for this: </p>

```<code>from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    # at this point you know you _always_ have an authenticated user
    user = request.user
    profile = Profile.objects.get(user=user)
    context = {
        'user':user,
        'profile':profile,
    }
    return render(request, 'user/home.html', context)
</code>```

Body:
I have a new django project I am working on. I am integrating Djangos user login and logout service that comes with the framework. I have a view and within the view, I want to check and see if there is a user object in the request.user. if there is not, I want to redirect to login page. If there is a user in the request.user, I want to display the users home page. how can I do this. Here is my code:

def home(request):
    if not request.user:
        return redirect('login')
    else:
        User = request.user
        profile = Profile.objects.get(user = User)
        parameters = {
            'user':User,
            'profile':profile,
        }
        return render(request, 'user/home.html', parameters)

It works if there is a user logged in but doesnt work if there is no user logged in...

Body:
Django provides a decorator for this:

from django.contrib.auth.decorators import login_required

@login_required
def home(request):
    # at this point you know you _always_ have an authenticated user
    user = request.user
    profile = Profile.objects.get(user=user)
    context = {
        'user':user,
        'profile':profile,
    }
    return render(request, 'user/home.html', context)


问:
Xcode - Implement network error alerts into my app? Cant get it to work?
I have downloaded and added apples reachability(.h+.m) files to my view bases project and not made any changes. I have also added the systemconfiguration.framework.

In my viewcontroller.h file I have added "@class reachability" just before "@interface", and I have also added "- (void) checkNetworkStatus:(NSNotification *)notice;" just before "@end".

I have imported reachability.h into my viewcontroller.m file, here is the rest of it:

// check for internet connection
          [[NSNotificationCenter defaultCenter] addObserver:self           selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

```<code>    internetReachable = [[Reachability reachabilityForInternetConnection]             retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"]          retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification

- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes

    NetworkStatus internetStatus = [internetReachable            currentReachabilityStatus];
    switch (internetStatus)

{
        case NotReachable:
{
            NSLog(@"The internet is down.");
            self.internetActive = NO;
            break;
}
        case ReachableViaWiFi:
{
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;

}
        case ReachableViaWWAN:
{
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;

            break;
}
}
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
{
        case NotReachable:
{
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

            break;

}
        case ReachableViaWiFi:
{
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;

}
        case ReachableViaWWAN:
{
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;

            break;
}
}
}
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];

    [super dealloc];
}

@end
</code>```

I get 2 warnings:
-"Incorrect implementation of class 'TestViewController'" (which worked before I tried to do this)
-And also, "method definition for -'checkNetworkStatus:' not found"

The 2 errors are:
-"'checkNetworkStatus' undeclared"
-And "expected ';' before ':'"

Can anyone please help me?

EDIT:

.h file:

```<code>>#import <UIKit/UIKit.h>

@class Reachability;

@interface TestViewController : UIViewController {

IBOutlet UIView *landscape;
IBOutlet UIView *portrait;
IBOutlet UIView *portraitupsidedown;

IBOutlet UIWebView *WebView;
IBOutlet UIWebView *WebView2;
IBOutlet UIWebView *WebView3;
IBOutlet UIWebView *WebView4;

Reachability* internetReachable;
    Reachability* hostReachable;
}

@property(nonatomic,retain) UIView *landscape;
@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *portraitupsidedown;

- (void) checkNetworkStatus:(NSNotification *)notice;

@end
</code>```

答:
You've got one-too-many }s at the end of checkNetworkStatus:.  If your code was properly white-spaced then it would be much harder to make this kind of mistake.  By "properly white-spaced" I mean your code should look like this:

```<code>}
- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;
            break;
        }
    }
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;
            break;
        }
    }
}
</code>```

This formatting makes it trivial to find bracketing/nesting errors.  :)

Body:
I have downloaded and added apples reachability(.h+.m) files to my view bases project and not made any changes. I have also added the systemconfiguration.framework.

In my viewcontroller.h file I have added "@class reachability" just before "@interface", and I have also added "- (void) checkNetworkStatus:(NSNotification *)notice;" just before "@end".

I have imported reachability.h into my viewcontroller.m file, here is the rest of it:

// check for internet connection
          [[NSNotificationCenter defaultCenter] addObserver:self           selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [[Reachability reachabilityForInternetConnection]             retain];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [[Reachability reachabilityWithHostName: @"www.apple.com"]          retain];
    [hostReachable startNotifier];

    // now patiently wait for the notification

- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes

    NetworkStatus internetStatus = [internetReachable            currentReachabilityStatus];
    switch (internetStatus)

{
        case NotReachable:
{
            NSLog(@"The internet is down.");
            self.internetActive = NO;
            break;
}
        case ReachableViaWiFi:
{
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;

}
        case ReachableViaWWAN:
{
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;

            break;
}
}
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
{
        case NotReachable:
{
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

            break;

}
        case ReachableViaWiFi:
{
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;

}
        case ReachableViaWWAN:
{
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;

            break;
}
}
}
}

- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}

- (void)dealloc:(BOOL)animated
{
[[NSNotificationCenter defaultCenter] removeObserver:self];

    [super dealloc];
}

@end

I get 2 warnings:
-"Incorrect implementation of class 'TestViewController'" (which worked before I tried to do this)
-And also, "method definition for -'checkNetworkStatus:' not found"

The 2 errors are:
-"'checkNetworkStatus' undeclared"
-And "expected ';' before ':'"

Can anyone please help me?

EDIT:

.h file:

>#import <UIKit/UIKit.h>

@class Reachability;

@interface TestViewController : UIViewController {

IBOutlet UIView *landscape;
IBOutlet UIView *portrait;
IBOutlet UIView *portraitupsidedown;

IBOutlet UIWebView *WebView;
IBOutlet UIWebView *WebView2;
IBOutlet UIWebView *WebView3;
IBOutlet UIWebView *WebView4;

Reachability* internetReachable;
    Reachability* hostReachable;
}

@property(nonatomic,retain) UIView *landscape;
@property(nonatomic,retain) UIView *portrait;
@property(nonatomic,retain) UIView *portraitupsidedown;

- (void) checkNetworkStatus:(NSNotification *)notice;

@end

Body:
You've got one-too-many }s at the end of checkNetworkStatus:.  If your code was properly white-spaced then it would be much harder to make this kind of mistake.  By "properly white-spaced" I mean your code should look like this:

}
- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;
            break;
        }
    }
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;
            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;
            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;
            break;
        }
    }
}

This formatting makes it trivial to find bracketing/nesting errors.  :)


问:
"Select Case True" - adding more criterias
I have a code below that stopped working after I've added this new bit:

```<code>Select Case True
    Case Range("B16") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    Case Range("B16") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("B16") = "Standard Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    End Select
</code>```

FULL CODE:

```<code>Private Sub Worksheet_Calculate()
Application.EnableEvents = False
Application.ScreenUpdating = False

    Select Case True
    Case Range("B14") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("B14") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    End Select

Select Case True
    Case Range("XES72") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("XES72") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    End Select

Select Case True
    Case Range("B16") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    Case Range("B16") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("B16") = "Standard Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    End Select

Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
</code>```

Any advice how to make sure that the "new" part I have added is also considered by the VBA?

The part which works is this (and everything above it):

```<code>Select Case True
    Case Range("B16") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
</code>```

Then, if I change B16 back to "Medium Risk" (or "Standard Risk") it simply doesn't hide the rows that it supposed to:

```<code> Case Range("B16") = "Medium Risk"
            Rows("5:12").EntireRow.Hidden = True
            Rows("24").EntireRow.Hidden = True
 Case Range("B16") = "Standard Risk"
            Rows("5:12").EntireRow.Hidden = True
            Rows("24").EntireRow.Hidden = True
        End Select
</code>```

答:
Your Select Case statements should be constructed a bit differently. Instead of this logic:

```<code>Select Case True
    Case Range("B16") = "High Risk"
    ...
    ...
</code>```

you should use this logic:

```<code>Select Case Range("B16")  '<< check the value of cell B16 ...
    Case "High Risk"      '<< ... in case it equals 'High Risk'...
    ...                   '<< ... do this
    ...
</code>```

Body:
I have a code below that stopped working after I've added this new bit:

Select Case True
    Case Range("B16") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    Case Range("B16") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("B16") = "Standard Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    End Select

FULL CODE:

Private Sub Worksheet_Calculate()
Application.EnableEvents = False
Application.ScreenUpdating = False

    Select Case True
    Case Range("B14") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("B14") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    End Select

Select Case True
    Case Range("XES72") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("XES72") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    End Select

Select Case True
    Case Range("B16") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False
    Case Range("B16") = "Medium Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    Case Range("B16") = "Standard Risk"
        Rows("5:12").EntireRow.Hidden = True
        Rows("24").EntireRow.Hidden = True
    End Select

Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

Any advice how to make sure that the "new" part I have added is also considered by the VBA?

The part which works is this (and everything above it):

Select Case True
    Case Range("B16") = "High Risk"
        Rows("5:12").EntireRow.Hidden = False
        Rows("24").EntireRow.Hidden = False

Then, if I change B16 back to "Medium Risk" (or "Standard Risk") it simply doesn't hide the rows that it supposed to:

 Case Range("B16") = "Medium Risk"
            Rows("5:12").EntireRow.Hidden = True
            Rows("24").EntireRow.Hidden = True
 Case Range("B16") = "Standard Risk"
            Rows("5:12").EntireRow.Hidden = True
            Rows("24").EntireRow.Hidden = True
        End Select

Body:
Your Select Case statements should be constructed a bit differently. Instead of this logic:

Select Case True
    Case Range("B16") = "High Risk"
    ...
    ...

you should use this logic:

Select Case Range("B16")  '<< check the value of cell B16 ...
    Case "High Risk"      '<< ... in case it equals 'High Risk'...
    ...                   '<< ... do this
    ...


问:
iterating through values in a dictionary to invert key and values
I am trying to invert an italian-english dictionary using the code that follows.

Some terms have one translation, while others have multiple possibilities. If an entry has multiple translations I iterate through each word, adding it to english-italian dict (if not already present).

If there is a single translation it should not iterate, but as I have written the code, it does. Also only the last translation in the term with multiple translations is added to the dictionary. I cannot figure out how to rewrite the code to resolve what should be a really simple task

```<code>from collections import defaultdict

def invertdict():
    source_dict ={'paramezzale (s.m.)': ['hog', 'keelson', 'inner keel'], 'vento (s.m.)': 'wind'}

    english_dict = defaultdict(list)

    for parola, words in source_dict.items():
        if len(words) > 1: # more than one translation ?
            for word in words: # if true, iterate through each word
                word = str(word).strip(' ')
                print(word)
        else: # only one translation, don't iterate!!
            word = str(words).strip(' ')
            print(word)
        if word in english_dict.keys(): # check to see if the term already exists
            if english_dict[word] != parola: # check that the italian is not present
                #english_dict[word] = [english_dict[word], parola]
                english_dict[word].append(parola).strip('')
        else:
           english_dict[word] = parola.strip(' ')

    print(len(english_dict))

    for key,value in english_dict.items():
       print(key, value)
</code>```

When this code is run, I get :

```<code>hog
keelson
inner keel
w
i
n
d
2
inner keel paramezzale (s.m.)
d vento (s.m.)
</code>```

instead of

```<code>hog: paramezzale, keelson: paramezzale, inner keel: paramezzale, wind: vento
</code>```

答:
It would be easier to use lists everywhere in the dictionary, like:

```<code>source_dict = {'many translations': ['a', 'b'], 'one translation': ['c']}
</code>```

Then you need 2 nested loops. Right now you're not always running the inner loop.

```<code>for italian_word, english_words in source_dict.items():
    for english_word in english_words:
        # print, add to english dict, etc.
</code>```

If you can't change the source_dict format, you need to check the type explicitly. I would transform the single item in a list.

```<code>for italian_word, item in source_dict.items():
    if not isinstance(item, list):
        item = [item]
</code>```

Full code:

```<code>source_dict ={'paramezzale (s.m.)': ['hog', 'keelson', 'inner keel'], 'vento (s.m.)': ['wind']}

english_dict = defaultdict(list)

for parola, words in source_dict.items():
    for word in words:
        word = str(word).strip(' ')
        # add to the list if not already present
        # english_dict is a defaultdict(list) so we can use .append directly
        if parola not in english_dict[word]:
               english_dict[word].append(parola)
</code>```

Body:
I am trying to invert an italian-english dictionary using the code that follows.

Some terms have one translation, while others have multiple possibilities. If an entry has multiple translations I iterate through each word, adding it to english-italian dict (if not already present).

If there is a single translation it should not iterate, but as I have written the code, it does. Also only the last translation in the term with multiple translations is added to the dictionary. I cannot figure out how to rewrite the code to resolve what should be a really simple task

from collections import defaultdict

def invertdict():
    source_dict ={'paramezzale (s.m.)': ['hog', 'keelson', 'inner keel'], 'vento (s.m.)': 'wind'}

    english_dict = defaultdict(list)

    for parola, words in source_dict.items():
        if len(words) > 1: # more than one translation ?
            for word in words: # if true, iterate through each word
                word = str(word).strip(' ')
                print(word)
        else: # only one translation, don't iterate!!
            word = str(words).strip(' ')
            print(word)
        if word in english_dict.keys(): # check to see if the term already exists
            if english_dict[word] != parola: # check that the italian is not present
                #english_dict[word] = [english_dict[word], parola]
                english_dict[word].append(parola).strip('')
        else:
           english_dict[word] = parola.strip(' ')

    print(len(english_dict))

    for key,value in english_dict.items():
       print(key, value)

When this code is run, I get :

hog
keelson
inner keel
w
i
n
d
2
inner keel paramezzale (s.m.)
d vento (s.m.)

instead of

hog: paramezzale, keelson: paramezzale, inner keel: paramezzale, wind: vento

Body:
It would be easier to use lists everywhere in the dictionary, like:

source_dict = {'many translations': ['a', 'b'], 'one translation': ['c']}

Then you need 2 nested loops. Right now you're not always running the inner loop.

for italian_word, english_words in source_dict.items():
    for english_word in english_words:
        # print, add to english dict, etc.

If you can't change the source_dict format, you need to check the type explicitly. I would transform the single item in a list.

for italian_word, item in source_dict.items():
    if not isinstance(item, list):
        item = [item]

Full code:

source_dict ={'paramezzale (s.m.)': ['hog', 'keelson', 'inner keel'], 'vento (s.m.)': ['wind']}

english_dict = defaultdict(list)

for parola, words in source_dict.items():
    for word in words:
        word = str(word).strip(' ')
        # add to the list if not already present
        # english_dict is a defaultdict(list) so we can use .append directly
        if parola not in english_dict[word]:
               english_dict[word].append(parola)


问:
How to copy visible pivot item data to a cell in Excel VBA

I have country code in pivot report filter. I would like to get the visible piviot item data and place each values in each cell from A1. I used the code below. But All the cell showing only last value in filter. I need to move automatically from A1 .Help me

```<code>Sub Getpivotitem()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim rng As Range

Set rng = Range("A1:X1")
Set ws = Sheets("Sheet1")

Dim pi As PivotItem
For Each pi In ws.PivotTables("PivotTable1").PivotFields("Country Code").PivotItems
    If pi.Visible = True Then
        For Each cell In rng.Columns
        cell.Value = pi
        Next cell
     End If
Next pi

End Sub
</code>```

答:
Following code will copy and paste all visible values fro Country Code column to A1, B1, C1 ....... cells.

```<code>Sub CopyVisiblesValues()

    Sheet1.PivotTables("PivotTable1").PivotSelect "'Country Code'[All]", xlLabelOnly + xlFirstRow, True
        Selection.Copy
    Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

End Sub
</code>```

Here Country Code is column header of pivot table as well as column header of source data. You may need to adjust Country Code with your one.

Body:
I have country code in pivot report filter. I would like to get the visible piviot item data and place each values in each cell from A1. I used the code below. But All the cell showing only last value in filter. I need to move automatically from A1 .Help me

Sub Getpivotitem()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim rng As Range

Set rng = Range("A1:X1")
Set ws = Sheets("Sheet1")

Dim pi As PivotItem
For Each pi In ws.PivotTables("PivotTable1").PivotFields("Country Code").PivotItems
    If pi.Visible = True Then
        For Each cell In rng.Columns
        cell.Value = pi
        Next cell
     End If
Next pi

End Sub

Body:
Following code will copy and paste all visible values fro Country Code column to A1, B1, C1 ....... cells.

Sub CopyVisiblesValues()

    Sheet1.PivotTables("PivotTable1").PivotSelect "'Country Code'[All]", xlLabelOnly + xlFirstRow, True
        Selection.Copy
    Range("A1").PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:=False, Transpose:=True

End Sub

Here Country Code is column header of pivot table as well as column header of source data. You may need to adjust Country Code with your one.


问:
Service with Overlay - catch back button press
How can i do that?

Current solution

I launch a transparent activity, that catches the back press, forwards it to my service and closes itself afterwards. But this activity will be visible in the current running activities and therefore it's not a very beautiful solution.

Solutions seen

I've seen an app that does catch the back press in a service - without an activity that catches the back press. If I show the current running activities, there is nothing from this app.

Question

How can this be done? I've read so many threads that say, this is not possible, but I can see, that there are apps that achieve that somehow...

答:
You can catch the back button click event. For this you need to create container class of your OverlayView. For example: create class Overlay which will extends some ViewGroup class. Than, in the class, inflate your xml layout and add it to your Overlay.class ViewGroup. Than in Overlay.class override method dispatchKeyEvent(KeyEvent event). That's all!

class Overlay extends FrameLayout{

  public Overlay(@NonNull Context context) {
        super(new ContextThemeWrapper(context, R.style.AppTheme));

        initView();
    }

    private void initView() {
      //inflate your xml here
      //than do: this.addView(<inflated view>);
      //And in the end add your Overlay to WindowManager (in Service class of course).
    }

     @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            //do staff here
            // and return True!
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}```


问:
chanding scene in javafx scene bulider
I am trying to make a  loading page in javafx scenebuilder  but I get an  error on  the line rootPane.getChildren().setAll(pane),it underlines  etChildren() and says it doesnt find the symbol,dont understant why that is.</p>

```<code>package javafxapplication14;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;

public class FXMLDocumentController implements Initializable {

    private Label label;

    private Object theStage;
    private Object rootPane;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }

    private void loadsecond(ActionEvent event) throws IOException {
        AnchorPane pane=FXMLLoader.load(getClass().getResource("Second.fxml"));
        rootPane.getChildren().setAll(pane);
    }
}
</code>```

答: The class Object can't handle .getChildren().

Title: chanding scene in javafx scene bulider

Body:
I am trying to make a  loading page in javafx scenebuilder  but I get an  error on  the line rootPane.getChildren().setAll(pane),it underlines  etChildren() and says it doesnt find the symbol,dont understant why that is.

package javafxapplication14;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;

public class FXMLDocumentController implements Initializable {

    private Label label;

    private Object theStage;
    private Object rootPane;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

    }

    private void loadsecond(ActionEvent event) throws IOException {
        AnchorPane pane=FXMLLoader.load(getClass().getResource("Second.fxml"));
        rootPane.getChildren().setAll(pane);
    }
}


问:
How to adjust QTextEdit to fit it's contents
I'm developing a Qt Application and I'm trying to find a way to use QTextEdit as a label with long text without the scroll bar. In my ui I have a QScrollArea and inside of it I want to place a couple off QTextEdit widgets and I only want use scrolling inside QScrollArea. Problem is that no matter how I try to resize the QTextEdit it seems it has a maximum height and cuts of text, even if I set the size manually and QTextEdit::size returns the correct value.

I did the same thing with QLabel and it works fine, but in this case I need some methods that are only provided in QTextEdit.

I found this post:
Resizing QT's QTextEdit to Match Text Height: maximumViewportSize()

And the answer given was the following:

I have solved this issue. There were 2 things that I had to do to get
  it to work:

Walk up the widget hierarchy and make sure all the size policies made
  sense to ensure that if any child widget wanted to be big/small, then
  the parent widget would want to be the same thing.

This is the main
  source of the fix. It turns out that since the QTextEdit is inside a
  QFrame that is the main widget in a QScrollArea, the QScrollArea has a
  constraint that it will not resize the internal widget unless the
  "widgetResizable" property is true. The documentation for that is
  here: http://doc.qt.io/qt-4.8/qscrollarea.html#widgetResizable-prop.
  The documentation was not clear to me until I played around with this
  setting and got it to work. From the docs, it seems that this property
  only deals with times where the main scroll area wants to resize a
  widget (i.e. from parent to child). It actually means that if the main
  widget in the scroll area wants to ever resize (i.e. child to parent),
  then this setting has to be set to true. So, the moral of the story is
  that the QTextEdit code was correct in overriding sizeHint, but the
  QScrollArea was ignoring the value returned from the main frame's
  sizeHint.

The problem is that I have no idea how to access the QTextEdit's QScrollArea to enable widgetResizable. Can anyone explain how I can achieve this or suggest a different way of resizing QTextEdit to perfectly fit it's content?

答:
Try this one :</p>

```<code>QTextEdit textEdit;
textEdit.setHtml("<p>test test test test test test</p><p>|||||||||</p>");
textEdit.show();
textEdit.setFixedWidth(textEdit.document()->idealWidth() +
                       textEdit.contentsMargins().left() +
                       textEdit.contentsMargins().right());
</code>```

Body:
Try this one :

QTextEdit textEdit;
textEdit.setHtml("<p>test test test test test test</p><p>|||||||||</p>");
textEdit.show();
textEdit.setFixedWidth(textEdit.document()->idealWidth() +
                       textEdit.contentsMargins().left() +
                       textEdit.contentsMargins().right());


问:
repeating previous regex
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

```<code>x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))
</code>```

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

```<code>x = re.search("(\d+\s+){5}", line)
</code>```

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?

答: Repetition of capturing groups does not work, and won't any time soon (in the sense of having the ability to individually actually access the matched parts) – you will just have to write the regex the long way or use a string method such as .split(), avoiding regex altogether.

Title: repeating previous regex

Body:
I have a line (and a arbitrary number of them)
0    1   1   75     55

I can get it by doing

x = re.search("\d+\s+\d+\s+(\d+)\s+(\d+)\s+(\d+)", line)
    if x != None:
        print(x.group(1))
        print(x.group(2))
        print(x.group(3))

But there must be a neater way to write this. I was looking at the docs for something to repeat the previous expression and found (exp){m times}.

So I try

x = re.search("(\d+\s+){5}", line)

and then expect x.group(1) to be 0, 2 to be 1, 3 to be 1 and so on
but x.group(1) ouputs 55 (the last number). Im sort of confused. Thanks.

Also on a side note. Do you guys have any recommendations for online tutorials (or free to download books) on regex?


问:
Best way to use html5 data attributes with rails content_tag helper?
The issue, of course, is that ruby symbols don't like hyphens. So something like this obviously won't work:

```<code>content_tag(:div, "Some Text", :id => "foo", :data-data_attr => some_variable)
</code>```

One option is to use a string rather than a symbol:

```<code>content_tag(:div, "Some Text", :id => "foo", 'data-data_attr' => some_variable)
</code>```

Or I could just interpolate:

```<code>"<div id='foo' data-data_attr='#{some_variable}'>Some Text</div>".html_safe
</code>```

I sorta prefer the later but both seem a little gross. Anyone know of a better way?

答:
Building on previous answers, here's the canonical way to do it now:

content_tag(:div, "Some Text", id: "foo", data: { attr: some_variable })
content_tag(:div, "Some Text", id: "foo", data: { "other-attr" => some_variable })
```

<p>Which generates:</p>

```
Some Text

Some Text

```

Body:
The issue, of course, is that ruby symbols don't like hyphens. So something like this obviously won't work:

content_tag(:div, "Some Text", :id => "foo", :data-data_attr => some_variable)

One option is to use a string rather than a symbol:

content_tag(:div, "Some Text", :id => "foo", 'data-data_attr' => some_variable)

Or I could just interpolate:

"
Some Text
".html_safe

I sorta prefer the later but both seem a little gross. Anyone know of a better way?

Body:
Building on previous answers, here's the canonical way to do it now:

content_tag(:div, "Some Text", id: "foo", data: { attr: some_variable })
content_tag(:div, "Some Text", id: "foo", data: { "other-attr" => some_variable })

Which generates:

<div id="foo" data-attr="some variable">Some Text</div>
<div id="foo" data-other-attr="some variable">Some Text</div>


问:
Occlusion estimation in pointcloud using pcl voxelgridOcclusionEstimation
I need to find out which points of a pointcloud are visible from a RGBD sensor located at origin(0,0,0).  I tried to  use the voxelgridOcclusionEstimation class of pcl to determine the visible region in the cloud as seen by the sensor. It uses ray tracing technique.

As an experiment,I tried to get the visible region in a sphere whose center satisfies one of the following:

center is along x

center is along y

center is along z

center is along xz plane

center is along y z plane

center is along x y plane.

The sensor is at the origin with zero rotation in all cases.

voxelgridOcclusionEstimation yeilds wierd results. The green region denotes visible region, while the red represents the occluded region.

My code is:

```<code>int main(int argc, char * argv[])
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in(new pcl::PointCloud<pcl::PointXYZ>);

pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_occluded(new pcl::PointCloud<pcl::PointXYZ>);

pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_visible(new pcl::PointCloud<pcl::PointXYZ>);

pcl::io::loadPCDFile(argv[1],*cloud_in);

Eigen::Quaternionf quat(1,0,0,0);
cloud_in->sensor_origin_  = Eigen::Vector4f(0,0,0,0);

cloud_in->sensor_orientation_= quat;
pcl::VoxelGridOcclusionEstimation<pcl::PointXYZ> voxelFilter;
voxelFilter.setInputCloud (cloud_in);

float leaf_size=atof(argv[2]);
voxelFilter.setLeafSize (leaf_size, leaf_size, leaf_size);
voxelFilter.initializeVoxelGrid();

std::vector<Eigen::Vector3i,
Eigen::aligned_allocator<Eigen::Vector3i> > occluded_voxels;

for (size_t i=0;i<cloud_in->size();i++)
{

    PointT pt=cloud_in->points[i];

    Eigen::Vector3i grid_cordinates=voxelFilter.getGridCoordinates (pt.x, pt.y, pt.z);

    int grid_state;

    int ret=voxelFilter.occlusionEstimation( grid_state, grid_cordinates );

    if (grid_state==1)
    {
        cloud_occluded->push_back(cloud_in->points[i]);
    }
    else
    {
    cloud_visible->push_back(cloud_in->points[i]);
    }

}
pcl::io::savePCDFile(argv[3],*cloud_occluded);
pcl::io::savePCDFile(argv[4],*cloud_visible);

return 0;
}
</code>```

答: The voxelgridOcclusionEstimation class works but the grid width is very important. If we make it very small then there will be unoccupied voxels in the Foreground, which will let the casted rays to pass to pass to Background. If they are set very big, then the surface will not be correctly represented. This is more difficult if the model does not have uniform point density as in the case of data captured by RGBD sensors</p>

Body:
I need to find out which points of a pointcloud are visible from a RGBD sensor located at origin(0,0,0).  I tried to  use the voxelgridOcclusionEstimation class of pcl to determine the visible region in the cloud as seen by the sensor. It uses ray tracing technique.

As an experiment,I tried to get the visible region in a sphere whose center satisfies one of the following:

center is along x

center is along y

center is along z

center is along xz plane

center is along y z plane

center is along x y plane.

The sensor is at the origin with zero rotation in all cases.

voxelgridOcclusionEstimation yeilds wierd results. The green region denotes visible region, while the red represents the occluded region.

My code is:

int main(int argc, char * argv[])
{
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in(new pcl::PointCloud<pcl::PointXYZ>);

pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_occluded(new pcl::PointCloud<pcl::PointXYZ>);

pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_visible(new pcl::PointCloud<pcl::PointXYZ>);

pcl::io::loadPCDFile(argv[1],*cloud_in);

Eigen::Quaternionf quat(1,0,0,0);
cloud_in->sensor_origin_  = Eigen::Vector4f(0,0,0,0);

cloud_in->sensor_orientation_= quat;
pcl::VoxelGridOcclusionEstimation<pcl::PointXYZ> voxelFilter;
voxelFilter.setInputCloud (cloud_in);

float leaf_size=atof(argv[2]);
voxelFilter.setLeafSize (leaf_size, leaf_size, leaf_size);
voxelFilter.initializeVoxelGrid();

std::vector<Eigen::Vector3i,
Eigen::aligned_allocator<Eigen::Vector3i> > occluded_voxels;

for (size_t i=0;i<cloud_in->size();i++)
{

    PointT pt=cloud_in->points[i];

    Eigen::Vector3i grid_cordinates=voxelFilter.getGridCoordinates (pt.x, pt.y, pt.z);

    int grid_state;

    int ret=voxelFilter.occlusionEstimation( grid_state, grid_cordinates );

    if (grid_state==1)
    {
        cloud_occluded->push_back(cloud_in->points[i]);
    }
    else
    {
    cloud_visible->push_back(cloud_in->points[i]);
    }

}
pcl::io::savePCDFile(argv[3],*cloud_occluded);
pcl::io::savePCDFile(argv[4],*cloud_visible);

return 0;
}


问:
ImportError: cannot import name NUMPY_MKL
I am trying to run the following simple code

```<code>import scipy
scipy.test()
</code>```

But I am getting the following error

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 586, in runfile
    execfile(filename, namespace)
  File "C:/Users/Mustafa/Documents/My Python Code/SpectralGraphAnalysis/main.py", line 8, in <module>
    import scipy
  File "C:\Python27\lib\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name NUMPY_MKL
</code>```

I am using python 2.7 under windows 10.

I have installed scipy but that does not seem to solve the problem

Any help is appreciated.

答:
I recently got the same error when trying to load scipy in jupyter (python3.x, win10), although just having upgraded to numpy-1.13.3+mkl through pip.
The solution was to simply upgrade the scipy package (from v0.19 to v1.0.0).</p>

Body:
I am trying to run the following simple code

import scipy
scipy.test()

But I am getting the following error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 586, in runfile
    execfile(filename, namespace)
  File "C:/Users/Mustafa/Documents/My Python Code/SpectralGraphAnalysis/main.py", line 8, in <module>
    import scipy
  File "C:\Python27\lib\site-packages\scipy\__init__.py", line 61, in <module>
    from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl
ImportError: cannot import name NUMPY_MKL

I am using python 2.7 under windows 10.

I have installed scipy but that does not seem to solve the problem

Any help is appreciated.


问:
Dictionary of generic lists of controls
I'm working on a product calculator program. Inside the app, the rep sale person can search for a client ID and the app shows him what services he can offer to client and his provision for sale. The form is generated acording to data i download from database.
Right now I'm trying to store generated controls in lists. Every time a search is made, I dispose of controls and clear the lists. The thing i cant seem to get working is to store all the lists in single dictionary.

Something like this...

```<code>public class ListOfControls<T> : IListOfControls<T> where T : Control
{
    private readonly List<T> _controlsList;

    public ListOfControls()
    {
        _controlsList = new List<T>();
    }

    public void AddControll(T control)
    {
        _controlsList.Add(control);
    }

    public T this[int number]
    {
        get
        {
            return _controlsList[number];
        }
    }

    public void ClearControls()
    {
        _controlsList.Clear();
    }

    public T Last()
    {
        return _controlsList.Last();
    }
}

class DictionaryOfControlsLists
{
    //will be private - public only for test
    public readonly Dictionary<string, IListOfControls<Control>> _dictionaryOfLists;

    public DictionaryOfControlsLists()
    {
            _dictionaryOfLists = new Dictionary<string, IListOfControls<Control>>();
    }

    //Other code....

}
</code>```

Now trying to implement...

```<code>DictionaryOfControlsLists _testDict = new DictionaryOfControlsLists();
_testDict._dictionaryOfLists.Add("test", new ListOfControls<Label>());
</code>```

Sadly this wont work...Any ideas? THANKS

答:
What you need is something like this:

```<code>class DictionaryOfControlsLists
{
    private readonly Dictionary<Type, IListOfControls<Control>> _dictionaryOfLists = new Dictionary<Type, IListOfControls<Control>>();

    public void Add<T>(T control) where T : Control
    {
        if (!_dictionaryOfLists.ContainsKey(typeof(T)))
        {
            _dictionaryOfLists[typeof(T)] = new ListOfControls<Control>();
        }
        _dictionaryOfLists[typeof(T)].AddControl(control);
    }

    public T Get<T>(int number) where T : Control
    {
        if (!_dictionaryOfLists.ContainsKey(typeof(T)))
        {
            _dictionaryOfLists[typeof(T)] = new ListOfControls<Control>();
        }
        return _dictionaryOfLists[typeof(T)][number] as T;
    }
}
</code>```

Then you can do this:

```<code>DictionaryOfControlsLists _testDict = new DictionaryOfControlsLists();
_testDict.Add<Label>(new Label());
Label label = _testDict.Get<Label>(0);
</code>```

If you need to extend this to have a string key then you need to implement a double dictionary within DictionaryOfControlsLists to handle it - something like a Dictionary<Type, Dictionary<string, IListOfControls<Control>>>.

Title: Dictionary of generic lists of controls

Body:
I'm working on a product calculator program. Inside the app, the rep sale person can search for a client ID and the app shows him what services he can offer to client and his provision for sale. The form is generated acording to data i download from database.
Right now I'm trying to store generated controls in lists. Every time a search is made, I dispose of controls and clear the lists. The thing i cant seem to get working is to store all the lists in single dictionary.

Something like this...

public class ListOfControls<T> : IListOfControls<T> where T : Control
{
    private readonly List<T> _controlsList;

    public ListOfControls()
    {
        _controlsList = new List<T>();
    }

    public void AddControll(T control)
    {
        _controlsList.Add(control);
    }

    public T this[int number]
    {
        get
        {
            return _controlsList[number];
        }
    }

    public void ClearControls()
    {
        _controlsList.Clear();
    }

    public T Last()
    {
        return _controlsList.Last();
    }
}

class DictionaryOfControlsLists
{
    //will be private - public only for test
    public readonly Dictionary<string, IListOfControls<Control>> _dictionaryOfLists;

    public DictionaryOfControlsLists()
    {
            _dictionaryOfLists = new Dictionary<string, IListOfControls<Control>>();
    }

    //Other code....

}

Now trying to implement...

DictionaryOfControlsLists _testDict = new DictionaryOfControlsLists();
_testDict._dictionaryOfLists.Add("test", new ListOfControls());

Sadly this wont work...Any ideas? THANKS

Body:
What you need is something like this:

class DictionaryOfControlsLists
{
    private readonly Dictionary<Type, IListOfControls<Control>> _dictionaryOfLists = new Dictionary<Type, IListOfControls<Control>>();

    public void Add<T>(T control) where T : Control
    {
        if (!_dictionaryOfLists.ContainsKey(typeof(T)))
        {
            _dictionaryOfLists[typeof(T)] = new ListOfControls<Control>();
        }
        _dictionaryOfLists[typeof(T)].AddControl(control);
    }

    public T Get<T>(int number) where T : Control
    {
        if (!_dictionaryOfLists.ContainsKey(typeof(T)))
        {
            _dictionaryOfLists[typeof(T)] = new ListOfControls<Control>();
        }
        return _dictionaryOfLists[typeof(T)][number] as T;
    }
}

Then you can do this:

DictionaryOfControlsLists _testDict = new DictionaryOfControlsLists();
_testDict.Add<Label>(new Label());
Label label = _testDict.Get<Label>(0);

If you need to extend this to have a string key then you need to implement a double dictionary within DictionaryOfControlsLists to handle it - something like a Dictionary<Type, Dictionary<string, IListOfControls<Control>>>.


问:
pull access denied for oracle/serverjre
I have been trying to build a docker image for oracle/weblogic 12.2.1.

I followed all the instructions carefully as given in the official repo.

https://github.com/oracle/docker-images/tree/master/OracleWebLogic/dockerfiles/12.2.1.1

but when i run:

```<code>docker build -t oracle/weblogic:12.2.1.1-developer .
</code>```

it gives me a permission denied error.

```<code>sudo docker build -t oracle/weblogic:12.2.1.1-developer .

Sending build context to Docker daemon  54.79MB

Step 1/13 : FROM oracle/serverjre:8

pull access denied for oracle/serverjre, repository does not exist or may require 'docker login'
</code>```

can anyone please help me??

Thankyou

答:
If you're using a custom image with Dockerfile, Delete the oracle/ it's not your local repository.
Try docker build -t weblogic:12.2.1.1-developer .
Or just make a docker run [image]

Title: pull access denied for oracle/serverjre

Body:
I have been trying to build a docker image for oracle/weblogic 12.2.1.

I followed all the instructions carefully as given in the official repo.

https://github.com/oracle/docker-images/tree/master/OracleWebLogic/dockerfiles/12.2.1.1

but when i run:

docker build -t oracle/weblogic:12.2.1.1-developer .

it gives me a permission denied error.

sudo docker build -t oracle/weblogic:12.2.1.1-developer .

Sending build context to Docker daemon  54.79MB

Step 1/13 : FROM oracle/serverjre:8

pull access denied for oracle/serverjre, repository does not exist or may require 'docker login'

can anyone please help me??

Thankyou


问:
JavaScript grouping array with age group and find largest date
I am trying to implement something like for each age group, I wanted to find the largest date, and then compare with today's date, get the date differences and store into another separate array. Here is some sample input:

```<code>//removed
</code>```

I sorted the array into ascending order:

```<code>frequentarr.sort(function(a, b) {
    da = new Date(a.date);
    db = new Date(b.date);
    if (da == db) {
        return 0;
    }
    return da > db ? 1 : -1;
});
console.log(frequentarr);
</code>```

My age group array:

```<code>var ageGroup = ['>=80', '70-79', '60-69', '50-59', '40-49', '30-39', '20-29', '10-19', '0-9'];
</code>```

I not sure how to actually group the account according to age group, and then for each age group, find the largest date. After that, compare with today's date to find the date differences.

Any ideas? Thanks!

Body:
I am trying to implement something like for each age group, I wanted to find the largest date, and then compare with today's date, get the date differences and store into another separate array. Here is some sample input:

//removed

I sorted the array into ascending order:

frequentarr.sort(function(a, b) {
    da = new Date(a.date);
    db = new Date(b.date);
    if (da == db) {
        return 0;
    }
    return da > db ? 1 : -1;
});
console.log(frequentarr);

My age group array:

var ageGroup = ['>=80', '70-79', '60-69', '50-59', '40-49', '30-39', '20-29', '10-19', '0-9'];

I not sure how to actually group the account according to age group, and then for each age group, find the largest date. After that, compare with today's date to find the date differences.

Any ideas? Thanks!

Body:
You could take the age and divide by 10 for the group and check if the date is greater than stored. If not, take the actual date.

var array = [{ age: 67, date: "2017/01/09" }, { age: 11, date: "2017/01/14" }, { age: 11, date: "2017/01/14" }, { age: 62, date: "2017/01/15" }, { age: 40, date: "2017/01/21" }, { age: 21, date: "2017/02/08" }, { age: 12, date: "2017/02/18" }, { age: 56, date: "2017/02/29" }, { age: 24, date: "2017/03/03" }, { age: 22, date: "2017/03/17" }, { age: 66, date: "2017/03/25" }, { age: 62, date: "2017/04/03" }, { age: 59, date: "2017/05/18" }, { age: 39, date: "2017/06/14" }, { age: 19, date: "2017/07/03" }, { age: 31, date: "2017/07/10" }, { age: 24, date: "2017/07/14" }, { age: 36, date: "2017/07/24" }, { age: 36, date: "2017/07/24" }, { age: 73, date: "2017/08/17" }, { age: 63, date: "2017/10/01" }, { age: 16, date: "2017/10/14" }, { age: 70, date: "2017/10/18" }, { age: 29, date: "2017/12/03" }, { age: 15, date: "2017/12/07" }, { age: 47, date: "2017/12/19" }, { age: 11, date: "2017/12/25" }, { age: 26, date: "2017/12/28" }],
    groups = [];

array.forEach(function (o) {
    var group = Math.floor(o.age / 10);

    if (groups[group] >= o.date) {
        return;
    }
    groups[group] = o.date;
});

console.log(groups);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Where to initialize jobs in rails?
I've created some ActiveJobs that I would like to start right when the application server is started. I've been having difficulty finding a place to initialize these jobs. Is there a location similar to a main method in rails?</p>

答:
You can put it inside your application.rb config file like this

```<code>config.after_initialize do
# Your code
end
</code>```

config.after_initialize takes a block which will be run after Rails has finished initializing the application.

Title: Where to initialize jobs in rails?

Body:
You can put it inside your application.rb config file like this

config.after_initialize do
# Your code
end

config.after_initialize takes a block which will be run after Rails has finished initializing the application.