AhmedSSoliman commited on
Commit
2e017a3
1 Parent(s): 9a02dd2

Upload raw/test.csv

Browse files
Files changed (1) hide show
  1. raw/test.csv +558 -0
raw/test.csv ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ intent,snippet
2
+ send a signal `signal.sigusr1` to the current process,"os.kill(os.getpid(), signal.SIGUSR1)"
3
+ decode a hex string '4a4b4c' to utf-8.,bytes.fromhex('4a4b4c').decode('utf-8')
4
+ check if all elements in list `mylist` are identical,all(x == myList[0] for x in myList)
5
+ "format number of spaces between strings `python`, `:` and `very good` to be `20`","print('%*s : %*s' % (20, 'Python', 20, 'Very Good'))"
6
+ how to convert a string from cp-1251 to utf-8?,d.decode('cp1251').encode('utf8')
7
+ get rid of none values in dictionary `kwargs`,"res = {k: v for k, v in list(kwargs.items()) if v is not None}"
8
+ get rid of none values in dictionary `kwargs`,"res = dict((k, v) for k, v in kwargs.items() if v is not None)"
9
+ capture final output of a chain of system commands `ps -ef | grep something | wc -l`,"subprocess.check_output('ps -ef | grep something | wc -l', shell=True)"
10
+ "concatenate a list of strings `['a', 'b', 'c']`",""""""""""""".join(['a', 'b', 'c'])"
11
+ find intersection data between series `s1` and series `s2`,pd.Series(list(set(s1).intersection(set(s2))))
12
+ sending http headers to `client`,client.send('HTTP/1.0 200 OK\r\n')
13
+ format a datetime string `when` to extract date only,"then = datetime.datetime.strptime(when, '%Y-%m-%d').date()"
14
+ split a multi-line string `inputstring` into separate strings,inputString.split('\n')
15
+ split a multi-line string ` a \n b \r\n c ` by new line character `\n`,' a \n b \r\n c '.split('\n')
16
+ "concatenate elements of list `b` by a colon "":""",""""""":"""""".join(str(x) for x in b)"
17
+ get the first object from a queryset in django model `entry`,Entry.objects.filter()[:1].get()
18
+ calculate sum over all rows of 2d numpy array,a.sum(axis=1)
19
+ enable warnings using action 'always',warnings.simplefilter('always')
20
+ concatenate items of list `l` with a space ' ',"print(' '.join(map(str, l)))"
21
+ run script 'hello.py' with argument 'htmlfilename.htm' on terminal using python executable,"subprocess.call(['python.exe', 'hello.py', 'htmlfilename.htm'])"
22
+ how can i parse a time string containing milliseconds in it with python?,"time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')"
23
+ convert a string `my_string` with dot and comma into a float number `my_float`,"my_float = float(my_string.replace(',', ''))"
24
+ "convert a string `123,456.908` with dot and comma into a floating number","float('123,456.908'.replace(',', ''))"
25
+ set pythonpath in python script.,sys.path.append('/path/to/whatever')
26
+ "split string 'words, words, words.' using a regex '(\\w+)'","re.split('(\\W+)', 'Words, words, words.')"
27
+ open a file `output.txt` in append mode,"file = open('Output.txt', 'a')"
28
+ "download a file ""http://www.example.com/songs/mp3.mp3"" over http and save to ""mp3.mp3""","urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')"
29
+ download a file `url` over http and save to `file_name`,"u = urllib.request.urlopen(url)
30
+ f = open(file_name, 'wb')
31
+ meta = u.info()
32
+ file_size = int(meta.getheaders('Content-Length')[0])
33
+ print(('Downloading: %s Bytes: %s' % (file_name, file_size)))
34
+ file_size_dl = 0
35
+ block_sz = 8192
36
+ while True:
37
+ buffer = u.read(block_sz)
38
+ if (not buffer):
39
+ break
40
+ file_size_dl += len(buffer)
41
+ f.write(buffer)
42
+ status = ('%10d [%3.2f%%]' % (file_size_dl, ((file_size_dl * 100.0) / file_size)))
43
+ status = (status + (chr(8) * (len(status) + 1)))
44
+ print(status, end=' ')
45
+ f.close()"
46
+ download a file 'http://www.example.com/' over http,"response = urllib.request.urlopen('http://www.example.com/')
47
+ html = response.read()"
48
+ download a file `url` over http,r = requests.get(url)
49
+ "download a file `url` over http and save to ""10mb""","response = requests.get(url, stream=True)
50
+ with open('10MB', 'wb') as handle:
51
+ for data in tqdm(response.iter_content()):
52
+ handle.write(data)"
53
+ argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser`,"parser.add_argument('--version', action='version', version='%(prog)s 2.0')"
54
+ remove key 'c' from dictionary `d`,{i: d[i] for i in d if i != 'c'}
55
+ "create new dataframe object by merging columns ""key"" of dataframes `split_df` and `csv_df` and rename the columns from dataframes `split_df` and `csv_df` with suffix `_left` and `_right` respectively","pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))"
56
+ split a string `s` by space with `4` splits,"s.split(' ', 4)"
57
+ read keyboard-input,input('Enter your input:')
58
+ enable debug mode on flask application `app`,app.run(debug=True)
59
+ python save list `mylist` to file object 'save.txt',"pickle.dump(mylist, open('save.txt', 'wb'))"
60
+ multiply a matrix `p` with a 3d tensor `t` in scipy,"scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)"
61
+ "create 3d array of zeroes of size `(3,3,3)`","numpy.zeros((3, 3, 3))"
62
+ cut off the last word of a sentence `content`,""""""" """""".join(content.split(' ')[:-1])"
63
+ convert scalar `x` to array,"x = np.asarray(x).reshape(1, -1)[(0), :]"
64
+ sum all elements of nested list `l`,"sum(sum(i) if isinstance(i, list) else i for i in L)"
65
+ convert hex string '470fc614' to a float number,"struct.unpack('!f', '470FC614'.decode('hex'))[0]"
66
+ multiple each value by `2` for all keys in a dictionary `my_dict`,"my_dict.update((x, y * 2) for x, y in list(my_dict.items()))"
67
+ running bash script 'sleep.sh',"subprocess.call('sleep.sh', shell=True)"
68
+ "join elements of list `l` with a comma `,`",""""""","""""".join(l)"
69
+ make a comma-separated string from a list `mylist`,"myList = ','.join(map(str, myList))"
70
+ reverse the list that contains 1 to 10,list(reversed(list(range(10))))
71
+ "remove substring 'bag,' from a string 'lamp, bag, mirror'","print('lamp, bag, mirror'.replace('bag,', ''))"
72
+ "reverse the order of words, delimited by `.`, in string `s`","""""""."""""".join(s.split('.')[::-1])"
73
+ convert epoch time represented as milliseconds `s` to string using format '%y-%m-%d %h:%m:%s.%f',datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
74
+ parse milliseconds epoch time '1236472051807' to format '%y-%m-%d %h:%m:%s',"time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 / 1000.0))"
75
+ get the date 7 days before the current date,(datetime.datetime.now() - datetime.timedelta(days=7)).date()
76
+ sum elements at index `column` of each list in list `data`,print(sum(row[column] for row in data))
77
+ sum columns of a list `array`,[sum(row[i] for row in array) for i in range(len(array[0]))]
78
+ encode binary string 'your string' to base64 code,"base64.b64encode(bytes('your string', 'utf-8'))"
79
+ combine list of dictionaries `dicts` with the same keys in each list to a single dictionary,"dict((k, [d[k] for d in dicts]) for k in dicts[0])"
80
+ merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k`,{k: [d[k] for d in dicts] for k in dicts[0]}
81
+ how do i get the url parameter in a flask view,request.args['myParam']
82
+ identify duplicate values in list `mylist`,"[k for k, v in list(Counter(mylist).items()) if v > 1]"
83
+ insert directory 'apps' into directory `__file__`,"sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'apps'))"
84
+ modify sys.path for python module `subdir`,"sys.path.append(os.path.join(os.path.dirname(__file__), 'subdir'))"
85
+ insert a 'none' value into a sqlite3 table.,"db.execute(""INSERT INTO present VALUES('test2', ?, 10)"", (None,))"
86
+ flatten list `list_of_menuitems`,[image for menuitem in list_of_menuitems for image in menuitem]
87
+ append elements of a set `b` to a list `a`,a.extend(b)
88
+ append elements of a set to a list in python,a.extend(list(b))
89
+ write the data of dataframe `df` into text file `np.txt`,"np.savetxt('c:\\data\\np.txt', df.values, fmt='%d')"
90
+ write content of dataframe `df` into text file 'c:\\data\\pandas.txt',"df.to_csv('c:\\data\\pandas.txt', header=None, index=None, sep=' ', mode='a')"
91
+ split a string `x` by last occurrence of character `-`,print(x.rpartition('-')[0])
92
+ get the last part of a string before the character '-',"print(x.rsplit('-', 1)[0])"
93
+ upload file using ftp,"ftp.storlines('STOR ' + filename, open(filename, 'r'))"
94
+ add one to the hidden web element with id 'xyz' with selenium python script,"browser.execute_script(""document.getElementById('XYZ').value+='1'"")"
95
+ "create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]`","np.maximum([2, 3, 4], [1, 5, 2])"
96
+ print a list `l` and move first 3 elements to the end of the list,print(l[3:] + l[:3])
97
+ loop over files in directory '.',"for fn in os.listdir('.'):
98
+ if os.path.isfile(fn):
99
+ pass"
100
+ loop over files in directory `source`,"for (root, dirs, filenames) in os.walk(source):
101
+ for f in filenames:
102
+ pass"
103
+ create a random list of integers,[int(1000 * random.random()) for i in range(10000)]
104
+ using %f with strftime() in python to get microseconds,datetime.datetime.now().strftime('%H:%M:%S.%f')
105
+ google app engine execute gql query 'select * from schedule where station = $1' with parameter `foo.key()`,"db.GqlQuery('SELECT * FROM Schedule WHERE station = $1', foo.key())"
106
+ filter rows in pandas starting with alphabet 'f' using regular expression.,df.b.str.contains('^f')
107
+ print a 2 dimensional list `tab` as a table with delimiters,print('\n'.join('\t'.join(str(col) for col in row) for row in tab))
108
+ pandas: delete rows in dataframe `df` based on multiple columns values,"df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()"
109
+ format the variables `self.goals` and `self.penalties` using string formatting,"""""""({:d} goals, ${:d})"""""".format(self.goals, self.penalties)"
110
+ "format string ""({} goals, ${})"" with variables `goals` and `penalties`","""""""({} goals, ${})"""""".format(self.goals, self.penalties)"
111
+ "format string ""({0.goals} goals, ${0.penalties})""","""""""({0.goals} goals, ${0.penalties})"""""".format(self)"
112
+ convert list of lists `l` to list of integers,[int(''.join(str(d) for d in x)) for x in L]
113
+ combine elements of each list in list `l` into digits of a single integer,[''.join(str(d) for d in x) for x in L]
114
+ convert a list of lists `l` to list of integers,L = [int(''.join([str(y) for y in x])) for x in L]
115
+ write the elements of list `lines` concatenated by special character '\n' to file `myfile`,myfile.write('\n'.join(lines))
116
+ removing an element from a list based on a predicate 'x' or 'n',"[x for x in ['AAT', 'XAC', 'ANT', 'TTA'] if 'X' not in x and 'N' not in x]"
117
+ remove duplicate words from a string `text` using regex,"text = re.sub('\\b(\\w+)( \\1\\b)+', '\\1', text)"
118
+ count non zero values in each column in pandas data frame,df.astype(bool).sum(axis=1)
119
+ search for string that matches regular expression pattern '(?<!distillr)\\\\acrotray\\.exe' in string 'c:\\somedir\\acrotray.exe',"re.search('(?<!Distillr)\\\\AcroTray\\.exe', 'C:\\SomeDir\\AcroTray.exe')"
120
+ split string 'qh qd jc kd js' into a list on white spaces,"""""""QH QD JC KD JS"""""".split()"
121
+ search for occurrences of regex pattern '>.*<' in xml string `line`,"print(re.search('>.*<', line).group(0))"
122
+ erase all the contents of a file `filename`,"open(filename, 'w').close()"
123
+ convert a string into datetime using the format '%y-%m-%d %h:%m:%s.%f',"datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f')"
124
+ find the index of a list with the first element equal to '332' within the list of lists `thelist`,"[index for index, item in enumerate(thelist) if item[0] == '332']"
125
+ lower a string `text` and remove non-alphanumeric characters aside from space,"re.sub('[^\\sa-zA-Z0-9]', '', text).lower().strip()"
126
+ remove all non-alphanumeric characters except space from a string `text` and lower it,"re.sub('(?!\\s)[\\W_]', '', text).lower().strip()"
127
+ subscript text 'h20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.,"plt.plot(x, y, label='H\u2082O')"
128
+ subscript text 'h20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.,"plt.plot(x, y, label='$H_2O$')"
129
+ loop over a list `mylist` if sublists length equals 3,[x for x in mylist if len(x) == 3]
130
+ initialize a list `lst` of 100 objects object(),lst = [Object() for _ in range(100)]
131
+ create list `lst` containing 100 instances of object `object`,lst = [Object() for i in range(100)]
132
+ get the content of child tag with`href` attribute whose parent has css `someclass`,self.driver.find_element_by_css_selector('.someclass a').get_attribute('href')
133
+ joining data from dataframe `df1` with data from dataframe `df2` based on matching values of column 'date_time' in both dataframes,"df1.merge(df2, on='Date_Time')"
134
+ use `%s` operator to print variable values `str1` inside a string,"'first string is: %s, second one is: %s' % (str1, 'geo.tif')"
135
+ split a string by a delimiter in python,[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]
136
+ check if directory `directory ` exists and create it if necessary,"if (not os.path.exists(directory)):
137
+ os.makedirs(directory)"
138
+ check if a directory `path` exists and create it if necessary,"try:
139
+ os.makedirs(path)
140
+ except OSError:
141
+ if (not os.path.isdir(path)):
142
+ raise"
143
+ check if a directory `path` exists and create it if necessary,distutils.dir_util.mkpath(path)
144
+ check if a directory `path` exists and create it if necessary,"try:
145
+ os.makedirs(path)
146
+ except OSError as exception:
147
+ if (exception.errno != errno.EEXIST):
148
+ raise"
149
+ replace a separate word 'h3' by 'h1' in a string 'text',"re.sub('\\bH3\\b', 'H1', text)"
150
+ substitute ascii letters in string 'aas30dsa20' with empty string '',"re.sub('\\D', '', 'aas30dsa20')"
151
+ get digits only from a string `aas30dsa20` using lambda function,""""""""""""".join([x for x in 'aas30dsa20' if x.isdigit()])"
152
+ "access a tag called ""name"" in beautifulsoup `soup`",print(soup.find('name').string)
153
+ get a dictionary `records` of key-value pairs in pymongo cursor `cursor`,"records = dict((record['_id'], record) for record in cursor)"
154
+ create new matrix object by concatenating data from matrix a and matrix b,"np.concatenate((A, B))"
155
+ concat two matrices `a` and `b` in numpy,"np.vstack((A, B))"
156
+ get the characters count in a file `filepath`,os.stat(filepath).st_size
157
+ "count the occurrences of item ""a"" in list `l`",l.count('a')
158
+ count the occurrences of items in list `l`,Counter(l)
159
+ count the occurrences of items in list `l`,"[[x, l.count(x)] for x in set(l)]"
160
+ count the occurrences of items in list `l`,"dict(((x, l.count(x)) for x in set(l)))"
161
+ "count the occurrences of item ""b"" in list `l`",l.count('b')
162
+ copy file `srcfile` to directory `dstdir`,"shutil.copy(srcfile, dstdir)"
163
+ find the key associated with the largest value in dictionary `x` whilst key is non-zero value,"max(k for k, v in x.items() if v != 0)"
164
+ get the largest key whose not associated with value of 0 in dictionary `x`,"(k for k, v in x.items() if v != 0)"
165
+ get the largest key in a dictionary `x` with non-zero value,"max(k for k, v in x.items() if v != 0)"
166
+ put the curser at beginning of the file,file.seek(0)
167
+ combine values from column 'b' and column 'a' of dataframe `df` into column 'c' of datafram `df`,"df['c'] = np.where(df['a'].isnull, df['b'], df['a'])"
168
+ remove key 'ele' from dictionary `d`,del d['ele']
169
+ update datetime field in `mymodel` to be the existing `timestamp` plus 100 years,MyModel.objects.update(timestamp=F('timestamp') + timedelta(days=36524.25))
170
+ merge list `['it']` and list `['was']` and list `['annoying']` into one list,['it'] + ['was'] + ['annoying']
171
+ increment a value with leading zeroes in a number `x`,str(int(x) + 1).zfill(len(x))
172
+ check if a pandas dataframe `df`'s index is sorted,all(df.index[:-1] <= df.index[1:])
173
+ convert tuple `t` to list,list(t)
174
+ convert list `t` to tuple,tuple(l)
175
+ convert tuple `level1` to list,"level1 = map(list, level1)"
176
+ send the output of pprint object `dataobject` to file `logfile`,"pprint.pprint(dataobject, logFile)"
177
+ get index of rows in column 'boolcol',df.loc[df['BoolCol']]
178
+ create a list containing the indexes of rows where the value of column 'boolcol' in dataframe `df` are equal to true,df.iloc[np.flatnonzero(df['BoolCol'])]
179
+ get list of indexes of rows where column 'boolcol' values match true,df[df['BoolCol'] == True].index.tolist()
180
+ get index of rows in dataframe `df` which column 'boolcol' matches value true,df[df['BoolCol']].index.tolist()
181
+ change working directory to the directory `owd`,os.chdir(owd)
182
+ insert data from a string `testfield` to sqlite db `c`,"c.execute(""INSERT INTO test VALUES (?, 'bar')"", (testfield,))"
183
+ "decode string ""\\x89\\n"" into a normal string","""""""\\x89\\n"""""".decode('string_escape')"
184
+ convert a raw string `raw_string` into a normal string,raw_string.decode('string_escape')
185
+ convert a raw string `raw_byte_string` into a normal string,raw_byte_string.decode('unicode_escape')
186
+ split a string `s` with into all strings of repeated characters,"[m.group(0) for m in re.finditer('(\\d)\\1*', s)]"
187
+ "scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none","plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')"
188
+ do a scatter plot with empty circles,"plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')"
189
+ remove a div with a id `main-content` using beautifulsoup,"soup.find('div', id='main-content').decompose()"
190
+ filter rows containing key word `ball` in column `ids`,df[df['ids'].str.contains('ball')]
191
+ convert index at level 0 into a column in dataframe `df`,"df.reset_index(level=0, inplace=True)"
192
+ add indexes in a data frame `df` to a column `index1`,df['index1'] = df.index
193
+ convert pandas index in a dataframe to columns,"df.reset_index(level=['tick', 'obs'])"
194
+ get reverse of list items from list 'b' using extended slicing,[x[::-1] for x in b]
195
+ join each element in array `a` with element at the same index in array `b` as a tuple,"np.array([zip(x, y) for x, y in zip(a, b)])"
196
+ zip two 2-d arrays `a` and `b`,"np.array(zip(a.ravel(), b.ravel()), dtype='i4,i4').reshape(a.shape)"
197
+ convert list `list_of_ints` into a comma separated string,""""""","""""".join([str(i) for i in list_of_ints])"
198
+ send a post request with raw data `data` and basic authentication with `username` and `password`,"requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))"
199
+ "find last occurrence of character '}' in string ""abcd}def}""",'abcd}def}'.rfind('}')
200
+ "iterate ove list `[1, 2, 3]` using list comprehension","print([item for item in [1, 2, 3]])"
201
+ extract all the values with keys 'x' and 'y' from a list of dictionaries `d` to list of tuples,"[(x['x'], x['y']) for x in d]"
202
+ get the filename without the extension from file 'hemanth.txt',print(os.path.splitext(os.path.basename('hemanth.txt'))[0])
203
+ create a dictionary by adding each two adjacent elements in tuple `x` as key/value pair to it,"dict(x[i:i + 2] for i in range(0, len(x), 2))"
204
+ "create a list containing flattened list `[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]`","values = sum([['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']], [])"
205
+ select rows in a dataframe `df` column 'closing_price' between two values 99 and 101,df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
206
+ replace all occurences of newlines `\n` with `<br>` in dataframe `df`,"df.replace({'\n': '<br>'}, regex=True)"
207
+ replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`,"df.replace({'\n': '<br>'}, regex=True)"
208
+ create a list containing each two adjacent letters in string `word` as its elements,"[(x + y) for x, y in zip(word, word[1:])]"
209
+ get a list of pairs from a string `word` using lambda function,"list(map(lambda x, y: x + y, word[:-1], word[1:]))"
210
+ extract a url from a string `mystring`,"print(re.findall('(https?://[^\\s]+)', myString))"
211
+ extract a url from a string `mystring`,"print(re.search('(?P<url>https?://[^\\s]+)', myString).group('url'))"
212
+ "remove all special characters, punctuation and spaces from a string `mystring` using regex","re.sub('[^A-Za-z0-9]+', '', mystring)"
213
+ create a datetimeindex containing 13 periods of the second friday of each month starting from date '2016-01-01',"pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)"
214
+ create multidimensional array `matrix` with 3 rows and 2 columns in python,"matrix = [[a, b], [c, d], [e, f]]"
215
+ replace spaces with underscore,"mystring.replace(' ', '_')"
216
+ get an absolute file path of file 'mydir/myfile.txt',os.path.abspath('mydir/myfile.txt')
217
+ split string `my_string` on white spaces,""""""" """""".join(my_string.split())"
218
+ get filename without extension from file `filename`,os.path.splitext(filename)[0]
219
+ get a list containing the sum of each element `i` in list `l` plus the previous elements,"[sum(l[:i]) for i, _ in enumerate(l)]"
220
+ split a string `docs/src/scripts/temp` by `/` keeping `/` in the result,"""""""Docs/src/Scripts/temp"""""".replace('/', '/\x00/').split('\x00')"
221
+ shuffle columns of an numpy array 'r',np.random.shuffle(np.transpose(r))
222
+ copy all values in a column 'b' to a new column 'd' in a pandas data frame 'df',df['D'] = df['B']
223
+ find a value within nested json 'data' where the key inside another key 'b' is unknown.,list(data['A']['B'].values())[0]['maindata'][0]['Info']
224
+ check characters of string `string` are true predication of function `predicate`,all(predicate(x) for x in string)
225
+ determine number of files on a drive with python,os.statvfs('/').f_files - os.statvfs('/').f_ffree
226
+ how to get a single result from a sqlite query in python?,cursor.fetchone()[0]
227
+ convert string `user_input` into a list of integers `user_list`,"user_list = [int(number) for number in user_input.split(',')]"
228
+ get a list of integers by splitting a string `user` with comma,"[int(s) for s in user.split(',')]"
229
+ sorting a python list by two criteria,"sorted(list, key=lambda x: (x[0], -x[1]))"
230
+ "sort a list of objects `ut`, based on a function `cmpfun` in descending order","ut.sort(key=cmpfun, reverse=True)"
231
+ reverse list `ut` based on the `count` attribute of each object,"ut.sort(key=lambda x: x.count, reverse=True)"
232
+ sort a list of objects `ut` in reverse order by their `count` property,"ut.sort(key=lambda x: x.count, reverse=True)"
233
+ click a href button 'send' with selenium,driver.find_element_by_partial_link_text('Send').click()
234
+ click a href button having text `send inmail` with selenium,driver.findElement(By.linkText('Send InMail')).click()
235
+ click a href button with text 'send inmail' with selenium,driver.find_element_by_link_text('Send InMail').click()
236
+ cast an int `i` to a string and concat to string 'me','ME' + str(i)
237
+ sorting data in dataframe pandas,"df.sort_values(['System_num', 'Dis'])"
238
+ prepend the line '#test firstline\n' to the contents of file 'infile' and save as the file 'outfile',"open('outfile', 'w').write('#test firstline\n' + open('infile').read())"
239
+ sort a list `l` by length of value in tuple,"l.sort(key=lambda t: len(t[1]), reverse=True)"
240
+ split string `s` by words that ends with 'd',"re.findall('\\b(\\w+)d\\b', s)"
241
+ return `true` if string `foobarrrr` contains regex `ba[rzd]`,"bool(re.search('ba[rzd]', 'foobarrrr'))"
242
+ removing duplicates in list `t`,list(set(t))
243
+ removing duplicates in list `source_list`,list(set(source_list))
244
+ removing duplicates in list `abracadabra`,list(OrderedDict.fromkeys('abracadabra'))
245
+ convert array `a` into a list,numpy.array(a).reshape(-1).tolist()
246
+ convert the first row of numpy matrix `a` to a list,numpy.array(a)[0].tolist()
247
+ "in `soup`, get the content of the sibling of the `td` tag with text content `address:`",print(soup.find(text='Address:').findNext('td').contents[0])
248
+ convert elements of each tuple in list `l` into a string separated by character `@`,""""""" """""".join([('%d@%d' % t) for t in l])"
249
+ convert each tuple in list `l` to a string with '@' separating the tuples' elements,""""""" """""".join([('%d@%d' % (t[0], t[1])) for t in l])"
250
+ get the html from the current web page of a selenium driver,driver.execute_script('return document.documentElement.outerHTML;')
251
+ get all matches with regex pattern `\\d+[xx]` in list of string `teststr`,"[i for i in teststr if re.search('\\d+[xX]', i)]"
252
+ "select values from column 'a' for which corresponding values in column 'b' will be greater than 50, and in column 'c' - equal 900 in dataframe `df`",df['A'][(df['B'] > 50) & (df['C'] == 900)]
253
+ sort dictionary `o` in ascending order based on its keys and items,sorted(o.items())
254
+ get sorted list of keys of dict `d`,sorted(d)
255
+ how to sort dictionaries by keys in python,sorted(d.items())
256
+ "convert string ""1"" into integer",int('1')
257
+ function to convert strings into integers,int()
258
+ convert items in `t1` to integers,"T2 = [map(int, x) for x in T1]"
259
+ call a shell script `./test.sh` using subprocess,subprocess.call(['./test.sh'])
260
+ call a shell script `notepad` using subprocess,subprocess.call(['notepad'])
261
+ combine lists `l1` and `l2` by alternating their elements,"[val for pair in zip(l1, l2) for val in pair]"
262
+ encode string 'data to be encoded',encoded = base64.b64encode('data to be encoded')
263
+ encode a string `data to be encoded` to `ascii` encoding,encoded = 'data to be encoded'.encode('ascii')
264
+ parse tab-delimited csv file 'text.txt' into a list,"lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))"
265
+ get attribute `my_str` of object `my_object`,"getattr(my_object, my_str)"
266
+ group a list of dicts `ld` into one dict by key,"print(dict(zip(LD[0], zip(*[list(d.values()) for d in LD]))))"
267
+ how do i sum the first value in each tuple in a list of tuples in python?,sum([pair[0] for pair in list_of_pairs])
268
+ "convert unicode string u""{'code1':1,'code2':1}"" into dictionary","d = ast.literal_eval(""{'code1':1,'code2':1}"")"
269
+ find all words in a string `mystring` that start with the `$` sign,[word for word in mystring.split() if word.startswith('$')]
270
+ remove any url within string `text`,"text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)"
271
+ "replace all elements in array `a` that are not present in array `[1, 3, 4]` with zeros","np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)"
272
+ calculate mean across dimension in a 2d array `a`,"np.mean(a, axis=1)"
273
+ running r script '/pathto/myrscript.r' from python,"subprocess.call(['/usr/bin/Rscript', '--vanilla', '/pathto/MyrScript.r'])"
274
+ run r script '/usr/bin/rscript --vanilla /pathto/myrscript.r',"subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)"
275
+ add a header to a csv file,writer.writeheader()
276
+ replacing nan in the dataframe `df` with row average,"df.fillna(df.mean(axis=1), axis=1)"
277
+ convert unix timestamp '1347517370' to formatted string '%y-%m-%d %h:%m:%s',"time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))"
278
+ call a base class's class method `do` from derived class `derived`,"super(Derived, cls).do(a)"
279
+ "selecting rows in numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1","a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]"
280
+ separate words delimited by one or more spaces into a list,"re.split(' +', 'hello world sample text')"
281
+ length of longest element in list `words`,"len(max(words, key=len))"
282
+ get the value associated with unicode key 'from_user' of first dictionary in list `result`,result[0]['from_user']
283
+ retrieve each line from a file 'file.txt' as a list,[line.split() for line in open('File.txt')]
284
+ swap keys with values in a dictionary `a`,"res = dict((v, k) for k, v in a.items())"
285
+ open a file `path/to/file_name.ext` in write mode,"new_file = open('path/to/FILE_NAME.ext', 'w')"
286
+ how to count distinct values in a column of a pandas group by object?,"df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()"
287
+ check if any key in the dictionary `dict1` starts with the string `emp$$`,any(key.startswith('EMP$$') for key in dict1)
288
+ create list of values from dictionary `dict1` that have a key that starts with 'emp$$',"[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]"
289
+ convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`,"pd.DataFrame({'email': sf.index, 'list': sf.values})"
290
+ print elements of list `list` seperated by tabs `\t`,"print('\t'.join(map(str, list)))"
291
+ print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8,print('\xd0\xbf\xd1\x80\xd0\xb8'.encode('raw_unicode_escape'))
292
+ encode a latin character in string `sopet\xc3\xb3n` properly,'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
293
+ "resized image `image` to width, height of `(x, y)` with filter of `antialias`","image = image.resize((x, y), Image.ANTIALIAS)"
294
+ "regex, find ""n""s only in the middle of string `s`","re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)"
295
+ display the float `1/3*100` as a percentage,print('{0:.0f}%'.format(1.0 / 3 * 100))
296
+ sort a list of dictionary `mylist` by the key `title`,mylist.sort(key=lambda x: x['title'])
297
+ sort a list `l` of dicts by dict value 'title',l.sort(key=lambda x: x['title'])
298
+ "sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.","l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))"
299
+ find 10 largest differences between each respective elements of list `l1` and list `l2`,"heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))"
300
+ beautifulsoup find all 'span' elements in html string `soup` with class of 'stargryb sp',"soup.find_all('span', {'class': 'starGryB sp'})"
301
+ write records in dataframe `df` to table 'test' in schema 'a_schema',"df.to_sql('test', engine, schema='a_schema')"
302
+ extract brackets from string `s`,"brackets = re.sub('[^(){}[\\]]', '', s)"
303
+ remove duplicate elements from list 'l',"list(dict((x[0], x) for x in L).values())"
304
+ read a file `file` without newlines,[line.rstrip('\n') for line in file]
305
+ get the position of item 1 in `testlist`,"[i for (i, x) in enumerate(testlist) if (x == 1)]"
306
+ get the position of item 1 in `testlist`,"[i for (i, x) in enumerate(testlist) if (x == 1)]"
307
+ get the position of item 1 in `testlist`,"for i in [i for (i, x) in enumerate(testlist) if (x == 1)]:
308
+ pass"
309
+ get the position of item 1 in `testlist`,"for i in (i for (i, x) in enumerate(testlist) if (x == 1)):
310
+ pass"
311
+ get the position of item 1 in `testlist`,"gen = (i for (i, x) in enumerate(testlist) if (x == 1))
312
+ for i in gen:
313
+ pass"
314
+ get the position of item `element` in list `testlist`,print(testlist.index(element))
315
+ get the position of item `element` in list `testlist`,"try:
316
+ print(testlist.index(element))
317
+ except ValueError:
318
+ pass"
319
+ find the first element of the tuple with the maximum second element in a list of tuples `lis`,"max(lis, key=lambda item: item[1])[0]"
320
+ get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`,"max(lis, key=itemgetter(1))[0]"
321
+ make a delay of 1 second,time.sleep(1)
322
+ convert list of tuples `l` to a string,""""""", """""".join('(' + ', '.join(i) + ')' for i in L)"
323
+ django set default value of field `b` equal to '0000000',"b = models.CharField(max_length=7, default='0000000', editable=False)"
324
+ sort lis `list5` in ascending order based on the degrees value of its elements,"sorted(list5, lambda x: (degree(x), x))"
325
+ how do i perform secondary sorting in python?,"sorted(list5, key=lambda vertex: (degree(vertex), vertex))"
326
+ convert a list into a generator object,"(n for n in [1, 2, 3, 5])"
327
+ remove elements from list `oldlist` that have an index number mentioned in list `removelist`,"newlist = [v for i, v in enumerate(oldlist) if i not in removelist]"
328
+ open a file `yourfile.txt` in write mode,"f = open('yourfile.txt', 'w')"
329
+ get attribute 'attr' from object `obj`,"getattr(obj, 'attr')"
330
+ "convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple","from functools import reduce
331
+ reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))"
332
+ "convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line","map(lambda a: a[0], (('aa',), ('bb',), ('cc',)))"
333
+ python pandas: how to replace a characters in a column of a dataframe?,"df['range'].replace(',', '-', inplace=True)"
334
+ "unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`","zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])"
335
+ "unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`","zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])"
336
+ unzip list `original`,"result = ([a for (a, b) in original], [b for (a, b) in original])"
337
+ unzip list `original` and return a generator,"result = ((a for (a, b) in original), (b for (a, b) in original))"
338
+ "unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]`","zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])"
339
+ "unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with none","map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])"
340
+ encode `decimal('3.9')` to a json string,json.dumps(Decimal('3.9'))
341
+ "add key ""mynewkey"" to dictionary `d` with value ""mynewvalue""",d['mynewkey'] = 'mynewvalue'
342
+ add key 'a' to dictionary `data` with value 1,"data.update({'a': 1, })"
343
+ add key 'a' to dictionary `data` with value 1,data.update(dict(a=1))
344
+ add key 'a' to dictionary `data` with value 1,data.update(a=1)
345
+ find maximal value in matrix `matrix`,max([max(i) for i in matrix])
346
+ round number `answer` to 2 precision after the decimal point,"answer = str(round(answer, 2))"
347
+ extract ip address from an html string,"ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)"
348
+ filter dataframe `df` by values in column `a` that appear more than once,df.groupby('A').filter(lambda x: len(x) > 1)
349
+ append each line in file `myfile` into a list,[x for x in myfile.splitlines() if x != '']
350
+ get a list of integers `lst` from a file `filename.txt`,"lst = map(int, open('filename.txt').readlines())"
351
+ add color bar with image `mappable` to plot `plt`,"plt.colorbar(mappable=mappable, cax=ax3)"
352
+ count most frequent 100 words in column 'text' of dataframe `df`,Counter(' '.join(df['text']).split()).most_common(100)
353
+ python split a string using regex,"re.findall('(.+?):(.+?)\\b ?', text)"
354
+ "generate all 2-element subsets of tuple `(1, 2, 3)`","list(itertools.combinations((1, 2, 3), 2))"
355
+ get a value of datetime.today() in the utc time zone,datetime.now(pytz.utc)
356
+ get a new list `list2`by removing empty list from a list of lists `list1`,list2 = [x for x in list1 if x != []]
357
+ create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`,list2 = [x for x in list1 if x]
358
+ django response with json `data`,"return HttpResponse(data, mimetype='application/json')"
359
+ get all text that is not enclosed within square brackets in string `example_str`,"re.findall('(.*?)\\[.*?\\]', example_str)"
360
+ use a regex to get all text in a string `example_str` that is not surrounded by square brackets,"re.findall('(.*?)(?:\\[.*?\\]|$)', example_str)"
361
+ "get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'","re.findall('\\(.+?\\)|\\w', '(zyx)bc')"
362
+ match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc',"re.findall('\\((.*?)\\)|(\\w)', '(zyx)bc')"
363
+ match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`,"re.findall('\\(.*?\\)|\\w', '(zyx)bc')"
364
+ formate each string cin list `elements` into pattern '%{0}%',elements = ['%{0}%'.format(element) for element in elements]
365
+ open a background process 'background-process' with arguments 'arguments',"subprocess.Popen(['background-process', 'arguments'])"
366
+ get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys',[mydict[x] for x in mykeys]
367
+ "convert list `[('name', 'joe'), ('age', 22)]` into a dictionary","dict([('Name', 'Joe'), ('Age', 22)])"
368
+ average each two columns of array `data`,"data.reshape(-1, j).mean(axis=1).reshape(data.shape[0], -1)"
369
+ double backslash escape all double quotes in string `s`,"print(s.encode('unicode-escape').replace('""', '\\""'))"
370
+ split a string into a list of words and whitespace,"re.split('(\\W+)', s)"
371
+ plotting stacked barplots on a panda data frame,"df.plot(kind='barh', stacked=True)"
372
+ reverse the keys and values in a dictionary `mydictionary`,{i[1]: i[0] for i in list(myDictionary.items())}
373
+ finding the index of elements containing substring 'how' and 'what' in a list of strings 'mylist'.,"[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]"
374
+ check if object `obj` is a string,"isinstance(obj, str)"
375
+ check if object `o` is a string,"isinstance(o, str)"
376
+ check if object `o` is a string,(type(o) is str)
377
+ check if object `o` is a string,"isinstance(o, str)"
378
+ check if `obj_to_test` is a string,"isinstance(obj_to_test, str)"
379
+ append list `list1` to `list2`,list2.extend(list1)
380
+ append list `mylog` to `list1`,list1.extend(mylog)
381
+ append list `a` to `c`,c.extend(a)
382
+ append items in list `mylog` to `list1`,"for line in mylog:
383
+ list1.append(line)"
384
+ append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`,"b.append((a[0][0], a[0][2]))"
385
+ initialize `secret_key` in flask config with `your_secret_string `,app.config['SECRET_KEY'] = 'Your_secret_string'
386
+ unpack a series of tuples in pandas into a dataframe with column names 'out-1' and 'out-2',"pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)"
387
+ find the index of an element 'msft' in a list `stocks_list`,[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']
388
+ rotate the xtick labels of matplotlib plot `ax` by `45` degrees to make long labels readable,"ax.set_xticklabels(labels, rotation=45)"
389
+ remove symbols from a string `s`,"re.sub('[^\\w]', ' ', s)"
390
+ get the current directory of a script,os.path.basename(os.path.dirname(os.path.realpath(__file__)))
391
+ find octal characters matches from a string `str` using regex,"print(re.findall(""'\\\\[0-7]{1,3}'"", str))"
392
+ split string `input` based on occurrences of regex pattern '[ ](?=[a-z]+\\b)',"re.split('[ ](?=[A-Z]+\\b)', input)"
393
+ split string `input` at every space followed by an upper-case letter,"re.split('[ ](?=[A-Z])', input)"
394
+ send multipart encoded file `files` to url `url` with headers `headers` and metadata `data`,"r = requests.post(url, files=files, headers=headers, data=data)"
395
+ write bytes `bytes_` to a file `filename` in python 3,"open('filename', 'wb').write(bytes_)"
396
+ get a list from a list `lst` with values mapped into a dictionary `dct`,[dct[k] for k in lst]
397
+ find duplicate names in column 'name' of the dataframe `x`,x.set_index('name').index.get_duplicates()
398
+ truncate float 1.923328437452 to 3 decimal places,"round(1.923328437452, 3)"
399
+ sort list `li` in descending order based on the date value in second element of each list in list `li`,"sorted(li, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)"
400
+ place the radial ticks in plot `ax` at 135 degrees,ax.set_rlabel_position(135)
401
+ check if path `my_path` is an absolute path,os.path.isabs(my_path)
402
+ get number of keys in dictionary `yourdict`,len(list(yourdict.keys()))
403
+ count the number of keys in dictionary `yourdictfile`,len(set(open(yourdictfile).read().split()))
404
+ pandas dataframe get first row of each group by 'id',df.groupby('id').first()
405
+ split a list in first column into multiple columns keeping other columns as well in pandas data frame,"pd.concat([df[0].apply(pd.Series), df[1]], axis=1)"
406
+ "extract attributes 'src=""js/([^""]*\\bjquery\\b[^""]*)""' from string `data`","re.findall('src=""js/([^""]*\\bjquery\\b[^""]*)""', data)"
407
+ "sum integers contained in strings in list `['', '3.4', '', '', '1.0']`","sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])"
408
+ call a subprocess with arguments `c:\\program files\\vmware\\vmware server\\vmware-cmd.bat` that may contain spaces,subprocess.Popen(['c:\\Program Files\\VMware\\VMware Server\\vmware-cmd.bat'])
409
+ reverse a priority queue `q` in python without using classes,"q.put((-n, n))"
410
+ make a barplot of data in column `group` of dataframe `df` colour-coded according to list `color`,"df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r'])"
411
+ find all matches of regex pattern '([a-fa-f\\d]{32})' in string `data`,"re.findall('([a-fA-F\\d]{32})', data)"
412
+ get the length of list `my_list`,len(my_list)
413
+ getting the length of array `l`,len(l)
414
+ getting the length of array `s`,len(s)
415
+ getting the length of `my_tuple`,len(my_tuple)
416
+ getting the length of `my_string`,len(my_string)
417
+ "remove escape character from string ""\\a""","""""""\\a"""""".decode('string_escape')"
418
+ replace each 'a' with 'b' and each 'b' with 'a' in the string 'obama' in a single pass.,"""""""obama"""""".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')"
419
+ remove directory tree '/folder_name',shutil.rmtree('/folder_name')
420
+ create a new column `weekday` in pandas data frame `data` based on the values in column `my_dt`,data['weekday'] = data['my_dt'].apply(lambda x: x.weekday())
421
+ reverse sort counter `x` by values,"sorted(x, key=x.get, reverse=True)"
422
+ reverse sort counter `x` by value,"sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)"
423
+ append a numpy array 'b' to a numpy array 'a',"np.vstack((a, b))"
424
+ numpy concatenate two arrays `a` and `b` along the first axis,"print(concatenate((a, b), axis=0))"
425
+ numpy concatenate two arrays `a` and `b` along the second axis,"print(concatenate((a, b), axis=1))"
426
+ numpy concatenate two arrays `a` and `b` along the first axis,"c = np.r_[(a[None, :], b[None, :])]"
427
+ numpy concatenate two arrays `a` and `b` along the first axis,"np.array((a, b))"
428
+ fetch address information for host 'google.com' ion port 80,"print(socket.getaddrinfo('google.com', 80))"
429
+ add a column 'day' with value 'sat' to dataframe `df`,"df.xs('sat', level='day', drop_level=False)"
430
+ return a 401 unauthorized in django,"return HttpResponse('Unauthorized', status=401)"
431
+ flask set folder 'wherever' as the default template folder,"Flask(__name__, template_folder='wherever')"
432
+ how do i insert into t1 (select * from t2) in sqlalchemy?,session.execute('INSERT INTO t1 (SELECT * FROM t2)')
433
+ sort a list of lists 'c2' such that third row comes first,c2.sort(key=lambda row: row[2])
434
+ sorting a list of lists in python,"c2.sort(key=lambda row: (row[2], row[1], row[0]))"
435
+ sorting a list of lists in python,"c2.sort(key=lambda row: (row[2], row[1]))"
436
+ set font `arial` to display non-ascii characters in matplotlib,"matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})"
437
+ convert datetime column 'date' of pandas dataframe 'df' to ordinal,df['date'].apply(lambda x: x.toordinal())
438
+ get html source of selenium webelement `element`,element.get_attribute('innerHTML')
439
+ get the integer location of a key `bob` in a pandas data frame,df.index.get_loc('bob')
440
+ open a 'gnome' terminal from python script and run 'sudo apt-get update' command.,"os.system('gnome-terminal -e \'bash -c ""sudo apt-get update; exec bash""\'')"
441
+ add an item with key 'third_key' and value 1 to an dictionary `my_dict`,my_dict.update({'third_key': 1})
442
+ declare an array,my_list = []
443
+ insert item `12` to a list `my_list`,my_list.append(12)
444
+ add an entry 'wuggah' at the beginning of list `mylist`,"myList.insert(0, 'wuggah')"
445
+ convert a hex-string representation to actual bytes,"""""""\\xF3\\xBE\\x80\\x80"""""".replace('\\x', '').decode('hex')"
446
+ select the last column of dataframe `df`,df[df.columns[-1]]
447
+ get the first value from dataframe `df` where column 'letters' is equal to 'c',"df.loc[df['Letters'] == 'C', 'Letters'].values[0]"
448
+ "converting two lists `[1, 2, 3]` and `[4, 5, 6]` into a matrix","np.column_stack(([1, 2, 3], [4, 5, 6]))"
449
+ get the type of `i`,type(i)
450
+ determine the type of variable `v`,type(v)
451
+ determine the type of variable `v`,type(v)
452
+ determine the type of variable `v`,type(v)
453
+ determine the type of variable `v`,type(v)
454
+ get the type of variable `variable_name`,print(type(variable_name))
455
+ get the 5th item of a generator,"next(itertools.islice(range(10), 5, 5 + 1))"
456
+ print a string `word` with string format,"print('""{}""'.format(word))"
457
+ join a list of strings `list` using a space ' ',""""""" """""".join(list)"
458
+ create list `y` containing two empty lists,y = [[] for n in range(2)]
459
+ read a file 'c:/name/mydocuments/numbers' into a list `data`,"data = [line.strip() for line in open('C:/name/MyDocuments/numbers', 'r')]"
460
+ delete all occurrences of character 'i' in string 'it is icy',""""""""""""".join([char for char in 'it is icy' if char != 'i'])"
461
+ delete all instances of a character 'i' in a string 'it is icy',"re.sub('i', '', 'it is icy')"
462
+ "delete all characters ""i"" in string ""it is icy""","""""""it is icy"""""".replace('i', '')"
463
+ how to delete all instances of a character in a string in python?,""""""""""""".join([char for char in 'it is icy' if char != 'i'])"
464
+ "drop rows of pandas dataframe `df` having nan in column at index ""1""",df.dropna(subset=[1])
465
+ "get elements from list `mylist`, that have a field `n` value 30",[x for x in myList if x.n == 30]
466
+ converting list of strings `intstringlist` to list of integer `nums`,nums = [int(x) for x in intstringlist]
467
+ convert list of string numbers into list of integers,"map(int, eval(input('Enter the unfriendly numbers: ')))"
468
+ "print ""."" without newline",sys.stdout.write('.')
469
+ round off the float that is the product of `2.52 * 100` and convert it to an int,int(round(2.51 * 100))
470
+ "find all files in directory ""/mydir"" with extension "".txt""","os.chdir('/mydir')
471
+ for file in glob.glob('*.txt'):
472
+ pass"
473
+ "find all files in directory ""/mydir"" with extension "".txt""","for file in os.listdir('/mydir'):
474
+ if file.endswith('.txt'):
475
+ pass"
476
+ "find all files in directory ""/mydir"" with extension "".txt""","for (root, dirs, files) in os.walk('/mydir'):
477
+ for file in files:
478
+ if file.endswith('.txt'):
479
+ pass"
480
+ plot dataframe `df` without a legend,df.plot(legend=False)
481
+ "loop through the ip address range ""192.168.x.x""","for i in range(256):
482
+ for j in range(256):
483
+ ip = ('192.168.%d.%d' % (i, j))
484
+ print(ip)"
485
+ "loop through the ip address range ""192.168.x.x""","for (i, j) in product(list(range(256)), list(range(256))):
486
+ pass"
487
+ "loop through the ip address range ""192.168.x.x""","generator = iter_iprange('192.168.1.1', '192.168.255.255', step=1)"
488
+ sum the corresponding decimal values for binary values of each boolean element in list `x`,"sum(1 << i for i, b in enumerate(x) if b)"
489
+ "write multiple strings `line1`, `line2` and `line3` in one line in a file `target`","target.write('%r\n%r\n%r\n' % (line1, line2, line3))"
490
+ convert list of lists `data` into a flat list,"[y for x in data for y in (x if isinstance(x, list) else [x])]"
491
+ print new line character as `\n` in a string `foo\nbar`,print('foo\nbar'.encode('string_escape'))
492
+ "remove last comma character ',' in string `s`",""""""""""""".join(s.rsplit(',', 1))"
493
+ calculate the mean of each element in array `x` with the element previous to it,(x[1:] + x[:-1]) / 2
494
+ get an array of the mean of each two consecutive values in numpy array `x`,x[:-1] + (x[1:] - x[:-1]) / 2
495
+ load data containing `utf-8` from file `new.txt` into numpy array `arr`,"arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')"
496
+ reverse sort list of dicts `l` by value for key `time`,"l = sorted(l, key=itemgetter('time'), reverse=True)"
497
+ sort a list of dictionary `l` based on key `time` in descending order,"l = sorted(l, key=lambda a: a['time'], reverse=True)"
498
+ get rows of dataframe `df` that match regex '(hel|just)',df.loc[df[0].str.contains('(Hel|Just)')]
499
+ "find the string in `your_string` between two special characters ""["" and ""]""","re.search('\\[(.*)\\]', your_string).group(1)"
500
+ how to create a list of date string in 'yyyymmdd' format with python pandas?,"[d.strftime('%Y%m%d') for d in pandas.date_range('20130226', '20130302')]"
501
+ count number of times string 'brown' occurred in string 'the big brown fox is brown',"""""""The big brown fox is brown"""""".count('brown')"
502
+ decode json string `request.body` to python dict,json.loads(request.body)
503
+ download the file from url `url` and save it under file `file_name`,"urllib.request.urlretrieve(url, file_name)"
504
+ split string `text` by space,text.split()
505
+ "split string `text` by "",""","text.split(',')"
506
+ split string `line` into a list by whitespace,line.split()
507
+ replace dot characters '.' associated with ascii letters in list `s` with space ' ',"[re.sub('(?<!\\d)\\.(?!\\d)', ' ', i) for i in s]"
508
+ sort list `list_of_strings` based on second index of each string `s`,"sorted(list_of_strings, key=lambda s: s.split(',')[1])"
509
+ call multiple bash function 'vasp' and 'tee tee_output' using '|',"subprocess.check_call('vasp | tee tee_output', shell=True)"
510
+ eliminate all strings from list `lst`,"[element for element in lst if isinstance(element, int)]"
511
+ get all the elements except strings from the list 'lst'.,"[element for element in lst if not isinstance(element, str)]"
512
+ sort a list of dictionaries `list_to_be_sorted` by the value of the dictionary key `name`,"newlist = sorted(list_to_be_sorted, key=lambda k: k['name'])"
513
+ sort a list of dictionaries `l` by values in key `name` in descending order,"newlist = sorted(l, key=itemgetter('name'), reverse=True)"
514
+ how do i sort a list of dictionaries by values of the dictionary in python?,list_of_dicts.sort(key=operator.itemgetter('name'))
515
+ how do i sort a list of dictionaries by values of the dictionary in python?,list_of_dicts.sort(key=operator.itemgetter('age'))
516
+ how to sort a dataframe by the ocurrences in a column in python (pandas),"df.groupby('prots').sum().sort('scores', ascending=False)"
517
+ "join together with "","" elements inside a list indexed with 'category' within a dictionary `trans`",""""""","""""".join(trans['category'])"
518
+ "concatenate array of strings `['a', 'b', 'c', 'd']` into a string",""""""""""""".join(['A', 'B', 'C', 'D'])"
519
+ get json data from restful service 'url',json.load(urllib.request.urlopen('url'))
520
+ remove all strings from a list a strings `sents` where the values starts with `@$\t` or `#`,[x for x in sents if not x.startswith('@$\t') and not x.startswith('#')]
521
+ django filter by hour,Entry.objects.filter(pub_date__contains='08:00')
522
+ sort a list of dictionary `list` first by key `points` and then by `time`,"list.sort(key=lambda item: (item['points'], item['time']))"
523
+ "convert datetime object `(1970, 1, 1)` to seconds","(t - datetime.datetime(1970, 1, 1)).total_seconds()"
524
+ insert `_suff` before the file extension in `long.file.name.jpg` or replace `_a` with `suff` if it precedes the extension.,"re.sub('(\\_a)?\\.([^\\.]*)$', '_suff.\\2', 'long.file.name.jpg')"
525
+ reload a module `module`,"import imp
526
+ imp.reload(module)"
527
+ convert integer `number` into an unassigned integer,"struct.unpack('H', struct.pack('h', number))"
528
+ convert int values in list `numlist` to float,numlist = [float(x) for x in numlist]
529
+ "write dataframe `df`, excluding index, to a csv file","df.to_csv(filename, index=False)"
530
+ convert a urllib unquoted string `unescaped` to a json data `json_data`,json_data = json.loads(unescaped)
531
+ create a list containing all ascii characters as its elements,[chr(i) for i in range(127)]
532
+ write `newfilebytes` to a binary file `newfile`,"newFile.write(struct.pack('5B', *newFileBytes))"
533
+ python regex - check for a capital letter with a following lowercase in string `string`,"re.sub('^[A-Z0-9]*(?![a-z])', '', string)"
534
+ get the last key of dictionary `dict`,list(dict.keys())[-1]
535
+ "write line ""hi there"" to file `f`","print('hi there', file=f)"
536
+ "write line ""hi there"" to file `myfile`","f = open('myfile', 'w')
537
+ f.write('hi there\n')
538
+ f.close()"
539
+ "write line ""hello"" to file `somefile.txt`","with open('somefile.txt', 'a') as the_file:
540
+ the_file.write('Hello\n')"
541
+ convert unicode string `s` to ascii,s.encode('iso-8859-15')
542
+ django get maximum value associated with field 'added' in model `authorizedemail`,AuthorizedEmail.objects.filter(group=group).order_by('-added')[0]
543
+ find all numbers and dots from a string `text` using regex,"re.findall('Test([0-9.]*[0-9]+)', text)"
544
+ python regex to find all numbers and dots from 'text',"re.findall('Test([\\d.]*\\d+)', text)"
545
+ execute script 'script.ps1' using 'powershell.exe' shell,"os.system('powershell.exe', 'script.ps1')"
546
+ sort a list of tuples `b` by third item in the tuple,b.sort(key=lambda x: x[1][2])
547
+ get a list of all keys in cassandra database `cf` with pycassa,list(cf.get_range().get_keys())
548
+ create a datetime with the current date & time,datetime.datetime.now()
549
+ get the index of an integer `1` from a list `lst` if the list also contains boolean items,"next(i for i, x in enumerate(lst) if not isinstance(x, bool) and x == 1)"
550
+ subtract 13 from every number in a list `a`,a[:] = [(x - 13) for x in a]
551
+ "choose a random file from the directory contents of the c drive, `c:\\`",random.choice(os.listdir('C:\\'))
552
+ get the highest element in absolute value in a numpy matrix `x`,"max(x.min(), x.max(), key=abs)"
553
+ get all urls within text `s`,"re.findall('""(http.*?)""', s, re.MULTILINE | re.DOTALL)"
554
+ match urls whose domain doesn't start with `t` from string `document` using regex,"re.findall('http://[^t][^s""]+\\.html', document)"
555
+ split a string `mystring` considering the spaces ' ',"mystring.replace(' ', '! !').split('!')"
556
+ open file `path` with mode 'r',"open(path, 'r')"
557
+ sum elements at the same index in list `data`,[[sum(item) for item in zip(*items)] for items in zip(*data)]
558
+ add a new axis to array `a`,"a[:, (np.newaxis)]"