text
stringlengths
4
1.08k
get http response codes with python,urllib.request.urlopen('http://google.com').getcode()
get last day of the second month in 2002,"calendar.monthrange(2008, 2)"
retrieving a variable's name in python at runtime?,locals()['i']
how to extract the n-th elements from a list of tuples in python?,zip(*elements)[1]
"how to ""scale"" a numpy array?","array([[1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 1, 1]])"
python: read lines from compressed text files,gzip.open('myfile.gz')
get all elements in a list where the value is equal to certain value,"rows = [i for i in range(0, len(a)) if a[i][0] == value]"
python | change text color in shell,colored.red('red string')
get the middle two characters of a string 'state' in a pandas dataframe `df`,df['state'].apply(lambda x: x[len(x) / 2 - 1:len(x) / 2 + 1])
find average of every three columns in pandas dataframe,"df.groupby(np.arange(len(df.columns)) // 3, axis=1).mean()"
screenshot of a window using python,QApplication.desktop()
lookup dictionary key `key1` in django template `json`,{{json.key1}}
how to search a list of tuples in python,[x[0] for x in a]
how to get cookies from web-browser with python?,"r = requests.get('http://stackoverflow.com', cookies=cj)"
get date format in python in windows,"locale.setlocale(locale.LC_ALL, 'english')"
convert list of booleans `walls` into a hex string,"hex(int(''.join([str(int(b)) for b in walls]), 2))"
how to read numbers in text file using python?,data = [[int(v) for v in line.split()] for line in lines]
navigation with beautifulsoup,soup.select('div.container a[href]')
sort dictionary `u` in ascending order based on second elements of its values,"sorted(list(u.items()), key=lambda v: v[1])"
subprocess: deleting child processes in windows,"subprocess.call(['taskkill', '/F', '/T', '/PID', str(p.pid)])"
"in python, how do i know when a process is finished?",self.process.terminate()
python convert tuple to string,""""""""""""".join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))"
how can i make an animation with contourf()?,plt.show()
what is a 'good practice' way to write a python gtk+ application?,gtk.main()
log info message 'log message' with attributes `{'app_name': 'myapp'}`,"logging.info('Log message', extra={'app_name': 'myapp'})"
failing to send email with the python example,"server = smtplib.SMTP('smtp.gmail.com', 587)"
finding the largest delta between two integers in a list in python,"max(abs(x - y) for x, y in zip(values[1:], values[:-1]))"
select rows from a dataframe based on values in a column in pandas,df.loc[df['column_name'] == some_value]
print a dictionary `{'user': {'name': 'markus'}}` with string formatting,"""""""Hello {user[name]}"""""".format(**{'user': {'name': 'Markus'}})"
group dataframe `data` entries by year value of the date in column 'date',data.groupby(data['date'].map(lambda x: x.year))
python: store many regex matches in tuple?,"['home', 'about', 'music', 'photos', 'stuff', 'contact']"
key order in python dictionaries,print(sorted(d.keys()))
python: lambda function in list comprehensions,[(lambda x: x * x) for _ in range(3)]
scrolling down a page with selenium webdriver,"driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')"
how does python do string magic?,""""""""""""".join(['x', 'x', 'x'])"
plot data of column 'index' versus column 'a' of dataframe `monthly_mean` after resetting its index,"monthly_mean.reset_index().plot(x='index', y='A')"
how to convert a numpy 2d array with object dtype to a regular 2d array of floats,"np.array(list(arr[:, (1)]), dtype=np.float)"
i want to plot perpendicular vectors in python,"plt.figure(figsize=(6, 6))"
python convert string literal to float,"total = sum(float(item) for item in s.split(','))"
matching blank lines with regular expressions,"re.split('\n\\s*\n', s)"
dividing a string at various punctuation marks using split(),""""""""""""".join(char if char.isalpha() else ' ' for char in test).split()"
is there a simple to get group names of a user in django,"l = request.user.groups.values_list('name', flat=True)"
extract array from list in python,zip(*data)
add tuple to list of tuples in python,"result = [(x + dx, y + dy) for x, y in points for dx, dy in offsets]"
how to get a list of file extensions for a general file type?,mimetypes.init()
how do i create a datetime in python from milliseconds?,datetime.datetime.fromtimestamp(ms / 1000.0)
how to clamp an integer to some range? (in python),"new_index = max(0, min(new_index, len(mylist) - 1))"
getting inverse (1/x) elements of a numpy array,"array = np.array([1, 2, 3, 4])"
copy keys to a new dictionary (python),set(d.keys())
create dict of squared int values in range of 100,{(x ** 2) for x in range(100)}
sorting a dictionary (with date keys) in python,"ordered = OrderedDict(sorted(list(mydict.items()), key=lambda t: t[0]))"
python: pandas dataframe from series of dict,new_df = pd.DataFrame(list(original['user']))
print cpu and memory usage,"print((psutil.cpu_percent()))
print((psutil.virtual_memory()))"
best way to plot an angle between two lines in matplotlib,"ax.set_xlim(0, 7)"
how to make a simple command-line chat in python?,sys.exit(0)
convert string representation of list to list in python,"ast.literal_eval('[""A"",""B"" ,""C"" ,"" D""]')"
3d plot with matplotlib,ax.set_zlabel('Z')
resampling trade data into ohlcv with pandas,"df.resample('30s', how={'volume': 'sum'})"
get a new string from the 3rd character to the end of the string `x`,x[2:]
how do i remove a node in xml using elementtree in python?,tree.remove(tree.findall('.//B')[1])
insert row into mysql database with column 'column1' set to the value `value`,"cursor.execute('INSERT INTO table (`column1`) VALUES (%s)', (value,))"
how do you get the magnitude of a vector in numpy?,"np.linalg.norm(x, ord=1)"
check if string `one` exists in the values of dictionary `d`,'one' in list(d.values())
regex: how to match sequence of key-value pairs at end of string,"pairs = dict([match.split(':', 1) for match in matches])"
how to add a scrollbar to a window with tkinter?,root.mainloop()
get value of first index of each element in list `a`,[x[0] for x in a]
how to get names of all the variables defined in methods of a class,"['setUp', 'bar', 'baz', 'var1', 'var2', 'var3', 'var4']"
regular expression to return all characters between two special characters,"re.findall('\\[(.*?)\\]', mystring)"
remove specific characters from list python,"result = [(a.split('-', 1)[0], b) for a, b in sorted_x]"
split items in list,"result = [item for word in words for item in word.split(',')]"
how to specify a position in a list and use it?,"test = [0, 1, 2, 3, 2, 2, 3]"
find the current directory,os.getcwd()
python extract data from file,line = line.decode('utf-8')
converting a java system.currenttimemillis() to date in python,print(date.fromtimestamp(1241711346274 / 1000.0))
check if dictionary key is filled with list of 2 numbers,"len(d[obj]) == 2 and isinstance(d[obj][0], int) and isinstance(d[obj][1], int)"
replace single instances of a character that is sometimes doubled,"s.replace('||', '|||')[::2]"
how to remove specific elements in a numpy array,"b = np.delete(a, [2, 3, 6])"
how to remove gaps between subplots in matplotlib?,ax1.set_xticklabels([])
getting the indices of several elements in a numpy array at once,"np.in1d(b, a).nonzero()[0]"
"python, encoding output to utf-8",f.write(s.encode('utf8'))
basic authentication using urllib2 with python with jira rest api,"r = requests.get('https://api.github.com', auth=('user', 'pass'))"
rename multiple files in python,"os.rename(file, new_name)"
list comprehension with if statement,[y for y in a if y not in b]
how to print particular json value in python?,"{'X': 'value1', 'Y': 'value2', 'Z': [{'A': 'value3', 'B': 'value4'}]}"
lowercase all keys and values in dictionary `{'my key': 'my value'}`,"dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())"
python dict how to create key or append an element to key?,"dic.setdefault(key, []).append(value)"
how to target a different host inside a fabric command,run('ls -lart')
how do i get the filepath for a class in python?,inspect.getfile(C.__class__)
how to force os.system() to use bash instead of shell,"os.system('GREPDB=""echo 123""; /bin/bash -c ""$GREPDB""')"
generate unique equal hash for equal dictionaries `a` and `b`,hash(pformat(a)) == hash(pformat(b))
update dictionary with dynamic keys and values in python,mydic.update({i: o['name']})
selenium phantomjs custom headers in python,driver.get('http://cn.bing.com')
how to delete an rdd in pyspark for the purpose of releasing resources?,"thisRDD = sc.parallelize(range(10), 2).cache()"
row-wise indexing in numpy,"A[np.arange(2)[:, (None)], B]"
output utf-8 characters in django as json,"print(json.dumps('\u0411', ensure_ascii=False))"
split list by condition in python,"aList, bList = [[x for x in a if x[0] == i] for i in (0, 1)]"
matplotlib: formatting dates on the x-axis in a 3d bar graph,ax.set_zlabel('Amount')
iterate over a dictionary `foo` sorted by the key,"for k in sorted(foo.keys()):
pass"