code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def _start_of_century(self): year = self.year - 1 - (self.year - 1) % YEARS_PER_CENTURY + 1 return self.set(year, 1, 1)
Reset the date to the first day of the century. :rtype: Date
def get_item(self, item_id): if self.object_id: url = self.build_url( self._endpoints.get('get_item').format(id=self.object_id, item_id=item_id)) else: url = self.build_url( self._endpoints.get...
Returns a DriveItem by it's Id :return: one item :rtype: DriveItem
def _poll_loop(self): next_poll = time.time() while True: next_poll += self._poll_period timeout = next_poll - time.time() if timeout < 0: timeout = 0 try: return self._stop_queue.get(timeout=timeout) except Time...
At self.poll_period poll for changes
def _get_request_body_bytes_only(param_name, param_value): if param_value is None: return b'' if isinstance(param_value, bytes): return param_value raise TypeError(_ERROR_VALUE_SHOULD_BE_BYTES.format(param_name))
Validates the request body passed in and converts it to bytes if our policy allows it.
def viewbox(self): return self.left, self.top, self.right, self.bottom
Return bounding box of the viewport. :return: (left, top, right, bottom) `tuple`.
def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None): watcher = watch.Watch() for event in watcher.stream( resource.get, namespace=namespace, name=name, field_selector=field_sel...
Stream events for a resource from the Kubernetes API :param resource: The API resource object that will be used to query the API :param namespace: The namespace to query :param name: The name of the resource instance to query :param label_selector: The label selector with which to filte...
def nlmsg_reserve(n, len_, pad): nlmsg_len_ = n.nm_nlh.nlmsg_len tlen = len_ if not pad else ((len_ + (pad - 1)) & ~(pad - 1)) if tlen + nlmsg_len_ > n.nm_size: return None buf = bytearray_ptr(n.nm_nlh.bytearray, nlmsg_len_) n.nm_nlh.nlmsg_len += tlen if tlen > len_: bytearray_pt...
Reserve room for additional data in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407 Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be zeroed out. bytearray_ptr() at the start of additional data or No...
def all_nets(transform_func): @functools.wraps(transform_func) def t_res(**kwargs): net_transform(transform_func, **kwargs) return t_res
Decorator that wraps a net transform function
def _narrow_states(node, old_state, new_state, previously_widened_state): l.debug('Narrowing state at IP %s', previously_widened_state.ip) s = previously_widened_state.copy() narrowing_occurred = False return s, narrowing_occurred
Try to narrow the state! :param old_state: :param new_state: :param previously_widened_state: :returns: The narrowed state, and whether a narrowing has occurred
def write_requirements(reqs_linenum, req_file): with open(req_file, 'r') as input: lines = input.readlines() for req in reqs_linenum: line_num = int(req[1]) if hasattr(req[0], 'link'): lines[line_num - 1] = '{}\n'.format(req[0].link) else: lines[line_num -...
Writes a list of req objects out to a given file.
def get_access_flags_string(value): buff = "" for i in ACCESS_FLAGS: if (i[0] & value) == i[0]: buff += i[1] + " " if buff != "": return buff[:-1] return buff
Transform an access flags to the corresponding string :param value: the value of the access flags :type value: int :rtype: string
def _from_dict(cls, _dict): args = {} if 'batches' in _dict: args['batches'] = [ BatchStatus._from_dict(x) for x in (_dict.get('batches')) ] return cls(**args)
Initialize a Batches object from a json dictionary.
def search_for_devices_by_serial_number(self, sn): import re sn_search = re.compile(sn) matches = [] for dev_o in self.get_all_devices_in_portal(): try: if sn_search.match(dev_o['sn']): matches.append(dev_o) except TypeError as ...
Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers.
async def jsk_vc_play(self, ctx: commands.Context, *, uri: str): voice = ctx.guild.voice_client if voice.is_playing(): voice.stop() uri = uri.lstrip("<").rstrip(">") voice.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(uri))) await ctx.send(f"Playing in {voi...
Plays audio direct from a URI. Can be either a local file or an audio resource on the internet.
def _draw_score_box(self, label, score, position, size): x1, y1 = position width, height = size pygame.draw.rect(self.screen, (187, 173, 160), (x1, y1, width, height)) w, h = label.get_size() self.screen.blit(label, (x1 + (width - w) / 2, y1 + 8)) score = self.score_font....
Draw a score box, whether current or best.
def cfset_to_set(cfset): count = cf.CFSetGetCount(cfset) buffer = (c_void_p * count)() cf.CFSetGetValues(cfset, byref(buffer)) return set([cftype_to_value(c_void_p(buffer[i])) for i in range(count)])
Convert CFSet to python set.
def parse(self, rrstr): if self._initialized: raise pycdlibexception.PyCdlibInternalError('SF record already initialized!') (su_len, su_entry_version_unused,) = struct.unpack_from('=BB', rrstr[:4], 2) if su_len == 12: (virtual_file_size_le, virtual_file_size_be) = struct....
Parse a Rock Ridge Sparse File record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
def concatenate_join_units(join_units, concat_axis, copy): if concat_axis == 0 and len(join_units) > 1: raise AssertionError("Concatenating join units along axis0") empty_dtype, upcasted_na = get_empty_dtype_and_na(join_units) to_concat = [ju.get_reindexed_values(empty_dtype=empty_dtype, ...
Concatenate values from several join units along selected axis.
def post(self, url, data=None, files=None, headers=None, raw=False, send_as_json=True, content_type=None, **request_kwargs): return self._secure_request( url, 'post', data=data, files=files, headers=headers, raw=raw, send_as_json=send_as_json, content_type=content_type, ...
POST request to AmigoCloud endpoint.
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): result = [] items = sorted(self.items()) for key, value in items: result.append(value.output(attrs, header)) return sep.join(result)
Return a string suitable for HTTP.
def _locked_refresh_doc_ids(self): d = {} for s in self._shards: for k in s.doc_index.keys(): if k in d: raise KeyError('doc "{i}" found in multiple repos'.format(i=k)) d[k] = s self._doc2shard_map = d
Assumes that the caller has the _index_lock !
def namespace(self, name=None, function=None, recursive=None): return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.namespace], name=name, function=function, recursive=recursive) )
Returns reference to namespace declaration that matches a defined criteria.
def get_schema_from_list(table_name, frum): columns = UniqueIndex(keys=("name",)) _get_schema_from_list(frum, ".", parent=".", nested_path=ROOT_PATH, columns=columns) return Schema(table_name=table_name, columns=list(columns))
SCAN THE LIST FOR COLUMN TYPES
def insert_uniques(self, table, columns, values): existing_rows = self.select(table, columns) unique = diff(existing_rows, values, y_only=True) keys = self.get_primary_key_vals(table) pk_col = self.get_primary_key(table) pk_index = columns.index(pk_col) to_insert, to_upda...
Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted
def get_history(self, i=None): ps = self.filter(context='history') if i is not None: return ps.to_list()[i] else: return ps
Get a history item by index. You can toggle whether history is recorded using * :meth:`enable_history` * :meth:`disable_history` :parameter int i: integer for indexing (can be positive or negative). If i is None or not provided, the entire list of histo...
def check(self, item_id): response = self._request("tasks/view/{id}".format(id=item_id)) if response.status_code == 404: return False try: content = json.loads(response.content.decode('utf-8')) status = content['task']["status"] if status == 'compl...
Check if an analysis is complete :type item_id: int :param item_id: task_id to check. :rtype: bool :return: Boolean indicating if a report is done or not.
def is_active(self): if self._queue.exhausted: return False return any(ch.is_active for ch in self._refs.values())
Returns True if listener has any active subscription.
def run_field_scan(ModelClass, model_kwargs, t_output_every, t_upto, field, vals, force_resume=True, parallel=False): model_kwarg_sets = [dict(model_kwargs, field=val) for val in vals] run_kwarg_scan(ModelClass, model_kwarg_sets, t_output_every, t_upto, force_resume, parall...
Run many models with a range of parameter sets. Parameters ---------- ModelClass: callable A class or factory function that returns a model object by calling `ModelClass(model_kwargs)` model_kwargs: dict See `ModelClass` explanation. t_output_every: float see :class:...
def prlsrvctl(sub_cmd, args=None, runas=None): if not salt.utils.path.which('prlsrvctl'): raise CommandExecutionError('prlsrvctl utility not available') cmd = ['prlsrvctl', sub_cmd] if args: cmd.extend(_normalize_args(args)) return __salt__['cmd.run'](cmd, runas=runas)
Execute a prlsrvctl command .. versionadded:: 2016.11.0 :param str sub_cmd: prlsrvctl subcommand to execute :param str args: The arguments supplied to ``prlsrvctl <sub_cmd>`` :param str runas: The user that the prlsrvctl command will be run as Example: .. code-block...
def _hz_to_semitones(self, hz): return np.log(hz / self._a440) / np.log(self._a)
Convert hertz into a number of semitones above or below some reference value, in this case, A440
def _get_national_number_groups_without_pattern(numobj): rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966) end_index = rfc3966_format.find(U_SEMICOLON) if end_index < 0: end_index = len(rfc3966_format) start_index = rfc3966_format.find(U_DASH) + 1 return rfc3966_format[start_...
Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.
def drop_it(title, filters, blacklist): title = title.lower() matched = False for f in filters: if re.match(f, title): matched = True if not matched: return True for b in blacklist: if re.match(b, title): return True return False
The found torrents should be in filters list and shouldn't be in blacklist.
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): try: args = parser.parse_args(to_argv(spec)) except SystemExit: raise TuneError("Error parsing args, see above message", spec) if "resources_per_trial" in spec: trial_kwargs["resources"] = json_to_resources( ...
Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. ...
def randomArray2(size, bound): if type(size) == type(1): size = (size,) temp = Numeric.array( ndim(*size), thunk=lambda: random.gauss(0, 1)) * (2.0 * bound) return temp - bound
Returns an array initialized to random values between -bound and bound distributed in a gaussian probability distribution more appropriate for a Tanh activation function.
def get_pipeline(self, *args, **kwargs): return getattr(missions, self.mission).pipelines.get(self.ID, *args, **kwargs)
Returns the `time` and `flux` arrays for the target obtained by a given pipeline. Options :py:obj:`args` and :py:obj:`kwargs` are passed directly to the :py:func:`pipelines.get` function of the mission.
def regex_match_list(line, patterns): m = None for ptn in patterns: m = ptn.match(line) if m is not None: break return m
Given a list of COMPILED regex patters, perform the "re.match" operation on the line for every pattern. Break from searching at the first match, returning the match object. In the case that no patterns match, the None type will be returned. @param line: (unicode string) to be searched in. ...
def template_file( task: Task, template: str, path: str, jinja_filters: FiltersDict = None, **kwargs: Any ) -> Result: jinja_filters = jinja_filters or {} or task.nornir.config.jinja2.filters text = jinja_helper.render_from_file( template=template, path=path, host=tas...
Renders contants of a file with jinja2. All the host data is available in the template Arguments: template: filename path: path to dir with templates jinja_filters: jinja filters to enable. Defaults to nornir.config.jinja2.filters **kwargs: additional data to pass to the template ...
def nvlist_to_dict(nvlist): result = {} for item in nvlist : result[item.name] = item.value.value() return result
Convert a CORBA namevalue list into a dictionary.
def match(self, fsys_view): evalue_dict = fsys_view[1] for key, value in six.viewitems(self.criteria): if key in evalue_dict: if evalue_dict[key] != value: return False else: return False return True
Compare potentially partial criteria against built filesystems entry dictionary
def updateSession(self, request): secure = request.isSecure() if not secure: cookieString = b"TWISTED_SESSION" else: cookieString = b"TWISTED_SECURE_SESSION" cookiename = b"_".join([cookieString] + request.sitepath) request.addCookie(cookiename, self.uid, ...
Update the cookie after session object was modified @param request: the request object which should get a new cookie
def build(self): assert not self.final, 'Trying to mutate a final graph.' for scc in sorted(nx.kosaraju_strongly_connected_components(self.graph), key=len, reverse=True): if len(scc) == 1: break self.shrink_to_node(NodeSet(scc)) s...
Finalise the graph, after adding all input files to it.
def libvlc_event_attach(p_event_manager, i_event_type, f_callback, user_data): f = _Cfunctions.get('libvlc_event_attach', None) or \ _Cfunction('libvlc_event_attach', ((1,), (1,), (1,), (1,),), None, ctypes.c_int, EventManager, ctypes.c_uint, Callback, ctypes.c_void_p) return f(p_eve...
Register for an event notification. @param p_event_manager: the event manager to which you want to attach to. Generally it is obtained by vlc_my_object_event_manager() where my_object is the object you want to listen to. @param i_event_type: the desired event to which we want to listen. @param f_callback: t...
def create(self, item, dry_run=None): logger.debug('Creating new item. Item: {item} Path: {data_file}'.format( item=item, data_file=self.data_file )) items = load_file(self.client, self.bucket_name, self.data_file) items = append_item(self.namespace, self.version,...
Creates a new item in file.
def clean(ctx): os.chdir(PROJECT_DIR) patterns = ['.cache', '.coverage', '.eggs', 'build', 'dist'] ctx.run('rm -vrf {0}'.format(' '.join(patterns))) ctx.run( )
clean generated project files
def _get_table_cells(table): sent_map = defaultdict(list) for sent in table.sentences: if sent.is_tabular(): sent_map[sent.cell].append(sent) return sent_map
Helper function with caching for table cells and the cells' sentences. This function significantly improves the speed of `get_row_ngrams` primarily by reducing the number of queries that are made (which were previously the bottleneck. Rather than taking a single mention, then its sentence, then its tab...
def get_state(self): battery = self.player.stats['battery']/100 if len(self.mode['items']) > 0: observation = [] for sensor in self.player.sensors: col = [] col.append(sensor.proximity_norm()) for item_type in self.mode['items']: ...
Create state from sensors and battery
def execute_proc(self, procname, args): self.logger(procname, args) with self.cursor() as cursor: cursor.callproc(procname, args) return cursor
Execute a stored procedure, returning a cursor. For internal use only.
def childgroup(self, field): grid = getattr(self, "grid", None) named_grid = getattr(self, "named_grid", None) if grid is not None: childgroup = self._childgroup(field.children, grid) elif named_grid is not None: childgroup = self._childgroup_by_name(field.childre...
Return a list of fields stored by row regarding the configured grid :param field: The original field this widget is attached to
def refreshThumbnails( self ): widget = self.thumbnailWidget() widget.setUpdatesEnabled(False) widget.blockSignals(True) widget.clear() widget.setIconSize(self.thumbnailSize()) factory = self.factory() if ( self.isGroupingActive() ): grouping =...
Refreshes the thumbnails view of the browser.
def triggered(self): if self.stop is not None and not self.stop_reached: return False if self.limit is not None and not self.limit_reached: return False return True
For a market order, True. For a stop order, True IFF stop_reached. For a limit order, True IFF limit_reached.
def on_batch_begin(self, last_input, last_target, **kwargs): "accumulate samples and batches" self.acc_samples += last_input.shape[0] self.acc_batches += 1
accumulate samples and batches
def format_ring_double_bond(mol): mol.require("Topology") mol.require("ScaleAndCenter") for r in sorted(mol.rings, key=len, reverse=True): vertices = [mol.atom(n).coords for n in r] try: if geometry.is_clockwise(vertices): cpath = iterator.consecutive(itertools.cy...
Set double bonds around the ring.
def add_task(self, task, func=None, **kwargs): if not self.__tasks: raise Exception("Tasks subparsers is disabled") if 'help' not in kwargs: if func.__doc__: kwargs['help'] = func.__doc__ task_parser = self.__tasks.add_parser(task, **kwargs) if sel...
Add a task parser
def cbpdn_setdict(): global mp_DSf mp_Df[:] = sl.rfftn(mp_D_Y, mp_cri.Nv, mp_cri.axisN) if mp_cri.Cd == 1: mp_DSf[:] = np.conj(mp_Df) * mp_Sf else: mp_DSf[:] = sl.inner(np.conj(mp_Df[np.newaxis, ...]), mp_Sf, axis=mp_cri.axisC+1)
Set the dictionary for the cbpdn stage. There are no parameters or return values because all inputs and outputs are from and to global variables.
def step_processing(self, warning=True): if not self.__is_processing: warning and LOGGER.warning( "!> {0} | Engine is not processing, 'step_processing' request has been ignored!".format( self.__class__.__name__)) return False LOGGER.debug("> St...
Steps the processing operation progress indicator. :param warning: Emit warning message. :type warning: int :return: Method success. :rtype: bool
def _grab_version(self): original_version = self.vcs.version logger.debug("Extracted version: %s", original_version) if original_version is None: logger.critical('No version found.') sys.exit(1) suggestion = utils.cleanup_version(original_version) new_vers...
Set the version to a non-development version.
def set_payload(self,val): self._options = self._options._replace(payload = val)
Set a payload for this object :param val: payload to be stored :type val: Anything that can be put in a list
def _check_kafka_disconnect(self): for node_id in self.consumer._client._conns: conn = self.consumer._client._conns[node_id] if conn.state == ConnectionStates.DISCONNECTED or \ conn.state == ConnectionStates.DISCONNECTING: self._spawn_kafka_connection_...
Checks the kafka connection is still valid
def generate_image(self, chars): background = random_color(238, 255) color = random_color(10, 200, random.randint(220, 255)) im = self.create_captcha_image(chars, color, background) self.create_noise_dots(im, color) self.create_noise_curve(im, color) im = im.filter(ImageF...
Generate the image of the given characters. :param chars: text to be generated.
def do_help(self, args: argparse.Namespace) -> None: if not args.command or args.verbose: self._help_menu(args.verbose) else: func = self.cmd_func(args.command) help_func = getattr(self, HELP_FUNC_PREFIX + args.command, None) if func and hasattr(func, 'arg...
List available commands or provide detailed help for a specific command
def _execute_hooks(self, element): if self.hooks and self.finalize_hooks: self.param.warning( "Supply either hooks or finalize_hooks not both, " "using hooks and ignoring finalize_hooks.") hooks = self.hooks or self.finalize_hooks for hook in hooks: ...
Executes finalize hooks
def H6(self): "Sum average." if not hasattr(self, '_H6'): self._H6 = ((self.rlevels2 + 2) * self.p_xplusy).sum(1) return self._H6
Sum average.
def _parse_boolean(value): if not value: return False try: value = value.lower() return value not in ("none", "0", "false", "no") except AttributeError: return True
Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value
def bulk_remove_entities(self, entities_and_kinds): criteria = [ Q(entity=entity, sub_entity_kind=entity_kind) for entity, entity_kind in entities_and_kinds ] criteria = reduce(lambda q1, q2: q1 | q2, criteria, Q()) EntityGroupMembership.objects.filter( ...
Remove many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, EntityKind) pairs. :param entities_and_kinds: A list of entity, entity-kind pairs to remove from the group. In the pairs, the entity-kind can be ``None``, to add a single e...
def parse_connection(self, global_params, region, connection): connection['id'] = connection.pop('connectionId') connection['name'] = connection.pop('connectionName') self.connections[connection['id']] = connection
Parse a single connection and fetch additional attributes :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param connection_url: URL of the AWS connection
def create_vlan(self, id_vlan): vlan_map = dict() vlan_map['vlan_id'] = id_vlan code, xml = self.submit({'vlan': vlan_map}, 'PUT', 'vlan/create/') return self.response(code, xml)
Set column 'ativada = 1'. :param id_vlan: VLAN identifier. :return: None
def AddUser(self, uid, username, active): user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, name=MOCK_IFACE + '.UserExists') self.AddObject(user_path,...
Convenience method to add a user. Return the object path of the new user.
def create_project_config_path( path, mode=0o777, parents=False, exist_ok=False ): project_path = Path(path).absolute().joinpath(RENKU_HOME) project_path.mkdir(mode=mode, parents=parents, exist_ok=exist_ok) return str(project_path)
Create new project configuration folder.
def current(cls, with_exception=True): if with_exception and len(cls.stack) == 0: raise NoContext() return cls.stack.top()
Returns the current database context.
def set_data(self, data): for name in self._fields: setattr(self, name, data.get(name)) return self
Fills form with data Args: data (dict): Data to assign form fields. Returns: Self. Form object.
def bind_name(self, name): if self.name: raise errors.Error('Already bound "{0}" with name "{1}" could not ' 'be rebound'.format(self, self.name)) self.name = name self.storage_name = ''.join(('_', self.name)) return self
Bind field to its name in model class.
def create_command( principal, permissions, endpoint_plus_path, notify_email, notify_message ): if not principal: raise click.UsageError("A security principal is required for this command") endpoint_id, path = endpoint_plus_path principal_type, principal_val = principal client = get_client()...
Executor for `globus endpoint permission create`
def on_epoch_end(self, **kwargs): "step the rest of the accumulated grads if not perfectly divisible" for p in (self.learn.model.parameters()): if p.requires_grad: p.grad.div_(self.acc_samples) if not self.drop_last: self.learn.opt.step() self.learn.opt.zero_grad()
step the rest of the accumulated grads if not perfectly divisible
def _get_expiration_date(cert): cert_obj = _read_cert(cert) if cert_obj is None: raise CommandExecutionError( 'Failed to read cert from {0}, see log for details'.format(cert) ) return datetime.strptime( salt.utils.stringutils.to_str(cert_obj.get_notAfter()), four_...
Returns a datetime.datetime object
def _append_expectation(self, expectation_config): expectation_type = expectation_config['expectation_type'] json.dumps(expectation_config) if 'column' in expectation_config['kwargs']: column = expectation_config['kwargs']['column'] self._expectations_config.expectations ...
Appends an expectation to `DataAsset._expectations_config` and drops existing expectations of the same type. If `expectation_config` is a column expectation, this drops existing expectations that are specific to \ that column and only if it is the same expectation type as `expectation_config`. Ot...
def check_species_object(species_name_or_object): if isinstance(species_name_or_object, Species): return species_name_or_object elif isinstance(species_name_or_object, str): return find_species_by_name(species_name_or_object) else: raise ValueError("Unexpected type for species: %s : ...
Helper for validating user supplied species names or objects.
def use_internal_state(self): old_state = random.getstate() random.setstate(self._random_state) yield self._random_state = random.getstate() random.setstate(old_state)
Use a specific RNG state.
def get_property(self, prop): prop = prop.split('.') root = self for p in prop: if p in root: root = root[p] else: return None return root
Access nested value using dot separated keys Args: prop (:obj:`str`): Property in the form of dot separated keys Returns: Property value if exists, else `None`
def create_paired_list(value): if isinstance(value, list): value = ",".join(value) array = re.split('\D+', value) if len(array) % 2 == 0: new_array = [list(array[i:i + 2]) for i in range(0, len(array), 2)] return new_array else: raise ValueError('The string should include...
Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: >>> create_paired_list('003,003,004,004') [['003','003'], ['004', '004']]
def rebuild_method(self, prepared_request, response): method = prepared_request.method if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' if response.status_code == codes.found and method != 'HEAD': method = 'GET' if response.status_co...
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
def valid_name(name): "Validate a cookie name string" if isinstance(name, bytes): name = name.decode('ascii') if not Definitions.COOKIE_NAME_RE.match(name): return False if name[0] == "$": return False return True
Validate a cookie name string
def answer(self): if isinstance(self.validator, list): return self.validator[0].choice() return self.validator.choice()
Return the answer for the question from the validator. This will ultimately only be called on the first validator if multiple validators have been added.
def csv(args): from xlrd import open_workbook p = OptionParser(csv.__doc__) p.set_sep(sep=',') opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) excelfile, = args sep = opts.sep csvfile = excelfile.rsplit(".", 1)[0] + ".csv" wb = open_workbook(ex...
%prog csv excelfile Convert EXCEL to csv file.
def get_parent_books(self, book_id): if self._catalog_session is not None: return self._catalog_session.get_parent_catalogs(catalog_id=book_id) return BookLookupSession( self._proxy, self._runtime).get_books_by_ids( list(self.get_parent_book_ids(book_i...
Gets the parent books of the given ``id``. arg: book_id (osid.id.Id): the ``Id`` of the ``Book`` to query return: (osid.commenting.BookList) - the parent books of the ``id`` raise: NotFound - a ``Book`` identified by ``Id is`` not found raise: NullAr...
def get_tag_list(resource_tag_dict): tag_list = [] if resource_tag_dict is None: return tag_list for tag_key, tag_value in resource_tag_dict.items(): tag = {_KEY: tag_key, _VALUE: tag_value if tag_value else ""} tag_list.append(tag) return tag_list
Transforms the SAM defined Tags into the form CloudFormation is expecting. SAM Example: ``` ... Tags: TagKey: TagValue ``` CloudFormation equivalent: - Key: TagKey Value: TagValue ``` :param resource_tag_dict: Customer defined dicti...
def summary(self, raw): taxonomies = [] level = "info" namespace = "Patrowl" if self.service == 'getreport': if 'risk_level' in raw and raw['risk_level']: risk_level = raw['risk_level'] if risk_level['grade'] in ["A", "B"]: ...
Parse, format and return scan summary.
def _any_would_run(func, filenames, *args): if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None): return True for filename in filenames: stamp_args, stamp_kwargs = _run_lint_on_file_stamped_args(filename, *args, ...
True if a linter function would be called on any of filenames.
def to_element(self, root_name=None): if not root_name: root_name = self.nodename elem = ElementTreeBuilder.Element(root_name) for attrname in self.serializable_attributes(): try: value = self.__dict__[attrname] except KeyError: ...
Serialize this `Resource` instance to an XML element.
def clean_tenant_url(url_string): if hasattr(settings, 'PUBLIC_SCHEMA_URLCONF'): if (settings.PUBLIC_SCHEMA_URLCONF and url_string.startswith(settings.PUBLIC_SCHEMA_URLCONF)): url_string = url_string[len(settings.PUBLIC_SCHEMA_URLCONF):] return url_string
Removes the TENANT_TOKEN from a particular string
def update_object(objref, data, **api_opts): if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to update object: {0}'.format(objref)} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data)
Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={}
def _get_documents(self): documents = self.tree.execute("$.documents") for doc in documents: sentences = {s['@id']: s['text'] for s in doc.get('sentences', [])} self.document_dict[doc['@id']] = {'sentences': sentences, 'location': doc...
Populate sentences attribute with a dict keyed by document id.
def get_user(self, id=None, name=None, email=None): log.info("Picking user: %s (%s) (%s)" % (name, email, id)) from qubell.api.private.user import User if email: user = User.get(self._router, organization=self, email=email) else: user = self.users[id or name] ...
Get user object by email or id.
def add_parser(self, name, func): self.__parser_map__[name] = _func2method(func, method_name=name) return None
Register a new parser method with the name ``name``. ``func`` must receive the input value for an environment variable.
def generate_heightmap(self, buffer=False, as_array=False): non_solids = [0, 8, 9, 10, 11, 38, 37, 32, 31] if buffer: return BytesIO(pack(">i", 256)+self.generate_heightmap()) else: bytes = [] for z in range(16): for x in range(16): ...
Return a heightmap, representing the highest solid blocks in this chunk.
def _format_csv(content, delimiter): reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter)) rows = [row for row in reader] max_widths = [max(map(len, column)) for column in zip(*rows)] lines = [ " ".join( "{entry:{width}}".format(entry=entry, width=width + 2) ...
Format delimited text to have same column width. Args: content (str): The content of a metric. delimiter (str): Value separator Returns: str: Formatted content. Example: >>> content = ( "value_mse,deviation_mse,data_set\n" "0.421601,0.173461,train\...
def get_energy_buckingham(structure, gulp_cmd='gulp', keywords=('optimise', 'conp', 'qok'), valence_dict=None): gio = GulpIO() gc = GulpCaller(gulp_cmd) gin = gio.buckingham_input( structure, keywords, valence_dict=valence_dict ) gout = gc....
Compute the energy of a structure using Buckingham potential. Args: structure: pymatgen.core.structure.Structure gulp_cmd: GULP command if not in standard place keywords: GULP first line keywords valence_dict: {El: valence}. Needed if the structure is not charge neutral.
def get_sentence(self, offset: int) -> BioCSentence or None: for sentence in self.sentences: if sentence.offset == offset: return sentence return None
Gets sentence with specified offset Args: offset: sentence offset Return: the sentence with specified offset
def read(self, n): while len(self.buf) < n: chunk = self.f.recv(4096) if not chunk: raise EndOfStreamError() self.buf += chunk res, self.buf = self.buf[:n], self.buf[n:] return res
Consume `n` characters from the stream.
def maximum(lhs, rhs): return _ufunc_helper( lhs, rhs, op.broadcast_maximum, lambda x, y: x if x > y else y, _internal._maximum_scalar, None)
Returns element-wise maximum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Parameters ...
def docs(ctx, output='html', rebuild=False, show=True, verbose=True): sphinx_build = ctx.run( 'sphinx-build -b {output} {all} {verbose} docs docs/_build'.format( output=output, all='-a -E' if rebuild else '', verbose='-v' if verbose else '')) if not sphinx_build.ok: ...
Build the docs and show them in default web browser.