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 __unixify ( self , s ) : return os . path . normpath ( s ) . replace ( os . sep , "/" )
| 1 |
windows path from unix path python
|
stupid windows . converts the backslash to forwardslash for consistency
|
cosqa-train-14800
|
def __unixify(self, s):
""" stupid windows. converts the backslash to forwardslash for consistency """
return os.path.normpath(s).replace(os.sep, "/")
|
def format_result ( input ) : items = list ( iteritems ( input ) ) return OrderedDict ( sorted ( items , key = lambda x : x [ 0 ] ) )
| 0 |
python create a ordered dict
|
From : http : // stackoverflow . com / questions / 13062300 / convert - a - dict - to - sorted - dict - in - python
|
cosqa-train-14801
|
def format_result(input):
"""From: http://stackoverflow.com/questions/13062300/convert-a-dict-to-sorted-dict-in-python
"""
items = list(iteritems(input))
return OrderedDict(sorted(items, key=lambda x: x[0]))
|
def kill ( self ) : if self . process : self . process . kill ( ) self . process . wait ( )
| 0 |
windows python kill firefox
|
Kill the browser .
|
cosqa-train-14802
|
def kill(self):
"""Kill the browser.
This is useful when the browser is stuck.
"""
if self.process:
self.process.kill()
self.process.wait()
|
def _get_str_columns ( sf ) : return [ name for name in sf . column_names ( ) if sf [ name ] . dtype == str ]
| 1 |
python create list of columns with their dtype
|
Returns a list of names of columns that are string type .
|
cosqa-train-14803
|
def _get_str_columns(sf):
"""
Returns a list of names of columns that are string type.
"""
return [name for name in sf.column_names() if sf[name].dtype == str]
|
def exit ( exit_code = 0 ) : core . processExitHooks ( ) if state . isExitHooked and not hasattr ( sys , 'exitfunc' ) : # The function is called from the exit hook sys . stderr . flush ( ) sys . stdout . flush ( ) os . _exit ( exit_code ) #pylint: disable=W0212 sys . exit ( exit_code )
| 1 |
wrap python sys exit
|
r A function to support exiting from exit hooks .
|
cosqa-train-14804
|
def exit(exit_code=0):
r"""A function to support exiting from exit hooks.
Could also be used to exit from the calling scripts in a thread safe manner.
"""
core.processExitHooks()
if state.isExitHooked and not hasattr(sys, 'exitfunc'): # The function is called from the exit hook
sys.stderr.flush()
sys.stdout.flush()
os._exit(exit_code) #pylint: disable=W0212
sys.exit(exit_code)
|
def vectorsToMatrix ( aa , bb ) : MM = np . zeros ( [ 3 , 3 ] , np . float ) for ii in range ( 3 ) : for jj in range ( 3 ) : MM [ ii , jj ] = aa [ ii ] * bb [ jj ] return MM
| 1 |
python create matrix from 2 matrices
|
Performs the vector multiplication of the elements of two vectors constructing the 3x3 matrix . : param aa : One vector of size 3 : param bb : Another vector of size 3 : return : A 3x3 matrix M composed of the products of the elements of aa and bb : M_ij = aa_i * bb_j
|
cosqa-train-14805
|
def vectorsToMatrix(aa, bb):
"""
Performs the vector multiplication of the elements of two vectors, constructing the 3x3 matrix.
:param aa: One vector of size 3
:param bb: Another vector of size 3
:return: A 3x3 matrix M composed of the products of the elements of aa and bb :
M_ij = aa_i * bb_j
"""
MM = np.zeros([3, 3], np.float)
for ii in range(3):
for jj in range(3):
MM[ii, jj] = aa[ii] * bb[jj]
return MM
|
def int2str ( num , radix = 10 , alphabet = BASE85 ) : return NumConv ( radix , alphabet ) . int2str ( num )
| 1 |
write a function that converts integer to string in roman notation python
|
helper function for quick base conversions from integers to strings
|
cosqa-train-14806
|
def int2str(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from integers to strings"""
return NumConv(radix, alphabet).int2str(num)
|
def create_rot2d ( angle ) : ca = math . cos ( angle ) sa = math . sin ( angle ) return np . array ( [ [ ca , - sa ] , [ sa , ca ] ] )
| 1 |
python create matrix from angle axis rotation
|
Create 2D rotation matrix
|
cosqa-train-14807
|
def create_rot2d(angle):
"""Create 2D rotation matrix"""
ca = math.cos(angle)
sa = math.sin(angle)
return np.array([[ca, -sa], [sa, ca]])
|
def packagenameify ( s ) : return '' . join ( w if w in ACRONYMS else w . title ( ) for w in s . split ( '.' ) [ - 1 : ] )
| 0 |
write a python function to seprate a name without array
|
Makes a package name
|
cosqa-train-14808
|
def packagenameify(s):
"""
Makes a package name
"""
return ''.join(w if w in ACRONYMS else w.title() for w in s.split('.')[-1:])
|
def from_json_str ( cls , json_str ) : return cls . from_json ( json . loads ( json_str , cls = JsonDecoder ) )
| 0 |
python create opject from string
|
Convert json string representation into class instance .
|
cosqa-train-14809
|
def from_json_str(cls, json_str):
"""Convert json string representation into class instance.
Args:
json_str: json representation as string.
Returns:
New instance of the class with data loaded from json string.
"""
return cls.from_json(json.loads(json_str, cls=JsonDecoder))
|
def _write_color_colorama ( fp , text , color ) : foreground , background , style = get_win_color ( color ) colorama . set_console ( foreground = foreground , background = background , style = style ) fp . write ( text ) colorama . reset_console ( )
| 1 |
write file python change text color
|
Colorize text with given color .
|
cosqa-train-14810
|
def _write_color_colorama (fp, text, color):
"""Colorize text with given color."""
foreground, background, style = get_win_color(color)
colorama.set_console(foreground=foreground, background=background,
style=style)
fp.write(text)
colorama.reset_console()
|
def scipy_sparse_to_spmatrix ( A ) : coo = A . tocoo ( ) SP = spmatrix ( coo . data . tolist ( ) , coo . row . tolist ( ) , coo . col . tolist ( ) , size = A . shape ) return SP
| 1 |
python create scipy sparse matrix
|
Efficient conversion from scipy sparse matrix to cvxopt sparse matrix
|
cosqa-train-14811
|
def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP
|
def build_service_class ( metadata ) : i = importlib . import_module ( metadata ) service = i . service env = get_jinja_env ( ) service_template = env . get_template ( 'service.py.jinja2' ) with open ( api_path ( service . name . lower ( ) ) , 'w' ) as t : t . write ( service_template . render ( service_md = service ) )
| 1 |
writing a python service
|
Generate a service class for the service contained in the specified metadata class .
|
cosqa-train-14812
|
def build_service_class(metadata):
"""Generate a service class for the service contained in the specified metadata class."""
i = importlib.import_module(metadata)
service = i.service
env = get_jinja_env()
service_template = env.get_template('service.py.jinja2')
with open(api_path(service.name.lower()), 'w') as t:
t.write(service_template.render(service_md=service))
|
def get_next_scheduled_time ( cron_string ) : itr = croniter . croniter ( cron_string , datetime . utcnow ( ) ) return itr . get_next ( datetime )
| 0 |
python croniter sign question
|
Calculate the next scheduled time by creating a crontab object with a cron string
|
cosqa-train-14813
|
def get_next_scheduled_time(cron_string):
"""Calculate the next scheduled time by creating a crontab object
with a cron string"""
itr = croniter.croniter(cron_string, datetime.utcnow())
return itr.get_next(datetime)
|
def add_to_js ( self , name , var ) : frame = self . page ( ) . mainFrame ( ) frame . addToJavaScriptWindowObject ( name , var )
| 1 |
writing javascript in python for webpage
|
Add an object to Javascript .
|
cosqa-train-14814
|
def add_to_js(self, name, var):
"""Add an object to Javascript."""
frame = self.page().mainFrame()
frame.addToJavaScriptWindowObject(name, var)
|
def _trim ( image ) : background = PIL . Image . new ( image . mode , image . size , image . getpixel ( ( 0 , 0 ) ) ) diff = PIL . ImageChops . difference ( image , background ) diff = PIL . ImageChops . add ( diff , diff , 2.0 , - 100 ) bbox = diff . getbbox ( ) if bbox : image = image . crop ( bbox ) return image
| 1 |
python crop black out of image
|
Trim a PIL image and remove white space .
|
cosqa-train-14815
|
def _trim(image):
"""Trim a PIL image and remove white space."""
background = PIL.Image.new(image.mode, image.size, image.getpixel((0, 0)))
diff = PIL.ImageChops.difference(image, background)
diff = PIL.ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
image = image.crop(bbox)
return image
|
def on_close ( self , evt ) : self . stop ( ) # DoseWatcher if evt . EventObject is not self : # Avoid deadlocks self . Close ( ) # wx.Frame evt . Skip ( )
| 0 |
wxpython destroy function called frame not disappear immediately
|
Pop - up menu and wx . EVT_CLOSE closing event
|
cosqa-train-14816
|
def on_close(self, evt):
"""
Pop-up menu and wx.EVT_CLOSE closing event
"""
self.stop() # DoseWatcher
if evt.EventObject is not self: # Avoid deadlocks
self.Close() # wx.Frame
evt.Skip()
|
def _mean_absolute_error ( y , y_pred , w ) : return np . average ( np . abs ( y_pred - y ) , weights = w )
| 0 |
python cross validation average accuracy intepretation
|
Calculate the mean absolute error .
|
cosqa-train-14817
|
def _mean_absolute_error(y, y_pred, w):
"""Calculate the mean absolute error."""
return np.average(np.abs(y_pred - y), weights=w)
|
def xeval ( source , optimize = True ) : native = xcompile ( source , optimize = optimize ) return native ( )
| 1 |
xcode compile python source
|
Compiles to native Python bytecode and runs program returning the topmost value on the stack .
|
cosqa-train-14818
|
def xeval(source, optimize=True):
"""Compiles to native Python bytecode and runs program, returning the
topmost value on the stack.
Args:
optimize: Whether to optimize the code after parsing it.
Returns:
None: If the stack is empty
obj: If the stack contains a single value
[obj, obj, ...]: If the stack contains many values
"""
native = xcompile(source, optimize=optimize)
return native()
|
def yank ( event ) : event . current_buffer . paste_clipboard_data ( event . cli . clipboard . get_data ( ) , count = event . arg , paste_mode = PasteMode . EMACS )
| 1 |
python ctype paste clipboard
|
Paste before cursor .
|
cosqa-train-14819
|
def yank(event):
"""
Paste before cursor.
"""
event.current_buffer.paste_clipboard_data(
event.cli.clipboard.get_data(), count=event.arg, paste_mode=PasteMode.EMACS)
|
def Parse ( text ) : precondition . AssertType ( text , Text ) if compatibility . PY2 : text = text . encode ( "utf-8" ) return yaml . safe_load ( text )
| 0 |
yaml python object parse into
|
Parses a YAML source into a Python object .
|
cosqa-train-14820
|
def Parse(text):
"""Parses a YAML source into a Python object.
Args:
text: A YAML source to parse.
Returns:
A Python data structure corresponding to the YAML source.
"""
precondition.AssertType(text, Text)
if compatibility.PY2:
text = text.encode("utf-8")
return yaml.safe_load(text)
|
def _monitor_callback_wrapper ( callback ) : def callback_handle ( name , array , _ ) : """ ctypes function """ callback ( name , array ) return callback_handle
| 0 |
python ctypes callback instance method
|
A wrapper for the user - defined handle .
|
cosqa-train-14821
|
def _monitor_callback_wrapper(callback):
"""A wrapper for the user-defined handle."""
def callback_handle(name, array, _):
""" ctypes function """
callback(name, array)
return callback_handle
|
def extract_zip ( zip_path , target_folder ) : with zipfile . ZipFile ( zip_path ) as archive : archive . extractall ( target_folder )
| 0 |
zipfiles within zipfiles in python
|
Extract the content of the zip - file at zip_path into target_folder .
|
cosqa-train-14822
|
def extract_zip(zip_path, target_folder):
"""
Extract the content of the zip-file at `zip_path` into `target_folder`.
"""
with zipfile.ZipFile(zip_path) as archive:
archive.extractall(target_folder)
|
def cint32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_int32 ) ) : return np . fromiter ( cptr , dtype = np . int32 , count = length ) else : raise RuntimeError ( 'Expected int pointer' )
| 0 |
python ctypes cast char array to pointer
|
Convert a ctypes int pointer array to a numpy array .
|
cosqa-train-14823
|
def cint32_array_to_numpy(cptr, length):
"""Convert a ctypes int pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)):
return np.fromiter(cptr, dtype=np.int32, count=length)
else:
raise RuntimeError('Expected int pointer')
|
def _run_asyncio ( loop , zmq_context ) : try : asyncio . set_event_loop ( loop ) loop . run_forever ( ) except : pass finally : loop . close ( ) zmq_context . destroy ( 1000 )
| 1 |
zmq context python hang on
|
Run asyncio ( should be called in a thread ) and close the loop and the zmq context when the thread ends : param loop : : param zmq_context : : return :
|
cosqa-train-14824
|
def _run_asyncio(loop, zmq_context):
"""
Run asyncio (should be called in a thread) and close the loop and the zmq context when the thread ends
:param loop:
:param zmq_context:
:return:
"""
try:
asyncio.set_event_loop(loop)
loop.run_forever()
except:
pass
finally:
loop.close()
zmq_context.destroy(1000)
|
def pointer ( self ) : return ctypes . cast ( ctypes . pointer ( ctypes . c_uint8 . from_buffer ( self . mapping , 0 ) ) , ctypes . c_void_p )
| 1 |
python ctypes how to create pointer pointer to uint var
|
Get a ctypes void pointer to the memory mapped region .
|
cosqa-train-14825
|
def pointer(self):
"""Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p
"""
return ctypes.cast(ctypes.pointer(ctypes.c_uint8.from_buffer(self.mapping, 0)), ctypes.c_void_p)
|
def cfloat32_array_to_numpy ( cptr , length ) : if isinstance ( cptr , ctypes . POINTER ( ctypes . c_float ) ) : return np . fromiter ( cptr , dtype = np . float32 , count = length ) else : raise RuntimeError ( 'Expected float pointer' )
| 0 |
python ctypes pass int array into fnction
|
Convert a ctypes float pointer array to a numpy array .
|
cosqa-train-14826
|
def cfloat32_array_to_numpy(cptr, length):
"""Convert a ctypes float pointer array to a numpy array."""
if isinstance(cptr, ctypes.POINTER(ctypes.c_float)):
return np.fromiter(cptr, dtype=np.float32, count=length)
else:
raise RuntimeError('Expected float pointer')
|
def POINTER ( obj ) : p = ctypes . POINTER ( obj ) if not isinstance ( p . from_param , classmethod ) : def from_param ( cls , x ) : if x is None : return cls ( ) else : return x p . from_param = classmethod ( from_param ) return p
| 1 |
python ctypes pass null pointer
|
Create ctypes pointer to object .
|
cosqa-train-14827
|
def POINTER(obj):
"""
Create ctypes pointer to object.
Notes
-----
This function converts None to a real NULL pointer because of bug
in how ctypes handles None on 64-bit platforms.
"""
p = ctypes.POINTER(obj)
if not isinstance(p.from_param, classmethod):
def from_param(cls, x):
if x is None:
return cls()
else:
return x
p.from_param = classmethod(from_param)
return p
|
def is_defined ( self , objtxt , force_import = False ) : return self . interpreter . is_defined ( objtxt , force_import )
| 0 |
python check if variable is instantiated
|
Return True if object is defined
|
cosqa-train-14828
|
def is_defined(self, objtxt, force_import=False):
"""Return True if object is defined"""
return self.interpreter.is_defined(objtxt, force_import)
|
def validate ( self , obj ) : if not isinstance ( obj , self . model_class ) : raise ValidationError ( 'Invalid object(%s) for service %s' % ( type ( obj ) , type ( self ) ) ) LOG . debug ( u'Object %s state: %s' , self . model_class , obj . __dict__ ) obj . full_clean ( )
| 1 |
"how to validate a python model"
|
Raises django . core . exceptions . ValidationError if any validation error exists
|
cosqa-train-14829
|
def validate(self, obj):
""" Raises django.core.exceptions.ValidationError if any validation error exists """
if not isinstance(obj, self.model_class):
raise ValidationError('Invalid object(%s) for service %s' % (type(obj), type(self)))
LOG.debug(u'Object %s state: %s', self.model_class, obj.__dict__)
obj.full_clean()
|
def contains_geometric_info ( var ) : return isinstance ( var , tuple ) and len ( var ) == 2 and all ( isinstance ( val , ( int , float ) ) for val in var )
| 1 |
python check if variable is list or float
|
Check whether the passed variable is a tuple with two floats or integers
|
cosqa-train-14830
|
def contains_geometric_info(var):
""" Check whether the passed variable is a tuple with two floats or integers """
return isinstance(var, tuple) and len(var) == 2 and all(isinstance(val, (int, float)) for val in var)
|
def _idx_col2rowm ( d ) : if 0 == len ( d ) : return 1 if 1 == len ( d ) : return np . arange ( d [ 0 ] ) # order='F' indicates column-major ordering idx = np . array ( np . arange ( np . prod ( d ) ) ) . reshape ( d , order = 'F' ) . T return idx . flatten ( order = 'F' )
| 0 |
"multi dimensional" indexes to linear indexes python
|
Generate indexes to change from col - major to row - major ordering
|
cosqa-train-14831
|
def _idx_col2rowm(d):
"""Generate indexes to change from col-major to row-major ordering"""
if 0 == len(d):
return 1
if 1 == len(d):
return np.arange(d[0])
# order='F' indicates column-major ordering
idx = np.array(np.arange(np.prod(d))).reshape(d, order='F').T
return idx.flatten(order='F')
|
def is_date_type ( cls ) : if not isinstance ( cls , type ) : return False return issubclass ( cls , date ) and not issubclass ( cls , datetime )
| 0 |
python check instance of date
|
Return True if the class is a date type .
|
cosqa-train-14832
|
def is_date_type(cls):
"""Return True if the class is a date type."""
if not isinstance(cls, type):
return False
return issubclass(cls, date) and not issubclass(cls, datetime)
|
def notin ( arg , values ) : op = ops . NotContains ( arg , values ) return op . to_expr ( )
| 0 |
python 3 "not in"
|
Like isin but checks whether this expression s value ( s ) are not contained in the passed values . See isin docs for full usage .
|
cosqa-train-14833
|
def notin(arg, values):
"""
Like isin, but checks whether this expression's value(s) are not
contained in the passed values. See isin docs for full usage.
"""
op = ops.NotContains(arg, values)
return op.to_expr()
|
def __contains__ ( self , key ) : assert isinstance ( key , basestring ) return dict . __contains__ ( self , key . lower ( ) )
| 0 |
python check is the key in the dictionary
|
Check lowercase key item .
|
cosqa-train-14834
|
def __contains__ (self, key):
"""Check lowercase key item."""
assert isinstance(key, basestring)
return dict.__contains__(self, key.lower())
|
def error_rate ( predictions , labels ) : return 100.0 - ( 100.0 * np . sum ( np . argmax ( predictions , 1 ) == np . argmax ( labels , 1 ) ) / predictions . shape [ 0 ] )
| 1 |
python confidence interval "failure rate"
|
Return the error rate based on dense predictions and 1 - hot labels .
|
cosqa-train-14835
|
def error_rate(predictions, labels):
"""Return the error rate based on dense predictions and 1-hot labels."""
return 100.0 - (
100.0 *
np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) /
predictions.shape[0])
|
def get_time ( filename ) : ts = os . stat ( filename ) . st_mtime return datetime . datetime . utcfromtimestamp ( ts )
| 0 |
python check modified time of file
|
Get the modified time for a file as a datetime instance
|
cosqa-train-14836
|
def get_time(filename):
"""
Get the modified time for a file as a datetime instance
"""
ts = os.stat(filename).st_mtime
return datetime.datetime.utcfromtimestamp(ts)
|
def createdb ( ) : manager . db . engine . echo = True manager . db . create_all ( ) set_alembic_revision ( )
| 1 |
python sqlalchemy "create table"
|
Create database tables from sqlalchemy models
|
cosqa-train-14837
|
def createdb():
"""Create database tables from sqlalchemy models"""
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision()
|
def is_password_valid ( password ) : pattern = re . compile ( r"^.{4,75}$" ) return bool ( pattern . match ( password ) )
| 0 |
python check password strength regex
|
Check if a password is valid
|
cosqa-train-14838
|
def is_password_valid(password):
"""
Check if a password is valid
"""
pattern = re.compile(r"^.{4,75}$")
return bool(pattern.match(password))
|
def cmd_reindex ( ) : db = connect ( args . database ) for idx in args . indexes : pg_reindex ( db , idx )
| 0 |
reindex in python "not in index"
|
Uses CREATE INDEX CONCURRENTLY to create a duplicate index then tries to swap the new index for the original .
|
cosqa-train-14839
|
def cmd_reindex():
"""Uses CREATE INDEX CONCURRENTLY to create a duplicate index, then tries to swap the new index for the original.
The index swap is done using a short lock timeout to prevent it from interfering with running queries. Retries until
the rename succeeds.
"""
db = connect(args.database)
for idx in args.indexes:
pg_reindex(db, idx)
|
def is_port_open ( port , host = "127.0.0.1" ) : s = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) try : s . connect ( ( host , int ( port ) ) ) s . shutdown ( 2 ) return True except Exception as e : return False
| 1 |
python check port network connection
|
Check if a port is open : param port : : param host : : return bool :
|
cosqa-train-14840
|
def is_port_open(port, host="127.0.0.1"):
"""
Check if a port is open
:param port:
:param host:
:return bool:
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, int(port)))
s.shutdown(2)
return True
except Exception as e:
return False
|
def extend ( self , iterable ) : return super ( Collection , self ) . extend ( self . _ensure_iterable_is_valid ( iterable ) )
| 0 |
'collection' object is not iterable python
|
Extend the list by appending all the items in the given list .
|
cosqa-train-14841
|
def extend(self, iterable):
"""Extend the list by appending all the items in the given list."""
return super(Collection, self).extend(
self._ensure_iterable_is_valid(iterable))
|
def is_power_of_2 ( num ) : log = math . log2 ( num ) return int ( log ) == float ( log )
| 0 |
python check power of 2
|
Return whether num is a power of two
|
cosqa-train-14842
|
def is_power_of_2(num):
"""Return whether `num` is a power of two"""
log = math.log2(num)
return int(log) == float(log)
|
def ci ( a , which = 95 , axis = None ) : p = 50 - which / 2 , 50 + which / 2 return percentiles ( a , p , axis )
| 0 |
25 and 75 percentile in python
|
Return a percentile range from an array of values .
|
cosqa-train-14843
|
def ci(a, which=95, axis=None):
"""Return a percentile range from an array of values."""
p = 50 - which / 2, 50 + which / 2
return percentiles(a, p, axis)
|
def cmp_contents ( filename1 , filename2 ) : with open_readable ( filename1 , 'rb' ) as fobj : contents1 = fobj . read ( ) with open_readable ( filename2 , 'rb' ) as fobj : contents2 = fobj . read ( ) return contents1 == contents2
| 0 |
python check the contents of two file are the same
|
Returns True if contents of the files are the same
|
cosqa-train-14844
|
def cmp_contents(filename1, filename2):
""" Returns True if contents of the files are the same
Parameters
----------
filename1 : str
filename of first file to compare
filename2 : str
filename of second file to compare
Returns
-------
tf : bool
True if binary contents of `filename1` is same as binary contents of
`filename2`, False otherwise.
"""
with open_readable(filename1, 'rb') as fobj:
contents1 = fobj.read()
with open_readable(filename2, 'rb') as fobj:
contents2 = fobj.read()
return contents1 == contents2
|
def transform_from_rot_trans ( R , t ) : R = R . reshape ( 3 , 3 ) t = t . reshape ( 3 , 1 ) return np . vstack ( ( np . hstack ( [ R , t ] ) , [ 0 , 0 , 0 , 1 ] ) )
| 0 |
2d rotatation matrix python
|
Transforation matrix from rotation matrix and translation vector .
|
cosqa-train-14845
|
def transform_from_rot_trans(R, t):
"""Transforation matrix from rotation matrix and translation vector."""
R = R.reshape(3, 3)
t = t.reshape(3, 1)
return np.vstack((np.hstack([R, t]), [0, 0, 0, 1]))
|
def is_client ( self ) : return ( self . args . client or self . args . browser ) and not self . args . server
| 0 |
python check to see if browser is present
|
Return True if Glances is running in client mode .
|
cosqa-train-14846
|
def is_client(self):
"""Return True if Glances is running in client mode."""
return (self.args.client or self.args.browser) and not self.args.server
|
def _linear_interpolation ( x , X , Y ) : return ( Y [ 1 ] * ( x - X [ 0 ] ) + Y [ 0 ] * ( X [ 1 ] - x ) ) / ( X [ 1 ] - X [ 0 ] )
| 0 |
3d linear interpolation python based on two points
|
Given two data points [ X Y ] linearly interpolate those at x .
|
cosqa-train-14847
|
def _linear_interpolation(x, X, Y):
"""Given two data points [X,Y], linearly interpolate those at x.
"""
return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])
|
def _is_utf_8 ( txt ) : assert isinstance ( txt , six . binary_type ) try : _ = six . text_type ( txt , 'utf-8' ) except ( TypeError , UnicodeEncodeError ) : return False else : return True
| 0 |
python check utf8 support
|
Check a string is utf - 8 encoded
|
cosqa-train-14848
|
def _is_utf_8(txt):
"""
Check a string is utf-8 encoded
:param bytes txt: utf-8 string
:return: Whether the string\
is utf-8 encoded or not
:rtype: bool
"""
assert isinstance(txt, six.binary_type)
try:
_ = six.text_type(txt, 'utf-8')
except (TypeError, UnicodeEncodeError):
return False
else:
return True
|
def loganalytics_data_plane_client ( cli_ctx , _ ) : from . vendored_sdks . loganalytics import LogAnalyticsDataClient from azure . cli . core . _profile import Profile profile = Profile ( cli_ctx = cli_ctx ) cred , _ , _ = profile . get_login_credentials ( resource = "https://api.loganalytics.io" ) return LogAnalyticsDataClient ( cred )
| 0 |
access azure logs in python
|
Initialize Log Analytics data client for use with CLI .
|
cosqa-train-14849
|
def loganalytics_data_plane_client(cli_ctx, _):
"""Initialize Log Analytics data client for use with CLI."""
from .vendored_sdks.loganalytics import LogAnalyticsDataClient
from azure.cli.core._profile import Profile
profile = Profile(cli_ctx=cli_ctx)
cred, _, _ = profile.get_login_credentials(
resource="https://api.loganalytics.io")
return LogAnalyticsDataClient(cred)
|
def validate ( self , val ) : if val in self . values : return True , None else : return False , "'%s' is not in enum: %s" % ( val , str ( self . values ) )
| 1 |
python check value a valid item in enum
|
Validates that the val is in the list of values for this Enum .
|
cosqa-train-14850
|
def validate(self, val):
"""
Validates that the val is in the list of values for this Enum.
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
:Parameters:
val
Value to validate. Should be a string.
"""
if val in self.values:
return True, None
else:
return False, "'%s' is not in enum: %s" % (val, str(self.values))
|
def token_accuracy ( labels , outputs ) : weights = tf . to_float ( tf . not_equal ( labels , 0 ) ) return tf . metrics . accuracy ( labels , outputs , weights = weights )
| 1 |
accuracy of computation in python
|
Compute tokenwise ( elementwise ) accuracy .
|
cosqa-train-14851
|
def token_accuracy(labels, outputs):
"""Compute tokenwise (elementwise) accuracy.
Args:
labels: ground-truth labels, shape=(batch, seq_length)
outputs: predicted tokens, shape=(batch, seq_length)
Returns:
Two ops, one for getting the current average accuracy and another for
updating the running average estimate.
"""
weights = tf.to_float(tf.not_equal(labels, 0))
return tf.metrics.accuracy(labels, outputs, weights=weights)
|
def isin ( self , column , compare_list ) : return [ x in compare_list for x in self . _data [ self . _columns . index ( column ) ] ]
| 0 |
python check values in column and mark true if in list
|
Returns a boolean list where each elements is whether that element in the column is in the compare_list .
|
cosqa-train-14852
|
def isin(self, column, compare_list):
"""
Returns a boolean list where each elements is whether that element in the column is in the compare_list.
:param column: single column name, does not work for multiple columns
:param compare_list: list of items to compare to
:return: list of booleans
"""
return [x in compare_list for x in self._data[self._columns.index(column)]]
|
def to_dotfile ( self ) : domain = self . get_domain ( ) filename = "%s.dot" % ( self . __class__ . __name__ ) nx . write_dot ( domain , filename ) return filename
| 0 |
add dots to python graph
|
Writes a DOT graphviz file of the domain structure and returns the filename
|
cosqa-train-14853
|
def to_dotfile(self):
""" Writes a DOT graphviz file of the domain structure, and returns the filename"""
domain = self.get_domain()
filename = "%s.dot" % (self.__class__.__name__)
nx.write_dot(domain, filename)
return filename
|
def check ( self , var ) : if not isinstance ( var , _str_type ) : return False return _enum_mangle ( var ) in self . _consts
| 0 |
python check variable enum
|
Check whether the provided value is a valid enum constant .
|
cosqa-train-14854
|
def check(self, var):
"""Check whether the provided value is a valid enum constant."""
if not isinstance(var, _str_type): return False
return _enum_mangle(var) in self._consts
|
def add_bg ( img , padding , color = COL_WHITE ) : img = gray3 ( img ) h , w , d = img . shape new_img = np . ones ( ( h + 2 * padding , w + 2 * padding , d ) ) * color [ : d ] new_img = new_img . astype ( np . uint8 ) set_img_box ( new_img , ( padding , padding , w , h ) , img ) return new_img
| 0 |
add padding to image python 3d effect
|
Adds a padding to the given image as background of specified color
|
cosqa-train-14855
|
def add_bg(img, padding, color=COL_WHITE):
"""
Adds a padding to the given image as background of specified color
:param img: Input image.
:param padding: constant padding around the image.
:param color: background color that needs to filled for the newly padded region.
:return: New image with background.
"""
img = gray3(img)
h, w, d = img.shape
new_img = np.ones((h + 2*padding, w + 2*padding, d)) * color[:d]
new_img = new_img.astype(np.uint8)
set_img_box(new_img, (padding, padding, w, h), img)
return new_img
|
def is_element_present ( driver , selector , by = By . CSS_SELECTOR ) : try : driver . find_element ( by = by , value = selector ) return True except Exception : return False
| 1 |
python check web page element exists
|
Returns whether the specified element selector is present on the page .
|
cosqa-train-14856
|
def is_element_present(driver, selector, by=By.CSS_SELECTOR):
"""
Returns whether the specified element selector is present on the page.
@Params
driver - the webdriver object (required)
selector - the locator that is used (required)
by - the method to search for the locator (Default: By.CSS_SELECTOR)
@Returns
Boolean (is element present)
"""
try:
driver.find_element(by=by, value=selector)
return True
except Exception:
return False
|
def seconds ( num ) : now = pytime . time ( ) end = now + num until ( end )
| 1 |
add sleep timer in loop python
|
Pause for this many seconds
|
cosqa-train-14857
|
def seconds(num):
"""
Pause for this many seconds
"""
now = pytime.time()
end = now + num
until(end)
|
def instance_contains ( container , item ) : return item in ( member for _ , member in inspect . getmembers ( container ) )
| 0 |
python check whether an object contains an attirbute
|
Search into instance attributes properties and return values of no - args methods .
|
cosqa-train-14858
|
def instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods."""
return item in (member for _, member in inspect.getmembers(container))
|
def deep_update ( d , u ) : for k , v in u . items ( ) : if isinstance ( v , Mapping ) : d [ k ] = deep_update ( d . get ( k , { } ) , v ) elif isinstance ( v , list ) : existing_elements = d . get ( k , [ ] ) d [ k ] = existing_elements + [ ele for ele in v if ele not in existing_elements ] else : d [ k ] = v return d
| 1 |
add update merge two dictionaries python
|
Deeply updates a dictionary . List values are concatenated .
|
cosqa-train-14859
|
def deep_update(d, u):
"""Deeply updates a dictionary. List values are concatenated.
Args:
d (dict): First dictionary which will be updated
u (dict): Second dictionary use to extend the first one
Returns:
dict: The merge dictionary
"""
for k, v in u.items():
if isinstance(v, Mapping):
d[k] = deep_update(d.get(k, {}), v)
elif isinstance(v, list):
existing_elements = d.get(k, [])
d[k] = existing_elements + [ele for ele in v if ele not in existing_elements]
else:
d[k] = v
return d
|
def url_syntax_check ( url ) : # pragma: no cover if url and isinstance ( url , str ) : # The given URL is not empty nor None. # and # * The given URL is a string. # We silently load the configuration. load_config ( True ) return Check ( url ) . is_url_valid ( ) # We return None, there is nothing to check. return None
| 0 |
python checking if a url is valid
|
Check the syntax of the given URL .
|
cosqa-train-14860
|
def url_syntax_check(url): # pragma: no cover
"""
Check the syntax of the given URL.
:param url: The URL to check the syntax for.
:type url: str
:return: The syntax validity.
:rtype: bool
.. warning::
If an empty or a non-string :code:`url` is given, we return :code:`None`.
"""
if url and isinstance(url, str):
# The given URL is not empty nor None.
# and
# * The given URL is a string.
# We silently load the configuration.
load_config(True)
return Check(url).is_url_valid()
# We return None, there is nothing to check.
return None
|
def strip_comment_marker ( text ) : lines = [ ] for line in text . splitlines ( ) : lines . append ( line . lstrip ( '#' ) ) text = textwrap . dedent ( '\n' . join ( lines ) ) return text
| 0 |
adding block comments in python
|
Strip # markers at the front of a block of comment text .
|
cosqa-train-14861
|
def strip_comment_marker(text):
""" Strip # markers at the front of a block of comment text.
"""
lines = []
for line in text.splitlines():
lines.append(line.lstrip('#'))
text = textwrap.dedent('\n'.join(lines))
return text
|
def _clear ( self ) : self . _finished = False self . _measurement = None self . _message = None self . _message_body = None
| 0 |
python clear all variables
|
Resets all assigned data for the current message .
|
cosqa-train-14862
|
def _clear(self):
"""Resets all assigned data for the current message."""
self._finished = False
self._measurement = None
self._message = None
self._message_body = None
|
def add_suffix ( fullname , suffix ) : name , ext = os . path . splitext ( fullname ) return name + '_' + suffix + ext
| 1 |
adding suffix to name python
|
Add suffix to a full file name
|
cosqa-train-14863
|
def add_suffix(fullname, suffix):
""" Add suffix to a full file name"""
name, ext = os.path.splitext(fullname)
return name + '_' + suffix + ext
|
def trim ( self ) : for key , value in list ( iteritems ( self . counters ) ) : if value . empty ( ) : del self . counters [ key ]
| 0 |
python clearing a vriable
|
Clear not used counters
|
cosqa-train-14864
|
def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key]
|
def adjacency ( tree ) : dd = ids ( tree ) N = len ( dd ) A = np . zeros ( ( N , N ) ) def _adj ( node ) : if np . isscalar ( node ) : return elif isinstance ( node , tuple ) and len ( node ) == 2 : A [ dd [ node ] , dd [ node [ 0 ] ] ] = 1 A [ dd [ node [ 0 ] ] , dd [ node ] ] = 1 _adj ( node [ 0 ] ) A [ dd [ node ] , dd [ node [ 1 ] ] ] = 1 A [ dd [ node [ 1 ] ] , dd [ node ] ] = 1 _adj ( node [ 1 ] ) _adj ( tree ) return A
| 0 |
adjacency matrix algorithm python
|
Construct the adjacency matrix of the tree : param tree : : return :
|
cosqa-train-14865
|
def adjacency(tree):
"""
Construct the adjacency matrix of the tree
:param tree:
:return:
"""
dd = ids(tree)
N = len(dd)
A = np.zeros((N, N))
def _adj(node):
if np.isscalar(node):
return
elif isinstance(node, tuple) and len(node) == 2:
A[dd[node], dd[node[0]]] = 1
A[dd[node[0]], dd[node]] = 1
_adj(node[0])
A[dd[node], dd[node[1]]] = 1
A[dd[node[1]], dd[node]] = 1
_adj(node[1])
_adj(tree)
return A
|
def paste ( cmd = paste_cmd , stdout = PIPE ) : return Popen ( cmd , stdout = stdout ) . communicate ( ) [ 0 ] . decode ( 'utf-8' )
| 0 |
python clipboard contents linux
|
Returns system clipboard contents .
|
cosqa-train-14866
|
def paste(cmd=paste_cmd, stdout=PIPE):
"""Returns system clipboard contents.
"""
return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')
|
def adjacency ( tree ) : dd = ids ( tree ) N = len ( dd ) A = np . zeros ( ( N , N ) ) def _adj ( node ) : if np . isscalar ( node ) : return elif isinstance ( node , tuple ) and len ( node ) == 2 : A [ dd [ node ] , dd [ node [ 0 ] ] ] = 1 A [ dd [ node [ 0 ] ] , dd [ node ] ] = 1 _adj ( node [ 0 ] ) A [ dd [ node ] , dd [ node [ 1 ] ] ] = 1 A [ dd [ node [ 1 ] ] , dd [ node ] ] = 1 _adj ( node [ 1 ] ) _adj ( tree ) return A
| 0 |
adjacency matrix of a data in python
|
Construct the adjacency matrix of the tree : param tree : : return :
|
cosqa-train-14867
|
def adjacency(tree):
"""
Construct the adjacency matrix of the tree
:param tree:
:return:
"""
dd = ids(tree)
N = len(dd)
A = np.zeros((N, N))
def _adj(node):
if np.isscalar(node):
return
elif isinstance(node, tuple) and len(node) == 2:
A[dd[node], dd[node[0]]] = 1
A[dd[node[0]], dd[node]] = 1
_adj(node[0])
A[dd[node], dd[node[1]]] = 1
A[dd[node[1]], dd[node]] = 1
_adj(node[1])
_adj(tree)
return A
|
def clone ( src , * * kwargs ) : obj = object . __new__ ( type ( src ) ) obj . __dict__ . update ( src . __dict__ ) obj . __dict__ . update ( kwargs ) return obj
| 0 |
python clone object from another object
|
Clones object with optionally overridden fields
|
cosqa-train-14868
|
def clone(src, **kwargs):
"""Clones object with optionally overridden fields"""
obj = object.__new__(type(src))
obj.__dict__.update(src.__dict__)
obj.__dict__.update(kwargs)
return obj
|
def managepy ( cmd , extra = None ) : extra = extra . split ( ) if extra else [ ] run_django_cli ( [ 'invoke' , cmd ] + extra )
| 1 |
admin to generate python django
|
Run manage . py using this component s specific Django settings
|
cosqa-train-14869
|
def managepy(cmd, extra=None):
"""Run manage.py using this component's specific Django settings"""
extra = extra.split() if extra else []
run_django_cli(['invoke', cmd] + extra)
|
def activate ( ) : # This is derived from the clone cli = CommandLineInterface ( ) cli . ensure_config ( ) cli . write_dockerfile ( ) cli . build ( ) cli . run ( )
| 0 |
python clone object in initiator
|
Usage : containment activate
|
cosqa-train-14870
|
def activate():
"""
Usage:
containment activate
"""
# This is derived from the clone
cli = CommandLineInterface()
cli.ensure_config()
cli.write_dockerfile()
cli.build()
cli.run()
|
def ansi ( color , text ) : code = COLOR_CODES [ color ] return '\033[1;{0}m{1}{2}' . format ( code , text , RESET_TERM )
| 1 |
ansi color escape sequences python
|
Wrap text in an ansi escape sequence
|
cosqa-train-14871
|
def ansi(color, text):
"""Wrap text in an ansi escape sequence"""
code = COLOR_CODES[color]
return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)
|
def mimetype ( self ) : return ( self . environment . mimetypes . get ( self . format_extension ) or self . compiler_mimetype or 'application/octet-stream' )
| 1 |
apache python mime type
|
MIME type of the asset .
|
cosqa-train-14872
|
def mimetype(self):
"""MIME type of the asset."""
return (self.environment.mimetypes.get(self.format_extension) or
self.compiler_mimetype or 'application/octet-stream')
|
def socket_close ( self ) : if self . sock != NC . INVALID_SOCKET : self . sock . close ( ) self . sock = NC . INVALID_SOCKET
| 1 |
python closing broken socket
|
Close our socket .
|
cosqa-train-14873
|
def socket_close(self):
"""Close our socket."""
if self.sock != NC.INVALID_SOCKET:
self.sock.close()
self.sock = NC.INVALID_SOCKET
|
def ts_func ( f ) : def wrap_func ( df , * args ) : # TODO: should vectorize to apply over all columns? return Chromatogram ( f ( df . values , * args ) , df . index , df . columns ) return wrap_func
| 1 |
apply a function ona series column python
|
This wraps a function that would normally only accept an array and allows it to operate on a DataFrame . Useful for applying numpy functions to DataFrames .
|
cosqa-train-14874
|
def ts_func(f):
"""
This wraps a function that would normally only accept an array
and allows it to operate on a DataFrame. Useful for applying
numpy functions to DataFrames.
"""
def wrap_func(df, *args):
# TODO: should vectorize to apply over all columns?
return Chromatogram(f(df.values, *args), df.index, df.columns)
return wrap_func
|
def mag ( z ) : if isinstance ( z [ 0 ] , np . ndarray ) : return np . array ( list ( map ( np . linalg . norm , z ) ) ) else : return np . linalg . norm ( z )
| 1 |
python code for finding magnitude of a vector
|
Get the magnitude of a vector .
|
cosqa-train-14875
|
def mag(z):
"""Get the magnitude of a vector."""
if isinstance(z[0], np.ndarray):
return np.array(list(map(np.linalg.norm, z)))
else:
return np.linalg.norm(z)
|
def apply ( f , obj , * args , * * kwargs ) : return vectorize ( f ) ( obj , * args , * * kwargs )
| 0 |
apply a function to a vector in python
|
Apply a function in parallel to each element of the input
|
cosqa-train-14876
|
def apply(f, obj, *args, **kwargs):
"""Apply a function in parallel to each element of the input"""
return vectorize(f)(obj, *args, **kwargs)
|
def generate_hash ( self , length = 30 ) : import random , string chars = string . ascii_letters + string . digits ran = random . SystemRandom ( ) . choice hash = '' . join ( ran ( chars ) for i in range ( length ) ) return hash
| 0 |
python code generate hash using random
|
Generate random string of given length
|
cosqa-train-14877
|
def generate_hash(self, length=30):
""" Generate random string of given length """
import random, string
chars = string.ascii_letters + string.digits
ran = random.SystemRandom().choice
hash = ''.join(ran(chars) for i in range(length))
return hash
|
def apply ( f , obj , * args , * * kwargs ) : return vectorize ( f ) ( obj , * args , * * kwargs )
| 0 |
apply a function to a vector python
|
Apply a function in parallel to each element of the input
|
cosqa-train-14878
|
def apply(f, obj, *args, **kwargs):
"""Apply a function in parallel to each element of the input"""
return vectorize(f)(obj, *args, **kwargs)
|
def angle_between_vectors ( x , y ) : dp = dot_product ( x , y ) if dp == 0 : return 0 xm = magnitude ( x ) ym = magnitude ( y ) return math . acos ( dp / ( xm * ym ) ) * ( 180. / math . pi )
| 0 |
python code that calculate angle between two points
|
Compute the angle between vector x and y
|
cosqa-train-14879
|
def angle_between_vectors(x, y):
""" Compute the angle between vector x and y """
dp = dot_product(x, y)
if dp == 0:
return 0
xm = magnitude(x)
ym = magnitude(y)
return math.acos(dp / (xm*ym)) * (180. / math.pi)
|
def transform ( self , df ) : for name , function in self . outputs : df [ name ] = function ( df )
| 1 |
apply function to each row of data frame python
|
Transforms a DataFrame in place . Computes all outputs of the DataFrame .
|
cosqa-train-14880
|
def transform(self, df):
"""
Transforms a DataFrame in place. Computes all outputs of the DataFrame.
Args:
df (pandas.DataFrame): DataFrame to transform.
"""
for name, function in self.outputs:
df[name] = function(df)
|
def has_multiline_items ( maybe_list : Optional [ Sequence [ str ] ] ) : return maybe_list and any ( is_multiline ( item ) for item in maybe_list )
| 0 |
python code to check every line of a list
|
Check whether one of the items in the list has multiple lines .
|
cosqa-train-14881
|
def has_multiline_items(maybe_list: Optional[Sequence[str]]):
"""Check whether one of the items in the list has multiple lines."""
return maybe_list and any(is_multiline(item) for item in maybe_list)
|
def apply_conditional_styles ( self , cbfct ) : for ridx in range ( self . nrows ) : for cidx in range ( self . ncols ) : fmts = cbfct ( self . actual_values . iloc [ ridx , cidx ] ) fmts and self . iloc [ ridx , cidx ] . apply_styles ( fmts ) return self
| 1 |
apply styling on individual elements of a particular column in python
|
Ability to provide dynamic styling of the cell based on its value . : param cbfct : function ( cell_value ) should return a dict of format commands to apply to that cell : return : self
|
cosqa-train-14882
|
def apply_conditional_styles(self, cbfct):
"""
Ability to provide dynamic styling of the cell based on its value.
:param cbfct: function(cell_value) should return a dict of format commands to apply to that cell
:return: self
"""
for ridx in range(self.nrows):
for cidx in range(self.ncols):
fmts = cbfct(self.actual_values.iloc[ridx, cidx])
fmts and self.iloc[ridx, cidx].apply_styles(fmts)
return self
|
def do_exit ( self , arg ) : if self . current : self . current . close ( ) self . resource_manager . close ( ) del self . resource_manager return True
| 0 |
python code to clean up and exit
|
Exit the shell session .
|
cosqa-train-14883
|
def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True
|
def SegmentMin ( a , ids ) : func = lambda idxs : np . amin ( a [ idxs ] , axis = 0 ) return seg_map ( func , a , ids ) ,
| 0 |
array of arrays python min
|
Segmented min op .
|
cosqa-train-14884
|
def SegmentMin(a, ids):
"""
Segmented min op.
"""
func = lambda idxs: np.amin(a[idxs], axis=0)
return seg_map(func, a, ids),
|
def random_id ( length ) : def char ( ) : """Generate single random char""" return random . choice ( string . ascii_letters + string . digits ) return "" . join ( char ( ) for _ in range ( length ) )
| 0 |
python code to generate a guid
|
Generates a random ID of given length
|
cosqa-train-14885
|
def random_id(length):
"""Generates a random ID of given length"""
def char():
"""Generate single random char"""
return random.choice(string.ascii_letters + string.digits)
return "".join(char() for _ in range(length))
|
def maxId ( self ) : if len ( self . model . db ) == 0 : return 0 return max ( map ( lambda obj : obj [ "id" ] , self . model . db ) )
| 1 |
asign all id's the max value python
|
int : current max id of objects
|
cosqa-train-14886
|
def maxId(self):
"""int: current max id of objects"""
if len(self.model.db) == 0:
return 0
return max(map(lambda obj: obj["id"], self.model.db))
|
def _join ( verb ) : data = pd . merge ( verb . x , verb . y , * * verb . kwargs ) # Preserve x groups if isinstance ( verb . x , GroupedDataFrame ) : data . plydata_groups = list ( verb . x . plydata_groups ) return data
| 0 |
python code to join between multiple data frames without using panda
|
Join helper
|
cosqa-train-14887
|
def _join(verb):
"""
Join helper
"""
data = pd.merge(verb.x, verb.y, **verb.kwargs)
# Preserve x groups
if isinstance(verb.x, GroupedDataFrame):
data.plydata_groups = list(verb.x.plydata_groups)
return data
|
def locked_delete ( self ) : filters = { self . key_name : self . key_value } self . session . query ( self . model_class ) . filter_by ( * * filters ) . delete ( )
| 0 |
auto filter delete user sqlalchemy python
|
Delete credentials from the SQLAlchemy datastore .
|
cosqa-train-14888
|
def locked_delete(self):
"""Delete credentials from the SQLAlchemy datastore."""
filters = {self.key_name: self.key_value}
self.session.query(self.model_class).filter_by(**filters).delete()
|
def rpc_fix_code ( self , source , directory ) : source = get_source ( source ) return fix_code ( source , directory )
| 0 |
python code to modify source code
|
Formats Python code to conform to the PEP 8 style guide .
|
cosqa-train-14889
|
def rpc_fix_code(self, source, directory):
"""Formats Python code to conform to the PEP 8 style guide.
"""
source = get_source(source)
return fix_code(source, directory)
|
def get_average_length_of_string ( strings ) : if not strings : return 0 return sum ( len ( word ) for word in strings ) / len ( strings )
| 0 |
average length of words in a string python
|
Computes average length of words
|
cosqa-train-14890
|
def get_average_length_of_string(strings):
"""Computes average length of words
:param strings: list of words
:return: Average length of word on list
"""
if not strings:
return 0
return sum(len(word) for word in strings) / len(strings)
|
def listified_tokenizer ( source ) : io_obj = io . StringIO ( source ) return [ list ( a ) for a in tokenize . generate_tokens ( io_obj . readline ) ]
| 1 |
python code to read a file and tokenize it
|
Tokenizes * source * and returns the tokens as a list of lists .
|
cosqa-train-14891
|
def listified_tokenizer(source):
"""Tokenizes *source* and returns the tokens as a list of lists."""
io_obj = io.StringIO(source)
return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]
|
def mean ( inlist ) : sum = 0 for item in inlist : sum = sum + item return sum / float ( len ( inlist ) )
| 0 |
average of elements in the list in python
|
Returns the arithematic mean of the values in the passed list . Assumes a 1D list but will function on the 1st dim of an array ( ! ) .
|
cosqa-train-14892
|
def mean(inlist):
"""
Returns the arithematic mean of the values in the passed list.
Assumes a '1D' list, but will function on the 1st dim of an array(!).
Usage: lmean(inlist)
"""
sum = 0
for item in inlist:
sum = sum + item
return sum / float(len(inlist))
|
def b ( s ) : return s if isinstance ( s , bytes ) else s . encode ( locale . getpreferredencoding ( ) )
| 1 |
python codecs decode encoding
|
Encodes Unicode strings to byte strings if necessary .
|
cosqa-train-14893
|
def b(s):
""" Encodes Unicode strings to byte strings, if necessary. """
return s if isinstance(s, bytes) else s.encode(locale.getpreferredencoding())
|
def create_alias ( self ) : LOG . info ( 'Creating alias %s' , self . env ) try : self . lambda_client . create_alias ( FunctionName = self . app_name , Name = self . env , FunctionVersion = '$LATEST' , Description = 'Alias for {}' . format ( self . env ) ) except boto3 . exceptions . botocore . exceptions . ClientError as error : LOG . debug ( 'Create alias error: %s' , error ) LOG . info ( "Alias creation failed. Retrying..." ) raise
| 0 |
aws lambda python access oracle
|
Create lambda alias with env name and points it to $LATEST .
|
cosqa-train-14894
|
def create_alias(self):
"""Create lambda alias with env name and points it to $LATEST."""
LOG.info('Creating alias %s', self.env)
try:
self.lambda_client.create_alias(
FunctionName=self.app_name,
Name=self.env,
FunctionVersion='$LATEST',
Description='Alias for {}'.format(self.env))
except boto3.exceptions.botocore.exceptions.ClientError as error:
LOG.debug('Create alias error: %s', error)
LOG.info("Alias creation failed. Retrying...")
raise
|
def alter_change_column ( self , table , column , field ) : return self . _update_column ( table , column , lambda a , b : b )
| 0 |
python codnitionally edit values of a column
|
Support change columns .
|
cosqa-train-14895
|
def alter_change_column(self, table, column, field):
"""Support change columns."""
return self._update_column(table, column, lambda a, b: b)
|
def create_aws_lambda ( ctx , bucket , region_name , aws_access_key_id , aws_secret_access_key ) : from canari . commands . create_aws_lambda import create_aws_lambda create_aws_lambda ( ctx . project , bucket , region_name , aws_access_key_id , aws_secret_access_key )
| 0 |
aws lambda script to call python frtom a3
|
Creates an AWS Chalice project for deployment to AWS Lambda .
|
cosqa-train-14896
|
def create_aws_lambda(ctx, bucket, region_name, aws_access_key_id, aws_secret_access_key):
"""Creates an AWS Chalice project for deployment to AWS Lambda."""
from canari.commands.create_aws_lambda import create_aws_lambda
create_aws_lambda(ctx.project, bucket, region_name, aws_access_key_id, aws_secret_access_key)
|
def rgba_bytes_tuple ( self , x ) : return tuple ( int ( u * 255.9999 ) for u in self . rgba_floats_tuple ( x ) )
| 1 |
python color not in tuple
|
Provides the color corresponding to value x in the form of a tuple ( R G B A ) with int values between 0 and 255 .
|
cosqa-train-14897
|
def rgba_bytes_tuple(self, x):
"""Provides the color corresponding to value `x` in the
form of a tuple (R,G,B,A) with int values between 0 and 255.
"""
return tuple(int(u*255.9999) for u in self.rgba_floats_tuple(x))
|
def list_rds ( region , filter_by_kwargs ) : conn = boto . rds . connect_to_region ( region ) instances = conn . get_all_dbinstances ( ) return lookup ( instances , filter_by = filter_by_kwargs )
| 0 |
aws python boto3 dynamodb get all items
|
List all RDS thingys .
|
cosqa-train-14898
|
def list_rds(region, filter_by_kwargs):
"""List all RDS thingys."""
conn = boto.rds.connect_to_region(region)
instances = conn.get_all_dbinstances()
return lookup(instances, filter_by=filter_by_kwargs)
|
def cmyk ( c , m , y , k ) : return Color ( "cmyk" , c , m , y , k )
| 1 |
python colors converter cmyk
|
Create a spectra . Color object in the CMYK color space .
|
cosqa-train-14899
|
def cmyk(c, m, y, k):
"""
Create a spectra.Color object in the CMYK color space.
:param float c: c coordinate.
:param float m: m coordinate.
:param float y: y coordinate.
:param float k: k coordinate.
:rtype: Color
:returns: A spectra.Color object in the CMYK color space.
"""
return Color("cmyk", c, m, y, k)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.