问:
Zend Framework 3 translator from DB
I've recently started working with ZF3 and I'm working on internationalization of the project.

I've managed to get it work but I'd like to make the translator get the translates from the database instead of reading them from .mo files. This way the user would be able to edit them in admin part of the application.

I have installed the Zend\Mvc\I18n module, registered it as a view_helper

```<code>// module's module.config.php:
'view_helpers' => [
    'invokables' => [
        'translate' => \Zend\I18n\View\Helper\Translate::class
    ]
]
</code>```

and instead of

```<code>// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'translation_file_patterns' => [
        [
            'type'     => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern'  => '%s.mo',
        ],
    ],
]
</code>```

I have

```<code>// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'remote_translation' => [
        [
            'type' => Service\Database::class
        ]
    ]
]
</code>```

and the Database service implements the RemoteLoaderInterface as required in the documentation, right now it has a hard-coded array but will later on replaced by the actual query.

```<code>//Database.php
namespace Core\Service;

use Zend\I18n\Translator\Loader\RemoteLoaderInterface;

class Database implements RemoteLoaderInterface {

    private $entityManager;

    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function load($locale, $textDomain)
    {
        $array = [];
        $array['and'] = 'i';
        return $array;
    }
}
</code>```

In my layout printing

```<code>// layout.phtml
$this->translate("and") // prints "i"
</code>```

results in a "i", which is just what I wanted.

Now, my problem is how do I pass the doctrine entity manager to the Database service? I know I have to use a factory in these situations and I have one ready

```<code>//DatabaseFactory.php
namespace Core\Service\Factory;

use Core\Service\Database;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class DatabaseFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        // Instantiate the service and inject dependencies
        return new Database($entityManager);
    }

}
</code>```

but I simply can't pass it in the module configuration because it requires the class to implement the RemoteLoaderInterface.

```<code>// module's module.config.php:
'remote_translation' => [
    [
        'type' => Service\Factory\DatabaseFactory::class // does not work
    ]
]
</code>```

Is there a workaround or anything I'm missing? Any help would be appreciated. Thanks in advice!

答:
It looks like you forgot to register the class and its factory with the service manager:</p>

```<code>// module's module.config.php
'translator' => [
    'loaderpluginmanager' => [
        'factories' => [
            Core\Service\Database::class => Service\Factory\DatabaseFactory::class,
        ],
    ],
    'locale' => 'en_US',
    'remote_translation' => [
        [
            'type' => Core\Service\Database::class
        ]
    ]
]
</code>```

Title: Zend Framework 3 translator from DB

Body:
I've recently started working with ZF3 and I'm working on internationalization of the project.

I've managed to get it work but I'd like to make the translator get the translates from the database instead of reading them from .mo files. This way the user would be able to edit them in admin part of the application.

I have installed the Zend\Mvc\I18n module, registered it as a view_helper

// module's module.config.php:
'view_helpers' => [
    'invokables' => [
        'translate' => \Zend\I18n\View\Helper\Translate::class
    ]
]

and instead of

// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'translation_file_patterns' => [
        [
            'type'     => 'gettext',
            'base_dir' => __DIR__ . '/../language',
            'pattern'  => '%s.mo',
        ],
    ],
]

I have

// module's module.config.php:
'translator' => [
    'locale' => 'en_US',
    'remote_translation' => [
        [
            'type' => Service\Database::class
        ]
    ]
]

and the Database service implements the RemoteLoaderInterface as required in the documentation, right now it has a hard-coded array but will later on replaced by the actual query.

//Database.php
namespace Core\Service;

use Zend\I18n\Translator\Loader\RemoteLoaderInterface;

class Database implements RemoteLoaderInterface {

    private $entityManager;

    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function load($locale, $textDomain)
    {
        $array = [];
        $array['and'] = 'i';
        return $array;
    }
}

In my layout printing

// layout.phtml
$this->translate("and") // prints "i"

results in a "i", which is just what I wanted.

Now, my problem is how do I pass the doctrine entity manager to the Database service? I know I have to use a factory in these situations and I have one ready

//DatabaseFactory.php
namespace Core\Service\Factory;

use Core\Service\Database;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;

class DatabaseFactory implements FactoryInterface
{
    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');

        // Instantiate the service and inject dependencies
        return new Database($entityManager);
    }

}

but I simply can't pass it in the module configuration because it requires the class to implement the RemoteLoaderInterface.

// module's module.config.php:
'remote_translation' => [
    [
        'type' => Service\Factory\DatabaseFactory::class // does not work
    ]
]

Is there a workaround or anything I'm missing? Any help would be appreciated. Thanks in advice!

Body:
It looks like you forgot to register the class and its factory with the service manager:

// module's module.config.php
'translator' => [
    'loaderpluginmanager' => [
        'factories' => [
            Core\Service\Database::class => Service\Factory\DatabaseFactory::class,
        ],
    ],
    'locale' => 'en_US',
    'remote_translation' => [
        [
            'type' => Core\Service\Database::class
        ]
    ]
]


来源: stackexchange

问:
XSLT Formatting to remove empty columns (And the headers)
I have a database field I am pulling xml out of. This field contains the content from multiple XML feeds of which I need two. I am displaying the XML on a page and using XSLT to format it.

My issue is that there could be up to 40 elements per message in the DB, of that I am looking for about 30. However, not all messages will have all 30. I need help figuring out how to remove a column if there is no data to display.

If I can use XSLT then great, if it is JavaScript(Jquery) then that is fine too. There will never be more then one row and one header at a time.

Here is a sample of the XML

```<code><MessageToUser>
  <Name>Bob</Name>
  <MessageType>Text Message</MessageType>
  <MessageID>121223</MessageID>
  <ResponseTo />
  <Message>Call Me Please </Message>
  <OfficePhone>555-555-1212</OfficePhone>
  <CellPhone>555-555-5555</CellPhone>
</MessageToUser>
</code>```

And here is the XSL I am using

```<code><xsl:template match="/">
<html>
<head>
  <style type="text/css">
    .Header{min-width: 100px;background-color:#9acddd;}
  </style>
</head>
<body>
  <table border="1">
    <tr>
        <th class="Header">Name</th>
        <th class="Header">Message</th>
        <th class="Header">Cell Phone</th>
        <th class="Header">Office Phone</th>
        <th class="Header">Message Type</th>
        <th class="Header">Message Time</th>
        <th class="Header">Message ID</th>
      </tr>
      <xsl:for-each select="MessageFromUser">
        <tr>
          <td><xsl:value-of select="Name" /></td>
          <td><xsl:value-of select="Message" /></td>
          <td><xsl:value-of select="CellPhone" /></td>
          <td><xsl:value-of select="OfficePhone" /></td>
          <td><xsl:value-of select="MessageType" /></td>
          <td><xsl:value-of select="MessageTime" /></td>
          <td><xsl:value-of select="MessageID" /></td>
        </tr>
      </xsl:for-each>
      <xsl:for-each select="MessageToUser">
        <tr>
          <td><xsl:value-of select="Name" /></td>
          <td><xsl:value-of select="Message" /></td>
          <td><xsl:value-of select="CellPhone" /></td>
          <td><xsl:value-of select="OfficePhone" /></td>
          <td><xsl:value-of select="MessageType" /></td>
          <td><xsl:value-of select="MessageTime" /></td>
          <td><xsl:value-of select="MessageID" /></td>
        </tr>
      </xsl:for-each>
    </table>
 </body>
</code>```

Using this XML MessageTime is blank and that column should be removed.

Thanks in advance for any help.

答:
Can you do this?</p>

```<code><xsl:if test="MessageTime">
  <td><xsl:value-of select="MessageTime" /></td>
</xsl:if>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a database field I am pulling xml out of. This field contains the content from multiple XML feeds of which I need two. I am displaying the XML on a page and using XSLT to format it.

My issue is that there could be up to 40 elements per message in the DB, of that I am looking for about 30. However, not all messages will have all 30. I need help figuring out how to remove a column if there is no data to display.

If I can use XSLT then great, if it is JavaScript(Jquery) then that is fine too. There will never be more then one row and one header at a time.

Here is a sample of the XML

<MessageToUser>
  <Name>Bob</Name>
  <MessageType>Text Message</MessageType>
  <MessageID>121223</MessageID>
  <ResponseTo />
  <Message>Call Me Please </Message>
  <OfficePhone>555-555-1212</OfficePhone>
  <CellPhone>555-555-5555</CellPhone>
</MessageToUser>

And here is the XSL I am using

<xsl:template match="/">

        Name
        Message
        Cell Phone
        Office Phone
        Message Type
        Message Time
        Message ID

      <xsl:for-each select="MessageFromUser">

          <xsl:value-of select="Name" />
          <xsl:value-of select="Message" />
          <xsl:value-of select="CellPhone" />
          <xsl:value-of select="OfficePhone" />
          <xsl:value-of select="MessageType" />
          <xsl:value-of select="MessageTime" />
          <xsl:value-of select="MessageID" />

      </xsl:for-each>
      <xsl:for-each select="MessageToUser">

          <xsl:value-of select="Name" />
          <xsl:value-of select="Message" />
          <xsl:value-of select="CellPhone" />
          <xsl:value-of select="OfficePhone" />
          <xsl:value-of select="MessageType" />
          <xsl:value-of select="MessageTime" />
          <xsl:value-of select="MessageID" />

      </xsl:for-each>

Using this XML MessageTime is blank and that column should be removed.

Thanks in advance for any help.

Body:
Can you do this?

<xsl:if test="MessageTime">
  <td><xsl:value-of select="MessageTime" /></td>
</xsl:if>


问:
Inheritance work with one class, but not with another
I created two classes: Player, Bullet. Both inherit from same SFML classes sf::Drawable, and sf::Transformable.

First class:

```<code>class Player :
    public sf::Drawable, sf::Transformable
{
public:
    Player();
    ~Player();

    enum Direction {UP, DOWN, LEFT, RIGHT};

    void update();
    void move(Direction dir);
    float getRotation();
    sf::Vector2f getPosition();
    void shoot();
    bool moveStatus;

private:
    sf::Sprite sprite;
    sf::Texture texture;

    float speed;
    size_t frame;

    sf::Clock animClock;
    sf::Clock shootTime;

    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};
</code>```

Second class:

```<code>class Bullet :
    public sf::Drawable, sf::Transformable
{
public:
    Bullet(float rot, sf::Vector2f pos);
    ~Bullet();

    void update();
    float getRotation();
    sf::Vector2f getPosition();
    void move(float x, float y);

private:
    sf::Sprite sprite;
    sf::Texture texture;

    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};
</code>```

I have a problem with virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;. In Player class it's working, but in Bullet class isn't.

The linker returns 2 errors:

I tried to add ampersand to definition before states but then Bullet has become an abstract class.

答:
Your problem is that you are missing the actual implementation of the draw method in your Bullet class.

Without code it's hard to say, but you are either missing it completely, or maybe have a typo in the signature.

ContentLicense: CC BY-SA 3.0

Body:
I created two classes: Player, Bullet. Both inherit from same SFML classes sf::Drawable, and sf::Transformable.

First class:

class Player :
    public sf::Drawable, sf::Transformable
{
public:
    Player();
    ~Player();

    enum Direction {UP, DOWN, LEFT, RIGHT};

    void update();
    void move(Direction dir);
    float getRotation();
    sf::Vector2f getPosition();
    void shoot();
    bool moveStatus;

private:
    sf::Sprite sprite;
    sf::Texture texture;

    float speed;
    size_t frame;

    sf::Clock animClock;
    sf::Clock shootTime;

    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};

Second class:

class Bullet :
    public sf::Drawable, sf::Transformable
{
public:
    Bullet(float rot, sf::Vector2f pos);
    ~Bullet();

    void update();
    float getRotation();
    sf::Vector2f getPosition();
    void move(float x, float y);

private:
    sf::Sprite sprite;
    sf::Texture texture;

    virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;
};

I have a problem with virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const;. In Player class it's working, but in Bullet class isn't.

The linker returns 2 errors:

I tried to add ampersand to definition before states but then Bullet has become an abstract class.


问:
JNLP files won't launch from IE11 on Windows 10
Since May 9, after a windows 10 update, on IE11 11.0.40, JNLP files wont launch from IE, but in a computer with IE version 11.0.34 it work perfectly.

Any ideas?

Thanks in advance

答:
I had the same problem after installing Windows 10 creators update.

Reason/Solution: I had both the 32-bit and the 64-bit JRE installed on my computer (Java 8 Update 131). This was not a problem before the creators update. Java applets and Java webstart applications have worked fine in Internet Explorer 11. However, Internet Explorer 11 (11.332.15063.0) seems to have problems with the 64-bit JRE. Java Webstart applications can only started if only a 32-bit JRE is installed.


问:
unable to get xpath of anchor element under span element
I have already learned to use xpath but i am kind of stuck here - http://phptravels.com/requirements/. Can anyone please tell me how to find xpath of "Demo" hyperlink on this website. I simply used //a[text()= 'Demo                 ']. keep whitespaces in mind.

答:
Here with equals, but better to use contains (or starts-with), as described @Guy

```<code>driver.findElement(By.xpath("//a[text()='Demo\n                ']")).getText();
</code>```

to get real text value of element - you can use this:

```<code>driver.findElement(webElement).getAttribute("text")
</code>```

Body:
Here with equals, but better to use contains (or starts-with), as described @Guy

driver.findElement(By.xpath("//a[text()='Demo\n                ']")).getText();

to get real text value of element - you can use this:

driver.findElement(webElement).getAttribute("text")


问:
Counting the number of elements with the values of x in a vector
I have a vector of numbers:

```<code>numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)
</code>```

How can I have R count the number of times a value x appears in the vector?

Body:
I have a vector of numbers:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
         453,435,324,34,456,56,567,65,34,435)

How can I have R count the number of times a value x appears in the vector?

Body:
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435 453,435,324,34,456,56,567,65,34,435)

> length(grep(435, numbers))
[1] 3

> length(which(435 == numbers))
[1] 3

> require(plyr)
> df = count(numbers)
> df[df$x == 435, ]
     x freq
11 435    3

> sum(435 == numbers)
[1] 3

> sum(grepl(435, numbers))
[1] 3

> sum(435 == numbers)
[1] 3

> tabulate(numbers)[435]
[1] 3

> table(numbers)['435']
435
  3

> length(subset(numbers, numbers=='435'))
[1] 3


问:
Missing Maven dependencies in Eclipse project
We have a project set up with maven for resolving dependancies. It usually works fine, but now I am trying to compile and run it on a new PC and I have problem with missing dependencies in Eclipse.

What is funny is that if I run "mvn package" in console or in eclipse, it works fine and even produces war containing all necessary jars. Only Eclipse complains with "The project was not built since its build path is incomplete. Cannot find the class file for org.slf4j.Logger...". If I compare the project with some other computer (where project works fine), I notice that there are quite a few libraries missing under "Maven dependencies" listing in Eclipse. Eventhough they are in the packaged war and they can be found also under repository folder.

So, the jar-s are there just Eclipse won't list them all under "Maven dependencies". What can I do?

Computer is running on Windows 7 with 64bit java & eclipse.

答:
For the following steps worked in my case:

1 On eclipse, right click on the desired project Maven -> Disable Maven Nature

2 Right click again then go to Properties. Delete every evidence of external Maven dependency leaving only JRE System Library.

3 Right click one more time on the project then go to Configure -> Convert to Maven Project

it worked for me also


问:
how do you get email data in Android Studio?
Why does this crash my android app whenever I attempt to run it / what is the best way to get email data into an android app?

The app itself only consists of a button to click - I have gotten the below code to work in eclipse and I am attempting to run it on a mobile phone and not an emulator so I am no longer getting a network error.

```<code>package com.example.marc.emailtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonOnClick(View v){

        String host = "pop.gmail.com";// change accordingly
        String StoreType = "pop3";
        String user = "******@gmail.com";// I purposefully hid these
        String password = "********";// I purposefully hid these

        try {
            //create properties field
            Properties properties = new Properties();

            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);

            //create the POP3 store object and connect with the pop server
            Store store = emailSession.getStore("pop3s");

            store.connect(host, user, password);

            //create the folder object and open it
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // retrieve the messages from the folder in an array and print it
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                Log.i("MainActivity1", "---------------------------------");
                Log.i("MainActivity1", "Email Number " + (i + 1));
                Log.i("MainActivity1", "Subject: " + message.getSubject());
                Log.i("MainActivity1", "From: " + message.getFrom()[0]);
                Log.i("MainActivity1", "Text: " + message.getContent().toString());

            }

            //close the store and folder objects
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            Log.i("MainActivity1", e.getMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
            Log.i("MainActivity1", e.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("MainActivity1", e.getMessage());

        }
    }
}
</code>```

答:
One of your Log.i calls has null as message.
Looking at your code, this will likely be in one of the catch blocks.

Try to log the errors like this:

```<code>Log.i("MainActivity1", "Error: " + e.getMessage());
</code>```

Body:
Why does this crash my android app whenever I attempt to run it / what is the best way to get email data into an android app?

The app itself only consists of a button to click - I have gotten the below code to work in eclipse and I am attempting to run it on a mobile phone and not an emulator so I am no longer getting a network error.

package com.example.marc.emailtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void buttonOnClick(View v){

        String host = "pop.gmail.com";// change accordingly
        String StoreType = "pop3";
        String user = "******@gmail.com";// I purposefully hid these
        String password = "********";// I purposefully hid these

        try {
            //create properties field
            Properties properties = new Properties();

            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);

            //create the POP3 store object and connect with the pop server
            Store store = emailSession.getStore("pop3s");

            store.connect(host, user, password);

            //create the folder object and open it
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // retrieve the messages from the folder in an array and print it
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                Log.i("MainActivity1", "---------------------------------");
                Log.i("MainActivity1", "Email Number " + (i + 1));
                Log.i("MainActivity1", "Subject: " + message.getSubject());
                Log.i("MainActivity1", "From: " + message.getFrom()[0]);
                Log.i("MainActivity1", "Text: " + message.getContent().toString());

            }

            //close the store and folder objects
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            Log.i("MainActivity1", e.getMessage());
        } catch (MessagingException e) {
            e.printStackTrace();
            Log.i("MainActivity1", e.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            Log.i("MainActivity1", e.getMessage());

        }
    }
}

Body:
One of your Log.i calls has null as message.
Looking at your code, this will likely be in one of the catch blocks.

Try to log the errors like this:

Log.i("MainActivity1", "Error: " + e.getMessage());


问:
Are there any Qt specific profilers around?
are there any profilers which work well with Qt? I'd prefer free profilers for windows but any hint is appreciated.

I tried "Very Sleepy" and it works but I cant convince it to demangle the method names. Maybe I'm just doing wrong? Any pit-falls I'm not aware of?

Thank you very much!

Here's a screnshot of Very Sleepys output:

答: Well, I happily use gprof from gcc. It's inside the MinGW package for Windows. </p>


问:
How to make CSS typewriter effect responsive?
I made this CSS typewriter animation however, I'm unable to make it responsive.

The below is my code:

HTML:

```<code><div class="animation">
    <p>CRISTIANO RONALDO</p>
</div>
</code>```

CSS:

```<code>.animation p{
  color: #D64933;
  font-family: 'Lato', cursive;
  font-size: 50px;
  white-space: nowrap;
  overflow: hidden;
  width: 30em;
  animation: title 7s steps(70, end);
  margin-bottom: 40px;

}

@keyframes title{
  from { width: 0; opacity: 0.0;}
  to { opacity: 1.0; }
}
</code>```

I want the animation to start from center of the page and also be responsive. Any thoughts on how it can be achieved?

Link to CodePen

答:
I'm not saying it's the best fix but at least it works (tho there is some shaking) :</p>

```<code>/*CSS*/
.animation {
width: 100%;
text-align: center;
}

.animation p{
margin: 0;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
color: #D64933;
font-family: 'Lato', cursive;
font-size: 50px;
white-space: nowrap;
overflow: hidden;
width: 30em;
animation: title 3s steps(70, end);
margin-bottom: 40px;

}
</code>```

Body:
I made this CSS typewriter animation however, I'm unable to make it responsive.

The below is my code:

HTML:

CRISTIANO RONALDO

CSS:

.animation p{
  color: #D64933;
  font-family: 'Lato', cursive;
  font-size: 50px;
  white-space: nowrap;
  overflow: hidden;
  width: 30em;
  animation: title 7s steps(70, end);
  margin-bottom: 40px;

}

@keyframes title{
  from { width: 0; opacity: 0.0;}
  to { opacity: 1.0; }
}

I want the animation to start from center of the page and also be responsive. Any thoughts on how it can be achieved?

Link to CodePen

Body:
I'm not saying it's the best fix but at least it works (tho there is some shaking) :

/*CSS*/
.animation {
width: 100%;
text-align: center;
}

.animation p{
margin: 0;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
color: #D64933;
font-family: 'Lato', cursive;
font-size: 50px;
white-space: nowrap;
overflow: hidden;
width: 30em;
animation: title 3s steps(70, end);
margin-bottom: 40px;

}


问:
PYTHON WebServer Daemon
The following code is a WebServer written by me.

```<code>#!/usr/bin/python

import BaseHTTPServer
import CGIHTTPServer

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 80)
handler.cgi_dicrectories = ["/cgi"]

httpd = server(server_address, handler)

try:
        httpd.serve_forever()
except KeyboardInterrupt:
        httpd.shutdown()
</code>```

The problem is that every time I use it, I have to launch it.
How can I make it become a Demon and make it work in the background?

答:
Try the next one:

```<code>gunicorn -D -b 127.0.0.1:80 -w 9 -c file_name.py customapp:application
</code>```

Or configure it on your own with http://gunicorn.org manual

Title: PYTHON WebServer Daemon

Body:
The following code is a WebServer written by me.

#!/usr/bin/python

import BaseHTTPServer
import CGIHTTPServer

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 80)
handler.cgi_dicrectories = ["/cgi"]

httpd = server(server_address, handler)

try:
        httpd.serve_forever()
except KeyboardInterrupt:
        httpd.shutdown()

The problem is that every time I use it, I have to launch it.
How can I make it become a Demon and make it work in the background?

Body:
Try the next one:

gunicorn -D -b 127.0.0.1:80 -w 9 -c file_name.py customapp:application

Or configure it on your own with http://gunicorn.org manual


问:
What to replace loops and nested if sentences with in order to speed up Python code?
How can I avoid for loops and nested if sentences and be more Pythonic?

At first glance this may seem like a "please do my all of my work for me" question. I can assure you that it is not. I'm trying to learn some real Python, and would like to discover ways of speeding up code based on a reproducible example and a pre-defined function.

I'm calculating returns from following certain signals in financial markets using loads of for loops and nested if sentences. I have made several attempts, but I am just getting nowhere with vectorizing or comprehensions or other more pythonic tools of the trade. I've been OK with that so far, but finally I'm starting to feel the pain of using functions that are simply too slow at scale.

I have a dataframe with two indexes and one particular event. The two first code snippets are included to show the procedure step by step. I've included the complete thing with some predefined settings and a function at the very end.

In[ 1 ]

```<code># Settings
import numpy as np
import pandas as pd
import datetime
np.random.seed(12345678)

Observations = 10

# Data frame values:
# Two indicators with values betwwen 0 and 10
# and one Event which does or does not occur with values 0 or 1
df = pd.DataFrame(np.random.randint(0,10,size=(Observations, 2)),
                  columns=['IndicatorA', 'IndicatorB'] )
df['Event'] = np.random.randint(0,2,size=(Observations, 1))

# Data frame index:
datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

# Placeholder for signals based on the existing values
# in the data frame
df['Signal'] = 0

print(df)
</code>```

Out[ 1 ]

The data frame is indexed by dates. The signal I'm looking for is determined by the interaction of these indicators and events. The Signal is calculated the following way (expanding on the snippet above):

In[ 2 ]

```<code>i = 0
for signals in df['Signal']:
    if i == 0:
        # First signal is always zero
        df.ix[i,'Signal'] = 0
    else:
        # Signal is 1 if Indicator A is above a certain level
        if df.ix[i,'IndicatorA'] > 5:
            df.ix[i,'Signal'] = 1
        else:
            # Signal is 1 if Indicator B is above a certain level
            # AND a certain event occurs
            if df.ix[i - 1,'IndicatorB'] > 5 & df.ix[i,'Event'] > 1:
                 df.ix[i,'Signal'] = 1
            else:
                df.ix[i,'Signal'] = 0
    i = i + 1

print(df['Signal'])
</code>```

Out[ 2 ]

Below is the whole thing defined as a function. Notice that the function returns the average of the Signal instead of the Signal column itself. This way the console is not cluttered when the code is run, and we can test the efficency of the code using %time in ipython.

```<code># Settings
import numpy as np
import pandas as pd
import datetime

# The whole thing defined as a function

def fxSlow(Observations):

    np.random.seed(12345678)

    df = pd.DataFrame(np.random.randint(0,10,size=(Observations, 2)),
                        columns=['IndicatorA', 'IndicatorB'] )
    df['Event'] = np.random.randint(0,2,size=(Observations, 1))

    datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'),
                periods=Observations).tolist()
    df['Signal'] = 0

    df['Dates'] = datelist
    df = df.set_index(['Dates'])

    i = 0
    for signals in df['Signal']:
        if i == 0:
            # First signal is always zero
            df.ix[i,'Signal'] = 0
        else:
            # Signal is 1 if Indocator A is above a certain level
            if df.ix[i,'IndicatorA'] > 5:
                df.ix[i,'Signal'] = 1
            else:
                # Signal is 1 if Indicator B is above a certain level
                # AND a certain event occurs
                if df.ix[i - 1,'IndicatorB'] > 5 & df.ix[i,'Event'] > 1:
                     df.ix[i,'Signal'] = 1
                else:
                    df.ix[i,'Signal'] = 0
        i = i + 1

    return np.mean(df['Signal'])
</code>```

Below you can see the results of running the function with different observations / size of the data frame:

So, how can I speed things up by being more Pythonic?

And as a bonus question, what causes the error when I increase the number of observations to 100000?

答:
Can you try something like this?

```<code>def fxSlow2(Observations):

    np.random.seed(12345678)

    df = pd.DataFrame(np.random.randint(0,10,size=(Observations, 2)),
                        columns=['IndicatorA', 'IndicatorB'] )
    df['Event'] = np.random.randint(0,2,size=(Observations, 1))

    datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'),
                periods=Observations).tolist()
    df['Signal'] = 0

    df['Dates'] = datelist
    df = df.set_index(['Dates'])

    df['Signal'] = (np.where(df.IndicatorA > 5,
          1,
          np.where( (df.shift(-1).IndicatorB > 5) &(df.Event > 1),
                    1,
                    0)
          )
    )

    df.loc[df.index[0],'Signal'] = 0

    return np.mean(df['Signal'])
</code>```

%time fxSlow2(100)

Wall time: 10 ms

Out[208]: 0.43

%time fxSlow2(1000)

Wall time: 15 ms

Out[209]: 0.414

%time fxSlow2(10000)

Wall time: 61 ms

Out[210]: 0.4058

Body:
How can I avoid for loops and nested if sentences and be more Pythonic?

At first glance this may seem like a "please do my all of my work for me" question. I can assure you that it is not. I'm trying to learn some real Python, and would like to discover ways of speeding up code based on a reproducible example and a pre-defined function.

I'm calculating returns from following certain signals in financial markets using loads of for loops and nested if sentences. I have made several attempts, but I am just getting nowhere with vectorizing or comprehensions or other more pythonic tools of the trade. I've been OK with that so far, but finally I'm starting to feel the pain of using functions that are simply too slow at scale.

I have a dataframe with two indexes and one particular event. The two first code snippets are included to show the procedure step by step. I've included the complete thing with some predefined settings and a function at the very end.

In[ 1 ]

# Settings
import numpy as np
import pandas as pd
import datetime
np.random.seed(12345678)

Observations = 10

# Data frame values:
# Two indicators with values betwwen 0 and 10
# and one Event which does or does not occur with values 0 or 1
df = pd.DataFrame(np.random.randint(0,10,size=(Observations, 2)),
                  columns=['IndicatorA', 'IndicatorB'] )
df['Event'] = np.random.randint(0,2,size=(Observations, 1))

# Data frame index:
datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'),
                         periods=Observations).tolist()
df['Dates'] = datelist
df = df.set_index(['Dates'])

# Placeholder for signals based on the existing values
# in the data frame
df['Signal'] = 0

print(df)

Out[ 1 ]

The data frame is indexed by dates. The signal I'm looking for is determined by the interaction of these indicators and events. The Signal is calculated the following way (expanding on the snippet above):

In[ 2 ]

i = 0
for signals in df['Signal']:
    if i == 0:
        # First signal is always zero
        df.ix[i,'Signal'] = 0
    else:
        # Signal is 1 if Indicator A is above a certain level
        if df.ix[i,'IndicatorA'] > 5:
            df.ix[i,'Signal'] = 1
        else:
            # Signal is 1 if Indicator B is above a certain level
            # AND a certain event occurs
            if df.ix[i - 1,'IndicatorB'] > 5 & df.ix[i,'Event'] > 1:
                 df.ix[i,'Signal'] = 1
            else:
                df.ix[i,'Signal'] = 0
    i = i + 1

print(df['Signal'])

Out[ 2 ]

Below is the whole thing defined as a function. Notice that the function returns the average of the Signal instead of the Signal column itself. This way the console is not cluttered when the code is run, and we can test the efficency of the code using %time in ipython.

# Settings
import numpy as np
import pandas as pd
import datetime

# The whole thing defined as a function

def fxSlow(Observations):

    np.random.seed(12345678)

    df = pd.DataFrame(np.random.randint(0,10,size=(Observations, 2)),
                        columns=['IndicatorA', 'IndicatorB'] )
    df['Event'] = np.random.randint(0,2,size=(Observations, 1))

    datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'),
                periods=Observations).tolist()
    df['Signal'] = 0

    df['Dates'] = datelist
    df = df.set_index(['Dates'])

    i = 0
    for signals in df['Signal']:
        if i == 0:
            # First signal is always zero
            df.ix[i,'Signal'] = 0
        else:
            # Signal is 1 if Indocator A is above a certain level
            if df.ix[i,'IndicatorA'] > 5:
                df.ix[i,'Signal'] = 1
            else:
                # Signal is 1 if Indicator B is above a certain level
                # AND a certain event occurs
                if df.ix[i - 1,'IndicatorB'] > 5 & df.ix[i,'Event'] > 1:
                     df.ix[i,'Signal'] = 1
                else:
                    df.ix[i,'Signal'] = 0
        i = i + 1

    return np.mean(df['Signal'])

Below you can see the results of running the function with different observations / size of the data frame:

So, how can I speed things up by being more Pythonic?

And as a bonus question, what causes the error when I increase the number of observations to 100000?

Body:
Can you try something like this?

def fxSlow2(Observations):

    np.random.seed(12345678)

    df = pd.DataFrame(np.random.randint(0,10,size=(Observations, 2)),
                        columns=['IndicatorA', 'IndicatorB'] )
    df['Event'] = np.random.randint(0,2,size=(Observations, 1))

    datelist = pd.date_range(pd.datetime.today().strftime('%Y-%m-%d'),
                periods=Observations).tolist()
    df['Signal'] = 0

    df['Dates'] = datelist
    df = df.set_index(['Dates'])

    df['Signal'] = (np.where(df.IndicatorA > 5,
          1,
          np.where( (df.shift(-1).IndicatorB > 5) &(df.Event > 1),
                    1,
                    0)
          )
    )

    df.loc[df.index[0],'Signal'] = 0

    return np.mean(df['Signal'])

%time fxSlow2(100)

Wall time: 10 ms

Out[208]: 0.43

%time fxSlow2(1000)

Wall time: 15 ms

Out[209]: 0.414

%time fxSlow2(10000)

Wall time: 61 ms

Out[210]: 0.4058


问:
Updating user address table
I am trying to update user address. It's adding record to the database successfully, but when it comes to displaying current version of address on the website, I have to hit re-submit first.

To view this page, information previously sent by Firefox needs to be resubmitted. When you resubmit your data, each action made on the form (such as a search or online order) will be repeated.

Php code in folder profileUpdate.php

```<code>$email = $_SESSION['email'];
    if (!empty($_POST)) {
        $first_name = $_POST["first_name"];
        $last_name  = $_POST["last_name"];
        $street     = $_POST["street"];
        $city       = $_POST["city"];
        $country    = $_POST["country"];
        $zip        = $_POST["zip"];
        $phone_no   = $_POST["phone_no"];

    if (empty($first_name) || empty($last_name) || empty($street) || empty($city) || empty($country) || empty($zip) || empty($phone_no) ) {
        $response->success = false;
        $response->message = 'All fields must be filled.';
    } else {

            $sql_address_update = "UPDATE address AS a\n"
                . "INNER JOIN customer AS c ON a.customer_ID = c.customer_ID\n"
                . "SET a.`first_name` = ?, a.`last_name` = ?, a.`street` = ?, a.`city` = ?, a.`country` = ?, a.`zip` = ?, a.`phone_no` = ?\n"
                . "WHERE (c.`email` = '". $email . "')";
            try {

                //Create customer
                $preparedStatement = $db->prepare($sql_address_update);
                $preparedStatement->bind_param('sssssii', $first_name, $last_name, $street, $city, $country, $zip, $phone_no);
                $preparedStatement->execute();

                $response->success = true;
                $response->message = 'Account created.';

                // $api=new SMSApi('Group07','129DFCF1651D3E75');
                // $reply=$api->SendEmailv2($email,"Verification","Hi. Follow this link to verify your account: https://139.59.131.217/verify.php?email=".$email."&ver=".$verificationString);
            }
            catch (Exception $e) {
                $response->success = false;
                $errorCode         = $e->getCode();
                if ($errorCode == 23000) //username and email columns are UNIQUE, this error code means violation of this rule (duplicate data)
                    {
                    $response->message = 'Duplicate username or email.';
                } else {
                    $response->message = "Error.";
                }
            }
        }
    }

$connection = null;
</code>```

profile.php file

   <?php if(isset($_SESSION['email'])){ while($row = $result_address->fetch_assoc()){ ?>

 Address EDIT

Name: <?php echo $row['first_name']. " " .$row['last_name'];?>

      Street: <?php echo $row['street'];?>

      City: <?php echo $row['city'];?>

      Country: <?php echo $row['country'];?>

      Zip code: <?php echo $row['zip'];?>

      Phone: <?php echo $row['phone_no'];?>

   <?php }}?>

   <form method="post" action='#' id="form" role="form" onsubmit="" class="form">

         <input type="text" name="first_name" id="first_name" class="input-md form-control" placeholder="First name" maxlength="20" required />

         <input type="text" name="last_name" id="last_name" class="input-md form-control" placeholder="Surname" maxlength="100" required />

         <input type="text" name="street" id="street" class="input-md form-control" placeholder="Street" maxlength="100" required />

         <input type="text" name="city" id="city" class="input-md form-control" placeholder="City" maxlength="100" required />

         <select class="input-md form-control" type="text" id="country" name="country" required />
            <option disabled selected>Select country..</option>
            <option value="dk">Denmark</option>
            <option value="cz">Czech Republic</option>
            <option value="pl">Poland</option>
            <option value="hu">Hungary</option>
            <option value="sk">Slovakia</option>
         </select>

         <input type="text" name="zip" id="zip" class="input-md form-control" placeholder="Zip code"required />

         <input type="text" name="phone_no" id="phone_no" data-validation="length" data-validation-length="max10" class="input-md form-control" placeholder="Phone number" required />

         <button class="btn btn-mod btn-small update" type="submit" name="submit" value="update" id="updateBtn">Upadate information</button>

   </form>

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>        $('#edit').on('click',function()
         {
         $('#p, #form').toggle();
         }
         );

         $( "#updateBtn" ).click(function() {
         $( "#p" ).toggle( "slow");
         $( "#form" ).hide();
       });</code>```

```
</div>
</div>
</p>

<p>Can you please give me advice how to make it without re-submitting the form & showing result right away?</p>

<p>I tried to use Ajax as well but I have probabl some flaw in the code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> $(function() {
  $("#update").click(function() {
  vvar first_name = $("#first_name").val();
  var last_name = $("#last_name").val();
  var street = $("#street").val();
  var city = $("#city").val();
  var coutnry = $("#country").val();
  var zip = $("#zip").val();
  var phone_no = $("#phone_no").val();
  var dataString = 'first_name='+ first_name + '&last_name=' + last_name + '&street=' + street + '&city=' + city + '&coutnry=' + country + '&zip=' + zip; + '&phone_no=' + phone_no;

if(first_name=='' || last_name=='' || city=='' || country=='' || zip=='' || phone_no=='')
{
  //
}
else
{
  $.ajax({
    type: "POST",
    url: "profileUpdate.php",
    data: dataString,
    success: function(){
     //
    }
  });
}
return false;
});
});</code>```

```

答:
If you want to see the results right away you need to take a different approach to this. PHP can't render output at run-time. Ajax can however. This is quite fluffy but I suggest you read up on ajax post/get calls.

This video shows the basics of retrieving data & showing it "live"
https://www.youtube.com/watch?v=IvagmRhTG4w&index=4&list=PLQj6bHfDUS-b5EXUbHVQ21N_2Vli39w0k

God dag :)

Title: Updating user address table

Body:
I am trying to update user address. It's adding record to the database successfully, but when it comes to displaying current version of address on the website, I have to hit re-submit first.

To view this page, information previously sent by Firefox needs to be resubmitted. When you resubmit your data, each action made on the form (such as a search or online order) will be repeated.

Php code in folder profileUpdate.php

$email = $_SESSION['email'];
    if (!empty($_POST)) {
        $first_name = $_POST["first_name"];
        $last_name  = $_POST["last_name"];
        $street     = $_POST["street"];
        $city       = $_POST["city"];
        $country    = $_POST["country"];
        $zip        = $_POST["zip"];
        $phone_no   = $_POST["phone_no"];

    if (empty($first_name) || empty($last_name) || empty($street) || empty($city) || empty($country) || empty($zip) || empty($phone_no) ) {
        $response->success = false;
        $response->message = 'All fields must be filled.';
    } else {

            $sql_address_update = "UPDATE address AS a\n"
                . "INNER JOIN customer AS c ON a.customer_ID = c.customer_ID\n"
                . "SET a.`first_name` = ?, a.`last_name` = ?, a.`street` = ?, a.`city` = ?, a.`country` = ?, a.`zip` = ?, a.`phone_no` = ?\n"
                . "WHERE (c.`email` = '". $email . "')";
            try {

                //Create customer
                $preparedStatement = $db->prepare($sql_address_update);
                $preparedStatement->bind_param('sssssii', $first_name, $last_name, $street, $city, $country, $zip, $phone_no);
                $preparedStatement->execute();

                $response->success = true;
                $response->message = 'Account created.';

                // $api=new SMSApi('Group07','129DFCF1651D3E75');
                // $reply=$api->SendEmailv2($email,"Verification","Hi. Follow this link to verify your account: https://139.59.131.217/verify.php?email=".$email."&ver=".$verificationString);
            }
            catch (Exception $e) {
                $response->success = false;
                $errorCode         = $e->getCode();
                if ($errorCode == 23000) //username and email columns are UNIQUE, this error code means violation of this rule (duplicate data)
                    {
                    $response->message = 'Duplicate username or email.';
                } else {
                    $response->message = "Error.";
                }
            }
        }
    }

$connection = null;

profile.php file

   <?php if(isset($_SESSION['email'])){ while($row = $result_address->fetch_assoc()){ ?>

 Address EDIT

Name: <?php echo $row['first_name']. " " .$row['last_name'];?>

      Street: <?php echo $row['street'];?>

      City: <?php echo $row['city'];?>

      Country: <?php echo $row['country'];?>

      Zip code: <?php echo $row['zip'];?>

      Phone: <?php echo $row['phone_no'];?>

   <?php }}?>

   <form method="post" action='#' id="form" role="form" onsubmit="" class="form">

         <input type="text" name="first_name" id="first_name" class="input-md form-control" placeholder="First name" maxlength="20" required />

         <input type="text" name="last_name" id="last_name" class="input-md form-control" placeholder="Surname" maxlength="100" required />

         <input type="text" name="street" id="street" class="input-md form-control" placeholder="Street" maxlength="100" required />

         <input type="text" name="city" id="city" class="input-md form-control" placeholder="City" maxlength="100" required />

         <select class="input-md form-control" type="text" id="country" name="country" required />
            <option disabled selected>Select country..</option>
            <option value="dk">Denmark</option>
            <option value="cz">Czech Republic</option>
            <option value="pl">Poland</option>
            <option value="hu">Hungary</option>
            <option value="sk">Slovakia</option>
         </select>

         <input type="text" name="zip" id="zip" class="input-md form-control" placeholder="Zip code"required />

         <input type="text" name="phone_no" id="phone_no" data-validation="length" data-validation-length="max10" class="input-md form-control" placeholder="Phone number" required />

         <button class="btn btn-mod btn-small update" type="submit" name="submit" value="update" id="updateBtn">Upadate information</button>

   </form>

        $('#edit').on('click',function()
         {
         $('#p, #form').toggle();
         }
         );

         $( "#updateBtn" ).click(function() {
         $( "#p" ).toggle( "slow");
         $( "#form" ).hide();
       });

Can you please give me advice how to make it without re-submitting the form & showing result right away?

I tried to use Ajax as well but I have probabl some flaw in the code

 $(function() {
  $("#update").click(function() {
  vvar first_name = $("#first_name").val();
  var last_name = $("#last_name").val();
  var street = $("#street").val();
  var city = $("#city").val();
  var coutnry = $("#country").val();
  var zip = $("#zip").val();
  var phone_no = $("#phone_no").val();
  var dataString = 'first_name='+ first_name + '&last_name=' + last_name + '&street=' + street + '&city=' + city + '&coutnry=' + country + '&zip=' + zip; + '&phone_no=' + phone_no;

if(first_name=='' || last_name=='' || city=='' || country=='' || zip=='' || phone_no=='')
{
  //
}
else
{
  $.ajax({
    type: "POST",
    url: "profileUpdate.php",
    data: dataString,
    success: function(){
     //
    }
  });
}
return false;
});
});


问:
How to prevent a link inside a label from triggering a checkbox?
I have this label:

```<code><label><input type="checkbox"> I agree to the <a href="terms">terms</a> and would like to continue</label>
</code>```

However, the link inside the label opens a foundation 5 reveal modal. This works fine, but clicking on the link also checks the checkbox.

How can I prevent the checkbox from being checked when the link is clicked?

答:
Another inline way:</p>
```<code><label>
     <input type="checkbox">
     I agree to the
     <span  onclick="event.stopPropagation();">
          <a href="terms">terms</a>
     </span>
     and would like to continue
</label>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this label:

<input type="checkbox"> I agree to the terms and would like to continue

However, the link inside the label opens a foundation 5 reveal modal. This works fine, but clicking on the link also checks the checkbox.

How can I prevent the checkbox from being checked when the link is clicked?

Body:
Another inline way:

<label>
     <input type="checkbox">
     I agree to the
     <span  onclick="event.stopPropagation();">
          <a href="terms">terms</a>
     </span>
     and would like to continue
</label>


问:
windows registry values coming back as long integers
I'm working my way through Violent Python and have encountered a problem with the first program in chapter 3.

The idea is to print the name of each network in HKEY_LOCAL_MACHINE../unmanaged as well as their assigned DefaultGateWayMac.

I've already checked various questions here on SO as I was initially having trouble setting up the script (Violen Python is getting quite old..).

the problem I'm facing is that when I attempt to print the Mac Address I'm getting a bunch of integers. My initial thought was that some of the combinations could be ASCII values, but even trying to convert them wouldn't create a correct MAC-address.

I've checked in my machine's registry keys for mac-addresses and most of them seem fine (some of them are empty). But as mentioned above, none of them seem to print fine.

This is my script:

```<code>from winreg import *

def val2addr(val):
    if val:
        address = ""
        for ch in val:
            if(not int(ch)):
                address += "%02x " % ord(ch)
                address = address.strip(' ').replace(' ', ':')[0: 17]
            else:
                address += str(ch)
        return address
    return "[!] No MAC [!]"

def print_networks():
    net = u"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"+\
          "\\NetworkList\\Signatures\\Unmanaged"
    print(str(HKEY_LOCAL_MACHINE) + net)
    key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, (KEY_WOW64_64KEY + KEY_READ))
    print('\n[*] Networks You have Joined:\n')

    for network in range(100):
        try:
            guid = EnumKey(key, network)
            netkey = OpenKey(key, str(guid))
            mac = QueryValueEx(netkey, 'DefaultGatewayMac')[0]
            mac = val2addr(mac)
            network_name = QueryValueEx(netkey, 'Description')[0]
            print("[+] Network Name: " + network_name + "[+] Mac: " + mac)
            CloseKey(netkey)
        except Exception as e:
            print(e)
            break

def main():
    print_networks()

if __name__ == '__main__':
    main()
</code>```

As you can see I've made some changes (in particular to val2addr):

```<code>def val2addr(val):
    addr = ''
    for ch in val:
        addr += '%02x '% ord(ch)
        addr = addr.strip(' ').replace(' ', ':')[0:17]
    return addr
</code>```

Here is some sample output that my program prints:

[*] Networks You have Joined:

[+] Network Name: DIRECT-HUJABERO059243[+] Mac: [!] No MAC [!]
[+] Network Name: Network  2[+] Mac: 72906311290171
[+] Network Name: Network  3[+] Mac: 1447774159240
[+] Network Name: Network[+] Mac: 200205114121180123
[+] Network Name: BTHub3-JZM3[+] Mac: 20451187180235148
[WinError 259] No more data is available
```

答:
It's the decimal representation of your MAC address.

Converting 72906311290171, I get 424ED2C94D3B, which is a MAC address (42:4E:D2:C9:4D:3B)

Conversion for python2:

```<code>dec_mac = 72906311290171
print ':'.join(s.encode('hex') for s in str(dec_mac).decode('hex'))
</code>```

and for python3

```<code>dec_mac = 72906311290171
print(':'.join(format(s, '02x') for s in bytes.fromhex(str(dec_mac))))
</code>```

Body:
I'm working my way through Violent Python and have encountered a problem with the first program in chapter 3.

The idea is to print the name of each network in HKEY_LOCAL_MACHINE../unmanaged as well as their assigned DefaultGateWayMac.

I've already checked various questions here on SO as I was initially having trouble setting up the script (Violen Python is getting quite old..).

the problem I'm facing is that when I attempt to print the Mac Address I'm getting a bunch of integers. My initial thought was that some of the combinations could be ASCII values, but even trying to convert them wouldn't create a correct MAC-address.

I've checked in my machine's registry keys for mac-addresses and most of them seem fine (some of them are empty). But as mentioned above, none of them seem to print fine.

This is my script:

from winreg import *

def val2addr(val):
    if val:
        address = ""
        for ch in val:
            if(not int(ch)):
                address += "%02x " % ord(ch)
                address = address.strip(' ').replace(' ', ':')[0: 17]
            else:
                address += str(ch)
        return address
    return "[!] No MAC [!]"

def print_networks():
    net = u"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"+\
          "\\NetworkList\\Signatures\\Unmanaged"
    print(str(HKEY_LOCAL_MACHINE) + net)
    key = OpenKey(HKEY_LOCAL_MACHINE, net, 0, (KEY_WOW64_64KEY + KEY_READ))
    print('\n[*] Networks You have Joined:\n')

    for network in range(100):
        try:
            guid = EnumKey(key, network)
            netkey = OpenKey(key, str(guid))
            mac = QueryValueEx(netkey, 'DefaultGatewayMac')[0]
            mac = val2addr(mac)
            network_name = QueryValueEx(netkey, 'Description')[0]
            print("[+] Network Name: " + network_name + "[+] Mac: " + mac)
            CloseKey(netkey)
        except Exception as e:
            print(e)
            break

def main():
    print_networks()

if __name__ == '__main__':
    main()

As you can see I've made some changes (in particular to val2addr):

def val2addr(val):
    addr = ''
    for ch in val:
        addr += '%02x '% ord(ch)
        addr = addr.strip(' ').replace(' ', ':')[0:17]
    return addr

Here is some sample output that my program prints:

[*] Networks You have Joined:

[+] Network Name: DIRECT-HUJABERO059243[+] Mac: [!] No MAC [!]
[+] Network Name: Network  2[+] Mac: 72906311290171
[+] Network Name: Network  3[+] Mac: 1447774159240
[+] Network Name: Network[+] Mac: 200205114121180123
[+] Network Name: BTHub3-JZM3[+] Mac: 20451187180235148
[WinError 259] No more data is available

Body:
It's the decimal representation of your MAC address.

Converting 72906311290171, I get 424ED2C94D3B, which is a MAC address (42:4E:D2:C9:4D:3B)

Conversion for python2:

dec_mac = 72906311290171
print ':'.join(s.encode('hex') for s in str(dec_mac).decode('hex'))

and for python3

dec_mac = 72906311290171
print(':'.join(format(s, '02x') for s in bytes.fromhex(str(dec_mac))))


问:
trouble with rpy2, rpart passing data correctly from python to r
I am trying to run rpart through RPY2 using Python 2.6.5 and R 10.0.

I create a data frame in python and pass it along but I get an error stating:

```<code>Error in function (x)  : binary operation on non-conformable arrays
Traceback (most recent call last):
  File "partitioningSANDBOX.py", line 86, in <module>
    model=r.rpart(**rpart_params)
  File "build/bdist.macosx-10.3-fat/egg/rpy2/robjects/functions.py", line 83, in __call__
  File "build/bdist.macosx-10.3-fat/egg/rpy2/robjects/functions.py", line 35, in __call__
rpy2.rinterface.RRuntimeError: Error in function (x)  : binary operation on non-conformable arrays
</code>```

Can anyone help me determine what I am doing wrong to throw this error?

the relevant part of my code is this:

```<code>import numpy as np
import rpy2
import rpy2.robjects as rob
import rpy2.robjects.numpy2ri

#Fire up the interface to R
r = rob.r
r.library("rpart")

datadict = dict(zip(['responsev','predictorv'],[cLogEC,csplitData]))
Rdata = r['data.frame'](**datadict)
Rformula = r['as.formula']('responsev ~.')
#Generate an RPART model in R.
Rpcontrol = r['rpart.control'](minsplit=10, xval=10)
rpart_params = {'formula' : Rformula, \
       'data' : Rdata,
       'control' : Rpcontrol}
model=r.rpart(**rpart_params)
</code>```

The two variables cLogEC and csplitData are numpy arrays of float type.

Also, my data frame looks like this:

```<code>In [2]: print Rdata
------> print(Rdata)
   responsev predictorv
1  0.6020600        312
2  0.3010300        300
3  0.4771213        303
4  0.4771213        249
5  0.9242793        239
6  1.1986571        297
7  0.7075702        287
8  1.8115750        270
9  0.6020600        296
10 1.3856063        248
11 0.6127839        295
12 0.3010300        283
13 1.1931246        345
14 0.3010300        270
15 0.3010300        251
16 0.3010300        246
17 0.3010300        273
18 0.7075702        252
19 0.4771213        252
20 0.9294189        223
21 0.6127839        252
22 0.7075702        267
23 0.9294189        252
24 0.3010300        378
25 0.3010300        282
</code>```

and the formula looks like this:

```<code>In [3]: print Rformula
------> print(Rformula)
responsev ~ .
</code>```

答:
The problem is related to R idiosyncratic code in rpart (to be precise, the following block, in particular the last line:

```<code>m <- match.call(expand.dots = FALSE)
m$model <- m$method <- m$control <- NULL
m$x <- m$y <- m$parms <- m$... <- NULL
m$cost <- NULL
m$na.action <- na.action
m[[1L]] <- as.name("model.frame")
m <- eval(m, parent.frame())
</code>```

).

One way to work around that is to avoid entering that block of code (see below) or may be to construct a nested evaluation from Python (so that parent.frame() behaves). This is not as simple as one would hope, but may be I'll find time to make it easier in the future.

```<code>from rpy2.robjects import DataFrame, Formula
import rpy2.robjects.numpy2ri as npr
import numpy as np
from rpy2.robjects.packages import importr
rpart = importr('rpart')
stats = importr('stats')

cLogEC = np.random.uniform(size=10)
csplitData = np.array(range(10), 'i')

dataf = DataFrame({'responsev': cLogEC,
                   'predictorv': csplitData})
formula = Formula('responsev ~.')
rpart.rpart(formula=formula, data=dataf,
            control=rpart.rpart_control(minsplit = 10, xval = 10),
            model = stats.model_frame(formula, data=dataf))
</code>```

Body:
I am trying to run rpart through RPY2 using Python 2.6.5 and R 10.0.

I create a data frame in python and pass it along but I get an error stating:

Error in function (x)  : binary operation on non-conformable arrays
Traceback (most recent call last):
  File "partitioningSANDBOX.py", line 86, in <module>
    model=r.rpart(**rpart_params)
  File "build/bdist.macosx-10.3-fat/egg/rpy2/robjects/functions.py", line 83, in __call__
  File "build/bdist.macosx-10.3-fat/egg/rpy2/robjects/functions.py", line 35, in __call__
rpy2.rinterface.RRuntimeError: Error in function (x)  : binary operation on non-conformable arrays

Can anyone help me determine what I am doing wrong to throw this error?

the relevant part of my code is this:

import numpy as np
import rpy2
import rpy2.robjects as rob
import rpy2.robjects.numpy2ri

#Fire up the interface to R
r = rob.r
r.library("rpart")

datadict = dict(zip(['responsev','predictorv'],[cLogEC,csplitData]))
Rdata = r['data.frame'](**datadict)
Rformula = r['as.formula']('responsev ~.')
#Generate an RPART model in R.
Rpcontrol = r['rpart.control'](minsplit=10, xval=10)
rpart_params = {'formula' : Rformula, \
       'data' : Rdata,
       'control' : Rpcontrol}
model=r.rpart(**rpart_params)

The two variables cLogEC and csplitData are numpy arrays of float type.

Also, my data frame looks like this:

In [2]: print Rdata
------> print(Rdata)
   responsev predictorv
1  0.6020600        312
2  0.3010300        300
3  0.4771213        303
4  0.4771213        249
5  0.9242793        239
6  1.1986571        297
7  0.7075702        287
8  1.8115750        270
9  0.6020600        296
10 1.3856063        248
11 0.6127839        295
12 0.3010300        283
13 1.1931246        345
14 0.3010300        270
15 0.3010300        251
16 0.3010300        246
17 0.3010300        273
18 0.7075702        252
19 0.4771213        252
20 0.9294189        223
21 0.6127839        252
22 0.7075702        267
23 0.9294189        252
24 0.3010300        378
25 0.3010300        282

and the formula looks like this:

In [3]: print Rformula
------> print(Rformula)
responsev ~ .

Body:
The problem is related to R idiosyncratic code in rpart (to be precise, the following block, in particular the last line:

m <- match.call(expand.dots = FALSE)
m$model <- m$method <- m$control <- NULL
m$x <- m$y <- m$parms <- m$... <- NULL
m$cost <- NULL
m$na.action <- na.action
m[[1L]] <- as.name("model.frame")
m <- eval(m, parent.frame())

).

One way to work around that is to avoid entering that block of code (see below) or may be to construct a nested evaluation from Python (so that parent.frame() behaves). This is not as simple as one would hope, but may be I'll find time to make it easier in the future.

from rpy2.robjects import DataFrame, Formula
import rpy2.robjects.numpy2ri as npr
import numpy as np
from rpy2.robjects.packages import importr
rpart = importr('rpart')
stats = importr('stats')

cLogEC = np.random.uniform(size=10)
csplitData = np.array(range(10), 'i')

dataf = DataFrame({'responsev': cLogEC,
                   'predictorv': csplitData})
formula = Formula('responsev ~.')
rpart.rpart(formula=formula, data=dataf,
            control=rpart.rpart_control(minsplit = 10, xval = 10),
            model = stats.model_frame(formula, data=dataf))


问:
Fixed body background scrolls with the page on iOS7
I've used the following CSS to ceate a fixed body background. It works well on almost all browsers except the new iOS7. On the latter the background is not fixed anymore. It scrolls with the page. Any idea how to fix the problem?

    body {
       background-color: #000;
       background-image: url('../pics/backgrounds/blackWhite.jpg');
       background-repeat: no-repeat;
       background-position: center;
       background-attachment: fixed;
       webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
    }
```

CHEERS

答:
I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

```<code>#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}
</code>```

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

```<code>@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}
</code>```

initial -   Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.

Body:
I've used the following CSS to ceate a fixed body background. It works well on almost all browsers except the new iOS7. On the latter the background is not fixed anymore. It scrolls with the page. Any idea how to fix the problem?

    body {
       background-color: #000;
       background-image: url('../pics/backgrounds/blackWhite.jpg');
       background-repeat: no-repeat;
       background-position: center;
       background-attachment: fixed;
       webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
    }

CHEERS

Body:
I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}

initial -   Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.


问:
virtualenvwrapper -- Opencv 3.1.0 installation error
I am trying to install opencv 3.1.0 by the help of following blog(Why? Because I followed the same blog to install opencv in Desktop, but In my Laptop, following issue came)

Here I encountered the following error as --

```<code>ujjal@ujjaldas223:~$ source /usr/local/bin/virtualenvwrapper.sh
/home/ujjal/anaconda2/bin/python: No module named virtualenvwrapper
virtualenvwrapper.sh: There was a problem running the initialization hooks.

If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/home/ujjal/anaconda2/bin/python and that PATH is
set properly.
</code>```

I followed the link, but failed to resolve issue.
Suggest me how to solve this error.
I am using ubuntu 16.04 LTS both in Desktop and laptop.

答:
I just solved it!
The problem was anaconda path appended to python.
Removing anaconda2 completely solved the issue.</p>

Body:
I am trying to install opencv 3.1.0 by the help of following blog(Why? Because I followed the same blog to install opencv in Desktop, but In my Laptop, following issue came)

Here I encountered the following error as --

ujjal@ujjaldas223:~$ source /usr/local/bin/virtualenvwrapper.sh
/home/ujjal/anaconda2/bin/python: No module named virtualenvwrapper
virtualenvwrapper.sh: There was a problem running the initialization hooks.

If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/home/ujjal/anaconda2/bin/python and that PATH is
set properly.

I followed the link, but failed to resolve issue.
Suggest me how to solve this error.
I am using ubuntu 16.04 LTS both in Desktop and laptop.


问:
Convert binary number 5 into list of intergers (4,1)
I have a configuration value expressed as a binary number to allow several options within the same value.

E.g. the value of 5 would be "101" or both 4 and 1.

Does anyone know of the best/fastest way to "input" the value '5' and get a list of {1,4} back?

答:
A maybe more traditional and easy to understand solution. You convert the number into a string binary representation, and then analyze each character to extract the corresponding decimal representations of each bit at 1.</p>

```<code>int number = 5;
string binaryRep = Convert.ToString(number, 2);
List<int> myList = new List<int>();
int pow = 0;

for(int i = binaryRep.Count() - 1; i >= 0; i--)
{
    if(binaryRep[i] == '1')
    {
        myList.Add((int)Math.Pow(2, pow));
    }

    pow++;
}
</code>```

Body:
A maybe more traditional and easy to understand solution. You convert the number into a string binary representation, and then analyze each character to extract the corresponding decimal representations of each bit at 1.

int number = 5;
string binaryRep = Convert.ToString(number, 2);
List<int> myList = new List<int>();
int pow = 0;

for(int i = binaryRep.Count() - 1; i >= 0; i--)
{
    if(binaryRep[i] == '1')
    {
        myList.Add((int)Math.Pow(2, pow));
    }

    pow++;
}


问:
Run mysql query through Wit.ai
On integrating Wit.ai into a website, is there some way to execute database queries because answers of user questions have to be fetched from the database and that can not be trained to Chatbot.</p>

答:
as you see in the tutorial you define actions in wit.ai, those actions can involve variables who can be send as a response to the users. So, you should make the query to the database in the actions defined by you, if you haven't defined them, then do it, because there is where you can make your logic happens. Also, take into account that you may handle non synchronized petitions to your database, then you should implement a block mechanism to return the context in each action just after you have done you're query.

I know you want to make an implementation in python, but I already have an implementation on node.js, so here is my sample code.

```<code>  getFullName({sessionId, context, entities}) {
    let session;
    let fbid = sessionId.split("-")[0];
    return fbTypingOn(fbid)
      .then(() => {
        return model.getSesion(fbid);
      })
      .then(sesion => {
        session = sesion;
        return callFbUserAPI(session);
      })
      .then(first_name => {
        session.context.fullNameGreeting = utilsBot.buildGreeting(session);
        return model.setSesion(session);
      })
      .then( sesion => {
        return session.context;
      })
      .catch( error => {
        console.log("Error in getFullName " + error);
        session.context.fullNameGreeting = "Hola";
        return context;
      });
  }
</code>```

Make sure you read all documentation in the official page, because if there isn't something, then you should do it. Also, there's already an implementation in python 2, I guess.

Title: Run mysql query through Wit.ai

Body:
as you see in the tutorial you define actions in wit.ai, those actions can involve variables who can be send as a response to the users. So, you should make the query to the database in the actions defined by you, if you haven't defined them, then do it, because there is where you can make your logic happens. Also, take into account that you may handle non synchronized petitions to your database, then you should implement a block mechanism to return the context in each action just after you have done you're query.

I know you want to make an implementation in python, but I already have an implementation on node.js, so here is my sample code.

  getFullName({sessionId, context, entities}) {
    let session;
    let fbid = sessionId.split("-")[0];
    return fbTypingOn(fbid)
      .then(() => {
        return model.getSesion(fbid);
      })
      .then(sesion => {
        session = sesion;
        return callFbUserAPI(session);
      })
      .then(first_name => {
        session.context.fullNameGreeting = utilsBot.buildGreeting(session);
        return model.setSesion(session);
      })
      .then( sesion => {
        return session.context;
      })
      .catch( error => {
        console.log("Error in getFullName " + error);
        session.context.fullNameGreeting = "Hola";
        return context;
      });
  }

Make sure you read all documentation in the official page, because if there isn't something, then you should do it. Also, there's already an implementation in python 2, I guess.


问:
Hibernate, dealing with Criteria and left outer join condition
I've an existing piece of code like follow:

```<code>Criteria crit = session.createCriteria(myClass);
crit.createAlias(TAB1, TAB1, JoinType.LEFT_OUTER_JOIN);
crit.createAlias(TAB1 + ".table2", TAB2, JoinType.LEFT_OUTER_JOIN);
crit.add(Restrictions.eq(TAB1 + ".deleted", Boolean.FALSE));
crit.add(Restrictions.eq(TAB2 + ".id", someId));
</code>```

This "generates" a sql query like follow:

```<code>SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id
WHERE tab1_.deleted=0
AND tab2_.id = 1234
</code>```

I need to put filters in the JOIN condition rather than in the WHERE clause.

To be clear, I need to have the following query:

```<code>SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id AND tab1_.deleted=0
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id AND AND tab2_.id = 1234
</code>```

How can I do this?

Thanks

答:
You are using:

```<code>crit.createAlias(${table}, ${alias}, ${joinType});
</code>```

You should be able to use:

```<code>crit.createAlias(${table}, ${alias}, ${joinType}, ${Criterion});
</code>```

Although I could not find an example in our codebase, I would expect this to work.

Body:
I've an existing piece of code like follow:

Criteria crit = session.createCriteria(myClass);
crit.createAlias(TAB1, TAB1, JoinType.LEFT_OUTER_JOIN);
crit.createAlias(TAB1 + ".table2", TAB2, JoinType.LEFT_OUTER_JOIN);
crit.add(Restrictions.eq(TAB1 + ".deleted", Boolean.FALSE));
crit.add(Restrictions.eq(TAB2 + ".id", someId));

This "generates" a sql query like follow:

SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id
WHERE tab1_.deleted=0
AND tab2_.id = 1234

I need to put filters in the JOIN condition rather than in the WHERE clause.

To be clear, I need to have the following query:

SELECT * FROM myClass this_
LEFT OUTER JOIN TAB1 tab1_ ON this_.id=tab1_.myClass_id AND tab1_.deleted=0
LEFT OUTER JOIN TAB2 tab2_ ON tab1_.tab2_id=tab2_.id AND AND tab2_.id = 1234

How can I do this?

Thanks

Body:
You are using:

crit.createAlias(${table}, ${alias}, ${joinType});

You should be able to use:

crit.createAlias(${table}, ${alias}, ${joinType}, ${Criterion});

Although I could not find an example in our codebase, I would expect this to work.


问:
Scaling a follower model
The problem is somewhat similar to twitter/facebook's:

followers and following

users add items

Subsequently you see the items added by all the people you are following.

Problem A: how to keep the query for items added by people you are following working well with growing datasets?

Problem B: we are seeing geographically disperse traffic. large userbase in the netherlands and brazil. any solution would probably need to allow for databases across multiple data centers.

We are running on a django/python stack. Already running edge server caching. (Anonymous users get the cached version, logged in user's version is run through a second level template parsing service first)

答:
Problem A: how to keep the query for items added by people you are following working well with growing datasets?

starting with a dataset of (who are my followers / who am i following); one could save these values as tuples and segmentate them across several SQL databases (though I doubt real segmentation is really needed even for twitter size databases). This would give the list of people who are followed. Secondly, a table for follower->items, sorted by follower could be easily queried; and also segmentated if needed given humongous datasets.

Problem B: we are seeing geographically disperse traffic. large userbase in the netherlands and brazil. any solution would probably need to allow for databases across multiple data centers.

one could designate a master database (cluster) and a slave databse (cluster), and replicate data from the master to the slave. However, this does imply the data is always saved to the master database. data queries can be done locally.

Another option is to run the database (clusters) in a master-master setup; but this is generally more trouble then it is worth.

Title: Scaling a follower model


答:
Pretty straight forward with flexbox.

wrap your animation in a container.
set display to flex
justify-content and align items to center

set height of body html and container to 100%

set font size to a view height so it remains responsive

```<code>body, html{
  height: 100%;
}

.container{
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.animation p{
  color: #D64933;
  font-family: 'Lato', cursive;
  font-size: 10vh;
  white-space: nowrap;
  overflow: hidden;
  width: 30em;
  animation: title 7s steps(70, end);
  margin-bottom: 40px;

}

@keyframes title{
  from { width: 0; opacity: 0.0;}
  to { opacity: 1.0; }
}

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
  <div class="animation">
    <p class="text-center">CRISTIANO RONALDO</p>
  </div>
</div>
</code>```

Title: How to make CSS typewriter effect responsive?

Body:
I made this CSS typewriter animation however, I'm unable to make it responsive.

The below is my code:

HTML:

CRISTIANO RONALDO

CSS:

.animation p{
  color: #D64933;
  font-family: 'Lato', cursive;
  font-size: 50px;
  white-space: nowrap;
  overflow: hidden;
  width: 30em;
  animation: title 7s steps(70, end);
  margin-bottom: 40px;

}

@keyframes title{
  from { width: 0; opacity: 0.0;}
  to { opacity: 1.0; }
}

I want the animation to start from center of the page and also be responsive. Any thoughts on how it can be achieved?

Link to CodePen

Body:
Pretty straight forward with flexbox.

wrap your animation in a container.
set display to flex
justify-content and align items to center

set height of body html and container to 100%

set font size to a view height so it remains responsive

body, html{
  height: 100%;
}

.container{
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.animation p{
  color: #D64933;
  font-family: 'Lato', cursive;
  font-size: 10vh;
  white-space: nowrap;
  overflow: hidden;
  width: 30em;
  animation: title 7s steps(70, end);
  margin-bottom: 40px;

}

@keyframes title{
  from { width: 0; opacity: 0.0;}
  to { opacity: 1.0; }
}

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
  <div class="animation">
    <p class="text-center">CRISTIANO RONALDO</p>
  </div>
</div>


问:
asp.net, deleting a cookie
This isn't the same as answered elsewhere (afaik), I'm documenting my answer for my own future use, but I'd also be interested in knowing more

I've created a cookie on the client in javascript like so

```<code>document.cookie = "Navigating=true";
</code>```

and I've tried removing it on the server by setting the expiry date with

```<code>string cookieName = "Navigating";
Response.Cookies.Remove(cookieName);

HttpCookie myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-2);
Response.Cookies.Add(myCookie);
</code>```

It doesn't work, here's the network trace

Note the name is wrong, it's cookie11 (I've removed the other cookies from the screenshot, it was the 11th cookie)

So now I set the value of the cookie to be something

```<code>myCookie.Value = "true";
</code>```

and try again, it still doesn't work, screenshot 2

The key is now right but the path is still wrong, so finally

```<code>        if (Request.Cookies[cookieName] != null)
        {
            //Response.Cookies.Remove(cookieName);

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie.Expires = DateTime.Now.AddDays(-2);
            myCookie.Value = "true";
            myCookie.Path = "";
            Response.Cookies.Add(myCookie);
        }
</code>```

and now the server removes the cookie correctly

This works, so there's no question, but I'd be interested in knowing why the javascript cookie doesn't have a path but the asp.net one does by default

答:
Javascript cookies are without path by default. As you wrote, this can cause mismatches when using ASP.NET with Javascript when handling cookies. By default, ASP.NET sets the cookie path as / (root). So - to ensure full compatability, when creating cookies via Javascript, you can set a path by simply using:

```<code>document.cookie="Navigating=true;path=/";
</code>```

Title: asp.net, deleting a cookie

Body:
This isn't the same as answered elsewhere (afaik), I'm documenting my answer for my own future use, but I'd also be interested in knowing more

I've created a cookie on the client in javascript like so

document.cookie = "Navigating=true";

and I've tried removing it on the server by setting the expiry date with

string cookieName = "Navigating";
Response.Cookies.Remove(cookieName);

HttpCookie myCookie = new HttpCookie(cookieName);
myCookie.Expires = DateTime.Now.AddDays(-2);
Response.Cookies.Add(myCookie);

It doesn't work, here's the network trace

Note the name is wrong, it's cookie11 (I've removed the other cookies from the screenshot, it was the 11th cookie)

So now I set the value of the cookie to be something

myCookie.Value = "true";

and try again, it still doesn't work, screenshot 2

The key is now right but the path is still wrong, so finally

        if (Request.Cookies[cookieName] != null)
        {
            //Response.Cookies.Remove(cookieName);

            HttpCookie myCookie = new HttpCookie(cookieName);
            myCookie.Expires = DateTime.Now.AddDays(-2);
            myCookie.Value = "true";
            myCookie.Path = "";
            Response.Cookies.Add(myCookie);
        }

and now the server removes the cookie correctly

This works, so there's no question, but I'd be interested in knowing why the javascript cookie doesn't have a path but the asp.net one does by default

Body:
Javascript cookies are without path by default. As you wrote, this can cause mismatches when using ASP.NET with Javascript when handling cookies. By default, ASP.NET sets the cookie path as / (root). So - to ensure full compatability, when creating cookies via Javascript, you can set a path by simply using:

document.cookie="Navigating=true;path=/";


问:
How to append string in java script with pre increment in same line
In JavaScript, I have 1 variable contains int value and one having String. Now I want to append the string like pre-increment the int variable like below code I am getting error

```<code>var count = 0;
var message = "value of Variable Count by increment  is:"+ ++count;
</code>```

答:
You can use Number as a standard function:

```<code>var count = 0;
var message = "value of Variable Count by increment  is:"+ Number(++count);
console.log(message);
</code>```

Body:
In JavaScript, I have 1 variable contains int value and one having String. Now I want to append the string like pre-increment the int variable like below code I am getting error

var count = 0;
var message = "value of Variable Count by increment  is:"+ ++count;

Body:
You can use Number as a standard function:

var count = 0;
var message = "value of Variable Count by increment  is:"+ Number(++count);
console.log(message);


问:
How to stop direct access to Form B unless Form A is completed in ASP.NET MVC?
This question applies to both ASP.NET webforms and MVC apps. I have a checkout process where there are two forms Form A (address page) and Form B (shopping cart page). The normal happy path works where the customer completes the Form A and then click submit button which takes him to the Form B.

The customer can accidently visit the Form B without ever visiting the Form A or completing the information. How can I find out whether the customer has completed the Form A if he access the Form B directly? If he has not completed the Form A, I want to redirect him to Form A. Is there a ASP.NET framework object that I can use for this purpose?

答:
The only foolproof way is to save something to a database that indicates that the particular user has completed Form A. This could be actually storing some entity that is created by Form A or just some sort of log. The key is that you'll need to associate with the user, which means the "user" must actually have an account and be logged in. If it's anonymous, there won't be any real way to track them.

With this set up, then, you'd simply check in your database that the user has a record indicating they've completed Form A in the controller action for Form B. If nothing exists, you redirect the user to Form A. Otherwise, you allow them to view Form B.

And alternate approach is to use Session or set a cookie to indicate that Form A has been completed. There's pros and cons to both of these, and neither is foolproof. With both Session and a cookie you can track anonymous users, so you don't have to force a login. However, Session is not a permanent data store. By default, it will expire after 20 minutes of no activity, and even if you bump that timeout up significantly, it's always going to be finite.

Additionally, depending on the session store you use, it can also be very volatile. In Proc is the default, as it requires no configuration. Everything is stored in memory, but if the server restarts, App Pool recycles, etc. then all the session data is lost. It is possible to configure it to use something like SQL Server, though, and that would be very stable. Either way, you'd still have the timeout issue to deal with.

With cookies, you can set a far-future expires cookie that would effectively be permanent. However, cookies are stored client-side and can be removed by the user. They can also be manipulated (either created manually or modified). This means if a malicious user figured out how you were tracking whether Form A had been completed, they could basically fake that, and make your site think they had completed Form A, when they had actually not. Now, whether any one would care enough to do that is an entirely different matter. Still, it's something to consider.

Finally, both Session and cookies can effectively be disabled by the user. Session actually uses a cookie to store the session id, so if the user disables cookies in their browser, neither approach will then work.

Your best bet is still forcing a login and storing something in a database to indicate that Form A has been completed by that authenticated user. However, if you can deal with or mitigate the downsides of using Session or cookies, then those might be viable options.


问:
ORACLE "before update" trigger does not fire when column is changed within another trigger
I am using ORACLE 12c.

On a table I have 2 triggers, both "before update".
One of the triggers fires while updating a column and within this trigger another column gets a new value. The second trigger should fire while updating this second column. But he did not.

```<code>create table TRIGGER_TEST
(
    col1 varchar2(64),
    col2 varchar2(64),
    col3 varchar2(64)
);

create or replace trigger TR_TRIGGER_TEST_1
before update of COL1 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_1');
    :new.col2 := 'only testing';
end;
/

create or replace trigger TR_TRIGGER_TEST_2
before update of COL2 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_2');
    :new.col3 := 'trigger_test_2 has fired';
end;
/

insert into TRIGGER_TEST values ('1_col1','1_col2','1_col3');
select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
1_col1               1_col2            1_col3
</code>```

After I have inserted the row I perform an UPDATE. And I expect COL1=
"now we will see", COL2="only testing" and COL3 = "trigger_test_2 has fired".

```<code>update TRIGGER_TEST set COL1 = 'now we will see';
</code>```

But what I get is this:

```<code>select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
now we will see      only testing      1_col3
</code>```

Can anybody explain this to me? I am really sure, that with former ORACLE versions this szenario has worked. But now it does not.

答: "update of COL2" in a trigger would mean update using a SQL statement such as UPDATE or MERGE, and not otherwise. Why dont you code the second trigger in the first ?</p>

Body:
I am using ORACLE 12c.

On a table I have 2 triggers, both "before update".
One of the triggers fires while updating a column and within this trigger another column gets a new value. The second trigger should fire while updating this second column. But he did not.

create table TRIGGER_TEST
(
    col1 varchar2(64),
    col2 varchar2(64),
    col3 varchar2(64)
);

create or replace trigger TR_TRIGGER_TEST_1
before update of COL1 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_1');
    :new.col2 := 'only testing';
end;
/

create or replace trigger TR_TRIGGER_TEST_2
before update of COL2 on TRIGGER_TEST
for each row
begin
    dbms_output.put_line('here we are in TR_TRIGGER_TEST_2');
    :new.col3 := 'trigger_test_2 has fired';
end;
/

insert into TRIGGER_TEST values ('1_col1','1_col2','1_col3');
select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
1_col1               1_col2            1_col3

After I have inserted the row I perform an UPDATE. And I expect COL1=
"now we will see", COL2="only testing" and COL3 = "trigger_test_2 has fired".

update TRIGGER_TEST set COL1 = 'now we will see';

But what I get is this:

select * from TRIGGER_TEST;

COL1                 COL2              COL3
----------------------------------------------------------------
now we will see      only testing      1_col3

Can anybody explain this to me? I am really sure, that with former ORACLE versions this szenario has worked. But now it does not.