code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def solve(self):
"""Solve rpn expression, return None if not valid."""
popflag = True
self.tmpopslist = []
while True:
while self.opslist and popflag:
op = self.opslist.pop()
if self.is_variable(op):
op = self.variables.get(... | def function[solve, parameter[self]]:
constant[Solve rpn expression, return None if not valid.]
variable[popflag] assign[=] constant[True]
name[self].tmpopslist assign[=] list[[]]
while constant[True] begin[:]
while <ast.BoolOp object at 0x7da207f9a860> begin[:]
... | keyword[def] identifier[solve] ( identifier[self] ):
literal[string]
identifier[popflag] = keyword[True]
identifier[self] . identifier[tmpopslist] =[]
keyword[while] keyword[True] :
keyword[while] identifier[self] . identifier[opslist] keyword[and] identifier[pop... | def solve(self):
"""Solve rpn expression, return None if not valid."""
popflag = True
self.tmpopslist = []
while True:
while self.opslist and popflag:
op = self.opslist.pop()
if self.is_variable(op):
op = self.variables.get(op) # depends on [control=['if'... |
def parse_clubs(self, clubs_page):
"""Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes.
"""
character_info = self.parse_sidebar(clubs_page)... | def function[parse_clubs, parameter[self, clubs_page]]:
constant[Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes.
]
variable[chara... | keyword[def] identifier[parse_clubs] ( identifier[self] , identifier[clubs_page] ):
literal[string]
identifier[character_info] = identifier[self] . identifier[parse_sidebar] ( identifier[clubs_page] )
identifier[second_col] = identifier[clubs_page] . identifier[find] ( literal[string] ,{ literal[strin... | def parse_clubs(self, clubs_page):
"""Parses the DOM and returns character clubs attributes.
:type clubs_page: :class:`bs4.BeautifulSoup`
:param clubs_page: MAL character clubs page's DOM
:rtype: dict
:return: character clubs attributes.
"""
character_info = self.parse_sidebar(clubs_page)... |
def delete_group(self, group_id):
"""
Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
"""
response = self._perform_request(
url='/um/groups/%s' % group_id,
method='DELETE')
return response | def function[delete_group, parameter[self, group_id]]:
constant[
Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
]
variable[response] assign[=] call[name[self]._perform_request, parameter[]]
return[name[response]] | keyword[def] identifier[delete_group] ( identifier[self] , identifier[group_id] ):
literal[string]
identifier[response] = identifier[self] . identifier[_perform_request] (
identifier[url] = literal[string] % identifier[group_id] ,
identifier[method] = literal[string] )
k... | def delete_group(self, group_id):
"""
Removes a group.
:param group_id: The unique ID of the group.
:type group_id: ``str``
"""
response = self._perform_request(url='/um/groups/%s' % group_id, method='DELETE')
return response |
def create_history_model(self, model, inherited):
"""
Creates a historical model to associate with the model provided.
"""
attrs = {
"__module__": self.module,
"_history_excluded_fields": self.excluded_fields,
}
app_module = "%s.models" % model._m... | def function[create_history_model, parameter[self, model, inherited]]:
constant[
Creates a historical model to associate with the model provided.
]
variable[attrs] assign[=] dictionary[[<ast.Constant object at 0x7da20c6a82b0>, <ast.Constant object at 0x7da20c6a87f0>], [<ast.Attribute obj... | keyword[def] identifier[create_history_model] ( identifier[self] , identifier[model] , identifier[inherited] ):
literal[string]
identifier[attrs] ={
literal[string] : identifier[self] . identifier[module] ,
literal[string] : identifier[self] . identifier[excluded_fields] ,
... | def create_history_model(self, model, inherited):
"""
Creates a historical model to associate with the model provided.
"""
attrs = {'__module__': self.module, '_history_excluded_fields': self.excluded_fields}
app_module = '%s.models' % model._meta.app_label
if inherited:
# inheri... |
def load(image):
r"""
Loads the ``image`` and returns a ndarray with the image's pixel content as well as
a header object.
The header can, with restrictions, be used to extract additional meta-information
about the image (e.g. using the methods in `~medpy.io.Header`). Additionally
it serves... | def function[load, parameter[image]]:
constant[
Loads the ``image`` and returns a ndarray with the image's pixel content as well as
a header object.
The header can, with restrictions, be used to extract additional meta-information
about the image (e.g. using the methods in `~medpy.io.Header... | keyword[def] identifier[load] ( identifier[image] ):
literal[string]
identifier[logger] = identifier[Logger] . identifier[getInstance] ()
identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[image] ))
keyword[if] keyword[not] identifier[os] . identifier[pat... | def load(image):
"""
Loads the ``image`` and returns a ndarray with the image's pixel content as well as
a header object.
The header can, with restrictions, be used to extract additional meta-information
about the image (e.g. using the methods in `~medpy.io.Header`). Additionally
it serves ... |
def get_netconf_client_capabilities_input_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities")
config = get_netconf_client_capabilities
input = ET.SubElement(ge... | def function[get_netconf_client_capabilities_input_session_id, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_netconf_client_capabilities] assign[=] call[name[ET].Element, parameter[constant[get... | keyword[def] identifier[get_netconf_client_capabilities_input_session_id] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_netconf_client_capabilities] = identifier[ET] . identifier[Ele... | def get_netconf_client_capabilities_input_session_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_netconf_client_capabilities = ET.Element('get_netconf_client_capabilities')
config = get_netconf_client_capabilities
input = ET.SubElement(get_netconf_client_cap... |
def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):
"""Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one t... | def function[load_cifar10_dataset, parameter[shape, path, plotable]]:
constant[Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one... | keyword[def] identifier[load_cifar10_dataset] ( identifier[shape] =(- literal[int] , literal[int] , literal[int] , literal[int] ), identifier[path] = literal[string] , identifier[plotable] = keyword[False] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifi... | def load_cifar10_dataset(shape=(-1, 32, 32, 3), path='data', plotable=False):
"""Load CIFAR-10 dataset.
It consists of 60000 32x32 colour images in 10 classes, with
6000 images per class. There are 50000 training images and 10000 test images.
The dataset is divided into five training batches and one t... |
def _compute_partial_derivative_site_amp(self, C, pga1100, vs30):
"""
Partial derivative of site amplification term with respect to
PGA on rock (equation 26), as described in the errata and not
in the original paper.
"""
delta_amp = np.zeros_like(vs30)
vlin = C['V... | def function[_compute_partial_derivative_site_amp, parameter[self, C, pga1100, vs30]]:
constant[
Partial derivative of site amplification term with respect to
PGA on rock (equation 26), as described in the errata and not
in the original paper.
]
variable[delta_amp] assign... | keyword[def] identifier[_compute_partial_derivative_site_amp] ( identifier[self] , identifier[C] , identifier[pga1100] , identifier[vs30] ):
literal[string]
identifier[delta_amp] = identifier[np] . identifier[zeros_like] ( identifier[vs30] )
identifier[vlin] = identifier[C] [ literal[strin... | def _compute_partial_derivative_site_amp(self, C, pga1100, vs30):
"""
Partial derivative of site amplification term with respect to
PGA on rock (equation 26), as described in the errata and not
in the original paper.
"""
delta_amp = np.zeros_like(vs30)
vlin = C['VLIN']
c ... |
def load(self):
"""Load configuration from the defined locations."""
if not self.loaded:
self.values = configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS)
for path in self.locations():
try:
part = configobj.ConfigObj(infile=path, **self.DEFAULT... | def function[load, parameter[self]]:
constant[Load configuration from the defined locations.]
if <ast.UnaryOp object at 0x7da204347610> begin[:]
name[self].values assign[=] call[name[configobj].ConfigObj, parameter[dictionary[[], []]]]
for taget[name[path]] in starred[cal... | keyword[def] identifier[load] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[loaded] :
identifier[self] . identifier[values] = identifier[configobj] . identifier[ConfigObj] ({},** identifier[self] . identifier[DEFAULT_CONFIG_OPTS] )
... | def load(self):
"""Load configuration from the defined locations."""
if not self.loaded:
self.values = configobj.ConfigObj({}, **self.DEFAULT_CONFIG_OPTS)
for path in self.locations():
try:
part = configobj.ConfigObj(infile=path, **self.DEFAULT_CONFIG_OPTS) # depends... |
def remove_entity_layer(self):
"""
Removes the entity layer (if exists) of the object (in memory)
"""
if self.entity_layer is not None:
this_node = self.entity_layer.get_node()
self.root.remove(this_node)
self.entity_layer = None
if self.header... | def function[remove_entity_layer, parameter[self]]:
constant[
Removes the entity layer (if exists) of the object (in memory)
]
if compare[name[self].entity_layer is_not constant[None]] begin[:]
variable[this_node] assign[=] call[name[self].entity_layer.get_node, parameter... | keyword[def] identifier[remove_entity_layer] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[entity_layer] keyword[is] keyword[not] keyword[None] :
identifier[this_node] = identifier[self] . identifier[entity_layer] . identifier[get_node] ()
... | def remove_entity_layer(self):
"""
Removes the entity layer (if exists) of the object (in memory)
"""
if self.entity_layer is not None:
this_node = self.entity_layer.get_node()
self.root.remove(this_node)
self.entity_layer = None # depends on [control=['if'], data=[]]
... |
def extract_listing(pid):
"""Extract listing; return list of tuples (artist(s), title, label)."""
print("Extracting tracklisting...")
listing_etree = open_listing_page(pid + '/segments.inc')
track_divs = listing_etree.xpath('//div[@class="segment__track"]')
listing = []
for track_div in track_d... | def function[extract_listing, parameter[pid]]:
constant[Extract listing; return list of tuples (artist(s), title, label).]
call[name[print], parameter[constant[Extracting tracklisting...]]]
variable[listing_etree] assign[=] call[name[open_listing_page], parameter[binary_operation[name[pid] + con... | keyword[def] identifier[extract_listing] ( identifier[pid] ):
literal[string]
identifier[print] ( literal[string] )
identifier[listing_etree] = identifier[open_listing_page] ( identifier[pid] + literal[string] )
identifier[track_divs] = identifier[listing_etree] . identifier[xpath] ( literal[stri... | def extract_listing(pid):
"""Extract listing; return list of tuples (artist(s), title, label)."""
print('Extracting tracklisting...')
listing_etree = open_listing_page(pid + '/segments.inc')
track_divs = listing_etree.xpath('//div[@class="segment__track"]')
listing = []
for track_div in track_di... |
def update_roles_gce(use_cache=True, cache_expiration=86400, cache_path="~/.gcetools/instances", group_name=None, region=None, zone=None):
"""
Dynamically update fabric's roles by using assigning the tags associated with
each machine in Google Compute Engine.
use_cache - will store a local cache in ~/.... | def function[update_roles_gce, parameter[use_cache, cache_expiration, cache_path, group_name, region, zone]]:
constant[
Dynamically update fabric's roles by using assigning the tags associated with
each machine in Google Compute Engine.
use_cache - will store a local cache in ~/.gcetools/
cache... | keyword[def] identifier[update_roles_gce] ( identifier[use_cache] = keyword[True] , identifier[cache_expiration] = literal[int] , identifier[cache_path] = literal[string] , identifier[group_name] = keyword[None] , identifier[region] = keyword[None] , identifier[zone] = keyword[None] ):
literal[string]
iden... | def update_roles_gce(use_cache=True, cache_expiration=86400, cache_path='~/.gcetools/instances', group_name=None, region=None, zone=None):
"""
Dynamically update fabric's roles by using assigning the tags associated with
each machine in Google Compute Engine.
use_cache - will store a local cache in ~/.... |
def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalList, self).dispatch(*args, **kwargs) | def function[dispatch, parameter[self]]:
constant[This decorator sets this view to have restricted permissions.]
return[call[call[name[super], parameter[name[AnimalList], name[self]]].dispatch, parameter[<ast.Starred object at 0x7da20e74b2e0>]]] | keyword[def] identifier[dispatch] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[super] ( identifier[AnimalList] , identifier[self] ). identifier[dispatch] (* identifier[args] ,** identifier[kwargs] ) | def dispatch(self, *args, **kwargs):
"""This decorator sets this view to have restricted permissions."""
return super(AnimalList, self).dispatch(*args, **kwargs) |
def filter(self, table, group_types, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [group_type for group_type in group_types
if query in group_type.name.lower()] | def function[filter, parameter[self, table, group_types, filter_string]]:
constant[Naive case-insensitive search.]
variable[query] assign[=] call[name[filter_string].lower, parameter[]]
return[<ast.ListComp object at 0x7da1b18dd660>] | keyword[def] identifier[filter] ( identifier[self] , identifier[table] , identifier[group_types] , identifier[filter_string] ):
literal[string]
identifier[query] = identifier[filter_string] . identifier[lower] ()
keyword[return] [ identifier[group_type] keyword[for] identifier[group_type... | def filter(self, table, group_types, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [group_type for group_type in group_types if query in group_type.name.lower()] |
def standalone_from_launchable(cls, launch):
"""
Given a launchable resource, create a definition of a standalone
instance, which doesn't depend on or contain references to other
elements.
"""
attrs = copy.copy(launch.el_attrs)
# Remove attributes we overwrite / d... | def function[standalone_from_launchable, parameter[cls, launch]]:
constant[
Given a launchable resource, create a definition of a standalone
instance, which doesn't depend on or contain references to other
elements.
]
variable[attrs] assign[=] call[name[copy].copy, parame... | keyword[def] identifier[standalone_from_launchable] ( identifier[cls] , identifier[launch] ):
literal[string]
identifier[attrs] = identifier[copy] . identifier[copy] ( identifier[launch] . identifier[el_attrs] )
keyword[del] identifier[attrs] [ literal[string] ]
keyword[... | def standalone_from_launchable(cls, launch):
"""
Given a launchable resource, create a definition of a standalone
instance, which doesn't depend on or contain references to other
elements.
"""
attrs = copy.copy(launch.el_attrs)
# Remove attributes we overwrite / don't need
... |
def append(self, func, *args, **kwargs):
"""
add a task to the chain
takes the same parameters as async_task()
"""
self.chain.append((func, args, kwargs))
# remove existing results
if self.started:
delete_group(self.group)
self.started = Fa... | def function[append, parameter[self, func]]:
constant[
add a task to the chain
takes the same parameters as async_task()
]
call[name[self].chain.append, parameter[tuple[[<ast.Name object at 0x7da1b170ef20>, <ast.Name object at 0x7da1b170fd30>, <ast.Name object at 0x7da1b170d840>]... | keyword[def] identifier[append] ( identifier[self] , identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[chain] . identifier[append] (( identifier[func] , identifier[args] , identifier[kwargs] ))
keyword[if] identifier[self... | def append(self, func, *args, **kwargs):
"""
add a task to the chain
takes the same parameters as async_task()
"""
self.chain.append((func, args, kwargs))
# remove existing results
if self.started:
delete_group(self.group)
self.started = False # depends on [contr... |
def waitGetPoses(self, pRenderPoseArray, unRenderPoseArrayCount, pGamePoseArray, unGamePoseArrayCount):
"""
Scene applications should call this function to get poses to render with (and optionally poses predicted an additional frame out to use for gameplay).
This function will block until "runni... | def function[waitGetPoses, parameter[self, pRenderPoseArray, unRenderPoseArrayCount, pGamePoseArray, unGamePoseArrayCount]]:
constant[
Scene applications should call this function to get poses to render with (and optionally poses predicted an additional frame out to use for gameplay).
This funct... | keyword[def] identifier[waitGetPoses] ( identifier[self] , identifier[pRenderPoseArray] , identifier[unRenderPoseArrayCount] , identifier[pGamePoseArray] , identifier[unGamePoseArrayCount] ):
literal[string]
identifier[fn] = identifier[self] . identifier[function_table] . identifier[waitGetPoses] ... | def waitGetPoses(self, pRenderPoseArray, unRenderPoseArrayCount, pGamePoseArray, unGamePoseArrayCount):
"""
Scene applications should call this function to get poses to render with (and optionally poses predicted an additional frame out to use for gameplay).
This function will block until "running s... |
def force_invalidate(self, vts):
"""Force invalidation of a VersionedTargetSet."""
for vt in vts.versioned_targets:
self._invalidator.force_invalidate(vt.cache_key)
vt.valid = False
self._invalidator.force_invalidate(vts.cache_key)
vts.valid = False | def function[force_invalidate, parameter[self, vts]]:
constant[Force invalidation of a VersionedTargetSet.]
for taget[name[vt]] in starred[name[vts].versioned_targets] begin[:]
call[name[self]._invalidator.force_invalidate, parameter[name[vt].cache_key]]
name[vt].valid as... | keyword[def] identifier[force_invalidate] ( identifier[self] , identifier[vts] ):
literal[string]
keyword[for] identifier[vt] keyword[in] identifier[vts] . identifier[versioned_targets] :
identifier[self] . identifier[_invalidator] . identifier[force_invalidate] ( identifier[vt] . identifier[cach... | def force_invalidate(self, vts):
"""Force invalidation of a VersionedTargetSet."""
for vt in vts.versioned_targets:
self._invalidator.force_invalidate(vt.cache_key)
vt.valid = False # depends on [control=['for'], data=['vt']]
self._invalidator.force_invalidate(vts.cache_key)
vts.valid =... |
def get_slice_location(dcmdata, teil=None):
""" get location of the slice
:param dcmdata: dicom data structure
:param teil: filename. Used when slice location doesnt exist
:return:
"""
slice_location = None
if hasattr(dcmdata, 'SliceLocation'):
# print(dcmdata.SliceLocation)
... | def function[get_slice_location, parameter[dcmdata, teil]]:
constant[ get location of the slice
:param dcmdata: dicom data structure
:param teil: filename. Used when slice location doesnt exist
:return:
]
variable[slice_location] assign[=] constant[None]
if call[name[hasattr], p... | keyword[def] identifier[get_slice_location] ( identifier[dcmdata] , identifier[teil] = keyword[None] ):
literal[string]
identifier[slice_location] = keyword[None]
keyword[if] identifier[hasattr] ( identifier[dcmdata] , literal[string] ):
keyword[try] :
identifier[slic... | def get_slice_location(dcmdata, teil=None):
""" get location of the slice
:param dcmdata: dicom data structure
:param teil: filename. Used when slice location doesnt exist
:return:
"""
slice_location = None
if hasattr(dcmdata, 'SliceLocation'):
# print(dcmdata.SliceLocation)
... |
def mcycle(return_X_y=True):
"""motorcyle acceleration dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame... | def function[mcycle, parameter[return_X_y]]:
constant[motorcyle acceleration dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
... | keyword[def] identifier[mcycle] ( identifier[return_X_y] = keyword[True] ):
literal[string]
identifier[motor] = identifier[pd] . identifier[read_csv] ( identifier[PATH] + literal[string] , identifier[index_col] = literal[int] )
keyword[if] identifier[return_X_y] :
identifier[X] = i... | def mcycle(return_X_y=True):
"""motorcyle acceleration dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame... |
def tar(self):
"""tar in bytes format"""
if not self.generated:
for data in self.generate():
pass
return self._tar_buffer.getvalue() | def function[tar, parameter[self]]:
constant[tar in bytes format]
if <ast.UnaryOp object at 0x7da1b15947c0> begin[:]
for taget[name[data]] in starred[call[name[self].generate, parameter[]]] begin[:]
pass
return[call[name[self]._tar_buffer.getvalue, parameter[]]] | keyword[def] identifier[tar] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[generated] :
keyword[for] identifier[data] keyword[in] identifier[self] . identifier[generate] ():
keyword[pass]
keyword[return] id... | def tar(self):
"""tar in bytes format"""
if not self.generated:
for data in self.generate():
pass # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
return self._tar_buffer.getvalue() |
def SetConsoleTextAttribute(stream_id, attrs):
"""Set a console text attribute."""
handle = handles[stream_id]
return windll.kernel32.SetConsoleTextAttribute(handle, attrs) | def function[SetConsoleTextAttribute, parameter[stream_id, attrs]]:
constant[Set a console text attribute.]
variable[handle] assign[=] call[name[handles]][name[stream_id]]
return[call[name[windll].kernel32.SetConsoleTextAttribute, parameter[name[handle], name[attrs]]]] | keyword[def] identifier[SetConsoleTextAttribute] ( identifier[stream_id] , identifier[attrs] ):
literal[string]
identifier[handle] = identifier[handles] [ identifier[stream_id] ]
keyword[return] identifier[windll] . identifier[kernel32] . identifier[SetConsoleTextAttribute] ( identifier[handle] , ide... | def SetConsoleTextAttribute(stream_id, attrs):
"""Set a console text attribute."""
handle = handles[stream_id]
return windll.kernel32.SetConsoleTextAttribute(handle, attrs) |
def _storeSample(self, inputVector, trueCatIndex, partition=0):
"""
Store a training sample and associated category label
"""
# If this is the first sample, then allocate a numpy array
# of the appropriate size in which to store all samples.
if self._samples is None:
self._samples = numpy... | def function[_storeSample, parameter[self, inputVector, trueCatIndex, partition]]:
constant[
Store a training sample and associated category label
]
if compare[name[self]._samples is constant[None]] begin[:]
name[self]._samples assign[=] call[name[numpy].zeros, parameter[tuple[[<... | keyword[def] identifier[_storeSample] ( identifier[self] , identifier[inputVector] , identifier[trueCatIndex] , identifier[partition] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[_samples] keyword[is] keyword[None] :
identifier[self] . identifier[_samples... | def _storeSample(self, inputVector, trueCatIndex, partition=0):
"""
Store a training sample and associated category label
"""
# If this is the first sample, then allocate a numpy array
# of the appropriate size in which to store all samples.
if self._samples is None:
self._samples = nump... |
def Read(self, file_object):
"""Reads a plist from a file-like object.
Args:
file_object (dfvfs.FileIO): a file-like object containing plist data.
Raises:
IOError: if the plist file-like object cannot be read.
OSError: if the plist file-like object cannot be read.
"""
try:
... | def function[Read, parameter[self, file_object]]:
constant[Reads a plist from a file-like object.
Args:
file_object (dfvfs.FileIO): a file-like object containing plist data.
Raises:
IOError: if the plist file-like object cannot be read.
OSError: if the plist file-like object cannot b... | keyword[def] identifier[Read] ( identifier[self] , identifier[file_object] ):
literal[string]
keyword[try] :
identifier[self] . identifier[root_key] = identifier[biplist] . identifier[readPlist] ( identifier[file_object] )
keyword[except] (
identifier[biplist] . identifier[NotBinaryPlistE... | def Read(self, file_object):
"""Reads a plist from a file-like object.
Args:
file_object (dfvfs.FileIO): a file-like object containing plist data.
Raises:
IOError: if the plist file-like object cannot be read.
OSError: if the plist file-like object cannot be read.
"""
try:
... |
def _speak_none_inherit(self, element):
"""
No speak any content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
self._isolate_text_node(element)
self._visit(element, self._speak_none) | def function[_speak_none_inherit, parameter[self, element]]:
constant[
No speak any content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
]
call[name[self]._isolate_text_node, parameter[name[eleme... | keyword[def] identifier[_speak_none_inherit] ( identifier[self] , identifier[element] ):
literal[string]
identifier[self] . identifier[_isolate_text_node] ( identifier[element] )
identifier[self] . identifier[_visit] ( identifier[element] , identifier[self] . identifier[_speak_none] ) | def _speak_none_inherit(self, element):
"""
No speak any content of element and descendants.
:param element: The element.
:type element: hatemile.util.html.htmldomelement.HTMLDOMElement
"""
self._isolate_text_node(element)
self._visit(element, self._speak_none) |
def save_as(self):
"""Dialog for getting name, location of dataset export."""
filename = splitext(self.filename)[0]
filename, _ = QFileDialog.getSaveFileName(self, 'Export events',
filename)
if filename == '':
return
... | def function[save_as, parameter[self]]:
constant[Dialog for getting name, location of dataset export.]
variable[filename] assign[=] call[call[name[splitext], parameter[name[self].filename]]][constant[0]]
<ast.Tuple object at 0x7da1b0e8f7f0> assign[=] call[name[QFileDialog].getSaveFileName, param... | keyword[def] identifier[save_as] ( identifier[self] ):
literal[string]
identifier[filename] = identifier[splitext] ( identifier[self] . identifier[filename] )[ literal[int] ]
identifier[filename] , identifier[_] = identifier[QFileDialog] . identifier[getSaveFileName] ( identifier[self] , l... | def save_as(self):
"""Dialog for getting name, location of dataset export."""
filename = splitext(self.filename)[0]
(filename, _) = QFileDialog.getSaveFileName(self, 'Export events', filename)
if filename == '':
return # depends on [control=['if'], data=[]]
self.filename = filename
shor... |
def add_record_set(self, record_set):
"""Append a record set to the 'additions' for the change set.
:type record_set:
:class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:param record_set: the record set to append.
:raises: ``ValueError`` if ``record_set`` is no... | def function[add_record_set, parameter[self, record_set]]:
constant[Append a record set to the 'additions' for the change set.
:type record_set:
:class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:param record_set: the record set to append.
:raises: ``ValueErro... | keyword[def] identifier[add_record_set] ( identifier[self] , identifier[record_set] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[record_set] , identifier[ResourceRecordSet] ):
keyword[raise] identifier[ValueError] ( literal[string] )
ident... | def add_record_set(self, record_set):
"""Append a record set to the 'additions' for the change set.
:type record_set:
:class:`google.cloud.dns.resource_record_set.ResourceRecordSet`
:param record_set: the record set to append.
:raises: ``ValueError`` if ``record_set`` is not of... |
def normalize_api_url(self):
"""
Checks that the API URL used to initialize this object actually returns
JSON. If it doesn't, make some educated guesses and try to find the
correct URL.
:returns: a valid API URL or ``None``
"""
def tester(self, api_url):
... | def function[normalize_api_url, parameter[self]]:
constant[
Checks that the API URL used to initialize this object actually returns
JSON. If it doesn't, make some educated guesses and try to find the
correct URL.
:returns: a valid API URL or ``None``
]
def functi... | keyword[def] identifier[normalize_api_url] ( identifier[self] ):
literal[string]
keyword[def] identifier[tester] ( identifier[self] , identifier[api_url] ):
literal[string]
identifier[data] = identifier[self] . identifier[_fetch_http] ( identifier[api_url] ,{ literal[str... | def normalize_api_url(self):
"""
Checks that the API URL used to initialize this object actually returns
JSON. If it doesn't, make some educated guesses and try to find the
correct URL.
:returns: a valid API URL or ``None``
"""
def tester(self, api_url):
"""
... |
def write_dicts_to_json(self, data):
"""Saves .json file with data
:param data: Data
"""
with open(self.path, "w") as out:
json.dump(
data, # data
out, # file handler
indent=4, sort_keys=True # pretty print
) | def function[write_dicts_to_json, parameter[self, data]]:
constant[Saves .json file with data
:param data: Data
]
with call[name[open], parameter[name[self].path, constant[w]]] begin[:]
call[name[json].dump, parameter[name[data], name[out]]] | keyword[def] identifier[write_dicts_to_json] ( identifier[self] , identifier[data] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[path] , literal[string] ) keyword[as] identifier[out] :
identifier[json] . identifier[dump] (
identifier[d... | def write_dicts_to_json(self, data):
"""Saves .json file with data
:param data: Data
"""
with open(self.path, 'w') as out: # data
# file handler
# pretty print
json.dump(data, out, indent=4, sort_keys=True) # depends on [control=['with'], data=['out']] |
def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None):
"""Sends the smart email."""
validate_consent_to_track(consent_to_track)
body = {
"To": to,
"CC": cc,
"BCC": bcc,
... | def function[smart_email_send, parameter[self, smart_email_id, to, consent_to_track, cc, bcc, attachments, data, add_recipients_to_list]]:
constant[Sends the smart email.]
call[name[validate_consent_to_track], parameter[name[consent_to_track]]]
variable[body] assign[=] dictionary[[<ast.Constant ... | keyword[def] identifier[smart_email_send] ( identifier[self] , identifier[smart_email_id] , identifier[to] , identifier[consent_to_track] , identifier[cc] = keyword[None] , identifier[bcc] = keyword[None] , identifier[attachments] = keyword[None] , identifier[data] = keyword[None] , identifier[add_recipients_to_list]... | def smart_email_send(self, smart_email_id, to, consent_to_track, cc=None, bcc=None, attachments=None, data=None, add_recipients_to_list=None):
"""Sends the smart email."""
validate_consent_to_track(consent_to_track)
body = {'To': to, 'CC': cc, 'BCC': bcc, 'Attachments': attachments, 'Data': data, 'AddRecipi... |
def find_font(face, bold, italic):
"""Find font"""
bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR
italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN
face = face.encode('utf8')
fontconfig.FcInit()
pattern = fontconfig.FcPatternCreate()
fontconfig.FcPatternAddInteger(pattern, FC_WEIG... | def function[find_font, parameter[face, bold, italic]]:
constant[Find font]
variable[bold] assign[=] <ast.IfExp object at 0x7da1b0ebd570>
variable[italic] assign[=] <ast.IfExp object at 0x7da1b0ebdba0>
variable[face] assign[=] call[name[face].encode, parameter[constant[utf8]]]
ca... | keyword[def] identifier[find_font] ( identifier[face] , identifier[bold] , identifier[italic] ):
literal[string]
identifier[bold] = identifier[FC_WEIGHT_BOLD] keyword[if] identifier[bold] keyword[else] identifier[FC_WEIGHT_REGULAR]
identifier[italic] = identifier[FC_SLANT_ITALIC] keyword[if] id... | def find_font(face, bold, italic):
"""Find font"""
bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR
italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN
face = face.encode('utf8')
fontconfig.FcInit()
pattern = fontconfig.FcPatternCreate()
fontconfig.FcPatternAddInteger(pattern, FC_WEIG... |
def clean_query(self):
"""
Removes any `None` value from an elasticsearch query.
"""
if self.query:
for key, value in self.query.items():
if isinstance(value, list) and None in value:
self.query[key] = [v for v in value if v is not None] | def function[clean_query, parameter[self]]:
constant[
Removes any `None` value from an elasticsearch query.
]
if name[self].query begin[:]
for taget[tuple[[<ast.Name object at 0x7da1b0a70070>, <ast.Name object at 0x7da1b0a70880>]]] in starred[call[name[self].query.items, ... | keyword[def] identifier[clean_query] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[query] :
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[self] . identifier[query] . identifier[items] ():
keyword[if] iden... | def clean_query(self):
"""
Removes any `None` value from an elasticsearch query.
"""
if self.query:
for (key, value) in self.query.items():
if isinstance(value, list) and None in value:
self.query[key] = [v for v in value if v is not None] # depends on [contr... |
def setResponseFromWSAddress(self, address, localURL):
'''Server-side has to set these fields in response.
address -- Address instance, representing a WS-Address
'''
self.From = localURL
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
... | def function[setResponseFromWSAddress, parameter[self, address, localURL]]:
constant[Server-side has to set these fields in response.
address -- Address instance, representing a WS-Address
]
name[self].From assign[=] name[localURL]
name[self].header_pyobjs assign[=] constant[None... | keyword[def] identifier[setResponseFromWSAddress] ( identifier[self] , identifier[address] , identifier[localURL] ):
literal[string]
identifier[self] . identifier[From] = identifier[localURL]
identifier[self] . identifier[header_pyobjs] = keyword[None]
identifier[pyobjs] =[]
... | def setResponseFromWSAddress(self, address, localURL):
"""Server-side has to set these fields in response.
address -- Address instance, representing a WS-Address
"""
self.From = localURL
self.header_pyobjs = None
pyobjs = []
namespaceURI = self.wsAddressURI
for (nsuri, name, valu... |
async def update_contents(self, **params):
"""Updates users content row
Accepts:
- txid
- cid
- description
- write_price
- read_price
- confirmed
- coinid
"""
if params.get("message"):
params = json.loads(params.get("message", "{}"))
if not params:
return {"error":400, "reason":"Missed r... | <ast.AsyncFunctionDef object at 0x7da237eee740> | keyword[async] keyword[def] identifier[update_contents] ( identifier[self] ,** identifier[params] ):
literal[string]
keyword[if] identifier[params] . identifier[get] ( literal[string] ):
identifier[params] = identifier[json] . identifier[loads] ( identifier[params] . identifier[get] ( literal[string] , l... | async def update_contents(self, **params):
"""Updates users content row
Accepts:
- txid
- cid
- description
- write_price
- read_price
- confirmed
- coinid
"""
if params.get('message'):
params = json.loads(params.get('message', '{}')) # depends on [control=['if'], data=[]]
if not ... |
def save(self, path):
''' Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
'''
# IMPORTANT WARNING: saves entire source video
self.clip.write_videofile... | def function[save, parameter[self, path]]:
constant[ Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
]
call[name[self].clip.write_videofile, parameter[name[pa... | keyword[def] identifier[save] ( identifier[self] , identifier[path] ):
literal[string]
identifier[self] . identifier[clip] . identifier[write_videofile] ( identifier[path] , identifier[audio_fps] = identifier[self] . identifier[clip] . identifier[audio] . identifier[fps] ) | def save(self, path):
""" Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
"""
# IMPORTANT WARNING: saves entire source video
self.clip.write_videofile(path, audio... |
def _get_dbid2goids(associations):
"""Return gene2go data for user-specified taxids."""
id2gos = cx.defaultdict(set)
for ntd in associations:
id2gos[ntd.DB_ID].add(ntd.GO_ID)
return dict(id2gos) | def function[_get_dbid2goids, parameter[associations]]:
constant[Return gene2go data for user-specified taxids.]
variable[id2gos] assign[=] call[name[cx].defaultdict, parameter[name[set]]]
for taget[name[ntd]] in starred[name[associations]] begin[:]
call[call[name[id2gos]][name[n... | keyword[def] identifier[_get_dbid2goids] ( identifier[associations] ):
literal[string]
identifier[id2gos] = identifier[cx] . identifier[defaultdict] ( identifier[set] )
keyword[for] identifier[ntd] keyword[in] identifier[associations] :
identifier[id2gos] [ identifier[ntd] ... | def _get_dbid2goids(associations):
"""Return gene2go data for user-specified taxids."""
id2gos = cx.defaultdict(set)
for ntd in associations:
id2gos[ntd.DB_ID].add(ntd.GO_ID) # depends on [control=['for'], data=['ntd']]
return dict(id2gos) |
def get(name, download=False, install=False):
'''
.. versionadded:: 2017.7.0
Returns details for the named update
Args:
name (str):
The name of the update you're searching for. This can be the GUID, a
KB number, or any part of the name of the update. GUIDs and KBs are
... | def function[get, parameter[name, download, install]]:
constant[
.. versionadded:: 2017.7.0
Returns details for the named update
Args:
name (str):
The name of the update you're searching for. This can be the GUID, a
KB number, or any part of the name of the update.... | keyword[def] identifier[get] ( identifier[name] , identifier[download] = keyword[False] , identifier[install] = keyword[False] ):
literal[string]
identifier[wua] = identifier[salt] . identifier[utils] . identifier[win_update] . identifier[WindowsUpdateAgent] ()
identifier[updates] = identif... | def get(name, download=False, install=False):
"""
.. versionadded:: 2017.7.0
Returns details for the named update
Args:
name (str):
The name of the update you're searching for. This can be the GUID, a
KB number, or any part of the name of the update. GUIDs and KBs are
... |
def detranslify(text):
"""Detranslify russian text"""
try:
res = translit.detranslify(text)
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text}
return res | def function[detranslify, parameter[text]]:
constant[Detranslify russian text]
<ast.Try object at 0x7da1b0ebdc60>
return[name[res]] | keyword[def] identifier[detranslify] ( identifier[text] ):
literal[string]
keyword[try] :
identifier[res] = identifier[translit] . identifier[detranslify] ( identifier[text] )
keyword[except] identifier[Exception] keyword[as] identifier[err] :
identifier[res] = identifier[def... | def detranslify(text):
"""Detranslify russian text"""
try:
res = translit.detranslify(text) # depends on [control=['try'], data=[]]
except Exception as err:
# because filter must die silently
res = default_value % {'error': err, 'value': text} # depends on [control=['except'], data... |
def add(self, tipo_opcao, nome_opcao):
"""Inserts a new Option Pool and returns its identifier.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:param nome_opcao_txt: Name Option. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:re... | def function[add, parameter[self, tipo_opcao, nome_opcao]]:
constant[Inserts a new Option Pool and returns its identifier.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\_-]
:param nome_opcao_txt: Name Option. String with a maximum of 50 characters and respe... | keyword[def] identifier[add] ( identifier[self] , identifier[tipo_opcao] , identifier[nome_opcao] ):
literal[string]
identifier[url] = literal[string]
keyword[return] identifier[self] . identifier[post] ( identifier[url] ,{ literal[string] : identifier[tipo_o... | def add(self, tipo_opcao, nome_opcao):
"""Inserts a new Option Pool and returns its identifier.
:param tipo_opcao: Type. String with a maximum of 50 characters and respect [a-zA-Z\\_-]
:param nome_opcao_txt: Name Option. String with a maximum of 50 characters and respect [a-zA-Z\\_-]
:retu... |
def task_submission_options(f):
"""
Options shared by both transfer and delete task submission
"""
def notify_opt_callback(ctx, param, value):
"""
Parse --notify
- "" is the same as "off"
- parse by lowercase, comma-split, strip spaces
- "off,x" is invalid for an... | def function[task_submission_options, parameter[f]]:
constant[
Options shared by both transfer and delete task submission
]
def function[notify_opt_callback, parameter[ctx, param, value]]:
constant[
Parse --notify
- "" is the same as "off"
- parse by lower... | keyword[def] identifier[task_submission_options] ( identifier[f] ):
literal[string]
keyword[def] identifier[notify_opt_callback] ( identifier[ctx] , identifier[param] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
... | def task_submission_options(f):
"""
Options shared by both transfer and delete task submission
"""
def notify_opt_callback(ctx, param, value):
"""
Parse --notify
- "" is the same as "off"
- parse by lowercase, comma-split, strip spaces
- "off,x" is invalid for an... |
def _list_store_resources(self, request, head_id, filter_ids,
resource_fetcher, block_xform):
"""Builds a list of blocks or resources derived from blocks,
handling multiple possible filter requests:
- filtered by a set of ids
- filtered by head block... | def function[_list_store_resources, parameter[self, request, head_id, filter_ids, resource_fetcher, block_xform]]:
constant[Builds a list of blocks or resources derived from blocks,
handling multiple possible filter requests:
- filtered by a set of ids
- filtered by head block
... | keyword[def] identifier[_list_store_resources] ( identifier[self] , identifier[request] , identifier[head_id] , identifier[filter_ids] ,
identifier[resource_fetcher] , identifier[block_xform] ):
literal[string]
identifier[resources] =[]
keyword[if] identifier[filter_ids] keywo... | def _list_store_resources(self, request, head_id, filter_ids, resource_fetcher, block_xform):
"""Builds a list of blocks or resources derived from blocks,
handling multiple possible filter requests:
- filtered by a set of ids
- filtered by head block
- filtered by both id... |
def _normalize_sv_coverage_cnvkit(group_id, inputs, backgrounds, work_dir, back_files, out_files):
"""Normalize CNV coverage depths by GC, repeats and background using CNVkit
- reference: calculates reference backgrounds from normals and pools
including GC and repeat information
- fix: Uses backgroun... | def function[_normalize_sv_coverage_cnvkit, parameter[group_id, inputs, backgrounds, work_dir, back_files, out_files]]:
constant[Normalize CNV coverage depths by GC, repeats and background using CNVkit
- reference: calculates reference backgrounds from normals and pools
including GC and repeat inform... | keyword[def] identifier[_normalize_sv_coverage_cnvkit] ( identifier[group_id] , identifier[inputs] , identifier[backgrounds] , identifier[work_dir] , identifier[back_files] , identifier[out_files] ):
literal[string]
keyword[from] identifier[bcbio] . identifier[structural] keyword[import] identifier[cnvk... | def _normalize_sv_coverage_cnvkit(group_id, inputs, backgrounds, work_dir, back_files, out_files):
"""Normalize CNV coverage depths by GC, repeats and background using CNVkit
- reference: calculates reference backgrounds from normals and pools
including GC and repeat information
- fix: Uses backgroun... |
def iter_sers(self):
"""
Generate each ``<c:ser>`` child element in this xChart in
c:order/@val sequence (not document or c:idx order).
"""
def ser_order(ser):
return ser.order.val
return (ser for ser in sorted(self.xpath('./c:ser'), key=ser_order)) | def function[iter_sers, parameter[self]]:
constant[
Generate each ``<c:ser>`` child element in this xChart in
c:order/@val sequence (not document or c:idx order).
]
def function[ser_order, parameter[ser]]:
return[name[ser].order.val]
return[<ast.GeneratorExp object at... | keyword[def] identifier[iter_sers] ( identifier[self] ):
literal[string]
keyword[def] identifier[ser_order] ( identifier[ser] ):
keyword[return] identifier[ser] . identifier[order] . identifier[val]
keyword[return] ( identifier[ser] keyword[for] identifier[ser] keyword[... | def iter_sers(self):
"""
Generate each ``<c:ser>`` child element in this xChart in
c:order/@val sequence (not document or c:idx order).
"""
def ser_order(ser):
return ser.order.val
return (ser for ser in sorted(self.xpath('./c:ser'), key=ser_order)) |
def _configure_from_module(self, item):
"""Configure from a module by import path.
Effectively, you give this an absolute or relative import path, it will
import it, and then pass the resulting object to
``_configure_from_object``.
Args:
item (str):
... | def function[_configure_from_module, parameter[self, item]]:
constant[Configure from a module by import path.
Effectively, you give this an absolute or relative import path, it will
import it, and then pass the resulting object to
``_configure_from_object``.
Args:
i... | keyword[def] identifier[_configure_from_module] ( identifier[self] , identifier[item] ):
literal[string]
identifier[package] = keyword[None]
keyword[if] identifier[item] [ literal[int] ]== literal[string] :
identifier[package] = identifier[self] . identifier[import_name]
... | def _configure_from_module(self, item):
"""Configure from a module by import path.
Effectively, you give this an absolute or relative import path, it will
import it, and then pass the resulting object to
``_configure_from_object``.
Args:
item (str):
A st... |
def get_reference_line_numeration_marker_patterns(prefix=u''):
"""Return a list of compiled regex patterns used to search for the marker.
Marker of a reference line in a full-text document.
:param prefix: (string) the possible prefix to a reference line
:return: (list) of compiled regex patterns.
... | def function[get_reference_line_numeration_marker_patterns, parameter[prefix]]:
constant[Return a list of compiled regex patterns used to search for the marker.
Marker of a reference line in a full-text document.
:param prefix: (string) the possible prefix to a reference line
:return: (list) of co... | keyword[def] identifier[get_reference_line_numeration_marker_patterns] ( identifier[prefix] = literal[string] ):
literal[string]
identifier[title] = literal[string]
keyword[if] identifier[type] ( identifier[prefix] ) keyword[in] ( identifier[str] , identifier[unicode] ):
identifier[title] =... | def get_reference_line_numeration_marker_patterns(prefix=u''):
"""Return a list of compiled regex patterns used to search for the marker.
Marker of a reference line in a full-text document.
:param prefix: (string) the possible prefix to a reference line
:return: (list) of compiled regex patterns.
... |
def list_of_matching(self, tup_tree, matched):
"""
Parse only the children of particular types defined in the list/tuple
matched under tup_tree.
Other children are ignored rather than giving an error.
"""
result = []
for child in kids(tup_tree):
if ... | def function[list_of_matching, parameter[self, tup_tree, matched]]:
constant[
Parse only the children of particular types defined in the list/tuple
matched under tup_tree.
Other children are ignored rather than giving an error.
]
variable[result] assign[=] list[[]]
... | keyword[def] identifier[list_of_matching] ( identifier[self] , identifier[tup_tree] , identifier[matched] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[child] keyword[in] identifier[kids] ( identifier[tup_tree] ):
keyword[if] identifier[name] ( identi... | def list_of_matching(self, tup_tree, matched):
"""
Parse only the children of particular types defined in the list/tuple
matched under tup_tree.
Other children are ignored rather than giving an error.
"""
result = []
for child in kids(tup_tree):
if name(child) not in... |
def walk(self):
""" Generate paths in "self.datapath".
"""
# FIFO?
if self._fifo:
if self._fifo > 1:
raise RuntimeError("INTERNAL ERROR: FIFO read twice!")
self._fifo += 1
# Read paths relative to directory containing the FIFO
... | def function[walk, parameter[self]]:
constant[ Generate paths in "self.datapath".
]
if name[self]._fifo begin[:]
if compare[name[self]._fifo greater[>] constant[1]] begin[:]
<ast.Raise object at 0x7da1b26adb70>
<ast.AugAssign object at 0x7da1b26aea10>
... | keyword[def] identifier[walk] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_fifo] :
keyword[if] identifier[self] . identifier[_fifo] > literal[int] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
... | def walk(self):
""" Generate paths in "self.datapath".
"""
# FIFO?
if self._fifo:
if self._fifo > 1:
raise RuntimeError('INTERNAL ERROR: FIFO read twice!') # depends on [control=['if'], data=[]]
self._fifo += 1
# Read paths relative to directory containing the FI... |
def get_scenario_data(scenario_id,**kwargs):
"""
Get all the datasets from the group with the specified name
@returns a list of dictionaries
"""
user_id = kwargs.get('user_id')
scenario_data = db.DBSession.query(Dataset).filter(Dataset.id==ResourceScenario.dataset_id, ResourceScenario.s... | def function[get_scenario_data, parameter[scenario_id]]:
constant[
Get all the datasets from the group with the specified name
@returns a list of dictionaries
]
variable[user_id] assign[=] call[name[kwargs].get, parameter[constant[user_id]]]
variable[scenario_data] assign[=] ... | keyword[def] identifier[get_scenario_data] ( identifier[scenario_id] ,** identifier[kwargs] ):
literal[string]
identifier[user_id] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[scenario_data] = identifier[db] . identifier[DBSession] . identifier[query] ( identifier[Dataset] ).... | def get_scenario_data(scenario_id, **kwargs):
"""
Get all the datasets from the group with the specified name
@returns a list of dictionaries
"""
user_id = kwargs.get('user_id')
scenario_data = db.DBSession.query(Dataset).filter(Dataset.id == ResourceScenario.dataset_id, ResourceScenario... |
def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
... | def function[add_plugin_arguments, parameter[self, parser]]:
constant[Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
]
for taget[name[manager]] in starred[call[name[self].hook_man... | keyword[def] identifier[add_plugin_arguments] ( identifier[self] , identifier[parser] ):
literal[string]
keyword[for] identifier[manager] keyword[in] identifier[self] . identifier[hook_managers] . identifier[values] ():
keyword[if] identifier[len] ( identifier[list] ( identifier[ma... | def add_plugin_arguments(self, parser):
"""Add plugin arguments to argument parser.
Parameters
----------
parser : argparse.ArgumentParser
The main haas ArgumentParser.
"""
for manager in self.hook_managers.values():
if len(list(manager)) == 0:
c... |
def run0(self):
"""Run one item (a callback or an RPC wait_any).
Returns:
A time to sleep if something happened (may be 0);
None if all queues are empty.
"""
if self.current:
self.inactive = 0
callback, args, kwds = self.current.popleft()
_logging_debug('nowevent: %s', cal... | def function[run0, parameter[self]]:
constant[Run one item (a callback or an RPC wait_any).
Returns:
A time to sleep if something happened (may be 0);
None if all queues are empty.
]
if name[self].current begin[:]
name[self].inactive assign[=] constant[0]
... | keyword[def] identifier[run0] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[current] :
identifier[self] . identifier[inactive] = literal[int]
identifier[callback] , identifier[args] , identifier[kwds] = identifier[self] . identifier[current] . identifier[po... | def run0(self):
"""Run one item (a callback or an RPC wait_any).
Returns:
A time to sleep if something happened (may be 0);
None if all queues are empty.
"""
if self.current:
self.inactive = 0
(callback, args, kwds) = self.current.popleft()
_logging_debug('nowevent: ... |
def get_private_and_public(username, password_verifier, private, preset):
"""Print out server public and private."""
session = SRPServerSession(
SRPContext(username, prime=preset[0], generator=preset[1]),
hex_from_b64(password_verifier), private=private)
click.secho('Server private: %s' % s... | def function[get_private_and_public, parameter[username, password_verifier, private, preset]]:
constant[Print out server public and private.]
variable[session] assign[=] call[name[SRPServerSession], parameter[call[name[SRPContext], parameter[name[username]]], call[name[hex_from_b64], parameter[name[pass... | keyword[def] identifier[get_private_and_public] ( identifier[username] , identifier[password_verifier] , identifier[private] , identifier[preset] ):
literal[string]
identifier[session] = identifier[SRPServerSession] (
identifier[SRPContext] ( identifier[username] , identifier[prime] = identifier[prese... | def get_private_and_public(username, password_verifier, private, preset):
"""Print out server public and private."""
session = SRPServerSession(SRPContext(username, prime=preset[0], generator=preset[1]), hex_from_b64(password_verifier), private=private)
click.secho('Server private: %s' % session.private_b64... |
async def send_offnetwork_invitation(
self, send_offnetwork_invitation_request
):
"""Send an email to invite a non-Google contact to Hangouts."""
response = hangouts_pb2.SendOffnetworkInvitationResponse()
await self._pb_request('devices/sendoffnetworkinvitation',
... | <ast.AsyncFunctionDef object at 0x7da207f98d90> | keyword[async] keyword[def] identifier[send_offnetwork_invitation] (
identifier[self] , identifier[send_offnetwork_invitation_request]
):
literal[string]
identifier[response] = identifier[hangouts_pb2] . identifier[SendOffnetworkInvitationResponse] ()
keyword[await] identifier[self] . ... | async def send_offnetwork_invitation(self, send_offnetwork_invitation_request):
"""Send an email to invite a non-Google contact to Hangouts."""
response = hangouts_pb2.SendOffnetworkInvitationResponse()
await self._pb_request('devices/sendoffnetworkinvitation', send_offnetwork_invitation_request, response)
... |
def read_named_csv(name, data_path=DATA_PATH, nrows=None, verbose=True):
""" Convert a dataset in a local file (usually a CSV) into a Pandas DataFrame
TODO: should be called read_named_dataset
Args:
`name` is assumed not to have an extension (like ".csv"), alternative extensions are tried automaticall... | def function[read_named_csv, parameter[name, data_path, nrows, verbose]]:
constant[ Convert a dataset in a local file (usually a CSV) into a Pandas DataFrame
TODO: should be called read_named_dataset
Args:
`name` is assumed not to have an extension (like ".csv"), alternative extensions are tried a... | keyword[def] identifier[read_named_csv] ( identifier[name] , identifier[data_path] = identifier[DATA_PATH] , identifier[nrows] = keyword[None] , identifier[verbose] = keyword[True] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[name] ):
keyword[... | def read_named_csv(name, data_path=DATA_PATH, nrows=None, verbose=True):
""" Convert a dataset in a local file (usually a CSV) into a Pandas DataFrame
TODO: should be called read_named_dataset
Args:
`name` is assumed not to have an extension (like ".csv"), alternative extensions are tried automaticall... |
def entropy(self, t, structure=None):
"""
Vibrational entropy at temperature T obtained from the integration of the DOS.
Only positive frequencies will be used.
Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number
of Avogadro times the atoms in a... | def function[entropy, parameter[self, t, structure]]:
constant[
Vibrational entropy at temperature T obtained from the integration of the DOS.
Only positive frequencies will be used.
Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number
of Avogadr... | keyword[def] identifier[entropy] ( identifier[self] , identifier[t] , identifier[structure] = keyword[None] ):
literal[string]
keyword[if] identifier[t] == literal[int] :
keyword[return] literal[int]
identifier[freqs] = identifier[self] . identifier[_positive_frequencies]... | def entropy(self, t, structure=None):
"""
Vibrational entropy at temperature T obtained from the integration of the DOS.
Only positive frequencies will be used.
Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number
of Avogadro times the atoms in a uni... |
async def AddUser(self, users):
'''
users : typing.Sequence[~AddUser]
Returns -> typing.Sequence[~AddUserResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='UserManager',
request='AddUser',
version=2,
... | <ast.AsyncFunctionDef object at 0x7da1b0dbe830> | keyword[async] keyword[def] identifier[AddUser] ( identifier[self] , identifier[users] ):
literal[string]
identifier[_params] = identifier[dict] ()
identifier[msg] = identifier[dict] ( identifier[type] = literal[string] ,
identifier[request] = literal[string] ,
... | async def AddUser(self, users):
"""
users : typing.Sequence[~AddUser]
Returns -> typing.Sequence[~AddUserResult]
"""
# map input types to rpc msg
_params = dict()
msg = dict(type='UserManager', request='AddUser', version=2, params=_params)
_params['users'] = users
reply =... |
def get_xsi_type(element):
"""
returns the type of an element of the XML tree (incl. its namespace),
i.e. nodes, edges, layers etc.), raises an exception if the element has no
'xsi:type' attribute.
"""
nsdict = NAMESPACES
#.xpath() always returns a list, so we need to select the first elemen... | def function[get_xsi_type, parameter[element]]:
constant[
returns the type of an element of the XML tree (incl. its namespace),
i.e. nodes, edges, layers etc.), raises an exception if the element has no
'xsi:type' attribute.
]
variable[nsdict] assign[=] name[NAMESPACES]
<ast.Try obje... | keyword[def] identifier[get_xsi_type] ( identifier[element] ):
literal[string]
identifier[nsdict] = identifier[NAMESPACES]
keyword[try] :
keyword[return] identifier[element] . identifier[xpath] ( literal[string] , identifier[namespaces] = identifier[nsdict] )[ literal[int] ]
keywo... | def get_xsi_type(element):
"""
returns the type of an element of the XML tree (incl. its namespace),
i.e. nodes, edges, layers etc.), raises an exception if the element has no
'xsi:type' attribute.
"""
nsdict = NAMESPACES
#.xpath() always returns a list, so we need to select the first elemen... |
def _populate_common_request(self, request):
'''Populate the Request with common fields.'''
url_record = self._item_session.url_record
# Note that referrer may have already been set by the --referer option
if url_record.parent_url and not request.fields.get('Referer'):
self.... | def function[_populate_common_request, parameter[self, request]]:
constant[Populate the Request with common fields.]
variable[url_record] assign[=] name[self]._item_session.url_record
if <ast.BoolOp object at 0x7da2054a7910> begin[:]
call[name[self]._add_referrer, parameter[name[... | keyword[def] identifier[_populate_common_request] ( identifier[self] , identifier[request] ):
literal[string]
identifier[url_record] = identifier[self] . identifier[_item_session] . identifier[url_record]
keyword[if] identifier[url_record] . identifier[parent_url] keyword[and]... | def _populate_common_request(self, request):
"""Populate the Request with common fields."""
url_record = self._item_session.url_record
# Note that referrer may have already been set by the --referer option
if url_record.parent_url and (not request.fields.get('Referer')):
self._add_referrer(reque... |
def _create_tunnels(self):
"""
Create SSH tunnels on top of a transport to the remote gateway
"""
if not self.is_active:
try:
self._connect_to_gateway()
except socket.gaierror: # raised by paramiko.Transport
msg = 'Could not resolv... | def function[_create_tunnels, parameter[self]]:
constant[
Create SSH tunnels on top of a transport to the remote gateway
]
if <ast.UnaryOp object at 0x7da1b1393880> begin[:]
<ast.Try object at 0x7da1b13905b0>
for taget[tuple[[<ast.Name object at 0x7da1b13b5db0>, <ast.Name... | keyword[def] identifier[_create_tunnels] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_active] :
keyword[try] :
identifier[self] . identifier[_connect_to_gateway] ()
keyword[except] identifier[socket] . ... | def _create_tunnels(self):
"""
Create SSH tunnels on top of a transport to the remote gateway
"""
if not self.is_active:
try:
self._connect_to_gateway() # depends on [control=['try'], data=[]]
except socket.gaierror: # raised by paramiko.Transport
msg = ... |
def write_default_config(self, filename):
"""Write the default config file.
"""
try:
with open(filename, 'wt') as file:
file.write(DEFAULT_CONFIG)
return True
except (IOError, OSError) as e:
print('Error writing %s: %s' % (filename, e.s... | def function[write_default_config, parameter[self, filename]]:
constant[Write the default config file.
]
<ast.Try object at 0x7da207f98910> | keyword[def] identifier[write_default_config] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[try] :
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[file] :
identifier[file] . identifier[write] ( i... | def write_default_config(self, filename):
"""Write the default config file.
"""
try:
with open(filename, 'wt') as file:
file.write(DEFAULT_CONFIG) # depends on [control=['with'], data=['file']]
return True # depends on [control=['try'], data=[]]
except (IOError, OSError... |
async def toggle(self):
"""Toggles between pause and resume command"""
self.logger.debug("toggle command")
if not self.state == 'ready':
return
if self.streamer is None:
return
try:
if self.streamer.is_playing():
await self.... | <ast.AsyncFunctionDef object at 0x7da1b198bb20> | keyword[async] keyword[def] identifier[toggle] ( identifier[self] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] keyword[not] identifier[self] . identifier[state] == literal[string] :
keyword[return]
... | async def toggle(self):
"""Toggles between pause and resume command"""
self.logger.debug('toggle command')
if not self.state == 'ready':
return # depends on [control=['if'], data=[]]
if self.streamer is None:
return # depends on [control=['if'], data=[]]
try:
if self.stream... |
def getxattr(self, req, ino, name, size):
""" Set an extended attribute
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err
"""
self.reply_err(req, errno.ENOSYS) | def function[getxattr, parameter[self, req, ino, name, size]]:
constant[ Set an extended attribute
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err
]
call[name[self].reply_err, parameter[name[req], name[errno].ENOSYS]] | keyword[def] identifier[getxattr] ( identifier[self] , identifier[req] , identifier[ino] , identifier[name] , identifier[size] ):
literal[string]
identifier[self] . identifier[reply_err] ( identifier[req] , identifier[errno] . identifier[ENOSYS] ) | def getxattr(self, req, ino, name, size):
""" Set an extended attribute
Valid replies:
reply_buf
reply_data
reply_xattr
reply_err
"""
self.reply_err(req, errno.ENOSYS) |
def emit_toi_stats(toi_set, peripherals):
"""
Calculates new TOI stats and emits them via statsd.
"""
count_by_zoom = defaultdict(int)
total = 0
for coord_int in toi_set:
coord = coord_unmarshall_int(coord_int)
count_by_zoom[coord.zoom] += 1
total += 1
peripherals.s... | def function[emit_toi_stats, parameter[toi_set, peripherals]]:
constant[
Calculates new TOI stats and emits them via statsd.
]
variable[count_by_zoom] assign[=] call[name[defaultdict], parameter[name[int]]]
variable[total] assign[=] constant[0]
for taget[name[coord_int]] in starr... | keyword[def] identifier[emit_toi_stats] ( identifier[toi_set] , identifier[peripherals] ):
literal[string]
identifier[count_by_zoom] = identifier[defaultdict] ( identifier[int] )
identifier[total] = literal[int]
keyword[for] identifier[coord_int] keyword[in] identifier[toi_set] :
id... | def emit_toi_stats(toi_set, peripherals):
"""
Calculates new TOI stats and emits them via statsd.
"""
count_by_zoom = defaultdict(int)
total = 0
for coord_int in toi_set:
coord = coord_unmarshall_int(coord_int)
count_by_zoom[coord.zoom] += 1
total += 1 # depends on [cont... |
def rename(self, newpath):
"Move folder to a new name, possibly a whole new path"
# POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder
#url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath)
params = {'mvDir':'/%s%s'... | def function[rename, parameter[self, newpath]]:
constant[Move folder to a new name, possibly a whole new path]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da18f723ca0>], [<ast.BinOp object at 0x7da18f722f80>]]
variable[r] assign[=] call[name[self].jfs.post, parameter[name[s... | keyword[def] identifier[rename] ( identifier[self] , identifier[newpath] ):
literal[string]
identifier[params] ={ literal[string] : literal[string] %( identifier[self] . identifier[jfs] . identifier[username] , identifier[newpath] )}
identifier[r] = identifier[self] . ide... | def rename(self, newpath):
"""Move folder to a new name, possibly a whole new path"""
# POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder
#url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath)
params = {'mvDir': '/%s%s' % (self.jf... |
def window(self, windowDuration, slideDuration=None):
"""
Return a new DStream in which each RDD contains all the elements in seen in a
sliding window of time over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
... | def function[window, parameter[self, windowDuration, slideDuration]]:
constant[
Return a new DStream in which each RDD contains all the elements in seen in a
sliding window of time over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
... | keyword[def] identifier[window] ( identifier[self] , identifier[windowDuration] , identifier[slideDuration] = keyword[None] ):
literal[string]
identifier[self] . identifier[_validate_window_param] ( identifier[windowDuration] , identifier[slideDuration] )
identifier[d] = identifier[self] .... | def window(self, windowDuration, slideDuration=None):
"""
Return a new DStream in which each RDD contains all the elements in seen in a
sliding window of time over this DStream.
@param windowDuration: width of the window; must be a multiple of this DStream's
ba... |
def random_new_from_seed(
seed: Hashable, algo: int = RNG_CMWC
) -> tcod.random.Random:
"""Return a new Random instance. Using the given ``seed`` and ``algo``.
Args:
seed (Hashable): The RNG seed. Should be a 32-bit integer, but any
hashable object is accepted.
al... | def function[random_new_from_seed, parameter[seed, algo]]:
constant[Return a new Random instance. Using the given ``seed`` and ``algo``.
Args:
seed (Hashable): The RNG seed. Should be a 32-bit integer, but any
hashable object is accepted.
algo (int): The random nu... | keyword[def] identifier[random_new_from_seed] (
identifier[seed] : identifier[Hashable] , identifier[algo] : identifier[int] = identifier[RNG_CMWC]
)-> identifier[tcod] . identifier[random] . identifier[Random] :
literal[string]
keyword[return] identifier[tcod] . identifier[random] . identifier[Random] ... | def random_new_from_seed(seed: Hashable, algo: int=RNG_CMWC) -> tcod.random.Random:
"""Return a new Random instance. Using the given ``seed`` and ``algo``.
Args:
seed (Hashable): The RNG seed. Should be a 32-bit integer, but any
hashable object is accepted.
algo (int)... |
def map_remove(self, key, mapkey, **kwargs):
"""
Remove an item from a map.
:param str key: The document ID
:param str mapkey: The key in the map
:param kwargs: See :meth:`mutate_in` for options
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_e... | def function[map_remove, parameter[self, key, mapkey]]:
constant[
Remove an item from a map.
:param str key: The document ID
:param str mapkey: The key in the map
:param kwargs: See :meth:`mutate_in` for options
:raise: :exc:`IndexError` if the mapkey does not exist
... | keyword[def] identifier[map_remove] ( identifier[self] , identifier[key] , identifier[mapkey] ,** identifier[kwargs] ):
literal[string]
identifier[op] = identifier[SD] . identifier[remove] ( identifier[mapkey] )
identifier[sdres] = identifier[self] . identifier[mutate_in] ( identifier[key]... | def map_remove(self, key, mapkey, **kwargs):
"""
Remove an item from a map.
:param str key: The document ID
:param str mapkey: The key in the map
:param kwargs: See :meth:`mutate_in` for options
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`... |
def find(obj, prs, forced_type=None, cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param... | def function[find, parameter[obj, prs, forced_type, cls]]:
constant[
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param forced_typ... | keyword[def] identifier[find] ( identifier[obj] , identifier[prs] , identifier[forced_type] = keyword[None] , identifier[cls] = identifier[anyconfig] . identifier[models] . identifier[processor] . identifier[Processor] ):
literal[string]
keyword[if] identifier[forced_type] keyword[is] keyword[not] keyw... | def find(obj, prs, forced_type=None, cls=anyconfig.models.processor.Processor):
"""
:param obj:
a file path, file, file-like object, pathlib.Path object or an
'anyconfig.globals.IOInfo' (namedtuple) object
:param prs: A list of :class:`anyconfig.models.processor.Processor` classes
:param... |
def engine(func):
"""Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is similar to `coroutine`, except it d... | def function[engine, parameter[func]]:
constant[Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is simi... | keyword[def] identifier[engine] ( identifier[func] ):
literal[string]
identifier[func] = identifier[_make_coroutine_wrapper] ( identifier[func] , identifier[replace_callback] = keyword[False] )
@ identifier[functools] . identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* i... | def engine(func):
"""Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to be
compatible with versions of Tornado older than 3.0 the
`coroutine` decorator is recommended instead.
This decorator is similar to `coroutine`, except it d... |
def detect_django_settings():
"""
Automatically try to discover Django settings files,
return them as relative module paths.
"""
matches = []
for root, dirnames, filenames in os.walk(os.getcwd()):
for filename in fnmatch.filter(filenames, '*settings.py'):
full = os.path.join... | def function[detect_django_settings, parameter[]]:
constant[
Automatically try to discover Django settings files,
return them as relative module paths.
]
variable[matches] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b21eeb60>, <ast.Name object at 0x7da1b21edf30>, <a... | keyword[def] identifier[detect_django_settings] ():
literal[string]
identifier[matches] =[]
keyword[for] identifier[root] , identifier[dirnames] , identifier[filenames] keyword[in] identifier[os] . identifier[walk] ( identifier[os] . identifier[getcwd] ()):
keyword[for] identifier[filena... | def detect_django_settings():
"""
Automatically try to discover Django settings files,
return them as relative module paths.
"""
matches = []
for (root, dirnames, filenames) in os.walk(os.getcwd()):
for filename in fnmatch.filter(filenames, '*settings.py'):
full = os.path.joi... |
def get_axes(x, y):
"""
computes the axis x and y of a given 2d grid
:param x:
:param y:
:return:
"""
n=int(np.sqrt(len(x)))
if n**2 != len(x):
raise ValueError("lenght of input array given as %s is not square of integer number!" % (len(x)))
x_image = x.reshape(n,n)
y_ima... | def function[get_axes, parameter[x, y]]:
constant[
computes the axis x and y of a given 2d grid
:param x:
:param y:
:return:
]
variable[n] assign[=] call[name[int], parameter[call[name[np].sqrt, parameter[call[name[len], parameter[name[x]]]]]]]
if compare[binary_operation[nam... | keyword[def] identifier[get_axes] ( identifier[x] , identifier[y] ):
literal[string]
identifier[n] = identifier[int] ( identifier[np] . identifier[sqrt] ( identifier[len] ( identifier[x] )))
keyword[if] identifier[n] ** literal[int] != identifier[len] ( identifier[x] ):
keyword[raise] ident... | def get_axes(x, y):
"""
computes the axis x and y of a given 2d grid
:param x:
:param y:
:return:
"""
n = int(np.sqrt(len(x)))
if n ** 2 != len(x):
raise ValueError('lenght of input array given as %s is not square of integer number!' % len(x)) # depends on [control=['if'], data=... |
def edit(
request,
slug,
rev_id=None,
template_name='wakawaka/edit.html',
extra_context=None,
wiki_page_form=WikiPageForm,
wiki_delete_form=DeleteWikiPageForm,
):
"""
Displays the form for editing and deleting a page.
"""
# Get the page for slug and get a specific revision, i... | def function[edit, parameter[request, slug, rev_id, template_name, extra_context, wiki_page_form, wiki_delete_form]]:
constant[
Displays the form for editing and deleting a page.
]
<ast.Try object at 0x7da1b0fd5540>
variable[delete_form] assign[=] constant[None]
if <ast.BoolOp object... | keyword[def] identifier[edit] (
identifier[request] ,
identifier[slug] ,
identifier[rev_id] = keyword[None] ,
identifier[template_name] = literal[string] ,
identifier[extra_context] = keyword[None] ,
identifier[wiki_page_form] = identifier[WikiPageForm] ,
identifier[wiki_delete_form] = identifier[DeleteWikiPag... | def edit(request, slug, rev_id=None, template_name='wakawaka/edit.html', extra_context=None, wiki_page_form=WikiPageForm, wiki_delete_form=DeleteWikiPageForm):
"""
Displays the form for editing and deleting a page.
"""
# Get the page for slug and get a specific revision, if given
try:
querys... |
def prepare_dependencies(self):
"""
Prepares a FileBuildInfo object for explaining what changed
The bsources, bdepends and bimplicit lists have all been
stored on disk as paths relative to the top-level SConstruct
directory. Convert the strings to actual Nodes (for use by the
... | def function[prepare_dependencies, parameter[self]]:
constant[
Prepares a FileBuildInfo object for explaining what changed
The bsources, bdepends and bimplicit lists have all been
stored on disk as paths relative to the top-level SConstruct
directory. Convert the strings to act... | keyword[def] identifier[prepare_dependencies] ( identifier[self] ):
literal[string]
identifier[attrs] =[
( literal[string] , literal[string] ),
( literal[string] , literal[string] ),
( literal[string] , literal[string] ),
]
keyword[for] ( identifier[nattr] ,... | def prepare_dependencies(self):
"""
Prepares a FileBuildInfo object for explaining what changed
The bsources, bdepends and bimplicit lists have all been
stored on disk as paths relative to the top-level SConstruct
directory. Convert the strings to actual Nodes (for use by the
... |
def values(self):
"""Returns a list of all values in the dictionary.
Returns:
list of str: [value1,value2,...,valueN]
"""
all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()]
return all_values | def function[values, parameter[self]]:
constant[Returns a list of all values in the dictionary.
Returns:
list of str: [value1,value2,...,valueN]
]
variable[all_values] assign[=] <ast.ListComp object at 0x7da18f09e2f0>
return[name[all_values]] | keyword[def] identifier[values] ( identifier[self] ):
literal[string]
identifier[all_values] =[ identifier[v] . identifier[decode] ( literal[string] ) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[rdb] . identifier[hgetall] ( identifier[self] . identifier[s... | def values(self):
"""Returns a list of all values in the dictionary.
Returns:
list of str: [value1,value2,...,valueN]
"""
all_values = [v.decode('utf-8') for (k, v) in self.rdb.hgetall(self.session_hash).items()]
return all_values |
def transform(self, X, lenscale=None):
"""
Apply the Fast Food RBF basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
... | def function[transform, parameter[self, X, lenscale]]:
constant[
Apply the Fast Food RBF basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar... | keyword[def] identifier[transform] ( identifier[self] , identifier[X] , identifier[lenscale] = keyword[None] ):
literal[string]
identifier[lenscale] = identifier[self] . identifier[_check_dim] ( identifier[X] . identifier[shape] [ literal[int] ], identifier[lenscale] )
identifier[VX] = id... | def transform(self, X, lenscale=None):
"""
Apply the Fast Food RBF basis to X.
Parameters
----------
X: ndarray
(N, d) array of observations where N is the number of samples, and
d is the dimensionality of X.
lenscale: scalar or ndarray, optional
... |
def _get_basilisp_bytecode(
fullname: str, mtime: int, source_size: int, cache_data: bytes
) -> List[types.CodeType]:
"""Unmarshal the bytes from a Basilisp bytecode cache file, validating the
file header prior to returning. If the file header does not match, throw
an exception."""
exc_details = {"n... | def function[_get_basilisp_bytecode, parameter[fullname, mtime, source_size, cache_data]]:
constant[Unmarshal the bytes from a Basilisp bytecode cache file, validating the
file header prior to returning. If the file header does not match, throw
an exception.]
variable[exc_details] assign[=] dict... | keyword[def] identifier[_get_basilisp_bytecode] (
identifier[fullname] : identifier[str] , identifier[mtime] : identifier[int] , identifier[source_size] : identifier[int] , identifier[cache_data] : identifier[bytes]
)-> identifier[List] [ identifier[types] . identifier[CodeType] ]:
literal[string]
identi... | def _get_basilisp_bytecode(fullname: str, mtime: int, source_size: int, cache_data: bytes) -> List[types.CodeType]:
"""Unmarshal the bytes from a Basilisp bytecode cache file, validating the
file header prior to returning. If the file header does not match, throw
an exception."""
exc_details = {'name': ... |
def view_assets_by_site(token, dstore):
"""
Display statistical information about the distribution of the assets
"""
taxonomies = dstore['assetcol/tagcol/taxonomy'].value
assets_by_site = dstore['assetcol'].assets_by_site()
data = ['taxonomy mean stddev min max num_sites num_assets'.split()]
... | def function[view_assets_by_site, parameter[token, dstore]]:
constant[
Display statistical information about the distribution of the assets
]
variable[taxonomies] assign[=] call[name[dstore]][constant[assetcol/tagcol/taxonomy]].value
variable[assets_by_site] assign[=] call[call[name[dsto... | keyword[def] identifier[view_assets_by_site] ( identifier[token] , identifier[dstore] ):
literal[string]
identifier[taxonomies] = identifier[dstore] [ literal[string] ]. identifier[value]
identifier[assets_by_site] = identifier[dstore] [ literal[string] ]. identifier[assets_by_site] ()
identifie... | def view_assets_by_site(token, dstore):
"""
Display statistical information about the distribution of the assets
"""
taxonomies = dstore['assetcol/tagcol/taxonomy'].value
assets_by_site = dstore['assetcol'].assets_by_site()
data = ['taxonomy mean stddev min max num_sites num_assets'.split()]
... |
def delete_record(zone_id, record_id, profile):
'''
Delete a record.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
... | def function[delete_record, parameter[zone_id, record_id, profile]]:
constant[
Delete a record.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype... | keyword[def] identifier[delete_record] ( identifier[zone_id] , identifier[record_id] , identifier[profile] ):
literal[string]
identifier[conn] = identifier[_get_driver] ( identifier[profile] = identifier[profile] )
identifier[record] = identifier[conn] . identifier[get_record] ( identifier[zone_id] = ... | def delete_record(zone_id, record_id, profile):
"""
Delete a record.
:param zone_id: Zone to delete.
:type zone_id: ``str``
:param record_id: Record to delete.
:type record_id: ``str``
:param profile: The profile key
:type profile: ``str``
:rtype: ``bool``
CLI Example:
... |
def setup_scheduler(self, before_connect=False):
'''
Set up the scheduler.
This is safe to call multiple times.
'''
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks = {}
if 'schedule' not in self.periodic_callbacks:
... | def function[setup_scheduler, parameter[self, before_connect]]:
constant[
Set up the scheduler.
This is safe to call multiple times.
]
call[name[self]._setup_core, parameter[]]
variable[loop_interval] assign[=] call[name[self].opts][constant[loop_interval]]
variab... | keyword[def] identifier[setup_scheduler] ( identifier[self] , identifier[before_connect] = keyword[False] ):
literal[string]
identifier[self] . identifier[_setup_core] ()
identifier[loop_interval] = identifier[self] . identifier[opts] [ literal[string] ]
identifier[new_periodic_c... | def setup_scheduler(self, before_connect=False):
"""
Set up the scheduler.
This is safe to call multiple times.
"""
self._setup_core()
loop_interval = self.opts['loop_interval']
new_periodic_callbacks = {}
if 'schedule' not in self.periodic_callbacks:
if 'schedule' no... |
def generate_timestamped_string(subject="test", number_of_random_chars=4):
"""
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to app... | def function[generate_timestamped_string, parameter[subject, number_of_random_chars]]:
constant[
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of ra... | keyword[def] identifier[generate_timestamped_string] ( identifier[subject] = literal[string] , identifier[number_of_random_chars] = literal[int] ):
literal[string]
identifier[random_str] = identifier[generate_random_string] ( identifier[number_of_random_chars] )
identifier[timestamp] = identifier[gene... | def generate_timestamped_string(subject='test', number_of_random_chars=4):
"""
Generate time-stamped string. Format as follows...
`2013-01-31_14:12:23_SubjectString_a3Zg`
Kwargs:
subject (str): String to use as subject.
number_of_random_chars (int) : Number of random characters to app... |
def list(self):
"""Lists the keys
:return: Returns a list of all keys (not just key names, but rather
the keys themselves).
"""
response = self.client.list_objects_v2(Bucket=self.db_path)
if u'Contents' in response:
# Filter out everything but the key names
... | def function[list, parameter[self]]:
constant[Lists the keys
:return: Returns a list of all keys (not just key names, but rather
the keys themselves).
]
variable[response] assign[=] call[name[self].client.list_objects_v2, parameter[]]
if compare[constant[Contents] in name... | keyword[def] identifier[list] ( identifier[self] ):
literal[string]
identifier[response] = identifier[self] . identifier[client] . identifier[list_objects_v2] ( identifier[Bucket] = identifier[self] . identifier[db_path] )
keyword[if] literal[string] keyword[in] identifier[response] :
... | def list(self):
"""Lists the keys
:return: Returns a list of all keys (not just key names, but rather
the keys themselves).
"""
response = self.client.list_objects_v2(Bucket=self.db_path)
if u'Contents' in response:
# Filter out everything but the key names
keys = [ke... |
def calc_avr_uvr_v1(self):
"""Calculate the flown through area and the wetted perimeter of both
outer embankments.
Note that each outer embankment lies beyond its foreland and that all
water flowing exactly above the a embankment is added to |AVR|.
The theoretical surface seperating water above the... | def function[calc_avr_uvr_v1, parameter[self]]:
constant[Calculate the flown through area and the wetted perimeter of both
outer embankments.
Note that each outer embankment lies beyond its foreland and that all
water flowing exactly above the a embankment is added to |AVR|.
The theoretical sur... | keyword[def] identifier[calc_avr_uvr_v1] ( identifier[self] ):
literal[string]
identifier[con] = identifier[self] . identifier[parameters] . identifier[control] . identifier[fastaccess]
identifier[der] = identifier[self] . identifier[parameters] . identifier[derived] . identifier[fastaccess]
id... | def calc_avr_uvr_v1(self):
"""Calculate the flown through area and the wetted perimeter of both
outer embankments.
Note that each outer embankment lies beyond its foreland and that all
water flowing exactly above the a embankment is added to |AVR|.
The theoretical surface seperating water above the... |
def on_new_line(self):
"""On new input line"""
self.set_cursor_position('eof')
self.current_prompt_pos = self.get_position('cursor')
self.new_input_line = False | def function[on_new_line, parameter[self]]:
constant[On new input line]
call[name[self].set_cursor_position, parameter[constant[eof]]]
name[self].current_prompt_pos assign[=] call[name[self].get_position, parameter[constant[cursor]]]
name[self].new_input_line assign[=] constant[False] | keyword[def] identifier[on_new_line] ( identifier[self] ):
literal[string]
identifier[self] . identifier[set_cursor_position] ( literal[string] )
identifier[self] . identifier[current_prompt_pos] = identifier[self] . identifier[get_position] ( literal[string] )
identifier[self... | def on_new_line(self):
"""On new input line"""
self.set_cursor_position('eof')
self.current_prompt_pos = self.get_position('cursor')
self.new_input_line = False |
def get_report_parts(self, apps, formats):
"""
Make report item texts in a specified format.
"""
for fmt in formats:
width = 100 if fmt is not None else tui.get_terminal_size()[0]
for sr in self.subreports:
sr.make_format(fmt, width)
logge... | def function[get_report_parts, parameter[self, apps, formats]]:
constant[
Make report item texts in a specified format.
]
for taget[name[fmt]] in starred[name[formats]] begin[:]
variable[width] assign[=] <ast.IfExp object at 0x7da18eb54100>
for taget[name[... | keyword[def] identifier[get_report_parts] ( identifier[self] , identifier[apps] , identifier[formats] ):
literal[string]
keyword[for] identifier[fmt] keyword[in] identifier[formats] :
identifier[width] = literal[int] keyword[if] identifier[fmt] keyword[is] keyword[not] keyword[... | def get_report_parts(self, apps, formats):
"""
Make report item texts in a specified format.
"""
for fmt in formats:
width = 100 if fmt is not None else tui.get_terminal_size()[0]
for sr in self.subreports:
sr.make_format(fmt, width) # depends on [control=['for'], da... |
def noise_gaussian(self, mean, std):
"""Create a gaussian noise variable"""
assert std > 0
ng = self.sym.sym('ng_{:d}'.format(len(self.scope['ng'])))
self.scope['ng'].append(ng)
return mean + std*ng | def function[noise_gaussian, parameter[self, mean, std]]:
constant[Create a gaussian noise variable]
assert[compare[name[std] greater[>] constant[0]]]
variable[ng] assign[=] call[name[self].sym.sym, parameter[call[constant[ng_{:d}].format, parameter[call[name[len], parameter[call[name[self].scope][c... | keyword[def] identifier[noise_gaussian] ( identifier[self] , identifier[mean] , identifier[std] ):
literal[string]
keyword[assert] identifier[std] > literal[int]
identifier[ng] = identifier[self] . identifier[sym] . identifier[sym] ( literal[string] . identifier[format] ( identifier[len]... | def noise_gaussian(self, mean, std):
"""Create a gaussian noise variable"""
assert std > 0
ng = self.sym.sym('ng_{:d}'.format(len(self.scope['ng'])))
self.scope['ng'].append(ng)
return mean + std * ng |
def saveSheets(fn, *vsheets, confirm_overwrite=False):
'Save sheet `vs` with given filename `fn`.'
givenpath = Path(fn)
# determine filetype to save as
filetype = ''
basename, ext = os.path.splitext(fn)
if ext:
filetype = ext[1:]
filetype = filetype or options.save_filetype
if... | def function[saveSheets, parameter[fn]]:
constant[Save sheet `vs` with given filename `fn`.]
variable[givenpath] assign[=] call[name[Path], parameter[name[fn]]]
variable[filetype] assign[=] constant[]
<ast.Tuple object at 0x7da20e9b21d0> assign[=] call[name[os].path.splitext, parameter[n... | keyword[def] identifier[saveSheets] ( identifier[fn] ,* identifier[vsheets] , identifier[confirm_overwrite] = keyword[False] ):
literal[string]
identifier[givenpath] = identifier[Path] ( identifier[fn] )
identifier[filetype] = literal[string]
identifier[basename] , identifier[ext] = identi... | def saveSheets(fn, *vsheets, confirm_overwrite=False):
"""Save sheet `vs` with given filename `fn`."""
givenpath = Path(fn)
# determine filetype to save as
filetype = ''
(basename, ext) = os.path.splitext(fn)
if ext:
filetype = ext[1:] # depends on [control=['if'], data=[]]
filetype... |
def get_cam_bounds(self):
"""Return the bounds of the camera in x, y, xMax, and yMax format."""
world_pos = self.get_world_pos()
screen_res = Ragnarok.get_world().get_backbuffer_size() * .5
return (self.pan.X - screen_res.X), (self.pan.Y - screen_res.Y), (self.pan.X + screen_res.X), (
... | def function[get_cam_bounds, parameter[self]]:
constant[Return the bounds of the camera in x, y, xMax, and yMax format.]
variable[world_pos] assign[=] call[name[self].get_world_pos, parameter[]]
variable[screen_res] assign[=] binary_operation[call[call[name[Ragnarok].get_world, parameter[]].get_... | keyword[def] identifier[get_cam_bounds] ( identifier[self] ):
literal[string]
identifier[world_pos] = identifier[self] . identifier[get_world_pos] ()
identifier[screen_res] = identifier[Ragnarok] . identifier[get_world] (). identifier[get_backbuffer_size] ()* literal[int]
keyword... | def get_cam_bounds(self):
"""Return the bounds of the camera in x, y, xMax, and yMax format."""
world_pos = self.get_world_pos()
screen_res = Ragnarok.get_world().get_backbuffer_size() * 0.5
return (self.pan.X - screen_res.X, self.pan.Y - screen_res.Y, self.pan.X + screen_res.X, self.pan.Y + screen_res.... |
def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"... | def function[wrap, parameter[item, args, krgs]]:
constant[Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func ... | keyword[def] identifier[wrap] ( identifier[item] , identifier[args] = keyword[None] , identifier[krgs] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[with] identifier[Wrap] (** identifier[kwargs] ):
keyword[if] identifier[callable] ( identifier[item] ):
identifier... | def wrap(item, args=None, krgs=None, **kwargs):
"""Wraps the given item content between horizontal lines. Item can be a
string or a function.
**Examples**:
::
qprompt.wrap("Hi, this will be wrapped.") # String item.
qprompt.wrap(myfunc, [arg1, arg2], {'krgk': krgv}) # Func item.
"... |
def saveVirtualOutputs(self,outdict):
""" Assign in-memory versions of generated products for this
``imageObject`` based on dictionary 'outdict'.
"""
if not self.inmemory:
return
for outname in outdict:
self.virtualOutputs[outname] = outdict[outname] | def function[saveVirtualOutputs, parameter[self, outdict]]:
constant[ Assign in-memory versions of generated products for this
``imageObject`` based on dictionary 'outdict'.
]
if <ast.UnaryOp object at 0x7da1b1b4b8e0> begin[:]
return[None]
for taget[name[outname]] in star... | keyword[def] identifier[saveVirtualOutputs] ( identifier[self] , identifier[outdict] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[inmemory] :
keyword[return]
keyword[for] identifier[outname] keyword[in] identifier[outdict] :
iden... | def saveVirtualOutputs(self, outdict):
""" Assign in-memory versions of generated products for this
``imageObject`` based on dictionary 'outdict'.
"""
if not self.inmemory:
return # depends on [control=['if'], data=[]]
for outname in outdict:
self.virtualOutputs[outname] = o... |
def get_jp2_bit_depth(stream):
"""Reads bit encoding depth of jpeg2000 file in binary stream format
:param stream: binary stream format
:type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...)
:return: bit depth
:rtype: int
"""
stream.seek(0)
while True:
read_buffer = ... | def function[get_jp2_bit_depth, parameter[stream]]:
constant[Reads bit encoding depth of jpeg2000 file in binary stream format
:param stream: binary stream format
:type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...)
:return: bit depth
:rtype: int
]
call[name[stream].se... | keyword[def] identifier[get_jp2_bit_depth] ( identifier[stream] ):
literal[string]
identifier[stream] . identifier[seek] ( literal[int] )
keyword[while] keyword[True] :
identifier[read_buffer] = identifier[stream] . identifier[read] ( literal[int] )
keyword[if] identifier[len] ( id... | def get_jp2_bit_depth(stream):
"""Reads bit encoding depth of jpeg2000 file in binary stream format
:param stream: binary stream format
:type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...)
:return: bit depth
:rtype: int
"""
stream.seek(0)
while True:
read_buffer = ... |
def append(self, exp):
"""
Args:
exp (Experience):
"""
if self._curr_size < self.max_size:
self._assign(self._curr_pos, exp)
self._curr_pos = (self._curr_pos + 1) % self.max_size
self._curr_size += 1
else:
self._assign(s... | def function[append, parameter[self, exp]]:
constant[
Args:
exp (Experience):
]
if compare[name[self]._curr_size less[<] name[self].max_size] begin[:]
call[name[self]._assign, parameter[name[self]._curr_pos, name[exp]]]
name[self]._curr_pos ass... | keyword[def] identifier[append] ( identifier[self] , identifier[exp] ):
literal[string]
keyword[if] identifier[self] . identifier[_curr_size] < identifier[self] . identifier[max_size] :
identifier[self] . identifier[_assign] ( identifier[self] . identifier[_curr_pos] , identifier[exp]... | def append(self, exp):
"""
Args:
exp (Experience):
"""
if self._curr_size < self.max_size:
self._assign(self._curr_pos, exp)
self._curr_pos = (self._curr_pos + 1) % self.max_size
self._curr_size += 1 # depends on [control=['if'], data=[]]
else:
se... |
def _fix(interval):
'''
Helper function for ``GenomeIntervalTree.from_bed and ``.from_table``.
Data tables may contain intervals with begin >= end. Such intervals lead to infinite recursions and
other unpleasant behaviour, so something has to be done about them. We 'fix' them by simply setting end = be... | def function[_fix, parameter[interval]]:
constant[
Helper function for ``GenomeIntervalTree.from_bed and ``.from_table``.
Data tables may contain intervals with begin >= end. Such intervals lead to infinite recursions and
other unpleasant behaviour, so something has to be done about them. We 'fix' ... | keyword[def] identifier[_fix] ( identifier[interval] ):
literal[string]
keyword[if] identifier[interval] . identifier[begin] >= identifier[interval] . identifier[end] :
identifier[warnings] . identifier[warn] ( literal[string] )
keyword[return] identifier[Interval] ( identifier[interval... | def _fix(interval):
"""
Helper function for ``GenomeIntervalTree.from_bed and ``.from_table``.
Data tables may contain intervals with begin >= end. Such intervals lead to infinite recursions and
other unpleasant behaviour, so something has to be done about them. We 'fix' them by simply setting end = be... |
def parseExtensionArgs(self, args, strict=False):
"""Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
registration request fields... | def function[parseExtensionArgs, parameter[self, args, strict]]:
constant[Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
regist... | keyword[def] identifier[parseExtensionArgs] ( identifier[self] , identifier[args] , identifier[strict] = keyword[False] ):
literal[string]
keyword[for] identifier[list_name] keyword[in] [ literal[string] , literal[string] ]:
identifier[required] =( identifier[list_name] == literal[st... | def parseExtensionArgs(self, args, strict=False):
"""Parse the unqualified simple registration request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized simple
registration request fields.
... |
def process_slice(self, b_rot90=None):
'''
Processes a single slice.
'''
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
if self.func == 'invertIntensities':
self.invert_slice_intensities() | def function[process_slice, parameter[self, b_rot90]]:
constant[
Processes a single slice.
]
if name[b_rot90] begin[:]
name[self]._Mnp_2Dslice assign[=] call[name[np].rot90, parameter[name[self]._Mnp_2Dslice]]
if compare[name[self].func equal[==] constant[invertIn... | keyword[def] identifier[process_slice] ( identifier[self] , identifier[b_rot90] = keyword[None] ):
literal[string]
keyword[if] identifier[b_rot90] :
identifier[self] . identifier[_Mnp_2Dslice] = identifier[np] . identifier[rot90] ( identifier[self] . identifier[_Mnp_2Dslice] )
... | def process_slice(self, b_rot90=None):
"""
Processes a single slice.
"""
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice) # depends on [control=['if'], data=[]]
if self.func == 'invertIntensities':
self.invert_slice_intensities() # depends on [control=['if'], dat... |
def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None)
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token)
except ValueError:
... | def function[parse_raw_token, parameter[self, raw_token]]:
constant[Parse token and secret from raw token response.]
if compare[name[raw_token] is constant[None]] begin[:]
return[tuple[[<ast.Constant object at 0x7da1b26524a0>, <ast.Constant object at 0x7da1b2652470>, <ast.Constant object at 0x7d... | keyword[def] identifier[parse_raw_token] ( identifier[self] , identifier[raw_token] ):
literal[string]
keyword[if] identifier[raw_token] keyword[is] keyword[None] :
keyword[return] ( keyword[None] , keyword[None] , keyword[None] )
keyword[try] :
id... | def parse_raw_token(self, raw_token):
"""Parse token and secret from raw token response."""
if raw_token is None:
return (None, None, None) # depends on [control=['if'], data=[]]
# Load as json first then parse as query string
try:
token_data = json.loads(raw_token) # depends on [contr... |
def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False,
sort=None, copy=True):
"""
Concatenate pandas objects along a particular axis with optional set logic
along the other axes.
Can also add a layer o... | def function[concat, parameter[objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, sort, copy]]:
constant[
Concatenate pandas objects along a particular axis with optional set logic
along the other axes.
Can also add a layer of hierarchical indexing on the concatenatio... | keyword[def] identifier[concat] ( identifier[objs] , identifier[axis] = literal[int] , identifier[join] = literal[string] , identifier[join_axes] = keyword[None] , identifier[ignore_index] = keyword[False] ,
identifier[keys] = keyword[None] , identifier[levels] = keyword[None] , identifier[names] = keyword[None] , i... | def concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=None, copy=True):
"""
Concatenate pandas objects along a particular axis with optional set logic
along the other axes.
Can also add a layer of hierarchical indexin... |
def inv(matrix):
'''
5 has way too many multiplies.
>> from sympy import *
>> from sympy.abc import *
>> Matrix([a]).inv()
Matrix([[1/a]])
>> cse(Matrix([[a, b], [c, d]]).inv())
Matrix([
[1/a + b*c/(a**2*(d - b*c/a)), -b/(a*(d - b*c/a))],
[ -c/(a*(d - b*c/a)), ... | def function[inv, parameter[matrix]]:
constant[
5 has way too many multiplies.
>> from sympy import *
>> from sympy.abc import *
>> Matrix([a]).inv()
Matrix([[1/a]])
>> cse(Matrix([[a, b], [c, d]]).inv())
Matrix([
[1/a + b*c/(a**2*(d - b*c/a)), -b/(a*(d - b*c/a))],
[ ... | keyword[def] identifier[inv] ( identifier[matrix] ):
literal[string]
identifier[size] = identifier[len] ( identifier[matrix] )
keyword[if] identifier[size] == literal[int] :
keyword[return] [ literal[int] / identifier[matrix] [ literal[int] ]]
keyword[elif] identifier[size] == literal[... | def inv(matrix):
"""
5 has way too many multiplies.
>> from sympy import *
>> from sympy.abc import *
>> Matrix([a]).inv()
Matrix([[1/a]])
>> cse(Matrix([[a, b], [c, d]]).inv())
Matrix([
[1/a + b*c/(a**2*(d - b*c/a)), -b/(a*(d - b*c/a))],
[ -c/(a*(d - b*c/a)), ... |
def glob(self, filename):
"""Returns a list of files that match the given pattern(s)."""
# Only support prefix with * at the end and no ? in the string
star_i = filename.find('*')
quest_i = filename.find('?')
if quest_i >= 0:
raise NotImplementedError(
... | def function[glob, parameter[self, filename]]:
constant[Returns a list of files that match the given pattern(s).]
variable[star_i] assign[=] call[name[filename].find, parameter[constant[*]]]
variable[quest_i] assign[=] call[name[filename].find, parameter[constant[?]]]
if compare[name[que... | keyword[def] identifier[glob] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[star_i] = identifier[filename] . identifier[find] ( literal[string] )
identifier[quest_i] = identifier[filename] . identifier[find] ( literal[string] )
keyword[if] ident... | def glob(self, filename):
"""Returns a list of files that match the given pattern(s)."""
# Only support prefix with * at the end and no ? in the string
star_i = filename.find('*')
quest_i = filename.find('?')
if quest_i >= 0:
raise NotImplementedError('{} not supported by compat glob'.format... |
def parse(cls, filename, root=None):
"""Parses the file at filename and returns a PythonFile.
If root is specified, it will open the file with root prepended to the path. The idea is to
allow for errors to contain a friendlier file path than the full absolute path.
"""
if root is not None:
if... | def function[parse, parameter[cls, filename, root]]:
constant[Parses the file at filename and returns a PythonFile.
If root is specified, it will open the file with root prepended to the path. The idea is to
allow for errors to contain a friendlier file path than the full absolute path.
]
i... | keyword[def] identifier[parse] ( identifier[cls] , identifier[filename] , identifier[root] = keyword[None] ):
literal[string]
keyword[if] identifier[root] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[os] . identifier[path] . identifier[isabs] ( identifier[filename] ):
... | def parse(cls, filename, root=None):
"""Parses the file at filename and returns a PythonFile.
If root is specified, it will open the file with root prepended to the path. The idea is to
allow for errors to contain a friendlier file path than the full absolute path.
"""
if root is not None:
... |
def do_package(self, line):
"""package <package-pid> <science-metadata-pid> <science-pid> [science- pid.
...] Create a simple OAI-ORE Resource Map on a Member Node.
"""
pids = self._split_args(line, 3, -1, pad=False)
self._command_processor.create_package(pids)
self._pr... | def function[do_package, parameter[self, line]]:
constant[package <package-pid> <science-metadata-pid> <science-pid> [science- pid.
...] Create a simple OAI-ORE Resource Map on a Member Node.
]
variable[pids] assign[=] call[name[self]._split_args, parameter[name[line], constant[3], <as... | keyword[def] identifier[do_package] ( identifier[self] , identifier[line] ):
literal[string]
identifier[pids] = identifier[self] . identifier[_split_args] ( identifier[line] , literal[int] ,- literal[int] , identifier[pad] = keyword[False] )
identifier[self] . identifier[_command_processor... | def do_package(self, line):
"""package <package-pid> <science-metadata-pid> <science-pid> [science- pid.
...] Create a simple OAI-ORE Resource Map on a Member Node.
"""
pids = self._split_args(line, 3, -1, pad=False)
self._command_processor.create_package(pids)
self._print_info_if_verb... |
def infer_genome(genome_object_string_or_int):
"""
If given an integer, return associated human EnsemblRelease for that
Ensembl version.
If given a string, return latest EnsemblRelease which has a reference
of the same name.
If given a PyEnsembl Genome, simply return it.
"""
if isinsta... | def function[infer_genome, parameter[genome_object_string_or_int]]:
constant[
If given an integer, return associated human EnsemblRelease for that
Ensembl version.
If given a string, return latest EnsemblRelease which has a reference
of the same name.
If given a PyEnsembl Genome, simply re... | keyword[def] identifier[infer_genome] ( identifier[genome_object_string_or_int] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[genome_object_string_or_int] , identifier[Genome] ):
keyword[return] identifier[genome_object_string_or_int]
keyword[if] identifier[is_integer... | def infer_genome(genome_object_string_or_int):
"""
If given an integer, return associated human EnsemblRelease for that
Ensembl version.
If given a string, return latest EnsemblRelease which has a reference
of the same name.
If given a PyEnsembl Genome, simply return it.
"""
if isinsta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.