positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def _parse_world_info(self, world_info_table):
"""
Parses the World Information table from Tibia.com and adds the found values to the object.
Parameters
----------
world_info_table: :class:`list`[:class:`bs4.Tag`]
"""
world_info = {}
for row in world_info... | Parses the World Information table from Tibia.com and adds the found values to the object.
Parameters
----------
world_info_table: :class:`list`[:class:`bs4.Tag`] |
def _rotate_and_chop(self, verts, normal, axis=[0, 0, 1]):
r"""
Method to rotate a set of vertices (or coords) to align with an axis
points must be coplanar and normal must be given
Chops axis coord to give vertices back in 2D
Used to prepare verts for printing or calculating con... | r"""
Method to rotate a set of vertices (or coords) to align with an axis
points must be coplanar and normal must be given
Chops axis coord to give vertices back in 2D
Used to prepare verts for printing or calculating convex hull in order
to arrange them in hull order for calcula... |
def split_certificate(certificate_path, destination_folder, password=None):
"""Splits a PKCS12 certificate into Base64-encoded DER certificate and key.
This method splits a potentially password-protected
`PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate
(format ``.p12`` or ``.pfx``) into on... | Splits a PKCS12 certificate into Base64-encoded DER certificate and key.
This method splits a potentially password-protected
`PKCS12 <https://en.wikipedia.org/wiki/PKCS_12>`_ certificate
(format ``.p12`` or ``.pfx``) into one certificate and one key part, both in
`pem <https://en.wikipedia.org/wiki/X.5... |
def click(self, force_click=False):
"""
Clicks the element
@type force_click: bool
@param force_click: force a click on the element using javascript, skipping webdriver
@rtype: WebElementWrapper
@return: Returns itself
"""
js_exec... | Clicks the element
@type force_click: bool
@param force_click: force a click on the element using javascript, skipping webdriver
@rtype: WebElementWrapper
@return: Returns itself |
def default_unmarshaller(instance, state):
"""
Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
... | Restore the state of an object.
If the ``__setstate__()`` method exists on the instance, it is called with the state object
as the argument. Otherwise, the instance's ``__dict__`` is replaced with ``state``.
:param instance: an uninitialized instance
:param state: the state object, as returned by :fun... |
def GroupSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a group field."""
tag_size = _TagSize(field_number) * 2
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
result += element.ByteSize()
... | Returns a sizer for a group field. |
def marvcli_undiscard(datasets):
"""Undiscard DATASETS previously discarded."""
create_app()
setids = parse_setids(datasets, discarded=True)
dataset = Dataset.__table__
stmt = dataset.update()\
.where(dataset.c.setid.in_(setids))\
.values(discarded=False)
db.... | Undiscard DATASETS previously discarded. |
def gap_to_sorl(time_gap):
"""
P1D to +1DAY
:param time_gap:
:return: solr's format duration.
"""
quantity, unit = parse_ISO8601(time_gap)
if unit[0] == "WEEKS":
return "+{0}DAYS".format(quantity * 7)
else:
return "+{0}{1}".format(quantity, unit[0]) | P1D to +1DAY
:param time_gap:
:return: solr's format duration. |
def str_to_etree(xml_str, encoding='utf-8'):
"""Deserialize API XML doc to an ElementTree.
Args:
xml_str: bytes
DataONE API XML doc
encoding: str
Decoder to use when converting the XML doc ``bytes`` to a Unicode str.
Returns:
ElementTree: Matching the API version of the ... | Deserialize API XML doc to an ElementTree.
Args:
xml_str: bytes
DataONE API XML doc
encoding: str
Decoder to use when converting the XML doc ``bytes`` to a Unicode str.
Returns:
ElementTree: Matching the API version of the XML doc. |
def zs(inlist):
"""
Returns a list of z-scores, one for each score in the passed list.
Usage: lzs(inlist)
"""
zscores = []
for item in inlist:
zscores.append(z(inlist, item))
return zscores | Returns a list of z-scores, one for each score in the passed list.
Usage: lzs(inlist) |
def list_namespaced_cron_job(self, namespace, **kwargs):
"""
list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_cron_job(namespace, async_... | list or watch objects of kind CronJob
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_cron_job(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
... |
def describe_api_integration_response(restApiId, resourcePath, httpMethod, statusCode,
region=None, key=None, keyid=None, profile=None):
'''
Get an integration response for a given method in a given API
CLI Example:
.. code-block:: bash
salt myminion boto... | Get an integration response for a given method in a given API
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.describe_api_integration_response restApiId resourcePath httpMethod statusCode |
def add(self, item):
"""
Transactional implementation of :func:`List.add(item) <hazelcast.proxy.list.List.add>`
:param item: (object), the new item to be added.
:return: (bool), ``true`` if the item is added successfully, ``false`` otherwise.
"""
check_not_none(item, "it... | Transactional implementation of :func:`List.add(item) <hazelcast.proxy.list.List.add>`
:param item: (object), the new item to be added.
:return: (bool), ``true`` if the item is added successfully, ``false`` otherwise. |
def _from_args(args):
"""Factory method to create a new instance from command line args.
:param args: instance of :class:`argparse.Namespace`
"""
return bugzscout.BugzScout(args.url, args.user, args.project, args.area) | Factory method to create a new instance from command line args.
:param args: instance of :class:`argparse.Namespace` |
def movingaverage(arr, window):
"""
Calculates the moving average ("rolling mean") of an array
of a certain window size.
"""
m = np.ones(int(window)) / int(window)
return scipy.ndimage.convolve1d(arr, m, axis=0, mode='reflect') | Calculates the moving average ("rolling mean") of an array
of a certain window size. |
def riseset(self, crd, ev="5deg"):
"""This will give the rise/set times of a source. It needs the
position in the frame, and a time. If the latter is not set, the
current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or string
... | This will give the rise/set times of a source. It needs the
position in the frame, and a time. If the latter is not set, the
current time will be used.
:param crd: a direction measure
:param ev: the elevation limit as a quantity or string
:returns: The returned value is a `dict`... |
def prepare(args):
"""
%prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta
Pick sequences from cdsfile to form pairs, ready to be calculated. The
pairsfile can be generated from formats.blast.cscore(). The first two
columns contain the pair.
"""
from jcvi.formats.fasta import Fast... | %prog prepare pairsfile cdsfile [pepfile] -o paired.cds.fasta
Pick sequences from cdsfile to form pairs, ready to be calculated. The
pairsfile can be generated from formats.blast.cscore(). The first two
columns contain the pair. |
def find_path(self, node_source, node_target, type='nodes'):
"""Determines shortest path
Determines the shortest path from `node_source` to
`node_target` in _graph using networkx' shortest path
algorithm.
Args
----
node_source: GridDing0
source node,... | Determines shortest path
Determines the shortest path from `node_source` to
`node_target` in _graph using networkx' shortest path
algorithm.
Args
----
node_source: GridDing0
source node, member of _graph
node_target: GridDing0
target node... |
def manage_admins():
"""Page for viewing and managing build admins."""
build = g.build
# Do not show cached data
db.session.add(build)
db.session.refresh(build)
add_form = forms.AddAdminForm()
if add_form.validate_on_submit():
invitation_user_id = '%s:%s' % (
models.Us... | Page for viewing and managing build admins. |
def _load_same_codes(self, refresh=False):
"""Loads the Same Codes into this object"""
if refresh is True:
self._get_same_codes()
else:
self._cached_same_codes() | Loads the Same Codes into this object |
def remove_actor(self, actor, reset_camera=False):
"""
Removes an actor from the Renderer.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Renderer.
reset_camera : bool, optional
Resets camera so all actors can b... | Removes an actor from the Renderer.
Parameters
----------
actor : vtk.vtkActor
Actor that has previously added to the Renderer.
reset_camera : bool, optional
Resets camera so all actors can be seen.
Returns
-------
success : bool
... |
def has_neigh(tag_name, params=None, content=None, left=True):
"""
This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this param... | This function generates functions, which matches all tags with neighbours
defined by parameters.
Args:
tag_name (str): Tag has to have neighbour with this tagname.
params (dict): Tag has to have neighbour with this parameters.
params (str): Tag has to have neighbour with this content.
... |
def query_order(self, transaction_id=None, out_trade_no=None):
"""
查询订单 api
:param transaction_id: 二选一 微信订单号 微信的订单号,优先使用
:param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。
:return: 返回的结果信息
"""
if not transaction_id and not out_trade_no:
... | 查询订单 api
:param transaction_id: 二选一 微信订单号 微信的订单号,优先使用
:param out_trade_no: 二选一 商户订单号 商户系统内部的订单号,当没提供transaction_id时需要传这个。
:return: 返回的结果信息 |
def set_webhook(self, webhook_path: Optional[str] = None, request_handler: Any = WebhookRequestHandler,
route_name: str = DEFAULT_ROUTE_NAME, web_app: Optional[Application] = None):
"""
Set webhook for bot
:param webhook_path: Optional[str] (default: None)
:param req... | Set webhook for bot
:param webhook_path: Optional[str] (default: None)
:param request_handler: Any (default: WebhookRequestHandler)
:param route_name: str Name of webhook handler route (default: 'webhook_handler')
:param web_app: Optional[Application] (default: None)
:return: |
def findall(self, title=None):
"""Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty)
"""
if title is None:
... | Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty) |
def predict(self, u):
'''Predicts the output value at u from the fitted polynomial expansion.
Therefore the method train() must be called first.
:param numpy.ndarray u: input value at which to predict the output.
:return: q_approx - the predicted value of the output at u
:rtyp... | Predicts the output value at u from the fitted polynomial expansion.
Therefore the method train() must be called first.
:param numpy.ndarray u: input value at which to predict the output.
:return: q_approx - the predicted value of the output at u
:rtype: float
*Sample Usage*:... |
def delimited(items, character='|'):
"""Returns a character delimited version of the provided list as a Python string"""
return '|'.join(items) if type(items) in (list, tuple, set) else items | Returns a character delimited version of the provided list as a Python string |
def write(self, writer=None, encoding='utf-8', indent=0, newline='',
omit_declaration=False, node_depth=0, quote_char='"'):
"""
Serialize this node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param writer: an object such as a file or st... | Serialize this node and its descendants to text, writing
the output to a given *writer* or to stdout.
:param writer: an object such as a file or stream to which XML text
is sent. If *None* text is sent to :attr:`sys.stdout`.
:type writer: a file, stream, etc or None
:param s... |
def Open(self, file_object):
"""Opens the CPIO archive file.
Args:
file_object (FileIO): a file-like object.
Raises:
IOError: if the file format signature is not supported.
OSError: if the file format signature is not supported.
"""
file_object.seek(0, os.SEEK_SET)
signature_... | Opens the CPIO archive file.
Args:
file_object (FileIO): a file-like object.
Raises:
IOError: if the file format signature is not supported.
OSError: if the file format signature is not supported. |
def forget_exporter(name):
'''
forget_exporter(name) yields True if an exporter of type name was successfully forgotten from
the neuropythy exporters list and false otherwise. This function must be called before an
exporter can be replaced.
'''
global exporters
name = name.lower()
if... | forget_exporter(name) yields True if an exporter of type name was successfully forgotten from
the neuropythy exporters list and false otherwise. This function must be called before an
exporter can be replaced. |
def legislator_inactive(request, abbr, legislator):
'''
Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
... | Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vo... |
def solve_let(expr, vars):
"""Solves a let-form by calling RHS with nested scope."""
lhs_value = solve(expr.lhs, vars).value
if not isinstance(lhs_value, structured.IStructured):
raise errors.EfilterTypeError(
root=expr.lhs, query=expr.original,
message="The LHS of 'let' must... | Solves a let-form by calling RHS with nested scope. |
def initialize_page(title, style, script, header=None):
"""
A function that returns a markup.py page object with the required html
header.
"""
page = markup.page(mode="strict_html")
page._escape = False
page.init(title=title, css=style, script=script, header=header)
return page | A function that returns a markup.py page object with the required html
header. |
def task_done(self, **kws):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently... | Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it will resume when all items... |
def do_display(self, arg):
"""
display expression
Add expression to the display list; expressions in this list
are evaluated at each step, and printed every time its value
changes.
WARNING: since the expressions is evaluated multiple time, pay
attention not to p... | display expression
Add expression to the display list; expressions in this list
are evaluated at each step, and printed every time its value
changes.
WARNING: since the expressions is evaluated multiple time, pay
attention not to put expressions with side-effects in the
... |
def remove(self, func):
"""Remove any provisioned log sink if auto created"""
if not self.data['name'].startswith(self.prefix):
return
parent = self.get_parent(self.get_log())
_, sink_path, _ = self.get_sink()
client = self.session.client(
'logging', 'v2',... | Remove any provisioned log sink if auto created |
def evaluate_binop_comparison(self, operation, left, right, **kwargs):
"""
Evaluate given comparison binary operation with given operands.
"""
if not operation in self.binops_comparison:
raise ValueError("Invalid comparison binary operation '{}'".format(operation))
if... | Evaluate given comparison binary operation with given operands. |
def append_once(cls, code, **kwargs):
"""One-off code generation using append.
If keyword args are provided, initialized using
:meth:`with_id_processor`.
"""
if kwargs:
g = cls.with_id_processor()
g._append_context(kwargs)
else:
... | One-off code generation using append.
If keyword args are provided, initialized using
:meth:`with_id_processor`. |
def get_loaded_project(self, project_id):
"""
Returns a project or raise a 404 error.
If project is not finished to load wait for it
"""
project = self.get_project(project_id)
yield from project.wait_loaded()
return project | Returns a project or raise a 404 error.
If project is not finished to load wait for it |
def _geometric_intersect(nodes1, degree1, nodes2, degree2, verify):
r"""Find all intersections among edges of two surfaces.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Uses :func:`generic_intersect` with the
:attr:`~.Intersec... | r"""Find all intersections among edges of two surfaces.
.. note::
There is also a Fortran implementation of this function, which
will be used if it can be built.
Uses :func:`generic_intersect` with the
:attr:`~.IntersectionStrategy.GEOMETRIC` intersection strategy.
Args:
nodes1... |
def to_utf8(value):
"""Returns a string encoded using UTF-8.
This function comes from `Tornado`_.
:param value:
A unicode or string to be encoded.
:returns:
The encoded string.
"""
if isinstance(value, unicode):
return value.encode('utf-8')
assert isinstance(value, str)
return value | Returns a string encoded using UTF-8.
This function comes from `Tornado`_.
:param value:
A unicode or string to be encoded.
:returns:
The encoded string. |
def push_script(self, scriptable, script, callback=None):
"""Run the script and add it to the list of threads."""
if script in self.threads:
self.threads[script].finish()
thread = Thread(self.run_script(scriptable, script),
scriptable, callback)
... | Run the script and add it to the list of threads. |
def run(self, argv):
"""Dispatch the given command."""
command = argv[0]
handlers = {
'cancel': self.cancel,
'create': self.create,
'events': self.events,
'finalize': self.finalize,
'list': self.list,
'pause': self.pause,
... | Dispatch the given command. |
def dict2pb(cls, adict, strict=False):
"""
Takes a class representing the ProtoBuf Message and fills it with data from
the dict.
"""
obj = cls()
for field in obj.DESCRIPTOR.fields:
if not field.label == field.LABEL_REQUIRED:
continue
if not field.has_default_value:
... | Takes a class representing the ProtoBuf Message and fills it with data from
the dict. |
def calculate_up_moves(high_data):
"""
Up Move.
Formula:
UPMOVE = Ht - Ht-1
"""
up_moves = [high_data[idx] - high_data[idx-1] for idx in range(1, len(high_data))]
return [np.nan] + up_moves | Up Move.
Formula:
UPMOVE = Ht - Ht-1 |
def dict2tlist(this_dict,**kwargs):
'''
#sequence will be losted
d = {'a':'b','c':'d'}
dict2tlist(d)
'''
if('check' in kwargs):
check = kwargs['check']
else:
check = 1
if(check):
if(isinstance(this_dict,dict)):
pass
else:
... | #sequence will be losted
d = {'a':'b','c':'d'}
dict2tlist(d) |
def associations(self, association_resource):
"""Retrieve Association for this resource of the type in association_resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided association resource_type.
... | Retrieve Association for this resource of the type in association_resource.
This method will return all *resources* (group, indicators, task, victims, etc) for this
resource that are associated with the provided association resource_type.
**Example Endpoints URI's**
+--------+--------... |
def result(self, r=None, **kwargs):
'''
Validates a result, stores it in self.results and prints it.
Accepts the same kwargs as the binwalk.core.module.Result class.
@r - An existing instance of binwalk.core.module.Result.
Returns an instance of binwalk.core.module.Result.
... | Validates a result, stores it in self.results and prints it.
Accepts the same kwargs as the binwalk.core.module.Result class.
@r - An existing instance of binwalk.core.module.Result.
Returns an instance of binwalk.core.module.Result. |
def _consume_add_and_get_tag(self, consume_rpc_result):
"""Add the tag to the channel and return it.
:param dict consume_rpc_result:
:rtype: str
"""
consumer_tag = consume_rpc_result['consumer_tag']
self._channel.add_consumer_tag(consumer_tag)
return consumer_ta... | Add the tag to the channel and return it.
:param dict consume_rpc_result:
:rtype: str |
def find_bookmark_file ():
"""Return the bookmark file of the Opera profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found.
"""
try:
dirname = get_profile_dir()
if os.path.isdir(dirname):
for name in OperaBookmarkFiles:
... | Return the bookmark file of the Opera profile.
Returns absolute filename if found, or empty string if no bookmark file
could be found. |
def train():
"""Training process"""
start_pipeline_time = time.time()
# Training/Testing
best_valid_acc = 0
stop_early = 0
for epoch in range(args.epochs):
# Epoch training stats
start_epoch_time = time.time()
epoch_L = 0.0
epoch_sent_num = 0
epoch_wc = 0... | Training process |
def class_sealer(fields, defaults,
base=__base__, make_init_func=make_init_func,
initializer=True, comparable=True, printable=True, convertible=False, pass_kwargs=False):
"""
This sealer makes a normal container class. It's mutable and supports arguments with default values.
... | This sealer makes a normal container class. It's mutable and supports arguments with default values. |
def send_request(self, method, action, body=None,
headers=None, ipaddr=None):
"""Perform the HTTP request.
The response is in either JSON format or plain text. A GET method will
invoke a JSON response while a PUT/POST/DELETE returns message from the
the server in pla... | Perform the HTTP request.
The response is in either JSON format or plain text. A GET method will
invoke a JSON response while a PUT/POST/DELETE returns message from the
the server in plain text format.
Exception is raised when server replies with an INTERNAL SERVER ERROR
status ... |
def specialspaceless(parser, token):
"""
Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout.
"""
nodelist = parser.parse(('endspecialspaceless',))
parser.delete_first_token()
return Spe... | Removes whitespace between HTML tags, and introduces a whitespace
after buttons an inputs, necessary for Bootstrap to place them
correctly in the layout. |
def get_state(self):
"""
Create state from sensors and battery
"""
# Include battery level in state
battery = self.player.stats['battery']/100
# Create observation from sensor proximities
# TODO: Have state persist, then update columns by `sensed_type`
# ... | Create state from sensors and battery |
def get_cash_balance(self):
"""
Returns the account cash balance available for investing
Returns
-------
float
The cash balance in your account.
"""
cash = False
try:
response = self.session.get('/browse/cashBalanceAj.action')
... | Returns the account cash balance available for investing
Returns
-------
float
The cash balance in your account. |
def reply_video(
self,
video: str,
quote: bool = None,
caption: str = "",
parse_mode: str = "",
duration: int = 0,
width: int = 0,
height: int = 0,
thumb: str = None,
supports_streaming: bool = True,
disable_notification: bool = Non... | Bound method *reply_video* of :obj:`Message <pyrogram.Message>`.
Use as a shortcut for:
.. code-block:: python
client.send_video(
chat_id=message.chat.id,
video=video
)
Example:
.. code-block:: python
messag... |
def select_hcons(xmrs, hi=None, relation=None, lo=None):
"""
Return the list of matching HCONS for *xmrs*.
:class:`~delphin.mrs.components.HandleConstraint` objects for
*xmrs* match if their `hi` matches *hi*, `relation` matches
*relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo*
... | Return the list of matching HCONS for *xmrs*.
:class:`~delphin.mrs.components.HandleConstraint` objects for
*xmrs* match if their `hi` matches *hi*, `relation` matches
*relation*, and `lo` matches *lo*. The *hi*, *relation*, and *lo*
filters are ignored if they are `None`.
Args:
xmrs (:cla... |
def acosh(x):
""" acosh(x)
Hyperbolic arc cos function.
"""
_math = infer_math(x)
if _math is math:
return _math.acosh(x)
else:
return _math.arccosh(x) | acosh(x)
Hyperbolic arc cos function. |
def get_reader(self):
"""Return a read-only :py:class:`~zipfile.ZipFile`."""
assert self._closed, "Archive not closed"
buf = io.BytesIO(self.get_bytes())
return zipfile.ZipFile(buf, mode='r') | Return a read-only :py:class:`~zipfile.ZipFile`. |
def merge_files(context):
"""
Given a context containing path to template, env, and service:
merge config into template and output the result to stdout
Args:
context: a populated context object
"""
resolver = EFTemplateResolver(
profile=context.profile,
region=context.region,
env=conte... | Given a context containing path to template, env, and service:
merge config into template and output the result to stdout
Args:
context: a populated context object |
def mctransp(I,J,K,c,d,M):
"""mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for ... | mctransp -- model for solving the Multi-commodity Transportation Problem
Parameters:
- I: set of customers
- J: set of facilities
- K: set of commodities
- c[i,j,k]: unit transportation cost on arc (i,j) for commodity k
- d[i][k]: demand for commodity k at node i
- M[... |
def _unpack_lookupswitch(bc, offset):
"""
function for unpacking the lookupswitch op arguments
"""
jump = (offset % 4)
if jump:
offset += (4 - jump)
(default, npairs), offset = _unpack(_struct_ii, bc, offset)
switches = list()
for _index in range(npairs):
pair, offset ... | function for unpacking the lookupswitch op arguments |
def goto_line(self, line_number):
"""Go to specified line number in current active editor."""
if line_number:
line_number = int(line_number)
try:
self.plugin.go_to_line(line_number)
except AttributeError:
pass | Go to specified line number in current active editor. |
def computePreRec(cm, class_names):
'''
This function computes the precision, recall and f1 measures,
given a confusion matrix
'''
n_classes = cm.shape[0]
if len(class_names) != n_classes:
print("Error in computePreRec! Confusion matrix and class_names "
"list must be of th... | This function computes the precision, recall and f1 measures,
given a confusion matrix |
def import_pipeline(conf, args):
"""Import a pipeline from json."""
with open(args.pipeline_json) as pipeline_json:
dst = conf.config['instances'][args.dst_instance]
dst_url = api.build_pipeline_url(build_instance_url(dst))
dst_auth = tuple([conf.creds['instances'][args.dst_instance]['us... | Import a pipeline from json. |
def __setitem(self, chunk, key, keys, value, extend=False):
"""Helper function to fill up the dictionary."""
def setitem(chunk):
if keys:
return self.__setitem(chunk, keys[0], keys[1:], value, extend)
else:
return value
if key in ['.', ']'... | Helper function to fill up the dictionary. |
def register_post_processor(func):
"""
Register a post processor function to be run as the final step in
serialization. The data passed in will already have gone through the
sideloading processor.
Usage:
@register_post_processor
def my_post_processor(data):
# do stuff wi... | Register a post processor function to be run as the final step in
serialization. The data passed in will already have gone through the
sideloading processor.
Usage:
@register_post_processor
def my_post_processor(data):
# do stuff with `data`
return data |
def write_file_to_zip_with_neutral_metadata(zfile, filename, content):
"""
Write the string `content` to `filename` in the open ZipFile `zfile`.
Args:
zfile (ZipFile): open ZipFile to write the content into
filename (str): the file path within the zip file to write into
content (str)... | Write the string `content` to `filename` in the open ZipFile `zfile`.
Args:
zfile (ZipFile): open ZipFile to write the content into
filename (str): the file path within the zip file to write into
content (str): the content to write into the zip
Returns: None |
def sprite_map_name(map):
"""
Returns the name of a sprite map The name is derived from the folder than
contains the sprites.
"""
map = map.render()
sprite_maps = _get_cache('sprite_maps')
sprite_map = sprite_maps.get(map)
if not sprite_map:
log.error("No sprite map found: %s", m... | Returns the name of a sprite map The name is derived from the folder than
contains the sprites. |
def afw_union(afw_1: dict, afw_2: dict) -> dict:
""" Returns a AFW that reads the union of the languages read
by input AFWs.
Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2
= (Σ, S_2 , s^0_2, ρ_2 , F_2 )`
be alternating automata accepting the languages :math:`L(
A_1)` and :math:`L... | Returns a AFW that reads the union of the languages read
by input AFWs.
Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2
= (Σ, S_2 , s^0_2, ρ_2 , F_2 )`
be alternating automata accepting the languages :math:`L(
A_1)` and :math:`L(A_2)`.
Then, :math:`B_∪ = (Σ, S_1 ∪ S_2 ∪ {root}, ρ_... |
def submit_reading(self, input_fname, start_ix, end_ix, ids_per_job,
num_tries=1, stagger=0):
"""Submit a batch of reading jobs
Parameters
----------
input_fname : str
The name of the file containing the ids to be read.
start_ix : int
... | Submit a batch of reading jobs
Parameters
----------
input_fname : str
The name of the file containing the ids to be read.
start_ix : int
The line index of the first item in the list to read.
end_ix : int
The line index of the last item in the... |
def initialize_grid(world_size, inner):
"""
Creates an empty grid (2d list) with the dimensions specified in
world_size. Each element is initialized to the inner argument.
"""
data = []
for i in range(world_size[1]):
data.append([])
for j in range(world_size[0]):
dat... | Creates an empty grid (2d list) with the dimensions specified in
world_size. Each element is initialized to the inner argument. |
def updateData(self,exten,data):
""" Write out updated data and header to
the original input file for this object.
"""
_extnum=self._interpretExten(exten)
fimg = fileutil.openImage(self._filename, mode='update', memmap=False)
fimg[_extnum].data = data
fimg[_ex... | Write out updated data and header to
the original input file for this object. |
def cmd(send, _, args):
"""Shows the currently guarded nicks.
Syntax: {command}
"""
guarded = args['handler'].guarded
if not guarded:
send("Nobody is guarded.")
else:
send(", ".join(guarded)) | Shows the currently guarded nicks.
Syntax: {command} |
def get_expanded_path(self, path):
"""
expands a path that starts with an ~ to an absolute path
:param path:
:return:
"""
if path.startswith('~'):
return os.path.expanduser('~') + path[1:]
else:
return path | expands a path that starts with an ~ to an absolute path
:param path:
:return: |
def load(self):
"""Return our application to be run."""
app = util.import_app("dallinger.experiment_server.sockets:app")
if self.options.get("mode") == "debug":
app.debug = True
return app | Return our application to be run. |
def activate(self, span, finish_on_close):
"""
Make a :class:`~opentracing.Span` instance active.
:param span: the :class:`~opentracing.Span` that should become active.
:param finish_on_close: whether *span* should automatically be
finished when :meth:`Scope.close()` is call... | Make a :class:`~opentracing.Span` instance active.
:param span: the :class:`~opentracing.Span` that should become active.
:param finish_on_close: whether *span* should automatically be
finished when :meth:`Scope.close()` is called.
If no :func:`tracer_stack_context()` is detected, ... |
def parse(fp):
"""
Parse the contents of the `~io.IOBase.readline`-supporting file-like object
``fp`` as a simple line-oriented ``.properties`` file and return a
generator of ``(key, value, original_lines)`` triples for every entry in
``fp`` (including duplicate keys) in order of occurrence. The th... | Parse the contents of the `~io.IOBase.readline`-supporting file-like object
``fp`` as a simple line-oriented ``.properties`` file and return a
generator of ``(key, value, original_lines)`` triples for every entry in
``fp`` (including duplicate keys) in order of occurrence. The third
element of each tri... |
def _parse_call_args(self,*args,**kwargs):
"""Helper function to parse the arguments to the __call__ and related functions,
return [6,nobj] array of frequencies (:3) and angles (3:)"""
interp= kwargs.get('interp',self._useInterp)
if len(args) == 5:
raise IOError("Must specify... | Helper function to parse the arguments to the __call__ and related functions,
return [6,nobj] array of frequencies (:3) and angles (3:) |
def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None):
"""POST stats to the given url.
:return: True if upload was successful, False otherwise.
"""
def error(msg):
# Report aleady closed, so just print error.
print('WARNING: Failed to upload stats to {}. due to {}'.format(sta... | POST stats to the given url.
:return: True if upload was successful, False otherwise. |
def wrap_case_result(raw, expr):
"""Wrap a CASE statement result in a Series and handle returning scalars.
Parameters
----------
raw : ndarray[T]
The raw results of executing the ``CASE`` expression
expr : ValueExpr
The expression from the which `raw` was computed
Returns
-... | Wrap a CASE statement result in a Series and handle returning scalars.
Parameters
----------
raw : ndarray[T]
The raw results of executing the ``CASE`` expression
expr : ValueExpr
The expression from the which `raw` was computed
Returns
-------
Union[scalar, Series] |
def get_variables(self, variables=None):
"""Get runtime variables for policy interpolation.
Runtime variables are merged with the passed in variables
if any.
"""
# Global policy variable expansion, we have to carry forward on
# various filter/action local vocabularies. W... | Get runtime variables for policy interpolation.
Runtime variables are merged with the passed in variables
if any. |
def _add_vector_layer(self, vector_layer, layer_name, save_style=False):
"""Add a vector layer to the folder.
:param vector_layer: The layer to add.
:type vector_layer: QgsVectorLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
:par... | Add a vector layer to the folder.
:param vector_layer: The layer to add.
:type vector_layer: QgsVectorLayer
:param layer_name: The name of the layer in the datastore.
:type layer_name: str
:param save_style: If we have to save a QML too. Default to False.
:type save_st... |
def keep_only_positive_boxes(boxes):
"""
Given a set of BoxList containing the `labels` field,
return a set of BoxList for which `labels > 0`.
Arguments:
boxes (list of BoxList)
"""
assert isinstance(boxes, (list, tuple))
assert isinstance(boxes[0], BoxList)
assert boxes[0].has_... | Given a set of BoxList containing the `labels` field,
return a set of BoxList for which `labels > 0`.
Arguments:
boxes (list of BoxList) |
def hotp(key,counter,format='dec6',hash=hashlib.sha1):
'''
Compute a HOTP value as prescribed by RFC4226
:param key:
the HOTP secret key given as an hexadecimal string
:param counter:
the OTP generation counter
:param format:
the output format, can be:
... | Compute a HOTP value as prescribed by RFC4226
:param key:
the HOTP secret key given as an hexadecimal string
:param counter:
the OTP generation counter
:param format:
the output format, can be:
- hex, for a variable length hexadecimal format,
... |
def rental_report(self, address, zipcode, format_type="json"):
"""Call the rental_report component
Rental Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- format_type - "json", "xlsx" or "all". Default is "json".
""... | Call the rental_report component
Rental Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- format_type - "json", "xlsx" or "all". Default is "json". |
def _safe_gremlin_string(value):
"""Sanitize and represent a string argument in Gremlin."""
if not isinstance(value, six.string_types):
if isinstance(value, bytes): # should only happen in py3
value = value.decode('utf-8')
else:
raise GraphQLInvalidArgumentError(u'Attemp... | Sanitize and represent a string argument in Gremlin. |
def filetime_from_git(content, git_content):
'''
Update modification and creation times from git
'''
if not content.settings['GIT_FILETIME_FROM_GIT']:
# Disabled for everything
return
if not string_to_bool(content.metadata.get('gittime', 'yes')):
# Disable for this content
... | Update modification and creation times from git |
def sigfig_round(values, sigfig=1):
"""
Round a single value to a specified number of significant figures.
Parameters
----------
values: float, value to be rounded
sigfig: int, number of significant figures to reduce to
Returns
----------
rounded: values, but rounded to the specif... | Round a single value to a specified number of significant figures.
Parameters
----------
values: float, value to be rounded
sigfig: int, number of significant figures to reduce to
Returns
----------
rounded: values, but rounded to the specified number of significant figures
Examples... |
def convert_softmax(builder, layer, input_names, output_names, keras_layer):
"""Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, output... | Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. |
def __default_emit_trace(self, data):
"""
Writes the given tracing data to Python Logging.
:param data: The tracing data to be written.
"""
message = format_trace_data(data)
self.io.logger.info(message) | Writes the given tracing data to Python Logging.
:param data: The tracing data to be written. |
def interpol_hist2d(h2d, oversamp_factor=10):
"""Sample the interpolator of a root 2d hist.
Root's hist2d has a weird internal interpolation routine,
also using neighbouring bins.
"""
from rootpy import ROOTError
xlim = h2d.bins(axis=0)
ylim = h2d.bins(axis=1)
xn = h2d.nbins(0)
yn ... | Sample the interpolator of a root 2d hist.
Root's hist2d has a weird internal interpolation routine,
also using neighbouring bins. |
def get_wide_interims(self):
"""Returns a dictionary with the analyses services from the current
worksheet which have at least one interim with 'Wide' attribute set to
true and that have not been yet submitted
The structure of the returned dictionary is the following:
<Analysis_... | Returns a dictionary with the analyses services from the current
worksheet which have at least one interim with 'Wide' attribute set to
true and that have not been yet submitted
The structure of the returned dictionary is the following:
<Analysis_keyword>: {
'analysis': <Ana... |
def register_cmdfinalization_hook(self, func: Callable[[plugin.CommandFinalizationData],
plugin.CommandFinalizationData]) -> None:
"""Register a hook to be called after a command is completed, whether it completes successfully or not."""
self._v... | Register a hook to be called after a command is completed, whether it completes successfully or not. |
def auto_correlation(sequence):
"""
test for the autocorrelation of a sequence between t and t - 1
as the 'auto_correlation' it is less likely that the sequence is
generated randomly.
:param sequence: any iterable with at most 2 values that can be turned
into a float via np.floa... | test for the autocorrelation of a sequence between t and t - 1
as the 'auto_correlation' it is less likely that the sequence is
generated randomly.
:param sequence: any iterable with at most 2 values that can be turned
into a float via np.float . e.g.
'1001001'
... |
def dpi(self):
""" Physical resolution of the document coordinate system (dots per
inch).
"""
if self._dpi is None:
if self._canvas is None:
return None
else:
return self.canvas.dpi
else:
return self._dpi | Physical resolution of the document coordinate system (dots per
inch). |
def rescale_field(self, new_dim):
"""
Changes the discretization of the potential field by linear
interpolation. This is necessary if the potential field
obtained from DFT is strangely skewed, or is too fine or coarse. Obeys
periodic boundary conditions at the edges of
th... | Changes the discretization of the potential field by linear
interpolation. This is necessary if the potential field
obtained from DFT is strangely skewed, or is too fine or coarse. Obeys
periodic boundary conditions at the edges of
the cell. Alternatively useful for mixing potentials tha... |
def close(self) -> None:
"""Close the task.
.. versionadded:: 1.0
This method must be called when the task is no longer needed.
"""
self.__data_channel_buffer.stop()
self.__data_channel_buffer.close()
self.__data_channel_buffer = None
if not self.__was_p... | Close the task.
.. versionadded:: 1.0
This method must be called when the task is no longer needed. |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.