Rectangle 27 16

Since the_list[1:] actually creates a copy of the whole list (excluding its first element), and zip() creates a list of tuples immediately when called, in total three copies of your list are created. If your list is very large, you might prefer

from itertools import izip, islice
for current_item, next_item in izip(the_list, islice(the_list, 1, None)):
    print(current_item, next_item)

which does not copy the list at all.

note that in python 3.x izip is suppressed of itertools and you should use builtin zip

Actually, doesn't the_list[1:] just create a slice object rather than a copy of almost the whole list -- so the OP's technique isn't quite as wasteful as you make it sound.

I think [1:] creates the slice object (or possibly "1:"), which is passed to __slice__ on the list, which then returns a copy containing only the selected elements. One idiomatic way to copy a list is l_copy = l[:] (which I find ugly and unreadable -- prefer l_copy = list(l))

__slice__
the_list[1:]
the_list[slice(1, None)]
list.__getitem__(the_list, slice(1, None))

@martineau: The copy created by the_list[1:] is only a shallow copy, so it consists only of one pointer per list item. The more memory intensive part is the zip() itself, because it will create a list of one tuple instance per list item, each of which will contain two pointers to the two items and some additional information. This list will consume nine times the amount of memory the copy caused by [1:] consumes.

Iterate a list as pair (current, next) in Python - Stack Overflow

python
Rectangle 27 16

Since the_list[1:] actually creates a copy of the whole list (excluding its first element), and zip() creates a list of tuples immediately when called, in total three copies of your list are created. If your list is very large, you might prefer

from itertools import izip, islice
for current_item, next_item in izip(the_list, islice(the_list, 1, None)):
    print(current_item, next_item)

which does not copy the list at all.

note that in python 3.x izip is suppressed of itertools and you should use builtin zip

Actually, doesn't the_list[1:] just create a slice object rather than a copy of almost the whole list -- so the OP's technique isn't quite as wasteful as you make it sound.

I think [1:] creates the slice object (or possibly "1:"), which is passed to __slice__ on the list, which then returns a copy containing only the selected elements. One idiomatic way to copy a list is l_copy = l[:] (which I find ugly and unreadable -- prefer l_copy = list(l))

__slice__
the_list[1:]
the_list[slice(1, None)]
list.__getitem__(the_list, slice(1, None))

@martineau: The copy created by the_list[1:] is only a shallow copy, so it consists only of one pointer per list item. The more memory intensive part is the zip() itself, because it will create a list of one tuple instance per list item, each of which will contain two pointers to the two items and some additional information. This list will consume nine times the amount of memory the copy caused by [1:] consumes.

Iterate a list as pair (current, next) in Python - Stack Overflow

python
Rectangle 27 106

The list

Disclaimer: please note this property is sent by the browser and can thus be faked, just like user agent strings. Never rely on the navigator object to be completely accurate.

As far as I know there isn't a single public list of all possible navigator.platform values, even though the property has been around for quite a bit. To make things worse, the property's definition changed throughout the years. It used to be:

navigator.platform indicates the machine type for which the browser was compiled.

This basically means the property can return Win16 when the user is running a browser compiled for 16-bit, even though the user is on a 32-bit or 64-bit Windows machine.

Of course W3Schools lists the old definition (I'm not even gonna link to them). W3 and MDN have agreed on a different definition though:

navigator.platform represents the platform on which the browser is executing.

Still, this definition is a bit vague. A decade ago a 'platform' would either be a CPU architecture or an operating system. In recent years handheld and media devices can be platforms too.

As with everything on the web, our fate is in the hands of the mighty browser vendors. In this case, all the major browsers (IE, Safari, Firefox and Chrome) agree that my 64-bit Windows machine is a Win32 platform. This means they're sticking to the old definition as far as Windows goes, because none of them are compiled for 64-bit thus far. Look on the bright side though: at least they all agree on something for once.

It seems like we're a bit luckier when it comes to handheld and media devices. As you've already stated in your question, the iPhone, iPod and iPad each got a unique value, even though they're all running the same operating system. All of Nintendo's and Sony's devices are returning unique values too. So only now navigator.platform is starting to look interesting.

But then Opera Mini for iPhone comes along, messing things up again. Opera Mini actually returns a code engine version number, which is a completely different interpretation of platform than anything we've come across so far. So now we're back where we started and we start to understand why there's so little information on this subject out there.

Even though the interpretations vary and I don't have a complete answer for you, I did feel like I should add my 2 cents for anyone else out there researching the navigator.platform property.

Below is a (definitely non-definite) list of the values I know of that I could verify with multiple sources. Because of the vague definition, I'm not too sure what the best way to order these is. For now I divided them into a few categories based on operating system or device brand and listed additional information and release dates where applicable.

It's really hard to test for Android devices. Android devices will return Android just as often as some version of Linux. For example on a Nexus 5 phone, both the Android browser and Chrome return Linux armv7l. In rare cases Android devices can even return null (instead of undefined).

Android
  • Linux: see notes above
null

As far as iOS goes: Safari, Chrome and Mercury agree, but Opera messes things up.

iPhone
iPod
iPad
iPhone Simulator
iPod Simulator
iPad Simulator
Macintosh
MacIntel
MacPPC
Mac68K
Pike v7.6 release 92
Pike v7.8 release 517
BlackBerry
FreeBSD
FreeBSD i386
FreeBSD amd64

Seriously unreliable because so many platforms are built on this. For example, Chrome on ChromeOS or Linux x86-64 both return Linux i686 as that's what they were compiled for.

Note Linux ARM lists architecture flags, e.g. armv5tej would denote a v5 ARM architecture with Thumb support ('T'), a DSP instruction set ('E'), and Jazelle support ('J').

Linux
Linux aarch64
Linux armv5tejl
Linux armv6l
Linux armv7l
Linux i686
Linux i686 on x86_64
Linux i686 X11
Linux MSM8960_v3.2.1.1_N_R069_Rev:18
Linux ppc64
Linux x86_64
Linux x86_64 X11

Even on a 64-bit Windows 8 they all stick to Win32.

OS/2
Pocket PC
Windows
Win16
Win32
WinCE

An empty string is returned on Firefox OS. See this bug report.

New Nintendo 3DS
Nintendo DSi
Nintendo 3DS
Nintendo Wii
Nintendo WiiU
OpenBSD amd64
Nokia_Series_40
S60
Symbian
Symbian OS
PalmOS
webOS
SunOS
SunOS i86pc
SunOS sun4u
PLAYSTATION 3
PlayStation 4
PSP
HP-UX
masking-agent
WebTV OS
X11
navigator.platform

Glad to be of help, Thomas.

FYI, some 64-bit browsers do exist, even IE, if you can dig it up. Thus, Win64 can sometimes appear. My browser sniffer is set to see it, and flag the browser as executing 64-bit. Very comprehensive list otherwise.. thanks. :)

There are a few more on this list: books.google.com/

I'm not able to check at the moment but wouldn't there be one for the Xbox 360, Xbox One, PS4 as well?

javascript - What is the list of possible values for navigator.platfor...

javascript
Rectangle 27 189

Lists from the start

The other answers show you how to make a list of data.frames when you already have a bunch of data.frames, e.g., d1, d2, .... Having sequentially named data frames is a problem, and putting them in a list is a good fix, but best practice is to avoid having a bunch of data.frames not in a list in the first place.

data.frames

If they're an odd assortment (which is unusual), you can simply assign them:

mylist <- list()
mylist[[1]] <- mtcars
mylist[[2]] <- data.frame(a = rnorm(50), b = runif(50))
...

The rest of the this answer will cover some common cases where you might be tempted to create sequential variables, and show you how to go straight to lists. If you're new to lists in R, you might want to also read What's the difference between [[ and [ in accessing elements of a list?.

Don't ever create d1 d2 d3, ..., in the first place. Create a list d with 3 elements.

This is done pretty easily when reading in files. Maybe you've got files data1.csv, data2.csv, ... in a directory. Your goal is a list of data.frames called mydata. The first thing you need is a vector with all the file names. You can construct this with paste (e.g., my_files = paste0("data", 1:5, ".csv")), but it's probably easier to use list.files to grab all the appropriate files: my_files <- list.files(pattern = "\\.csv$").

At this point, most R beginners will use a for loop, and there's nothing wrong with that, it works just fine.

my_data <- list()
for (i in seq_along(my_files)) {
    my_data[[i]] <- read.csv(file = my_files[i])
}
lapply
my_data <- lapply(my_files, read.csv)

Either way, it's handy to name the list elements to match the files

names(my_data) <- gsub("\\.csv$", "", my_files)
# or, if you prefer the consistent syntax of stringr
names(my_data) <- stringr::str_replace(my_files, pattern = ".csv", replacement = "")

This is super-easy, the base function split() does it for you. You can split by a column (or columns) of the data, or by anything else you want

mt_list = split(mtcars, f = mtcars$cyl)
# This gives a list of three data frames, one for each value of cyl

This is also a nice way to break a data frame into pieces for cross-validation. Maybe you want to split mtcars into training, test, and validation pieces.

groups = sample(c("train", "test", "validate"),
                size = nrow(mtcars), replace = TRUE)
mt_split = split(mtcars, f = groups)
# and mt_split has appropriate names already!
my_sim_data = data.frame(x = rnorm(50), y = rnorm(50))

But who does only one simulation? You want to do this 100 times, 1000 times, more! But you don't want 10,000 data frames in your workspace. Use replicate and put them in a list:

sim_list = replicate(n = 10,
                     expr = {data.frame(x = rnorm(50), y = rnorm(50))},
                     simplify = F)

In this case especially, you should also consider whether you really need separate data frames, or would a single data frame with a "group" column work just as well? Using data.table or dplyr it's quite easy to do things "by group" to a data frame.

If you have data frames named in a pattern, e.g., df1, df2, df3, and you want them in a list, you can get them if you can write a regular expression to match the names. Something like

df_list = mget(ls(pattern = "df[0-9]"))
# this would match any object with "df" followed by a digit in its name
# you can test what objects will be got by just running the
ls(pattern = "df[0-9]")
# part and adjusting the pattern until it gets the right objects.

Generally, mget is used to get multiple objects and return them in a named list. Its counterpart get is used to get a single object and return it not in a list.

A common task is combining a list of data frames into one big data frame. If you want to stack them on top of each other, you would use rbind for a pair of them, but for a list of data frames here are three good choices:

# base option - slower but not extra dependencies
big_data = do.call(what = rbind, args = df_list)

# data table and dplyr have nice functions for this
# they will be faster and can also add id columns to identify
# which list item they came from. They can also fill in
# missing values if some data frames have more columns than others
big_data = data.table::rbindlist(df_list)
big_data = dplyr::bind_rows(df_list)
cbind
dplyr::bind_cols

To merge (join) a list of data frames, you can see these answers. Often, the idea is to use Reduce with merge (or some other joining function) to get them together.

Put similar data in lists because you want to do similar things to each data frame, and functions like lapply, sapply do.call, the purrr package, and the old plyr l*ply functions make it easy to do that. Examples of people easily doing things with lists are all over SO.

Even if you use a lowly for loop, it's much easier to loop over the elements of a list than it is to construct variable names with paste and access the objects with get. Easier to debug, too (it would have prevented this bug).

Think of scalability. If you really only need three variables, it's fine to use d1, d2, d3. But then if it turns out you really need 6, that's a lot more typing. And next time, when you need 10 or 20, you find yourself copying and pasting lines of code, maybe using find/replace to change d14 to d15, and you're thinking this isn't how programming should be. If you use a list, the difference between 3 cases, 30 cases, and 300 cases is at most one line of code---no change at all if your number of cases is automatically detected by, e.g., how many .csv files are in your directory.

You can name the elements of a list, in case you want to use something other than numeric indices to access your data frames (and you can use both, this isn't an XOR choice).

Overall, using lists will lead you to write cleaner, easier-to-read code, which will result in fewer bugs and less confusion.

Which book do you recommend that covers working with lists?

I recommend reading questions and answers on Stack Overflow that are tagged with both r and list.

@Gregor I'd like to add that we can to avoid name the list elements to match the files just simply by assigning the my_data <- NULL rather than `my_data <- list()'! :)

It's possible, but my_data <- list() makes it clear you are creating a list, which is good! Clear code is a good thing. I don't see any advantage to using my_data <- NULL instead.

I agree, about what you said, but like I said, doing so you can escape the stage of naming the files. names(my_data) <- gsub("\\.csv$", "", my_files) ;) <br> But I Do respect your advises as I am learning a lot from them as newbie and I do really appreciate it :)

r - How do I make a list of data frames? - Stack Overflow

r list dataframe r-faq
Rectangle 27 12

Concatenate all list of tags

I don't really know how to transform an horizontal list of comma-separated values to a list of rows without creating a table containing numbers, as many numbers as you may have comma-separated values. If you can create this table, here is my answer:

SELECT 
  SUBSTRING_INDEX(SUBSTRING_INDEX(all_tags, ',', num), ',', -1) AS one_tag,
  COUNT(*) AS cnt
FROM (
  SELECT
    GROUP_CONCAT(tags separator ',') AS all_tags,
    LENGTH(GROUP_CONCAT(tags SEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(tags SEPARATOR ','), ',', '')) + 1 AS count_tags
  FROM test
) t
JOIN numbers n
ON n.num <= t.count_tags
GROUP BY one_tag
ORDER BY cnt DESC;
+---------------------+-----+
| one_tag             | cnt |
+---------------------+-----+
| chicken             |   5 |
| pork                |   4 |
| spaghetti           |   3 |
| fried-rice          |   2 |
| manchurain          |   2 |
| pho                 |   1 |
| chicken-calzone     |   1 |
| fettuccine          |   1 |
| chorizo             |   1 |
| meat-balls          |   1 |
| miso-soup           |   1 |
| chanko-nabe         |   1 |
| chicken-manchurian  |   1 |
| pork-manchurian     |   1 |
| sweet-and-sour-pork |   1 |
| peking-duck         |   1 |
| duck                |   1 |
+---------------------+-----+
17 rows in set (0.01 sec)
  • We concatenate all tags using a comma to create only one list of tags instead of one per row
  • We count how many tags we have in our list
  • We find how we can get one value in this list
  • We find how we can get all values as distinct rows
CREATE TABLE test (
    id INT PRIMARY KEY,
    tags VARCHAR(255)
);

INSERT INTO test VALUES
    ("1",         "pho,pork"),
    ("2",         "fried-rice,chicken"),
    ("3",         "fried-rice,pork"),
    ("4",         "chicken-calzone,chicken"),
    ("5",         "fettuccine,chicken"),
    ("6",         "spaghetti,chicken"),
    ("7",         "spaghetti,chorizo"),
    ("8",         "spaghetti,meat-balls"),
    ("9",         "miso-soup"),
    ("10",        "chanko-nabe"),
    ("11",        "chicken-manchurian,chicken,manchurain"),
    ("12",        "pork-manchurian,pork,manchurain"),
    ("13",        "sweet-and-sour-pork,pork"),
    ("14",        "peking-duck,duck");

We will work with all tags in a single line, so we use GROUP_CONCAT to do the job:

SELECT GROUP_CONCAT(tags SEPARATOR ',') FROM test;

Returns all tags separated by a comma:

To count all tags, we get the length of the full list of tags, and we remove the length of the full list of tags after replacing the , by nothing. We add 1, as the separator is between two values.

SELECT LENGTH(GROUP_CONCAT(tags SEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(tags SEPARATOR ','), ',', '')) + 1 AS count_tags
FROM test;
+------------+
| count_tags |
+------------+
|         28 |
+------------+
1 row in set (0.00 sec)
SUBSTRING_INDEX
-- returns the string until the 2nd delimiter\'s occurrence from left to right: a,b
SELECT SUBSTRING_INDEX('a,b,c', ',', 2);

-- return the string until the 1st delimiter, from right to left: c
SELECT SUBSTRING_INDEX('a,b,c', ',', -1);

-- we need both to get: b (with 2 being the tag number)
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('a,b,c', ',', 2), ',', -1);

With such logic, to get the 3nd tag in our list, we use:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(tags SEPARATOR ','), ',', 3), ',', -1)
FROM test;
+-------------------------------------------------------------------------------------+
| SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(tags SEPARATOR ','), ',', 3), ',', -1) |
+-------------------------------------------------------------------------------------+
| fried-rice                                                                          |
+-------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  • I know we can create rows by joining tables
  • I need to get the Nth tag in the list using the request above

So we will create a table containing all numbers from 1 to the maximum number of tags you may have in your list. If you can have 1M values, create 1M entries from 1 to 1,000,000. For 100 tags, this will be:

CREATE TABLE numbers (
  num INT PRIMARY KEY
);

INSERT INTO numbers VALUES
    ( 1 ), ( 2 ), ( 3 ), ( 4 ), ( 5 ), ( 6 ), ( 7 ), ( 8 ), ( 9 ), ( 10 ), 
    ( 11 ), ( 12 ), ( 13 ), ( 14 ), ( 15 ), ( 16 ), ( 17 ), ( 18 ), ( 19 ), ( 20 ), 
    ( 21 ), ( 22 ), ( 23 ), ( 24 ), ( 25 ), ( 26 ), ( 27 ), ( 28 ), ( 29 ), ( 30 ), 
    ( 31 ), ( 32 ), ( 33 ), ( 34 ), ( 35 ), ( 36 ), ( 37 ), ( 38 ), ( 39 ), ( 40 ), 
    ( 41 ), ( 42 ), ( 43 ), ( 44 ), ( 45 ), ( 46 ), ( 47 ), ( 48 ), ( 49 ), ( 50 ), 
    ( 51 ), ( 52 ), ( 53 ), ( 54 ), ( 55 ), ( 56 ), ( 57 ), ( 58 ), ( 59 ), ( 60 ), 
    ( 61 ), ( 62 ), ( 63 ), ( 64 ), ( 65 ), ( 66 ), ( 67 ), ( 68 ), ( 69 ), ( 70 ), 
    ( 71 ), ( 72 ), ( 73 ), ( 74 ), ( 75 ), ( 76 ), ( 77 ), ( 78 ), ( 79 ), ( 80 ), 
    ( 81 ), ( 82 ), ( 83 ), ( 84 ), ( 85 ), ( 86 ), ( 87 ), ( 88 ), ( 89 ), ( 90 ), 
    ( 91 ), ( 92 ), ( 93 ), ( 94 ), ( 95 ), ( 96 ), ( 97 ), ( 98 ), ( 99 ), ( 100 );

Now, we get the numth (num being a row in number) using the following query:

SELECT n.num, SUBSTRING_INDEX(SUBSTRING_INDEX(all_tags, ',', num), ',', -1) as one_tag
FROM (
  SELECT
    GROUP_CONCAT(tags SEPARATOR ',') AS all_tags,
    LENGTH(GROUP_CONCAT(tags SEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(tags SEPARATOR ','), ',', '')) + 1 AS count_tags
  FROM test
) t
JOIN numbers n
ON n.num <= t.count_tags
+-----+---------------------+
| num | one_tag             |
+-----+---------------------+
|   1 | pho                 |
|   2 | pork                |
|   3 | fried-rice          |
|   4 | chicken             |
|   5 | fried-rice          |
|   6 | pork                |
|   7 | chicken-calzone     |
|   8 | chicken             |
|   9 | fettuccine          |
|  10 | chicken             |
|  11 | spaghetti           |
|  12 | chicken             |
|  13 | spaghetti           |
|  14 | chorizo             |
|  15 | spaghetti           |
|  16 | meat-balls          |
|  17 | miso-soup           |
|  18 | chanko-nabe         |
|  19 | chicken-manchurian  |
|  20 | chicken             |
|  21 | manchurain          |
|  22 | pork-manchurian     |
|  23 | pork                |
|  24 | manchurain          |
|  25 | sweet-and-sour-pork |
|  26 | pork                |
|  27 | peking-duck         |
|  28 | duck                |
+-----+---------------------+
28 rows in set (0.01 sec)

As soon as we now have classic rows, we can easily count occurrences of each tags.

+1 for effort and creativity.

MySql PHP select count of distinct values from comma separated data (t...

php mysql sql
Rectangle 27 448

Add .idea directory to the list of ignored files

First, add it to .gitignore, so it is not accidentally committed by you (or someone else) again:

.idea

Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:

Third, commit the .gitignore file and the removal of .idea from the repository. After that push it to the remote(s).

$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push

(optionally you can replace last line with git push some_remote, where some_remote is the name of the remote you want to push to)

fatal: pathspec '.idea' did not match any files

Thank's very much very helpful.

git rm -r --cached .idea

If you get @annedroiid error of 'did not match any files', you can try and add its path. Like when I was deleting the database.yml file, I simply did 'git rm -r --cached config/database.yml'

Accidentally committed .idea directory files into git - Stack Overflow

git
Rectangle 27 438

Add .idea directory to the list of ignored files

First, add it to .gitignore, so it is not accidentally committed by you (or someone else) again:

.idea

Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:

Third, commit the .gitignore file and the removal of .idea from the repository. After that push it to the remote(s).

$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push

(optionally you can replace last line with git push some_remote, where some_remote is the name of the remote you want to push to)

fatal: pathspec '.idea' did not match any files
git rm -r --cached .idea

If you get @annedroiid error of 'did not match any files', you can try and add its path. Like when I was deleting the database.yml file, I simply did 'git rm -r --cached config/database.yml'

Accidentally committed .idea directory files into git - Stack Overflow

git
Rectangle 27 28

Create a SSH config file

You should at this point already have created at least a single default identity. To see if you have a default identity already, list the contents of your .ssh directory. Default identity files appear as a id_encrypt and id_encrypt.pub pair. The encrypt value is either rsa or dsa. Use the ssh-keygen command to create a new identity. In the example below, the identity is named personalid.

$ ssh-keygen -f ~/.ssh/personalid -C "personalid"
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/manthony/.ssh/personalid.
Your public key has been saved in /Users/manthony/.ssh/personalid.pub.
The key fingerprint is:
7a:9c:b2:9c:8e:4e:f4:af:de:70:77:b9:52:fd:44:97 personalid
The key's randomart image is:
+--[ RSA 2048]----+
|         |
|         |
|        .|
|        Eo|
|  .  S  . ..|
|  . . o . ... .|
|  . = = ..o o |
|  . o X ... . .|
|  .ooB.o ..  |
+-----------------+

If you have multiple Bitbucket accounts, you need to generate a new public/private key pair for each account.

When you have multiple identity files, create a SSH config file mechanisms to create aliases for your various identities. You can construct a SSH config file using many parameters and different approaches. The format for the alias entries use in this example is:

Host alias
HostName bitbucket.org
IdentityFile ~/.ssh/identity

To create a config file for two identities (workid and personalid), you would do the following:

  • Open a terminal window.
  • Edit the ~/.ssh/config file. If you don't have a config file, create one.

Add an alias for each identity combination for example:

Host workid
 HostName bitbucket.org
 IdentityFile ~/.ssh/workid
Host personalid
 HostName bitbucket.org
 IdentityFile ~/.ssh/personalid

Close and save the file.

git@bitbucket.org:accountname/reponame.git  ->  git@alias:accountname/reponame.git

To clone a repository with one of multiple SSH identities that you configured, you clone the repo and using your alias in the SSH URL. To try this for yourself, log into Bitbucket and do the following:

  • Display the SSH URL. For example, ssh URL as: git@bitbucket.org:accountname/reponame.git then clone the repository using: git clone git@personalid:accountname/reponame.git

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

git - How to maintain multiple bitbucket accounts with multiple ssh ke...

git bitbucket
Rectangle 27 28

Create a SSH config file

You should at this point already have created at least a single default identity. To see if you have a default identity already, list the contents of your .ssh directory. Default identity files appear as a id_encrypt and id_encrypt.pub pair. The encrypt value is either rsa or dsa. Use the ssh-keygen command to create a new identity. In the example below, the identity is named personalid.

$ ssh-keygen -f ~/.ssh/personalid -C "personalid"
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/manthony/.ssh/personalid.
Your public key has been saved in /Users/manthony/.ssh/personalid.pub.
The key fingerprint is:
7a:9c:b2:9c:8e:4e:f4:af:de:70:77:b9:52:fd:44:97 personalid
The key's randomart image is:
+--[ RSA 2048]----+
|         |
|         |
|        .|
|        Eo|
|  .  S  . ..|
|  . . o . ... .|
|  . = = ..o o |
|  . o X ... . .|
|  .ooB.o ..  |
+-----------------+

If you have multiple Bitbucket accounts, you need to generate a new public/private key pair for each account.

When you have multiple identity files, create a SSH config file mechanisms to create aliases for your various identities. You can construct a SSH config file using many parameters and different approaches. The format for the alias entries use in this example is:

Host alias
HostName bitbucket.org
IdentityFile ~/.ssh/identity

To create a config file for two identities (workid and personalid), you would do the following:

  • Open a terminal window.
  • Edit the ~/.ssh/config file. If you don't have a config file, create one.

Add an alias for each identity combination for example:

Host workid
 HostName bitbucket.org
 IdentityFile ~/.ssh/workid
Host personalid
 HostName bitbucket.org
 IdentityFile ~/.ssh/personalid

Close and save the file.

git@bitbucket.org:accountname/reponame.git  ->  git@alias:accountname/reponame.git

To clone a repository with one of multiple SSH identities that you configured, you clone the repo and using your alias in the SSH URL. To try this for yourself, log into Bitbucket and do the following:

  • Display the SSH URL. For example, ssh URL as: git@bitbucket.org:accountname/reponame.git then clone the repository using: git clone git@personalid:accountname/reponame.git

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

git - How to maintain multiple bitbucket accounts with multiple ssh ke...

git bitbucket
Rectangle 27 97

To copy a list you can use list(a) or a[:]. In both cases a new object is created. These two methods, however, have limitations with collections of mutable objects as inner objects keep their references intact:

>>> a = [[1,2],[3],[4]]

>>> b = a[:]
>>> c = list(a)

>>> c[0].append(9)

>>> a
[[1, 2, 9], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>> b
[[1, 2, 9], [3], [4]]
>>>

If you want a full copy of your objects you need copy.deepcopy

>>> from copy import deepcopy
>>> a = [[1,2],[3],[4]]

>>> b = a[:]
>>> c = deepcopy(a)

>>> c[0].append(9)

>>> a
[[1, 2], [3], [4]]
>>> b
[[1, 2], [3], [4]]
>>> c
[[1, 2, 9], [3], [4]]
>>>

what is the difference between a regular copy and a deep copy? Why does what happens above happen? I think I have a general understanding, it seems to be like the same problem encountered by the op at the second layer. How does it work internally?

python list by value not by reference - Stack Overflow

python list reference
Rectangle 27 73

What are the options to clone or copy a list in Python?

There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing equivalent objects.

A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.

There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.

In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:

a_copy = a_list[:]

You can also accomplish the same thing by passing the list through the list constructor,

a_copy = list(a_list)

but using the constructor is less efficient:

>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844

In Python 3, lists get the list.copy method:

a_copy = a_list.copy()
>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125

my_list is a pointer to the actual list in memory. When you say new_list = my_list you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.

>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]

The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.

import copy
a_deep_copy = copy.deepcopy(a_list)
>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]

And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.

You may see this used as a way to deepcopy, but don't do it:

problematic_deep_copy = eval(repr(a_list))
  • It's dangerous, particularly if you're evaluating something from a source you don't trust.
  • It's not reliable, if a subelement you're copying doesn't have a representation that can be eval'd to reproduce an equivalent element.
>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644

python - How to clone or copy a list? - Stack Overflow

python list copy clone
Rectangle 27 73

What are the options to clone or copy a list in Python?

There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing equivalent objects.

A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.

There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.

In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:

a_copy = a_list[:]

You can also accomplish the same thing by passing the list through the list constructor,

a_copy = list(a_list)

but using the constructor is less efficient:

>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844

In Python 3, lists get the list.copy method:

a_copy = a_list.copy()
>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125

my_list is a pointer to the actual list in memory. When you say new_list = my_list you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.

>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]

The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.

import copy
a_deep_copy = copy.deepcopy(a_list)
>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]

And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.

You may see this used as a way to deepcopy, but don't do it:

problematic_deep_copy = eval(repr(a_list))
  • It's dangerous, particularly if you're evaluating something from a source you don't trust.
  • It's not reliable, if a subelement you're copying doesn't have a representation that can be eval'd to reproduce an equivalent element.
>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644

python - How to clone or copy a list? - Stack Overflow

python list copy clone
Rectangle 27 71

What are the options to clone or copy a list in Python?

There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing equivalent objects.

A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.

There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.

In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:

a_copy = a_list[:]

You can also accomplish the same thing by passing the list through the list constructor,

a_copy = list(a_list)

but using the constructor is less efficient:

>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844

In Python 3, lists get the list.copy method:

a_copy = a_list.copy()
>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125

my_list is a pointer to the actual list in memory. When you say new_list = my_list you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.

>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]

The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.

import copy
a_deep_copy = copy.deepcopy(a_list)
>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]

And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.

You may see this used as a way to deepcopy, but don't do it:

problematic_deep_copy = eval(repr(a_list))
  • It's dangerous, particularly if you're evaluating something from a source you don't trust.
  • It's not reliable, if a subelement you're copying doesn't have a representation that can be eval'd to reproduce an equivalent element.
>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644

python - How to clone or copy a list? - Stack Overflow

python list copy clone
Rectangle 27 62

The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.

So if you're going to need to change the values use a List.

  • As a tuple is immutable it can be used as a key in a dictionary.
  • If you can't change it neither can anyone else, which is to say you don't need to worry about any API functions etc. changing your tuple without being asked.

Note that a tuple is only immutable if all of its elements are. You could say the same is true of all immutable collections, like frozenset or the various third-party frozen dict/tree/etc. types, but none of those allow you to add mutable elements. (And of course a tuple is only hashable if all of its elements are, which is handles in the usual EAFP way, so d[1, [2]] will raise TypeError: unhashable type: 'list'.)

A tuple can only be used as a key in a dictionary if all of its elements are immutable. See here

python - What's the difference between lists and tuples? - Stack Overf...

python list tuples
Rectangle 27 67

What are the options to clone or copy a list in Python?

There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing equivalent objects.

A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.

There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.

In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:

a_copy = a_list[:]

You can also accomplish the same thing by passing the list through the list constructor,

a_copy = list(a_list)

but using the constructor is less efficient:

>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844

In Python 3, lists get the list.copy method:

a_copy = a_list.copy()
>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125

my_list is a pointer to the actual list in memory. When you say new_list = my_list you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.

>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]

The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.

import copy
a_deep_copy = copy.deepcopy(a_list)
>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]

And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.

You may see this used as a way to deepcopy, but don't do it:

problematic_deep_copy = eval(repr(a_list))
  • It's dangerous, particularly if you're evaluating something from a source you don't trust.
  • It's not reliable, if a subelement you're copying doesn't have a representation that can be eval'd to reproduce an equivalent element.
>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644

python - How to clone or copy a list? - Stack Overflow

python list copy clone
Rectangle 27 66

What are the options to clone or copy a list in Python?

There are two semantic ways to copy a list. A shallow copy creates a new list of the same objects, a deep copy creates a new list containing equivalent objects.

A shallow copy only copies the list itself, which is a container of references to the objects in the list. If the objects contained themselves are mutable and one is changed, the change will be reflected in both lists.

There are different ways to do this in Python 2 and 3. The Python 2 ways will also work in Python 3.

In Python 2, the idiomatic way of making a shallow copy of a list is with a complete slice of the original:

a_copy = a_list[:]

You can also accomplish the same thing by passing the list through the list constructor,

a_copy = list(a_list)

but using the constructor is less efficient:

>>> timeit
>>> l = range(20)
>>> min(timeit.repeat(lambda: l[:]))
0.30504298210144043
>>> min(timeit.repeat(lambda: list(l)))
0.40698814392089844

In Python 3, lists get the list.copy method:

a_copy = a_list.copy()
>>> import timeit
>>> l = list(range(20))
>>> min(timeit.repeat(lambda: l[:]))
0.38448613602668047
>>> min(timeit.repeat(lambda: list(l)))
0.6309100328944623
>>> min(timeit.repeat(lambda: l.copy()))
0.38122922903858125

my_list is a pointer to the actual list in memory. When you say new_list = my_list you're not making a copy, you're just adding another name that points at that original list in memory. We can have similar issues when we make copies of lists.

>>> l = [[], [], []]
>>> l_copy = l[:]
>>> l_copy
[[], [], []]
>>> l_copy[0].append('foo')
>>> l_copy
[['foo'], [], []]
>>> l
[['foo'], [], []]

The list is just an array of pointers to the contents, so a shallow copy just copies the pointers, and so you have two different lists, but they have the same contents. To make copies of the contents, you need a deep copy.

import copy
a_deep_copy = copy.deepcopy(a_list)
>>> import copy
>>> l
[['foo'], [], []]
>>> l_deep_copy = copy.deepcopy(l)
>>> l_deep_copy[0].pop()
'foo'
>>> l_deep_copy
[[], [], []]
>>> l
[['foo'], [], []]

And so we see that the deep copied list is an entirely different list from the original. You could roll your own function - but don't. You're likely to create bugs you otherwise wouldn't have by using the standard library's deepcopy function.

You may see this used as a way to deepcopy, but don't do it:

problematic_deep_copy = eval(repr(a_list))
  • It's dangerous, particularly if you're evaluating something from a source you don't trust.
  • It's not reliable, if a subelement you're copying doesn't have a representation that can be eval'd to reproduce an equivalent element.
>>> import timeit
>>> import copy
>>> l = list(range(10))
>>> min(timeit.repeat(lambda: copy.deepcopy(l)))
16.84255409205798
>>> min(timeit.repeat(lambda: eval(repr(l))))
34.813894678023644

python - How to clone or copy a list? - Stack Overflow

python list copy clone
Rectangle 27 206

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  • Create an empty folder anywhere with any name you prefer, for example spring-source
  • Create a new file named pom.xml
  • Copy the xml below into this file
  • Open the spring-source folder in your console
mvn install
  • After download finished, you'll find spring jars in /spring-source/target/dependencies <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>spring-source-download</groupId> <artifactId>SpringDependencies</artifactId> <version>1.0</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.8</version> <executions> <execution> <id>download-dependencies</id> <phase>generate-resources</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/dependencies</outputDirectory> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

I liked the way you downloaded spring jars. but /spring-source/target/dependencies contains only 7 jar files. How can i download all jars?

The latest Spring 3.2.7 is not there.

Simply use the maven install method, here is the pom.xml for downloading it pastebin.com/n1aNbNXf

great except the maven site is blocked as a "security risk". What then?

java - Where can I download Spring Framework jars without using Maven?...

java spring spring-mvc
Rectangle 27 6

Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}

Assuming blah blah blah is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudocode approximates) is the colon, :

mydict = {k: v for k, v in blahs}
>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

Just like list comprehensions, you can add a filter part to the end:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

Here we test for if the last character is divisible by 2.

Create a dictionary with list comprehension in Python - Stack Overflow

python dictionary list-comprehension language-features dict-comprehension
Rectangle 27 6

Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}

Assuming blah blah blah is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudocode approximates) is the colon, :

mydict = {k: v for k, v in blahs}
>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

Just like list comprehensions, you can add a filter part to the end:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

Here we test for if the last character is divisible by 2.

Create a dictionary with list comprehension in Python - Stack Overflow

python dictionary list-comprehension language-features dict-comprehension
Rectangle 27 6

Create a dictionary with list comprehension in Python

I like the Python list comprehension syntax.

Can it be used to create dictionaries too? For example, by iterating over pairs of keys and values:

mydict = {(k,v) for (k,v) in blah blah blah}

Assuming blah blah blah is an iterable of two-tuples - you're so close. Let's create some "blahs" like that:

blahs = [('blah0', 'blah'), ('blah1', 'blah'), ('blah2', 'blah'), ('blah3', 'blah')]

Now the syntax here is the mapping part. What makes this a dict comprehension instead of a set comprehension (which is what your pseudocode approximates) is the colon, :

mydict = {k: v for k, v in blahs}
>>> mydict
{'blah0': 'blah', 'blah1': 'blah', 'blah3': 'blah', 'blah2': 'blah'}

Just like list comprehensions, you can add a filter part to the end:

>>> mydict = {k: v for k, v in blahs if not int(k[-1]) % 2}
>>> mydict
{'blah0': 'blah', 'blah2': 'blah'}

Here we test for if the last character is divisible by 2.

Create a dictionary with list comprehension in Python - Stack Overflow

python dictionary list-comprehension language-features dict-comprehension