code
stringlengths
51
2.34k
docstring
stringlengths
11
171
def config_set_acl(args): acl_updates = [{"user": user, "role": args.role} \ for user in set(expand_fc_groups(args.users)) \ if user != fapi.whoami()] id = args.snapshot_id if not id: r = fapi.list_repository_configs(namespace=args.namespace, name=args.config) fapi._check_response_code(r, 200) versions = r.json() if len(versions) == 0: if fcconfig.verbosity: eprint("Configuration {0}/{1} not found".format(args.namespace, args.config)) return 1 latest = sorted(versions, key=lambda c: c['snapshotId'])[-1] id = latest['snapshotId'] r = fapi.update_repository_config_acl(args.namespace, args.config, id, acl_updates) fapi._check_response_code(r, 200) if fcconfig.verbosity: print("Updated ACL for {0}/{1}:{2}".format(args.namespace, args.config, id)) return 0
Assign an ACL role to a list of users for a config.
def layers(self): if self._layers is None: self.__init() lyrs = [] for lyr in self._layers: lyr['object'] = GlobeServiceLayer(url=self._url + "/%s" % lyr['id'], securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) lyrs.append(lyr) return lyrs
gets the globe service layers
def payload(self, value): if not isinstance(value, rdfvalue.RDFValue): raise RuntimeError("Payload must be an RDFValue.") self.Set("args", value.SerializeToString()) if value._age is not None: self.args_age = value._age self.args_rdf_name = value.__class__.__name__
Automatically encode RDFValues into the message.
def filter_stopwords(phrase): if not isinstance(phrase, list): phrase = phrase.split() stopwords = ['the', 'a', 'in', 'to'] return [word.lower() for word in phrase if word.lower() not in stopwords]
Filter out stop words and return as a list of words
def discover_glitter_apps(self): for app_name in settings.INSTALLED_APPS: module_name = '{app_name}.glitter_apps'.format(app_name=app_name) try: glitter_apps_module = import_module(module_name) if hasattr(glitter_apps_module, 'apps'): self.glitter_apps.update(glitter_apps_module.apps) except ImportError: pass self.discovered = True
Find all the Glitter App configurations in the current project.
def register_view_for(cls, app, action, classview, attr): if 'view_for_endpoints' not in cls.__dict__: cls.view_for_endpoints = {} cls.view_for_endpoints.setdefault(app, {})[action] = (classview, attr)
Register a classview and viewhandler for a given app and action
def check(text): err = "glaad.terms" msg = "Possibly offensive term. Consider using '{}' instead of '{}'." list = [ ["gay man", ["homosexual man"]], ["gay men", ["homosexual men"]], ["lesbian", ["homosexual woman"]], ["lesbians", ["homosexual women"]], ["gay people", ["homosexual people"]], ["gay couple", ["homosexual couple"]], ["sexual orientation", ["sexual preference"]], ["openly gay", ["admitted homosexual", "avowed homosexual"]], ["equal rights", ["special rights"]] ] return preferred_forms_check(text, list, err, msg, ignore_case=False)
Suggest preferred forms given the reference document.
def Reset(self): self.pan = self.world_center self.desired_pan = self.pos
Reset the camera back to its defaults.
def exempt(self, obj): name = '%s.%s' % (obj.__module__, obj.__name__) @wraps(obj) def __inner(*a, **k): return obj(*a, **k) self._exempt_routes.add(name) return __inner
decorator to mark a view as exempt from htmlmin.
def _resolve_username(self, account, username): if account is not None: warnings.warn( "Use keyword argument 'username' instead of 'account'", DeprecationWarning) return username or account or self.username
Resolve username and handle deprecation of account kwarg
def _process(self, project, build_system, job_priorities): jobs = [] cache_key = '{}-{}-ref_data_names_cache'.format(project, build_system) ref_data_names_map = cache.get(cache_key) if not ref_data_names_map: ref_data_names_map = self._build_ref_data_names(project, build_system) cache.set(cache_key, ref_data_names_map, SETA_REF_DATA_NAMES_CACHE_TIMEOUT) for jp in job_priorities: if not valid_platform(jp.platform): continue if is_job_blacklisted(jp.testtype): continue key = jp.unique_identifier() if key in ref_data_names_map: jobs.append(ref_data_names_map[key]) else: logger.warning('Job priority (%s) not found in accepted jobs list', jp) return jobs
Return list of ref_data_name for job_priorities
def Initialize(self): if "r" in self.mode: delegate = self.Get(self.Schema.DELEGATE) if delegate: self.delegate = aff4.FACTORY.Open( delegate, mode=self.mode, token=self.token, age=self.age_policy)
Open the delegate object.
def card(self): body, more, is_markdown = self._entry_content return TrueCallableProxy( self._get_card, body or more) if is_markdown else CallableProxy(None)
Get the entry's OpenGraph card
def main(): log = logging.getLogger('sip.mock_workflow_stage') if len(sys.argv) != 2: log.critical('Expecting JSON string as first argument!') return config = json.loads(sys.argv[1]) log.info('Running mock_workflow_stage (version: %s).', __version__) log.info('Received configuration: %s', json.dumps(config)) log.info('Starting task') i = 0 start_time = time.time() duration = config.get('duration', 20) while time.time() - start_time <= duration: time.sleep(duration / 20) elapsed = time.time() - start_time log.info(" %s %2i / 20 (elapsed %.2f s)", config.get('message', 'Progress '), i + 1, elapsed) i += 1 log.info('Task complete!')
Run the workflow task.
def _get_struct_encodedu32(self): useful = [] while True: byte = ord(self._src.read(1)) useful.append(byte) if byte < 127: break useful = ['00000000' + bin(b)[2:] for b in useful[::-1]] return int(''.join([b[-7:] for b in useful]), 2)
Get a EncodedU32 number.
def _discretize(a): arr = np.asarray(a) index = np.argsort(arr) inverse_index = np.zeros(arr.size, dtype=np.intp) inverse_index[index] = np.arange(arr.size, dtype=np.intp) arr = arr[index] obs = np.r_[True, arr[1:] != arr[:-1]] return obs.cumsum()[inverse_index] - 1
Discretizes array values to class labels.
def to_json(self): result = super(Environment, self).to_json() result.update({ 'name': self.name }) return result
Returns the JSON representation of the environment.
def load_objects(self, directory_name=None): if directory_name is not None: if directory_name == parameters.REAL_KBO_AST_DIR: kbos = parsers.ossos_discoveries(all_objects=True, data_release=None) else: kbos = parsers.ossos_discoveries(directory_name, all_objects=False, data_release=None) for kbo in kbos: self.kbos[kbo.name] = kbo.orbit self.kbos[kbo.name].mag = kbo.mag self.doplot()
Load the targets from a file.
def report_status(self, status): status = Instance('', TaskStatus).validate(None, status) print(r'{taskname} | {percent:>3}% | {message}'.format( taskname=self.__class__.__name__, percent=int(round(100*status.progress)), message=status.message if status.message else '', ))
Hook for reporting the task status towards completion
def deserialize(self, xml_input, *args, **kwargs): return xmltodict.parse(xml_input, *args, **kwargs)
Convert XML to dict object
def write_id (self): self.writeln(u"<tr>") self.writeln(u'<td>%s</td>' % self.part("id")) self.write(u"<td>%d</td></tr>" % self.stats.number)
Write ID for current URL.
def _get_last_tag(self): current_version = LooseVersion( self._get_version_from_tag(self.release_notes_generator.current_tag) ) versions = [] for tag in self.repo.tags(): if not tag.name.startswith(self.github_info["prefix_prod"]): continue version = LooseVersion(self._get_version_from_tag(tag.name)) if version >= current_version: continue versions.append(version) if versions: versions.sort() return "{}{}".format(self.github_info["prefix_prod"], versions[-1])
Gets the last release tag before self.current_tag
def save(self, *args, **kwargs): if self.order == '' or self.order is None: try: self.order = self.get_auto_order_queryset().order_by("-order")[0].order + 1 except IndexError: self.order = 0 super(BaseOrdered, self).save()
if order left blank
def update(self, enabled=None): if enabled is None: enabled = self.checkState(0) == QtCore.Qt.Checked elif not enabled or self._element.get('enabled', 'True') != 'True': self.setCheckState(0, QtCore.Qt.Unchecked) else: self.setCheckState(0, QtCore.Qt.Checked) if enabled: self.setForeground(0, QtGui.QBrush()) else: self.setForeground(0, QtGui.QBrush(QtGui.QColor('lightGray'))) for child in self.children(): child.update(enabled)
Updates this item based on the interface.
def future_import(feature, node): root = find_root(node) if does_tree_import(u"__future__", feature, node): return shebang_encoding_idx = None for idx, node in enumerate(root.children): if is_shebang_comment(node) or is_encoding_comment(node): shebang_encoding_idx = idx if is_docstring(node): continue names = check_future_import(node) if not names: break if feature in names: return import_ = FromImport(u'__future__', [Leaf(token.NAME, feature, prefix=" ")]) if shebang_encoding_idx == 0 and idx == 0: import_.prefix = root.children[0].prefix root.children[0].prefix = u'' children = [import_ , Newline()] root.insert_child(idx, Node(syms.simple_stmt, children))
This seems to work
def order_by(self, order_by: Union[set, str]): clone = self._clone() if isinstance(order_by, str): order_by = {order_by} clone._order_by = clone._order_by.union(order_by) return clone
Update order_by setting for filter set
def guard(ctx, opts=""): return test(ctx, include_slow=True, loop_on_fail=True, opts=opts)
Execute all tests and then watch for changes, re-running.
def Reset(self): hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString( self._hasher_names_string) self._hashers = hashers_manager.HashersManager.GetHashers(hasher_names)
Resets the internal state of the analyzer.
def options(self, parser, env=None): if env is None: env = os.environ env_opt_name = 'NOSE_%s' % self.__dest_opt_name.upper() parser.add_option("--%s" % self.__opt_name, dest=self.__dest_opt_name, type="string", default=env.get(env_opt_name), help=".ini file providing the environment for the " "test web application.")
Adds command-line options for this plugin.
def _commands(ctx): ctx = ctx.parent ctx.show_hidden_subcommands = False main = ctx.command for subcommand in main.list_commands(ctx): cmd = main.get_command(ctx, subcommand) if cmd is None: continue help = cmd.short_help or "" click.echo("{}:{}".format(subcommand, help))
Prints a list of commands for shell completion hooks.
def cursesMain(_scr, sheetlist): 'Populate VisiData object with sheets from a given list.' colors.setup() for vs in sheetlist: vd().push(vs) status('Ctrl+H opens help') return vd().run(_scr)
Populate VisiData object with sheets from a given list.
def _remove_duplicates(self): contained = set() for m1, m2 in itertools.combinations(self._max_rects, 2): if m1.contains(m2): contained.add(m2) elif m2.contains(m1): contained.add(m1) self._max_rects = [m for m in self._max_rects if m not in contained]
Remove every maximal rectangle contained by another one.
def _local_times_from_hours_since_midnight(times, hours): tz_info = times.tz naive_times = times.tz_localize(None) return pd.DatetimeIndex( (naive_times.normalize().astype(np.int64) + (hours * NS_PER_HR).astype(np.int64)).astype('datetime64[ns]'), tz=tz_info)
converts hours since midnight from an array of floats to localized times
def create_admin_object_resource(name, server=None, **kwargs): defaults = { 'description': '', 'className': 'com.sun.messaging.Queue', 'enabled': True, 'id': name, 'resAdapter': 'jmsra', 'resType': 'javax.jms.Queue', 'target': 'server' } data = defaults data.update(kwargs) if data['resType'] == 'javax.jms.Queue': data['className'] = 'com.sun.messaging.Queue' elif data['resType'] == 'javax.jms.Topic': data['className'] = 'com.sun.messaging.Topic' else: raise CommandExecutionError('resType should be "javax.jms.Queue" or "javax.jms.Topic"!') if data['resAdapter'] != 'jmsra': raise CommandExecutionError('resAdapter should be "jmsra"!') if 'resType' in data: data['restype'] = data['resType'] del data['resType'] if 'className' in data: data['classname'] = data['className'] del data['className'] return _create_element(name, 'resources/admin-object-resource', data, server)
Create a JMS destination
def list_bzip2 (archive, compression, cmd, verbosity, interactive): return stripext(cmd, archive, verbosity)
List a BZIP2 archive.
def percentile(self, lst_data, percent , key=lambda x:x): new_list = sorted(lst_data) k = (len(new_list)-1) * percent f = math.floor(k) c = math.ceil(k) if f == c: return key(new_list[int(k)]) d0 = float(key(new_list[int(f)])) * (c-k) d1 = float(key(new_list[int(c)])) * (k-f) return d0+d1
calculates the 'num' percentile of the items in the list
def get(self): self._cast = type([]) source_value = os.getenv(self.env_name) if source_value is None: os.environ[self.env_name] = json.dumps(self.default) return self.default try: val = json.loads(source_value) except JSONDecodeError as e: click.secho(str(e), err=True, color='red') sys.exit(1) except ValueError as e: click.secho(e.message, err=True, color='red') sys.exit(1) if self.validator: val = self.validator(val) return val
convert json env variable if set to list
def flatten_path_lists(env_dict, env_root=None): for (key, val) in env_dict.items(): if isinstance(val, list): env_dict[key] = os.path.join(env_root, os.path.join(*val)) if (env_root and not os.path.isabs(os.path.join(*val))) else os.path.join(*val) return env_dict
Join paths in environment dict down to strings.
def abspath(relpath, root=None): root = root or cwd() if op.isfile(root): root = op.dirname(root) return op.abspath(op.join(root, relpath))
Returns an absolute path based on the given root and relative path.
def Handle(self, unused_args, token=None): result = ApiGrrUser(username=token.username) if data_store.RelationalDBEnabled(): user_record = data_store.REL_DB.ReadGRRUser(token.username) result.InitFromDatabaseObject(user_record) else: try: user_record = aff4.FACTORY.Open( aff4.ROOT_URN.Add("users").Add(token.username), aff4_users.GRRUser, token=token) result.InitFromAff4Object(user_record) except IOError: result.settings = aff4_users.GRRUser.SchemaCls.GUI_SETTINGS() result.interface_traits = ( self.interface_traits or ApiGrrUserInterfaceTraits()) return result
Fetches and renders current user's settings.
def parse_altitude(cls, distance, unit): if distance is not None: distance = float(distance) CONVERTERS = { 'km': lambda d: d, 'm': lambda d: units.kilometers(meters=d), 'mi': lambda d: units.kilometers(miles=d), 'ft': lambda d: units.kilometers(feet=d), 'nm': lambda d: units.kilometers(nautical=d), 'nmi': lambda d: units.kilometers(nautical=d) } try: return CONVERTERS[unit](distance) except KeyError: raise NotImplementedError( 'Bad distance unit specified, valid are: %r' % CONVERTERS.keys() ) else: return distance
Parse altitude managing units conversion
def format_number_field(__, prec, number, locale): prec = NUMBER_DECIMAL_DIGITS if prec is None else int(prec) locale = Locale.parse(locale) pattern = locale.decimal_formats.get(None) return pattern.apply(number, locale, force_frac=(prec, prec))
Formats a number field.
async def _async_stop(self): if self.presence: self.presence.set_unavailable() for behav in self.behaviours: behav.kill() if self.web.is_started(): await self.web.runner.cleanup() if self.is_alive(): self.client.stop() aexit = self.conn_coro.__aexit__(*sys.exc_info()) await aexit logger.info("Client disconnected.") self._alive.clear()
Stops an agent and kills all its behaviours.
def write_config(filename, config, mode="w"): with open(filename, mode) as filey: config.write(filey) return filename
use configparser to write a config object to filename
def build_computation(self, message: Message, transaction: BaseOrSpoofTransaction) -> BaseComputation: transaction_context = self.vm_state.get_transaction_context(transaction) if message.is_create: is_collision = self.vm_state.has_code_or_nonce( message.storage_address ) if is_collision: computation = self.vm_state.get_computation(message, transaction_context) computation._error = ContractCreationCollision( "Address collision while creating contract: {0}".format( encode_hex(message.storage_address), ) ) self.vm_state.logger.debug2( "Address collision while creating contract: %s", encode_hex(message.storage_address), ) else: computation = self.vm_state.get_computation( message, transaction_context, ).apply_create_message() else: computation = self.vm_state.get_computation( message, transaction_context).apply_message() return computation
Apply the message to the VM.
def func(self, name: str): for f in self.body: if (hasattr(f, '_ctype') and isinstance(f._ctype, FuncType) and f._name == name): return f
return the first func defined named name
def _compileSmsRegexes(self): if self._smsTextMode: if self.CMGR_SM_DELIVER_REGEX_TEXT == None: self.CMGR_SM_DELIVER_REGEX_TEXT = re.compile(r'^\+CMGR: "([^"]+)","([^"]+)",[^,]*,"([^"]+)"$') self.CMGR_SM_REPORT_REGEXT_TEXT = re.compile(r'^\+CMGR: ([^,]*),\d+,(\d+),"{0,1}([^"]*)"{0,1},\d*,"([^"]+)","([^"]+)",(\d+)$') elif self.CMGR_REGEX_PDU == None: self.CMGR_REGEX_PDU = re.compile(r'^\+CMGR: (\d*),"{0,1}([^"]*)"{0,1},(\d+)$')
Compiles regular expression used for parsing SMS messages based on current mode
def do_WhoIsRequest(self, apdu): if _debug: WhoIsIAmServices._debug("do_WhoIsRequest %r", apdu) if not self.localDevice: if _debug: WhoIsIAmServices._debug(" - no local device") return low_limit = apdu.deviceInstanceRangeLowLimit high_limit = apdu.deviceInstanceRangeHighLimit if (low_limit is not None): if (high_limit is None): raise MissingRequiredParameter("deviceInstanceRangeHighLimit required") if (low_limit < 0) or (low_limit > 4194303): raise ParameterOutOfRange("deviceInstanceRangeLowLimit out of range") if (high_limit is not None): if (low_limit is None): raise MissingRequiredParameter("deviceInstanceRangeLowLimit required") if (high_limit < 0) or (high_limit > 4194303): raise ParameterOutOfRange("deviceInstanceRangeHighLimit out of range") if (low_limit is not None): if (self.localDevice.objectIdentifier[1] < low_limit): return if (high_limit is not None): if (self.localDevice.objectIdentifier[1] > high_limit): return self.i_am(address=apdu.pduSource)
Respond to a Who-Is request.
def allow_origin(self, request): origins = self.origins if origins is AnyOrigin: return '*' else: origin = request.origin return origin if origin in origins else ''
Generate allow origin header
def add_events(self, **kwargs): event_q = kwargs.get('event_queue') pri = kwargs.get('priority') if not event_q or not pri: return try: event_type = 'server.failure.recovery' payload = {} timestamp = time.ctime() data = (event_type, payload) event_q.put((pri, timestamp, data)) LOG.debug('Added failure recovery event to the queue.') except Exception as exc: LOG.exception('Error: %(exc)s for event %(event)s', {'exc': str(exc), 'event': event_type}) raise exc
Add failure event into the queue.
def _make_parameters(self): self.value_means = [] self.value_ranges = [] self.arrangement = [] self.variable_parameters = [] current_var = 0 for parameter in self.parameters: if parameter.type == ParameterType.DYNAMIC: self.value_means.append(parameter.value[0]) if parameter.value[1] < 0: raise AttributeError( '"{}" parameter has an invalid range. Range values ' 'must be greater than zero'.format(parameter.label)) self.value_ranges.append(parameter.value[1]) var_label = 'var{}'.format(current_var) self.arrangement.append(var_label) self.variable_parameters.append(var_label) current_var += 1 elif parameter.type == ParameterType.STATIC: self.arrangement.append(parameter.value) else: raise AttributeError( '"{}"Unknown parameter type ({}). Parameters can be STATIC or' ' DYNAMIC.'.format(parameter.type)) return
Converts a list of Parameters into DEAP format.
def split_data(data, subset, splits): return dict([(k, data[k][splits[subset]]) for k in data])
Returns the data for a given protocol
def list(self): connection = self._backend._get_connection() return list(self._backend.list(connection))
List the tables in the database
def _gdal_write_datasets(self, dst_ds, datasets): for i, band in enumerate(datasets['bands']): chn = datasets.sel(bands=band) bnd = dst_ds.GetRasterBand(i + 1) bnd.SetNoDataValue(0) bnd.WriteArray(chn.values)
Write datasets in a gdal raster structure dts_ds
def _perform_merge(self, other): if len(other.value) > len(self.value): self.value = other.value[:] return True
Merges the longer string
def auc(y_true, y_pred, round=True): y_true, y_pred = _mask_value_nan(y_true, y_pred) if round: y_true = y_true.round() if len(y_true) == 0 or len(np.unique(y_true)) < 2: return np.nan return skm.roc_auc_score(y_true, y_pred)
Area under the ROC curve
def from_representation(self, data): if data in self._TRUE_VALUES: return True elif data in self._FALSE_VALUES: return False else: raise ValueError( "{type} type value must be one of {values}".format( type=self.type, values=self._TRUE_VALUES.union(self._FALSE_VALUES) ) )
Convert representation value to ``bool`` if it has expected form.
def _load_webgl_backend(ipython): from .. import app app_instance = app.use_app("ipynb_webgl") if app_instance.backend_name == "ipynb_webgl": ipython.write("Vispy IPython module has loaded successfully") else: ipython.write_err("Unable to load webgl backend of Vispy")
Load the webgl backend for the IPython notebook
def deftypes(self): for f in self.body: if (hasattr(f, '_ctype') and (f._ctype._storage == Storages.TYPEDEF or (f._name == '' and isinstance(f._ctype, ComposedType)))): yield f
generator on all definition of type
def strip_pad(hdu): l = hdu.header.ascardlist() d = [] for index in range(len(l)): if l[index].key in __comment_keys and str(l[index])==__cfht_padding: d.append(index) d.reverse() for index in d: del l[index] return(0)
Remove the padding lines that CFHT adds to headers
def _is_api_key_correct(request): api_key = getattr(settings, 'GECKOBOARD_API_KEY', None) if api_key is None: return True auth = request.META.get('HTTP_AUTHORIZATION', '').split() if len(auth) == 2: if auth[0].lower() == b'basic': request_key = base64.b64decode(auth[1]).split(b':')[0] return request_key == api_key return False
Return whether the Geckoboard API key on the request is correct.
def _hcn_func(self): self.hc = 1./(np.pi*self.dist)*np.sqrt(2.*self._dEndfr()) return
Eq. 56 from Barack and Cutler 2004
def _get_db(): with cd(env.remote_path): file_path = '/tmp/' + _sql_paths('remote', str(base64.urlsafe_b64encode(uuid.uuid4().bytes)).replace('=', '')) run(env.python + ' manage.py dump_database | gzip > ' + file_path) local_file_path = './backups/' + _sql_paths('remote', datetime.now()) get(file_path, local_file_path) run('rm ' + file_path) return local_file_path
Get database from server
def generate_table_results(output=None, without_header=None): array = [] str_output = str(output) if not without_header: array.append('RESULT') array.append('-' * max(6, len(str_output))) array.append(str_output) return os.linesep.join(array)
Convert returned data from non-list actions into a nice table for command line usage
def __updateNavButtons(self): navButtons = None for v in self.views: if v.getId() == 'com.android.systemui:id/nav_buttons': navButtons = v break if navButtons: self.navBack = self.findViewById('com.android.systemui:id/back', navButtons) self.navHome = self.findViewById('com.android.systemui:id/home', navButtons) self.navRecentApps = self.findViewById('com.android.systemui:id/recent_apps', navButtons) else: if self.uiAutomatorHelper: print >> sys.stderr, "WARNING: nav buttons not found. Perhaps the device has hardware buttons." self.navBack = None self.navHome = None self.navRecentApps = None
Updates the navigation buttons that might be on the device screen.
def _get_filesystem_config(file_types): out = " filesystems {\n" for file_type in sorted(list(file_types)): if file_type in _FILESYSTEM_CONFIG: out += _FILESYSTEM_CONFIG[file_type] out += " }\n" return out
Retrieve filesystem configuration, including support for specified file types.
def Shift(self, value, copy=False): numPoints = self.GetN() if copy: shiftGraph = self.Clone() else: shiftGraph = self X = self.GetX() EXlow = self.GetEXlow() EXhigh = self.GetEXhigh() Y = self.GetY() EYlow = self.GetEYlow() EYhigh = self.GetEYhigh() for i in range(numPoints): shiftGraph.SetPoint(i, X[i] + value, Y[i]) shiftGraph.SetPointError( i, EXlow[i], EXhigh[i], EYlow[i], EYhigh[i]) return shiftGraph
Shift the graph left or right by value
def read(self, size=-1): buf = self._fd.read(size) self._progress_cb(len(buf)) return buf
Read bytes and update the progress bar.
def fromRoman(strng): if not strng: raise TypeError('Input can not be blank') if not romanNumeralPattern.search(strng): raise ValueError('Invalid Roman numeral: %s', strng) result = 0 index = 0 for numeral, integer in romanNumeralMap: while strng[index:index+len(numeral)] == numeral: result += integer index += len(numeral) return result
convert Roman numeral to integer
def dot_v2(vec1, vec2): return vec1.x * vec2.x + vec1.y * vec2.y
Return the dot product of two vectors
def create_backend_noexc(log: logging.Logger, name: str=None, git_index: GitIndex=None, args: str=None) -> Optional[StorageBackend]: try: return create_backend(name, git_index, args) except KeyError: log.critical("No such backend: %s (looked in %s)", name, list(__registry__.keys())) return None except ValueError: log.critical("Invalid backend arguments: %s", args) return None
Initialize a new Backend, return None if there was a known problem.
def remove_path(target_path): if os.path.isdir(target_path): shutil.rmtree(target_path) else: os.unlink(target_path)
Delete the target path
def begin(self, access_mode=None): if self._active_transaction: raise SystemError("Transaction in progress") self._active_transaction = self.driver.session(access_mode=access_mode).begin_transaction()
Begins a new transaction, raises SystemError exception if a transaction is in progress
def load(self): print("[DEBUG] Loading plugin {} from {}".format(self.name, self.source)) import pydoc path, attr = self.source.split(":") module = pydoc.locate(path) return getattr(module, attr)
Load the object defined by the plugin entry point
def send_bytes(self): data = b''.join(self.bytes_to_send) self.bytes_to_send = [] return data
Retrieve all pending bytes to send on the network
def on_motion(self, event): 'on motion we will move the rect if the mouse is over us' if self.press is None: return if event.inaxes != self.ax: return x0, y0, btn = self.press x0.append(event.xdata) y0.append(event.ydata)
on motion we will move the rect if the mouse is over us
def _clean_name(fname, data): for to_remove in dd.get_batches(data) + [dd.get_sample_name(data), data["sv"]["variantcaller"]]: for ext in ("-", "_"): if fname.startswith("%s%s" % (to_remove, ext)): fname = fname[len(to_remove) + len(ext):] if fname.startswith(to_remove): fname = fname[len(to_remove):] return fname
Remove standard prefixes from a filename before renaming with useful names.
def print_result_for_plain_cgi_script(contenttype: str, headers: TYPE_WSGI_RESPONSE_HEADERS, content: bytes, status: str = '200 OK') -> None: headers = [ ("Status", status), ("Content-Type", contenttype), ("Content-Length", str(len(content))), ] + headers sys.stdout.write("\n".join([h[0] + ": " + h[1] for h in headers]) + "\n\n") sys.stdout.write(content)
Writes HTTP request result to stdout.
def git_hash(blob): head = str("blob " + str(len(blob)) + "\0").encode("utf-8") return sha1(head + blob).hexdigest()
Return git-hash compatible SHA-1 hexdigits for a blob of data.
def find_link(self, device): for i in range(len(self.mpstate.mav_master)): conn = self.mpstate.mav_master[i] if (str(i) == device or conn.address == device or getattr(conn, 'label', None) == device): return i return None
find a device based on number, name or label
def kl_error(self, input_data, targets, average=True, cache=None, prediction=True): if cache is not None: activations = cache else: activations = \ self.feed_forward(input_data, prediction=prediction) targets_non_nan = gpuarray.empty_like(targets) nan_to_zeros(targets, targets_non_nan) kl_error = gpuarray.sum(targets_non_nan * (cumath.log(targets_non_nan + eps) - cumath.log(activations + eps))) if average: kl_error /= targets.shape[0] return kl_error.get()
The KL divergence error
def rgb2cmy(self, img, whitebg=False): tmp = img*1.0 if whitebg: tmp = (1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0 out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0 out[:,:,2] = (tmp[:,:,0] + tmp[:,:,1])/2.0 return out
transforms image from RGB to CMY
def _cli_check_readfmt(readfmt): if readfmt is None: return None readfmt = readfmt.lower() if not readfmt in curate.get_reader_formats(): errstr = "Reader for file type '" + readfmt + "' does not exist.\n" errstr += "For a complete list of file types, use the 'bsecurate get-reader-formats' command" raise RuntimeError(errstr) return readfmt
Checks that a file type exists and if not, raises a helpful exception
def _load_from_string(data): global _CACHE if PYTHON_3: data = json.loads(data.decode("utf-8")) else: data = json.loads(data) _CACHE = _recursively_convert_unicode_to_str(data)['data']
Loads the cache from the string
def create(self, request): variant_id = request.data.get("variant_id", None) if variant_id is not None: variant = ProductVariant.objects.get(id=variant_id) product_request = ProductRequest(variant=variant) product_request.save() serializer = self.serializer_class(product_request) response = Response(data=serializer.data, status=status.HTTP_201_CREATED) else: response = Response( {"message": "Missing 'variant_id'"}, status=status.HTTP_400_BAD_REQUEST) return response
Create a new product request
def normalize_hostname(hostname): try: new_hostname = hostname.encode('idna').decode('ascii').lower() except UnicodeError as error: raise UnicodeError('Hostname {} rejected: {}'.format(hostname, error)) from error if hostname != new_hostname: new_hostname.encode('idna') return new_hostname
Normalizes a hostname so that it is ASCII and valid domain name.
def count(self, low, high=None): if high is None: high = low return self.database.zcount(self.key, low, high)
Return the number of items between the given bounds.
def _get_pygments_extensions(): import pygments.lexers as lexers extensions = [] for lx in lexers.get_all_lexers(): lexer_exts = lx[2] if lexer_exts: other_exts = [le for le in lexer_exts if not le.startswith('*')] lexer_exts = [le[1:] for le in lexer_exts if le.startswith('*')] lexer_exts = [le for le in lexer_exts if not le.endswith('_*')] extensions = extensions + list(lexer_exts) + list(other_exts) return sorted(list(set(extensions)))
Return all file type extensions supported by Pygments
def _man_args(self, f): argcount = f.func_code.co_argcount if isinstance(f, types.MethodType): argcount -= 1 if f.func_defaults is None: return argcount return argcount - len(f.func_defaults)
Returns number of mandatory arguments required by given function.
def format_sourcefile_name(self, fileName, runSet): if fileName.startswith(runSet.common_prefix): fileName = fileName[len(runSet.common_prefix):] return fileName.ljust(runSet.max_length_of_filename + 4)
Formats the file name of a program for printing on console.
def check(ctx, meta_model_file, model_file, ignore_case): debug = ctx.obj['debug'] check_model(meta_model_file, model_file, debug, ignore_case)
Check validity of meta-model and optionally model.
def cli(env): mask = ('openTicketCount, closedTicketCount, ' 'openBillingTicketCount, openOtherTicketCount, ' 'openSalesTicketCount, openSupportTicketCount, ' 'openAccountingTicketCount') account = env.client['Account'].getObject(mask=mask) table = formatting.Table(['Status', 'count']) nested = formatting.Table(['Type', 'count']) nested.add_row(['Accounting', account['openAccountingTicketCount']]) nested.add_row(['Billing', account['openBillingTicketCount']]) nested.add_row(['Sales', account['openSalesTicketCount']]) nested.add_row(['Support', account['openSupportTicketCount']]) nested.add_row(['Other', account['openOtherTicketCount']]) nested.add_row(['Total', account['openTicketCount']]) table.add_row(['Open', nested]) table.add_row(['Closed', account['closedTicketCount']]) env.fout(table)
Summary info about tickets.
async def get_shade(self, shade_id, from_cache=True) -> BaseShade: if not from_cache: await self.get_shades() for _shade in self.shades: if _shade.id == shade_id: return _shade raise ResourceNotFoundException("Shade not found. Id: {}".format(shade_id))
Get a shade instance based on shade id.
def build_cpp(build_context, target, compiler_config, workspace_dir): rmtree(workspace_dir) binary = join(*split(target.name)) objects = link_cpp_artifacts(build_context, target, workspace_dir, True) buildenv_workspace = build_context.conf.host_to_buildenv_path( workspace_dir) objects.extend(compile_cc( build_context, compiler_config, target.props.in_buildenv, get_source_files(target, build_context), workspace_dir, buildenv_workspace, target.props.cmd_env)) bin_file = join(buildenv_workspace, binary) link_cmd = ( [compiler_config.linker, '-o', bin_file] + objects + compiler_config.link_flags) build_context.run_in_buildenv( target.props.in_buildenv, link_cmd, target.props.cmd_env) target.artifacts.add(AT.binary, relpath(join(workspace_dir, binary), build_context.conf.project_root), binary)
Compile and link a C++ binary for `target`.
def main(): argv = sys.argv[1:] returncode = 1 try: returncode = _main(os.environ, argv) except exceptions.InvalidArgument as error: if error.message: sys.stderr.write("Error: " + error.message + '\n') else: raise sys.exit(returncode)
The main command-line entry point, with system interactions.
def _get_jobs_url(self): if self._jobs_url is None: self.get_instance_status() if self._jobs_url is None: raise ValueError("Cannot obtain jobs URL") return self._jobs_url
Get & save jobs URL from the status call.
def fnames(self, names): names = list(names[:len(self._fnames)]) self._fnames = names + self._fnames[len(names):]
Ensure constant size of fnames
def generate_pdf(self): printer = QtGui.QPrinter(QtGui.QPrinter.HighResolution) printer.setPageSize(QtGui.QPrinter.A4) printer.setColorMode(QtGui.QPrinter.Color) printer.setOutputFormat(QtGui.QPrinter.PdfFormat) report_path = unique_filename(suffix='.pdf') printer.setOutputFileName(report_path) self.print_(printer) url = QtCore.QUrl.fromLocalFile(report_path) QtGui.QDesktopServices.openUrl(url)
Generate a PDF from the displayed content.
def logout(self): logger.debug('Logout') method = self._anaconda_client_api.remove_authentication return self._create_worker(method)
Logout from anaconda cloud.
def parse_ast(source, filename=None): if isinstance(source, text_type) and sys.version_info[0] == 2: source = CODING_COOKIE_RE.sub(r'\1', source, 1) return ast.parse(source, filename or '<unknown>')
Parse source into a Python AST, taking care of encoding.