问:
Parse string with Python and pull numbers for simple math
I am running "Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2" on Ubuntu.

I have a line as follows from serial:

```<code>line="[99]  nodeId=99    uptime=31987895     BarC=1.15     sensorVal=226 -"
</code>```

and wish to parse this. I need to extract 1.15 and 226 as numbers so I can do math with those numbers.

I have used the following python code:

```<code>pressure=line.split()[3].split("=")[1:2]
print(pressure)
</code>```

This prints this:

```<code>['1.15']
</code>```

How do I get rid of the  ' ' (apostrophes) and the  [  ]  and turn this into something I can do simple math with. A floating number will be fine.

Here is more output:

```<code>Listening at 868 Mhz...
[99]  nodeId=99    uptime=48743987     BarC=1.19     sensorVal=229 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48745052     BarC=1.19     sensorVal=229
[99]  nodeId=99    uptime=48527151     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48528216     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48529276     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48530341     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48531402     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48532467     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48533528     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48534594     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48535655     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48536720     BarC=1.20     sen**
</code>```

答:
Barring the usage of regular expressions, I would like to help you understand why you have a problem in the first place.

It appears that you have concocted a long sequence of method calls that give you something very close to what you want without paying attention to the return values. Let's break it down:

line is a string. line.split() returns a list of the space-separated string elements of in line. [3] gets the fourth element of the list, which is again a string. .split('=') breaks it into a list again. [1:2] extracts the second element as a sublist. You can get the first element of the list by indexing pressure[0]. A much easier way would be to extract the index as [1] instead of [1:2], which would return the second element as a string instead of a list.

In general, it is a good idea to process each of these steps in a separate line. Error checking is another reason to do this. Lines like Listening at 868 Mhz... do not have an = in the fourth element (Mhz...). There may also be lines that don't even have four elements. Either one will cause an IndexError.

To parse the a float number, just wrap the final string result in a call to float.

Here is a better way to extract the number string using the same calls:

```<code>elems = line.split()
if len(elems) > 3:
    items = elems[3].split('=')
    if len(items) > 1:
        pressure = float(items[1])
</code>```

This should show you why regex is a cleaner option for something like this.

Body:
I am running "Python 2.7.9 (default, Sep 17 2016, 20:26:04)
[GCC 4.9.2] on linux2" on Ubuntu.

I have a line as follows from serial:

line="[99]  nodeId=99    uptime=31987895     BarC=1.15     sensorVal=226 -"

and wish to parse this. I need to extract 1.15 and 226 as numbers so I can do math with those numbers.

I have used the following python code:

pressure=line.split()[3].split("=")[1:2]
print(pressure)

This prints this:

['1.15']

How do I get rid of the  ' ' (apostrophes) and the  [  ]  and turn this into something I can do simple math with. A floating number will be fine.

Here is more output:

Listening at 868 Mhz...
[99]  nodeId=99    uptime=48743987     BarC=1.19     sensorVal=229 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48745052     BarC=1.19     sensorVal=229
[99]  nodeId=99    uptime=48527151     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48528216     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48529276     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48530341     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48531402     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48532467     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48533528     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48534594     BarC=1.20     sensorVal=230
[99]  nodeId=99    uptime=48535655     BarC=1.20     sensorVal=230 - ACK sent. Sending packet to node 99 - waiting for ACK...nothing...
[99]  nodeId=99    uptime=48536720     BarC=1.20     sen**

Body:
Barring the usage of regular expressions, I would like to help you understand why you have a problem in the first place.

It appears that you have concocted a long sequence of method calls that give you something very close to what you want without paying attention to the return values. Let's break it down:

line is a string. line.split() returns a list of the space-separated string elements of in line. [3] gets the fourth element of the list, which is again a string. .split('=') breaks it into a list again. [1:2] extracts the second element as a sublist. You can get the first element of the list by indexing pressure[0]. A much easier way would be to extract the index as [1] instead of [1:2], which would return the second element as a string instead of a list.

In general, it is a good idea to process each of these steps in a separate line. Error checking is another reason to do this. Lines like Listening at 868 Mhz... do not have an = in the fourth element (Mhz...). There may also be lines that don't even have four elements. Either one will cause an IndexError.

To parse the a float number, just wrap the final string result in a call to float.

Here is a better way to extract the number string using the same calls:

elems = line.split()
if len(elems) > 3:
    items = elems[3].split('=')
    if len(items) > 1:
        pressure = float(items[1])

This should show you why regex is a cleaner option for something like this.


来源: stackexchange

问:
Reordering items in Flatlist
Is there a way to configure reordering of items in a Flatlist?  i.e. similar to what you can do in IOS TableView: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/TableView_iPhone/ManageReorderRow/ManageReorderRow.html

(if not any points as to how react-native developers would then implement this?)

答: Haven't try it but seems to work fine: https://github.com/gitim/react-native-sortable-list</p>

ContentLicense: CC BY-SA 3.0

Title: Reordering items in Flatlist


问:
Is it safe to override the constructor pseudofunction when subclassing builtins?
In ES6, we can finally subclass builtins like Array:

```<code>class Bar extends Array {
    ...
}
</code>```

Without doing anything special, the Array methods which would normally return Array instances will return Bar instances when called through a Bar, since they look up their constructor function through Symbol.species.

Now, say I defined a custom constructor function for Bar. Is there any guarantee as to how static and member methods of Array call the constructor they look up through Symbol.species? Is it, in short, ever safe to provide a user-defined constructor for a subclass of a builtin like Array?

答:
Is there any guarantee as to how static and member methods of Array call the constructor?

Yes, it's properly specified and nailed down. Specifically, all the prototype methods (slice, concat, map, filter) do use the abstract ArraySpeciesCreate algorithm which will call the constructor with a single argument: an integer length. Array.of and Array.from do something very similar, although the latter does not pass a length when it creates an array from an iterator.

concat, slice, from and of also do explicitly set the length property after assigning the elements, map and filter do not.

Body:
In ES6, we can finally subclass builtins like Array:

class Bar extends Array {
    ...
}

Without doing anything special, the Array methods which would normally return Array instances will return Bar instances when called through a Bar, since they look up their constructor function through Symbol.species.

Now, say I defined a custom constructor function for Bar. Is there any guarantee as to how static and member methods of Array call the constructor they look up through Symbol.species? Is it, in short, ever safe to provide a user-defined constructor for a subclass of a builtin like Array?


问:
Looks for patterns across different lines
I have a file like this (test.txt):

```<code>abc
12
34
def
56
abc
ghi
78
def
90
</code>```

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

```<code>cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'
</code>```

Is there any better way?

答:
You could do this with sed. It's not ideal in that it doesn't actually understand records, but it might work for you...

```<code>sed -Ene 'H;${x;s/.*\nabc\nghi\n([0-9]+)\ndef\n.*/\1/;p;}' input.txt
</code>```

Here's what's basically going on:

H - appends the current line to sed's "hold space"

${ - specifies the start of a series of commands that will be run once we come to the end of the file

x - swaps the hold space with the pattern space, so that future substitutions will work on what was stored using H

s/../../ - analyses the pattern space (which is now multi-line), capturing the data specified in your question, replacing the entire pattern space with the bracketed expression...

p - prints the result.

One important factor here is that the regular expression is ERE, so the -E option is important. If your version of sed uses some other option to enable support for ERE, then use that option instead.

Another consideration is that the regex above assumes Unix-style line endings. If you try to process a text file that was generated on DOS or Windows, the regex may need to be a little different.

Body:
I have a file like this (test.txt):

abc
12
34
def
56
abc
ghi
78
def
90

And I would like to search the 78 which is enclosed by "abc\nghi" and "def". Currently, I know I can do this by:

cat test.txt | awk '/abc/,/def/' | awk '/ghi/,'/def/'

Is there any better way?

Body:
You could do this with sed. It's not ideal in that it doesn't actually understand records, but it might work for you...

sed -Ene 'H;${x;s/.*\nabc\nghi\n([0-9]+)\ndef\n.*/\1/;p;}' input.txt

Here's what's basically going on:

H - appends the current line to sed's "hold space"

${ - specifies the start of a series of commands that will be run once we come to the end of the file

x - swaps the hold space with the pattern space, so that future substitutions will work on what was stored using H

s/../../ - analyses the pattern space (which is now multi-line), capturing the data specified in your question, replacing the entire pattern space with the bracketed expression...

p - prints the result.

One important factor here is that the regular expression is ERE, so the -E option is important. If your version of sed uses some other option to enable support for ERE, then use that option instead.

Another consideration is that the regex above assumes Unix-style line endings. If you try to process a text file that was generated on DOS or Windows, the regex may need to be a little different.


问:
Is it better to use the column name or column index on .Net DataSets?
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

```<code>int price = (int)dr["Price"];
</code>```

While column index is just faster (I think):

```<code>int price = (int)dr[3];
</code>```

Would using column names break if you decide to obfuscate the database?

答:
I would think the column name is the best way to go.  It is easier to determine what you are pulling, and the column order is determined by the select statement which could change sometime down the road.  You could argue the column name could change too, but i would think this would be much less likely.

EDIT:

Actually if you were really bent on using column indexes you could create constants of the column indexes and name the constant the name of the column.  So:

```<code>PRIMARY_KEY_COLUMN_NAME_INDEX = 0
</code>```

That would at least make it readable.

OwnerDisplayName: tpower

ContentLicense: CC BY-SA 2.5

Body:
When retrieving values from a DataRow is it better to use the column name or column index?

The column name is more readable and easier to maintain:

int price = (int)dr["Price"];

While column index is just faster (I think):

int price = (int)dr[3];

Would using column names break if you decide to obfuscate the database?

LastEditorDisplayName: tpower

Body:
I would think the column name is the best way to go.  It is easier to determine what you are pulling, and the column order is determined by the select statement which could change sometime down the road.  You could argue the column name could change too, but i would think this would be much less likely.

EDIT:

Actually if you were really bent on using column indexes you could create constants of the column indexes and name the constant the name of the column.  So:

PRIMARY_KEY_COLUMN_NAME_INDEX = 0

That would at least make it readable.

OwnerDisplayName: Kevin

LastEditorDisplayName: Kevin


问:
SSL and Client Certificates
An internal team, separate from my own, has stated that they prefer to do incoming authentication based on client certificates. Which sounds good to me, except that I haven't messed with them before and aren't quite sure where to start researching (Wikipedia went straight into a lot of detail that I'm not sure is pertinent to what I need to find out). If I have an IIS6 server with a web app that runs under an AD user account, what steps should I take to eventually fire off a request from that web app to a remote server, via .NET (I'm guessing HttpWebRequest)? I do see that we have an internal trusted certificate authority and all. Remote server is running Apache on Linux boxes.

I'm essentially in learning mode, not necessarily looking for a blow-by-blow list of what needs to happen (though if I could learn how it works while learning how to do it, that'd be nice too :)  ... do you have any resources I could start looking into in order to figure out how to successfully authenticate securely via SSL with this remote server and communicate with it via client certs? Probably from creation of the client cert on up, though I'd like to more fully understand how it all works in the first place.

答: Here is a link - http://support.microsoft.com/kb/315588. Hope this helps with what you are looking for.</p>

OwnerDisplayName: Chris

Title: SSL and Client Certificates


问:
Wrap async await queries in try catch
I originally had try...catch in my getAllUsers method for querying but ended up removing it because as far as I could tell it wasn't doing anything. I know the async function returns a promise so it should be fine and actually based on how the code is structured I think it's required otherwise the try...catch in the query would swallow the error. Is there anything I'm missing with this structure and use of async/await, try...catch, and .then .catch?

```<code>let getAllUsers = async () => {
  let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

router.get(`${path}`, (req, res) => {
    queries.users.getAllUsers()
      .then(users => {
        res.status(200).json(users);
      })
      .catch(error => {
        res.status(500).send(error)
      });
});
</code>```

答:
There's just no reason to use await at all in your function.  Instead of this:

```<code>let getAllUsers = async () => {
    let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};
</code>```

It can just be this:

```<code>let getAllUsers = () => {
    return models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
};
</code>```

You just return the promise directly and the caller uses the promise the same as you already were.  Since you are not using the result within your getAllUsers() function or coordinating it with anything else, there's no reason to use await.  And, since there's no use of await, there's no reason for the function to be declared async either.

If you wanted to use await, you could use it for the caller of getAllUsers() like this:

```<code>router.get(`${path}`, async (req, res) => {
    try {
        let users = await queries.users.getAllUsers();
        res.status(200).json(users);
    } catch(error => {
        res.status(500).json(error);
    }
});
</code>```

And, here you would have to use try/catch in order to catch rejected promises.  Personally, I don't see how this is particularly better than what you had originally with .then() and .catch() so for a situation as simple as this (with no coordination or serialization with other promises), it's really just a matter of personal preference whether to use .then() and .catch() or await with try/catch.

Title: Wrap async await queries in try catch

Body:
I originally had try...catch in my getAllUsers method for querying but ended up removing it because as far as I could tell it wasn't doing anything. I know the async function returns a promise so it should be fine and actually based on how the code is structured I think it's required otherwise the try...catch in the query would swallow the error. Is there anything I'm missing with this structure and use of async/await, try...catch, and .then .catch?

let getAllUsers = async () => {
  let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

router.get(`${path}`, (req, res) => {
    queries.users.getAllUsers()
      .then(users => {
        res.status(200).json(users);
      })
      .catch(error => {
        res.status(500).send(error)
      });
});

Body:
There's just no reason to use await at all in your function.  Instead of this:

let getAllUsers = async () => {
    let res = await models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
    return res;
};

It can just be this:

let getAllUsers = () => {
    return models.users.findAll({
      attributes: [ 'firstName', 'lastName' ]
    });
};

You just return the promise directly and the caller uses the promise the same as you already were.  Since you are not using the result within your getAllUsers() function or coordinating it with anything else, there's no reason to use await.  And, since there's no use of await, there's no reason for the function to be declared async either.

If you wanted to use await, you could use it for the caller of getAllUsers() like this:

router.get(`${path}`, async (req, res) => {
    try {
        let users = await queries.users.getAllUsers();
        res.status(200).json(users);
    } catch(error => {
        res.status(500).json(error);
    }
});

And, here you would have to use try/catch in order to catch rejected promises.  Personally, I don't see how this is particularly better than what you had originally with .then() and .catch() so for a situation as simple as this (with no coordination or serialization with other promises), it's really just a matter of personal preference whether to use .then() and .catch() or await with try/catch.


问:
When to break up a function
Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.

```<code>def anti_vowel(text):
   list = ['a', 'e', 'i', 'o', 'u']
   big_list = ['A', 'E', 'I', 'O', 'U']
   list_word = []

   for f in text:
      list_word.append(f)

   for vowel in list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   for vowel in big_list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   new_word = ''.join(list_word)
   return new_word

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")
</code>```

This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?

答:
A little improvement:</p>

```<code>list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

def anti_vowel(text):
    return ''.join([x for x in text if x not in list])

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")
</code>```

Title: When to break up a function

Body:
Currently I am very new to python programming, been working on it for a while, I came across a little project task which was to make a program that takes all of the vowels out of a statement so I decided to try it out. I came up with a program but it seems that it only takes out the vowels sometimes, I find this very weird and I would like to ask for some assistance in solving it.

def anti_vowel(text):
   list = ['a', 'e', 'i', 'o', 'u']
   big_list = ['A', 'E', 'I', 'O', 'U']
   list_word = []

   for f in text:
      list_word.append(f)

   for vowel in list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   for vowel in big_list:
      for letter in list_word:
         if vowel == letter:
            list_word.remove(vowel)

   new_word = ''.join(list_word)
   return new_word

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")

This statement as it sits prints out 'IiIuUUuoouU', but if I add more iterations over the lists using more for statements it decreases the amount of shown letters. Can someone tell me why this might be?

Body:
A little improvement:

list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']

def anti_vowel(text):
    return ''.join([x for x in text if x not in list])

print anti_vowel("uuuUUUUUIIIIiiiIiIoOuuooouuUOUUuooouU")


问:
searching multiple keyword and print out matched keyword with several field in logs
example log (sample.log)

```<code>11:00:00 INFO KOREA AAABB DDDRR
11:00:01 INFO SWEDEN TYTY PLO
11:00:02 INFO US OIILL OTLTOL
11:00:03 INFO NORTHKOREA OTL
</code>```

KEYWORDs (multiple)
    "KOREA", "OTL"

What I want as a result

```<code>11:00:00 KOREA
11:00:02 OTL
11:00:03 KOREA OTL
</code>```

I'm just thinking by using awk fuction.
But I failed....

```<code># $val_1 = KOREA
# $val_2 = OTL

# awk /$val_1|$val_2/'print{$1, $val_1, $val_2}' sample.log
</code>```

答:
Following awk may help you in same.

```<code>awk '
function check(word){
  match($0,word);
  if(substr($0,RSTART,RLENGTH)){
    return substr($0,RSTART,RLENGTH)
}}
{
  val=check("KOREA");
  val=val?$1 FS val FS check("OTL"):check("OTL")?$1 FS check("OTL"):check("OTL");
  if(val){
    print val};
  val=""
}'   Input_file
</code>```

Body:
example log (sample.log)

11:00:00 INFO KOREA AAABB DDDRR
11:00:01 INFO SWEDEN TYTY PLO
11:00:02 INFO US OIILL OTLTOL
11:00:03 INFO NORTHKOREA OTL

KEYWORDs (multiple)
    "KOREA", "OTL"

What I want as a result

11:00:00 KOREA
11:00:02 OTL
11:00:03 KOREA OTL

I'm just thinking by using awk fuction.
But I failed....

# $val_1 = KOREA
# $val_2 = OTL

# awk /$val_1|$val_2/'print{$1, $val_1, $val_2}' sample.log

Body:
Following awk may help you in same.

awk '
function check(word){
  match($0,word);
  if(substr($0,RSTART,RLENGTH)){
    return substr($0,RSTART,RLENGTH)
}}
{
  val=check("KOREA");
  val=val?$1 FS val FS check("OTL"):check("OTL")?$1 FS check("OTL"):check("OTL");
  if(val){
    print val};
  val=""
}'   Input_file


问:
I am having trouble creating a proper trigger in Microsoft SQL Server 2014
I am trying to create a trigger on tplayoffStatus so that teams are not allowed to be inserted into the table with more than one loss. When inserting a value into the table tplayoffStatus the error I keep getting is

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Can anyone help me with this? Is my SELECT statement wrong for returning multiple values in the column losses?

SQL Server 2014 table schema:

```<code>CREATE TABLE tcollegeFootballTeams
(
    TeamAbbreviation varchar(5) NOT NULL PRIMARY KEY,
    TeamName varchar(50) NOT NULL,
    City varchar(50) NOT NULL,
    State varchar(2) NOT NULL,
    Wins int NOT NULL,
    Losses int NOT NULL
)

CREATE TABLE tplayoffStatus
(
    TeamName varchar(50) NOT NULL PRIMARY KEY,
    TeamAbbreviation varchar(5) NOT NULL FOREIGN KEY REFERENCES tcollegeFootballTeams(TeamAbbreviation)
);

CREATE TRIGGER [dbo].[trgNoPlayoffForYou]
ON [dbo].[tplayoffStatus]
AFTER INSERT
AS
    DECLARE @Losses INT
    DECLARE @ErrorMessage VARCHAR(30)

    SELECT @Losses = (SELECT Losses
                      FROM dbo.tcollegeFootballTeams
                      WHERE (Losses > 1))

    IF (@Losses = 'True')
    BEGIN
        SET @ErrorMessage = 'You may not enter the playoffs with more than 1 loss'
        PRINT @ErrorMessage
        ROLLBACK TRANSACTION
    END
</code>```

Query 1:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('OSU', 'THE Ohio State University', 'Columbus', 'OH', 10, 2)
</code>```

[Results][2]

Query 2:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses  )
VALUES ('BAMA', 'Alabama', 'Tuscaloosa', 'AL', 12, 0)
</code>```

[Results][3]

Query 3:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses  )
VALUES ('UGA', 'Georgia', 'Athens', 'GA', 11, 1)
</code>```

[Results][4]

Query 4:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('CLEM', 'Clemson', 'Clemson', 'SC', 11, 1)
</code>```

[Results][5]

Query 5:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('WIS', 'Wisconsin', 'Madison', 'WI', 11, 1)
</code>```

[Results][6]

Query 6:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('ND', 'Notre Dame', 'South Bend', 'IN', 10, 2)
</code>```

[Results][7]

Query 7:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('OKLA', 'Oklahoma', 'Norman', 'OK', 10, 2)
</code>```

[Results][8]

Query 8:

```<code>INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('MIAF', 'Miami of Florida', 'Coral Gables', 'FL', 10, 2)
</code>```

答:
your trigger is wrong. You need to query the inserted table for the records inserted and join to the tcollegeFootballTeams table for Losses

```<code>CREATE TRIGGER [dbo].[trgNoPlayoffForYou] ON [dbo].[tplayoffStatus]
AFTER INSERT
AS

    IF EXISTS
       (
           SELECT *
           FROM   inserted i
                  INNER JOIN dbo.tcollegeFootballTeams t
                  ON i.TeamAbbreviation = t.TeamAbbreviation
           WHERE  t.Losses > 1
       )
    BEGIN
           SET  @ErrorMessage = 'You may not enter the playoffs with more than 1 loss'
           Print @ErrorMessage
           Rollback Transaction
    END
</code>```

Body:
I am trying to create a trigger on tplayoffStatus so that teams are not allowed to be inserted into the table with more than one loss. When inserting a value into the table tplayoffStatus the error I keep getting is

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Can anyone help me with this? Is my SELECT statement wrong for returning multiple values in the column losses?

SQL Server 2014 table schema:

CREATE TABLE tcollegeFootballTeams
(
    TeamAbbreviation varchar(5) NOT NULL PRIMARY KEY,
    TeamName varchar(50) NOT NULL,
    City varchar(50) NOT NULL,
    State varchar(2) NOT NULL,
    Wins int NOT NULL,
    Losses int NOT NULL
)

CREATE TABLE tplayoffStatus
(
    TeamName varchar(50) NOT NULL PRIMARY KEY,
    TeamAbbreviation varchar(5) NOT NULL FOREIGN KEY REFERENCES tcollegeFootballTeams(TeamAbbreviation)
);

CREATE TRIGGER [dbo].[trgNoPlayoffForYou]
ON [dbo].[tplayoffStatus]
AFTER INSERT
AS
    DECLARE @Losses INT
    DECLARE @ErrorMessage VARCHAR(30)

    SELECT @Losses = (SELECT Losses
                      FROM dbo.tcollegeFootballTeams
                      WHERE (Losses > 1))

    IF (@Losses = 'True')
    BEGIN
        SET @ErrorMessage = 'You may not enter the playoffs with more than 1 loss'
        PRINT @ErrorMessage
        ROLLBACK TRANSACTION
    END

Query 1:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('OSU', 'THE Ohio State University', 'Columbus', 'OH', 10, 2)

[Results][2]

Query 2:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses  )
VALUES ('BAMA', 'Alabama', 'Tuscaloosa', 'AL', 12, 0)

[Results][3]

Query 3:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses  )
VALUES ('UGA', 'Georgia', 'Athens', 'GA', 11, 1)

[Results][4]

Query 4:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('CLEM', 'Clemson', 'Clemson', 'SC', 11, 1)

[Results][5]

Query 5:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('WIS', 'Wisconsin', 'Madison', 'WI', 11, 1)

[Results][6]

Query 6:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('ND', 'Notre Dame', 'South Bend', 'IN', 10, 2)

[Results][7]

Query 7:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('OKLA', 'Oklahoma', 'Norman', 'OK', 10, 2)

[Results][8]

Query 8:

INSERT INTO tcollegeFootballTeams (TeamAbbreviation, TeamName, City, State, Wins, Losses)
VALUES ('MIAF', 'Miami of Florida', 'Coral Gables', 'FL', 10, 2)

Body:
your trigger is wrong. You need to query the inserted table for the records inserted and join to the tcollegeFootballTeams table for Losses

CREATE TRIGGER [dbo].[trgNoPlayoffForYou] ON [dbo].[tplayoffStatus]
AFTER INSERT
AS

    IF EXISTS
       (
           SELECT *
           FROM   inserted i
                  INNER JOIN dbo.tcollegeFootballTeams t
                  ON i.TeamAbbreviation = t.TeamAbbreviation
           WHERE  t.Losses > 1
       )
    BEGIN
           SET  @ErrorMessage = 'You may not enter the playoffs with more than 1 loss'
           Print @ErrorMessage
           Rollback Transaction
    END


问:
Is using jQuery in Vue project preferable or not?
I have read that including jQuery inside Vue project is not advisable https://vuejsdevelopers.com/2017/05/20/vue-js-safely-jquery-plugin/

But if I include specific plugin for each task then those plugin have common code each in their own codebase. For example let's say finding some element by complex selector. This is already supported in jQuery so if I use jQuery plugin the plugin would be using jQuery's centralised code but if I use vanilla JS plugins each plugins would have their own code and may be duplicated across several plugins which would ultimately increase my JavaScript file size.

I wanted to know what is the best practise for Vue project - go with vanilla JS plugins or use jQuery and it's plugins whilst creating components for it. I am quiet confused.

It is early days since my project has started and I want to know what is the best way to include plugins? Should I include jQuery plugins in my Vue project or should I use vanilla plugins doesn't matter if most of them have duplicate code inside their plugin.

答:
I have read that including jQuery inside Vue project is not advisable

Vue-like frameworks - which make extensive use of data-binding -  don't typically need frameworks like jQuery.

The whole point of these kind of frameworks is that they build the HTML view for you based on the bound data.

This is in contrast with jQuery-only projects where you need to manually build the HTML view yourself with the help of jQuery.

I'm pretty sure that when you get the hang of how Vue works, you won't need jQuery - and in the cases you do, the DOM API will mostly have you covered.

Should I include jQuery plugins in my Vue project or should I use vanilla plugins doesn't matter if most of them have duplicate code inside their plugin?

Prefer using Vue plugins where possible. If there's a jQuery plugin that you absolutely need to use, then go for it and include jQuery.


问:
php for instagram feed
I'm trying to embed an instagram feed on a webpage. I have gone through the steps on the instagram developer page to get an access token but I don't know what to do with it. Is there php code that you can suggest that I can use to create a feed by adding the user id and the access token?</p>

答:
Look at results here, Google is your friend :)

Example

Title: php for instagram feed


问:
how to create an ubercart product content type within a module
I'd like to create a product content type from within a module. I followed this very helpful guide to programmatically create a content type. Now how do I "productize" it?

If there already exists a module that does this that I can use to learn from, please do point me in it's direction. Or perhaps there is a guide floating around somewhere?

Thanks!

答:
I was just figuring this out, this seems to work ok, its unfortunate the api doesnt support this in a official way.</p>

```<code>    function create_uc_product_type ( $name , $pcid , $description )
     {

     $pcid = preg_replace ( array ( '/\s+/' , '/\W/' ) , array ( '_' , '' ) , strtolower ( $pcid ) );

    db_query ( "INSERT INTO {uc_product_classes} (pcid, name, description) VALUES ('%s', '%s', '%s')" , $pcid , $name , $description );
    uc_product_node_info ( TRUE );
    variable_set ( 'node_options_' . $pcid , variable_get ( 'node_options_product' , array ( 'status' , 'promote' ) ) );

    if ( module_exists ( 'comment' ) ) {
        variable_set ( 'comment_' . $pcid , variable_get ( 'comment_product' , COMMENT_NODE_READ_WRITE ) );
    }

    module_invoke_all ( 'product_class' , $pcid , 'insert' );

    if ( module_exists ( 'imagefield' ) ) {
        uc_product_add_default_image_field ( $pcid );
    }

    $type = node_get_types('type', $pcid);
    $type->custom = 1;

    node_type_save($type);

    node_types_rebuild ( );
    menu_rebuild ( );

    drupal_set_message ( t ( 'Product class ' . $pcid . ' created.' ) );

}
</code>```

Body:
I was just figuring this out, this seems to work ok, its unfortunate the api doesnt support this in a official way.

    function create_uc_product_type ( $name , $pcid , $description )
     {

     $pcid = preg_replace ( array ( '/\s+/' , '/\W/' ) , array ( '_' , '' ) , strtolower ( $pcid ) );

    db_query ( "INSERT INTO {uc_product_classes} (pcid, name, description) VALUES ('%s', '%s', '%s')" , $pcid , $name , $description );
    uc_product_node_info ( TRUE );
    variable_set ( 'node_options_' . $pcid , variable_get ( 'node_options_product' , array ( 'status' , 'promote' ) ) );

    if ( module_exists ( 'comment' ) ) {
        variable_set ( 'comment_' . $pcid , variable_get ( 'comment_product' , COMMENT_NODE_READ_WRITE ) );
    }

    module_invoke_all ( 'product_class' , $pcid , 'insert' );

    if ( module_exists ( 'imagefield' ) ) {
        uc_product_add_default_image_field ( $pcid );
    }

    $type = node_get_types('type', $pcid);
    $type->custom = 1;

    node_type_save($type);

    node_types_rebuild ( );
    menu_rebuild ( );

    drupal_set_message ( t ( 'Product class ' . $pcid . ' created.' ) );

}


问:
Most efficient way to find the index of the only '1' bit in a char variable (in C)
This is an interview question:

You are given a char variable named ch, when you know that it represents a number that in its binary form, only one of its eight bits will be equal to '1'. I.E. , the only possible values for ch are: 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80.

Given the variable ch, I need to write the most efficient code to get the index of that '1' bit. For example: if ch == 0x1 -> result is 0. if ch == 0x4 -> result is 2.

The obvious way is to use switch-case, but I need something more efficient.

Is there any bit manipulation you can do here for efficient implementation?

答:
The type char may be either signed or unsigned (implementation-defined behavior). In order to safely operate on the value 0x80 we should operate explicitly with unsigned char data.

I assume that there are no special functions available that give us the bit position more or less directly, such as ffs() (find first set), clz() (count leading zeros), or popcount() (population count), and that we are to determine the bit position using just standard ISO C.

One approach is to spread each bit position in ch to a separate nibble (a four-bit group), then perform an in-register table lookup, where each table element comprises one nibble in a 32-bit int.

The expansion can be accomplished by squaring the input twice, which moves bit [i] to bit [4*i]. Code below then uses a special trick to allow extraction of the table element with a multiply and a right shift, where the multiply moves the desired table entry into bits [31:28] of the intermediate result. Note that the table is specified in a readable way and equates to the constant0x01234567, a substitution every reasonable compiler will make.

Compiler Explorer (Godbolt) shows that most of the execution time cost of uchar_bitpos() is three dependent integer multiplies plus a couple of other instructions.

This code assumes 8-bit char and 32-bit int. For better portability unsigned char variables could be turned into uint8_t variables and unsigned int variables could be turned into uint32_t variables.

#include <stdio.h>
#include <stdlib.h>

int uchar_bitpos (unsigned char ch)
{
    unsigned int ch_pow2, ch_pow4;
    const unsigned int table =
        ((0 << 28) | (1 << 24) | (2 << 20) | (3 << 16) |
         (4 << 12) | (5 <<  8) | (6 <<  4) | (7 <<  0));
    ch_pow2 = ch * ch;
    ch_pow4 = ch_pow2 * ch_pow2;
    return (ch_pow4 * table) >> 28;
}

int main (void)
{
    unsigned char a = 0x80;
    do {
        printf ("a = %2x   bitpos=%d\n", a, uchar_bitpos (a));
        a = a / 2;
    } while (a);
    return EXIT_SUCCESS;
}
```

<p>The output of the above program should look as follows:</p>

```a = 80   bitpos=7
a = 40   bitpos=6
a = 20   bitpos=5
a = 10   bitpos=4
a =  8   bitpos=3
a =  4   bitpos=2
a =  2   bitpos=1
a =  1   bitpos=0
```

Body:
The type char may be either signed or unsigned (implementation-defined behavior). In order to safely operate on the value 0x80 we should operate explicitly with unsigned char data.

I assume that there are no special functions available that give us the bit position more or less directly, such as ffs() (find first set), clz() (count leading zeros), or popcount() (population count), and that we are to determine the bit position using just standard ISO C.

One approach is to spread each bit position in ch to a separate nibble (a four-bit group), then perform an in-register table lookup, where each table element comprises one nibble in a 32-bit int.

The expansion can be accomplished by squaring the input twice, which moves bit [i] to bit [4*i]. Code below then uses a special trick to allow extraction of the table element with a multiply and a right shift, where the multiply moves the desired table entry into bits [31:28] of the intermediate result. Note that the table is specified in a readable way and equates to the constant0x01234567, a substitution every reasonable compiler will make.

Compiler Explorer (Godbolt) shows that most of the execution time cost of uchar_bitpos() is three dependent integer multiplies plus a couple of other instructions.

This code assumes 8-bit char and 32-bit int. For better portability unsigned char variables could be turned into uint8_t variables and unsigned int variables could be turned into uint32_t variables.

#include <stdio.h>
#include <stdlib.h>

int uchar_bitpos (unsigned char ch)
{
    unsigned int ch_pow2, ch_pow4;
    const unsigned int table =
        ((0 << 28) | (1 << 24) | (2 << 20) | (3 << 16) |
         (4 << 12) | (5 <<  8) | (6 <<  4) | (7 <<  0));
    ch_pow2 = ch * ch;
    ch_pow4 = ch_pow2 * ch_pow2;
    return (ch_pow4 * table) >> 28;
}

int main (void)
{
    unsigned char a = 0x80;
    do {
        printf ("a = %2x   bitpos=%d\n", a, uchar_bitpos (a));
        a = a / 2;
    } while (a);
    return EXIT_SUCCESS;
}

The output of the above program should look as follows:

a = 80   bitpos=7
a = 40   bitpos=6
a = 20   bitpos=5
a = 10   bitpos=4
a =  8   bitpos=3
a =  4   bitpos=2
a =  2   bitpos=1
a =  1   bitpos=0


问:
use python pandas to show csv to placeholder in web file
I have a csv file and need to convert it to view it in html. I know python pandas can do it with

```<code>df = pd.read_csv("myfile.csv")
df.to_html('output.html')'
</code>```

but I don't want to show it in single web page, I have index.html file and I want to show it in there but in another section.

答:
found the answer using tablib

```<code>from flask import Flask, render_template
import tablib
import os

app = Flask (__name__)
dataset = tablib.Dataset()
with open(os.path.join(os.path.dirname(__file__),'email.csv')) as f:
    dataset.csv = f.read()

@app.route("/")
def index():
    data = dataset.html
    #return dataset.html
    return render_template('index.html', data=data)

if __name__ == "__main__":
    app.run()
</code>```

index.html

```<code><html>
<head>
    <meta charset="utf-8" />
    <link rel=stylesheet type=text/css href="{{ url_for('static',
    filename='css/style.css') }}"/>
    <title>Show CSV</title>
</head>
<body>
  <div class="table">
    {% block body %}
    {{ data|safe }}
    {% endblock %}
  </div>
</body>
</html>
</code>```

Body:
I have a csv file and need to convert it to view it in html. I know python pandas can do it with

df = pd.read_csv("myfile.csv")
df.to_html('output.html')'

but I don't want to show it in single web page, I have index.html file and I want to show it in there but in another section.

Body:
found the answer using tablib

from flask import Flask, render_template
import tablib
import os

app = Flask (__name__)
dataset = tablib.Dataset()
with open(os.path.join(os.path.dirname(__file__),'email.csv')) as f:
    dataset.csv = f.read()

@app.route("/")
def index():
    data = dataset.html
    #return dataset.html
    return render_template('index.html', data=data)

if __name__ == "__main__":
    app.run()

index.html

<html>
<head>
    <meta charset="utf-8" />
    <link rel=stylesheet type=text/css href="{{ url_for('static',
    filename='css/style.css') }}"/>
    <title>Show CSV</title>
</head>
<body>
  <div class="table">
    {% block body %}
    {{ data|safe }}
    {% endblock %}
  </div>
</body>
</html>


问:
unable to start grunt - "TypeError: grunt.registerHelper is not a function" on ubuntu 16
Unable to start grunt

Trying to run grunt serve on a mean project but instead getting this:

Running "serve" task
Loading "clean.js" tasks...ERROR

TypeError: grunt.registerHelper is not a function

Running "clean:server" (clean) task
Warning: grunt.helper is not a function Use --force to continue.

Aborted due to warnings.

Execution Time (2017-11-05 07:32:02 UTC+1)
loading tasks        814ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 90%
serve                 63ms  ▇▇▇ 7%
loading grunt-clean   14ms  ▇ 2%
Total 900ms

any thoughts

答:
try: </p>

```<code>npm install
</code>```

<p>& if always persist try:</p>

```<code>bower update
npm update
</code>```

Body:
try:

npm install

& if always persist try:

bower update
npm update


问:
I'm trying to split this "for" loop to create 5 different DIV elements
thank you for passing by. I'm really a newbie and I'm trying to do (by taking some code, hopefully there's nothing wrong with that) 5 different players and I've used the following code: https://codepen.io/katzkode/pen/ZbxYYG

I'm trying to split the following loop in 5 different divs (5 different players, instead of #audio-players, there'd be a new div for each one):

```<code>function createAudioPlayers() {
    for (f in files) {
        var playerString = "<div id=\"audioplayer-" + f + "\" class=\"audioplayer\"><button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button><div id=\"timeline-" + f + "\" class=\"timeline\"><div id=\"playhead-" + f + "\" class=\"playhead\"></div></div></div>";
        $("#audio-players").append(playerString);
    }
}
</code>```

Here's the code to pull the files from:

```<code>var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];
</code>```

And I'm unsure how to proceed, I'm still learning. Thank you.

答:
Use

```<code>for (f of files) {
</code>```

inplace of

```<code>for (f in files) {
</code>```

For more details : https://bitsofco.de/for-in-vs-for-of/

Body:
thank you for passing by. I'm really a newbie and I'm trying to do (by taking some code, hopefully there's nothing wrong with that) 5 different players and I've used the following code: https://codepen.io/katzkode/pen/ZbxYYG

I'm trying to split the following loop in 5 different divs (5 different players, instead of #audio-players, there'd be a new div for each one):

function createAudioPlayers() {
    for (f in files) {
        var playerString = "
<button id=\"playbutton-" + f + "\" class=\"play playbutton\"></button>

";
        $("#audio-players").append(playerString);
    }
}

Here's the code to pull the files from:

var files = ["interlude.mp3", // 0
            "chooseyourweapon.mp3", // 1
            "interlude.mp3", // 2
            "scriptures.mp3",
       "scriptures.mp3"// 3
            ];

And I'm unsure how to proceed, I'm still learning. Thank you.

Body:
Use

for (f of files) {

inplace of

for (f in files) {

For more details : https://bitsofco.de/for-in-vs-for-of/


问:
how to mock the SmtpClient object which is used inside a function for Unit Testing
I want to write the Nunit or unit test for the SendMail method which is present in the BatchProcess without sending mails.

How to can I mock the SmtpClient which is present inside another method. Please help.

```<code>namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Assuming we are populating the emails from the data from database
            List<EmailEntity> emails = new List<EmailEntity>();
            BatchProcess.SendMail(emails);
        }
    }

    public class EmailEntity
    {
        public string ToAddress { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }

    public class BatchProcess
    {
        public static void SendMail(List<EmailEntity> emails)
        {
            foreach (EmailEntity email in emails)
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("sampleSmtp.sampleTest.com");
                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add(email.ToAddress);
                mail.Subject = email.Subject;
                mail.Body = email.Body;
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
            }
        }
    }
}
</code>```

答:
That's one of the reason why you should use Dependency Injection.

The point is that you shouldn't create an instance of SmtpClient in SendMail(). It's better to define your wrapper over SmtpClient that implements ISmtpClient interface and pass that interface to constructor of BatchProcess so that you could mock it in the test:

```<code>public interface ISmtpClient
{
    int Port { get; set; }

    ICredentialsByHost Credentials { get; set; }

    bool EnableSsl { get; set; }

    void Send(MailMessage mail);
}

public class SmtpClientWrapper : SmtpClient, ISmtpClient
{
}

public class BatchProcess
{
    private readonly ISmtpClient smtpClient;

    BatchProcess(ISmtpClient smtpClient)
    {
        this.smtpClient = smtpClient;
    }

    public void SendMail(List<EmailEntity> emails)
    {
        foreach (EmailEntity email in emails)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("your_email_address@gmail.com");
            mail.To.Add(email.ToAddress);
            mail.Subject = email.Subject;
            mail.Body = email.Body;

            //  You could leave this configuration here but it's far better to have it configured in SmtpClientWrapper constructor
            //  or at least outside the loop
            smtpClient.Port = 587;
            smtpClient.Credentials = new System.Net.NetworkCredential("username", "password");
            smtpClient.EnableSsl = true;

            smtpClient.Send(mail);
        }
    }
}
</code>```

Body:
I want to write the Nunit or unit test for the SendMail method which is present in the BatchProcess without sending mails.

How to can I mock the SmtpClient which is present inside another method. Please help.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Assuming we are populating the emails from the data from database
            List<EmailEntity> emails = new List<EmailEntity>();
            BatchProcess.SendMail(emails);
        }
    }

    public class EmailEntity
    {
        public string ToAddress { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }

    public class BatchProcess
    {
        public static void SendMail(List<EmailEntity> emails)
        {
            foreach (EmailEntity email in emails)
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("sampleSmtp.sampleTest.com");
                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add(email.ToAddress);
                mail.Subject = email.Subject;
                mail.Body = email.Body;
                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
            }
        }
    }
}

Body:
That's one of the reason why you should use Dependency Injection.

The point is that you shouldn't create an instance of SmtpClient in SendMail(). It's better to define your wrapper over SmtpClient that implements ISmtpClient interface and pass that interface to constructor of BatchProcess so that you could mock it in the test:

public interface ISmtpClient
{
    int Port { get; set; }

    ICredentialsByHost Credentials { get; set; }

    bool EnableSsl { get; set; }

    void Send(MailMessage mail);
}

public class SmtpClientWrapper : SmtpClient, ISmtpClient
{
}

public class BatchProcess
{
    private readonly ISmtpClient smtpClient;

    BatchProcess(ISmtpClient smtpClient)
    {
        this.smtpClient = smtpClient;
    }

    public void SendMail(List<EmailEntity> emails)
    {
        foreach (EmailEntity email in emails)
        {
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("your_email_address@gmail.com");
            mail.To.Add(email.ToAddress);
            mail.Subject = email.Subject;
            mail.Body = email.Body;

            //  You could leave this configuration here but it's far better to have it configured in SmtpClientWrapper constructor
            //  or at least outside the loop
            smtpClient.Port = 587;
            smtpClient.Credentials = new System.Net.NetworkCredential("username", "password");
            smtpClient.EnableSsl = true;

            smtpClient.Send(mail);
        }
    }
}


问:
jQuery matching multiple classes
For the first time, I got in this kind of unusual situtation

I have to select a div on which more than 2 classes are applied, that to in random order

For Example:

Assume that I have a
 on which following 3 classes are applied
content-text, right-align and bold-font. I need to select this div, but problem is that classes are applied in different order on different pages

```<code><div class="content-text right-align bold-font">...</div>
<div class="right-align content-text bold-font">...</div>
<div class="content-text bold-font right-align ">...</div>
...
</code>```

How can I select this particular div, no matter how classes are applied?

Thanks

答:
This will work fine. CSS selectors in general don't care about the order of classes, just the ones that are applied. This also goes for jQuery:</p>

```<code>$('div.content-text.right-align.bold-font');
</code>```

Title: jQuery matching multiple classes

Body:
For the first time, I got in this kind of unusual situtation

I have to select a div on which more than 2 classes are applied, that to in random order

For Example:

Assume that I have a
 on which following 3 classes are applied
content-text, right-align and bold-font. I need to select this div, but problem is that classes are applied in different order on different pages

...

...

...

...

How can I select this particular div, no matter how classes are applied?

Thanks

Body:
This will work fine. CSS selectors in general don't care about the order of classes, just the ones that are applied. This also goes for jQuery:

$('div.content-text.right-align.bold-font');


问:
Prompting user to select pen color doesn't function
I'm supposed to prompt the user to select a pen color based on ones that I've picked out. I've already included an if, else if, else stamtement plus and .equalsignorecase, but whenever I run the file, it won't let me input anything?

(Also my variable "color" is defined as a string if that helps.)

Edit: I already have a scanner class embedded into my code. It's:

```<code>Scanner cool=new Scanner(system.in)
</code>```

Hence any of my code that has "cool" in it is the name I've given my scanner.

```<code>System.out.println("Please enter the color that you wish to use to draw your point(color options: Red, blue, light blue, pink, green, orange, magenta, and yellow):");
color=cool.nextLine();

StdDraw.setPenRadius(0.05);
StdDraw.circle(2, 2, 4);

if ("red".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.RED);}

else if ("blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BLUE);}

else if ("light blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);}

else if ("pink".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.PINK);}

else if ("green".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.GREEN);}

else if ("orange".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.ORANGE);}

else if ("magenta".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.MAGENTA);}

else if ("yellow".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.YELLOW);}

else
{
   StdDraw.setPenColor(StdDraw.CYAN);
}
</code>```

答:
According to your question, it is supposed that you want to show what you have input. Below are some relevant input process:

You can use any of the following options based on the requirements.

Scanner class

```<code>import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
</code>```

BufferedReader and InputStreamReader classes

```<code>import java.io.BufferedReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(br.readLine());
</code>```

DataInputStream class

```<code>import java.io.DataInputStream;
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();
</code>```

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader

Console class

```<code>import java.io.Console;
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
</code>```

Apparently, this method does not work well in some IDEs. The input you have taken can be printed / prompted by System.out.println(input_object) .

Body:
I'm supposed to prompt the user to select a pen color based on ones that I've picked out. I've already included an if, else if, else stamtement plus and .equalsignorecase, but whenever I run the file, it won't let me input anything?

(Also my variable "color" is defined as a string if that helps.)

Edit: I already have a scanner class embedded into my code. It's:

Scanner cool=new Scanner(system.in)

Hence any of my code that has "cool" in it is the name I've given my scanner.

System.out.println("Please enter the color that you wish to use to draw your point(color options: Red, blue, light blue, pink, green, orange, magenta, and yellow):");
color=cool.nextLine();

StdDraw.setPenRadius(0.05);
StdDraw.circle(2, 2, 4);

if ("red".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.RED);}

else if ("blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BLUE);}

else if ("light blue".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.BOOK_LIGHT_BLUE);}

else if ("pink".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.PINK);}

else if ("green".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.GREEN);}

else if ("orange".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.ORANGE);}

else if ("magenta".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.MAGENTA);}

else if ("yellow".equalsIgnoreCase(color))
{StdDraw.setPenColor(StdDraw.YELLOW);}

else
{
   StdDraw.setPenColor(StdDraw.CYAN);
}

Body:
According to your question, it is supposed that you want to show what you have input. Below are some relevant input process:

You can use any of the following options based on the requirements.

Scanner class

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();

BufferedReader and InputStreamReader classes

import java.io.BufferedReader;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(br.readLine());

DataInputStream class

import java.io.DataInputStream;
DataInputStream dis = new DataInputStream(System.in);
int i = dis.readInt();

The readLine method from the DataInputStream class has been deprecated. To get String value, you should use the previous solution with BufferedReader

Console class

import java.io.Console;
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());

Apparently, this method does not work well in some IDEs. The input you have taken can be printed / prompted by System.out.println(input_object) .


问:
mysql table column update
I am trying to update Registered_User_Contact table

```<code>select t1.username , t2.username, t1.registered_user_id, t2.registered_user_id from Registered_User_Contact t2 inner join Registered_User t1 on t1.username = t2.username;

-----------+------------+--------------------+--------------------+
| username   | username   | registered_user_id | registered_user_id |
+------------+------------+--------------------+--------------------+
| bose       | bose       |                  1 |               NULL |
| chiragjain | chiragjain |                  2 |               NULL |
| mike1      | mike1      |                  3 |               NULL
</code>```

this is my SQL command:

```<code>UPDATE Registered_User_Contact set t2.registered_user_id = t1.registered_user_id from Registered_User t1 inner join Registered_User_Contact t2 on t1.username = t2.username;
</code>```

答:
Your syntax for an update join is off.  Try the following instead:</p>

```<code>UPDATE Registered_User_Contact t1
INNER JOIN Registered_User t2
    ON t1.username = t2.username
SET t1.registered_user_id = t2.registered_user_id;
</code>```

Title: mysql table column update

Body:
I am trying to update Registered_User_Contact table

select t1.username , t2.username, t1.registered_user_id, t2.registered_user_id from Registered_User_Contact t2 inner join Registered_User t1 on t1.username = t2.username;

-----------+------------+--------------------+--------------------+
| username   | username   | registered_user_id | registered_user_id |
+------------+------------+--------------------+--------------------+
| bose       | bose       |                  1 |               NULL |
| chiragjain | chiragjain |                  2 |               NULL |
| mike1      | mike1      |                  3 |               NULL

this is my SQL command:

UPDATE Registered_User_Contact set t2.registered_user_id = t1.registered_user_id from Registered_User t1 inner join Registered_User_Contact t2 on t1.username = t2.username;

Body:
Your syntax for an update join is off.  Try the following instead:

UPDATE Registered_User_Contact t1
INNER JOIN Registered_User t2
    ON t1.username = t2.username
SET t1.registered_user_id = t2.registered_user_id;


问:
Ionic Text color change onclick
I'm a beginner in Ionic 3.

I have a 4 text in same color, I'm trying to make when I click on the 4 text at for time I want to change color.

Example

I click on 1st text, then I want to change it black color
I click on text 2, then I want to change black color and 1st text  is  set a default color,

Please help me to fix this issue

```<code>    <div class="row">
      <div  class="col right-border">
        <div  text-center>
          <h2 class="main-one" >$ 2,300</h2> <p class="main-txt-home">Today's Revenue</p>
        </div>
      </div>
      <div  class="col bottom-border">
        <div text-center>
          <h2  class="main-one">$ 53,100</h2><p class="main-txt-home">Expected Revenue for this month</p>
        </div>
      </div>
    </div>
    <div class="row">
      <div  class="col top-border">
        <div  text-center>
          <h2  class="main-one">12</h2><p class="main-txt-home"> Bookings taken today</p>
        </div>
      </div>
      <div class="col left-border">
        <div  text-center>
          <h2  class="main-one">68%</h2><p class="main-txt-home">Total Monthly occupancy</p>
        </div>
      </div>
    </div>
  </div>
</code>```

答:
You can use [ngClass] attribute to achieve this. This can be used to dynamically return the class name as per the last clicked text. The code will be something like below.

```<code> <div class="row">
  <div  class="col right-border">
    <div  text-center [ngClass]="getTextColor('text1')" (click)="setSelectedText('text1')">
      <h2 class="main-one" >$ 2,300</h2> <p class="main-txt-home">Today's Revenue</p>
    </div>
  </div>
  <div  class="col bottom-border">
    <div text-center [ngClass]="getTextColor('text2')"  (click)="setSelectedText('text2')">
      <h2  class="main-one">$ 53,100</h2><p class="main-txt-home">Expected Revenue for this month</p>
    </div>
  </div>
</div>
<div class="row">
  <div  class="col top-border">
    <div  text-center [ngClass]="getTextColor('text3')"  (click)="setSelectedText('text3')">
      <h2  class="main-one">12</h2><p class="main-txt-home"> Bookings taken today</p>
    </div>
  </div>
  <div class="col left-border">
    <div  text-center>
      <h2  class="main-one">68%</h2><p class="main-txt-home">Total Monthly occupancy</p>
    </div>
  </div>
</div>
</code>```

In controller

```<code> private selecteTextId :string;

 setSelectedText(textId:string) {
     this.selecteTextId = textId;
 }

 getTextColor(textId:string):string{
   return this.selecteTextId == textId? "highlight-color" : "";
 }
</code>```

In scss file

```<code>.highlight-color {
  color:blue;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Ionic Text color change onclick

Body:
I'm a beginner in Ionic 3.

I have a 4 text in same color, I'm trying to make when I click on the 4 text at for time I want to change color.

Example

I click on 1st text, then I want to change it black color
I click on text 2, then I want to change black color and 1st text  is  set a default color,

Please help me to fix this issue

$ 2,300

Today's Revenue

$ 53,100

Expected Revenue for this month

12

 Bookings taken today

68%

Total Monthly occupancy

Body:
You can use [ngClass] attribute to achieve this. This can be used to dynamically return the class name as per the last clicked text. The code will be something like below.

 <div class="row">
  <div  class="col right-border">
    <div  text-center [ngClass]="getTextColor('text1')" (click)="setSelectedText('text1')">
      <h2 class="main-one" >$ 2,300</h2> <p class="main-txt-home">Today's Revenue</p>
    </div>
  </div>
  <div  class="col bottom-border">
    <div text-center [ngClass]="getTextColor('text2')"  (click)="setSelectedText('text2')">
      <h2  class="main-one">$ 53,100</h2><p class="main-txt-home">Expected Revenue for this month</p>
    </div>
  </div>
</div>
<div class="row">
  <div  class="col top-border">
    <div  text-center [ngClass]="getTextColor('text3')"  (click)="setSelectedText('text3')">
      <h2  class="main-one">12</h2><p class="main-txt-home"> Bookings taken today</p>
    </div>
  </div>
  <div class="col left-border">
    <div  text-center>
      <h2  class="main-one">68%</h2><p class="main-txt-home">Total Monthly occupancy</p>
    </div>
  </div>
</div>

In controller

 private selecteTextId :string;

 setSelectedText(textId:string) {
     this.selecteTextId = textId;
 }

 getTextColor(textId:string):string{
   return this.selecteTextId == textId? "highlight-color" : "";
 }

In scss file

.highlight-color {
  color:blue;
}


问:
Gitlab Continuous Delivery options
I'm iOS developer and
I've been playing with Gitlab lately trying to figure out if it's better/more convenient than redmine+jenkins+HockeyApp. Gitlab seems to be quite cool except for I cannot figure out how to upload my ad-hoc iOS build to HockeyApp (or TestFlight). Is it even possible?

Thanks

答:
I ended up with the following configuration:

add deploy.sh file:

```<code>#!/bin/bash
echo "deploy to hockeyapp"

HOCKEYAPP_APP_NAME="MyApp.iOS.ipa"
HOCKEYAPP_TOKEN="MyTOKEN"
HOCKEYAPP_ID="MYAPPID"

function buildNotes {

    # We need an initial bullet point for our list of commit logs
    echo -n "* "
    # Get the latest app uploads
    curl -H "X-HockeyAppToken: $HOCKEYAPP_TOKEN" \
    "https://rink.hockeyapp.net/api/2/apps/$HOCKEYAPP_ID/app_versions?page=1" | \
    # Put every property on a separate line
    sed 's/,/\n/g' | \
    # Remove all the quotation marks
    sed 's/"//g' | \
    # Look at only the notes properties
    grep notes | \
    # Look at the first one, i.e. the latest app upload
    head -n 1 | \
    # Find the commit information at the bottom of the notes
    sed -n 's/.*(commit:\([^)]*\)).*/\1/p' | \
    # Let's find all the logs since that commit
    xargs -I '{}' git log {}..HEAD --pretty=format:'%h %s' --no-merges | \
    # Add a star to each newline to make the list
    sed ':a;N;$!ba;s/\n/\n* /g'
    # The end of the revision log must have the latest commit
    # This is so later we can do the above again
    echo
    echo -n "* (commit:"
    git rev-parse HEAD | xargs echo -n
    echo -n ')'
}

function deployAppFlavor () {
    echo "executeCurlCommand"
    curl -F "status=2" \
    -F "notify=1" \
    -F "notes=<release_notes" \
    -F "notes_type=0" \
    -F "ipa=@src/build/MyApp.iOS.ipa/$1" \
    -H "X-HockeyAppToken: $2"\
     "https://rink.hockeyapp.net/api/2/apps/$3/app_versions/upload"
}

function deployApp {
    buildNotes > release_notes
    deployAppFlavor $HOCKEYAPP_APP_NAME $HOCKEYAPP_TOKEN $HOCKEYAPP_ID
}

deployApp
</code>```

and then update yml file:

```<code> build_project:
   stage: build

   script:
     - xcodebuild clean -workspace MyApp.iOS.xcworkspace -scheme MyApp.iOS -quiet
     - xcodebuild build -workspace MyApp.iOS.xcworkspace -scheme MyApp.iOS -destination 'platform=iOS Simulator,name=iPhone 6s' | xcpretty -s > -quiet

 archive_project:
   stage: archive
   script:
     - xcodebuild clean archive -archivePath "build/MyApp.iOS.xcarchive" -workspace "MyApp.iOS.xcworkspace" -scheme MyApp.iOS -quiet
     - xcodebuild -exportArchive -archivePath "build/MyApp.IOS.xcarchive" -exportPath "build/MyApp.iOS.ipa" -exportOptionsPlist "export.plist" -quiet
   artifacts:
     paths:
       - src/build/MyApp.iOS.ipa

 deploy:
   before_script:
     - chmod +x ./scripts/deploy.sh
   stage: deploy
   script:
     - ./scripts/deploy.sh
</code>```

Title: Gitlab Continuous Delivery options

Body:
I ended up with the following configuration:

add deploy.sh file:

#!/bin/bash
echo "deploy to hockeyapp"

HOCKEYAPP_APP_NAME="MyApp.iOS.ipa"
HOCKEYAPP_TOKEN="MyTOKEN"
HOCKEYAPP_ID="MYAPPID"

function buildNotes {

    # We need an initial bullet point for our list of commit logs
    echo -n "* "
    # Get the latest app uploads
    curl -H "X-HockeyAppToken: $HOCKEYAPP_TOKEN" \
    "https://rink.hockeyapp.net/api/2/apps/$HOCKEYAPP_ID/app_versions?page=1" | \
    # Put every property on a separate line
    sed 's/,/\n/g' | \
    # Remove all the quotation marks
    sed 's/"//g' | \
    # Look at only the notes properties
    grep notes | \
    # Look at the first one, i.e. the latest app upload
    head -n 1 | \
    # Find the commit information at the bottom of the notes
    sed -n 's/.*(commit:\([^)]*\)).*/\1/p' | \
    # Let's find all the logs since that commit
    xargs -I '{}' git log {}..HEAD --pretty=format:'%h %s' --no-merges | \
    # Add a star to each newline to make the list
    sed ':a;N;$!ba;s/\n/\n* /g'
    # The end of the revision log must have the latest commit
    # This is so later we can do the above again
    echo
    echo -n "* (commit:"
    git rev-parse HEAD | xargs echo -n
    echo -n ')'
}

function deployAppFlavor () {
    echo "executeCurlCommand"
    curl -F "status=2" \
    -F "notify=1" \
    -F "notes=<release_notes" \
    -F "notes_type=0" \
    -F "ipa=@src/build/MyApp.iOS.ipa/$1" \
    -H "X-HockeyAppToken: $2"\
     "https://rink.hockeyapp.net/api/2/apps/$3/app_versions/upload"
}

function deployApp {
    buildNotes > release_notes
    deployAppFlavor $HOCKEYAPP_APP_NAME $HOCKEYAPP_TOKEN $HOCKEYAPP_ID
}

deployApp

and then update yml file:

 build_project:
   stage: build

   script:
     - xcodebuild clean -workspace MyApp.iOS.xcworkspace -scheme MyApp.iOS -quiet
     - xcodebuild build -workspace MyApp.iOS.xcworkspace -scheme MyApp.iOS -destination 'platform=iOS Simulator,name=iPhone 6s' | xcpretty -s > -quiet

 archive_project:
   stage: archive
   script:
     - xcodebuild clean archive -archivePath "build/MyApp.iOS.xcarchive" -workspace "MyApp.iOS.xcworkspace" -scheme MyApp.iOS -quiet
     - xcodebuild -exportArchive -archivePath "build/MyApp.IOS.xcarchive" -exportPath "build/MyApp.iOS.ipa" -exportOptionsPlist "export.plist" -quiet
   artifacts:
     paths:
       - src/build/MyApp.iOS.ipa

 deploy:
   before_script:
     - chmod +x ./scripts/deploy.sh
   stage: deploy
   script:
     - ./scripts/deploy.sh


问:
Encoding error when attempt to install matplotlib on ubuntu
I'm attempting to install matplotlib in a python2 virtualenv in Ubuntu 14.04, and am running into the following error:

```<code>../virtualenv/bin/pip install matplotlib

Traceback (most recent call last):
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/basecommand.py", line 211, in main
    status = self.run(options, args)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/commands/install.py", line 305, in run
    wb.build(autobuilding=True)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/wheel.py", line 705, in build
    self.requirement_set.prepare_files(self.finder)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/req/req_set.py", line 334, in prepare_files
    functools.partial(self._prepare_file, finder))
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/req/req_set.py", line 321, in _walk_req_to_install
    more_reqs = handler(req_to_install)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/req/req_set.py", line 491, in _prepare_file
    session=self.session)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 825, in unpack_url
    session,
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 673, in unpack_http_url
    from_path, content_type = _download_http_url(link, session, temp_dir)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 886, in _download_http_url
    _download_url(resp, link, content_file)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 621, in _download_url
    for chunk in progress_indicator(resp_read(4096), 4096):
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/utils/ui.py", line 133, in iter
    for x in it:
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 586, in resp_read
    decode_content=False):
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 307, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 243, in read
    data = self._fp.read(amt)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 54, in read
    self.__callback(self.__buf.getvalue())
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/controller.py", line 224, in cache_response
    self.serializer.dumps(request, response, body=body),
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 49, in dumps
    "body": _b64_encode_bytes(body),
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 12, in _b64_encode_bytes
    return base64.b64encode(b).decode("ascii")
MemoryError
</code>```

Any thoughts about what might be going on and why I am getting a Memory Error?

答:
This appears to be the MemoryError while trying to install a large package (matplotlib) in a low memory environment. It appears that the cause is the caching mechanism, as disabling the cache fixes the issue.

Try this:

pip install --no-cache-dir matplotlib

Body:
I'm attempting to install matplotlib in a python2 virtualenv in Ubuntu 14.04, and am running into the following error:

../virtualenv/bin/pip install matplotlib

Traceback (most recent call last):
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/basecommand.py", line 211, in main
    status = self.run(options, args)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/commands/install.py", line 305, in run
    wb.build(autobuilding=True)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/wheel.py", line 705, in build
    self.requirement_set.prepare_files(self.finder)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/req/req_set.py", line 334, in prepare_files
    functools.partial(self._prepare_file, finder))
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/req/req_set.py", line 321, in _walk_req_to_install
    more_reqs = handler(req_to_install)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/req/req_set.py", line 491, in _prepare_file
    session=self.session)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 825, in unpack_url
    session,
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 673, in unpack_http_url
    from_path, content_type = _download_http_url(link, session, temp_dir)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 886, in _download_http_url
    _download_url(resp, link, content_file)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 621, in _download_url
    for chunk in progress_indicator(resp_read(4096), 4096):
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/utils/ui.py", line 133, in iter
    for x in it:
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/download.py", line 586, in resp_read
    decode_content=False):
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 307, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py", line 243, in read
    data = self._fp.read(amt)
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py", line 54, in read
    self.__callback(self.__buf.getvalue())
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/controller.py", line 224, in cache_response
    self.serializer.dumps(request, response, body=body),
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 49, in dumps
    "body": _b64_encode_bytes(body),
  File "/home/me/sites/dashboard.mysite.com/virtualenv/local/lib/python2.7/site-packages/pip/_vendor/cachecontrol/serialize.py", line 12, in _b64_encode_bytes
    return base64.b64encode(b).decode("ascii")
MemoryError

Any thoughts about what might be going on and why I am getting a Memory Error?


问:
UWP : How to get new size of shape after rotation?
How to measure its width and height after rotation in UWP? It can be any shape, such as a polygon or ellipse.

答:
Just calculate coordinates of extremal points.

For polygons

```<code>left = min(p[i].x)
right = max(p[i].x)
top = min(p[i].y)
bottom = max(p[i].y)
</code>```

For ellipse or another analytical curves  get extremal coordinates analytically

```<code>solve X'(t) = 0 for t=tz
(there are some subtle moments for min/max finding through derivatives)
find min and max from X(tz) and curve ends and so on
</code>```

Body:
Just calculate coordinates of extremal points.

For polygons

left = min(p[i].x)
right = max(p[i].x)
top = min(p[i].y)
bottom = max(p[i].y)

For ellipse or another analytical curves  get extremal coordinates analytically

solve X'(t) = 0 for t=tz
(there are some subtle moments for min/max finding through derivatives)
find min and max from X(tz) and curve ends and so on


答:
Use

document.querySelector("#mydiv svg") !== null

or

document.querySelector("#mydiv svg").querySelector("svg") !== null

Title: How to check if a div has an svg in it using JavaScript?

Body:
I have a div like the following with a question mark in it...

?

In my code, when someone tries to submit a form, I do a check to see if that field has a question mark in it, like this:

const fieldText = $('#mydiv').text();
return fieldText.indexOf('?') !== -1;

That works fine, but now, instead of a question mark in that div, I have an SVG of a question mark (rather than just a text question mark), like this.

  <svg version='1.1' id='Layer_1' class='q-mark-svg' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' viewBox='0 0 50 50' style='enable-background:new 0 0 50 50;' xml:space='preserve'>

    <g>
      <g>
        <path class='q-mark' d='M18.3,17.2c0,0.4-0.1,0.7-0.2,1c-0.1,0.3-0.3,0.6-0.5,0.8c-0.2,0.2-0.5,0.4-0.8,0.5c-0.3,0.1-0.6,0.2-1,0.2 c-0.7,0-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8c0-1.6,0.3-3.2,0.9-4.6c0.6-1.4,1.5-2.7,2.6-3.8s2.3-1.9,3.8-2.5 c1.4-0.6,3-0.9,4.6-0.9s3.1,0.3,4.6,1c1.4,0.6,2.7,1.5,3.8,2.6s1.9,2.3,2.6,3.8c0.6,1.4,0.9,2.9,0.9,4.5c0,3.2-1.2,6-3.5,8.4 l-3.8,3.5c-1.3,1.3-2,2.7-2,4.3c0,0.7-0.2,1.3-0.7,1.8c-0.5,0.5-1.1,0.7-1.8,0.7s-1.3-0.2-1.8-0.7c-0.5-0.5-0.7-1.1-0.7-1.8 c0-2.9,1.2-5.6,3.5-7.9l3.8-3.6c1.3-1.4,2-2.9,2-4.8c0-0.9-0.2-1.8-0.5-2.6c-0.4-0.8-0.8-1.5-1.5-2.1c-0.6-0.6-1.3-1.1-2.1-1.5 c-0.8-0.4-1.7-0.5-2.6-0.5c-0.9,0-1.8,0.2-2.6,0.5c-0.8,0.4-1.5,0.8-2.1,1.4c-0.6,0.6-1.1,1.3-1.4,2.1 C18.5,15.3,18.3,16.2,18.3,17.2z M28.5,40.9c0,1-0.3,1.8-1,2.5c-0.7,0.7-1.5,1-2.5,1c-1,0-1.8-0.3-2.5-1c-0.7-0.7-1-1.5-1-2.5 c0-1,0.3-1.8,1-2.5c0.7-0.7,1.5-1,2.5-1c1,0,1.8,0.3,2.5,1C28.2,39.1,28.5,40,28.5,40.9z'/>
      </g>
    </g>
  </svg>

I still want to run a check on that div, but now I have to check to see if it has an SVG in it, rather than just "?".  How can I use JS to check if a div has an svg element in it?

FYI, I tried the following since I thought it would still look for the text, but to no avail...

const fieldText = $('#mydiv').text();
return fieldText.indexOf('svg') !== -1;


问:
Format datepicker not change angularjs
i have define the format for my datepicker like this

```<code>    $scope.open1 = function() {
    $scope.popup1.opened = true;
  };

  $scope.open2 = function() {
    $scope.popup2.opened = true;
  };
  $scope.formats = ['dd-MMMM-yyyy', 'yyyyMMdd'];
  $scope.format = $scope.formats[1];
  $scope.dt = new Date();
  $scope.dt2 = new Date();
  console.log($scope.dt);
  $scope.popup1 = {
    opened: false
  };

  $scope.popup2 = {
    opened: false
  };
</code>```

but when i console.log, the result becoming like this

i want something like when i console.log the result will be same as i define. for example Tue Nov 14 2017 into 20171114

here is my .html file

```<code><div class="col-md-2">
        <p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt2" is-open="popup2.opened"/>
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open2()"><i class="glyphicon glyphicon-calendar"></i></button>
          </span>
        </p>
        </div>
</code>```

答:
it works for me, hope it helps</p>

```<code>var d = new Date($scope.dt);
  var curr_year = d.getFullYear();
  var curr_Month = d.getMonth()+1;
          if (curr_Month.toString().length < 2) {
            var curr_Month = "0" + (d.getMonth()+1);
          } else {
            var curr_Month = d.getMonth()+1;
          }
          //alert(curr_Month);

          var curr_date = d.getDate();
          if (curr_date.toString().length<2) {
            var curr_date = "0"+ d.getDate();
          } else {
            var curr_date = d.getDate();
          }
          //alert(curr_date);
          var todayDate = (curr_year + "" + (curr_Month) + "" + curr_date);
</code>```

Title: Format datepicker not change angularjs

Body:
i have define the format for my datepicker like this

    $scope.open1 = function() {
    $scope.popup1.opened = true;
  };

  $scope.open2 = function() {
    $scope.popup2.opened = true;
  };
  $scope.formats = ['dd-MMMM-yyyy', 'yyyyMMdd'];
  $scope.format = $scope.formats[1];
  $scope.dt = new Date();
  $scope.dt2 = new Date();
  console.log($scope.dt);
  $scope.popup1 = {
    opened: false
  };

  $scope.popup2 = {
    opened: false
  };

but when i console.log, the result becoming like this

i want something like when i console.log the result will be same as i define. for example Tue Nov 14 2017 into 20171114

here is my .html file

          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt2" is-open="popup2.opened"/>

            <button type="button" class="btn btn-default" ng-click="open2()"></button>

Body:
it works for me, hope it helps

var d = new Date($scope.dt);
  var curr_year = d.getFullYear();
  var curr_Month = d.getMonth()+1;
          if (curr_Month.toString().length < 2) {
            var curr_Month = "0" + (d.getMonth()+1);
          } else {
            var curr_Month = d.getMonth()+1;
          }
          //alert(curr_Month);

          var curr_date = d.getDate();
          if (curr_date.toString().length<2) {
            var curr_date = "0"+ d.getDate();
          } else {
            var curr_date = d.getDate();
          }
          //alert(curr_date);
          var todayDate = (curr_year + "" + (curr_Month) + "" + curr_date);


问:
How to configure iOs UITextViews and UILabels so that their height is determined by their content
I am basically trying to find the correct way to design a UITableViewCell that has two UITextViews and three UILabels inside it. The two UITextViews have dynamic content and their size cannot be determined until runtime.

I have tried various methods of recalculating the height of my UITextViews based on the content that is loaded in them at runtime, and though very laborious and inane, I have gotten that to work, but they then bleed over the UILabels positioned in the xib below them.

Do I really have to recalculate the y coordinates of every UILabel after calculating the new size of the UITextViews? Is there a way to simply have the elements in the xib 'push' the elements below them down based on their new size?

What is the correct approach to configuring a UITableViewCell with multiple dynamic text views so that my entire application is not comprised of code to calculate heights and coordinates?

Or is the answer that I should not be putting more than one dynamic UITextView in the same UITableViewCell ?

答:
I have used something like this for a cell to calculate its height in

```<code>tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
</code>```

function

```<code>    CGSize labelSize = [self.comments sizeWithFont:[UIFont fontWithName:@"Verdana" size:17.0]
                                                 constrainedToSize:CGSizeMake(280.0f, MAXFLOAT)
                                                     lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height + 20;
</code>```

+20 is for padding.

and also if you are having every cell like the one you mention above, than you can create a class of UITableViewCell with following UIView elements inside it.

Body:
I have used something like this for a cell to calculate its height in

tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

function

    CGSize labelSize = [self.comments sizeWithFont:[UIFont fontWithName:@"Verdana" size:17.0]
                                                 constrainedToSize:CGSizeMake(280.0f, MAXFLOAT)
                                                     lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height + 20;

+20 is for padding.

and also if you are having every cell like the one you mention above, than you can create a class of UITableViewCell with following UIView elements inside it.


问:
Why do ListView items not grow to wrap their content?
I have a rather complex ListView, with variable list item heights. Under certain conditions, I need to display an additional view in a list item, which is hidden by default (View.GONE). By enabling it (View.VISIBLE), the list item grows in height (or at least it's supposed to).

The problem:
Even though I declare the item's root layout to wrap_content, and each component in the item to fill_parent, the view I hide/show which is supposed to change the item's height is simply cut off at the bottom instead of its parent (the item layout) growing in height to fully display it.

Are there any gotchas related to ListViews and item layouts and item height which I may have missed?

Some more observations:

For testing purposes, I have now reduced the list item layout to just contain the root LinearLayout and an ImageView. When I set the LinearLayout height to e.g. 200dip and the ImageView to fill_parent, I would have expected the ImageView to grow until it hits the 200dip limit set by its parent.

However, the image will instead be only ever as tall as its bitmap resource (as if I had set it to wrap_content) and the whole list item will be of the same height (i.e. as if I had set it to wrap_content, too).

If however, I set the image height to e.g. 200dip, then the list item will grow in height, and so will the item layout.

In other words, the layout_height of the list item layout is completely ignored, and so is any height value on ImageView other than a hard-coded pixel value.

答:
this works for me     </p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:text="@string/text_list_devices" />

    <ListView
        android:id="@+id/lv_paired"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:cacheColorHint="#00000000"
        android:layout_above="@+id/signup_t"
        android:layout_below="@id/tv_status"
        />

    <Button

        android:id="@+id/signup_t"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"
        android:layout_alignParentBottom="true"
        android:text="Print All Records"
        android:typeface="sans"
        android:layout_marginLeft="45dp"
        android:layout_marginRight="45dp"
        android:textSize="24sp"
        android:background="@drawable/selector_for_button"
        android:textStyle="bold" />
</RelativeLayout>
</code>```

Body:
this works for me

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:padding="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tv_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="17sp"
        android:text="@string/text_list_devices" />

    <ListView
        android:id="@+id/lv_paired"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:cacheColorHint="#00000000"
        android:layout_above="@+id/signup_t"
        android:layout_below="@id/tv_status"
        />

    <Button

        android:id="@+id/signup_t"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textColor="@android:color/white"
        android:layout_alignParentBottom="true"
        android:text="Print All Records"
        android:typeface="sans"
        android:layout_marginLeft="45dp"
        android:layout_marginRight="45dp"
        android:textSize="24sp"
        android:background="@drawable/selector_for_button"
        android:textStyle="bold" />
</RelativeLayout>


答:
I think this is slightly nicer code to get the results you want. Note I'm not retaining the "%" as you have indicated you want to select the larger of columns later. This way we convert to numbers and only use the columns we need, we also get rid of the annoying spaces in the column names from the beginning. By setting the index, we can get Pandas to line up the entries without calling merge.</p>

```<code>def parse_percentage(perc_string):
    "Parse the percentage strings of the form 99.00% (99.00%)"
    return float(perc_string.split('%')[0])

t1 = pd.read_csv('t1.csv',
                 skipfooter=1,
                 engine='python',
                 sep=' *, *',  # This gets rid of the spaces
                 index_col='Host',
                 usecols=['Host', 'Time Up'],
                 converters={'Time Up': parse_percentage})

t2 = pd.read_csv('t2.csv',
                  skipfooter=1,
                  engine='python',
                  sep=' *, *',
                  usecols=['Host', 'Service', 'Time OK'],
                  converters={'Time OK': parse_percentage}).fillna(method='ffill').set_index('Host')

combined = pandas.concat([t1, t2[t2.Service == 'server_hit_rate']['Time OK']], axis=1)
combined.to_csv('test.csv)
</code>```

Title: column operation in csv [python]

Body:
I have a scenario where I am extracting a row value from a csv file.

(CSV) test1:

    Host, Time Up, Time Down, Time Unreachable, Time Undetermined
server1.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000

(CSV) test2:

Host,Service, Time OK, Time Warning, Time Unknown, Time Critical, Time Undetermined
server1.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
server2.test.com:1717,application_availability_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,server_hit_rate,99.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,max_hit_rate,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_log_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
,application_sessions_check,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000
Average,100.000% (100.000%),0.000% (0.000%),0.000% (0.000%),0.000% (0.000%),0.000

This is my code:

df = pd.read_csv('test1.csv',skipfooter=1)
df2 = pd.read_csv('test2.csv',skipfooter=1)
combined = pd.merge(df[['Host',' Time Up']],df2[['Host',' Time OK']], on='Host')
combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])

Here I am trying to get the value of "server_hit_rate" which is 99% & belongs to 3rd row data.
But with this above code I am able to get the data which is in first row only. i.e.

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%   100.000%
1  server2.test.com:1717  100.000%   100.000%

The required output should be:

                    Host    Time Up    Time OK
0  server1.test.com:1717  100.000%    99.000%
1  server2.test.com:1717  100.000%    99.000%

Any advice to achieve the following will be helpful.

Edit1:

import pandas as pd
import pandas
import os, shutil, glob
import sys
import datetime
import time
def t1():
    import pandas as pd
    import pandas
    today=datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
    print "date :", today
    df = pd.read_csv('t1.csv',skipfooter=1, engine='python')
    df2 = pd.read_csv('t2.csv',skipfooter=1, engine='python')
    temp = df2.ffill()[df2['Service']=='server_hit_rate']
    combined = pd.merge(df[['Host',' Time Up']],temp[['Host',' Time OK']], on='Host')
    combined[' Time OK'] = combined[' Time OK'].apply(lambda x: x.split('(')[0])
    combined[' Time Up'] = combined[' Time Up'].apply(lambda x: x.split('(')[0])
    combined.to_csv('test.csv',index=False)
t1()

O/P:

Wed Nov 15 10:07:01  2017
Empty DataFrame
Columns: [Host, % Time Up, % Time OK]
Index: []

Body:
I think this is slightly nicer code to get the results you want. Note I'm not retaining the "%" as you have indicated you want to select the larger of columns later. This way we convert to numbers and only use the columns we need, we also get rid of the annoying spaces in the column names from the beginning. By setting the index, we can get Pandas to line up the entries without calling merge.

def parse_percentage(perc_string):
    "Parse the percentage strings of the form 99.00% (99.00%)"
    return float(perc_string.split('%')[0])

t1 = pd.read_csv('t1.csv',
                 skipfooter=1,
                 engine='python',
                 sep=' *, *',  # This gets rid of the spaces
                 index_col='Host',
                 usecols=['Host', 'Time Up'],
                 converters={'Time Up': parse_percentage})

t2 = pd.read_csv('t2.csv',
                  skipfooter=1,
                  engine='python',
                  sep=' *, *',
                  usecols=['Host', 'Service', 'Time OK'],
                  converters={'Time OK': parse_percentage}).fillna(method='ffill').set_index('Host')

combined = pandas.concat([t1, t2[t2.Service == 'server_hit_rate']['Time OK']], axis=1)
combined.to_csv('test.csv)


问:
How to make android studio not add white space automatically after press enter in new line
Android studio add a couple of white space after press enter in new line.

How to cancel this behavior because when I execute "git diff", there is a red block in that place, which is not allow when review in gerrit.

Thanks a lot in advance.

答: If you are using any code formatter try to check in that file or review your code style hope this helps: Android Studio "This file is indented with tabs instead of 4 spaces"</p>