code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def get_status(self, json_status=None): """ Returns status of for json """ if json_status: self.json_status = json_status if self.json_status not in AjaxResponseStatus.choices: raise ValueError( "Invalid status selected: '{}'".format(self.json_status)) ...
Returns status of for json
def get_project_session(project_name, project_directory, map_type=None): """ Load project manager and in memory sqlite db sessionmaker for GSSHA project """ sqlalchemy_url, sql_engine = init_sqlite_memory() gdb_sessionmaker = get_sessionmaker(sqlalchemy_url, sql_engine) project_manager = Project...
Load project manager and in memory sqlite db sessionmaker for GSSHA project
def perform(self, specifications): """ This method is the entry point of javascript code writer. Monolithe will call it when the javascript plugin is to generate code. """ self.enum_list = [] self.model_list = [] self.job_commands = filter(lambda attr: attr.name == 'comma...
This method is the entry point of javascript code writer. Monolithe will call it when the javascript plugin is to generate code.
def start(self): """ Start a node """ try: # For IOU we need to send the licence everytime if self.node_type == "iou": try: licence = self._project.controller.settings["IOU"]["iourc_content"] except KeyError: ...
Start a node
def run(parser, args, output_file=sys.stdout): """Run command line interface.""" # Try loading results file (if requested) result_storage = {} if args.store: args.store.seek(0) try: result_storage = pickle.load(args.store) except EOFError: pass arg...
Run command line interface.
def server_bind(self, *args, **kwargs): '''Server Bind. Forces reuse of port.''' self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Can't use super() here since SimpleXMLRPCServer is an old-style class SimpleXMLRPCServer.server_bind(self, *args, **kwargs)
Server Bind. Forces reuse of port.
def db_get(table, record, column, if_exists=False): ''' Gets a column's value for a specific record. Args: table: A string - name of the database table. record: A string - identifier of the record. column: A string - name of the column. if_exists: A boolean - if True, it is ...
Gets a column's value for a specific record. Args: table: A string - name of the database table. record: A string - identifier of the record. column: A string - name of the column. if_exists: A boolean - if True, it is not an error if the record does not exist. Retu...
def add_sldId(self, rId): """ Return a reference to a newly created <p:sldId> child element having its r:id attribute set to *rId*. """ return self._add_sldId(id=self._next_id, rId=rId)
Return a reference to a newly created <p:sldId> child element having its r:id attribute set to *rId*.
def get_one_version(kwargs=None, call=None): ''' Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name ''' if call == 'action': raise SaltCloudSystemExit( 'The get_cluster_...
Returns the OpenNebula version. .. versionadded:: 2016.3.5 CLI Example: .. code-block:: bash salt-cloud -f get_one_version one_provider_name
def genes(context, build, api_key): """ Load the hgnc aliases to the mongo database. """ LOG.info("Running scout update genes") adapter = context.obj['adapter'] # Fetch the omim information api_key = api_key or context.obj.get('omim_api_key') if not api_key: LOG.warning("Please ...
Load the hgnc aliases to the mongo database.
def check_ends_with_period(self, definition, docstring): """D400: First line should end with a period. The [first line of a] docstring is a phrase ending in a period. """ if docstring: summary_line = ast.literal_eval(docstring).strip().split('\n')[0] if not summ...
D400: First line should end with a period. The [first line of a] docstring is a phrase ending in a period.
def space(self, n=1, interval=0, pre_dl=None, post_dl=None): """Press white space key n times. **中文文档** 按空格键 n 次。 """ self.delay(pre_dl) self.k.tap_key(self.k.space_key, n) self.delay(post_dl)
Press white space key n times. **中文文档** 按空格键 n 次。
def worker_exec(self, **kwargs): """Target function of workers""" self.feed(**kwargs) self.logger.info('thread {} exit'.format(current_thread().name))
Target function of workers
def remove_redis_keyword(self, keyword): ''' Remove the keyword for redis. ''' redisvr.srem(CMS_CFG['redis_kw'] + self.userinfo.user_name, keyword) return json.dump({}, self)
Remove the keyword for redis.
def setcookie(self, key, value, max_age=None, expires=None, path='/', domain=None, secure=None, httponly=False): """ Add a new cookie """ newcookie = Morsel() newcookie.key = key newcookie.value = value newcookie.coded_value = value if max_age is not None:...
Add a new cookie
def check_for_errors(self): """Check connection and channel for errors. :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ try...
Check connection and channel for errors. :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
def chunks(l, n): """ Yield n successive chunks from l. """ newn = int(1.0 * len(l) / n + 0.5) for i in range(0, n - 1): yield l[i * newn:i * newn + newn] yield l[n * newn - newn:]
Yield n successive chunks from l.
def unstash(self, filter_func=None, to_stash='active', from_stash='stashed'): """ Unstash some states. This is an alias for move(), with defaults for the stashes. :param filter_func: Unstash states that match this filter. Should be a function that takes a state and r...
Unstash some states. This is an alias for move(), with defaults for the stashes. :param filter_func: Unstash states that match this filter. Should be a function that takes a state and returns True or False. (default: unstash all states) :param from_stash: take matching stat...
def linRegressUsingMasked2dArrays(xVals, arrays, badMask=None, zeroOffset=False, calcError=False): """ if you have multiple 2d arrays each with position given by xVals[array-index] and you want to do a linear regression on all cells ...
if you have multiple 2d arrays each with position given by xVals[array-index] and you want to do a linear regression on all cells but you also might mask different areas in each 2darray zeroOffset - whether plot goest through origin returns ascent, offset, RMS-error
def t0_ref_supconj(b, orbit, solve_for=None, **kwargs): """ Create a constraint for t0_ref in an orbit - allowing translating between t0_ref and t0_supconj. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should ...
Create a constraint for t0_ref in an orbit - allowing translating between t0_ref and t0_supconj. :parameter b: the :class:`phoebe.frontend.bundle.Bundle` :parameter str orbit: the label of the orbit in which this constraint should be built :parameter str solve_for: if 't0_ref' should not be th...
def extract_tree_block(self): "iterate through data file to extract trees" lines = iter(self.data) while 1: try: line = next(lines).strip() except StopIteration: break # enter trees block if line.lower(...
iterate through data file to extract trees
def _make_request(self, params, translation_url, headers): """ This is the final step, where the request is made, the data is retrieved and returned. """ resp = requests.get(translation_url, params=params, headers=headers) resp.encoding = "UTF-8-sig" ...
This is the final step, where the request is made, the data is retrieved and returned.
def validate_identifier(self, field): """Validate field identifier.""" if field.data: field.data = field.data.lower() if Community.get(field.data, with_deleted=True): raise validators.ValidationError( _('The identifier already exists. ' ...
Validate field identifier.
def analysis_summary_report(feature, parent): """Retrieve an HTML table report of current selected analysis. """ _ = feature, parent # NOQA project_context_scope = QgsExpressionContextUtils.projectScope( QgsProject.instance()) key = provenance_layer_analysis_impacted['provenance_key'] i...
Retrieve an HTML table report of current selected analysis.
def armor(blob, type_str): """See https://tools.ietf.org/html/rfc4880#section-6 for details.""" head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str) body = base64.b64encode(blob).decode('ascii') checksum = base64.b64encode(util.crc24(blob)).decode('ascii') tail = '-----END PGP {}-...
See https://tools.ietf.org/html/rfc4880#section-6 for details.
def _create_response_record(self, response): """Creates record for lexicon API calls""" record = dict() record['id'] = response['id'] record['type'] = response['type'] record['name'] = self._full_name(response['name']) if 'content' in response: record['content...
Creates record for lexicon API calls
def query_mousemine(intermine_url: str, gene_id: str) -> IntermineResult: """ :param intermine_url: intermine server, eg http://www.mousemine.org/mousemine/service :param gene_id: gene ID, eg ENSMUSG00000063180 :return: Intermine_Result object """ service = Service(inte...
:param intermine_url: intermine server, eg http://www.mousemine.org/mousemine/service :param gene_id: gene ID, eg ENSMUSG00000063180 :return: Intermine_Result object
def get_as_html(self) -> str: """ Returns the table object as an HTML string. :return: HTML representation of the table. """ table_string = self._get_pretty_table().get_html_string() title = ('{:^' + str(len(table_string.splitlines()[0])) + '}').format(self.title) ...
Returns the table object as an HTML string. :return: HTML representation of the table.
def update(self, user, **kwargs): """If parent resource is not an editable state, should not be able to update""" yield self.get_parent() if not self.parent.editable: err = 'Cannot update child of {} resource'.format(self.parent.state.name) raise exceptions.Unauthorized(...
If parent resource is not an editable state, should not be able to update
def annotate(args): """ %prog annotate blastfile query.fasta subject.fasta Annotate overlap types (dovetail, contained, etc) in BLAST tabular file. """ from jcvi.assembly.goldenpath import Cutoff, Overlap, Overlap_types p = OptionParser(annotate.__doc__) p.set_align(pctid=94, hitlen=500) ...
%prog annotate blastfile query.fasta subject.fasta Annotate overlap types (dovetail, contained, etc) in BLAST tabular file.
def add_service(protocol=None, service_address=None, scheduler='wlc'): ''' Add a virtual service. protocol The service protocol(only support tcp, udp and fwmark service). service_address The LVS service address. scheduler Algorithm for allocating TCP connections and UDP da...
Add a virtual service. protocol The service protocol(only support tcp, udp and fwmark service). service_address The LVS service address. scheduler Algorithm for allocating TCP connections and UDP datagrams to real servers. CLI Example: .. code-block:: bash salt...
def plot_fluxseries( self, names: Optional[Iterable[str]] = None, average: bool = False, **kwargs: Any) \ -> None: """Plot the `flux` series of the handled model. See the documentation on method |Element.plot_inputseries| for additional information. "...
Plot the `flux` series of the handled model. See the documentation on method |Element.plot_inputseries| for additional information.
def run(self, *args): """Move an identity into a unique identity.""" params = self.parser.parse_args(args) from_id = params.from_id to_uuid = params.to_uuid code = self.move(from_id, to_uuid) return code
Move an identity into a unique identity.
def get_identity(self, subject_id, entities=None, check_not_on_or_after=True): """ Get all the identity information that has been received and are still valid about the subject. :param subject_id: The identifier of the subject :param entities: The identifiers of the...
Get all the identity information that has been received and are still valid about the subject. :param subject_id: The identifier of the subject :param entities: The identifiers of the entities whoes assertions are interesting. If the list is empty all entities are interesting. ...
def sync_one(self, aws_syncr, amazon, key): """Make sure this key is as defined""" key_info = amazon.kms.key_info(key.name, key.location) if not key_info: amazon.kms.create_key(key.name, key.description, key.location, key.grant, key.policy.document) else: amazon.k...
Make sure this key is as defined
def set_condition_expression(self, value): """ Setter for 'condition_expression' field. :param value - a new value of 'condition_expression' field. """ if value is None: self.__condition_expression = value if not isinstance(value, condition_expression.Conditio...
Setter for 'condition_expression' field. :param value - a new value of 'condition_expression' field.
def scan_index(content_dir): """ Scan all files in a content directory """ def scan_directory(root, files): """ Helper function to scan a single directory """ try: for file in files: fullpath = os.path.join(root, file) relpath = os.path.relpath(fullpa...
Scan all files in a content directory
def unimplemented(self, node): """Unimplemented nodes.""" self.raise_exception(node, exc=NotImplementedError, msg="'%s' not supported" % (node.__class__.__name__))
Unimplemented nodes.
def _no_answer_do_retry(self, pk, pattern): """Resend packets that we have not gotten answers to""" logger.info('Resending for pattern %s', pattern) # Set the timer to None before trying to send again self.send_packet(pk, expected_reply=pattern, resend=True)
Resend packets that we have not gotten answers to
def rels(self): """Returns a LIST of all the metadata relations""" r = [] for i in self.metadata: r = r + i[REL] return []
Returns a LIST of all the metadata relations
def is_subdomain(domain, reference): """Tests if a hostname is a subdomain of a reference hostname e.g. www.domain.com is subdomain of reference @param domain: Domain to test if it is a subdomain @param reference: Reference "parent" domain """ index_of_reference = domain.find(reference) if ...
Tests if a hostname is a subdomain of a reference hostname e.g. www.domain.com is subdomain of reference @param domain: Domain to test if it is a subdomain @param reference: Reference "parent" domain
def subtract(self, **kwargs): """Returns a new MayaDT object with the given offsets.""" return self.from_datetime( pendulum.instance(self.datetime()).subtract(**kwargs) )
Returns a new MayaDT object with the given offsets.
def all_partitions(mechanism, purview, node_labels=None): """Return all possible partitions of a mechanism and purview. Partitions can consist of any number of parts. Args: mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Yields: KPartition: A partition of...
Return all possible partitions of a mechanism and purview. Partitions can consist of any number of parts. Args: mechanism (tuple[int]): A mechanism. purview (tuple[int]): A purview. Yields: KPartition: A partition of this mechanism and purview into ``k`` parts.
def _next_trace_frames( self, session: Session, trace_frame: TraceFrameQueryResult, visited_ids: Set[int], backwards: bool = False, ) -> List[TraceFrameQueryResult]: """Finds all trace frames that the given trace_frame flows to. When backwards=True, the resul...
Finds all trace frames that the given trace_frame flows to. When backwards=True, the result will include the parameter trace_frame, since we are filtering on the parameter's callee.
def events(self, *etypes, idle_timeout=None): """ returns a blocking generator yielding Slack event objects params: - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of valid event...
returns a blocking generator yielding Slack event objects params: - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of valid event types. - idle_timeout(int): optional maximum amount of t...
def getFileLine(where=-1, targetModule=None): """ Return the filename and line number for the given location. If where is a negative integer, look for the code entry in the current stack that is the given number of frames above this module. If where is a function, look for the code entry of the fun...
Return the filename and line number for the given location. If where is a negative integer, look for the code entry in the current stack that is the given number of frames above this module. If where is a function, look for the code entry of the function. @param where: how many frames to go back up, o...
def extract_code_from_function(function): """Return code handled by function.""" if not function.__name__.startswith('fix_'): return None code = re.sub('^fix_', '', function.__name__) if not code: return None try: int(code[1:]) except ValueError: return None ...
Return code handled by function.
def int_pair(s, default=(0, None)): """Return the digits to either side of a single non-digit character as a 2-tuple of integers >>> int_pair('90210-007') (90210, 7) >>> int_pair('04321.0123') (4321, 123) """ s = re.split(r'[^0-9]+', str(s).strip()) if len(s) and len(s[0]): if l...
Return the digits to either side of a single non-digit character as a 2-tuple of integers >>> int_pair('90210-007') (90210, 7) >>> int_pair('04321.0123') (4321, 123)
def add_chassis(self, chassis, port=22611, password='xena'): """ Add chassis. XenaManager-2G -> Add Chassis. :param chassis: chassis IP address :param port: chassis port number :param password: chassis password :return: newly created chassis :rtype: xenamanager....
Add chassis. XenaManager-2G -> Add Chassis. :param chassis: chassis IP address :param port: chassis port number :param password: chassis password :return: newly created chassis :rtype: xenamanager.xena_app.XenaChassis
def _prepare_order_bys(self): """ Build a set of order by columns """ order_bys = OrderedSet() if self._order_bys: for ingredient in self._order_bys: if isinstance(ingredient, Dimension): # Reverse the ordering columns so that dimensions ...
Build a set of order by columns
def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs): """ Create an iterator that generates mini-batch sample indices The generated mini-batches indices take the form of nested lists of either: - 1D NumPy integer arrays - slices The list nesting ...
Create an iterator that generates mini-batch sample indices The generated mini-batches indices take the form of nested lists of either: - 1D NumPy integer arrays - slices The list nesting structure with match that of the tree of data sources rooted at `self` Pa...
def lfc(pressure, temperature, dewpt, parcel_temperature_profile=None, dewpt_start=None): r"""Calculate the level of free convection (LFC). This works by finding the first intersection of the ideal parcel path and the measured parcel temperature. Parameters ---------- pressure : `pint.Quantity...
r"""Calculate the level of free convection (LFC). This works by finding the first intersection of the ideal parcel path and the measured parcel temperature. Parameters ---------- pressure : `pint.Quantity` The atmospheric pressure temperature : `pint.Quantity` The temperature a...
def single_qubit_matrix_to_gates( mat: np.ndarray, tolerance: float = 0 ) -> List[ops.SingleQubitGate]: """Implements a single-qubit operation with few gates. Args: mat: The 2x2 unitary matrix of the operation to implement. tolerance: A limit on the amount of error introduced by the ...
Implements a single-qubit operation with few gates. Args: mat: The 2x2 unitary matrix of the operation to implement. tolerance: A limit on the amount of error introduced by the construction. Returns: A list of gates that, when applied in order, perform the desired ...
def get_lldp_neighbor_detail_input_request_type_get_rbridge_specific_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail input = ET.SubElem...
Auto Generated Code
def get_generated_vcl(self, service_id, version_number): """Display the generated VCL for a particular service and version.""" content = self._fetch("/service/%s/version/%d/generated_vcl" % (service_id, version_number)) return FastlyVCL(self, content)
Display the generated VCL for a particular service and version.
def _internal_get_cut_vertex_list(graph): """Works on a single connected component to produce the node list of cut vertices. Returns a list of nodes. Returns an empty list if there are no nodes in the graph (i.e. if it's an empty graph). """ list_of_cut_vertices = set() if graph.num_nodes() == 0...
Works on a single connected component to produce the node list of cut vertices. Returns a list of nodes. Returns an empty list if there are no nodes in the graph (i.e. if it's an empty graph).
async def blob(self, elem=None, elem_type=None, params=None): """ Loads/dumps blob :return: """ elem_type = elem_type if elem_type else elem.__class__ if hasattr(elem_type, 'kv_serialize'): elem = elem_type() if elem is None else elem return await ...
Loads/dumps blob :return:
def check_arguments(c: typing.Callable, hints: typing.Mapping[str, typing.Optional[type]], *args, **kwargs) -> None: """Check arguments type, raise :class:`TypeError` if argument type is not expected type. :param c: callable object want to check types :param hint...
Check arguments type, raise :class:`TypeError` if argument type is not expected type. :param c: callable object want to check types :param hints: assumed type of given ``c`` result of :func:`typing.get_type_hints`
def _map_agent_mod(self, agent, mod_condition): """Map a single modification condition on an agent. Parameters ---------- agent : :py:class:`indra.statements.Agent` Agent to check for invalid modification sites. mod_condition : :py:class:`indra.statements.ModConditio...
Map a single modification condition on an agent. Parameters ---------- agent : :py:class:`indra.statements.Agent` Agent to check for invalid modification sites. mod_condition : :py:class:`indra.statements.ModCondition` Modification to check for validity and map. ...
def __get_password(self, description='', confirm=False, clear=False, username='glances'): """Read a password from the command line. - if confirm = True, with confirmation - if clear = True, plain (clear password) """ from glances.password import GlancesPas...
Read a password from the command line. - if confirm = True, with confirmation - if clear = True, plain (clear password)
def train_batch(self, batch_info: BatchInfo) -> None: """ Batch - the most atomic unit of learning. For this reinforforcer, that involves: 1. Roll out environment and store out experience in the buffer 2. Sample the buffer and train the algo on sample batch """ ...
Batch - the most atomic unit of learning. For this reinforforcer, that involves: 1. Roll out environment and store out experience in the buffer 2. Sample the buffer and train the algo on sample batch
def _frame_received(self, frame): """ Put the frame into the _rx_frames dict with a key of the frame_id. """ try: self._rx_frames[frame["frame_id"]] = frame except KeyError: # Has no frame_id, ignore? pass _LOGGER.debug("Frame received:...
Put the frame into the _rx_frames dict with a key of the frame_id.
def secp256k1(): """ create the secp256k1 curve """ GFp = FiniteField(2 ** 256 - 2 ** 32 - 977) # This is P from below... aka FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F ec = EllipticCurve(GFp, 0, 7) return ECDSA(ec, ec.point(0x79BE667EF9DCBBAC55A062...
create the secp256k1 curve
def log_and_count(self, event_str, msg_str=None, inc_int=None): """Count an event and write a message to a logger. Args: event_str: str The name of an event to count. Used as a key in the event dict. The same name will be used in the summary. This also becomes a part o...
Count an event and write a message to a logger. Args: event_str: str The name of an event to count. Used as a key in the event dict. The same name will be used in the summary. This also becomes a part of the message logged by this function. msg_str: str ...
def open(self): """Connect to modbus server (open TCP connection) :returns: connect status (True if open) :rtype: bool """ # restart TCP if already open if self.is_open(): self.close() # init socket and connect # list available sockets on the ...
Connect to modbus server (open TCP connection) :returns: connect status (True if open) :rtype: bool
def create_repo(self, repo_name=None, feed=None, envs=[], checksum_type="sha256", query='/repositories/'): """ `repo_name` - Name of repository to create `feed` - Repo URL to feed from `checksum_type` - Used for generating meta-data Create repository in specified environments, a...
`repo_name` - Name of repository to create `feed` - Repo URL to feed from `checksum_type` - Used for generating meta-data Create repository in specified environments, associate the yum_distributor with it and publish the repo
def _from_pb(cls, pb, set_key=True, ent=None, key=None): """Internal helper to create an entity from an EntityProto protobuf.""" if not isinstance(pb, entity_pb.EntityProto): raise TypeError('pb must be a EntityProto; received %r' % pb) if ent is None: ent = cls() # A key passed in override...
Internal helper to create an entity from an EntityProto protobuf.
def get(self): """ Constructs a TaskActionsContext :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext """ return TaskActionsContext( self._version, ...
Constructs a TaskActionsContext :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext
def insert_or_merge_entity(self, table_name, entity, timeout=None): ''' Merges an existing entity or inserts a new entity if it does not exist in the table. If insert_or_merge_entity is used to merge an entity, any properties from the previous entity will be retained if the re...
Merges an existing entity or inserts a new entity if it does not exist in the table. If insert_or_merge_entity is used to merge an entity, any properties from the previous entity will be retained if the request does not define or include them. :param str table_name: ...
def create_node(self, body, **kwargs): # noqa: E501 """create_node # noqa: E501 create a Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_node(body, async_req=Tr...
create_node # noqa: E501 create a Node # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_node(body, async_req=True) >>> result = thread.get() :param async_req ...
def init(self, advertise_addr=None, listen_addr='0.0.0.0:2377', force_new_cluster=False, default_addr_pool=None, subnet_size=None, **kwargs): """ Initialize a new swarm on this Engine. Args: advertise_addr (str): Externally reachable address advertised to ...
Initialize a new swarm on this Engine. Args: advertise_addr (str): Externally reachable address advertised to other nodes. This can either be an address/port combination in the form ``192.168.1.1:4567``, or an interface followed by a port number, like...
def allmap(self, fcn, args): """ Do a function call on every worker with different arguments Parameters ---------- fcn: funtion Function to call. args: tuple The arguments for Pool.map """ results = self.map(_lockstep_fcn, ...
Do a function call on every worker with different arguments Parameters ---------- fcn: funtion Function to call. args: tuple The arguments for Pool.map
def _build_process_container_tree(self, pids): """ tops = [1,2,3] childs = {1: [4,5], 2: [6,7], 3: [], 4: []} """ containers = [] procs = [] ppids = [] childs = {} for pid in pids: proc = process.Process(pid) procs.append(pr...
tops = [1,2,3] childs = {1: [4,5], 2: [6,7], 3: [], 4: []}
def upload(self, localpath, href): """ Upload file from localpath to remote server :param localpath: local path :param href: remote path :return: response """ localpath = _(localpath) href = remote(href) if not os.path.exists(localpath): ...
Upload file from localpath to remote server :param localpath: local path :param href: remote path :return: response
def use_gae_thread(): """Makes ``Client``s started after this use the appengine thread class.""" global _THREAD_CLASS # pylint: disable=global-statement try: from google.appengine.api.background_thread import background_thread _THREAD_CLASS = background_thread.BackgroundThread except Im...
Makes ``Client``s started after this use the appengine thread class.
def readShiftFile(self, filename): """ Reads a shift file from disk and populates a dictionary. """ order = [] fshift = open(filename,'r') flines = fshift.readlines() fshift.close() common = [f.strip('#').strip() for f in flines if f.startswith('#')] ...
Reads a shift file from disk and populates a dictionary.
def install_middleware(self): """ Attempts to insert the ScoutApm middleware as the first middleware (first on incoming requests, last on outgoing responses). """ from django.conf import settings # If MIDDLEWARE is set, update that, with handling of tuple vs array forms ...
Attempts to insert the ScoutApm middleware as the first middleware (first on incoming requests, last on outgoing responses).
def generate_key_bytes(hashclass, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} t...
Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. @param hashclass: class from L{Crypto.Hash} that can be used as a secure hashing function (like C{MD5} ...
def get_modal_link(self, url, obj={}): """ Returns the metadata for a link that needs to be confirmed, if it exists, it also parses the message and title of the url to include row field data if needed. """ if not (url in self.modal_links.keys()): return None ...
Returns the metadata for a link that needs to be confirmed, if it exists, it also parses the message and title of the url to include row field data if needed.
def parse_pattern(s): """Parse a string such as 'foo/bar/*.py' Assumes is_pattern(s) has been called and returned True 1. directory to process 2. pattern to match""" if '{' in s: return None, None # Unsupported by fnmatch if s and s[0] == '~': s = os.path.expanduser(s) parts...
Parse a string such as 'foo/bar/*.py' Assumes is_pattern(s) has been called and returned True 1. directory to process 2. pattern to match
def check(self): "either invalid or one of quorum, noquorum, quorumpossible" if not self.is_valid: return True test = (self.has_quorum, self.has_quorum_possible, self.has_noquorum) assert 1 == len([x for x in test if x is not None]) return True
either invalid or one of quorum, noquorum, quorumpossible
def initdb(): """ Sync database Create new tables etc... """ print("Syncing up database...") cwd_to_sys_path() if db and hasattr(db, "Model"): db.create_all() for m in db.Model.__subclasses__(): if hasattr(m, "initialize__"): print("Sync up model: %s ..." % m...
Sync database Create new tables etc...
def msvc9_find_vcvarsall(version): """ Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone compiler build for Python (VCForPython). Fall back to original behavior when the standalone compiler is not available. Redirect the path of "vcvarsall.bat". Known supported compilers ...
Patched "distutils.msvc9compiler.find_vcvarsall" to use the standalone compiler build for Python (VCForPython). Fall back to original behavior when the standalone compiler is not available. Redirect the path of "vcvarsall.bat". Known supported compilers ------------------------- Microsoft Visu...
def process_ether_frame(self, id=None, msg=None): """process_ether_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg ...
process_ether_frame Convert a complex nested json dictionary to a flattened dictionary and capture all unique keys for table construction :param id: key for this msg :param msg: ether frame for packet
def det2lab_xds( pixels_coord, frame_number, starting_frame, starting_angle, oscillation_angle, rotation_axis, wavelength, wavevector, NX, NY, pixelsize_x, pixelsize_y, distance_to_detector, x_center, y_center, detector_x, detector_y, detector_normal, **kwargs): ...
Converts pixels coordinates from the frame into q-vector
def _transform_call_params(self, params): """ possible modifiers: file, b64encode, b64decode format: modifier1@modifier2@...modifierN@k_final """ rez = {} for k, v in params.items(): if isinstance(v, dict): v = self._transform_call_...
possible modifiers: file, b64encode, b64decode format: modifier1@modifier2@...modifierN@k_final
def start_capture(self, adapter_number, output_file): """ Starts a packet capture. :param adapter_number: adapter number :param output_file: PCAP destination file for the capture """ try: adapter = self._ethernet_adapters[adapter_number] except KeyEr...
Starts a packet capture. :param adapter_number: adapter number :param output_file: PCAP destination file for the capture
def MI_deleteInstance(self, env, instanceName): # pylint: disable=invalid-name """Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally ove...
Delete a CIM instance Implements the WBEM operation DeleteInstance in terms of the delete_instance method. A derived class will not normally override this method.
def urlunsplit(data): """Combine the elements of a tuple as returned by urlsplit() into a complete URL as a string. The data argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example,...
Combine the elements of a tuple as returned by urlsplit() into a complete URL as a string. The data argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an empty query;...
def fade_speed(self, value): """ Setter for **self.__fade_speed** attribute. :param value: Attribute value. :type value: float """ if value is not None: assert type(value) is float, "'{0}' attribute: '{1}' type is not 'float'!".format("fade_speed", value) ...
Setter for **self.__fade_speed** attribute. :param value: Attribute value. :type value: float
def get_next_step(self): """Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None """ if self.rbAggLayerFromCanvas.isChecked(): new_step = self.parent.step_fc_agglayer_from_canvas elif ...
Find the proper step when user clicks the Next button. :returns: The step to be switched to :rtype: WizardStep instance or None
def set_status(self, value): """Set the status of the scheduling object.""" self._check_object_exists() DB.set_hash_value(self.key, 'status', value) self.publish('status_changed', event_data=dict(status=value))
Set the status of the scheduling object.
def nucmer_hit_containing_reference_position(nucmer_hits, ref_name, ref_position, qry_name=None): '''Returns the first nucmer match found that contains the given reference location. nucmer_hits = hits made by self._parse_nucmer_coords_file. Returns None if no matching hit found''' ...
Returns the first nucmer match found that contains the given reference location. nucmer_hits = hits made by self._parse_nucmer_coords_file. Returns None if no matching hit found
def convert_time_stamp_to_date(content): '''Convert time stamp to date time format''' start_time_stamp = content.get('startTime') end_time_stamp = content.get('endTime') if start_time_stamp: start_time = datetime.datetime.utcfromtimestamp(start_time_stamp // 1000).strftime("%Y/%m/%d %H:%M:%S") ...
Convert time stamp to date time format
def close(self): """Close connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return: """ LOGGER.debug('Connection Closing') if not self.is_closed: self.set_state(self.CLOSING) ...
Close connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
def whole_sequence_accuracy(y_true, y_pred, lengths): """Average accuracy measured on whole sequences. Returns the fraction of sequences in y_true that occur in y_pred without a single error. """ lengths = np.asarray(lengths) end = np.cumsum(lengths) start = end - lengths bounds = np.vs...
Average accuracy measured on whole sequences. Returns the fraction of sequences in y_true that occur in y_pred without a single error.
def load_clubs(self): """Fetches the MAL user clubs page and sets the current user's clubs attributes. :rtype: :class:`.User` :return: Current user object. """ user_clubs = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/clubs').text self.s...
Fetches the MAL user clubs page and sets the current user's clubs attributes. :rtype: :class:`.User` :return: Current user object.
def selected(self): """Get column which is being order by.""" if self._selected: return self._selected if self.asc else \ "-{0}".format(self._selected) return None
Get column which is being order by.
def callJavaFunc(func, *args): """ Call Java Function """ gateway = _get_gateway() args = [_py2java(gateway, a) for a in args] result = func(*args) return _java2py(gateway, result)
Call Java Function
def process_fixed_issues(self, volumes, existing_issues): """Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict...
Provided a list of volumes and existing issues, returns a list of fixed issues to be deleted Args: volumes (`dict`): A dictionary keyed on the issue id, with the :obj:`Volume` object as the value existing_issues (`dict`): A dictionary keyed on the issue id, with the :obj:`EBSVolumeAudit...