问:
Changing the domain of a scale without shifting the entire plot
I am working on a realtime simulation. I generate an hour of data, but I only want to present a portion of that, and scroll the plot when I get close to the right edge. I define two signals:

```<code>    "signals": [
     {
      "name": "timeStart",
      "init":0
     },
     {
      "name": "timeEnd",
      "init": 480000 }
     ],
</code>```

and a scale

```<code>    "scales": [
        {
            "name": "x",
            "type": "time",
            "range": "width",
            "nice": "minute",
            "domainMin": {"signal": "timeStart"},
            "domainMax": {"signal": "timeEnd"},
            "zero": false
        }
</code>```

I have a filter in the marks to make sure I only display the inrange data.

In my javascript, I update the values of timeStart and timeEnd, and the plot now contains the subset of the data I want, but the entire plot is shifted right by the amount of time I've added to timeStart and timeEnd. Not what I want. Putting offsets on the axis doesn't work. What am I missing?

答:
I figured out what I was missing. Adding

```<code>    "padding": {"left":100, "right": 100, "top": 50, "bottom":100},
</code>```

fixed the problem.

Body:
I am working on a realtime simulation. I generate an hour of data, but I only want to present a portion of that, and scroll the plot when I get close to the right edge. I define two signals:

    "signals": [
     {
      "name": "timeStart",
      "init":0
     },
     {
      "name": "timeEnd",
      "init": 480000 }
     ],

and a scale

    "scales": [
        {
            "name": "x",
            "type": "time",
            "range": "width",
            "nice": "minute",
            "domainMin": {"signal": "timeStart"},
            "domainMax": {"signal": "timeEnd"},
            "zero": false
        }

I have a filter in the marks to make sure I only display the inrange data.

In my javascript, I update the values of timeStart and timeEnd, and the plot now contains the subset of the data I want, but the entire plot is shifted right by the amount of time I've added to timeStart and timeEnd. Not what I want. Putting offsets on the axis doesn't work. What am I missing?

Body:
I figured out what I was missing. Adding

    "padding": {"left":100, "right": 100, "top": 50, "bottom":100},

fixed the problem.


来源: stackexchange

问:
Keep Outlook App pane open
I am developing an Outlook App. That works fine, the app works perfect but we would like to keep the pane open when a user changes the email.

After googleing for some time I couldn't find a solution for this problem. Can you guys help?

答:
it is possible in outlook 2016. It is called pinnable Taskpane. You can see detail

https://blogs.msdn.microsoft.com/exchangedev/2017/01/26/pinnable-taskpane-in-outlook-2016/

ContentLicense: CC BY-SA 3.0

Title: Keep Outlook App pane open


问:
Find a file in HEAD from its old name in an old git commit
Say I know the name of a file in an old commit. But since then, it's been renamed or moved. How can I find it in the HEAD revision, and how can I look at its history from the known old commit up to the present HEAD?

For example, I know in Linux kernel version 3.8, there was a file drivers/usb/gadget/u_serial.c. But in more recent kernels I see that file is no longer there. I'd like to see the file's history from the point I knew in 3.8, up to the present HEAD.

答:
It's a bit sloppy, but the following script will trace the rename history starting from a file which no longer exists:

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

file=$1

while true
do
    # find the commit in which $file disappeared
    revhash=$(git log --pretty=%H --diff-filter=D -n 1 $revspec -- $file)

    # break out if $file has not disappeared since $revhash
    test -z "$revhash" && break
    revspec=${revhash}..
    echo -n "$revhash renamed $file => "

    # $revhash corresponds to the commit in which $file was removed, i.e. renamed
    # so we combine grep, cut, sed, and diff-tree to figure out what it was renamed to
    file=$(git diff-tree -M --numstat $revhash | grep '=>' | cut -f3- | sed "s/\(.*\){\(.*\) => \(.*\)}\(.*\)/\1\2\4 => \1\3\4/;s/\/\//\//g" | grep $file | sed "s/.* => //")
    echo "$file"
    test -z "$file" && echo -e "???\nNo rename target found, presumably file was deleted." && break
done
</code>```

and then you can git log --follow the last filename that's returned to you to trace its history.

Body:
It's a bit sloppy, but the following script will trace the rename history starting from a file which no longer exists:

#!/bin/sh

file=$1

while true
do
    # find the commit in which $file disappeared
    revhash=$(git log --pretty=%H --diff-filter=D -n 1 $revspec -- $file)

    # break out if $file has not disappeared since $revhash
    test -z "$revhash" && break
    revspec=${revhash}..
    echo -n "$revhash renamed $file => "

    # $revhash corresponds to the commit in which $file was removed, i.e. renamed
    # so we combine grep, cut, sed, and diff-tree to figure out what it was renamed to
    file=$(git diff-tree -M --numstat $revhash | grep '=>' | cut -f3- | sed "s/\(.*\){\(.*\) => \(.*\)}\(.*\)/\1\2\4 => \1\3\4/;s/\/\//\//g" | grep $file | sed "s/.* => //")
    echo "$file"
    test -z "$file" && echo -e "???\nNo rename target found, presumably file was deleted." && break
done

and then you can git log --follow the last filename that's returned to you to trace its history.


问:
Python: Adding Fields to Objects Dynamically
I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like:

```<code>user = object()
user.first_name = 'John'
user.last_name = 'Smith'
</code>```

When I execute that in Python command line interpretor I get:

```<code>AttributeError: 'object' object has no attribute 'first_name'
</code>```

Any idea?

答:
Try this:</p>

```<code>class Object:
    pass

obj = Object()
obj.x = 5
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am wondering whether it is possible to add fields to objects dynamically. For example, I want to be able to add something like:

user = object()
user.first_name = 'John'
user.last_name = 'Smith'

When I execute that in Python command line interpretor I get:

AttributeError: 'object' object has no attribute 'first_name'

Any idea?

Body:
Try this:

class Object:
    pass

obj = Object()
obj.x = 5


问:
Python: Checking if a key is part of a dictionary
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

```<code>commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands
</code>```

Then I have a function to check if the message that was send is indeed a command:

```<code>import string

def is_valid_command(command):
    return True if command in commands.keys() else False
</code>```

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

```<code>message = "!ping"
print(str(is_valid_command(message)))
>>> False
</code>```

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

```<code>def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()
</code>```

This result in this:

```<code>!ping
!random
input !ping
False
</code>```

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

```<code>try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False
</code>```

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?

答:
I am using python2.7  and your code returns True for me.

Instead of writing function, you can directly use :

message = "!ping"
print(commands.has_key(message))

Body:
I'm trying to make my own irc bot (for twitch) in Python. I have a dictionary with my commands:

commands = {

    '!ping': {
        'cooldown': 30,
        'return': '!pong'
    },

    '!random': {
        'cooldown': 30,
        'return': 'command',
        'argc': 2,
        'arg_username': True,
        'usage': '!random <min> <max>'
    }

} # End of commands

Then I have a function to check if the message that was send is indeed a command:

import string

def is_valid_command(command):
    return True if command in commands.keys() else False

So when i test this function out, it don't seems to work, and I don't know what I am doiing wrong:

message = "!ping"
print(str(is_valid_command(message)))
>>> False

I tried to change '!ping' inside the dictionary to "!ping", and virsa versa with the message, even deleted the '!' and it always says it's False.

Thanks in regards,
Laurens

EDIT:

def is_valid_command(command):
    for key in commands.keys():
        print(key)
    print("input " + str(command))
    print(command in commands.keys())
    return command in commands.keys()

This result in this:

!ping
!random
input !ping
False

EDIT2: @e4c5 wanted me to use try/except, as i quickly try it (inside that methode), it still return False

try:
    cmd = commands[command]
    print ('Try True')
    return True
except KeyError:
    print('Try False')
    return False

EDIT3: u'!ping' before fixed this (message = u'!ping'), but when I read a string from somewhere else, is there a function that does this unicoding?


问:
Undefined index // php
I'm stuck in my php script for a blog where I want to display the time and date for all the articles. I created a function but I don't know why it doesn't want to work:

```<code>function articles(){
    global $bdd;

    $articles = $bdd->query("SELECT id, titre, accroche, contenu, publication, image FROM articles");
    $articles = $articles->fetchAll();

    return $articles;
}

function formattage_date($publication){
    $publication = explode(" ", $publication);
    $date = explode("-", $publication[0]);
    $heure = explode(":", $publication[1]);

    $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

    $resultat = $date[2] . ' ' . $mois[$date[1]] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

    return $resultat;

}
</code>```

When I want to use $mois, php says: Notice: Undefined index: 03 in C:\wamp\www\entertheletter.dev\fonctions\blog.php on line 18

答:
Your problem is the following;

```<code>$mois[$date[1]]
</code>```

The date string from the database is zerofilled if the value is below 10. So assume that the month is january (janvier), you get 01 instead of 1. When accessing the $mois array with that index, it is not able to find it because 01 is not a valid index.

To fix this, remove the first 0 if the date is zerofilled. Or just cast it to int like

```<code>$mois[(int)$date[1]]
</code>```

Title: Undefined index // php

Body:
I'm stuck in my php script for a blog where I want to display the time and date for all the articles. I created a function but I don't know why it doesn't want to work:

function articles(){
    global $bdd;

    $articles = $bdd->query("SELECT id, titre, accroche, contenu, publication, image FROM articles");
    $articles = $articles->fetchAll();

    return $articles;
}

function formattage_date($publication){
    $publication = explode(" ", $publication);
    $date = explode("-", $publication[0]);
    $heure = explode(":", $publication[1]);

    $mois = ["", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "decembre"];

    $resultat = $date[2] . ' ' . $mois[$date[1]] . ' ' . $date[0] . ' à ' . $heure[0] . 'h' . $heure[1];

    return $resultat;

}

When I want to use $mois, php says: Notice: Undefined index: 03 in C:\wamp\www\entertheletter.dev\fonctions\blog.php on line 18

Body:
Your problem is the following;

$mois[$date[1]]

The date string from the database is zerofilled if the value is below 10. So assume that the month is january (janvier), you get 01 instead of 1. When accessing the $mois array with that index, it is not able to find it because 01 is not a valid index.

To fix this, remove the first 0 if the date is zerofilled. Or just cast it to int like

$mois[(int)$date[1]]


问:
Python import firebase module causes program to loop unexpectedly
I am using Python2.7 ,Python-firebase 1.2 .

If we comment firebase import then it is giving output only once or else it is giving multiple times.

```<code>from firebase import firebase

print "result"
</code>```

output:

```<code>result
result
result
result
</code>```

答:
That firebase module was written by bad programmers as it performs tasks that you don't explicitly ask for. For that reason, I would advise anybody to steer clear from using that module because you cannot know what other booby traps they might have in their code. Sure, they probably think this behavior is convenient, but convenience is everything but breaking the expectations of programmers (which is the one rule that absolutely every module writer has to follow) and if it was convenient this question wouldn't exist. They do say that it relies heavily on multiprocessing but they don't mention you won't have a say in it:

The interface heavily depends on the standart multiprocessing library when concurrency comes in. While creating an asynchronous call, an on-demand process pool is created and, the async method is executed by one of the idle process inside the pool. The pool remains alive until the main process dies. So every time you trigger an async call, you always use the same pool. When the method returns, the pool process ships the returning value back to the main process within the callback function provided.

So, all that being said... This happens because the main __init__.py of that module imports its async.py module, which in turn creates a multiprocessing.Pool (set to its _process_pool) with 5 fixed slots, and given nothing to work with you get 5 additional processes of your main script - hence, it prints out result 6 times (the main process and the 5 spawned sub-processes).

Bottom line - do not use this module. There are other alternatives, but if you absolutely have to - guard your code with a main process check:

```<code>if __name__ == "__main__":
    print("result")
</code>```

It will still spawn 5 subprocesses, and wait for all of them to finish (which is rather quick) but at least it won't execute your guarded code.

Body:
I am using Python2.7 ,Python-firebase 1.2 .

If we comment firebase import then it is giving output only once or else it is giving multiple times.

from firebase import firebase

print "result"

output:

result
result
result
result

Body:
That firebase module was written by bad programmers as it performs tasks that you don't explicitly ask for. For that reason, I would advise anybody to steer clear from using that module because you cannot know what other booby traps they might have in their code. Sure, they probably think this behavior is convenient, but convenience is everything but breaking the expectations of programmers (which is the one rule that absolutely every module writer has to follow) and if it was convenient this question wouldn't exist. They do say that it relies heavily on multiprocessing but they don't mention you won't have a say in it:

The interface heavily depends on the standart multiprocessing library when concurrency comes in. While creating an asynchronous call, an on-demand process pool is created and, the async method is executed by one of the idle process inside the pool. The pool remains alive until the main process dies. So every time you trigger an async call, you always use the same pool. When the method returns, the pool process ships the returning value back to the main process within the callback function provided.

So, all that being said... This happens because the main __init__.py of that module imports its async.py module, which in turn creates a multiprocessing.Pool (set to its _process_pool) with 5 fixed slots, and given nothing to work with you get 5 additional processes of your main script - hence, it prints out result 6 times (the main process and the 5 spawned sub-processes).

Bottom line - do not use this module. There are other alternatives, but if you absolutely have to - guard your code with a main process check:

if __name__ == "__main__":
    print("result")

It will still spawn 5 subprocesses, and wait for all of them to finish (which is rather quick) but at least it won't execute your guarded code.


问:
Laravel Auth Login by company name, username, and password
I like user to login by company name, username, and password - they need to enter all those fields.

username, and password fields are in the users table.
company_name are in the companies table.

username can be duplicated in the users table but each username is belong to different company name. company_id is defined in users table.

How can I Auth against company name, username, and password?

I had a look at the attemptLogin() method.

```<code> protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }
</code>```

I can't override this because I need to pass specific user that is belong to company then do auth check.

Update:

```<code>protected function authenticated(Request $request, User $user)
{
    if (!$user->enable) {
        Auth::logout();

        return redirect('/login')->with('status', 'Account is disabled');
    }

    return redirect()->intended('/');
}
</code>```

答:
Since username and company_name pair is unique, you can do this:

```<code>protected function attemptLogin(Request $request)
{
    $user = User::where('username', $request->username)
        ->where(function ($q) use ($request) {
            q->whereHas('company', function ($q) use ($request) {
                $q->where('company_name', $request->company_name);
            })
            ->orWhereHas('warehouse', function ($q) use ($request) {
                $q->where('company_name', $request->company_name);
            });
        })
        ->first();

    return !is_null($user) && \Hash::check($request->password, $user->password));
}

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        'company_name' => 'required',
        'username' => 'required|string',
        'password' => 'required|string',
    ]);
}
</code>```

Body:
I like user to login by company name, username, and password - they need to enter all those fields.

username, and password fields are in the users table.
company_name are in the companies table.

username can be duplicated in the users table but each username is belong to different company name. company_id is defined in users table.

How can I Auth against company name, username, and password?

I had a look at the attemptLogin() method.

 protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->has('remember')
        );
    }

I can't override this because I need to pass specific user that is belong to company then do auth check.

Update:

protected function authenticated(Request $request, User $user)
{
    if (!$user->enable) {
        Auth::logout();

        return redirect('/login')->with('status', 'Account is disabled');
    }

    return redirect()->intended('/');
}

Body:
Since username and company_name pair is unique, you can do this:

protected function attemptLogin(Request $request)
{
    $user = User::where('username', $request->username)
        ->where(function ($q) use ($request) {
            q->whereHas('company', function ($q) use ($request) {
                $q->where('company_name', $request->company_name);
            })
            ->orWhereHas('warehouse', function ($q) use ($request) {
                $q->where('company_name', $request->company_name);
            });
        })
        ->first();

    return !is_null($user) && \Hash::check($request->password, $user->password));
}

protected function validateLogin(Request $request)
{
    $this->validate($request, [
        'company_name' => 'required',
        'username' => 'required|string',
        'password' => 'required|string',
    ]);
}


问:
c# hosting a usercontrol in IE
Our web page is only available internally in our company and we am very intrested in being able to offer  interactive .net usercontrols on our departments website in the .Net 2.0 enviorment. I have been successful with embeding the object as so:

```<code><object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1"
        width="400" height="400">
    <param name="TestStr" value="Test Param String" />
</object>
</code>```

The control worked just fine and the value was passed to the control without issue.
But I had a problem with passing  subsequent values back to the embedded control

 attempt to Recieve event from control:

attempt to update control:

```<code><script type="text/javascript">
   function UpdateStr()
   {
      Object1.Text = "update string";
   }
</script>
</code>```

Reference:

http://www.15seconds.com/issue/030610.htm

http://windowsclient.net/articles/iesourcing.aspx

Questions:

Is this technology outdated? - if so is there a replacement

Should I just work with action script instead of trying this?

I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner?

(side note : - how do i paste html script examples?)

Thanks.

Brad

答: If the things that you are doing with the Windows Controls could be done with ASP.NET web controls instead, I recommend that you consider switching. You'll have much better control over the exchange of info from the client to the server.</p>

OwnerDisplayName: Brad

Title: c# hosting a usercontrol in IE

Body:
Our web page is only available internally in our company and we am very intrested in being able to offer  interactive .net usercontrols on our departments website in the .Net 2.0 enviorment. I have been successful with embeding the object as so:

<object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1"
        width="400" height="400">
    <param name="TestStr" value="Test Param String" />
</object>

The control worked just fine and the value was passed to the control without issue.
But I had a problem with passing  subsequent values back to the embedded control

 attempt to Recieve event from control:

attempt to update control:

Reference:

http://www.15seconds.com/issue/030610.htm

http://windowsclient.net/articles/iesourcing.aspx

Questions:

Is this technology outdated? - if so is there a replacement

Should I just work with action script instead of trying this?

I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner?

(side note : - how do i paste html script examples?)

Thanks.

Brad

LastEditorDisplayName: Benoit

OwnerDisplayName: David Thomas Garcia


问:
how to direct different message to diferent Topics in Kafka
I have producers with different topics configured to it. and all the producers are listening to a same file, which gets multiple events per sec, all the events are different from each other. please find the below sample.

A event1
B event2
C event3
A event4
C event5
B event6
D event7
E event8
F event9
E event10

considering each event as 1 message. how to direct different messages to their corresponding topics from the list of producers that are listening to the event file.

Thanks.
Regards,

答:
Have you looked at the Kafka documentation?

https://kafka.apache.org/documentation/#producerapi

https://kafka.apache.org/0102/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html

Assuming that A, B, etc. are the names of the desired destination topics, simply replace "my-topic" with A etc. in the code below:

```<code>Producer<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<String, String>("my-topic", "my-key", "my-value");
</code>```

Body:
Have you looked at the Kafka documentation?

https://kafka.apache.org/documentation/#producerapi

https://kafka.apache.org/0102/javadoc/index.html?org/apache/kafka/clients/producer/KafkaProducer.html

Assuming that A, B, etc. are the names of the desired destination topics, simply replace "my-topic" with A etc. in the code below:

Producer<String, String> producer = new KafkaProducer<>(props);
producer.send(new ProducerRecord<String, String>("my-topic", "my-key", "my-value");


问:
Python Boolean "In" and "Or" Statements Together
Say I want to check if either of two given elements are present in a given tuple, like:

```<code>if foo in my_tuple or bar in my_tuple:
</code>```

Is there a more pythonic way to frame this expression? Specifically, if I want to check for several elements, the statements becomes annoyingly long. I've tried

```<code>if (foo or bar) in my_tuple:
</code>```

But this chooses foo over bar and checks only for foo. Would appreciate any inputs on this.

答:
This is pythonic and would work:</p>

```<code>if any(v in my_tuple for v in [foo, bar, eggs, spam, parrot, lumberjack]):
</code>```

Body:
Say I want to check if either of two given elements are present in a given tuple, like:

if foo in my_tuple or bar in my_tuple:

Is there a more pythonic way to frame this expression? Specifically, if I want to check for several elements, the statements becomes annoyingly long. I've tried

if (foo or bar) in my_tuple:

But this chooses foo over bar and checks only for foo. Would appreciate any inputs on this.

Body:
This is pythonic and would work:

if any(v in my_tuple for v in [foo, bar, eggs, spam, parrot, lumberjack]):


问:
HTTP Status [404] ? [Not Found] for /login in spring security
I'm having a problem with the customized login form in spring security. I'm new with the spring mvc. As of now I'm having a 404 Not found when clicking the submit button in my login form.

CODE BELOW:

headerindex.jsp

```<code><form class="navbar-form navbar-right" method="post" action="<c:url value="/login" />" id="form_login">
    <div class="form-group">
        <input type="text" class="form-control" name="username"
            placeholder="Username">
    </div>
    <div class="form-group">
        <input type="text" class="form-control" name="password"
            placeholder="Password">
    </div>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <button type="submit" class="btn btn-default">Sign In</button>
</form>
</code>```

security-context.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="select username, password, enabled from user where binary username = ?" />

        </security:authentication-provider>
    </security:authentication-manager>
    <security:http use-expressions="true">
        <security:intercept-url pattern="/" access="permitAll" />
        <security:intercept-url pattern="/index" access="permitAll" />
        <security:intercept-url pattern="/login" access="permitAll" />
        <security:intercept-url pattern="/**" access="denyAll" />
        <security:form-login authentication-success-forward-url="/home"
            login-page="/" password-parameter="password"
            username-parameter="username"
            authentication-failure-forward-url="/login?error=true" />
        <security:logout logout-success-url="/loggedout" />
        <security:access-denied-handler error-page="/denied" />
    </security:http>
    <security:global-method-security secured-annotations="enabled"></security:global-method-security>
</beans>
</code>```

UsersDao.java

```<code>@Component("usersDao")
public class UsersDao {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SessionFactory sessionFactory;

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public void create(User user) {

        System.out.println(user);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        session().save(user);
    }

    public boolean exists(String username) {

        return getUser(username) != null;
    }

    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {

        return session().createQuery("from user").list();

    }

    public User getUser(String username) {
        Criteria criteria = session().createCriteria(User.class);
        criteria.add(Restrictions.idEq(username));
        return (User)criteria.uniqueResult();
    }
</code>```

答:
I solved my problem. After checking my DAO codes I found that I was using the PasswordEncoder and I didn't set it in the bean of the security-context.xml. I just commented out the PasswordEncoder and I can now login. :)

UsersDao.java

```<code>@Component("usersDao")
public class UsersDao {

    //@Autowired
    //private PasswordEncoder passwordEncoder;

    @Autowired
    private SessionFactory sessionFactory;

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public void create(User user) {

        System.out.println(user);
        //user.setPassword(passwordEncoder.encode(user.getPassword()));
        session().save(user);
    }

    public boolean exists(String username) {

        return getUser(username) != null;
    }

    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {

        return session().createQuery("from user").list();

    }

    public User getUser(String username) {
        Criteria criteria = session().createCriteria(User.class);
        criteria.add(Restrictions.idEq(username));
        return (User)criteria.uniqueResult();
    }
</code>```

Body:
I'm having a problem with the customized login form in spring security. I'm new with the spring mvc. As of now I'm having a 404 Not found when clicking the submit button in my login form.

CODE BELOW:

headerindex.jsp

<form class="navbar-form navbar-right" method="post" action="<c:url value="/login" />" id="form_login">

        <input type="text" class="form-control" name="username"
            placeholder="Username">

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

    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <button type="submit" class="btn btn-default">Sign In</button>
</form>

security-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service data-source-ref="dataSource"
                users-by-username-query="select username, password, enabled from user where binary username = ?" />

        </security:authentication-provider>
    </security:authentication-manager>
    <security:http use-expressions="true">
        <security:intercept-url pattern="/" access="permitAll" />
        <security:intercept-url pattern="/index" access="permitAll" />
        <security:intercept-url pattern="/login" access="permitAll" />
        <security:intercept-url pattern="/**" access="denyAll" />
        <security:form-login authentication-success-forward-url="/home"
            login-page="/" password-parameter="password"
            username-parameter="username"
            authentication-failure-forward-url="/login?error=true" />
        <security:logout logout-success-url="/loggedout" />
        <security:access-denied-handler error-page="/denied" />
    </security:http>
    <security:global-method-security secured-annotations="enabled"></security:global-method-security>
</beans>

UsersDao.java

@Component("usersDao")
public class UsersDao {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SessionFactory sessionFactory;

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public void create(User user) {

        System.out.println(user);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        session().save(user);
    }

    public boolean exists(String username) {

        return getUser(username) != null;
    }

    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {

        return session().createQuery("from user").list();

    }

    public User getUser(String username) {
        Criteria criteria = session().createCriteria(User.class);
        criteria.add(Restrictions.idEq(username));
        return (User)criteria.uniqueResult();
    }

Body:
I solved my problem. After checking my DAO codes I found that I was using the PasswordEncoder and I didn't set it in the bean of the security-context.xml. I just commented out the PasswordEncoder and I can now login. :)

UsersDao.java

@Component("usersDao")
public class UsersDao {

    //@Autowired
    //private PasswordEncoder passwordEncoder;

    @Autowired
    private SessionFactory sessionFactory;

    public Session session() {
        return sessionFactory.getCurrentSession();
    }

    @Transactional
    public void create(User user) {

        System.out.println(user);
        //user.setPassword(passwordEncoder.encode(user.getPassword()));
        session().save(user);
    }

    public boolean exists(String username) {

        return getUser(username) != null;
    }

    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {

        return session().createQuery("from user").list();

    }

    public User getUser(String username) {
        Criteria criteria = session().createCriteria(User.class);
        criteria.add(Restrictions.idEq(username));
        return (User)criteria.uniqueResult();
    }


问:
How can I use checkboxGroupInput in Shiny to control several reactive layers in a ggplot2 plot efficiently?
I have made three reactive layers in my graph. In the reproducible example below, the graph starts with function1 drawn. If I check function2, shiny recalculates and redraws function1 and function2. Then if I tick function3, all 3 functions are recalculated and redrawn.

Say the functions I want to run are very long inferences that take several minutes each.

How can I make it so that when I check (or uncheck) one function, shiny does not recalculate and redraw all checked functions?

In the code below, I have included print statements which show that each reactive is run each time renderPlot is called (which is when input$fun changes).

```<code>library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1))
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    fn1 <- reactive({
      print("we are in fn1 <- reactive({})")
      if (1 %in% input$fun ) {
        geom_line(mapping = aes(x, y=x^2), color="blue") }
    })

    fn2 <- reactive({
      print("we are in fn2 <- reactive({})")
      if (2 %in% input$fun)  {
        geom_line(mapping = aes(x, y=x^2 + x), color="red") }
    })

    fn3 <- reactive({
      print("we are in fn3 <- reactive({})")
      if (3 %in% input$fun) {
        geom_line(mapping = aes(x, y=x^2 - x), color="green") }
    })

    output$plot <- renderPlot({

      cat("\n we are in output$plot <-  renderPlot({}) \n")
      ggplot() + fn1() + fn2() + fn3()
    })
  })
))
</code>```

I can achieve this efficiency using single checkboxes (checkboxInput) but I would prefer not to use single checkboxes. Single checkboxes don’t look as good, unless there is a way to make them look more like checkbox Group Inputs?

I have been trying to work this out and searching SO for some time. I would be very grateful for any help with this!!!

EDIT
Here is some code in response to @Jimbou ’s shiny code using base R plot() and lines(). Please see my comment below the shiny code @Jimbou provided.

```<code>    output$plot <- renderPlot({
  cat("\n we are in output$plot <- renderPlot({}) \n")
  plot(NULL, xlim = c(0,10), ylim = c(0,100))
  if(1 %in% input$fun) {
    print("we are in  if(1 %in% input$fun){} ")
    lines(x=x, y=x^2, col=2)
  }
  if(2 %in% input$fun) {
    print("we are in  if(2 %in% input$fun){} ")
    lines(x=x, y=x^2 + x, col=3)
  }
  if(3 %in% input$fun) {
    print("we are in  if(3 %in% input$fun){} ")
    lines(x=x, y=x^2 - x, col=4)
  }
})
</code>```

答:
I think the closest you can get is to delay the processing of your layers until you click an action button to explicitly tell the server when to start processing the plot.</p>

```<code>library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1)),
        actionButton(inputId = "btn_update_plot",
                     label = "Update Plot")
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    p <- eventReactive(
      input$btn_update_plot,
      {
        ggp = ggplot()

        if (1 %in% input$fun )
        {
          ggp <- ggp + geom_line(mapping = aes(x, y=x^2), color="blue")
        }

        if (2 %in% input$fun)
        {
          ggp <- ggp + geom_line(mapping = aes(x, y=x^2 + x), color="red")
        }

        if (3 %in% input$fun)
        {
          ggp <- ggp + geom_line(mapping = aes(x, y=x^2 - x), color="green")
        }

        ggp
      }
    )

    output$plot <- renderPlot({
      print("we are in output$plot <-  renderPlot({})")
      p()
    })
  })
))
</code>```

Body:
I have made three reactive layers in my graph. In the reproducible example below, the graph starts with function1 drawn. If I check function2, shiny recalculates and redraws function1 and function2. Then if I tick function3, all 3 functions are recalculated and redrawn.

Say the functions I want to run are very long inferences that take several minutes each.

How can I make it so that when I check (or uncheck) one function, shiny does not recalculate and redraw all checked functions?

In the code below, I have included print statements which show that each reactive is run each time renderPlot is called (which is when input$fun changes).

library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1))
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    fn1 <- reactive({
      print("we are in fn1 <- reactive({})")
      if (1 %in% input$fun ) {
        geom_line(mapping = aes(x, y=x^2), color="blue") }
    })

    fn2 <- reactive({
      print("we are in fn2 <- reactive({})")
      if (2 %in% input$fun)  {
        geom_line(mapping = aes(x, y=x^2 + x), color="red") }
    })

    fn3 <- reactive({
      print("we are in fn3 <- reactive({})")
      if (3 %in% input$fun) {
        geom_line(mapping = aes(x, y=x^2 - x), color="green") }
    })

    output$plot <- renderPlot({

      cat("\n we are in output$plot <-  renderPlot({}) \n")
      ggplot() + fn1() + fn2() + fn3()
    })
  })
))

I can achieve this efficiency using single checkboxes (checkboxInput) but I would prefer not to use single checkboxes. Single checkboxes don’t look as good, unless there is a way to make them look more like checkbox Group Inputs?

I have been trying to work this out and searching SO for some time. I would be very grateful for any help with this!!!

EDIT
Here is some code in response to @Jimbou ’s shiny code using base R plot() and lines(). Please see my comment below the shiny code @Jimbou provided.

    output$plot <- renderPlot({
  cat("\n we are in output$plot <- renderPlot({}) \n")
  plot(NULL, xlim = c(0,10), ylim = c(0,100))
  if(1 %in% input$fun) {
    print("we are in  if(1 %in% input$fun){} ")
    lines(x=x, y=x^2, col=2)
  }
  if(2 %in% input$fun) {
    print("we are in  if(2 %in% input$fun){} ")
    lines(x=x, y=x^2 + x, col=3)
  }
  if(3 %in% input$fun) {
    print("we are in  if(3 %in% input$fun){} ")
    lines(x=x, y=x^2 - x, col=4)
  }
})

Body:
I think the closest you can get is to delay the processing of your layers until you click an action button to explicitly tell the server when to start processing the plot.

library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1)),
        actionButton(inputId = "btn_update_plot",
                     label = "Update Plot")
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    p <- eventReactive(
      input$btn_update_plot,
      {
        ggp = ggplot()

        if (1 %in% input$fun )
        {
          ggp <- ggp + geom_line(mapping = aes(x, y=x^2), color="blue")
        }

        if (2 %in% input$fun)
        {
          ggp <- ggp + geom_line(mapping = aes(x, y=x^2 + x), color="red")
        }

        if (3 %in% input$fun)
        {
          ggp <- ggp + geom_line(mapping = aes(x, y=x^2 - x), color="green")
        }

        ggp
      }
    )

    output$plot <- renderPlot({
      print("we are in output$plot <-  renderPlot({})")
      p()
    })
  })
))


答:
If you get a lot of elements that you need to compare it's better to check intersection of set objects:

```<code>if {foo, bar, other_vars} & set(my_tuple):
</code>```

BUT keep in mind that values should be hashable, if not, look at Rory Daulton answer

Title: Python Boolean "In" and "Or" Statements Together

Body:
If you get a lot of elements that you need to compare it's better to check intersection of set objects:

if {foo, bar, other_vars} & set(my_tuple):

BUT keep in mind that values should be hashable, if not, look at Rory Daulton answer


问:
Multiple UIPickerView in the same UIView
I'm a complete beginner on iOS dev and I want to create a little iOS application. On this application, 3 UIPickerViews are supposed to display different data.

My problem is on the display. I'm used to dev on Android or Windows phone and I don't understand how to populate the UIPickerViews with different data.

This is the code I have already written:

```<code>//
//  ViewController.swift
//  iphoneVersion
//
//  Created by fselva on 13/05/2015.
//  Copyright (c) 2015 fselva. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate{

@IBOutlet weak var pickerView1: UIPickerView!
@IBOutlet weak var pickerView2: UIPickerView!
@IBOutlet weak var pickerView3: UIPickerView!

var test = ["Todo","Waiting","Maybe","Inbox","Note"]

var test2 = ["@Office","@Computer","@Home","@Meeting", "@Read", "@Achat", "@Call"]

override func viewDidLoad() {
    super.viewDidLoad()
    pickerView1.tag = 1
    pickerView2.tag = 2
    pickerView3.tag = 3
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView : UIPickerView!) -> Int{
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
    if pickerView2.tag == 2 {
        return test.count
    } else if pickerView3 == 3{
        return test2.count
    }
    return 1
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

    if pickerView2 == 2 {
        return test[row]
    } else if pickerView3 == 3{
        return test2[row]
    }
        return ""
}

}
</code>```

@IBOutlet weak var pickerView1: UIPickerView!has been automatically created by Ctrl+Click from the storyboard to the ViewController.swift.

The first UIPickerView is currently supposed to display nothing.  The second one is supposed to display test and the third one displays test2.

After hours of investigation on internet, I have heard about tags to define who must display what, but it doesn't work.

Am I doing something wrong, am I missing something somewhere?

答:
Here is Full Source Multiple UIPickerView in the TextField in Swift 3

```<code>class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var textFiel1: UITextField!

@IBOutlet weak var textFiel_2: UITextField!

 let piker1 = UIPickerView()
 let piker2 = UIPickerView()

let country = ["Ban","Ind","PK"]
let number = ["1","2","3"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    piker1.dataSource = self
    piker1.delegate = self

    piker2.dataSource = self
    piker2.delegate = self

    piker1.tag = 1
    piker2.tag = 2;

     textFiel1.inputView = piker1
      textFiel_2.inputView = piker2

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if pickerView == piker1 {
        return country.count

    } else if pickerView == piker2{
         return number.count
    }

    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if pickerView == piker1 {
        return country[row]

    } else if pickerView == piker2{
         return number[row]
    }
    return ""
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == piker1 {
        textFiel1.text = country[row]
          self.view.endEditing(false)
    } else if pickerView == piker2{
        textFiel_2.text = number[row]
          self.view.endEditing(false)
    }
}

}
</code>```

Body:
I'm a complete beginner on iOS dev and I want to create a little iOS application. On this application, 3 UIPickerViews are supposed to display different data.

My problem is on the display. I'm used to dev on Android or Windows phone and I don't understand how to populate the UIPickerViews with different data.

This is the code I have already written:

//
//  ViewController.swift
//  iphoneVersion
//
//  Created by fselva on 13/05/2015.
//  Copyright (c) 2015 fselva. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UIPickerViewDelegate{

@IBOutlet weak var pickerView1: UIPickerView!
@IBOutlet weak var pickerView2: UIPickerView!
@IBOutlet weak var pickerView3: UIPickerView!

var test = ["Todo","Waiting","Maybe","Inbox","Note"]

var test2 = ["@Office","@Computer","@Home","@Meeting", "@Read", "@Achat", "@Call"]

override func viewDidLoad() {
    super.viewDidLoad()
    pickerView1.tag = 1
    pickerView2.tag = 2
    pickerView3.tag = 3
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponentsInPickerView(pickerView : UIPickerView!) -> Int{
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
    if pickerView2.tag == 2 {
        return test.count
    } else if pickerView3 == 3{
        return test2.count
    }
    return 1
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {

    if pickerView2 == 2 {
        return test[row]
    } else if pickerView3 == 3{
        return test2[row]
    }
        return ""
}

}

@IBOutlet weak var pickerView1: UIPickerView!has been automatically created by Ctrl+Click from the storyboard to the ViewController.swift.

The first UIPickerView is currently supposed to display nothing.  The second one is supposed to display test and the third one displays test2.

After hours of investigation on internet, I have heard about tags to define who must display what, but it doesn't work.

Am I doing something wrong, am I missing something somewhere?

Body:
Here is Full Source Multiple UIPickerView in the TextField in Swift 3

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

@IBOutlet weak var textFiel1: UITextField!

@IBOutlet weak var textFiel_2: UITextField!

 let piker1 = UIPickerView()
 let piker2 = UIPickerView()

let country = ["Ban","Ind","PK"]
let number = ["1","2","3"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    piker1.dataSource = self
    piker1.delegate = self

    piker2.dataSource = self
    piker2.delegate = self

    piker1.tag = 1
    piker2.tag = 2;

     textFiel1.inputView = piker1
      textFiel_2.inputView = piker2

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

    if pickerView == piker1 {
        return country.count

    } else if pickerView == piker2{
         return number.count
    }

    return 1
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if pickerView == piker1 {
        return country[row]

    } else if pickerView == piker2{
         return number[row]
    }
    return ""
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    if pickerView == piker1 {
        textFiel1.text = country[row]
          self.view.endEditing(false)
    } else if pickerView == piker2{
        textFiel_2.text = number[row]
          self.view.endEditing(false)
    }
}

}


问:
How to set Excel read only file/sheet by C# interop?
I need to perform this operation by c# Excel Interop:

The step is:

File->Informations-> Authorizations -> Protect current sheet

Step 1:

Step 2: set true/false the follow check boxes and insert a Password for a current sheet

I don't find any information to do it.

答:
My Italian is non-existant. If you are asking how to save an Excel workbook with a password, you are looking for the Workbook.SaveAs documentation - should look something like this:

```<code>myWorkBook.SaveAs(myfilename, format, password)
</code>```

Edit - To protect a specific sheet, use the WorkSheet.Protect method.

Body:
My Italian is non-existant. If you are asking how to save an Excel workbook with a password, you are looking for the Workbook.SaveAs documentation - should look something like this:

myWorkBook.SaveAs(myfilename, format, password)

Edit - To protect a specific sheet, use the WorkSheet.Protect method.


问:
Can not load Office Addin in Word online when set Requirement Set in manifest file
I load office add-in js file from CDN with this link: https://appsforoffice.microsoft.com/lib/1/hosted/office.js

As document said this is the latest version of the office api. In my add-in, I only use Office.context.document.setSelectedDataAsync which is belong to Selection Requirements Set to replace value from my Word

I configure the manifest file with this code

```<code><Requirements>
   <Sets DefaultMinVersion="1.1">
      <Set Name="Selection" MinVersion="1.1"/>
   </Sets>
   <Methods>
      <Method Name="Document.setSelectedDataAsync"/>
   </Methods>
</Requirements>
</code>```

When I publish the manifest file in Office 365, the add-in does not appear in the Admin Managed Tab (I'm testing in Word online and Word 2016)

I've tried to remove Methods Tag but the add-in still not show up. When I remove the Requirements tag, the add-in shows up again.

What I've done wrong here? Does I use wrong version of Office Api or the config in manifest is wrong?

答: The extraction process needs to tag it for Office Online for Word and it doesn't appear to be happening properly. I will need to follow up on this</p>

Body:
I load office add-in js file from CDN with this link: https://appsforoffice.microsoft.com/lib/1/hosted/office.js

As document said this is the latest version of the office api. In my add-in, I only use Office.context.document.setSelectedDataAsync which is belong to Selection Requirements Set to replace value from my Word

I configure the manifest file with this code

<Requirements>
   <Sets DefaultMinVersion="1.1">
      <Set Name="Selection" MinVersion="1.1"/>
   </Sets>
   <Methods>
      <Method Name="Document.setSelectedDataAsync"/>
   </Methods>
</Requirements>

When I publish the manifest file in Office 365, the add-in does not appear in the Admin Managed Tab (I'm testing in Word online and Word 2016)

I've tried to remove Methods Tag but the add-in still not show up. When I remove the Requirements tag, the add-in shows up again.

What I've done wrong here? Does I use wrong version of Office Api or the config in manifest is wrong?


问:
Pass a value to an on-click function
I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an on-click function.

The first script shows the API running

```<code>  var base_url      = window.location.origin,
      hash_bang     = "/#/sign-up?referral=",
      login         = "login",
      api_key       = "api_key";

  function get_short_url(login, api_key, func, value) {
      var value = document.getElementById('input-refcode').value;

      $.getJSON(
          "https://api-ssl.bitly.com//v3/shorten?callback=?",
          {
              "format": "json",
              "apiKey": api_key,
              "login": login,
              "longUrl": base_url + hash_bang + value
          },

          function(response)
          {
              func(response.data.url);
          }
      );
  }
</code>```

Second is a script that shares a text via Twitter using on-click

```<code>  $('#twitter').on('click', function() {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
      win.focus();

  });
</code>```

Is there a way to get the output from the first function get_short_url then bind it in a on-click like this for example

```<code>  $('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
      win.focus();
  });
</code>```

I tried this solution but the browser flagged the function as a pop-up

```<code>  $('#twitter').on('click', function() {

     var base_url          = window.location.origin,
         hash_bang_twitter = "/%23/sign-up?referral=",
         referral_code      = document.getElementById('input-refcode').value;

       get_short_url(login, api_key, function(short_url) {
           win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
           win.focus();
       });
  });
</code>```

答:
I'm no pro at js, but this seems fairly simple.  I have not tested this.</p>

```<code>var base_url      = window.location.origin,
    hash_bang     = "/#/sign-up?referral=",
    login         = "login",
    api_key       = "api_key";

function get_short_url() {
    var value = ('#input-refcode').val();
    var result = '';
    $.getJSON(
        "https://api-ssl.bitly.com//v3/shorten?callback=?",
        {
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": base_url + hash_bang + value
        },

        function(response)
        {
            result = response.data.url;
        }
    );
    return result;
};

$('#twitter').on('click', function() {
    var short_url = get_short_url(function(short_url)
    if (short_url !== '') {
        win = window.open('https://twitter.com/intent/tweet?text=' + encodeURI("Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us! " + short_url));
        win.focus();
    }

});
</code>```

Title: Pass a value to an on-click function

Body:
I have this API that I'm currently using to output a short URL or URL generator. Is there a way to pass the output to an on-click function.

The first script shows the API running

  var base_url      = window.location.origin,
      hash_bang     = "/#/sign-up?referral=",
      login         = "login",
      api_key       = "api_key";

  function get_short_url(login, api_key, func, value) {
      var value = document.getElementById('input-refcode').value;

      $.getJSON(
          "https://api-ssl.bitly.com//v3/shorten?callback=?",
          {
              "format": "json",
              "apiKey": api_key,
              "login": login,
              "longUrl": base_url + hash_bang + value
          },

          function(response)
          {
              func(response.data.url);
          }
      );
  }

Second is a script that shares a text via Twitter using on-click

  $('#twitter').on('click', function() {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!', '_blank');
      win.focus();

  });

Is there a way to get the output from the first function get_short_url then bind it in a on-click like this for example

  $('#twitter').on('click', get_short_url(login, api_key, function(short_url)) {
      win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us!' + short_url, '_blank');
      win.focus();
  });

I tried this solution but the browser flagged the function as a pop-up

  $('#twitter').on('click', function() {

     var base_url          = window.location.origin,
         hash_bang_twitter = "/%23/sign-up?referral=",
         referral_code      = document.getElementById('input-refcode').value;

       get_short_url(login, api_key, function(short_url) {
           win = window.open('https://twitter.com/intent/tweet?text=Get Free Rides at Electric Studio! Sign up ' + short_url + ' to purchase your first timer package! After your first ride, you get 1 ride on us!' + ' https://www.electricstudio.ph/', '_blank');
           win.focus();
       });
  });

Body:
I'm no pro at js, but this seems fairly simple.  I have not tested this.

var base_url      = window.location.origin,
    hash_bang     = "/#/sign-up?referral=",
    login         = "login",
    api_key       = "api_key";

function get_short_url() {
    var value = ('#input-refcode').val();
    var result = '';
    $.getJSON(
        "https://api-ssl.bitly.com//v3/shorten?callback=?",
        {
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": base_url + hash_bang + value
        },

        function(response)
        {
            result = response.data.url;
        }
    );
    return result;
};

$('#twitter').on('click', function() {
    var short_url = get_short_url(function(short_url)
    if (short_url !== '') {
        win = window.open('https://twitter.com/intent/tweet?text=' + encodeURI("Get Free Rides at Electric Studio! Sign up to purchase your first timer package! After your first ride, you get 1 ride on us! " + short_url));
        win.focus();
    }

});


问:
Comparing the Most Significant Bit of two numbers: ==, <, <=
Is there a quick bit operation to implement msb_equal: a function to check if two numbers have the same most significant bit?

For example, 0b000100 and 0b000111 both have 4 as their most significant bit value, so they are most msb_equal. In contrast 0b001111 has 8 as the MSB value, and 0b010000 has 16 as it's MSB value, so the pair are not msb_equal.

Similarly, are there fast ways to compute <, and <=?

Examples:

```<code>msb_equal(0, 0) => true
msb_equal(2, 3) => true

msb_equal(0, 1) => false
msb_equal(1, 2) => false
msb_equal(3, 4) => false

msb_equal(128, 255) => true
</code>```

A comment asks why 0 and 1 are not msb_equal. My view on this is that if I write out two numbers in binary, they are msb_equal when the most significant 1 bit in each is the same bit.

Writing out 2 & 3:

```<code>2 == b0010
3 == b0011
</code>```

In this case, the top most 1 is the same in each number

Writing out 1 & 0:

```<code>1 == b0001
0 == b0000
</code>```

Here, the top most 1s are not the same.

It could be said that as 0 has no top most set bit, msb_equal(0,0) is ambiguous. I'm defining it as true: I feel this is helpful and consistent.

答:
Yes, there are fast bit based operations to compute MSB equality and inequalities.

Note on syntax

I'll provide implementations using c language syntax for bitwise and logical operators:

| – bitwise OR. || – logical OR.

& – bitwise AND. && – logical AND.

^ – bitwise XOR.

==

```<code>msb_equal(l, r) -> bool
{
  return (l^r) <= (l&r)
}
</code>```

<

This is taken from the Wikipedia page on the Z Order Curve (which is awesome):

```<code>msb_less_than(l, r) -> bool
{
  (l < r) && (l < l^r)
}
</code>```

<=

```<code>msb_less_than_equal(l, r) -> bool
{
  (l < r) || (l^r <= l&r)
}
</code>```

Body:
Is there a quick bit operation to implement msb_equal: a function to check if two numbers have the same most significant bit?

For example, 0b000100 and 0b000111 both have 4 as their most significant bit value, so they are most msb_equal. In contrast 0b001111 has 8 as the MSB value, and 0b010000 has 16 as it's MSB value, so the pair are not msb_equal.

Similarly, are there fast ways to compute <, and <=?

Examples:

msb_equal(0, 0) => true
msb_equal(2, 3) => true

msb_equal(0, 1) => false
msb_equal(1, 2) => false
msb_equal(3, 4) => false

msb_equal(128, 255) => true

A comment asks why 0 and 1 are not msb_equal. My view on this is that if I write out two numbers in binary, they are msb_equal when the most significant 1 bit in each is the same bit.

Writing out 2 & 3:

2 == b0010
3 == b0011

In this case, the top most 1 is the same in each number

Writing out 1 & 0:

1 == b0001
0 == b0000

Here, the top most 1s are not the same.

It could be said that as 0 has no top most set bit, msb_equal(0,0) is ambiguous. I'm defining it as true: I feel this is helpful and consistent.

Body:
Yes, there are fast bit based operations to compute MSB equality and inequalities.

Note on syntax

I'll provide implementations using c language syntax for bitwise and logical operators:

| – bitwise OR. || – logical OR.

& – bitwise AND. && – logical AND.

^ – bitwise XOR.

==

msb_equal(l, r) -> bool
{
  return (l^r) <= (l&r)
}

<

This is taken from the Wikipedia page on the Z Order Curve (which is awesome):

msb_less_than(l, r) -> bool
{
  (l < r) && (l < l^r)
}

<=

msb_less_than_equal(l, r) -> bool
{
  (l < r) || (l^r <= l&r)
}


问:
Get selected value from database table?
im new in field of manipulating databases so i have a problem.
So after making a query to select all values from a table row with something like :

```<code>while($row = $result->fetch_assoc()) { }
</code>```

For example if table has names in it we would get :

```<code>John
Bob
Steve
Mark
</code>```

If we put these results in a form of a link or a button, is there any way to get their value?

i tried something like :

```<code>if (isset($_POST['result_button'])) {
$value =$row['name'];
}
</code>```

I tried this when i put all the results from query in to a form of button, but that only pulls the last value from table row.

I tried putting results into array like :

```<code>$result= array();
$result[]=$row['name'];

echo $result[2];
</code>```

I don't fully understand how arrays works so might have done something wrong there but from what i tried this works only if i put echo$result[0];

答:
Ok, firstly:

$row = $result->fetch_assoc()

This does not work how you're expecting it to. What this is basically saying, is that for each returned value (from the MySQL query), store in $row for this iteration of the while loop.

So, in you're example, $row will first be John, then Bob, then Steve and finally Mark. They are not all stored in the variable at the same time. Bob overwrites John, etc.

I'm going to skip your second bit of code, as it's clear you do not have an understanding of arrays.

Arrays

There is plenty of material about arrays on the web. I'm not sure why you had to post the question here, however...

To define an array:

```<code>$my_array = array();
</code>```

An array with values:

```<code>$my_array = array(
    "bar",
    "foo"
);
</code>```

Assign variables to an array:

```<code>$my_array = array();
$my_array[0] = "Help" // $my_array[0] now contains "Help"
$my_array[1] = "Me"; // $my_array[0] now contains "Me"
</code>```

So, taking you're final example:

```<code>$result= array();
$result[]=$row['name'];

echo $result[2];
</code>```

You haven't stored anything in the 2nd element of the array.

This would be more appropriate:

```<code>$result= array();
$result[0] = $row['name'];

echo $result[0]; // This would print what was stored in $row['name']
</code>```

Title: Get selected value from database table?

Body:
im new in field of manipulating databases so i have a problem.
So after making a query to select all values from a table row with something like :

while($row = $result->fetch_assoc()) { }

For example if table has names in it we would get :

John
Bob
Steve
Mark

If we put these results in a form of a link or a button, is there any way to get their value?

i tried something like :

if (isset($_POST['result_button'])) {
$value =$row['name'];
}

I tried this when i put all the results from query in to a form of button, but that only pulls the last value from table row.

I tried putting results into array like :

$result= array();
$result[]=$row['name'];

echo $result[2];

I don't fully understand how arrays works so might have done something wrong there but from what i tried this works only if i put echo$result[0];

Body:
Ok, firstly:

$row = $result->fetch_assoc()

This does not work how you're expecting it to. What this is basically saying, is that for each returned value (from the MySQL query), store in $row for this iteration of the while loop.

So, in you're example, $row will first be John, then Bob, then Steve and finally Mark. They are not all stored in the variable at the same time. Bob overwrites John, etc.

I'm going to skip your second bit of code, as it's clear you do not have an understanding of arrays.

Arrays

There is plenty of material about arrays on the web. I'm not sure why you had to post the question here, however...

To define an array:

$my_array = array();

An array with values:

$my_array = array(
    "bar",
    "foo"
);

Assign variables to an array:

$my_array = array();
$my_array[0] = "Help" // $my_array[0] now contains "Help"
$my_array[1] = "Me"; // $my_array[0] now contains "Me"

So, taking you're final example:

$result= array();
$result[]=$row['name'];

echo $result[2];

You haven't stored anything in the 2nd element of the array.

This would be more appropriate:

$result= array();
$result[0] = $row['name'];

echo $result[0]; // This would print what was stored in $row['name']


问:
how to attach multiple files with comments in wordpress
I wanto attach multiple files with comment in wordpress.  The comments section after the post should attach multiple files with comment.  Any code, method or plugin related to it.  thanks</p>

答: Comment attachment plugin has option to upload single file not multiple file</p>


问:
Hybris-Solid Concepts of hybris
Can anyone please tell me the solid concepts of hybris ? I have google it but could not find any exact answer .This is the question asked in Interview .</p>

答:
SOLID stands for five principles used in OOP(Object Oriented Programming) when designing software so that the developed system will be easier to extend and maintain  https://en.wikipedia.org/wiki/SOLID_(object-oriented_design).

Also it is independent of the Programming Language(it can be applied using different programming languages) and independent of the platform(which in this case is Hybris Platform),
and that is way in my opinion linking them(i.e Hybris-SOLID concepts) does not make any sense.

Title: Hybris-Solid Concepts of hybris


问:
Behat, Mink and Selenium. How to check a checkbox?
I am getting an error when trying to check a checkbox with Behat/Mink/Selenium.  Below is my setup and a description of my error.

behat.yml

```<code>default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~
</code>```

composer.json

```<code>{
    "require": {
        "behat/behat": "~3.3",
        "behat/mink-extension": "~2.2",
        "behat/mink-goutte-driver": "~1.2",
        "behat/mink-selenium2-driver": "~1.3"
    },
    "config": {
        "bin-dir": "bin/"
    }
</code>```

}

I run selenium 3.4.0 like this (including a gecko driver)

```<code>java -Dwebdriver.gecko.driver=/home/ubuntu/path/to/geckodriver -jar selenium-server-standalone-3.4.0.jar
</code>```

FeatureContext Class:

```<code><?php

use Behat\MinkExtension\Context\MinkContext;
use Behat\Behat\Tester\Exception\PendingException;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext
{
}

?>
</code>```

The feature under test

```<code>Feature: Search
    In order to use behat
    As a tester
    I need to be able to get all these componets to work!

    @javascript
    Scenario: A very simple test of behat functionality
        Given I am on "http://behat-testing.christaylordeveloper.co.uk/"
        Then I should see "MY BLOG"
        And the "#slave-para" element should not contain "Hi there"
        When I check "test-cb"
        Then the "#slave-para" element should contain "Hi there"
</code>```

The error

this is the output of the test showing a mouseMoveTo error

```<code>ubuntu@ip-172-31-7-6:~/behat-tests$ bin/behat
Feature: Search
  In order to use behat
    As a tester
    I need to be able to get all these componets to work!

  @javascript
  Scenario: A very simple test of behat functionality                # features/simple-test.feature:7
    Given I am on "http://behat-testing.christaylordeveloper.co.uk/" # FeatureContext::visit()
    Then I should see "MY BLOG"                                      # FeatureContext::assertPageContainsText()
    And the "#slave-para" element should not contain "Hi there"      # FeatureContext::assertElementNotContains()
    When I check "test-cb"                                           # FeatureContext::checkOption()
      mouseMoveTo
      Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
      System info: host: 'ip-172-31-7-6', ip: '172.31.7.6', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-1018-aws', java.version: '1.8.0_131'
      Driver info: driver.version: RemoteWebDriver (WebDriver\Exception\UnknownCommand)
    Then the "#slave-para" element should contain "Hi there"         # FeatureContext::assertElementContains()

--- Failed scenarios:

    features/simple-test.feature:7

1 scenario (1 failed)
5 steps (3 passed, 1 failed, 1 skipped)
0m3.75s (10.46Mb)
</code>```

If I comment-out the @javascript tag and comment-out the last step of the scenario (which involves javascript) it passes just fine.

How can I test with javascript without this mouseMoveTo error?

Thank you

Update Number 2:

I now have this working using chromedriver version 2.32 and selenium standalone server 3.5.3

I run the server from the command line like this:

```<code>java -Dwebdriver.chrome.driver=chromedriver -jar selenium-server-standalone-3.5.3.jar
</code>```

My behat.yml is

```<code>default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~
            browser_name: 'chrome'
</code>```

答:
So after updating the question it became clear what is the problem. mouseMoveTo error is well known issue when using selenium3. This error happens only for firefox browser with gecko driver. To fix this issue you can use chrome or update the MinkSelenium2Driver library. Should be master branch of MinkSelenium2Driver which requires behat/mink: ~1.7@dev. Here is the point of the problem MinkSelenium2Driver
So if its ok for you to use all the latest behat versions, then composer.json could looks like this:

```<code>"require": {
    "behat/behat": "v3.3.1",
    "behat/mink": "v1.7.1",
    "behat/mink-extension": "v2.2",
    "behat/mink-selenium2-driver": "dev-master",
</code>```

}

Body:
I am getting an error when trying to check a checkbox with Behat/Mink/Selenium.  Below is my setup and a description of my error.

behat.yml

default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~

composer.json

{
    "require": {
        "behat/behat": "~3.3",
        "behat/mink-extension": "~2.2",
        "behat/mink-goutte-driver": "~1.2",
        "behat/mink-selenium2-driver": "~1.3"
    },
    "config": {
        "bin-dir": "bin/"
    }

}

I run selenium 3.4.0 like this (including a gecko driver)

java -Dwebdriver.gecko.driver=/home/ubuntu/path/to/geckodriver -jar selenium-server-standalone-3.4.0.jar

FeatureContext Class:

<?php

use Behat\MinkExtension\Context\MinkContext;
use Behat\Behat\Tester\Exception\PendingException;

/**
 * Defines application features from the specific context.
 */
class FeatureContext extends MinkContext
{
}

?>

The feature under test

Feature: Search
    In order to use behat
    As a tester
    I need to be able to get all these componets to work!

    @javascript
    Scenario: A very simple test of behat functionality
        Given I am on "http://behat-testing.christaylordeveloper.co.uk/"
        Then I should see "MY BLOG"
        And the "#slave-para" element should not contain "Hi there"
        When I check "test-cb"
        Then the "#slave-para" element should contain "Hi there"

The error

this is the output of the test showing a mouseMoveTo error

ubuntu@ip-172-31-7-6:~/behat-tests$ bin/behat
Feature: Search
  In order to use behat
    As a tester
    I need to be able to get all these componets to work!

  @javascript
  Scenario: A very simple test of behat functionality                # features/simple-test.feature:7
    Given I am on "http://behat-testing.christaylordeveloper.co.uk/" # FeatureContext::visit()
    Then I should see "MY BLOG"                                      # FeatureContext::assertPageContainsText()
    And the "#slave-para" element should not contain "Hi there"      # FeatureContext::assertElementNotContains()
    When I check "test-cb"                                           # FeatureContext::checkOption()
      mouseMoveTo
      Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
      System info: host: 'ip-172-31-7-6', ip: '172.31.7.6', os.name: 'Linux', os.arch: 'amd64', os.version: '4.4.0-1018-aws', java.version: '1.8.0_131'
      Driver info: driver.version: RemoteWebDriver (WebDriver\Exception\UnknownCommand)
    Then the "#slave-para" element should contain "Hi there"         # FeatureContext::assertElementContains()

--- Failed scenarios:

    features/simple-test.feature:7

1 scenario (1 failed)
5 steps (3 passed, 1 failed, 1 skipped)
0m3.75s (10.46Mb)

If I comment-out the @javascript tag and comment-out the last step of the scenario (which involves javascript) it passes just fine.

How can I test with javascript without this mouseMoveTo error?

Thank you

Update Number 2:

I now have this working using chromedriver version 2.32 and selenium standalone server 3.5.3

I run the server from the command line like this:

java -Dwebdriver.chrome.driver=chromedriver -jar selenium-server-standalone-3.5.3.jar

My behat.yml is

default:
    extensions:
        Behat\MinkExtension:
            goutte: ~
            selenium2: ~
            browser_name: 'chrome'

Body:
So after updating the question it became clear what is the problem. mouseMoveTo error is well known issue when using selenium3. This error happens only for firefox browser with gecko driver. To fix this issue you can use chrome or update the MinkSelenium2Driver library. Should be master branch of MinkSelenium2Driver which requires behat/mink: ~1.7@dev. Here is the point of the problem MinkSelenium2Driver
So if its ok for you to use all the latest behat versions, then composer.json could looks like this:

"require": {
    "behat/behat": "v3.3.1",
    "behat/mink": "v1.7.1",
    "behat/mink-extension": "v2.2",
    "behat/mink-selenium2-driver": "dev-master",

}


问:
Should we declare a collection class or interface?
I've got this idea from Java - i was told that you should declare a collection like this

```<code>List<Object> myList = new ArrayList<Object>();
</code>```

where ArrayList is a class implementing List interface. The point of this is to enhance maintainability by generalizing code - as, should you change teh implementation to, e.g LinkedList<Object>, you could to it 100% painlessly.

So, projecting this on C#, is it considered a good practice to do the same thing in C# :

```<code>IList<Object> list = new List<Object>()
</code>```

?

EDIT : i just found that LinkedList in C# does not even implement the IList interface, so i guess it settles the question for lists at least

答:
Yes, generally this is a good practice to use interfaces wherever you can.

There are two important exceptions for containers, though:

When you must use a hash-based container for objects that are not comparable, use HashSet<T> or Dictionary<TK,TV>,

When you declare a local variable, using var for implicit typing is often preferred for convenience,

Note that if you plan to use a sorted container you have IOrderedSet<T> and IOrderedDictionary<TK,TV>.

Body:
I've got this idea from Java - i was told that you should declare a collection like this

List<Object> myList = new ArrayList<Object>();

where ArrayList is a class implementing List interface. The point of this is to enhance maintainability by generalizing code - as, should you change teh implementation to, e.g LinkedList<Object>, you could to it 100% painlessly.

So, projecting this on C#, is it considered a good practice to do the same thing in C# :

IList<Object> list = new List<Object>()

?

EDIT : i just found that LinkedList in C# does not even implement the IList interface, so i guess it settles the question for lists at least


问:
Angular/ NgForm/NgModel directives error : There is no directive with "exportAs" set to "ngForm"
I have a asp.net core/Angular project.
In my app.module.client.ts file, i'm importing the '@angular/forms' as below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}```
</div>
</div>
</p>

<p>My component is configured like this:</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>import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Operator } from '../shared/operator.model';

@Component({
    selector: 'operator-form',
    template: require('./operator-form.component.html')
})

export class OperatorFormComponent {

    model = new Operator("Login", "Name", "Last name", "password");
    submitted = false;
    onSubmit() { this.submitted = true; }
    // TODO: Remove this when we're done
    get diagnostic() { return JSON.stringify(this.model); }
}</code>```

My template is configured as below:

    <form  #formOperator="ngForm">

            Login
            <input type="text" class="form-control" id="login" required [(ngModel)]="model.login" name="login" />

            First Name
            <input type="text" class="form-control" id="firstName" required [(ngModel)]="model.firstName" name="firstName" />

            Last Name
            <input type="text" class="form-control" id="lastName" required [(ngModel)]="model.lastName" name="lastName" />

            Password
            <input type="text" class="form-control" id="password" required [(ngModel)]="model.password" name="password" />

            Valid until
            <input type="date" class="form-control" id="expirationDate" [(ngModel)]="model.validUntil" name="expirationDate" />

        <button type="submit" class="btn btn-success">Submit</button>
    </form>```

Unfortunately i've got the error: There is no directive with "exportAs" set to "ngForm"

Any idea?

Thanks!

答:
When you create an angular project with the command "dotnet new Angular", the app.module is divided in three files: app.module.client.ts, app.module.server.ts and the app.module.shared.ts.

In order to import properly the package '@angular/forms' you have to add it in the app.module.shared.ts or to add it in the client and the server files.

Body:
I have a asp.net core/Angular project.
In my app.module.client.ts file, i'm importing the '@angular/forms' as below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { sharedConfig } from './app.module.shared';

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}

My component is configured like this:

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Operator } from '../shared/operator.model';

@Component({
    selector: 'operator-form',
    template: require('./operator-form.component.html')
})

export class OperatorFormComponent {

    model = new Operator("Login", "Name", "Last name", "password");
    submitted = false;
    onSubmit() { this.submitted = true; }
    // TODO: Remove this when we're done
    get diagnostic() { return JSON.stringify(this.model); }
}

My template is configured as below:

    <form  #formOperator="ngForm">

            Login
            <input type="text" class="form-control" id="login" required [(ngModel)]="model.login" name="login" />

            First Name
            <input type="text" class="form-control" id="firstName" required [(ngModel)]="model.firstName" name="firstName" />

            Last Name
            <input type="text" class="form-control" id="lastName" required [(ngModel)]="model.lastName" name="lastName" />

            Password
            <input type="text" class="form-control" id="password" required [(ngModel)]="model.password" name="password" />

            Valid until
            <input type="date" class="form-control" id="expirationDate" [(ngModel)]="model.validUntil" name="expirationDate" />

        <button type="submit" class="btn btn-success">Submit</button>
    </form>

Unfortunately i've got the error: There is no directive with "exportAs" set to "ngForm"

Any idea?

Thanks!


问:
Count Characters after a certain pattern
I have a database that contains a column "Code" where the records have the following format "xx-xxx" and "xx-xx", for the later format i want to add a zero after the "-" to make it "xx-0xx", is there anyway to count the characters after a certain pattern in Mysql</p>

答:
Yes, you can use the CHAR_LENGTH(str) like this:</p>

```<code>SELECT code,CHAR_LENGTH(SUBSTR(code,3))
from table
</code>```

Body:
Yes, you can use the CHAR_LENGTH(str) like this:

SELECT code,CHAR_LENGTH(SUBSTR(code,3))
from table


问:
Is there any shortcut for // MARK: in Xcode like there is for /// <#Description#>?
Is there any keyboard shortcut for '<strong>// MARK:</strong>' in swift like there is for header doc '/// Description' ?  </p>

答:
There is no problem to add it as a code snippet to Xcode.

What you should do is:

Type: // MARK:  <#Description#>, select it and then drag it to the code snippet in the utilities section:

Fill the popup form, as follows:

and that's it!

Usage:

As per the screenshot above, the completion handler shortcut is: 'm'; By typing 'm' in the code area, you should see:

Body: Is there any keyboard shortcut for '// MARK:' in swift like there is for header doc '/// Description' ?


问:
Javascript array length of 0
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

```<code>var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})
</code>```

And this is shown in the inspector, the "length: 42" belongs to line 115.

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?

答:
console.log is not synchronous.

Your console.log statements appear after you have called getTrips but before the getTrips callback has fired.

Effectively, you are trying to return the response from an asynchronous call.

response is an object. Objects in JS are always referenced. You are logging that reference, and then the object gets updated with the new values (and the new length) when the getTrips callbacks fire. The new object is reflected in the console.

response.length is a number. You are logging it. Number values are not references. It is 0 because at the time you called console.log it was 0. The display doesn't update when the value changed because is a number and not an object.

Title: Javascript array length of 0

Body:
I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

And this is shown in the inspector, the "length: 42" belongs to line 115.

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?


问:
Cannot Load Graph using Highcharts
I am using highcharts to display the graph dynamically . But my graph is not loaded . It throws the following error .

```<code>Error: Highcharts error #14: www.highcharts.com/errors/14
</code>```

I am trying the following code . In this code i passing the series data in the variables  left and right . But my Graph is not loading . If i pass the variables as static Graph is Loaded.

```<code>    var left = [];
   var right = [];

 if(($('#love').val() != '') && ($('#architectural').val() != '')){

 var rights = [[  $('#love').val() , $('#love').val() ] ,      [$('#architectural').val() ,$('#architectural').val() ]];

}

if(($('#righty').val() != '') && ($('#lefty').val() != '')){

if($('#righty').val() == 5){

   var second1 = (1 +','+ $('#right1').val() );

}else if($('#righty').val() == 4 ){

    var second1 = (2 +','+ $('#right1').val());

}else if($('#righty').val() == 3 ){

   var second1 = (3 +','+ $('#right1').val());

 }else if($('#righty').val() == 2 ){

   var second1 = (4 +','+ $('#right1').val());

 }else{

    var second1 = (5 +','+ $('#right1').val());

 }

 if($('#lefty').val() == 5){

  var first1 = ( $('#condition').val() +','+ 1 );

  }else if($('#lefty').val() == 4 ){

  var first1 = ($('#condition').val() +','+ 2);

}else if($('#lefty').val() == 3 ){

  var first1 = ($('#condition').val() +','+ 3);

}else if($('#lefty').val() == 2 ){

 var first1 = ($('#condition').val() +','+ 4);

}else{

 var first1 = ($('#condition').val() +','+ 5);

}

var lefts = [[  second1 ] , [ first1 ] ];

 }

 //var left = [[4,7],[9,2]];
 //var right = [[2,2],[4,4]];

     left.push(lefts);
      right.push(rights);

  Highcharts.chart('container', {

 title:{
    text:''
 },

 tooltip: { enabled: false },

 exporting: { enabled: false },

 credits: {enabled: false},

 plotOptions: {
    series: {
        pointStart: 1
    }
 },

xAxis: {
    max: 10,
    min: 1,
    tickInterval: 1
},

 yAxis: {
    max: 10,
    min: 1,
    tickInterval: 1,

  plotLines: [{
  color: 'black',
  value: 5.5,
  width: 2

  }],

},

  series: [{
    showInLegend: false,
    data: left
  },
 {
   showInLegend: false,
    data: right
  }],
 });

      }

  }
</code>```

I am getting the following  graph :

答:
Finally i changed my string values passing in the variable left and right. here is my correct answer,</p>

```<code> if(($('#love').val() != '') && ($('#architectural').val() != '')){

 var right= [[  parseFloat($('#love').val()) , parseFloat($('#love').val()) ] , [ (parseFloat($('#architectural').val())),parseFloat($('#architectural').val())]];

   }

   if(($('#righty').val() != '') && ($('#lefty').val() != '')){

   if($('#righty').val() == 5){

    var second1 = [1 , parseFloat($('#right1').val()) ];

   }else if($('#righty').val() == 4 ){

       var second1 = [2 , parseFloat($('#right1').val())];

   }else if($('#righty').val() == 3 ){

       var second1 = [3 , parseFloat($('#right1').val())];

   }else if($('#righty').val() == 2 ){

     var second1 = [4 , parseFloat($('#right1').val())];

   }else{

      var second1 = [5 , parseFloat($('#right1').val())];

   }

  if($('#lefty').val() == 5){

     var first1 = [parseFloat($('#condition').val()) , 1 ];

  }else if($('#lefty').val() == 4 ){

      var first1 = [parseFloat($('#condition').val()) , 2];

  }else if($('#lefty').val() == 3 ){

       var first1 = [parseFloat($('#condition').val()) , 3];

  }else if($('#lefty').val() == 2 ){

       var first1 = [parseFloat($('#condition').val()) , 4];

  }else{

    var first1 = [parseFloat($('#condition').val()) , 5];

  }

  var left = [second1   ,  first1  ];

 }

     Highcharts.chart('container', {

    title:{
        text:''
     },

     tooltip: { enabled: false },

     exporting: { enabled: false },

     credits: {enabled: false},

      plotOptions: {
        series: {
        pointStart: 1
           }
     },

     xAxis: {
         max: 10,
         min: 1,
         tickInterval: 1
     },

    yAxis: {
        max: 10,
        min: 1,
        tickInterval: 1,

    plotLines: [{
     color: 'black',
     value: 5.5,
     width: 2

    }],

  },

  series: [{
    showInLegend: false,
    data: left
   },
   {
     showInLegend: false,
    data: right
   }],
   });

     }

    }
</code>```

Title: Cannot Load Graph using Highcharts

Body:
I am using highcharts to display the graph dynamically . But my graph is not loaded . It throws the following error .

Error: Highcharts error #14: www.highcharts.com/errors/14

I am trying the following code . In this code i passing the series data in the variables  left and right . But my Graph is not loading . If i pass the variables as static Graph is Loaded.

    var left = [];
   var right = [];

 if(($('#love').val() != '') && ($('#architectural').val() != '')){

 var rights = [[  $('#love').val() , $('#love').val() ] ,      [$('#architectural').val() ,$('#architectural').val() ]];

}

if(($('#righty').val() != '') && ($('#lefty').val() != '')){

if($('#righty').val() == 5){

   var second1 = (1 +','+ $('#right1').val() );

}else if($('#righty').val() == 4 ){

    var second1 = (2 +','+ $('#right1').val());

}else if($('#righty').val() == 3 ){

   var second1 = (3 +','+ $('#right1').val());

 }else if($('#righty').val() == 2 ){

   var second1 = (4 +','+ $('#right1').val());

 }else{

    var second1 = (5 +','+ $('#right1').val());

 }

 if($('#lefty').val() == 5){

  var first1 = ( $('#condition').val() +','+ 1 );

  }else if($('#lefty').val() == 4 ){

  var first1 = ($('#condition').val() +','+ 2);

}else if($('#lefty').val() == 3 ){

  var first1 = ($('#condition').val() +','+ 3);

}else if($('#lefty').val() == 2 ){

 var first1 = ($('#condition').val() +','+ 4);

}else{

 var first1 = ($('#condition').val() +','+ 5);

}

var lefts = [[  second1 ] , [ first1 ] ];

 }

 //var left = [[4,7],[9,2]];
 //var right = [[2,2],[4,4]];

     left.push(lefts);
      right.push(rights);

  Highcharts.chart('container', {

 title:{
    text:''
 },

 tooltip: { enabled: false },

 exporting: { enabled: false },

 credits: {enabled: false},

 plotOptions: {
    series: {
        pointStart: 1
    }
 },

xAxis: {
    max: 10,
    min: 1,
    tickInterval: 1
},

 yAxis: {
    max: 10,
    min: 1,
    tickInterval: 1,

  plotLines: [{
  color: 'black',
  value: 5.5,
  width: 2

  }],

},

  series: [{
    showInLegend: false,
    data: left
  },
 {
   showInLegend: false,
    data: right
  }],
 });

      }

  }

I am getting the following  graph :

Body:
Finally i changed my string values passing in the variable left and right. here is my correct answer,

 if(($('#love').val() != '') && ($('#architectural').val() != '')){

 var right= [[  parseFloat($('#love').val()) , parseFloat($('#love').val()) ] , [ (parseFloat($('#architectural').val())),parseFloat($('#architectural').val())]];

   }

   if(($('#righty').val() != '') && ($('#lefty').val() != '')){

   if($('#righty').val() == 5){

    var second1 = [1 , parseFloat($('#right1').val()) ];

   }else if($('#righty').val() == 4 ){

       var second1 = [2 , parseFloat($('#right1').val())];

   }else if($('#righty').val() == 3 ){

       var second1 = [3 , parseFloat($('#right1').val())];

   }else if($('#righty').val() == 2 ){

     var second1 = [4 , parseFloat($('#right1').val())];

   }else{

      var second1 = [5 , parseFloat($('#right1').val())];

   }

  if($('#lefty').val() == 5){

     var first1 = [parseFloat($('#condition').val()) , 1 ];

  }else if($('#lefty').val() == 4 ){

      var first1 = [parseFloat($('#condition').val()) , 2];

  }else if($('#lefty').val() == 3 ){

       var first1 = [parseFloat($('#condition').val()) , 3];

  }else if($('#lefty').val() == 2 ){

       var first1 = [parseFloat($('#condition').val()) , 4];

  }else{

    var first1 = [parseFloat($('#condition').val()) , 5];

  }

  var left = [second1   ,  first1  ];

 }

     Highcharts.chart('container', {

    title:{
        text:''
     },

     tooltip: { enabled: false },

     exporting: { enabled: false },

     credits: {enabled: false},

      plotOptions: {
        series: {
        pointStart: 1
           }
     },

     xAxis: {
         max: 10,
         min: 1,
         tickInterval: 1
     },

    yAxis: {
        max: 10,
        min: 1,
        tickInterval: 1,

    plotLines: [{
     color: 'black',
     value: 5.5,
     width: 2

    }],

  },

  series: [{
    showInLegend: false,
    data: left
   },
   {
     showInLegend: false,
    data: right
   }],
   });

     }

    }