text
stringlengths
4
1.08k
create a dictionary of pairs from a list of tuples `mylistoftuples`,dict(x[1:] for x in reversed(myListOfTuples))
categorize list in python,"list([x for x in totalist if x[:2] == ['A', 'B']])"
check if the string `mystring` is empty,"if (not myString):
pass"
decode string `content` to utf-8 code,print(content.decode('utf8'))
"reading freebase data dump in python, read to few lines?","open('file', 'rb')"
finding missing values in a numpy array,m[~m.mask]
convert a number 2130706433 to ip string,"socket.inet_ntoa(struct.pack('!L', 2130706433))"
converting string to dict?,"ast.literal_eval(""{'x':1, 'y':2}"")"
get the immediate minimum among a list of numbers in python,max([x for x in num_list if x < 3])
how do i access the request object or any other variable in a form's clean() method?,"myform = MyForm(request.POST, request=request)"
format a datetime into a string with milliseconds,print(datetime.utcnow().strftime('%Y%m%d%H%M%S%f'))
sorting list based on values from another list?,"[x for y, x in sorted(zip(Y, X))]"
how do i use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', 'A')"
python turning a list into a list of tuples,"done = [(el, x) for el in [a, b, c, d]]"
logging in a framework,log = logging.getLogger(__name__)
"check whether a path ""/does/not/exist"" exists",print(os.path.exists('/does/not/exist'))
equivalent of bash backticks in python,output = os.popen('cat /tmp/baz').read()
get all characters in string 'foobar' up to the fourth index,"""""""foobar""""""[:4]"
flask sqlalchemy query with keyword as variable,"User.query.filter_by(hometown='New York', university='USC')"
returning the highest 6 names in a list of tuple in python,"heapq.nlargest(6, your_list, key=itemgetter(1))"
how to split python script in parts and to import the parts in a loop?,time.sleep(1)
create a flat dictionary by summing values associated with similar keys in each dictionary of list `dictlist`,"dict((key, sum(d[key] for d in dictList)) for key in dictList[0])"
how to speed up the code - searching through a dataframe takes hours,df.head()
how do i check if a list is sorted?,mylist.sort()
changing the font on a wxpython textctrl widget,myTextCtrl.SetFont(font1)
using spritesheets in tkinter,self.canvas.pack()
django template convert to string,{{(value | stringformat): 'i'}}
define global variable `something` with value `bob`,globals()['something'] = 'bob'
beautiful soup using regex to find tags?,"soup.find_all(['a', 'div'])"
python: logging module - globally,logger.debug('submodule message')
os.getcwd() for a different drive in windows,os.chdir('z:')
change one character in a string in python?,new = text[:1] + 'Z' + text[2:]
get logical xor of `a` and `b`,(bool(a) ^ bool(b))
search for occurrences of regex pattern `pattern` in string `url`,print(pattern.search(url).group(1))
delete every non `utf-8` characters from a string `line`,"line = line.decode('utf-8', 'ignore').encode('utf-8')"
pandas changing cell values based on another cell,df.sort_index(inplace=True)
how do i compile a visual studio project from the command-line?,os.system('msbuild project.sln /p:Configuration=Debug')
"find the maximum x,y value fromn a series of images","x = np.maximum(x, y)"
"find element by css selector ""input[onclick*='1 bedroom deluxe']""","driver.find_element_by_css_selector(""input[onclick*='1 Bedroom Deluxe']"")"
simple way to create matrix of random numbers,"numpy.random.random((3, 3))"
python convert list to dictionary,"dict(zip(l[::2], l[1::2]))"
slicing numpy array with another array,"numpy.ma.array(strided, mask=mask)"
convert an int 65 to hex string,hex(65)
remove parentheses and text within it in string `filename`,"re.sub('\\([^)]*\\)', '', filename)"
find/extract a sequence of integers within a list in python,"[1, 2, 3, 4]"
"how to do an inverse `range`, i.e. create a compact range based on a set of numbers?","[1, 1, 2, 2]"
returning distinct rows in sqlalchemy with sqlite,session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()
how to find hidden attributes of python objects? (attributes that don't appear in the dir(obj) list),"['a', 'b', 'c', 'd'], ['a', 'b', 'c']"
how to insert / retrieve a file stored as a blob in a mysql db using python,"cursor.execute(sql, (thedata,))"
best way to plot an angle between two lines in matplotlib,"ax.set_ylim(0, 5)"
get the date 1 month from today,"(date(2010, 12, 31) + relativedelta(months=(+ 1)))"
python regex to get everything until the first dot in a string,find = re.compile('^(.*?)\\..*')
python-requests close http connection,"r = requests.post(url=url, data=body, headers={'Connection': 'close'})"
drawing cards from a deck in scipy with scipy.stats.hypergeom,"scipy.stats.hypergeom.pmf(k, M, n, N)"
how can i do assignments in a list comprehension?,l = [[x for x in range(5)] for y in range(4)]
selecting unique observations in a pandas data frame,"df.drop_duplicates(cols='uniqueid', inplace=True)"
sort a list `your_list` of class objects by their values for the attribute `anniversary_score`,your_list.sort(key=operator.attrgetter('anniversary_score'))
is there a way to use phantomjs in python?,driver.quit()
how to call a system command with specified time limit in python?,"os.killpg(self.process.pid, signal.SIGTERM)"
sort objects in `articles` in descending order of counts of `likes`,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
"make a line plot with errorbars, `ebar`, from data `x, y, err` and set color of the errorbars to `y` (yellow)","ebar = plt.errorbar(x, y, yerr=err, ecolor='y')"
how to apply ceiling to pandas datetime,"df['date'] += np.array(-df['date'].dt.second % 60, dtype='<m8[s]')"
get the number of rows in table using sqlalchemy,rows = session.query(Congress).count()
doing math to a list in python,"[(3 * x) for x in [111, 222, 333]]"
get rows that have the same value across its columns in pandas,"df[df.apply(lambda x: min(x) == max(x), 1)]"
how to extract elements from a list in python?,"[a[i] for i in (1, 2, 5)]"
what is the proper way to print a nested list with the highest value in python,"print(max(x, key=sum))"
use groupby in pandas to count things in one column in comparison to another,"df.pivot_table(index='Event', columns='Status', aggfunc=len, fill_value=0)"
get path from a module name,imp.find_module('os')[1]
how to use opencv (python) to blur faces?,"cv2.rectangle(image, (x, y), (x + w, y + h), (255, 255, 0), 5)"
"how to join two sets in one line without using ""|""","set([1, 2, 3]) | set([4, 5, 6])"
how to get the resolution of a monitor in pygame?,"pygame.display.set_mode((0, 0), pygame.FULLSCREEN)"
python pandas group by date using datetime data,df = df.groupby([df['Date_Time'].dt.date]).mean()
switch every pair of characters in a string,"print(''.join(''.join(i) for i in zip(a2, a1)) + a[-1] if len(a) % 2 else '')"
numeric sort in python,list1.sort(key=int)
how do i use a regular expression to match a name?,"re.match('[a-zA-Z][\\w-]*$', '!A_B')"
how to configure logging in python,logging.info('Doing something')
terminate a python script from another python script,os.getpid()
how sending and receiving works in python sockets?,"socket.socket(socket.AF_INET, socket.SOCK_DGRAM)"
format string with dict `{'5': 'you'}` with integer keys,'hello there %(5)s' % {'5': 'you'}
invert colors when plotting a png file using matplotlib,"plt.imshow(cv2.cvtColor(cube, cv2.COLOR_BGR2RGB))"
how to change the order of dataframe columns?,"df = df[['mean', '0', '1', '2', '3']]"
proper way to do row correlations in a pandas dataframe,"df_example.iloc[([1, 4]), :-1].T.corr()"
"remove the punctuation '!', '.', ':' from a string `asking`","out = ''.join(c for c in asking if c not in ('!', '.', ':'))"
check if type of a variable `s` is string,"isinstance(s, str)"
numpy: how to select rows based on a bunch of criteria,"a[np.in1d(a[:, (1)], b)]"
how can i lookup an attribute in any scope by name?,"getattr(__builtins__, 'range')"
how to replace the nth element of multi dimension lists in python?,[list(e) for e in zip(*[fl[i::2] for i in range(2)])]
python list initialization using multiple range statements,"list(range(1, 6)) + list(range(15, 20))"
summing elements in a list,sum(your_list)
how does one convert a .net tick to a python datetime?,"datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=ticks / 10)"
combining two series into a dataframe in pandas,"pd.concat([s1, s2], axis=1).reset_index()"
sort a list of lists `l` by index 2 of the inner list,"sorted(L, key=itemgetter(2))"
removing control characters from a string `s`,return ''.join(ch for ch in s if unicodedata.category(ch)[0] != 'C')
"how do i iterate over a python dictionary, ordered by values?","sorted(list(dictionary.items()), key=lambda x: x[1])"
python list comprehension double for,[x.lower() for x in words]
using a global flag for python regexp compile,"""""""(?s)Your.*regex.*here"""""""
is there a function for converting ip address to decimal number in python?,"print(struct.unpack('!I', socket.inet_aton('127.0.0.1'))[0])"
"in python, how to list all characters matched by posix extended regex `[:space:]`?","re.findall('\\s', chrs, re.UNICODE)"