code_tokens
stringlengths 60
3.94k
| label
int64 0
1
| doc
stringlengths 16
98
| docstring_tokens
stringlengths 0
1.41k
| idx
stringlengths 13
17
| code
stringlengths 87
6.4k
|
---|---|---|---|---|---|
def to_dataframe ( products ) : try : import pandas as pd except ImportError : raise ImportError ( "to_dataframe requires the optional dependency Pandas." ) return pd . DataFrame . from_dict ( products , orient = 'index' )
| 1 |
python query result into df
|
Return the products from a query response as a Pandas DataFrame with the values in their appropriate Python types .
|
cosqa-train-13800
|
def to_dataframe(products):
"""Return the products from a query response as a Pandas DataFrame
with the values in their appropriate Python types.
"""
try:
import pandas as pd
except ImportError:
raise ImportError("to_dataframe requires the optional dependency Pandas.")
return pd.DataFrame.from_dict(products, orient='index')
|
def get_closest_index ( myList , myNumber ) : closest_values_index = _np . where ( self . time == take_closest ( myList , myNumber ) ) [ 0 ] [ 0 ] return closest_values_index
| 1 |
how to identify the closest match in a list python
|
Assumes myList is sorted . Returns closest value to myNumber . If two numbers are equally close return the smallest number .
|
cosqa-train-13801
|
def get_closest_index(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
Parameters
----------
myList : array
The list in which to find the closest value to myNumber
myNumber : float
The number to find the closest to in MyList
Returns
-------
closest_values_index : int
The index in the array of the number closest to myNumber in myList
"""
closest_values_index = _np.where(self.time == take_closest(myList, myNumber))[0][0]
return closest_values_index
|
def PopTask ( self ) : try : _ , task = heapq . heappop ( self . _heap ) except IndexError : return None self . _task_identifiers . remove ( task . identifier ) return task
| 0 |
python queue get pop
|
Retrieves and removes the first task from the heap .
|
cosqa-train-13802
|
def PopTask(self):
"""Retrieves and removes the first task from the heap.
Returns:
Task: the task or None if the heap is empty.
"""
try:
_, task = heapq.heappop(self._heap)
except IndexError:
return None
self._task_identifiers.remove(task.identifier)
return task
|
def impute_data ( self , x ) : imp = Imputer ( missing_values = 'NaN' , strategy = 'mean' , axis = 0 ) return imp . fit_transform ( x )
| 1 |
how to impute missing data in python
|
Imputes data set containing Nan values
|
cosqa-train-13803
|
def impute_data(self,x):
"""Imputes data set containing Nan values"""
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
return imp.fit_transform(x)
|
def display_pil_image ( im ) : from IPython . core import display b = BytesIO ( ) im . save ( b , format = 'png' ) data = b . getvalue ( ) ip_img = display . Image ( data = data , format = 'png' , embed = True ) return ip_img . _repr_png_ ( )
| 1 |
python quickest way to display image
|
Displayhook function for PIL Images rendered as PNG .
|
cosqa-train-13804
|
def display_pil_image(im):
"""Displayhook function for PIL Images, rendered as PNG."""
from IPython.core import display
b = BytesIO()
im.save(b, format='png')
data = b.getvalue()
ip_img = display.Image(data=data, format='png', embed=True)
return ip_img._repr_png_()
|
def impute_data ( self , x ) : imp = Imputer ( missing_values = 'NaN' , strategy = 'mean' , axis = 0 ) return imp . fit_transform ( x )
| 1 |
how to impute missing values in python
|
Imputes data set containing Nan values
|
cosqa-train-13805
|
def impute_data(self,x):
"""Imputes data set containing Nan values"""
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
return imp.fit_transform(x)
|
def quote ( self , s ) : if six . PY2 : from pipes import quote else : from shlex import quote return quote ( s )
| 1 |
python quote in a string
|
Return a shell - escaped version of the string s .
|
cosqa-train-13806
|
def quote(self, s):
"""Return a shell-escaped version of the string s."""
if six.PY2:
from pipes import quote
else:
from shlex import quote
return quote(s)
|
def setup_path ( ) : import os . path import sys if sys . argv [ 0 ] : top_dir = os . path . dirname ( os . path . abspath ( sys . argv [ 0 ] ) ) sys . path = [ os . path . join ( top_dir , "src" ) ] + sys . path pass return
| 1 |
how to include def files in python
|
Sets up the python include paths to include src
|
cosqa-train-13807
|
def setup_path():
"""Sets up the python include paths to include src"""
import os.path; import sys
if sys.argv[0]:
top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path = [os.path.join(top_dir, "src")] + sys.path
pass
return
|
def LinSpace ( start , stop , num ) : return np . linspace ( start , stop , num = num , dtype = np . float32 ) ,
| 0 |
python range multiply a constant
|
Linspace op .
|
cosqa-train-13808
|
def LinSpace(start, stop, num):
"""
Linspace op.
"""
return np.linspace(start, stop, num=num, dtype=np.float32),
|
def adjust_bounding_box ( bbox ) : for i in range ( 0 , 4 ) : if i in bounding_box : bbox [ i ] = bounding_box [ i ] else : bbox [ i ] += delta_bounding_box [ i ] return bbox
| 0 |
how to increase boxplot width python
|
Adjust the bounding box as specified by user . Returns the adjusted bounding box .
|
cosqa-train-13809
|
def adjust_bounding_box(bbox):
"""Adjust the bounding box as specified by user.
Returns the adjusted bounding box.
- bbox: Bounding box computed from the canvas drawings.
It must be a four-tuple of numbers.
"""
for i in range(0, 4):
if i in bounding_box:
bbox[i] = bounding_box[i]
else:
bbox[i] += delta_bounding_box[i]
return bbox
|
def LinSpace ( start , stop , num ) : return np . linspace ( start , stop , num = num , dtype = np . float32 ) ,
| 1 |
python range of int with left fill
|
Linspace op .
|
cosqa-train-13810
|
def LinSpace(start, stop, num):
"""
Linspace op.
"""
return np.linspace(start, stop, num=num, dtype=np.float32),
|
def _digits ( minval , maxval ) : if minval == maxval : return 3 else : return min ( 10 , max ( 2 , int ( 1 + abs ( np . log10 ( maxval - minval ) ) ) ) )
| 1 |
how to input lowest and highest range on python
|
Digits needed to comforatbly display values in [ minval maxval ]
|
cosqa-train-13811
|
def _digits(minval, maxval):
"""Digits needed to comforatbly display values in [minval, maxval]"""
if minval == maxval:
return 3
else:
return min(10, max(2, int(1 + abs(np.log10(maxval - minval)))))
|
def iter_finds ( regex_obj , s ) : if isinstance ( regex_obj , str ) : for m in re . finditer ( regex_obj , s ) : yield m . group ( ) else : for m in regex_obj . finditer ( s ) : yield m . group ( )
| 1 |
python re findall lazy iterator
|
Generate all matches found within a string for a regex and yield each match as a string
|
cosqa-train-13812
|
def iter_finds(regex_obj, s):
"""Generate all matches found within a string for a regex and yield each match as a string"""
if isinstance(regex_obj, str):
for m in re.finditer(regex_obj, s):
yield m.group()
else:
for m in regex_obj.finditer(s):
yield m.group()
|
def lambda_tuple_converter ( func ) : if func is not None and func . __code__ . co_argcount == 1 : return lambda * args : func ( args [ 0 ] if len ( args ) == 1 else args ) else : return func
| 1 |
how to input tuples into a function python
|
Converts a Python 2 function as lambda ( x y ) : x + y In the Python 3 format : lambda x y : x + y
|
cosqa-train-13813
|
def lambda_tuple_converter(func):
"""
Converts a Python 2 function as
lambda (x,y): x + y
In the Python 3 format:
lambda x,y : x + y
"""
if func is not None and func.__code__.co_argcount == 1:
return lambda *args: func(args[0] if len(args) == 1 else args)
else:
return func
|
def replace ( self , text ) : for ( pattern , repl ) in self . patterns : text = re . subn ( pattern , repl , text ) [ 0 ] return text
| 1 |
python re sub multiple replacements
|
Do j / v replacement
|
cosqa-train-13814
|
def replace(self, text):
"""Do j/v replacement"""
for (pattern, repl) in self.patterns:
text = re.subn(pattern, repl, text)[0]
return text
|
def utcfromtimestamp ( cls , timestamp ) : obj = datetime . datetime . utcfromtimestamp ( timestamp ) obj = pytz . utc . localize ( obj ) return cls ( obj )
| 1 |
how to instantiate a time object from a timestamp in python
|
Returns a datetime object of a given timestamp ( in UTC ) .
|
cosqa-train-13815
|
def utcfromtimestamp(cls, timestamp):
"""Returns a datetime object of a given timestamp (in UTC)."""
obj = datetime.datetime.utcfromtimestamp(timestamp)
obj = pytz.utc.localize(obj)
return cls(obj)
|
def getlines ( filename , module_globals = None ) : if filename in cache : return cache [ filename ] [ 2 ] try : return updatecache ( filename , module_globals ) except MemoryError : clearcache ( ) return [ ]
| 1 |
python read and cache file in memory
|
Get the lines for a file from the cache . Update the cache if it doesn t contain an entry for this file already .
|
cosqa-train-13816
|
def getlines(filename, module_globals=None):
"""Get the lines for a file from the cache.
Update the cache if it doesn't contain an entry for this file already."""
if filename in cache:
return cache[filename][2]
try:
return updatecache(filename, module_globals)
except MemoryError:
clearcache()
return []
|
def new_from_list ( cls , items , * * kwargs ) : obj = cls ( * * kwargs ) for item in items : obj . append ( ListItem ( item ) ) return obj
| 1 |
how to instantiate an object for each item in a list in python
|
Populates the ListView with a string list .
|
cosqa-train-13817
|
def new_from_list(cls, items, **kwargs):
"""Populates the ListView with a string list.
Args:
items (list): list of strings to fill the widget with.
"""
obj = cls(**kwargs)
for item in items:
obj.append(ListItem(item))
return obj
|
def read_credentials ( fname ) : with open ( fname , 'r' ) as f : username = f . readline ( ) . strip ( '\n' ) password = f . readline ( ) . strip ( '\n' ) return username , password
| 0 |
python read credentials from text file
|
read a simple text file from a private location to get username and password
|
cosqa-train-13818
|
def read_credentials(fname):
"""
read a simple text file from a private location to get
username and password
"""
with open(fname, 'r') as f:
username = f.readline().strip('\n')
password = f.readline().strip('\n')
return username, password
|
def __iter__ ( self ) : for value , count in self . counts ( ) : for _ in range ( count ) : yield value
| 1 |
how to iterate every other element in python
|
Iterate through all elements .
|
cosqa-train-13819
|
def __iter__(self):
"""Iterate through all elements.
Multiple copies will be returned if they exist.
"""
for value, count in self.counts():
for _ in range(count):
yield value
|
def smartread ( path ) : with open ( path , "rb" ) as f : content = f . read ( ) result = chardet . detect ( content ) return content . decode ( result [ "encoding" ] )
| 1 |
python read file guess encoding example chardet
|
Read text from file automatically detect encoding . chardet required .
|
cosqa-train-13820
|
def smartread(path):
"""Read text from file, automatically detect encoding. ``chardet`` required.
"""
with open(path, "rb") as f:
content = f.read()
result = chardet.detect(content)
return content.decode(result["encoding"])
|
def _sub_patterns ( patterns , text ) : for pattern , repl in patterns : text = re . sub ( pattern , repl , text ) return text
| 1 |
how to iterate through replace python
|
Apply re . sub to bunch of ( pattern repl )
|
cosqa-train-13821
|
def _sub_patterns(patterns, text):
"""
Apply re.sub to bunch of (pattern, repl)
"""
for pattern, repl in patterns:
text = re.sub(pattern, repl, text)
return text
|
def _read_preference_for ( self , session ) : # Override this operation's read preference with the transaction's. if session : return session . _txn_read_preference ( ) or self . __read_preference return self . __read_preference
| 1 |
python read preference shard
|
Read only access to the read preference of this instance or session .
|
cosqa-train-13822
|
def _read_preference_for(self, session):
"""Read only access to the read preference of this instance or session.
"""
# Override this operation's read preference with the transaction's.
if session:
return session._txn_read_preference() or self.__read_preference
return self.__read_preference
|
def walk_tree ( root ) : yield root for child in root . children : for el in walk_tree ( child ) : yield el
| 0 |
how to iterate through tree nodes in python
|
Pre - order depth - first
|
cosqa-train-13823
|
def walk_tree(root):
"""Pre-order depth-first"""
yield root
for child in root.children:
for el in walk_tree(child):
yield el
|
def get_iter_string_reader ( stdin ) : bufsize = 1024 iter_str = ( stdin [ i : i + bufsize ] for i in range ( 0 , len ( stdin ) , bufsize ) ) return get_iter_chunk_reader ( iter_str )
| 1 |
python read stream of input
|
return an iterator that returns a chunk of a string every time it is called . notice that even though bufsize_type might be line buffered we re not doing any line buffering here . that s because our StreamBufferer handles all buffering . we just need to return a reasonable - sized chunk .
|
cosqa-train-13824
|
def get_iter_string_reader(stdin):
""" return an iterator that returns a chunk of a string every time it is
called. notice that even though bufsize_type might be line buffered, we're
not doing any line buffering here. that's because our StreamBufferer
handles all buffering. we just need to return a reasonable-sized chunk. """
bufsize = 1024
iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize))
return get_iter_chunk_reader(iter_str)
|
def head ( filename , n = 10 ) : with freader ( filename ) as fr : for _ in range ( n ) : print ( fr . readline ( ) . strip ( ) )
| 1 |
python read the first 10 lines in a file and print each line
|
prints the top n lines of a file
|
cosqa-train-13825
|
def head(filename, n=10):
""" prints the top `n` lines of a file """
with freader(filename) as fr:
for _ in range(n):
print(fr.readline().strip())
|
def isInteractive ( ) : if sys . stdout . isatty ( ) and os . name != 'nt' : #Hopefully everything but ms supports '\r' try : import threading except ImportError : return False else : return True else : return False
| 0 |
how to keep interactive mode running not script for python
|
A basic check of if the program is running in interactive mode
|
cosqa-train-13826
|
def isInteractive():
"""
A basic check of if the program is running in interactive mode
"""
if sys.stdout.isatty() and os.name != 'nt':
#Hopefully everything but ms supports '\r'
try:
import threading
except ImportError:
return False
else:
return True
else:
return False
|
def _read_date_from_string ( str1 ) : full_date = [ int ( x ) for x in str1 . split ( '/' ) ] return datetime . date ( full_date [ 0 ] , full_date [ 1 ] , full_date [ 2 ] )
| 1 |
python read xx/xx/xxxx datetime from string
|
Reads the date from a string in the format YYYY / MM / DD and returns : class : datetime . date
|
cosqa-train-13827
|
def _read_date_from_string(str1):
"""
Reads the date from a string in the format YYYY/MM/DD and returns
:class: datetime.date
"""
full_date = [int(x) for x in str1.split('/')]
return datetime.date(full_date[0], full_date[1], full_date[2])
|
def process_kill ( pid , sig = None ) : sig = sig or signal . SIGTERM os . kill ( pid , sig )
| 1 |
how to kill process daemon in python from the same function
|
Send signal to process .
|
cosqa-train-13828
|
def process_kill(pid, sig=None):
"""Send signal to process.
"""
sig = sig or signal.SIGTERM
os.kill(pid, sig)
|
def ReadManyFromPath ( filepath ) : with io . open ( filepath , mode = "r" , encoding = "utf-8" ) as filedesc : return ReadManyFromFile ( filedesc )
| 1 |
python read yaml file deserialize
|
Reads a Python object stored in a specified YAML file .
|
cosqa-train-13829
|
def ReadManyFromPath(filepath):
"""Reads a Python object stored in a specified YAML file.
Args:
filepath: A filepath to the YAML file.
Returns:
A Python data structure corresponding to the YAML in the given file.
"""
with io.open(filepath, mode="r", encoding="utf-8") as filedesc:
return ReadManyFromFile(filedesc)
|
def mouse_get_pos ( ) : p = POINT ( ) AUTO_IT . AU3_MouseGetPos ( ctypes . byref ( p ) ) return p . x , p . y
| 1 |
how to know mouse pointer position in python
|
cosqa-train-13830
|
def mouse_get_pos():
"""
:return:
"""
p = POINT()
AUTO_IT.AU3_MouseGetPos(ctypes.byref(p))
return p.x, p.y
|
|
def memory_usage ( method ) : def wrapper ( * args , * * kwargs ) : logging . info ( 'Memory before method %s is %s.' , method . __name__ , runtime . memory_usage ( ) . current ( ) ) result = method ( * args , * * kwargs ) logging . info ( 'Memory after method %s is %s' , method . __name__ , runtime . memory_usage ( ) . current ( ) ) return result return wrapper
| 1 |
python record function runtime
|
Log memory usage before and after a method .
|
cosqa-train-13831
|
def memory_usage(method):
"""Log memory usage before and after a method."""
def wrapper(*args, **kwargs):
logging.info('Memory before method %s is %s.',
method.__name__, runtime.memory_usage().current())
result = method(*args, **kwargs)
logging.info('Memory after method %s is %s',
method.__name__, runtime.memory_usage().current())
return result
return wrapper
|
def getpackagepath ( ) : moduleDirectory = os . path . dirname ( __file__ ) packagePath = os . path . dirname ( __file__ ) + "/../" return packagePath
| 1 |
how to know path of python
|
* Get the root path for this python package - used in unit testing code *
|
cosqa-train-13832
|
def getpackagepath():
"""
*Get the root path for this python package - used in unit testing code*
"""
moduleDirectory = os.path.dirname(__file__)
packagePath = os.path.dirname(__file__) + "/../"
return packagePath
|
def tuplize ( nested ) : if isinstance ( nested , str ) : return nested try : return tuple ( map ( tuplize , nested ) ) except TypeError : return nested
| 1 |
python recursion on nested list to tuple
|
Recursively converts iterables into tuples .
|
cosqa-train-13833
|
def tuplize(nested):
"""Recursively converts iterables into tuples.
Args:
nested: A nested structure of items and iterables.
Returns:
A nested structure of items and tuples.
"""
if isinstance(nested, str):
return nested
try:
return tuple(map(tuplize, nested))
except TypeError:
return nested
|
def _get_column_types ( self , data ) : columns = list ( zip_longest ( * data ) ) return [ self . _get_column_type ( column ) for column in columns ]
| 1 |
how to know the data type for each column python
|
Get a list of the data types for each column in * data * .
|
cosqa-train-13834
|
def _get_column_types(self, data):
"""Get a list of the data types for each column in *data*."""
columns = list(zip_longest(*data))
return [self._get_column_type(column) for column in columns]
|
def redirect_output ( fileobj ) : old = sys . stdout sys . stdout = fileobj try : yield fileobj finally : sys . stdout = old
| 1 |
python redirect stdout on screen and to file
|
Redirect standard out to file .
|
cosqa-train-13835
|
def redirect_output(fileobj):
"""Redirect standard out to file."""
old = sys.stdout
sys.stdout = fileobj
try:
yield fileobj
finally:
sys.stdout = old
|
def _GetProxies ( self ) : # Detect proxies from the OS environment. result = client_utils . FindProxies ( ) # Also try to connect directly if all proxies fail. result . append ( "" ) # Also try all proxies configured in the config system. result . extend ( config . CONFIG [ "Client.proxy_servers" ] ) return result
| 1 |
how to know the proxies in a browser python
|
Gather a list of proxies to use .
|
cosqa-train-13836
|
def _GetProxies(self):
"""Gather a list of proxies to use."""
# Detect proxies from the OS environment.
result = client_utils.FindProxies()
# Also try to connect directly if all proxies fail.
result.append("")
# Also try all proxies configured in the config system.
result.extend(config.CONFIG["Client.proxy_servers"])
return result
|
def redirect_stdout ( new_stdout ) : old_stdout , sys . stdout = sys . stdout , new_stdout try : yield None finally : sys . stdout = old_stdout
| 1 |
python redirect stdout to 2 places
|
Redirect the stdout
|
cosqa-train-13837
|
def redirect_stdout(new_stdout):
"""Redirect the stdout
Args:
new_stdout (io.StringIO): New stdout to use instead
"""
old_stdout, sys.stdout = sys.stdout, new_stdout
try:
yield None
finally:
sys.stdout = old_stdout
|
def bytesize ( arr ) : byte_size = np . prod ( arr . shape ) * np . dtype ( arr . dtype ) . itemsize return byte_size
| 0 |
how to know the size of numpy array in python
|
Returns the memory byte size of a Numpy array as an integer .
|
cosqa-train-13838
|
def bytesize(arr):
"""
Returns the memory byte size of a Numpy array as an integer.
"""
byte_size = np.prod(arr.shape) * np.dtype(arr.dtype).itemsize
return byte_size
|
def get ( self , key ) : res = self . connection . get ( key ) print ( res ) return res
| 0 |
python redis get all values
|
get a set of keys from redis
|
cosqa-train-13839
|
def get(self, key):
""" get a set of keys from redis """
res = self.connection.get(key)
print(res)
return res
|
def _crop_list_to_size ( l , size ) : for x in range ( size - len ( l ) ) : l . append ( False ) for x in range ( len ( l ) - size ) : l . pop ( ) return l
| 1 |
how to limit size of a list in python
|
Make a list a certain size
|
cosqa-train-13840
|
def _crop_list_to_size(l, size):
"""Make a list a certain size"""
for x in range(size - len(l)):
l.append(False)
for x in range(len(l) - size):
l.pop()
return l
|
def connect ( self ) : self . client = redis . Redis ( host = self . host , port = self . port , password = self . password )
| 1 |
python redis pubsub has no data
|
Connects to publisher
|
cosqa-train-13841
|
def connect(self):
"""
Connects to publisher
"""
self.client = redis.Redis(
host=self.host, port=self.port, password=self.password)
|
def read_raw ( data_path ) : with open ( data_path , 'rb' ) as f : data = pickle . load ( f ) return data
| 1 |
how to load a file with pickle python
|
Parameters ---------- data_path : str
|
cosqa-train-13842
|
def read_raw(data_path):
"""
Parameters
----------
data_path : str
"""
with open(data_path, 'rb') as f:
data = pickle.load(f)
return data
|
def _read_group_h5 ( filename , groupname ) : with h5py . File ( filename , 'r' ) as h5f : data = h5f [ groupname ] [ ( ) ] return data
| 1 |
how to load h5 data sets in python
|
Return group content .
|
cosqa-train-13843
|
def _read_group_h5(filename, groupname):
"""Return group content.
Args:
filename (:class:`pathlib.Path`): path of hdf5 file.
groupname (str): name of group to read.
Returns:
:class:`numpy.array`: content of group.
"""
with h5py.File(filename, 'r') as h5f:
data = h5f[groupname][()]
return data
|
def match_files ( files , pattern : Pattern ) : for name in files : if re . match ( pattern , name ) : yield name
| 1 |
python regex on folder of filenames
|
Yields file name if matches a regular expression pattern .
|
cosqa-train-13844
|
def match_files(files, pattern: Pattern):
"""Yields file name if matches a regular expression pattern."""
for name in files:
if re.match(pattern, name):
yield name
|
def _load_ngram ( name ) : module = importlib . import_module ( 'lantern.analysis.english_ngrams.{}' . format ( name ) ) return getattr ( module , name )
| 0 |
how to load npy in python
|
Dynamically import the python module with the ngram defined as a dictionary . Since bigger ngrams are large files its wasteful to always statically import them if they re not used .
|
cosqa-train-13845
|
def _load_ngram(name):
"""Dynamically import the python module with the ngram defined as a dictionary.
Since bigger ngrams are large files its wasteful to always statically import them if they're not used.
"""
module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name))
return getattr(module, name)
|
def load ( self , path ) : with io . open ( path , 'rb' ) as fin : self . weights = pickle . load ( fin )
| 1 |
how to load weight file in python
|
Load the pickled model weights .
|
cosqa-train-13846
|
def load(self, path):
"""Load the pickled model weights."""
with io.open(path, 'rb') as fin:
self.weights = pickle.load(fin)
|
def find_number ( regex , s ) : result = find_string ( regex , s ) if result is None : return None return int ( result )
| 1 |
python regex return value as int
|
Find a number using a given regular expression . If the string cannot be found returns None . The regex should contain one matching group as only the result of the first group is returned . The group should only contain numeric characters ( [ 0 - 9 ] + ) . s - The string to search . regex - A string containing the regular expression . Returns an integer or None .
|
cosqa-train-13847
|
def find_number(regex, s):
"""Find a number using a given regular expression.
If the string cannot be found, returns None.
The regex should contain one matching group,
as only the result of the first group is returned.
The group should only contain numeric characters ([0-9]+).
s - The string to search.
regex - A string containing the regular expression.
Returns an integer or None.
"""
result = find_string(regex, s)
if result is None:
return None
return int(result)
|
def getScriptLocation ( ) : location = os . path . abspath ( "./" ) if __file__ . rfind ( "/" ) != - 1 : location = __file__ [ : __file__ . rfind ( "/" ) ] return location
| 1 |
how to locate the location of a file in python
|
Helper function to get the location of a Python file .
|
cosqa-train-13848
|
def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location
|
def is_valid_regex ( string ) : try : re . compile ( string ) is_valid = True except re . error : is_valid = False return is_valid
| 1 |
python regular expression to check validity
|
Checks whether the re module can compile the given regular expression .
|
cosqa-train-13849
|
def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return is_valid
|
def info ( self , text ) : self . logger . info ( "{}{}" . format ( self . message_prefix , text ) )
| 1 |
how to log a variable without knowing its type in python
|
Ajout d un message de log de type INFO
|
cosqa-train-13850
|
def info(self, text):
""" Ajout d'un message de log de type INFO """
self.logger.info("{}{}".format(self.message_prefix, text))
|
def upcaseTokens ( s , l , t ) : return [ tt . upper ( ) for tt in map ( _ustr , t ) ]
| 0 |
how to lowercase all caps in a sentence python
|
Helper parse action to convert tokens to upper case .
|
cosqa-train-13851
|
def upcaseTokens(s,l,t):
"""Helper parse action to convert tokens to upper case."""
return [ tt.upper() for tt in map(_ustr,t) ]
|
def detach_index ( self , name ) : assert type ( name ) == str if name in self . _indexes : del self . _indexes [ name ]
| 1 |
python remove an index
|
cosqa-train-13852
|
def detach_index(self, name):
"""
:param name:
:return:
"""
assert type(name) == str
if name in self._indexes:
del self._indexes[name]
|
|
def price_rounding ( price , decimals = 2 ) : try : exponent = D ( '.' + decimals * '0' ) except InvalidOperation : # Currencies with no decimal places, ex. JPY, HUF exponent = D ( ) return price . quantize ( exponent , rounding = ROUND_UP )
| 1 |
how to maitain decimals in division python
|
Takes a decimal price and rounds to a number of decimal places
|
cosqa-train-13853
|
def price_rounding(price, decimals=2):
"""Takes a decimal price and rounds to a number of decimal places"""
try:
exponent = D('.' + decimals * '0')
except InvalidOperation:
# Currencies with no decimal places, ex. JPY, HUF
exponent = D()
return price.quantize(exponent, rounding=ROUND_UP)
|
def strip_spaces ( value , sep = None , join = True ) : value = value . strip ( ) value = [ v . strip ( ) for v in value . split ( sep ) ] join_sep = sep or ' ' return join_sep . join ( value ) if join else value
| 1 |
python remove commas and spaces in list
|
Cleans trailing whitespaces and replaces also multiple whitespaces with a single space .
|
cosqa-train-13854
|
def strip_spaces(value, sep=None, join=True):
"""Cleans trailing whitespaces and replaces also multiple whitespaces with a single space."""
value = value.strip()
value = [v.strip() for v in value.split(sep)]
join_sep = sep or ' '
return join_sep.join(value) if join else value
|
def gaussian_kernel ( gstd ) : Nc = np . ceil ( gstd * 3 ) * 2 + 1 x = np . linspace ( - ( Nc - 1 ) / 2 , ( Nc - 1 ) / 2 , Nc , endpoint = True ) g = np . exp ( - .5 * ( ( x / gstd ) ** 2 ) ) g = g / np . sum ( g ) return g
| 1 |
how to make a gaussian filter kernal python
|
Generate odd sized truncated Gaussian
|
cosqa-train-13855
|
def gaussian_kernel(gstd):
"""Generate odd sized truncated Gaussian
The generated filter kernel has a cutoff at $3\sigma$
and is normalized to sum to 1
Parameters
-------------
gstd : float
Standard deviation of filter
Returns
-------------
g : ndarray
Array with kernel coefficients
"""
Nc = np.ceil(gstd*3)*2+1
x = np.linspace(-(Nc-1)/2,(Nc-1)/2,Nc,endpoint=True)
g = np.exp(-.5*((x/gstd)**2))
g = g/np.sum(g)
return g
|
def _remove_dict_keys_with_value ( dict_ , val ) : return { k : v for k , v in dict_ . items ( ) if v is not val }
| 1 |
python remove condition apply to dict
|
Removes dict keys which have have self as value .
|
cosqa-train-13856
|
def _remove_dict_keys_with_value(dict_, val):
"""Removes `dict` keys which have have `self` as value."""
return {k: v for k, v in dict_.items() if v is not val}
|
def plot_dot_graph ( graph , filename = None ) : if not plot . pygraphviz_available : logger . error ( "Pygraphviz is not installed, cannot generate graph plot!" ) return if not plot . PIL_available : logger . error ( "PIL is not installed, cannot display graph plot!" ) return agraph = AGraph ( graph ) agraph . layout ( prog = 'dot' ) if filename is None : filename = tempfile . mktemp ( suffix = ".png" ) agraph . draw ( filename ) image = Image . open ( filename ) image . show ( )
| 1 |
how to make a graph in python without an addon
|
Plots a graph in graphviz dot notation .
|
cosqa-train-13857
|
def plot_dot_graph(graph, filename=None):
"""
Plots a graph in graphviz dot notation.
:param graph: the dot notation graph
:type graph: str
:param filename: the (optional) file to save the generated plot to. The extension determines the file format.
:type filename: str
"""
if not plot.pygraphviz_available:
logger.error("Pygraphviz is not installed, cannot generate graph plot!")
return
if not plot.PIL_available:
logger.error("PIL is not installed, cannot display graph plot!")
return
agraph = AGraph(graph)
agraph.layout(prog='dot')
if filename is None:
filename = tempfile.mktemp(suffix=".png")
agraph.draw(filename)
image = Image.open(filename)
image.show()
|
def unique ( list ) : unique = [ ] [ unique . append ( x ) for x in list if x not in unique ] return unique
| 0 |
python remove duplicated list
|
Returns a copy of the list without duplicates .
|
cosqa-train-13858
|
def unique(list):
""" Returns a copy of the list without duplicates.
"""
unique = []; [unique.append(x) for x in list if x not in unique]
return unique
|
def strip_html ( string , keep_tag_content = False ) : r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE return r . sub ( '' , string )
| 1 |
python remove html string
|
Remove html code contained into the given string .
|
cosqa-train-13859
|
def strip_html(string, keep_tag_content=False):
"""
Remove html code contained into the given string.
:param string: String to manipulate.
:type string: str
:param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default).
:type keep_tag_content: bool
:return: String with html removed.
:rtype: str
"""
r = HTML_TAG_ONLY_RE if keep_tag_content else HTML_RE
return r.sub('', string)
|
def get_plugin_icon ( self ) : path = osp . join ( self . PLUGIN_PATH , self . IMG_PATH ) return ima . icon ( 'pylint' , icon_path = path )
| 1 |
how to make a python execute using icon
|
Return widget icon
|
cosqa-train-13860
|
def get_plugin_icon(self):
"""Return widget icon"""
path = osp.join(self.PLUGIN_PATH, self.IMG_PATH)
return ima.icon('pylint', icon_path=path)
|
def remove_last_entry ( self ) : self . current_beat -= 1.0 / self . bar [ - 1 ] [ 1 ] self . bar = self . bar [ : - 1 ] return self . current_beat
| 0 |
python remove last element from array
|
Remove the last NoteContainer in the Bar .
|
cosqa-train-13861
|
def remove_last_entry(self):
"""Remove the last NoteContainer in the Bar."""
self.current_beat -= 1.0 / self.bar[-1][1]
self.bar = self.bar[:-1]
return self.current_beat
|
def generate_header ( headerfields , oldheader , group_by_field ) : fieldtypes = [ 'peptidefdr' , 'peptidepep' , 'nopsms' , 'proteindata' , 'precursorquant' , 'isoquant' ] return generate_general_header ( headerfields , fieldtypes , peptabledata . HEADER_PEPTIDE , oldheader , group_by_field )
| 1 |
how to make a python header
|
Returns a header as a list ready to write to TSV file
|
cosqa-train-13862
|
def generate_header(headerfields, oldheader, group_by_field):
"""Returns a header as a list, ready to write to TSV file"""
fieldtypes = ['peptidefdr', 'peptidepep', 'nopsms', 'proteindata',
'precursorquant', 'isoquant']
return generate_general_header(headerfields, fieldtypes,
peptabledata.HEADER_PEPTIDE, oldheader,
group_by_field)
|
def remove_last_entry ( self ) : self . current_beat -= 1.0 / self . bar [ - 1 ] [ 1 ] self . bar = self . bar [ : - 1 ] return self . current_beat
| 1 |
python remove last item in array
|
Remove the last NoteContainer in the Bar .
|
cosqa-train-13863
|
def remove_last_entry(self):
"""Remove the last NoteContainer in the Bar."""
self.current_beat -= 1.0 / self.bar[-1][1]
self.bar = self.bar[:-1]
return self.current_beat
|
def slugify ( string ) : string = re . sub ( '[^\w .-]' , '' , string ) string = string . replace ( " " , "-" ) return string
| 0 |
python remove letters from file name
|
Removes non - alpha characters and converts spaces to hyphens . Useful for making file names . Source : http : // stackoverflow . com / questions / 5574042 / string - slugification - in - python
|
cosqa-train-13864
|
def slugify(string):
"""
Removes non-alpha characters, and converts spaces to hyphens. Useful for making file names.
Source: http://stackoverflow.com/questions/5574042/string-slugification-in-python
"""
string = re.sub('[^\w .-]', '', string)
string = string.replace(" ", "-")
return string
|
def is_int ( value ) : if isinstance ( value , bool ) : return False try : int ( value ) return True except ( ValueError , TypeError ) : return False
| 1 |
how to make an integer a boolean python
|
Return True if value is an integer .
|
cosqa-train-13865
|
def is_int(value):
"""Return `True` if ``value`` is an integer."""
if isinstance(value, bool):
return False
try:
int(value)
return True
except (ValueError, TypeError):
return False
|
def ms_to_datetime ( ms ) : dt = datetime . datetime . utcfromtimestamp ( ms / 1000 ) return dt . replace ( microsecond = ( ms % 1000 ) * 1000 ) . replace ( tzinfo = pytz . utc )
| 1 |
python remove microsecond from datetime
|
Converts a millisecond accuracy timestamp to a datetime
|
cosqa-train-13866
|
def ms_to_datetime(ms):
"""
Converts a millisecond accuracy timestamp to a datetime
"""
dt = datetime.datetime.utcfromtimestamp(ms / 1000)
return dt.replace(microsecond=(ms % 1000) * 1000).replace(tzinfo=pytz.utc)
|
def _npiter ( arr ) : for a in np . nditer ( arr , flags = [ "refs_ok" ] ) : c = a . item ( ) if c is not None : yield c
| 1 |
how to make array iterable python
|
Wrapper for iterating numpy array
|
cosqa-train-13867
|
def _npiter(arr):
"""Wrapper for iterating numpy array"""
for a in np.nditer(arr, flags=["refs_ok"]):
c = a.item()
if c is not None:
yield c
|
def strip_accents ( string ) : return u'' . join ( ( character for character in unicodedata . normalize ( 'NFD' , string ) if unicodedata . category ( character ) != 'Mn' ) )
| 0 |
python remove non alphabet character
|
Strip all the accents from the string
|
cosqa-train-13868
|
def strip_accents(string):
"""
Strip all the accents from the string
"""
return u''.join(
(character for character in unicodedata.normalize('NFD', string)
if unicodedata.category(character) != 'Mn'))
|
def to_capitalized_camel_case ( snake_case_string ) : parts = snake_case_string . split ( '_' ) return '' . join ( [ i . title ( ) for i in parts ] )
| 1 |
how to make every capital letter lowercase python
|
Convert a string from snake case to camel case with the first letter capitalized . For example some_var would become SomeVar .
|
cosqa-train-13869
|
def to_capitalized_camel_case(snake_case_string):
"""
Convert a string from snake case to camel case with the first letter capitalized. For example, "some_var"
would become "SomeVar".
:param snake_case_string: Snake-cased string to convert to camel case.
:returns: Camel-cased version of snake_case_string.
"""
parts = snake_case_string.split('_')
return ''.join([i.title() for i in parts])
|
def drop_bad_characters ( text ) : # Strip all non-ascii and non-printable characters text = '' . join ( [ c for c in text if c in ALLOWED_CHARS ] ) return text
| 1 |
python remove non alphanumeric characters from string
|
Takes a text and drops all non - printable and non - ascii characters and also any whitespace characters that aren t space .
|
cosqa-train-13870
|
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
text = ''.join([c for c in text if c in ALLOWED_CHARS])
return text
|
def flatten ( lis ) : new_lis = [ ] for item in lis : if isinstance ( item , collections . Sequence ) and not isinstance ( item , basestring ) : new_lis . extend ( flatten ( item ) ) else : new_lis . append ( item ) return new_lis
| 0 |
python remove outer list from nested list
|
Given a list possibly nested to any level return it flattened .
|
cosqa-train-13871
|
def flatten(lis):
"""Given a list, possibly nested to any level, return it flattened."""
new_lis = []
for item in lis:
if isinstance(item, collections.Sequence) and not isinstance(item, basestring):
new_lis.extend(flatten(item))
else:
new_lis.append(item)
return new_lis
|
def paragraph ( separator = '\n\n' , wrap_start = '' , wrap_end = '' , html = False , sentences_quantity = 3 ) : return paragraphs ( quantity = 1 , separator = separator , wrap_start = wrap_start , wrap_end = wrap_end , html = html , sentences_quantity = sentences_quantity )
| 1 |
how to make paragraphs in python
|
Return a random paragraph .
|
cosqa-train-13872
|
def paragraph(separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3):
"""Return a random paragraph."""
return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,
wrap_end=wrap_end, html=html,
sentences_quantity=sentences_quantity)
|
def trim_trailing_silence ( self ) : length = self . get_active_length ( ) self . pianoroll = self . pianoroll [ : length ]
| 1 |
python remove pause in audio
|
Trim the trailing silence of the pianoroll .
|
cosqa-train-13873
|
def trim_trailing_silence(self):
"""Trim the trailing silence of the pianoroll."""
length = self.get_active_length()
self.pianoroll = self.pianoroll[:length]
|
def negate ( self ) : self . from_value , self . to_value = self . to_value , self . from_value self . include_lower , self . include_upper = self . include_upper , self . include_lower
| 0 |
how to make python range inclusive
|
Reverse the range
|
cosqa-train-13874
|
def negate(self):
"""Reverse the range"""
self.from_value, self.to_value = self.to_value, self.from_value
self.include_lower, self.include_upper = self.include_upper, self.include_lower
|
def remove_bad ( string ) : remove = [ ':' , ',' , '(' , ')' , ' ' , '|' , ';' , '\'' ] for c in remove : string = string . replace ( c , '_' ) return string
| 1 |
python remove spaces around string
|
remove problem characters from string
|
cosqa-train-13875
|
def remove_bad(string):
"""
remove problem characters from string
"""
remove = [':', ',', '(', ')', ' ', '|', ';', '\'']
for c in remove:
string = string.replace(c, '_')
return string
|
def clean ( some_string , uppercase = False ) : if uppercase : return some_string . strip ( ) . upper ( ) else : return some_string . strip ( ) . lower ( )
| 0 |
how to make strings upper in python 3
|
helper to clean up an input string
|
cosqa-train-13876
|
def clean(some_string, uppercase=False):
"""
helper to clean up an input string
"""
if uppercase:
return some_string.strip().upper()
else:
return some_string.strip().lower()
|
def urlize_twitter ( text ) : html = TwitterText ( text ) . autolink . auto_link ( ) return mark_safe ( html . replace ( 'twitter.com/search?q=' , 'twitter.com/search/realtime/' ) )
| 1 |
python remove urls in twitter
|
Replace #hashtag and
|
cosqa-train-13877
|
def urlize_twitter(text):
"""
Replace #hashtag and @username references in a tweet with HTML text.
"""
html = TwitterText(text).autolink.auto_link()
return mark_safe(html.replace(
'twitter.com/search?q=', 'twitter.com/search/realtime/'))
|
def inpaint ( self ) : import inpaint filled = inpaint . replace_nans ( np . ma . filled ( self . raster_data , np . NAN ) . astype ( np . float32 ) , 3 , 0.01 , 2 ) self . raster_data = np . ma . masked_invalid ( filled )
| 1 |
how to mask the image in white python
|
Replace masked - out elements in an array using an iterative image inpainting algorithm .
|
cosqa-train-13878
|
def inpaint(self):
""" Replace masked-out elements in an array using an iterative image inpainting algorithm. """
import inpaint
filled = inpaint.replace_nans(np.ma.filled(self.raster_data, np.NAN).astype(np.float32), 3, 0.01, 2)
self.raster_data = np.ma.masked_invalid(filled)
|
def cleanup ( self ) : for instance in self . context : del ( instance ) for plugin in self . plugins : del ( plugin )
| 1 |
python removin instances from memory
|
Forcefully delete objects from memory
|
cosqa-train-13879
|
def cleanup(self):
"""Forcefully delete objects from memory
In an ideal world, this shouldn't be necessary. Garbage
collection guarantees that anything without reference
is automatically removed.
However, because this application is designed to be run
multiple times from the same interpreter process, extra
case must be taken to ensure there are no memory leaks.
Explicitly deleting objects shines a light on where objects
may still be referenced in the form of an error. No errors
means this was uneccesary, but that's ok.
"""
for instance in self.context:
del(instance)
for plugin in self.plugins:
del(plugin)
|
def match ( string , patterns ) : if patterns is None : return True else : return any ( re . match ( pattern , string ) for pattern in patterns )
| 1 |
how to match a number of string pattern on in python list
|
Given a string return true if it matches the supplied list of patterns .
|
cosqa-train-13880
|
def match(string, patterns):
"""Given a string return true if it matches the supplied list of
patterns.
Parameters
----------
string : str
The string to be matched.
patterns : None or [pattern, ...]
The series of regular expressions to attempt to match.
"""
if patterns is None:
return True
else:
return any(re.match(pattern, string)
for pattern in patterns)
|
def _remove_empty_items ( d , required ) : new_dict = { } for k , v in d . items ( ) : if k in required : new_dict [ k ] = v elif isinstance ( v , int ) or v : # "if v" would suppress emitting int(0) new_dict [ k ] = v return new_dict
| 1 |
python removing empty literals dict keys
|
Return a new dict with any empty items removed .
|
cosqa-train-13881
|
def _remove_empty_items(d, required):
"""Return a new dict with any empty items removed.
Note that this is not a deep check. If d contains a dictionary which
itself contains empty items, those are never checked.
This method exists to make to_serializable() functions cleaner.
We could revisit this some day, but for now, the serialized objects are
stripped of empty values to keep the output YAML more compact.
Args:
d: a dictionary
required: list of required keys (for example, TaskDescriptors always emit
the "task-id", even if None)
Returns:
A dictionary with empty items removed.
"""
new_dict = {}
for k, v in d.items():
if k in required:
new_dict[k] = v
elif isinstance(v, int) or v:
# "if v" would suppress emitting int(0)
new_dict[k] = v
return new_dict
|
def file_matches ( filename , patterns ) : return any ( fnmatch . fnmatch ( filename , pat ) for pat in patterns )
| 1 |
how to match patterns in filenames using re in python
|
Does this filename match any of the patterns?
|
cosqa-train-13882
|
def file_matches(filename, patterns):
"""Does this filename match any of the patterns?"""
return any(fnmatch.fnmatch(filename, pat) for pat in patterns)
|
def replace_all ( text , dic ) : for i , j in dic . iteritems ( ) : text = text . replace ( i , j ) return text
| 1 |
python replace all values in dictionary
|
Takes a string and dictionary . replaces all occurrences of i with j
|
cosqa-train-13883
|
def replace_all(text, dic):
"""Takes a string and dictionary. replaces all occurrences of i with j"""
for i, j in dic.iteritems():
text = text.replace(i, j)
return text
|
def Fsphere ( q , R ) : return 4 * np . pi / q ** 3 * ( np . sin ( q * R ) - q * R * np . cos ( q * R ) )
| 1 |
how to model a sphere python
|
Scattering form - factor amplitude of a sphere normalized to F ( q = 0 ) = V
|
cosqa-train-13884
|
def Fsphere(q, R):
"""Scattering form-factor amplitude of a sphere normalized to F(q=0)=V
Inputs:
-------
``q``: independent variable
``R``: sphere radius
Formula:
--------
``4*pi/q^3 * (sin(qR) - qR*cos(qR))``
"""
return 4 * np.pi / q ** 3 * (np.sin(q * R) - q * R * np.cos(q * R))
|
def _replace_nan ( a , val ) : mask = isnull ( a ) return where_method ( val , mask , a ) , mask
| 1 |
python replace missing valumes with na
|
replace nan in a by val and returns the replaced array and the nan position
|
cosqa-train-13885
|
def _replace_nan(a, val):
"""
replace nan in a by val, and returns the replaced array and the nan
position
"""
mask = isnull(a)
return where_method(val, mask, a), mask
|
def align_file_position ( f , size ) : align = ( size - 1 ) - ( f . tell ( ) % size ) f . seek ( align , 1 )
| 1 |
how to move file pointer to specific offset after a line in python
|
Align the position in the file to the next block of specified size
|
cosqa-train-13886
|
def align_file_position(f, size):
""" Align the position in the file to the next block of specified size """
align = (size - 1) - (f.tell() % size)
f.seek(align, 1)
|
def set_property ( self , key , value ) : self . properties [ key ] = value self . sync_properties ( )
| 0 |
python replace property with attribute
|
Update only one property in the dict
|
cosqa-train-13887
|
def set_property(self, key, value):
"""
Update only one property in the dict
"""
self.properties[key] = value
self.sync_properties()
|
def __next__ ( self , reward , ask_id , lbl ) : return self . next ( reward , ask_id , lbl )
| 0 |
how to move to next iterattion python
|
For Python3 compatibility of generator .
|
cosqa-train-13888
|
def __next__(self, reward, ask_id, lbl):
"""For Python3 compatibility of generator."""
return self.next(reward, ask_id, lbl)
|
def handle_whitespace ( text ) : text = re_retab . sub ( sub_retab , text ) text = re_whitespace . sub ( '' , text ) . strip ( ) return text
| 1 |
python replace spaces and tabs
|
r Handles whitespace cleanup .
|
cosqa-train-13889
|
def handle_whitespace(text):
r"""Handles whitespace cleanup.
Tabs are "smartly" retabbed (see sub_retab). Lines that contain
only whitespace are truncated to a single newline.
"""
text = re_retab.sub(sub_retab, text)
text = re_whitespace.sub('', text).strip()
return text
|
def normalize_array ( lst ) : np_arr = np . array ( lst ) x_normalized = np_arr / np_arr . max ( axis = 0 ) return list ( x_normalized )
| 1 |
how to normalize a ndarray in python
|
Normalizes list
|
cosqa-train-13890
|
def normalize_array(lst):
"""Normalizes list
:param lst: Array of floats
:return: Normalized (in [0, 1]) input array
"""
np_arr = np.array(lst)
x_normalized = np_arr / np_arr.max(axis=0)
return list(x_normalized)
|
def list_replace ( subject_list , replacement , string ) : for s in subject_list : string = string . replace ( s , replacement ) return string
| 1 |
python replace string using nested for loop
|
To replace a list of items by a single replacement : param subject_list : list : param replacement : string : param string : string : return : string
|
cosqa-train-13891
|
def list_replace(subject_list, replacement, string):
"""
To replace a list of items by a single replacement
:param subject_list: list
:param replacement: string
:param string: string
:return: string
"""
for s in subject_list:
string = string.replace(s, replacement)
return string
|
def normalize ( data ) : out_data = data . copy ( ) for i , sample in enumerate ( out_data ) : out_data [ i ] /= sum ( out_data [ i ] ) return out_data
| 0 |
how to normalize a set of data python
|
Normalize the data to be in the [ 0 1 ] range .
|
cosqa-train-13892
|
def normalize(data):
"""Normalize the data to be in the [0, 1] range.
:param data:
:return: normalized data
"""
out_data = data.copy()
for i, sample in enumerate(out_data):
out_data[i] /= sum(out_data[i])
return out_data
|
def _get_pretty_string ( obj ) : sio = StringIO ( ) pprint . pprint ( obj , stream = sio ) return sio . getvalue ( )
| 1 |
python repr to compare objects
|
Return a prettier version of obj
|
cosqa-train-13893
|
def _get_pretty_string(obj):
"""Return a prettier version of obj
Parameters
----------
obj : object
Object to pretty print
Returns
-------
s : str
Pretty print object repr
"""
sio = StringIO()
pprint.pprint(obj, stream=sio)
return sio.getvalue()
|
def normalize_array ( lst ) : np_arr = np . array ( lst ) x_normalized = np_arr / np_arr . max ( axis = 0 ) return list ( x_normalized )
| 0 |
how to normalize an array in python without using the normalize function
|
Normalizes list
|
cosqa-train-13894
|
def normalize_array(lst):
"""Normalizes list
:param lst: Array of floats
:return: Normalized (in [0, 1]) input array
"""
np_arr = np.array(lst)
x_normalized = np_arr / np_arr.max(axis=0)
return list(x_normalized)
|
def parse_cookies ( self , req , name , field ) : return core . get_value ( req . COOKIES , name , field )
| 1 |
python request cookie get
|
Pull the value from the cookiejar .
|
cosqa-train-13895
|
def parse_cookies(self, req, name, field):
"""Pull the value from the cookiejar."""
return core.get_value(req.COOKIES, name, field)
|
def restart_program ( ) : python = sys . executable os . execl ( python , python , * sys . argv )
| 0 |
how to not auto end a python program
|
DOES NOT WORK WELL WITH MOPIDY Hack from https : // www . daniweb . com / software - development / python / code / 260268 / restart - your - python - program to support updating the settings since mopidy is not able to do that yet Restarts the current program Note : this function does not return . Any cleanup action ( like saving data ) must be done before calling this function
|
cosqa-train-13896
|
def restart_program():
"""
DOES NOT WORK WELL WITH MOPIDY
Hack from
https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program
to support updating the settings, since mopidy is not able to do that yet
Restarts the current program
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function
"""
python = sys.executable
os.execl(python, python, * sys.argv)
|
def disable_insecure_request_warning ( ) : import requests from requests . packages . urllib3 . exceptions import InsecureRequestWarning requests . packages . urllib3 . disable_warnings ( InsecureRequestWarning )
| 1 |
python requests disable ssl certificate verification
|
Suppress warning about untrusted SSL certificate .
|
cosqa-train-13897
|
def disable_insecure_request_warning():
"""Suppress warning about untrusted SSL certificate."""
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
|
def first_unique_char ( s ) : if ( len ( s ) == 1 ) : return 0 ban = [ ] for i in range ( len ( s ) ) : if all ( s [ i ] != s [ k ] for k in range ( i + 1 , len ( s ) ) ) == True and s [ i ] not in ban : return i else : ban . append ( s [ i ] ) return - 1
| 1 |
how to obtain unique characters in a string python
|
: type s : str : rtype : int
|
cosqa-train-13898
|
def first_unique_char(s):
"""
:type s: str
:rtype: int
"""
if (len(s) == 1):
return 0
ban = []
for i in range(len(s)):
if all(s[i] != s[k] for k in range(i + 1, len(s))) == True and s[i] not in ban:
return i
else:
ban.append(s[i])
return -1
|
def http_request_json ( * args , * * kwargs ) : ret , status = http_request ( * args , * * kwargs ) return json . loads ( ret ) , status
| 1 |
python requests response code and body
|
cosqa-train-13899
|
def http_request_json(*args, **kwargs):
"""
See: http_request
"""
ret, status = http_request(*args, **kwargs)
return json.loads(ret), status
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.