text stringlengths 4 1.08k |
|---|
how to safely remove elements from a list in python,[x for x in a if x <= 1 or x >= 4] |
how to pass parameters to a build in sublime text 3?,"{'cmd': ['python', '$file', 'arg1', 'arg2']}" |
updating a matplotlib bar graph?,plt.show() |
how to get user email with python social auth with facebook and save it,SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] |
finding a eulerian tour,"graph = [(1, 2), (2, 3), (3, 1), (3, 4), (4, 3)]" |
print bold text 'hello',print('\x1b[1m' + 'Hello') |
what is the definition of mean in pandas data frame?,df['col'] = df['col'].map(int) |
get all environment variables,os.environ |
print float `a` with two decimal points,print(('%.2f' % a)) |
how to print the function name as a string in python from inside that function,print(applejuice.__name__) |
create a list of tuples with the values of keys 'name' and 'age' from each dictionary `d` in the list `thisismylist`,"[(d['Name'], d['Age']) for d in thisismylist]" |
averages of slices on a 1d nparray: how to make it more numpy-thonic?,np.cumsum(a[::-1])[::-1] - np.cumsum(a) |
how to execute select * like statement with a placeholder in sqlite?,"cursor.execute('SELECT * FROM posts WHERE tags LIKE ?', ('%{}%'.format(tag),))" |
is it possible to call a python module from objc?,print(urllib.request.urlopen('http://google.com').read()) |
split string 'happy_hats_for_cats' using string '_for_',"re.split('_for_', 'happy_hats_for_cats')" |
how do i autosize text in matplotlib python?,plt.show() |
reverse y-axis in pyplot,plt.gca().invert_yaxis() |
sorting a list in python,"sorted(words, key=lambda x: 'a' + x if x.startswith('s') else 'b' + x)" |
access the class variable `a_string` from a class object `test`,"getattr(test, a_string)" |
python - finding index of first non-empty item in a list,"next((i for i, j in enumerate(lst) if j == 2), 42)" |
how do i make this simple list comprehension?,"[sum(nums[i:i + 3]) for i in range(0, len(nums), 3)]" |
how to set the labels size on a pie chart in python,plt.show() |
how to build html5lib parser to deal with a mixture of xml and html tags,"xml_soup = BeautifulSoup(xml_object, 'xml')" |
unboundlocalerror: local variable 'x' referenced before assignment. proper use of tsplot in seaborn package for a dataframe?,"sns.tsplot(melted, time=0, unit='variable', value='value')" |
convert snmp octet string to human readable date format,"datetime.datetime(*struct.unpack('>HBBBBBB', s))" |
pandas reset index on series to remove multiindex,s.reset_index(0).reset_index(drop=True) |
how to make a numpy array from an array of arrays?,np.vstack(a) |
"sort a list of dictionaries `mylist` by keys ""weight"" and ""factor""","mylist.sort(key=operator.itemgetter('weight', 'factor'))" |
check whether a file `fname` exists,os.path.isfile(fname) |
how do i abort the execution of a python script?,sys.exit(0) |
get values from matplotlib axessubplot,plt.show() |
disable output of root logger,logging.getLogger().setLevel(logging.INFO) |
remove duplicates from list `myset`,mynewlist = list(myset) |
norm along row in pandas,np.sqrt(np.square(df).sum(axis=1)) |
accessing function arguments from decorator,MyClass().say('hello') |
how to group by multiple keys in spark?,"[('id1, pd1', '5.0, 7.5, 8.1'), ('id2, pd2', '6.0')]" |
smallest sum of difference between elements in two lists,"sum(abs(x - y) for x, y in zip(sorted(xs), sorted(ys)))" |
generating all combinations of a list in python,"print(list(itertools.combinations(a, i)))" |
how to plot bar graphs with same x coordinates side by side,plt.show() |
"a simple website with python using simplehttpserver and socketserver, how to only display the html file and not the whole directory?",server.serve_forever() |
how to make a histogram from a list of strings in python?,df.plot(kind='bar') |
how to append in a json file in python?,"json.dump(data, f)" |
how to get a function name as a string in python?,my_function.__name__ |
how do i convert a unicode to a string at the python level?,""""""""""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')" |
python: find out whether a list of integers is coherent,"return my_list == list(range(my_list[0], my_list[-1] + 1))" |
get current time,datetime.datetime.time(datetime.datetime.now()) |
python - find the greatest number in a set of numbers,"print(max(1, 2, 3))" |
how to get data from r to pandas,"pd.DataFrame(data=[i[0] for i in x], columns=['X'])" |
how to convert a python dict object to a java equivalent object?,"map.put(key, new_value)" |
how do you get default headers in a urllib2 request?,response = opener.open('http://www.google.com/') |
how to display the first few characters of a string in python?,a_string = 'This is a string' |
element-wise minimum of multiple vectors in numpy,"np.amin(V, axis=0)" |
"escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))" |
how to convert numpy datetime64 into datetime,datetime.datetime.utcfromtimestamp(x.astype('O') / 1000000000.0) |
how to make arrow that loops in matplotlib?,plt.show() |
python string interpolation with tuple slices?,"'Dealer has %s showing.' % (self.dealer[0], self.dealer[1])" |
join list of lists in python,print(list(itertools.chain.from_iterable(a))) |
pymongo: how to use $or operator to an column that is an array?,"collection1.find({'albums': {'$in': [3, 7, 8]}})" |
matching and combining multiple 2d lists in python,"[['00f7e0b88577106a', '2', 'hdisk37']]" |
how to make a python http request with post data and cookie?,"print(requests.get(url, data=data, cookies=cookies).text)" |
converting utc time string to datetime object,"datetime.strptime('2012-03-01T10:00:00Z', '%Y-%m-%dT%H:%M:%SZ')" |
median of pandas dataframe,df['dist'].median() |
how to throw an error window in python in windows,"ctypes.windll.user32.MessageBoxW(0, 'Error', 'Error', 0)" |
remove the space between subplots in matplotlib.pyplot,"fig.subplots_adjust(wspace=0, hspace=0)" |
sorting numpy array on multiple columns in python,df.sort(['date']) |
why do i get a spurious ']' character in syslog messages with python's sysloghandler on os x?,logger.error('Test ABC') |
python write (iphone) emoji to a file,f.write(e8) |
how to construct a set out of list items in python?,"lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]" |
"remove newline in string ""hello\n\n\n"" on the right side",'Hello\n\n\n'.rstrip('\n') |
"create list by splitting string `mystring` using "","" as delimiter","mystring.split(',')" |
reverse a string `s`,''.join(reversed(s)) |
add string `-` in `4th` position of a string `s`,s[:4] + '-' + s[4:] |
how do i send a post request as a json?,"response = urllib.request.urlopen(req, json.dumps(data))" |
write a regex statement to match 'lol' to 'lolllll'.,"re.sub('l+', 'l', 'lollll')" |
"split a string `string` by multiple separators `,` and `;`","[t.strip() for s in string.split(',') for t in s.split(';')]" |
string to list conversion in python,"[x.strip() for x in s.split(',')]" |
how to check if a dictionary is in another dictionary in python,set(L[0].f.items()).issubset(set(a3.f.items())) |
how to get multiple parameters with same name from a url in pylons?,request.params.getall('c') |
using django orm get_or_create with multiple databases,MyModel.objects.using('my_non_default_database').get_or_create(name='Bob') |
sorting by multiple conditions in python,table.sort(key=lambda t: t.points) |
"python: find the min, max value in a list of tuples","map(max, zip(*alist))" |
remove letters from string `example_line` if the letter exist in list `bad_chars`,""""""""""""".join(dropwhile(lambda x: x in bad_chars, example_line[::-1]))[::-1]" |
accessing relative path in python,os.path.expanduser(path) |
how to combine dictionary + list to form one sorted list,"dict((item[0], (item[1], z[item[0]])) for item in l)" |
python: add a character to each item in a list,"['ha', 'cb', 'dc', 'sd']" |
load json file 'sample.json' with utf-8 bom header,json.loads(open('sample.json').read().decode('utf-8-sig')) |
best way to structure a tkinter application,"self.main.pack(side='right', fill='both', expand=True)" |
representing a multi-select field for weekdays in a django model,weekdays = models.PositiveIntegerField(choices=WEEKDAYS) |
"in python, how do i remove from a list any element containing certain kinds of characters?","regex = re.compile('\\b[A-Z]{3,}\\b')" |
how to convert unicode accented characters to pure ascii without accents?,"unicodedata.normalize('NFD', myfoo).encode('ascii', 'ignore')" |
flatten list of tuples `a`,list(chain.from_iterable(a)) |
create a dictionary `list_dict` containing each tuple in list `tuple_list` as values and the tuple's first element as the corresponding key,list_dict = {t[0]: t for t in tuple_list} |
how to use else inside python's timeit,"timeit.timeit(stmt=""'hi' if True else 'bye'"")" |
python extract pattern matches,p = re.compile('name (.*?) is valid') |
python: converting radians to degrees,"round(math.degrees(math.asin(0.5)), 2)" |
find all digits between a character in python,"print(re.findall('\\d+', re.findall('\xab([\\s\\S]*?)\xbb', text)[0]))" |
"in python 2.5, how do i kill a subprocess?","os.kill(process.pid, signal.SIGKILL)" |
get seconds since midnight in python,datetime.now() - datetime.now() |
remove multiple spaces in a string `foo`,""""""" """""".join(foo.split())" |
python regression with matrices,"np.polyfit(X, Y, 1)" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.