positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def suggest_path(root_dir): """List all files and subdirectories in a directory. If the directory is not specified, suggest root directory, user directory, current and parent directory. :param root_dir: string: directory to list :return: list """ if not root_dir: return [os.path.absp...
List all files and subdirectories in a directory. If the directory is not specified, suggest root directory, user directory, current and parent directory. :param root_dir: string: directory to list :return: list
def set_lr(self, lr): """ Set a learning rate for the optimizer """ if isinstance(lr, list): for group_lr, param_group in zip(lr, self.optimizer.param_groups): param_group['lr'] = group_lr else: for param_group in self.optimizer.param_groups: ...
Set a learning rate for the optimizer
def extract_full_summary_from_signature(operation): """ Extract the summary from the docstring of the command. """ lines = inspect.getdoc(operation) regex = r'\s*(:param)\s+(.+?)\s*:(.*)' summary = '' if lines: match = re.search(regex, lines) summary = lines[:match.regs[0][0]] if mat...
Extract the summary from the docstring of the command.
def list_policies(region=None, key=None, keyid=None, profile=None): ''' List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: policies = [] for ret in _...
List policies. CLI Example: .. code-block:: bash salt myminion boto_iam.list_policies
def _render_profile(path, caller, runner): ''' Render profile as Jinja2. :param path: :return: ''' env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(path)), trim_blocks=False) return env.get_template(os.path.basename(path)).render(salt=caller, runners=runner).strip()
Render profile as Jinja2. :param path: :return:
def map_exp_ids(self, exp): """Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight) """ names = self.exp_feature_names if self.discretized_feature_names is not None: ...
Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight)
def add(self, resource, replace=False): """Add just a single resource.""" uri = resource.uri if (uri in self and not replace): raise ResourceSetDupeError( "Attempt to add resource already in this set") self[uri] = resource
Add just a single resource.
def popitem_move(self, from_dict, to_dict, priority_min='-inf', priority_max='+inf'): '''Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is ...
Select an item and move it to another dictionary. The item comes from `from_dict`, and has the lowest score at least `priority_min` and at most `priority_max`. If some item is found, remove it from `from_dict`, add it to `to_dict`, and return it. This runs as a single atomic o...
def _record_extension(self, bank_id, key, value): """ To structure a record extension property bean """ record_bean = { 'value': value, 'displayName': self._text_bean(key), 'description': self._text_bean(key), 'displayLabel': self._text_bea...
To structure a record extension property bean
def camel_to_title(name): """Takes a camelCaseFieldName and returns an Title Case Field Name Args: name (str): E.g. camelCaseFieldName Returns: str: Title Case converted name. E.g. Camel Case Field Name """ split = re.findall(r"[A-Z]?[a-z0-9]+|[A-Z]+(?=[A-Z]|$)", name) ret = " ...
Takes a camelCaseFieldName and returns an Title Case Field Name Args: name (str): E.g. camelCaseFieldName Returns: str: Title Case converted name. E.g. Camel Case Field Name
def _parse_remote_model(self, context): """ parse the remote resource model and adds its full name :type context: models.QualiDriverModels.ResourceRemoteCommandContext """ if not context.remote_endpoints: raise Exception('no remote resources found in context: {0}', j...
parse the remote resource model and adds its full name :type context: models.QualiDriverModels.ResourceRemoteCommandContext
def delete(self, user_name: str): """ Deletes the resource with the given name. """ user = self._get_or_abort(user_name) session.delete(user) session.commit() return '', 204
Deletes the resource with the given name.
def _send_content(self, content, connection): """ Send a content array from the connection """ if connection: if connection.async: callback = connection.callbacks['remote'] if callback: callback(self, self.parent_object, content) ...
Send a content array from the connection
def task_del(self, t): """ Remove a task in this legion. If the task has active processes, an attempt is made to stop them before the task is deleted. """ name = t._name if name in self._tasknames: del self._tasknames[name] self._tasks.discard(t) ...
Remove a task in this legion. If the task has active processes, an attempt is made to stop them before the task is deleted.
def all_releases(self,response_type=None,params=None): """ Function to request all releases of economic data. `<https://research.stlouisfed.org/docs/api/fred/releases.html>`_ :arg str response_type: File extension of response. Options are 'xml', 'json', 'dict...
Function to request all releases of economic data. `<https://research.stlouisfed.org/docs/api/fred/releases.html>`_ :arg str response_type: File extension of response. Options are 'xml', 'json', 'dict','df','numpy','csv','tab,'pipe'. Required. :arg str realtime_start...
def _get_observation(self): """ Returns an OrderedDict containing observations [(name_string, np.array), ...]. Important keys: robot-state: contains robot-centric information. """ di = super()._get_observation() # proprioceptive features di["j...
Returns an OrderedDict containing observations [(name_string, np.array), ...]. Important keys: robot-state: contains robot-centric information.
def add_logger(name, level=None, format=None): ''' Set up a stdout logger. Args: name (str): name of the logger level: defaults to logging.INFO format (str): format string for logging output. defaults to ``%(filename)-11s %(lineno)-3d: %(message)s``. Retur...
Set up a stdout logger. Args: name (str): name of the logger level: defaults to logging.INFO format (str): format string for logging output. defaults to ``%(filename)-11s %(lineno)-3d: %(message)s``. Returns: The logger object.
def get_uid(user=None): ''' Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned. ''' if not HAS_PWD: return None elif user i...
Get the uid for a given user name. If no user given, the current euid will be returned. If the user does not exist, None will be returned. On systems which do not support pwd or os.geteuid, None will be returned.
def _get_key_dir(): ''' return the location of the GPG key directory ''' gpg_keydir = None if 'config.get' in __salt__: gpg_keydir = __salt__['config.get']('gpg_keydir') if not gpg_keydir: gpg_keydir = __opts__.get( 'gpg_keydir', os.path.join( ...
return the location of the GPG key directory
def number_to_string(n, alphabet): """ Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '1011110001100001010...
Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '101111000110000101001110' >>> number_to_string(12345678, ...
def context_id(self): """Return this Async's Context Id if it exists.""" if not self._context_id: self._context_id = self._get_context_id() self.update_options(context_id=self._context_id) return self._context_id
Return this Async's Context Id if it exists.
def list_users(): """ List all users on the database """ echo_header("List of users") for user in current_app.appbuilder.sm.get_all_users(): click.echo( "username:{0} | email:{1} | role:{2}".format( user.username, user.email, user.roles ) )
List all users on the database
def fence_fetch_point_send(self, target_system, target_component, idx, force_mavlink1=False): ''' Request a current fence point from MAV target_system : System ID (uint8_t) target_component : Component ID (uint8_t) idx...
Request a current fence point from MAV target_system : System ID (uint8_t) target_component : Component ID (uint8_t) idx : point index (first point is 1, 0 is for return point) (uint8_t)
def _set_association(self, v, load=False): """ Setter method for association, mapped from YANG variable /interface/port_channel/switchport/private_vlan/association (container) If this variable is read-only (config: false) in the source YANG file, then _set_association is considered as a private meth...
Setter method for association, mapped from YANG variable /interface/port_channel/switchport/private_vlan/association (container) If this variable is read-only (config: false) in the source YANG file, then _set_association is considered as a private method. Backends looking to populate this variable should ...
def _get_pathcost_func( name: str ) -> Callable[[int, int, int, int, Any], float]: """Return a properly cast PathCostArray callback.""" return ffi.cast( # type: ignore "TCOD_path_func_t", ffi.addressof(lib, name) )
Return a properly cast PathCostArray callback.
def from_conll(this_class, text): """Construct a Token from a line in CoNLL-X format.""" fields = text.split('\t') fields[0] = int(fields[0]) # index fields[6] = int(fields[6]) # head index if fields[5] != '_': # feats fields[5] = tuple(fields[5].split('|')) f...
Construct a Token from a line in CoNLL-X format.
def dissolved(self, concs): """ Return dissolved concentrations """ new_concs = concs.copy() for r in self.rxns: if r.has_precipitates(self.substances): net_stoich = np.asarray(r.net_stoich(self.substances)) s_net, s_stoich, s_idx = r.precipitate_stoic...
Return dissolved concentrations
def print_results(results): """Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances. """ if not isinstance(results, list): results = [results] for r in results: try: ...
Print `results` (the results of validation) to stdout. Args: results: A list of FileValidationResults or ObjectValidationResults instances.
def find_mappable(*axes): """Find the most recently added mappable layer in the given axes Parameters ---------- *axes : `~matplotlib.axes.Axes` one or more axes to search for a mappable """ for ax in axes: for aset in ('collections', 'images'): try: ...
Find the most recently added mappable layer in the given axes Parameters ---------- *axes : `~matplotlib.axes.Axes` one or more axes to search for a mappable
def getWeight(grph, nd1, nd2, weightString = "weight", returnType = int): """ A way of getting the weight of an edge with or without weight as a parameter returns a the value of the weight parameter converted to returnType if it is given or 1 (also converted) if not """ if not weightString: ...
A way of getting the weight of an edge with or without weight as a parameter returns a the value of the weight parameter converted to returnType if it is given or 1 (also converted) if not
def read_dict(file_name, clear_none=False, encoding='utf-8'): """ 读取字典文件 :param encoding: :param clear_none: :param file_name: :return: """ with open(file_name, 'rb') as f: data = f.read() if encoding is not None: data = data.decode(encoding) line_list = data.sp...
读取字典文件 :param encoding: :param clear_none: :param file_name: :return:
def Wait(self): """Wait until the next action is needed.""" time.sleep(self.sleep_time - int(self.sleep_time)) # Split a long sleep interval into 1 second intervals so we can heartbeat. for _ in range(int(self.sleep_time)): time.sleep(1) # Back off slowly at first and fast if no answer. ...
Wait until the next action is needed.
def maybe_start_recording(tokens, index): """Return a new _MultilineStringRecorder when its time to record.""" if _is_begin_quoted_type(tokens[index].type): string_type = _get_string_type_from_token(tokens[index].type) return _MultilineStringRecorder(index, string_type) ...
Return a new _MultilineStringRecorder when its time to record.
def get_member_calendar(self, max_results=0): ''' a method to retrieve the upcoming events for all groups member belongs to :param max_results: [optional] integer with number of events to include :return: dictionary with list of event details inside [json] key event_details = s...
a method to retrieve the upcoming events for all groups member belongs to :param max_results: [optional] integer with number of events to include :return: dictionary with list of event details inside [json] key event_details = self._reconstruct_event({})
def create(cls, name, ipv4_network=None, ipv6_network=None, comment=None): """ Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :pa...
Create the network element :param str name: Name of element :param str ipv4_network: network cidr (optional if ipv6) :param str ipv6_network: network cidr (optional if ipv4) :param str comment: comment (optional) :raises CreateElementFailed: element creation failed with reason ...
def plural(random=random, *args, **kwargs): """ Return a plural noun. >>> mock_random.seed(0) >>> plural(random=mock_random) 'onions' >>> plural(random=mock_random, capitalize=True) 'Chimps' >>> plural(random=mock_random, slugify=True) 'blisters' """ return inflectify.plural...
Return a plural noun. >>> mock_random.seed(0) >>> plural(random=mock_random) 'onions' >>> plural(random=mock_random, capitalize=True) 'Chimps' >>> plural(random=mock_random, slugify=True) 'blisters'
def localize_file(path_or_buffer): '''Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage tem...
Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage temporary_file_flag (bool): temporary file fl...
def get_vcs_root(): """Returns the vcs module and the root of the repo. Returns: A tuple containing the vcs module to use (git, hg) and the root of the repository. If no repository exisits then (None, None) is returned. """ for vcs in (git, hg): repo_root = vcs.repository_root() ...
Returns the vcs module and the root of the repo. Returns: A tuple containing the vcs module to use (git, hg) and the root of the repository. If no repository exisits then (None, None) is returned.
def cross_entropy_calc(TOP, P, POP): """ Calculate cross entropy. :param TOP: test outcome positive :type TOP : dict :param P: condition positive :type P : dict :param POP: population :type POP : dict :return: cross entropy as float """ try: result = 0 for i ...
Calculate cross entropy. :param TOP: test outcome positive :type TOP : dict :param P: condition positive :type P : dict :param POP: population :type POP : dict :return: cross entropy as float
def get_requested_aosp_permissions(self): """ Returns requested permissions declared within AOSP project. This includes several other permissions as well, which are in the platform apps. :rtype: list of str """ aosp_permissions = [] all_permissions = self.get_pe...
Returns requested permissions declared within AOSP project. This includes several other permissions as well, which are in the platform apps. :rtype: list of str
def visit_break(self, node, parent): """visit a Break node by returning a fresh instance of it""" return nodes.Break( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
visit a Break node by returning a fresh instance of it
def initialiseDevice(self): """ performs initialisation of the device :param batchSize: the no of samples that each provideData call should yield :return: """ logger.debug("Initialising device") self.getInterruptStatus() self.setAccelerometerSensitivity(se...
performs initialisation of the device :param batchSize: the no of samples that each provideData call should yield :return:
def on_draw(self, e): """Draw all visuals.""" gloo.clear() for visual in self.visuals: logger.log(5, "Draw visual `%s`.", visual) visual.on_draw()
Draw all visuals.
def notch_fir(timeseries, f1, f2, order, beta=5.0): """ notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the number of samples in the filter le...
notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the number of samples in the filter length. For a few Hz bandwidth, a length corresponding to ...
def version(): """ Version Imports and displays current boiler version. :return: """ echo(green('\nshift-boiler:')) echo(green('-' * 40)) echo(yellow('Version: ') + '{}'.format(boiler_version)) echo(yellow('GitHub: ') + 'https://github.com/projectshift/shift-boiler') echo(yellow(...
Version Imports and displays current boiler version. :return:
def add_leverage(self): """ Adds leverage term to the model Returns ---------- None (changes instance attributes) """ if self.leverage is True: pass else: self.leverage = True self.z_no += 1 self.laten...
Adds leverage term to the model Returns ---------- None (changes instance attributes)
def service_command(name, command): """Run an init.d/upstart command.""" service_command_template = getattr(env, 'ARGYLE_SERVICE_COMMAND_TEMPLATE', u'/etc/init.d/%(name)s %(command)s') sudo(service_command_template % {'name': name, ...
Run an init.d/upstart command.
def build_tree_fast(self, new_path=None, seq_type='nucl' or 'prot'): """Make a tree with FastTree. Names will be truncated however.""" # Check output # if new_path is None: new_path = self.prefix_path + '.tree' # Command # command_args = [] if seq_type == 'nucl': command_...
Make a tree with FastTree. Names will be truncated however.
def clone(url, directory, single_branch=None): print_info('Cloning {0} to {1} {2}'.format( url, directory, '[full clone]' if single_branch is None else '[{0}]'.format(single_branch) )) # type: (str, str, str) -> Repo """ Clone a repository, optionally using shallow clone ...
Clone a repository, optionally using shallow clone :rtype: Repo :param url: URL of the repository :param directory: Directory to clone to :param single_branch: branch to clone if shallow clone is preferred :return: GitPython repository object of the newly cloned repository
def list_replica_set_for_all_namespaces(self, **kwargs): # noqa: E501 """list_replica_set_for_all_namespaces # noqa: E501 list or watch objects of kind ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass a...
list_replica_set_for_all_namespaces # noqa: E501 list or watch objects of kind ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_replica_set_for_all_namespaces(async_r...
def selection_pos(self): """Return start and end positions of the visual selection respectively.""" buff = self._vim.current.buffer beg = buff.mark('<') end = buff.mark('>') return beg, end
Return start and end positions of the visual selection respectively.
def format_h4(s, format="text", indents=0): """ Encloses string in format text Args, Returns: see format_h1() """ _CHAR = "^" if format.startswith("text"): return format_underline(s, _CHAR, indents) elif format.startswith("markdown"): return ["#### {}".format(s)]...
Encloses string in format text Args, Returns: see format_h1()
def stsci(hdulist): """For STScI GEIS files, need to do extra steps.""" instrument = hdulist[0].header.get('INSTRUME', '') # Update extension header keywords if instrument in ("WFPC2", "FOC"): rootname = hdulist[0].header.get('ROOTNAME', '') filetype = hdulist[0].header.get('FILETYPE',...
For STScI GEIS files, need to do extra steps.
def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: self.switch_to_plugin() editorstack.set_or_clear_breakpoint()
Set/Clear breakpoint
def get_lateration_parameters(all_points, indices, index, edm, W=None): """ Get parameters relevant for lateration from full all_points, edm and W. """ if W is None: W = np.ones(edm.shape) # delete points that are not considered anchors anchors = np.delete(all_points, indices, axis=0) r...
Get parameters relevant for lateration from full all_points, edm and W.
def _addr_to_stack_offset(self, addr): """ Convert an address to a stack offset. :param claripy.ast.Base addr: The address to convert from. :return: A stack offset if the addr comes from the stack pointer, or None if the address ...
Convert an address to a stack offset. :param claripy.ast.Base addr: The address to convert from. :return: A stack offset if the addr comes from the stack pointer, or None if the address does not come from the stack pointer.
def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """Generated an opimitized fused multiply adder. A generalized FMA unit that multiplies each pair of numbers in mult_pairs, then adds the resulting numbers and and th...
Generated an opimitized fused multiply adder. A generalized FMA unit that multiplies each pair of numbers in mult_pairs, then adds the resulting numbers and and the values of the add wires all together to form an answer. This is faster than separate adders and multipliers because you avoid unnecessary ...
def Storage_trackCacheStorageForOrigin(self, origin): """ Function path: Storage.trackCacheStorageForOrigin Domain: Storage Method name: trackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Registers origin...
Function path: Storage.trackCacheStorageForOrigin Domain: Storage Method name: trackCacheStorageForOrigin Parameters: Required arguments: 'origin' (type: string) -> Security origin. No return value. Description: Registers origin to be notified when an update occurs to its cache storage lis...
def compose(*fs): """ Compose functions together in order: compose(f, g, h) = lambda n: f(g(h(n))) """ # Pull the iterator out into a tuple so we can call `composed` # more than once. rs = tuple(reversed(fs)) def composed(n): return reduce(lambda a, b: b(a), rs, n) # Attem...
Compose functions together in order: compose(f, g, h) = lambda n: f(g(h(n)))
def _create_axes(hist: HistogramBase, vega: dict, kwargs: dict): """Create axes in the figure.""" xlabel = kwargs.pop("xlabel", hist.axis_names[0]) ylabel = kwargs.pop("ylabel", hist.axis_names[1] if len(hist.axis_names) >= 2 else None) vega["axes"] = [ {"orient": "bottom", "scale": "xscale", "t...
Create axes in the figure.
def get_expire_delta(self, reference=None): """ Return the number of seconds until this token expires. """ if reference is None: reference = now() expiration = self.expires if timezone: if timezone.is_aware(reference) and timezone.is_naive(expirat...
Return the number of seconds until this token expires.
def extend(self, iterable): """Extend the right side of this GeventDeque by appending elements from the iterable argument. """ self._deque.extend(iterable) if len(self._deque) > 0: self.notEmpty.set()
Extend the right side of this GeventDeque by appending elements from the iterable argument.
def _fill_vao(self): """Put array location in VAO for shader in same order as arrays given to Mesh.""" with self.vao: self.vbos = [] for loc, verts in enumerate(self.arrays): vbo = VBO(verts) self.vbos.append(vbo) self.vao.assign_ve...
Put array location in VAO for shader in same order as arrays given to Mesh.
def get_missing(self, verify_file): """ Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :retur...
Use a verification configuration which has a list of required options and their respective types. This information is used to identify missing and incompatible options in the loaded configuration. :param str verify_file: The file to load for verification data. :return: A dictionary of missing and incompatible ...
def expected_peer_units(): """Get a generator for units we expect to join peer relation based on goal-state. The local unit is excluded from the result to make it easy to gauge completion of all peers joining the relation with existing hook tools. Example usage: log('peer {} of {} joined peer ...
Get a generator for units we expect to join peer relation based on goal-state. The local unit is excluded from the result to make it easy to gauge completion of all peers joining the relation with existing hook tools. Example usage: log('peer {} of {} joined peer relation' .format(len(rela...
def _credential_allows_container_list(self): # type: (StorageAccount) -> bool """Check if container list is allowed :param StorageAccount self: this :rtype: bool :return: if container list is allowed """ if self.is_sas: sasparts = self.key.split('&') ...
Check if container list is allowed :param StorageAccount self: this :rtype: bool :return: if container list is allowed
def postponed_from_when(self): """ A string describing when the event was postponed from (in the local time zone). """ what = self.what if what: return _("{what} from {when}").format(what=what, when=self.cancellationpa...
A string describing when the event was postponed from (in the local time zone).
def _parse_ppt_segment(self, fptr): """Parse the PPT segment. The packet headers are not parsed, i.e. they remain "uninterpreted" raw data beffers. Parameters ---------- fptr : file object The file to parse. Returns ------- PPTSegmen...
Parse the PPT segment. The packet headers are not parsed, i.e. they remain "uninterpreted" raw data beffers. Parameters ---------- fptr : file object The file to parse. Returns ------- PPTSegment The current PPT segment.
def process_args(args): """Processes passed arguments.""" passed_args = args if isinstance(args, argparse.Namespace): passed_args = vars(passed_args) elif hasattr(args, "to_dict"): passed_args = passed_args.to_dict() return Box(passed_args, frozen_box=True, default_box=True)
Processes passed arguments.
def populate_observables(self, time, kinds, datasets, ignore_effects=False): """ TODO: add documentation ignore_effects: whether to ignore reflection and features (useful for computing luminosities) """ if self.irrad_method is not 'none' and not ignore_effects: # T...
TODO: add documentation ignore_effects: whether to ignore reflection and features (useful for computing luminosities)
def play_song(self, song, tempo=120, delay=0.05): """ Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and...
Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``). For an exhaustive lis...
def preprocess_uci_adult(data_name): """Some tricks of feature engineering are adapted from tensorflow's wide and deep tutorial. """ csv_columns = [ "age", "workclass", "fnlwgt", "education", "education_num", "marital_status", "occupation", "relationship", "race", "gender", "capi...
Some tricks of feature engineering are adapted from tensorflow's wide and deep tutorial.
def published(self, for_user=None): """ For non-staff users, return items with a published status and whose publish and expiry dates fall before and after the current date when specified. """ from yacms.core.models import CONTENT_STATUS_PUBLISHED if for_user is no...
For non-staff users, return items with a published status and whose publish and expiry dates fall before and after the current date when specified.
def activateAaPdpContextAccept(ProtocolConfigurationOptions_presence=0, GprsTimer_presence=0): """ACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.11""" a = TpPd(pd=0x8) b = MessageType(mesType=0x51) # 01010001 c = LlcServiceAccessPointIdentifier() d = QualityOfService() ...
ACTIVATE AA PDP CONTEXT ACCEPT Section 9.5.11
def get_yeast_sequence(chromosome, start, end, reverse_complement=False): '''Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_co...
Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_complement: Get the reverse complement. :type revervse_complement: bool :re...
def _get_vrfs(self): """Get the current VRFs configured in the device. :return: A list of vrf names as string """ vrfs = [] ios_cfg = self._get_running_config() parse = HTParser(ios_cfg) vrfs_raw = parse.find_lines("^vrf definition") for line in vrfs_raw:...
Get the current VRFs configured in the device. :return: A list of vrf names as string
def close_session(self, commit=True): """Commit and close the DB session associated with this task (no error is raised if None is open) Args: commit (bool): commit session before closing (default=True) """ if self._session is not None: if commit: ...
Commit and close the DB session associated with this task (no error is raised if None is open) Args: commit (bool): commit session before closing (default=True)
def _run_prospector(filename, stamp_file_name, disabled_linters, show_lint_files): """Run prospector.""" linter_tools = [ "pep257", "pep8", "pyflakes" ] if can_run_pylint(): linter_tools.append("pylint") # ...
Run prospector.
def start(context, mip_config, email, priority, dryrun, command, start_with, family): """Start a new analysis.""" mip_cli = MipCli(context.obj['script']) mip_config = mip_config or context.obj['mip_config'] email = email or environ_email() kwargs = dict(config=mip_config, family=family, priority=pri...
Start a new analysis.
def n_orifices_per_row_max(self): """A bound on the number of orifices allowed in each row. The distance between consecutive orifices must be enough to retain structural integrity of the pipe. """ c = math.pi * pipe.ID_SDR(self.nom_diam_pipe, self.sdr) b = self.orifice_di...
A bound on the number of orifices allowed in each row. The distance between consecutive orifices must be enough to retain structural integrity of the pipe.
def parse_cli_configuration(arguments: List[str]) -> CliConfiguration: """ Parses the configuration passed in via command line arguments. :param arguments: CLI arguments :return: the configuration """ try: parsed_arguments = {x.replace("_", "-"): y for x, y in vars(_argument_parser.parse...
Parses the configuration passed in via command line arguments. :param arguments: CLI arguments :return: the configuration
def sc_pan(self, viewer, event, msg=True): """Interactively pan the image by scrolling motion. """ if not self.canpan: return True # User has "Pan Reverse" preference set? rev = self.settings.get('pan_reverse', False) direction = event.direction if r...
Interactively pan the image by scrolling motion.
def session(self): """A context manager for this client's session. This function closes the current session when this client goes out of scope. """ self._session = requests.session() yield self._session.close() self._session = None
A context manager for this client's session. This function closes the current session when this client goes out of scope.
def _run( self, circuit: circuits.Circuit, param_resolver: study.ParamResolver, repetitions: int, ) -> Dict[str, List[np.ndarray]]: """See definition in `cirq.SimulatesSamples`.""" circuit = protocols.resolve_parameters(circuit, param_resolver) _verify_xmon_c...
See definition in `cirq.SimulatesSamples`.
def modify_image_attribute(self, image_id, attribute='launchPermission', operation='add', user_ids=None, groups=None, product_codes=None): """ Changes an attribute of an image. :type image_id: string :param image_id: The imag...
Changes an attribute of an image. :type image_id: string :param image_id: The image id you wish to change :type attribute: string :param attribute: The attribute you wish to change :type operation: string :param operation: Either add or remove (this is required for cha...
def extra_keywords_to_widgets(extra_keyword_definition): """Create widgets for extra keyword. :param extra_keyword_definition: An extra keyword definition. :type extra_keyword_definition: dict :return: QCheckBox and The input widget :rtype: (QCheckBox, QWidget) """ # Check box check_bo...
Create widgets for extra keyword. :param extra_keyword_definition: An extra keyword definition. :type extra_keyword_definition: dict :return: QCheckBox and The input widget :rtype: (QCheckBox, QWidget)
def is_cache(cache): """Returns `True` if ``cache`` is a readable cache file or object Parameters ---------- cache : `str`, `file`, `list` Object to detect as cache Returns ------- iscache : `bool` `True` if the input object is a cache, or a file in LAL cache format, ...
Returns `True` if ``cache`` is a readable cache file or object Parameters ---------- cache : `str`, `file`, `list` Object to detect as cache Returns ------- iscache : `bool` `True` if the input object is a cache, or a file in LAL cache format, otherwise `False`
def distort(value): """ Distorts a string by randomly replacing characters in it. :param value: a string to distort. :return: a distored string. """ value = value.lower() if (RandomBoolean.chance(1, 5)): value = value[0:1].upper() + value[1:] ...
Distorts a string by randomly replacing characters in it. :param value: a string to distort. :return: a distored string.
def _strip_stray_atoms(self): """Remove stray atoms and surface pieces. """ components = self.bond_graph.connected_components() major_component = max(components, key=len) for atom in list(self.particles()): if atom not in major_component: self.remove(atom)
Remove stray atoms and surface pieces.
def init_db(self, txn=None): """Connect to database and create tables. Parameters ---------- txn : sa.engine.Connection, optional The transaction to execute in. If this is not provided, a new transaction will be started with the engine provided. Returns ...
Connect to database and create tables. Parameters ---------- txn : sa.engine.Connection, optional The transaction to execute in. If this is not provided, a new transaction will be started with the engine provided. Returns ------- metadata : sa.Me...
async def respond_rpc(self, msg, _context): """Respond to an RPC previously sent to a service.""" rpc_id = msg.get('response_uuid') result = msg.get('result') payload = msg.get('response') self.service_manager.send_rpc_response(rpc_id, result, payload)
Respond to an RPC previously sent to a service.
def put_buffer(filename, content, conn=None): """ helper function for put :param filename: <str> :param content: <bytes> :param conn: <rethinkdb.DefaultConnection> :return: <dict> """ obj_dict = {PRIMARY_FIELD: filename, CONTENT_FIELD: content, TIMESTAMP_F...
helper function for put :param filename: <str> :param content: <bytes> :param conn: <rethinkdb.DefaultConnection> :return: <dict>
def get_valid_format_order(cls, format_target, format_order=None): """ Checks to see if the target format string follows the proper style """ format_order = format_order or cls.parse_format_order(format_target) cls.validate_no_token_duplicates(format_order) format_target = cls.re...
Checks to see if the target format string follows the proper style
def distance_corr(x, y, tail='upper', n_boot=1000, seed=None): """Distance correlation between two arrays. Statistical significance (p-value) is evaluated with a permutation test. Parameters ---------- x, y : np.ndarray 1D or 2D input arrays, shape (n_samples, n_features). x and y ...
Distance correlation between two arrays. Statistical significance (p-value) is evaluated with a permutation test. Parameters ---------- x, y : np.ndarray 1D or 2D input arrays, shape (n_samples, n_features). x and y must have the same number of samples and must not contain miss...
def checkGlyphIsEmpty(glyph, allowWhiteSpace=True): """ This will establish if the glyph is completely empty by drawing the glyph with an EmptyPen. Additionally, the unicode of the glyph is checked against a list of known unicode whitespace characters. This makes it possible to filter out gl...
This will establish if the glyph is completely empty by drawing the glyph with an EmptyPen. Additionally, the unicode of the glyph is checked against a list of known unicode whitespace characters. This makes it possible to filter out glyphs that have a valid reason to be empty and those that can...
def get_smokedetector_by_name(self, name): """Retrieves a smokedetector object by its name :param name: The name of the smokedetector to return :return: A smokedetector object """ return next((smokedetector for smokedetector in self.smokedetectors if smokede...
Retrieves a smokedetector object by its name :param name: The name of the smokedetector to return :return: A smokedetector object
def create_header(self): """ return header dict """ try: self.check_valid() _header_list = [] for k,v in self.inputs.items(): if v is None: return {self.__class__.__name__.replace('_','-'):None} elif k == 'value': _header_list.insert(0,str(v)) elif isinstance(v,bool): if v is Tr...
return header dict
def iter_package_families(paths=None): """Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional)...
Iterate over package families, in no particular order. Note that multiple package families with the same name can be returned. Unlike packages, families later in the searchpath are not hidden by earlier families. Args: paths (list of str, optional): paths to search for package families, ...
def format_box(title, ch="*"): """ Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** ************************* """ lt = len(title) return [(ch * (lt + 8)),...
Encloses title in a box. Result is a list >>> for line in format_box("Today's TODO list"): ... print(line) ************************* *** Today's TODO list *** *************************
def predict(self, text): """Predict using the model. Args: text: string, the input text. Returns: tags: list, shape = (num_words,) Returns predicted values. """ pred = self.predict_proba(text) tags = self._get_tags(pred) retu...
Predict using the model. Args: text: string, the input text. Returns: tags: list, shape = (num_words,) Returns predicted values.