code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_category_activities(self, category_id = None):
"""Return activities for category. If category is not specified, will
return activities that have no category"""
category_id = category_id or -1
return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryAct... | Return activities for category. If category is not specified, will
return activities that have no category |
def linear_copy(self, deep=False):
"""
Returns a copy of the input unstructured grid containing only
linear cells. Converts the following cell types to their
linear equivalents.
- VTK_QUADRATIC_TETRA --> VTK_TETRA
- VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID
... | Returns a copy of the input unstructured grid containing only
linear cells. Converts the following cell types to their
linear equivalents.
- VTK_QUADRATIC_TETRA --> VTK_TETRA
- VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID
- VTK_QUADRATIC_WEDGE --> VTK_WEDGE
- VTK_... |
def list(self):
"""
Get all current hooks
:return: All hooks
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from Logentries
"""
return self._post(
... | Get all current hooks
:return: All hooks
:rtype: list of dict
:raises: This will raise a
:class:`ServerException<logentries_api.exceptions.ServerException>`
if there is an error from Logentries |
def on_snapshot(self, callback):
"""Monitor the documents in this collection that match this query.
This starts a watch on this query using a background thread. The
provided callback is run on the snapshot of the documents.
Args:
callback(~.firestore.query.QuerySnapshot): a... | Monitor the documents in this collection that match this query.
This starts a watch on this query using a background thread. The
provided callback is run on the snapshot of the documents.
Args:
callback(~.firestore.query.QuerySnapshot): a callback to run when
a chan... |
def deployment_allocation_health(self, id, healthy_allocations=list(), unhealthy_allocations=list()):
""" This endpoint is used to set the health of an allocation that is in the deployment manually. In some use
cases, automatic detection of allocation health may not be desired. As such those task gr... | This endpoint is used to set the health of an allocation that is in the deployment manually. In some use
cases, automatic detection of allocation health may not be desired. As such those task groups can be marked
with an upgrade policy that uses health_check = "manual". Those allocations must ha... |
def remove_user(uid):
""" Removes a user from the DCOS Enterprise.
:param uid: user id
:type uid: str
"""
try:
acl_url = urljoin(_acl_url(), 'users/{}'.format(uid))
r = http.delete(acl_url)
assert r.status_code == 204
except DCOSHTTPException as e:
# does... | Removes a user from the DCOS Enterprise.
:param uid: user id
:type uid: str |
def loadinfofont(self):
"""Auxiliary method to load font if not yet done."""
if self.infofont == None:
self.infofont = imft.load_path(os.path.join(fontsdir, "courR10.pil")) | Auxiliary method to load font if not yet done. |
def gtr(self, value):
"""
Set a new GTR object
Parameters
-----------
value : GTR
the new GTR object
"""
if not (isinstance(value, GTR) or isinstance(value, GTR_site_specific)):
raise TypeError(" GTR instance expected")
self._gtr... | Set a new GTR object
Parameters
-----------
value : GTR
the new GTR object |
def answer_approval(self, issue_id_or_key, approval_id, decision):
"""
Answer a pending approval
:param issue_id_or_key: str
:param approval_id: str
:param decision: str
:return:
"""
url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_... | Answer a pending approval
:param issue_id_or_key: str
:param approval_id: str
:param decision: str
:return: |
def __scripts(self, filestem):
"""
Generates the required scripts.
"""
script_construct = open('%s/%s' % (self.tmpdir, RSD.CONSTRUCT), 'w')
script_save = open('%s/%s' % (self.tmpdir, RSD.SAVE), 'w')
script_subgroups = open('%s/%s' % (self.tmpdir, RSD.SUBGROUPS), 'w')
... | Generates the required scripts. |
def resource_absent(resource, identifier_fields, profile='pagerduty', subdomain=None, api_key=None, **kwargs):
'''
Generic resource.absent state method. Pagerduty state modules should be a thin wrapper over this method,
with a custom diff function.
This method calls delete_resource() and formats the ... | Generic resource.absent state method. Pagerduty state modules should be a thin wrapper over this method,
with a custom diff function.
This method calls delete_resource() and formats the result as a salt state return value.
example:
resource_absent("users", ["id","name","email"]) |
def visit_comprehension(self, node, parent):
"""visit a Comprehension node by returning a fresh instance of it"""
newnode = nodes.Comprehension(parent)
newnode.postinit(
self.visit(node.target, newnode),
self.visit(node.iter, newnode),
[self.visit(child, newno... | visit a Comprehension node by returning a fresh instance of it |
def _repaint(self, drawing_context):
"""Repaint the canvas item. This will occur on a thread."""
# canvas size
canvas_width = self.canvas_size[1]
canvas_height = self.canvas_size[0]
# draw background
if self.background_color:
with drawing_context.saver():
... | Repaint the canvas item. This will occur on a thread. |
def deep_copy(numpy_dict):
"""
Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them.
"""
out = {}
for key in numpy_dict:
out[key] = numpy_dict[key].copy()
return out | Returns a copy of a dictionary whose values are numpy arrays.
Copies their values rather than copying references to them. |
def _transform(self, Y, scan_onsets, beta, beta0,
rho_e, sigma_e, rho_X, sigma2_X, rho_X0, sigma2_X0):
""" Given the data Y and the response amplitudes beta and beta0
estimated in the fit step, estimate the corresponding X and X0.
It is done by a forward-backward algor... | Given the data Y and the response amplitudes beta and beta0
estimated in the fit step, estimate the corresponding X and X0.
It is done by a forward-backward algorithm.
We assume X and X0 both are vector autoregressive (VAR)
processes, to capture temporal smoothness. Their... |
def add_job_set(self, job_list):
"""
Adds a job set to the manager's queue. If there is no job set running,
it is activated immediately. A new job set handle is returned.
"""
assert not self._closed
results = Results(loop=self._loop)
js = JobSet(job_list, result... | Adds a job set to the manager's queue. If there is no job set running,
it is activated immediately. A new job set handle is returned. |
def export_hcurves_csv(ekey, dstore):
"""
Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
oq = dstore['oqparam']
info = get_info(dstore)
rlzs_assoc = dstore['csm_info'].get_rlzs_assoc()
R... | Exports the hazard curves into several .csv files
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object |
def save(filename=None, family='ipv4'):
'''
Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6
'''
if _conf() and not filename:
... | Save the current in-memory rules to disk
CLI Example:
.. code-block:: bash
salt '*' iptables.save /etc/sysconfig/iptables
IPv6:
salt '*' iptables.save /etc/sysconfig/iptables family=ipv6 |
def delete_view(self, query_criteria=None, uid='_all_users'):
'''
a method to delete a view associated with a user design doc
:param query_criteria: [optional] dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to up... | a method to delete a view associated with a user design doc
:param query_criteria: [optional] dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
:return: integer with status of operation
an example ... |
def data_available(dataset_name=None):
"""Check if the data set is available on the local machine already."""
dr = data_resources[dataset_name]
if 'dirs' in dr:
for dirs, files in zip(dr['dirs'], dr['files']):
for dir, file in zip(dirs, files):
if not os.path.exists(os.pa... | Check if the data set is available on the local machine already. |
def parse_extra_model_fields(extra_model_fields):
"""
Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list of (fie... | Parses the value of EXTRA_MODEL_FIELDS, grouping the entries by model
and instantiating the extra fields. Returns a sequence of tuples of
the form (model_key, fields) where model_key is a pair of app_label,
model_name and fields is a list of (field_name, field_instance) pairs. |
def get_parameters(self):
"""Return a list of parameters."""
parenthesis = self.tokens[-1]
for token in parenthesis.tokens:
if isinstance(token, IdentifierList):
return token.get_identifiers()
elif imt(token, i=(Function, Identifier), t=T.Literal):
... | Return a list of parameters. |
def addDataDocuments(self, scidata_pid_list, scimeta_pid=None):
"""Add Science Data object(s)
Args:
scidata_pid_list : list of str
List of one or more PIDs of Science Data objects
scimeta_pid: str
PID of a Science Metadata object that documents the Science D... | Add Science Data object(s)
Args:
scidata_pid_list : list of str
List of one or more PIDs of Science Data objects
scimeta_pid: str
PID of a Science Metadata object that documents the Science Data objects. |
def folderitem(self, obj, item, index):
"""Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
... | Service triggered each time an item is iterated in folderitems.
The use of this service prevents the extra-loops in child objects.
:obj: the instance of the class to be foldered
:item: dict containing the properties of the object to be used by
the template
:index: current ind... |
def read_pipette_id(self, mount) -> Optional[str]:
'''
Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None
'''
res: Optional[str] = None... | Reads in an attached pipette's ID
The ID is unique to this pipette, and is a string of unknown length
:param mount: string with value 'left' or 'right'
:return id string, or None |
def get_count(self, query=None):
"""
Return total number of alerts that meet the query filter.
"""
query = query or Query()
return self.get_db().alerts.find(query.where).count() | Return total number of alerts that meet the query filter. |
def get_related(self):
"""Check if any of the context interfaces have relation ids.
Set self.related and return True if one of the interfaces
has relation ids.
"""
# Fresh start
self.related = False
try:
for interface in self.interfaces:
... | Check if any of the context interfaces have relation ids.
Set self.related and return True if one of the interfaces
has relation ids. |
def import_attribute(self, path):
"""
Import an attribute from a module.
"""
module = '.'.join(path.split('.')[:-1])
function = path.split('.')[-1]
module = importlib.import_module(module)
return getattr(module, function) | Import an attribute from a module. |
def ReadUntilClose(self):
"""Yield packets until a Close packet is received."""
while True:
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != b'W... | Yield packets until a Close packet is received. |
def lookup_color(color):
"""
Returns the hex color for any valid css color name
>>> lookup_color('aliceblue')
'F0F8FF'
"""
if color is None: return
color = color.lower()
if color in COLOR_MAP:
return COLOR_MAP[color]
return color | Returns the hex color for any valid css color name
>>> lookup_color('aliceblue')
'F0F8FF' |
def savepoint(cr):
"""return a context manager wrapping postgres savepoints"""
if hasattr(cr, 'savepoint'):
with cr.savepoint():
yield
else:
name = uuid.uuid1().hex
cr.execute('SAVEPOINT "%s"' % name)
try:
yield
cr.execute('RELEASE SAVEPOIN... | return a context manager wrapping postgres savepoints |
def threshold_gradients_pctile(self, thresh_pctile, min_mag=0.0):
"""Creates a new DepthImage by zeroing out all depths
where the magnitude of the gradient at that point is
greater than some percentile of all gradients.
Parameters
----------
thresh_pctile : float
... | Creates a new DepthImage by zeroing out all depths
where the magnitude of the gradient at that point is
greater than some percentile of all gradients.
Parameters
----------
thresh_pctile : float
percentile to threshold all gradients above
min_mag : float
... |
def prototype_adjacency(self, n_block_features, alpha=None):
"""Build a new graph.
Doc for ".create(n_features, alpha)"
Parameters
-----------
n_features : int
[alpha] : float (0,1)
Unused.
Each graph will have a minimum of
(n_blocks *... | Build a new graph.
Doc for ".create(n_features, alpha)"
Parameters
-----------
n_features : int
[alpha] : float (0,1)
Unused.
Each graph will have a minimum of
(n_blocks * n_block_features**2 - n_blocks) / 2
edges and exactly this amo... |
def _update(dict1,dict2,**kwargs):
'''
dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
_update(dict1,dict2)
pobj(dict1)
pobj(dict2)
'''
if('deepcopy' in kwargs):
deepcopy = kwargs['deepcopy']
else:
deepcopy = 1
if(deep... | dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
_update(dict1,dict2)
pobj(dict1)
pobj(dict2) |
def to_json(self):
"""Convert the Design Day to a dictionary."""
return {
'name': self.name,
'day_type': self.day_type,
'location': self.location.to_json(),
'dry_bulb_condition': self.dry_bulb_condition.to_json(),
'humidity_condition': self.hum... | Convert the Design Day to a dictionary. |
def prepare(self):
"""
Prepares the android project to the build process.
Checks if the project uses either gradle or ant and executes the necessary steps.
"""
self.src_folder = self.get_src_folder()
st = os.stat('%s/gradlew' % self.path)
os.chmod('%s/gradlew' % self.path, st.st_mode | stat... | Prepares the android project to the build process.
Checks if the project uses either gradle or ant and executes the necessary steps. |
def read(text, name=None):
"""Read a block of text as a docutils document.
:param str text: Scene script text.
:param str name: An optional name for the document.
:return: A document object.
"""
doc = docutils.utils.new_document(name, SceneScript.settings)
parse... | Read a block of text as a docutils document.
:param str text: Scene script text.
:param str name: An optional name for the document.
:return: A document object. |
def init(cls, name):
"""Return an instance of this class or an appropriate subclass"""
clsdict = {subcls.name: subcls for subcls in cls.__subclasses__()
if hasattr(subcls, 'name')}
return clsdict.get(name, cls)(name) | Return an instance of this class or an appropriate subclass |
def task(*args, **kwargs):
'''Register a function as a task, as well as applying any attributes. '''
# support @task
if args and hasattr(args[0], '__call__'):
return _taskify(args[0])
# as well as @task(), @task('default'), etc.
else:
def wrapper(func):
global DEFAULT, SETUP, TEARDOWN
func = _taskify(f... | Register a function as a task, as well as applying any attributes. |
def transaction_id(self):
"""
Transaction ID for Transbank, a secure random int between 0 and 999999999.
"""
if not self._transaction_id:
self._transaction_id = random.randint(0, 10000000000 - 1)
return self._transaction_id | Transaction ID for Transbank, a secure random int between 0 and 999999999. |
def delete_invitation(self, invitation_id, **kwargs): # noqa: E501
"""Delete a user invitation. # noqa: E501
An endpoint for deleting an active user invitation which has been sent for a new or an existing user to join the account. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.c... | Delete a user invitation. # noqa: E501
An endpoint for deleting an active user invitation which has been sent for a new or an existing user to join the account. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/user-invitations/{invitation-id} -H 'Authorization: Bearer API_KEY'` # n... |
def _LoadArtifactsFromFiles(self, file_paths, overwrite_if_exists=True):
"""Load artifacts from file paths as json or yaml."""
loaded_files = []
loaded_artifacts = []
for file_path in file_paths:
try:
with io.open(file_path, mode="r", encoding="utf-8") as fh:
logging.debug("Loadi... | Load artifacts from file paths as json or yaml. |
def parse_value_object(self, tup_tree):
"""
::
<!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)>
"""
self.check_node(tup_tree, 'VALUE.OBJECT')
child = self.one_child(tup_tree, ('CLASS', 'INSTANCE'))
return (name(tup_tree), attrs(tup_tree), child) | ::
<!ELEMENT VALUE.OBJECT (CLASS | INSTANCE)> |
def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
self.host, self.path = urllib.parse.urlparse(url)[1:3] | Sets the URL referring to a robots.txt file. |
def set_prev_sonorus(self):
"""
Выставляет параметры звонкости/глухости, для предыдущих согласных.
"""
prev = self.get_prev_letter()
if not prev:
return
if not (self.is_consonant() and prev.is_consonant()):
return
if self.is_sonorus() and s... | Выставляет параметры звонкости/глухости, для предыдущих согласных. |
def edit_profile(session, uidentity, **kwargs):
"""Edit unique identity profile.
This function allows to edit or update the profile information
of the given unique identity. The values to update are given
as keyword arguments. The allowed keys are listed below
(other keywords will be ignored):
... | Edit unique identity profile.
This function allows to edit or update the profile information
of the given unique identity. The values to update are given
as keyword arguments. The allowed keys are listed below
(other keywords will be ignored):
- `name`: name of the unique identity
- `ema... |
def create_from_json(cls, json_data):
"""Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
"""
msa = Msa()
msa.msa = json_data["msa_info"]["msa"]
msa.meta = json_data["meta... | Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object |
def _iparam_classname(classname, arg_name):
"""
Convert a class name specified in an operation method into a CIM
object that can be passed to imethodcall().
"""
if isinstance(classname, CIMClassName):
classname = classname.copy()
classname.host = None
... | Convert a class name specified in an operation method into a CIM
object that can be passed to imethodcall(). |
def writeByte(self, byte):
"""
Writes a byte into the L{WriteData} stream object.
@type byte: int
@param byte: Byte value to write into the stream.
"""
self.data.write(pack("B" if not self.signed else "b", byte)) | Writes a byte into the L{WriteData} stream object.
@type byte: int
@param byte: Byte value to write into the stream. |
def detach_subnets(self, subnets):
"""
Detaches load balancer from one or more subnets.
:type subnets: string or List of strings
:param subnets: The name of the subnet(s) to detach.
"""
if isinstance(subnets, str) or isinstance(subnets, unicode):
subnets = [... | Detaches load balancer from one or more subnets.
:type subnets: string or List of strings
:param subnets: The name of the subnet(s) to detach. |
def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
"""
``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing
``None`` in... | ``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular log_softmax.
``vector`` can have an arbitrar... |
def get_versions(self):
"""
Returns the versions available
"""
response = self.ebs.describe_application_versions(application_name=self.app_name)
return response['DescribeApplicationVersionsResponse']['DescribeApplicationVersionsResult']['ApplicationVersions'] | Returns the versions available |
def download_dxfile(dxid, filename, chunksize=dxfile.DEFAULT_BUFFER_SIZE, append=False, show_progress=False,
project=None, describe_output=None, **kwargs):
'''
:param dxid: DNAnexus file ID or DXFile (file handler) object
:type dxid: string or DXFile
:param filename: Local filename
... | :param dxid: DNAnexus file ID or DXFile (file handler) object
:type dxid: string or DXFile
:param filename: Local filename
:type filename: string
:param append: If True, appends to the local file (default is to truncate local file if it exists)
:type append: boolean
:param project: project to us... |
def write_to(self, group):
"""Write stored items to the given HDF5 group.
We assume that self.create() has been called.
"""
# The HDF5 group where to write data
items_group = group[self.name]
nitems = items_group.shape[0]
items_group.resize((nitems + len(self.d... | Write stored items to the given HDF5 group.
We assume that self.create() has been called. |
def append_fallback(model, fields):
"""
If translated field is encountered, add also all its fallback fields.
Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names)
"""
fields = set(fields)
trans = set()
from modeltranslation.translator import translator
opts = translat... | If translated field is encountered, add also all its fallback fields.
Returns tuple: (set_of_new_fields_to_use, set_of_translated_field_names) |
def _ed1(token):
"""
Return tokens the edit distance of which is one from the given token
"""
insertion = {letter.join([token[:i], token[i:]]) for letter in string.ascii_lowercase for i in range(1, len(token) + 1)}
deletion = {''.join([token[:i], token[i+1:]]) for i in range(1, len(token) + 1)}
... | Return tokens the edit distance of which is one from the given token |
def _call_middlewares(self):
''' Execute the middleware stack '''
for middleware in self.middlewares:
if self._check_condition(middleware['when']):
self._call_one_middleware(middleware) | Execute the middleware stack |
def parse_options():
"""
Parse command line arguments.
Returns:
options, args
"""
parser = argparse.ArgumentParser(description='Video downloader by radzak.',
prog='RTVdownloader')
urls_group = parser.add_mutually_exclusive_group(required=True)
u... | Parse command line arguments.
Returns:
options, args |
def matchingPositions(self, tokenArray):
'''Returns a list of positions (indexes) in the tokenArray where this WordTemplate
matches (the method self.matches(token) returns True). Returns an empty list if
no matching tokens appear in the input list.
Parameters
-... | Returns a list of positions (indexes) in the tokenArray where this WordTemplate
matches (the method self.matches(token) returns True). Returns an empty list if
no matching tokens appear in the input list.
Parameters
----------
tokenArray: list of word tokens... |
def from_node(index, name, session, data):
"""
>>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None
True
>>> Member.from_node(-1, '', '', '{')
Member(index=-1, name='', session='', data={})
"""
if data.startswith('postgres'):... | >>> Member.from_node(-1, '', '', '{"conn_url": "postgres://foo@bar/postgres"}') is not None
True
>>> Member.from_node(-1, '', '', '{')
Member(index=-1, name='', session='', data={}) |
def create_view(self, query_criteria=None, uid='_all_users'):
'''
a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
... | a method to add a view to a design document of a uid
:param query_criteria: dictionary with valid jsonmodel query criteria
:param uid: [optional] string with uid of design document to update
:return: integer with status of operation
an example of how to construct the quer... |
def union_conforms(element: Union, etype, namespace: Dict[str, Any], conforms: Callable) -> bool:
""" Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward refe... | Determine whether element conforms to at least one of the types in etype
:param element: element to test
:param etype: type to test against
:param namespace: Namespace to use for resolving forward references
:param conforms: conformance test function
:return: True if element conforms to at least on... |
def events(self, **kwargs):
""" Fetch events meeting specified criteria """
events_result = self.service.events().list(**kwargs).execute()
return [Event(event) for event in events_result.get("items", [])] | Fetch events meeting specified criteria |
def define_new(cls, name, members, is_abstract=False):
"""
Define a new struct type derived from the current type.
Parameters
----------
name: str
Name of the struct type
members: {member_name : type}
Dictionary of struct member types.
is_... | Define a new struct type derived from the current type.
Parameters
----------
name: str
Name of the struct type
members: {member_name : type}
Dictionary of struct member types.
is_abstract: bool
If set, marks the struct as abstract. |
def superuser_required(view_func):
"""
Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary.
"""
@wraps(view_func)
def _checklogin(request, *args, **kwargs):
if request.user.is_active and request.user.is_superuser:
... | Decorator for views that checks that the user is logged in and is a staff
member, displaying the login page if necessary. |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_lldp_pdu_transmitted(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail")
config = get_lldp_neighbor_detail
output = ET.SubEleme... | Auto Generated Code |
def get_access_tokens(self, oauth_verifier):
"""
Wrapper around get_auth_session, returns session, and sets access_token and
access_token_secret on the QB Object.
:param oauth_verifier: the oauth_verifier as specified by OAuth 1.0a
"""
qb_service = OAuth1Service(
... | Wrapper around get_auth_session, returns session, and sets access_token and
access_token_secret on the QB Object.
:param oauth_verifier: the oauth_verifier as specified by OAuth 1.0a |
def example_exc_handler(tries_remaining, exception, delay):
"""Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised.
"""
print >> sys.stderr, "Caught '%s', %d tries remaining, sleeping for %s second... | Example exception handler; prints a warning to stderr.
tries_remaining: The number of tries remaining.
exception: The exception instance which was raised. |
def Nu_cylinder_Whitaker(Re, Pr, mu=None, muw=None):
r'''Calculates Nusselt number for crossflow across a single tube as shown
in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream
temperature. Recommends a viscosity exponent correction of 0.25, which is
applied only if provided. Also ... | r'''Calculates Nusselt number for crossflow across a single tube as shown
in [1]_ at a specified `Re` and `Pr`, both evaluated at the free stream
temperature. Recommends a viscosity exponent correction of 0.25, which is
applied only if provided. Also shown in [2]_.
.. math::
Nu_D = (0.4 Re_D^{0... |
def on_btn_orientation(self, event):
"""
Create and fill wxPython grid for entering
orientation data.
"""
wait = wx.BusyInfo('Compiling required data, please wait...')
wx.SafeYield()
#dw, dh = wx.DisplaySize()
size = wx.DisplaySize()
size = (size[0... | Create and fill wxPython grid for entering
orientation data. |
def delete_record(self, bucket_name, record_key, record_version=''):
'''
a method for deleting an object record in s3
:param bucket_name: string with name of bucket
:param record_key: string with key value of record
:param record_version: [optional] string with aws id of ve... | a method for deleting an object record in s3
:param bucket_name: string with name of bucket
:param record_key: string with key value of record
:param record_version: [optional] string with aws id of version of record
:return: dictionary with status of delete request |
def videogrep(inputfile, outputfile, search, searchtype, maxclips=0, padding=0, test=False, randomize=False, sync=0, use_transcript=False, use_vtt=False, export_clips=False):
"""Search through and find all instances of the search term in an srt or transcript,
create a supercut around that instance, and output a... | Search through and find all instances of the search term in an srt or transcript,
create a supercut around that instance, and output a new video file
comprised of those supercuts. |
def one_to_one(graph, nodes):
"""
Return True if graph contains only one to one mappings. The
directed graph should be represented as a dictionary mapping of
edges for each node. Nodes should be passed a simple list.
"""
edges = itertools.chain.from_iterable(graph.values())
return len(graph)... | Return True if graph contains only one to one mappings. The
directed graph should be represented as a dictionary mapping of
edges for each node. Nodes should be passed a simple list. |
def main(data, utype, ctype):
"""Create a Vine from the data, utype and ctype"""
copula = CopulaModel(data, utype, ctype)
print(copula.sampling(1, plot=True))
print(copula.model.vine_model[-1].tree_data) | Create a Vine from the data, utype and ctype |
def optimizeTransform(transform):
"""
Optimises a series of transformations parsed from a single
transform="" attribute.
The transformation list is modified in-place.
"""
# FIXME: reordering these would optimize even more cases:
# first: Fold consecutive runs of the same transformation
... | Optimises a series of transformations parsed from a single
transform="" attribute.
The transformation list is modified in-place. |
def export_svg(self):
""" Exports the path as SVG.
Uses the filename given when creating this object.
The file is automatically updated to reflect
changes to the path.
"""
d = ""
if len(self._points) > 0:
d += "M "+s... | Exports the path as SVG.
Uses the filename given when creating this object.
The file is automatically updated to reflect
changes to the path. |
def _splpy_all_ports_ready(callable_):
"""Call all_ports_ready for a primitive operator."""
if hasattr(type(callable_), 'all_ports_ready'):
try:
return callable_.all_ports_ready()
except:
ei = sys.exc_info()
if streamsx._streams._runtime._call_exit(callable_, ... | Call all_ports_ready for a primitive operator. |
def _get_hanging_wall_term(self, C, rup, dists):
"""
Returns the hanging wall scaling term defined in equations 7 to 16
"""
return (C["c10"] *
self._get_hanging_wall_coeffs_rx(C, rup, dists.rx) *
self._get_hanging_wall_coeffs_rrup(dists) *
... | Returns the hanging wall scaling term defined in equations 7 to 16 |
def forever(klass, *args, **kws):
"""Create a server and block the calling thread until KeyboardInterrupt.
Shorthand for: ::
with Server(*args, **kws):
try;
time.sleep(99999999)
except KeyboardInterrupt:
pass
""... | Create a server and block the calling thread until KeyboardInterrupt.
Shorthand for: ::
with Server(*args, **kws):
try;
time.sleep(99999999)
except KeyboardInterrupt:
pass |
def register(self, function=None, *, singleton=False, threadlocal=False, name=None):
"""
Add an object to the injector's registry.
Can be used as a decorator like so:
>>> @injector.register
... def my_dependency(): ...
or a plain function call by passing in a c... | Add an object to the injector's registry.
Can be used as a decorator like so:
>>> @injector.register
... def my_dependency(): ...
or a plain function call by passing in a callable
injector.register(my_dependency)
:param function: The function or callable to ad... |
def groupselectmin(table, key, value, presorted=False, buffersize=None,
tempdir=None, cache=True):
"""Group by the `key` field then return the row with the minimum of the
`value` field within each group. N.B., will only return one row for each
group, even if multiple rows have the same (m... | Group by the `key` field then return the row with the minimum of the
`value` field within each group. N.B., will only return one row for each
group, even if multiple rows have the same (minimum) value. |
def _check_permission(self, name, obj=None):
"""
If customer is not authorized he should not get information that object is exists.
Therefore 403 is returned if object was not found or is redirected to the login page.
If custmer is authorized and object was not found is returned 404.
... | If customer is not authorized he should not get information that object is exists.
Therefore 403 is returned if object was not found or is redirected to the login page.
If custmer is authorized and object was not found is returned 404.
If object was found and user is not authorized is returned 4... |
def Address(self):
"""
Get the wallet address associated with the token.
Returns:
str: base58 encoded string representing the wallet address.
"""
if self._address is None:
self._address = Crypto.ToAddress(self.ScriptHash)
return self._address | Get the wallet address associated with the token.
Returns:
str: base58 encoded string representing the wallet address. |
def split_line(line: str) -> typing.Tuple[str, str]:
"""
Separates the raw line string into two strings: (1) the command and (2) the
argument(s) string
:param line:
:return:
"""
index = line.find(' ')
if index == -1:
return line.lower(), ''
return line[:index].lower(), lin... | Separates the raw line string into two strings: (1) the command and (2) the
argument(s) string
:param line:
:return: |
def create_uniq_field_dis_func(*classes):
# type: (*Type) -> Callable
"""Given attr classes, generate a disambiguation function.
The function is based on unique fields."""
if len(classes) < 2:
raise ValueError("At least two classes required.")
cls_and_attrs = [(cl, set(at.name for at in fie... | Given attr classes, generate a disambiguation function.
The function is based on unique fields. |
def json_error_formatter(body, status, title, environ):
"""A json_formatter for webob exceptions."""
body = webob.exc.strip_tags(body)
status_code = int(status.split(None, 1)[0])
error_dict = {
'status': status_code,
'title': title,
'detail': body
}
return {'errors': [err... | A json_formatter for webob exceptions. |
def parse_lines(stream, separator=None):
"""
Takes each line of a stream, creating a generator that yields
tuples of line, row - where row is the line split by separator
(or by whitespace if separator is None.
:param stream:
:param separator: (optional)
:return: generator
"""
separa... | Takes each line of a stream, creating a generator that yields
tuples of line, row - where row is the line split by separator
(or by whitespace if separator is None.
:param stream:
:param separator: (optional)
:return: generator |
def get_filedata(self, condition=None, page_size=1000):
"""Return a generator over all results matching the provided condition
:param condition: An :class:`.Expression` which defines the condition
which must be matched on the filedata that will be retrieved from
file data store.... | Return a generator over all results matching the provided condition
:param condition: An :class:`.Expression` which defines the condition
which must be matched on the filedata that will be retrieved from
file data store. If a condition is unspecified, the following condition
... |
def error(self, message):
"""error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
"""
self.print_usage(_sys.... | error(message: string)
Prints a usage message incorporating the message to stderr and
exits.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception. |
def framesig(sig, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,)), stride_trick=True):
"""Frame a signal into overlapping frames.
:param sig: the audio signal to frame.
:param frame_len: length of each frame measured in samples.
:param frame_step: number of samples after the start of the prev... | Frame a signal into overlapping frames.
:param sig: the audio signal to frame.
:param frame_len: length of each frame measured in samples.
:param frame_step: number of samples after the start of the previous frame that the next frame should begin.
:param winfunc: the analysis window to apply to each fr... |
def jump( self ):
"""
Select a jump at random from all potential jumps, then update the lattice state.
Args:
None
Returns:
None
"""
potential_jumps = self.potential_jumps()
if not potential_jumps:
raise BlockedLatticeError('No... | Select a jump at random from all potential jumps, then update the lattice state.
Args:
None
Returns:
None |
def prepare_tree(self):
"""
Set link to parent and calculate distance to root for all tree nodes.
Should be run once the tree is read and after every rerooting,
topology change or branch length optimizations.
"""
self.tree.root.branch_length = 0.001
self.tree.root... | Set link to parent and calculate distance to root for all tree nodes.
Should be run once the tree is read and after every rerooting,
topology change or branch length optimizations. |
def bbox_to_poly(north, south, east, west):
"""
Convenience function to parse bbox -> poly
"""
return Polygon([(west, south), (east, south), (east, north), (west, north)]) | Convenience function to parse bbox -> poly |
def has(self, querypart_name, value=None):
"""Returns True if `querypart_name` with `value` is set.
For example you can check if you already used condition by `sql.has('where')`.
If you want to check for more information, for example if that condition
also contain ID, you can do this b... | Returns True if `querypart_name` with `value` is set.
For example you can check if you already used condition by `sql.has('where')`.
If you want to check for more information, for example if that condition
also contain ID, you can do this by `sql.has('where', 'id')`. |
def mapper_from_grid_stack_and_border(self, grid_stack, border):
"""Setup a rectangular mapper from a rectangular pixelization, as follows:
1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border.
2) Determine the rectangular pixelization's geo... | Setup a rectangular mapper from a rectangular pixelization, as follows:
1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border.
2) Determine the rectangular pixelization's geometry, by laying the pixelization over the sub-grid.
3) Setup the re... |
def link_sources(self):
"Returns potential Link or Stream sources."
if isinstance(self, GenericOverlayPlot):
zorders = []
elif self.batched:
zorders = list(range(self.zorder, self.zorder+len(self.hmap.last)))
else:
zorders = [self.zorder]
if i... | Returns potential Link or Stream sources. |
def pack_weights(self, args):
"""Pack separate weight matrices into a single packed
weight.
Parameters
----------
args : dict of str -> NDArray
Dictionary containing unpacked weights.
Returns
-------
args : dict of str -> NDArray
... | Pack separate weight matrices into a single packed
weight.
Parameters
----------
args : dict of str -> NDArray
Dictionary containing unpacked weights.
Returns
-------
args : dict of str -> NDArray
Dictionary with packed weights associated... |
def add_task_bt(self, filename, select=False):
"""
Add a new BT task
:param str filename: path to torrent file to upload
:param bool select: whether to select files in the torrent.
* True: it returns the opened torrent (:class:`.Torrent`) and
can then iterat... | Add a new BT task
:param str filename: path to torrent file to upload
:param bool select: whether to select files in the torrent.
* True: it returns the opened torrent (:class:`.Torrent`) and
can then iterate files in :attr:`.Torrent.files` and
select/unsele... |
def count_calls_with_dims(**dims):
"""Decorator to track the number of times a function is called
with with dimensions.
"""
def counter_wrapper(fn):
@functools.wraps(fn)
def fn_wrapper(*args, **kwargs):
counter("%s_calls" %
pyformance.registry.get_qualname... | Decorator to track the number of times a function is called
with with dimensions. |
def generate_scan_parameter_description(scan_parameters):
'''Generate scan parameter dictionary. This is the only way to dynamically create table with dictionary, cannot be done with tables.IsDescription
Parameters
----------
scan_parameters : list, tuple
List of scan parameters names (strings)... | Generate scan parameter dictionary. This is the only way to dynamically create table with dictionary, cannot be done with tables.IsDescription
Parameters
----------
scan_parameters : list, tuple
List of scan parameters names (strings).
Returns
-------
table_description : dict
T... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.