code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def editproject(self, project_id, **kwargs):
"""
Edit an existing project.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param default_branch: they default branch
:param description: short project d... | Edit an existing project.
:param name: new project name
:param path: custom repository name for new project. By default generated based on name
:param default_branch: they default branch
:param description: short project description
:param issues_enabled:
:param merge_re... |
def stackexchange_request(self, path, callback, access_token=None,
post_args=None, **kwargs):
"""Make a request to the StackExchange API, passing in the path, a
callback, the access token, optional post arguments and keyword
arguments to be added as values in the request b... | Make a request to the StackExchange API, passing in the path, a
callback, the access token, optional post arguments and keyword
arguments to be added as values in the request body or URI |
def _compute_term2(self, C, mag, rrup):
"""
This computes the term f2 in equation 32, page 1021
"""
c78_factor = (C['c7'] * np.exp(C['c8'] * mag)) ** 2
R = np.sqrt(rrup ** 2 + c78_factor)
return C['c4'] * np.log(R) + (C['c5'] + C['c6'] * mag) * rrup | This computes the term f2 in equation 32, page 1021 |
def getSrcBlockParents(self, url, block):
"""
List block at src DBS
"""
#blockname = block.replace("#", urllib.quote_plus('#'))
#resturl = "%s/blockparents?block_name=%s" % (url, blockname)
params={'block_name':block}
return cjson.decode(self.callDBSService(url, '... | List block at src DBS |
def _converged(self):
"""Check convergence based on maximum absolute difference
Returns
-------
converged : boolean
Whether the parameter estimation converged.
max_diff : float
Maximum absolute difference between prior and posterior.
"""
... | Check convergence based on maximum absolute difference
Returns
-------
converged : boolean
Whether the parameter estimation converged.
max_diff : float
Maximum absolute difference between prior and posterior. |
def killall(self, everywhere=False):
"""Kills all nailgun servers started by pants.
:param bool everywhere: If ``True``, kills all pants-started nailguns on this machine;
otherwise restricts the nailguns killed to those started for the
current bu... | Kills all nailgun servers started by pants.
:param bool everywhere: If ``True``, kills all pants-started nailguns on this machine;
otherwise restricts the nailguns killed to those started for the
current build root. |
def total_length(self):
"""Returns the total length of the captions."""
if not self._captions:
return 0
return int(self._captions[-1].end_in_seconds) - int(self._captions[0].start_in_seconds) | Returns the total length of the captions. |
def _render_condition(field, field_type, comparators):
"""Render a single query condition.
Parameters
----------
field : str
The field the condition applies to
field_type : str
The data type of the field.
comparators : array_like
An iterable of logic operators to use.
... | Render a single query condition.
Parameters
----------
field : str
The field the condition applies to
field_type : str
The data type of the field.
comparators : array_like
An iterable of logic operators to use.
Returns
-------
str
a condition string. |
def _identify_dict(core):
"""Specification for a dictionary."""
if not core:
return {}, 1, (), int
core = core.copy()
key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0]
shape = numpy.array(core[key]).shape
dtype = numpy.array(core[key]).dtype
dim = len(key)
return core... | Specification for a dictionary. |
def rotate_about(self, p, theta):
"""
Rotate counter-clockwise around a point, by theta degrees.
Positive y goes *up,* as in traditional mathematics.
The new position is returned as a new Point.
"""
result = self.clone()
result.translate(-p.x, -p.y)
resu... | Rotate counter-clockwise around a point, by theta degrees.
Positive y goes *up,* as in traditional mathematics.
The new position is returned as a new Point. |
def delete(self, filename):
"""Delete a file from the repository.
This method will not delete a script from a migrated JSS.
Please remove migrated scripts with jss.Script.delete.
Args:
filename: String filename only (i.e. no path) of file to
delete. Will han... | Delete a file from the repository.
This method will not delete a script from a migrated JSS.
Please remove migrated scripts with jss.Script.delete.
Args:
filename: String filename only (i.e. no path) of file to
delete. Will handle deleting scripts vs. packages
... |
def set_granularity(self, level):
"""
Set the values for
:data:`~aeneas.runtimeconfiguration.RuntimeConfiguration.MFCC_WINDOW_LENGTH`
and
:data:`~aeneas.runtimeconfiguration.RuntimeConfiguration.MFCC_WINDOW_SHIFT`
matching the given granularity level.
Currently s... | Set the values for
:data:`~aeneas.runtimeconfiguration.RuntimeConfiguration.MFCC_WINDOW_LENGTH`
and
:data:`~aeneas.runtimeconfiguration.RuntimeConfiguration.MFCC_WINDOW_SHIFT`
matching the given granularity level.
Currently supported levels:
* ``1`` (paragraph)
... |
def skip_incremental(self, *criteria):
"""Perform an incremental check on a set of criteria.
This can be used to execute a part of a crawler only once per an
interval (which is specified by the ``expire`` setting). If the
operation has already been performed (and should thus be skipped)... | Perform an incremental check on a set of criteria.
This can be used to execute a part of a crawler only once per an
interval (which is specified by the ``expire`` setting). If the
operation has already been performed (and should thus be skipped),
this will return ``True``. If the operat... |
def handleError(self, error_code, message):
'''Log and set the controller state.'''
self._fail = True
self.reason = error_code
self._error = message | Log and set the controller state. |
def registry_storage(cls):
""" Get registry storage
:return: WTaskRegistryBase
"""
if cls.__registry_storage__ is None:
raise ValueError('__registry_storage__ must be defined')
if isinstance(cls.__registry_storage__, WTaskRegistryBase) is False:
raise TypeError("Property '__registry_storage__' is inval... | Get registry storage
:return: WTaskRegistryBase |
def delete(self):
"""Delete this object from the One Codex server."""
check_bind(self)
if self.id is None:
raise ServerError("{} object does not exist yet".format(self.__class__.name))
elif not self.__class__._has_schema_method("destroy"):
raise MethodNotSupported... | Delete this object from the One Codex server. |
def dimension_set(self, p_dim, s_dim=None, dimensions=None, extant=set()):
"""
Return a dict that describes the combination of one or two dimensions, for a plot
:param p_dim:
:param s_dim:
:param dimensions:
:param extant:
:return:
"""
if not dim... | Return a dict that describes the combination of one or two dimensions, for a plot
:param p_dim:
:param s_dim:
:param dimensions:
:param extant:
:return: |
def output_format_lock(self, packages, **kwargs):
""" Text to lock file """
self._output_config['type'] = PLAIN
text = ''
tmp_packages = OrderedDict()
columns = self._config.get_columns()
widths = {}
for _pkg in packages.values():
_pkg_name = _pkg.pack... | Text to lock file |
def print_obj(arg, frame, format=None, short=False):
"""Return a string representation of an object """
try:
if not frame:
# ?? Should we have set up a dummy globals
# to have persistence?
obj = eval(arg, None, None)
else:
obj = eval(arg, frame.f_g... | Return a string representation of an object |
def window_flattop(N, mode='symmetric',precision=None):
r"""Flat-top tapering window
Returns symmetric or periodic flat top window.
:param N: window length
:param mode: way the data are normalised. If mode is *symmetric*, then
divide n by N-1. IF mode is *periodic*, divide by N,
to be ... | r"""Flat-top tapering window
Returns symmetric or periodic flat top window.
:param N: window length
:param mode: way the data are normalised. If mode is *symmetric*, then
divide n by N-1. IF mode is *periodic*, divide by N,
to be consistent with octave code.
When using windows for fil... |
def salt_ssh(project, target, module, args=None, kwargs=None):
"""
Execute a `salt-ssh` command
"""
cmd = ['salt-ssh']
cmd.extend(generate_salt_cmd(target, module, args, kwargs))
cmd.append('--state-output=mixed')
cmd.append('--roster-file=%s' % project.roster_path)
cmd.append('--config-... | Execute a `salt-ssh` command |
def build_dated_queryset(self):
"""
Build pages for all years in the queryset.
"""
qs = self.get_dated_queryset()
months = self.get_date_list(qs)
[self.build_month(dt) for dt in months] | Build pages for all years in the queryset. |
def get_resampled_coordinates(lons, lats):
"""
Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or nump... | Resample polygon line segments and return the coordinates of the new
vertices. This limits distortions when projecting a polygon onto a
spherical surface.
Parameters define longitudes and latitudes of a point collection in the
form of lists or numpy arrays.
:return:
A tuple of two numpy ar... |
def complete_use(self, text, *_):
""" Autocomplete for use """
return [t + " " for t in REGIONS if t.startswith(text)] | Autocomplete for use |
def add_tags(self, md5, tags):
"""Add tags to this sample"""
if not tags: return
tag_set = set(self.get_tags(md5)) if self.get_tags(md5) else set()
if isinstance(tags, str):
tags = [tags]
for tag in tags:
tag_set.add(tag)
self.data_store.store_work... | Add tags to this sample |
def get_info(self, component):
""" Get the information about this component """
# Grab it, clean it and ship it
work_results = self._get_work_results('info', component)
return self.data_store.clean_for_serialization(work_results) | Get the information about this component |
def _find_highest_supported_command(self, *segment_classes, **kwargs):
"""Search the BPD for the highest supported version of a segment."""
return_parameter_segment = kwargs.get("return_parameter_segment", False)
parameter_segment_name = "{}I{}S".format(segment_classes[0].TYPE[0], segment_class... | Search the BPD for the highest supported version of a segment. |
def is_pointer(type_):
"""returns True, if type represents C++ pointer type, False otherwise"""
return does_match_definition(type_,
cpptypes.pointer_t,
(cpptypes.const_t, cpptypes.volatile_t)) \
or does_match_definition(type_,
... | returns True, if type represents C++ pointer type, False otherwise |
def normalize_url(url):
""" Normalize url
"""
if not url:
return url
matched = _windows_path_prefix.match(url)
if matched:
return path2url(url)
p = six.moves.urllib.parse.urlparse(url)
if p.scheme == '':
if p.netloc == '' and p.path != '':
# it should be... | Normalize url |
def command(self):
"""Manually import an OFX into a nYNAB budget"""
print('pynYNAB OFX import')
args = self.parser.parse_args()
verify_common_args(args)
client = clientfromkwargs(**args)
delta = do_ofximport(args.file, client)
client.push(expected_delta=delta) | Manually import an OFX into a nYNAB budget |
def get_manifests(self, repo_name, digest=None):
'''get_manifests calls get_manifest for each of the schema versions,
including v2 and v1. Version 1 includes image layers and metadata,
and version 2 must be parsed for a specific manifest, and the 2nd
call includes the layers. If a digest is not... | get_manifests calls get_manifest for each of the schema versions,
including v2 and v1. Version 1 includes image layers and metadata,
and version 2 must be parsed for a specific manifest, and the 2nd
call includes the layers. If a digest is not provided
latest is used.
Parameters
... |
def getShocks(self):
'''
Determine which agents switch from employment to unemployment. All unemployed agents remain
unemployed until death.
Parameters
----------
None
Returns
-------
None
'''
employed = self.eStateNow == 1.0
... | Determine which agents switch from employment to unemployment. All unemployed agents remain
unemployed until death.
Parameters
----------
None
Returns
-------
None |
def jsonrpc_map(self):
""" Map of json-rpc available calls.
:return str:
"""
result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([
"{0}: {1}".format(fname, f.__doc__)
for fname, f in self.dispatcher.items()
]))
return Response(resul... | Map of json-rpc available calls.
:return str: |
def view_dot_graph(graph, filename=None, view=False):
"""
View the given DOT source. If view is True, the image is rendered
and viewed by the default application in the system. The file path of
the output is returned. If view is False, a graphviz.Source object is
returned. If view is False and t... | View the given DOT source. If view is True, the image is rendered
and viewed by the default application in the system. The file path of
the output is returned. If view is False, a graphviz.Source object is
returned. If view is False and the environment is in a IPython session,
an IPython image objec... |
def wait_for_port(host, port=22, timeout=900, gateway=None):
'''
Wait until a connection to the specified port can be made on a specified
host. This is usually port 22 (for SSH), but in the case of Windows
installations, it might be port 445 (for psexec). It may also be an
alternate port for SSH, de... | Wait until a connection to the specified port can be made on a specified
host. This is usually port 22 (for SSH), but in the case of Windows
installations, it might be port 445 (for psexec). It may also be an
alternate port for SSH, depending on the base image. |
def apply_rcparams(self):
"""
Set the rcParams
"""
from matplotlib import rcParams
for key, val in self.rcParams.items():
try:
rcParams[key] = val
except Exception as e:
msg = ("""Setting "mpl.rcParams['{}']={}" """
... | Set the rcParams |
def _compute_static_prob(tri, com):
"""
For an object with the given center of mass, compute
the probability that the given tri would be the first to hit the
ground if the object were dropped with a pose chosen uniformly at random.
Parameters
----------
tri: (3,3) float, the vertices of a t... | For an object with the given center of mass, compute
the probability that the given tri would be the first to hit the
ground if the object were dropped with a pose chosen uniformly at random.
Parameters
----------
tri: (3,3) float, the vertices of a triangle
cm: (3,) float, the center of mass ... |
def for_category(self, category, context=None):
"""Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`)
"""
assert self.ins... | Returns actions list for this category in current application.
Actions are filtered according to :meth:`.Action.available`.
if `context` is None, then current action context is used
(:attr:`context`) |
def browse_stations_categories(self):
"""Get the categories from Browse Stations.
Returns:
list: Station categories that can contain subcategories.
"""
response = self._call(
mc_calls.BrowseStationCategories
)
station_categories = response.body.get('root', {}).get('subcategories', [])
return stat... | Get the categories from Browse Stations.
Returns:
list: Station categories that can contain subcategories. |
def define_options(self, names, parser_options=None):
"""Given a list of option names, this returns a list of dicts
defined in all_options and self.shared_options. These can then
be used to populate the argparser with"""
def copy_option(options, name):
return {k: v for k, v i... | Given a list of option names, this returns a list of dicts
defined in all_options and self.shared_options. These can then
be used to populate the argparser with |
def print_smart_tasks():
"""Print smart tasks as JSON"""
print("Printing information about smart tasks")
tasks = api(gateway.get_smart_tasks())
if len(tasks) == 0:
exit(bold("No smart tasks defined"))
container = []
for task in tasks:
container.append(api(task).task_control.raw)... | Print smart tasks as JSON |
def pretty_constants(self):
"""
the sequence of tuples (index, pretty type, value) of the constant
pool entries.
"""
for i in range(1, len(self.consts)):
t, v = self.pretty_const(i)
if t:
yield (i, t, v) | the sequence of tuples (index, pretty type, value) of the constant
pool entries. |
def get_objective_requisite_assignment_session(self, *args, **kwargs):
"""Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request... | Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request
raise: Unimplemented -
supports_objective_requisite_assi... |
def check_file_path(self, path):
"""
Ensure file exists at the provided path
:type path: string
:param path: path to directory to check
"""
if os.path.exists(path) is not True:
msg = "File Not Found {}".format(path)
raise OSError(msg) | Ensure file exists at the provided path
:type path: string
:param path: path to directory to check |
def double_prompt_for_plaintext_password():
"""Get the desired password from the user through a double prompt."""
password = 1
password_repeat = 2
while password != password_repeat:
password = getpass.getpass('Enter password: ')
password_repeat = getpass.getpass('Repeat password: ')
... | Get the desired password from the user through a double prompt. |
def send_many(self, outputs_array, fee=None, change_addr=None, id=None, endpoint=None):
"""
Args:
outputs_array: (dict) array, the data structure of each element in the array is as follows:
{"asset": <asset>,"value": <value>,"address": <address>}
asset: (str) ... | Args:
outputs_array: (dict) array, the data structure of each element in the array is as follows:
{"asset": <asset>,"value": <value>,"address": <address>}
asset: (str) asset identifier (for NEO: 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b', for GAS: '602... |
def _validate_currency(self, currency):
"""Check if the given order book is valid.
:param currency: Major currency name in lowercase.
:type currency: str | unicode
:raise InvalidCurrencyError: If an invalid major currency is given.
"""
if currency not in self.major_curre... | Check if the given order book is valid.
:param currency: Major currency name in lowercase.
:type currency: str | unicode
:raise InvalidCurrencyError: If an invalid major currency is given. |
def dumps(value,encoding=None):
"""dumps(object,encoding=None) -> string
This function dumps a python object as a tnetstring.
"""
# This uses a deque to collect output fragments in reverse order,
# then joins them together at the end. It's measurably faster
# than creating all the intermedi... | dumps(object,encoding=None) -> string
This function dumps a python object as a tnetstring. |
def cancel(self, CorpNum, ItemCode, MgtKey, Memo=None, UserID=None):
""" 발행취소
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
M... | 발행취소
args
CorpNum : 팝빌회원 사업자번호
ItemCode : 명세서 종류 코드
[121 - 거래명세서], [122 - 청구서], [123 - 견적서],
[124 - 발주서], [125 - 입금표], [126 - 영수증]
MgtKey : 파트너 문서관리번호
Memo : 처리메모
UserID : 팝빌회원 아이디... |
def gcp_fixed_k(V,E,K):
"""gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
- K: number of colors to be used
Returns a model, ready to be solved.
"""
model = Model("... | gcp_fixed_k -- model for minimizing number of bad edges in coloring a graph
Parameters:
- V: set/list of nodes in the graph
- E: set/list of edges in the graph
- K: number of colors to be used
Returns a model, ready to be solved. |
def get_dvcs_info():
"""Gets current repository info from git"""
cmd = "git rev-list --count HEAD"
commit_count = str(
int(subprocess.check_output(shlex.split(cmd)).decode("utf8").strip())
)
cmd = "git rev-parse HEAD"
commit = str(subprocess.check_output(shlex.split(cmd)).decode("utf8").... | Gets current repository info from git |
def security_rule_present(name, access, direction, priority, protocol, security_group, resource_group,
destination_address_prefix=None, destination_port_range=None, source_address_prefix=None,
source_port_range=None, description=None, destination_address_prefixes=None... | .. versionadded:: 2019.2.0
Ensure a security rule exists.
:param name:
Name of the security rule.
:param access:
'allow' or 'deny'
:param direction:
'inbound' or 'outbound'
:param priority:
Integer between 100 and 4096 used for ordering rule application.
:pa... |
def bake(self):
"""
Bake a ``shell`` command so it's ready to execute and returns None.
:return: None
"""
command_list = self.command.split(' ')
command, args = command_list[0], command_list[1:]
self._sh_command = getattr(sh, command)
# Reconstruct comma... | Bake a ``shell`` command so it's ready to execute and returns None.
:return: None |
def tagMap(self):
""""Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping
ASN.1 tags to ASN.1 objects contained within callee.
"""
if self.tagSet:
return Set.tagMap.fget(self)
else:
return self.componentType.tagMapUnique | Return a :class:`~pyasn1.type.tagmap.TagMap` object mapping
ASN.1 tags to ASN.1 objects contained within callee. |
def sync_via_get(self, owner, id, **kwargs):
"""
Sync files (via GET)
Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to us... | Sync files (via GET)
Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to use webhooks or scripts to keep them always in sync.
This m... |
def close(self):
"""
Close the sockets
"""
self._socket.close()
if self._async_socket_cache:
self._async_socket_cache.close()
self._async_socket_cache = None | Close the sockets |
def install(self):
"""
install the server
"""
try:
if self.args.server is not None:
server = ServerLists(self.server_type)
DynamicImporter(
'ezhost',
server.name,
args=self.args,
... | install the server |
def verify_message(address, message, signature):
"""
Verify message was signed by the address
:param address: signing address
:param message: message to check
:param signature: signature being tested
:return:
"""
bitcoin_message = BitcoinMessage(message)
verified = VerifyMessage(addr... | Verify message was signed by the address
:param address: signing address
:param message: message to check
:param signature: signature being tested
:return: |
def top(self):
"""
The top-most row index in the vertical span of this cell.
"""
if self.vMerge is None or self.vMerge == ST_Merge.RESTART:
return self._tr_idx
return self._tc_above.top | The top-most row index in the vertical span of this cell. |
def _register_handler(handler, file_formats):
"""Register a handler for some file extensions.
Args:
handler (:obj:`BaseFileHandler`): Handler to be registered.
file_formats (str or list[str]): File formats to be handled by this
handler.
"""
if not isinstance(handler, BaseFil... | Register a handler for some file extensions.
Args:
handler (:obj:`BaseFileHandler`): Handler to be registered.
file_formats (str or list[str]): File formats to be handled by this
handler. |
def astat(args):
"""
%prog astat coverage.log
Create coverage-rho scatter plot.
"""
p = OptionParser(astat.__doc__)
p.add_option("--cutoff", default=1000, type="int",
help="Length cutoff [default: %default]")
p.add_option("--genome", default="",
help="Genom... | %prog astat coverage.log
Create coverage-rho scatter plot. |
def fit(sim_mat, D_len, cidx):
"""
Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.
D: numpy array - Symmetric distance matrix
k: ... | Algorithm maximizes energy between clusters, which is distinction in this algorithm. Distance matrix contains mostly 0, which are overlooked due to search of maximal distances. Algorithm does not try to retain k clusters.
D: numpy array - Symmetric distance matrix
k: int - number of clusters |
def set_span_from_ids(self, span_list):
"""
Sets the span for the term from list of ids
@type span_list: []
@param span_list: list of wf ids forming span
"""
this_span = Cspan()
this_span.create_from_ids(span_list)
self.node.append(this_span.get_node()) | Sets the span for the term from list of ids
@type span_list: []
@param span_list: list of wf ids forming span |
def apply_status_code(self, status_code):
"""
When a trace entity is generated under the http context,
the status code will affect this entity's fault/error/throttle flags.
Flip these flags based on status code.
"""
self._check_ended()
if not status_code:
... | When a trace entity is generated under the http context,
the status code will affect this entity's fault/error/throttle flags.
Flip these flags based on status code. |
def get_system_device_models(auth, url):
"""Takes string no input to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of diction... | Takes string no input to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each dictionary represents a single ... |
def parse_frequency(variant, info_key):
"""Parse any frequency from the info dict
Args:
variant(cyvcf2.Variant)
info_key(str)
Returns:
frequency(float): or None if frequency does not exist
"""
raw_annotation = variant.INFO.get(info_key)
raw_annotation = None if raw_anno... | Parse any frequency from the info dict
Args:
variant(cyvcf2.Variant)
info_key(str)
Returns:
frequency(float): or None if frequency does not exist |
def _process_templatedata(self, node, **_):
"""
Processes a `TemplateData` node, this is just a bit of as-is text
to be written to the output.
"""
# escape double quotes
value = re.sub('"', r'\\"', node.data)
# escape new lines
value = re.sub('\n', r'\\n... | Processes a `TemplateData` node, this is just a bit of as-is text
to be written to the output. |
def get_context_loop_positions(context):
"""
Return the paginated current position within a loop,
and the non-paginated position.
"""
try:
loop_counter = context['forloop']['counter']
except KeyError:
return 0, 0
try:
page = context['page_obj']
except KeyError:
... | Return the paginated current position within a loop,
and the non-paginated position. |
def pwd_phasebin(phases, mags, binsize=0.002, minbin=9):
'''
This bins the phased mag series using the given binsize.
'''
bins = np.arange(0.0, 1.0, binsize)
binnedphaseinds = npdigitize(phases, bins)
binnedphases, binnedmags = [], []
for x in npunique(binnedphaseinds):
thisbin_... | This bins the phased mag series using the given binsize. |
def sql(line, cell=None):
""" Create a SQL module with one or more queries. Use %sql --help for more details.
The supported syntax is:
%%sql [--module <modulename>]
[<optional Python code for default argument values>]
[<optional named queries>]
[<optional unnamed query>]
At least one query should be pr... | Create a SQL module with one or more queries. Use %sql --help for more details.
The supported syntax is:
%%sql [--module <modulename>]
[<optional Python code for default argument values>]
[<optional named queries>]
[<optional unnamed query>]
At least one query should be present. Named queries should star... |
def bind_arguments(func, args, kwargs):
"""Bind the arguments provided into a dict. When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it. This can be useful
to implement a cache decorator that uses the functi... | Bind the arguments provided into a dict. When passed a function,
a tuple of arguments and a dict of keyword arguments `bind_arguments`
returns a dict of names as the function would see it. This can be useful
to implement a cache decorator that uses the function arguments to build
the cache key based o... |
def compute_Pi_V(self, CDR3_seq, V_usage_mask):
"""Compute Pi_V.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V)*P(delV|V). This corresponds to V_{x_1}.
For clarity in parsing the algorithm implementation, we include which
... | Compute Pi_V.
This function returns the Pi array from the model factors of the V genomic
contributions, P(V)*P(delV|V). This corresponds to V_{x_1}.
For clarity in parsing the algorithm implementation, we include which
instance attributes are used in the method as 'param... |
def single_column_accuracy_comparison():
"""
Plot accuracy of the ideal observer (with and without locations) as the number
of sensations increases.
"""
pointRange = 1
numTrials = 10
args = []
resultsDir = os.path.dirname(os.path.realpath(__file__))
for t in range(numTrials):
for useLocation in ... | Plot accuracy of the ideal observer (with and without locations) as the number
of sensations increases. |
def send_with_options(self, *, args=None, kwargs=None, delay=None, **options):
"""Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the ... | Asynchronously send a message to this actor, along with an
arbitrary set of processing options for the broker and
middleware.
Parameters:
args(tuple): Positional arguments that are passed to the actor.
kwargs(dict): Keyword arguments that are passed to the actor.
d... |
def by_pdb(self, pdb_id, take_top_percentile = 30.0, cut_off = None, matrix = None, sequence_identity_cut_off = None, silent = None):
'''Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb_id.
Only protein chains are considered in the matching so e.... | Returns a list of all PDB files which contain protein sequences similar to the protein sequences of pdb_id.
Only protein chains are considered in the matching so e.g. some results may have DNA or RNA chains or ligands
while some may not. |
def _setup_arch(self, arch_mode=None):
"""Set up architecture.
"""
# set up architecture information
self.arch_info = None
if self.binary.architecture == ARCH_X86:
self._setup_x86_arch(arch_mode)
else:
# TODO: add arch to the binary file class.
... | Set up architecture. |
def create(self, source, destination, gateway_ip, comment=None):
"""
Add a new policy route to the engine.
:param str source: network address with /cidr
:param str destination: network address with /cidr
:param str gateway: IP address, must be on source network
:... | Add a new policy route to the engine.
:param str source: network address with /cidr
:param str destination: network address with /cidr
:param str gateway: IP address, must be on source network
:param str comment: optional comment |
def stop_channels(self):
"""Stops all the running channels for this kernel.
"""
if self.shell_channel.is_alive():
self.shell_channel.stop()
if self.sub_channel.is_alive():
self.sub_channel.stop()
if self.stdin_channel.is_alive():
self.stdin_cha... | Stops all the running channels for this kernel. |
def draw(self, milliseconds, surface):
"""Render the bounds of this collision ojbect onto the specified surface."""
super(CollidableObj, self).draw(milliseconds, surface) | Render the bounds of this collision ojbect onto the specified surface. |
def ticker_pitch(ax=None):
'''Set the y-axis of the given axes to MIDI frequencies
Parameters
----------
ax : matplotlib.pyplot.axes
The axes handle to apply the ticker.
By default, uses the current axes handle.
'''
ax, _ = __get_axes(ax=ax)
ax.yaxis.set_major_formatter(FMT... | Set the y-axis of the given axes to MIDI frequencies
Parameters
----------
ax : matplotlib.pyplot.axes
The axes handle to apply the ticker.
By default, uses the current axes handle. |
def store_image(cls, http_client, link_hash, src, config):
"""\
Writes an image src http string to disk as a temporary file
and returns the LocallyStoredImage object
that has the info you should need on the image
"""
# check for a cache hit already on disk
image =... | \
Writes an image src http string to disk as a temporary file
and returns the LocallyStoredImage object
that has the info you should need on the image |
def send(self, template, email, _vars=None, options=None, schedule_time=None, limit=None):
"""
Remotely send an email template to a single email address.
http://docs.sailthru.com/api/send
@param template: template string
@param email: Email value
@param _vars: a key/value... | Remotely send an email template to a single email address.
http://docs.sailthru.com/api/send
@param template: template string
@param email: Email value
@param _vars: a key/value hash of the replacement vars to use in the send. Each var may be referenced as {varname} within the template i... |
def heal(self, channel=0, method="linear", fill_value=np.nan, verbose=True):
"""
Remove nans from channel using interpolation.
Parameters
----------
channel : int or str (optional)
Channel to heal. Default is 0.
method : {'linear', 'nearest', 'cubic'} (option... | Remove nans from channel using interpolation.
Parameters
----------
channel : int or str (optional)
Channel to heal. Default is 0.
method : {'linear', 'nearest', 'cubic'} (optional)
The interpolation method. Note that cubic interpolation is only
possi... |
def session_commit(self, session):
"""Send session_commit signal in sqlalchemy ``before_commit``.
This marks the success of session so the session may enter commit
state.
"""
# this may happen when there's nothing to commit
if not hasattr(session, 'meepo_unique_id'):
... | Send session_commit signal in sqlalchemy ``before_commit``.
This marks the success of session so the session may enter commit
state. |
def cli(env, identifier, postinstall, key, image):
"""Reload operating system on a virtual server."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
keys = []
if key:
for single_key in key:
resolver = SoftLayer.SshKeyManager(e... | Reload operating system on a virtual server. |
def send_email(self, **kwargs):
"""
Sends an email using Mandrill's API. Returns a
Requests :class:`Response` object.
At a minimum kwargs must contain the keys to, from_email, and text.
Everything passed as kwargs except for the keywords 'key', 'async',
and 'ip_pool' will... | Sends an email using Mandrill's API. Returns a
Requests :class:`Response` object.
At a minimum kwargs must contain the keys to, from_email, and text.
Everything passed as kwargs except for the keywords 'key', 'async',
and 'ip_pool' will be sent as key-value pairs in the message object.
... |
def _canBeExpanded( self, headVerbRoot, headVerbWID, suitableNomAdvExpansions, expansionVerbs, widToToken ):
''' Teeb kindlaks, kas kontekst on verbiahela laiendamiseks piisavalt selge/yhene:
1) Nii 'nom/adv' kandidaate kui ka Vinf kandidaate on täpselt üks;
2) Nom/adv ei kuulu mi... | Teeb kindlaks, kas kontekst on verbiahela laiendamiseks piisavalt selge/yhene:
1) Nii 'nom/adv' kandidaate kui ka Vinf kandidaate on täpselt üks;
2) Nom/adv ei kuulu mingi suurema fraasi kooseisu (meetodi _isLikelyNotPhrase() abil);
Kui tingimused täidetud, tagastab lisatava v... |
def mmols(self):
""" Dict of filepaths for all mmol files associated with code.
Notes
-----
Downloads mmol files if not already present.
Returns
-------
mmols_dict : dict, or None.
Keys : int
mmol number
Values : str
... | Dict of filepaths for all mmol files associated with code.
Notes
-----
Downloads mmol files if not already present.
Returns
-------
mmols_dict : dict, or None.
Keys : int
mmol number
Values : str
Filepath for the c... |
def constant_image_value(image, crs='EPSG:32613', scale=1):
"""Extract the output value from a calculation done with constant images"""
return getinfo(ee.Image(image).reduceRegion(
reducer=ee.Reducer.first(), scale=scale,
geometry=ee.Geometry.Rectangle([0, 0, 10, 10], crs, False))) | Extract the output value from a calculation done with constant images |
def get_auth_stdin(refresh_token_filename, manual_login=False):
"""Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through ... | Simple wrapper for :func:`get_auth` that prompts the user using stdin.
Args:
refresh_token_filename (str): Path to file where refresh token will be
cached.
manual_login (bool): If true, prompt user to log in through a browser
and enter authorization code manually. Defaults t... |
def _set_uplink_switch(self, v, load=False):
"""
Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_uplink_switch is considered as a private
method. Backends looking to populate this v... | Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_uplink_switch is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_uplink_... |
def remove(self, name, func):
''' Remove a callback from a hook. '''
was_empty = self._empty()
if name in self.hooks and func in self.hooks[name]:
self.hooks[name].remove(func)
if self.app and not was_empty and self._empty(): self.app.reset() | Remove a callback from a hook. |
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)
... | get location of the slice
:param dcmdata: dicom data structure
:param teil: filename. Used when slice location doesnt exist
:return: |
def set_helper(self, helper):
"""
.. todo::
Document this.
"""
# We don't want to "unset" in this method.
if helper is None:
return
# Get the right kind of helper if given a DockerHelper
if isinstance(helper, DockerHelper):
he... | .. todo::
Document this. |
def copy(self, parent=None):
"""Copies an existing structure and all of it's children"""
new = Structure(None, parent=parent)
new.key = self.key
new.type_ = self.type_
new.val_guaranteed = self.val_guaranteed
new.key_guaranteed = self.key_guaranteed
for child in s... | Copies an existing structure and all of it's children |
def resolve_sound(self, sound):
"""Function tries to identify a sound in the data.
Notes
-----
The function tries to resolve sounds to take a sound with less complex
features in order to yield the next approximate sound class, if the
transcription data are sound classes.... | Function tries to identify a sound in the data.
Notes
-----
The function tries to resolve sounds to take a sound with less complex
features in order to yield the next approximate sound class, if the
transcription data are sound classes. |
def data_interp(self, i, currenttime):
"""
Method to streamline request for data from cache,
Uses linear interpolation bewtween timesteps to
get u,v,w,temp,salt
"""
if self.active.value is True:
while self.get_data.value is True:
lo... | Method to streamline request for data from cache,
Uses linear interpolation bewtween timesteps to
get u,v,w,temp,salt |
def expose_event(self, widget, event):
"""When an area of the window is exposed, we just copy out of the
server-side, off-screen surface to that area.
"""
x, y, width, height = event.area
self.logger.debug("surface is %s" % self.surface)
if self.surface is not None:
... | When an area of the window is exposed, we just copy out of the
server-side, off-screen surface to that area. |
def linestyle(i,a=5,b=3):
'''
provide one out of 25 unique combinations of style, color and mark
use in combination with markevery=a+mod(i,b) to add spaced points,
here a would be the base spacing that would depend on the data
density, modulated with the number of lines to be plotted (b)
Param... | provide one out of 25 unique combinations of style, color and mark
use in combination with markevery=a+mod(i,b) to add spaced points,
here a would be the base spacing that would depend on the data
density, modulated with the number of lines to be plotted (b)
Parameters
----------
i : integer
... |
def condor_submit(cmd):
"""
Submits cmd to HTCondor queue
Parameters
----------
cmd: string
Command to be submitted
Returns
-------
int
returncode value from calling the submission command.
"""
is_running = subprocess.call('condor_status', shell=True) == 0
i... | Submits cmd to HTCondor queue
Parameters
----------
cmd: string
Command to be submitted
Returns
-------
int
returncode value from calling the submission command. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.