code
stringlengths
1
18.2k
args and args['io_big']: retval['io_big'] = True # also add the queue if self.queue_name is not None: retval['queue'] = str(self.queue_name) return retval
def format(self, format, dependencies = 0, limit_command_line = None): """Formats the current job into a nicer string to fit into a table.""" command_line = self._cmdline() if limit_command_line is not None and len(command_line) > limit_command_line: command_line = command_line[:limit_command_line-3] + '...' job_id = "...
self.exec_dir if dependencies: deps = str(sorted(list(set([dep.unique for dep in self.get_jobs_we_wait_for()])))) if dependencies < len(deps): deps = deps[:dependencies-3] + '...' return format.format(self.unique, job_id, queue[:12], status, self.name, deps, command_line) else: return format.format(self.unique, job_id,...
def get_repo_name(repo_dir): """ Takes a directory (which must be a git repo) and returns the repository name, derived from remote.origin.url; <domain>/foo/bar.git => bar :param repo_dir: path of the directory :return: string """ repo = git.Repo(repo_dir) url = repo.remotes.origin.url return url.split('/')[-1].split('....
def extract_feature_order_from_model_xml(file_path): """ Takes the path to a FeatureIDE model.xml file and extracts the feature order. :param file_path: path to the model file :return: list of features as strings """ root = xml.etree.ElementTree.parse(file_path).getroot() feature_order_node = root.find('featureOrder') ...
def get_feature_order_constraints(container_dir): """ Returns the feature order constraints dict defined in featuremodel/productline/feature_order.json :param container_dir: the container dir. :return: dict """ import json file_path = os.path.join(container_dir, '_lib/featuremodel/productline/feature_order.json') with ...
def get_features_from_equation(container_dir, product_name): """ Takes the container dir and the product name and returns the list of features. :param container_dir: path of the container dir :param product_name: name of the product :return: list of strings, each representing one feature """ import featuremonkey file_p...
def get_feature_ide_paths(container_dir, product_name): """ Takes the container_dir and the product name and returns all relevant paths from the feature_order_json to the config_file_path. :param container_dir: the full path of the container dir :param product_name: the name of the product :return: object with divert p...
def index_get(array, *argv): """ checks if a index is available in the array and returns it :param array: the data array :param argv: index integers :return: None if not available or the return value """ try: for index in argv: array = array[index] return array # there is either no info available or no popular times # ...
def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent): """ check for optional return parameters and add them to the result json :param detail_json: :param detail: :param rating: :param rating_n: :param popularity: :param current_popularity: :param time_spent: :re...
def get_populartimes_from_search(place_identifier, user_agent=default_user_agent, **kwargs): """ request information for a place and parse current popularity :param place_identifier: name and address string :return: """ params_url = { "tbm": "map", "tch": 1, "q": urllib.parse.quote_plus(place_identifier), "pb": "!4m12!...
4, 8) popular_times = index_get(info, 84, 0) # current_popularity is also not available if popular_times isn't current_popularity = index_get(info, 84, 7, 1) time_spent = index_get(info, 117, 0) # extract numbers from time string if time_spent is not None: time_spent = time_spent.replace("\xa0", " ") time_spent = [[ fl...
def check_response_code(resp): """ check if query quota has been surpassed or other errors occured :param resp: json response :return: """ if resp["status"] == "OK" or resp["status"] == "ZERO_RESULTS": return if resp["status"] == "REQUEST_DENIED": raise Exception("Google Places " + resp["status"], "Request was denied, ...
def get_place_details(api_key, place_id, **kwargs): """ sends request to detail to get a search string and uses standard proto buffer to get additional information on the current status of popular times :return: json details """ params = { 'placeid': place_id, 'key': api_key, } resp = requests.get(url=DETAIL_GOOGLEMAPS...
def get_hashed_filename(name, file, suffix=None): """ Gets a new filename for the provided file of the form "oldfilename.hash.ext". If the old filename looks like it already contains a hash, it will be replaced (so you don't end up with names like "pic.hash.hash.ext") """ basename, hash, ext = split_filename(name) file...
def split_filename(name): """ Splits the filename into three parts: the name part, the hash part, and the extension. Like with the extension, the hash part starts with a dot. """ parts = hashed_filename_re.match(name).groupdict() return (parts['name'] or '', parts['hash'] or '', parts['ext'] or '')
def next_departures(bus_number, stop_code, date, time, nb_departure, db_file): """ Getting the 10 next departures How to check with tools database sqlite3 stm.db SELECT "t2"."departure_time" FROM "trips" AS t1 INNER JOIN "stop_times" AS t2 ON ("t1"."trip_id" = "t2"."trip_id") INNER JOIN "stops" AS t3 ON ("t2"."stop_id"...
from calendar WHERE (20190102 BETWEEN start_date AND end_date) AND sunday == 1 select * from calendar_dates WHERE 20190102 == date Select where cases of holiday for days that does not apply SELECT t1.service_id FROM calendar AS t1 WHERE (20190102 BETWEEN t1.start_date AND t1.end_date) AND t1.wednesday == 1 AND (t1.serv...
available query_result = Trip.select(StopTime.departure_time)\ .join(StopTime, on=(Trip.trip_id == StopTime.trip_id))\ .join(Stop, on=(StopTime.stop_id == Stop.stop_id))\ .where( (Trip.route_id == bus_number) & (Stop.stop_code == stop_code) & (Trip.service_id .in_(subquery)))\ .order_by(StopTime.departure_time) result ...
def random_ipv4(cidr='10.0.0.0/8'): """ Return a random IPv4 address from the given CIDR block. :key str cidr: CIDR block :returns: An IPv4 address from the given CIDR block :rtype: ipaddress.IPv4Address """ try: u_cidr = unicode(cidr) except NameError: u_cidr = cidr network = ipaddress.ip_network(u_cidr) start = int(n...
def output_files(self): """Returns the list of output files from this rule. Paths are relative to buildroot. """ for item in self.source_files: yield os.path.join(self.address.repo, self.address.path, item)
def _compile_qt_resources(): """ Compiles PyQT resources file """ if config.QT_RES_SRC(): epab.utils.ensure_exe('pyrcc5') LOGGER.info('compiling Qt resources') elib_run.run(f'pyrcc5 {config.QT_RES_SRC()} -o {config.QT_RES_TGT()}')
def to_json(msg): """ Returns a JSON string representation of this message """ result = {} # herald specification version #result[herald.MESSAGE_HERALD_VERSION] = herald.HERALD_SPECIFICATION_VERSION # headers result[herald.MESSAGE_HEADERS] = {} if msg.headers is not None: for key in msg.headers: result[herald.MESSAGE_H...
def from_json(json_string): """ Returns a new MessageReceived from the provided json_string string """ # parse the provided json_message try: parsed_msg = json.loads(json_string) except ValueError as ex: # if the provided json_message is not a valid JSON return None except TypeError as ex: # if json_message not string ...
in parsed_msg: parsed_content = parsed_msg[herald.MESSAGE_CONTENT] if parsed_content is not None: if isinstance(parsed_content, str): msg.set_content(parsed_content) else: msg.set_content(jabsorb.from_jabsorb(parsed_content)) except KeyError as ex: _logger.error("Error retrieving message content! " + str(ex)) # other h...
def run(self): """ Runs the given method until cancel() is called """ # The "or" part is for Python 2.6 while not (self.finished.wait(self.interval) or self.finished.is_set()): self.function(*self.args, **self.kwargs)
def resource(string: str): """ :param string: String can be type, resource or python case """ try: prefix, resulting_type = Naming.pop_prefix(string) prefix += Naming.RESOURCE_PREFIX except IndexError: prefix = '' resulting_type = string resulting_type = dasherize(underscore(resulting_type)) return prefix + (pluralize(...
def python(string: str): """ :param string: String can be type, resource or python case """ return underscore(singularize(string) if Naming._pluralize(string) else string)
def pop_prefix(string: str): """Erases the prefix and returns it. :throws IndexError: There is no prefix. :return A set with two elements: 1- the prefix, 2- the type without it. """ result = string.split(Naming.TYPE_PREFIX) if len(result) == 1: result = string.split(Naming.RESOURCE_PREFIX) if len(result) == 1: raise In...
def new_type(type_name: str, prefix: str or None = None) -> str: """ Creates a resource type with optionally a prefix. Using the rules of JSON-LD, we use prefixes to disambiguate between different types with the same name: one can Accept a device or a project. In eReuse.org there are different events with the same name...
from a device """ if Naming.TYPE_PREFIX in type_name: raise TypeError('Cannot create new type: type {} is already prefixed.'.format(type_name)) prefix = (prefix + Naming.TYPE_PREFIX) if prefix is not None else '' return prefix + type_name
def hid(manufacturer: str, serial_number: str, model: str) -> str: """Computes the HID for the given properties of a device. The HID is suitable to use to an URI.""" return Naming.url_word(manufacturer) + '-' + Naming.url_word(serial_number) + '-' + Naming.url_word(model)
def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str, password: str) -> Membership: """ Get a Membership document :param membership_type: "IN" to ask for membership or "OUT" to cancel membership :param current_block: Current block data :param identity: Identity document :...
def getvar(syntree, targetvar): """Scan an ast object for targetvar and return its value. Only handles single direct assignment of python literal types. See docs on ast.literal_eval for more info: http://docs.python.org/2/library/ast.html#ast.literal_eval Args: syntree: ast.Module object targetvar: name of global varia...
def run(cmd, shell=False, debug=False): 'Run a command and return the output.' proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=shell) (out, _) = proc.communicate() # no need for stderr if debug: print(cmd) print(out) return out
def findObjects(path): """Finds objects in pairtree. Given a path that corresponds to a pairtree, walk it and look for non-shorty (it's ya birthday) directories. """ objects = [] if not os.path.isdir(path): return [] contents = os.listdir(path) for item in contents: fullPath = os.path.join(path, item) if not os.path.is...
def get_pair_path(meta_id): """Determines the pair path for the digital object meta-id.""" pair_tree = pair_tree_creator(meta_id) pair_path = os.path.join(pair_tree, meta_id) return pair_path
def pair_tree_creator(meta_id): """Splits string into a pairtree path.""" chunks = [] for x in range(0, len(meta_id)): if x % 2: continue if (len(meta_id) - 1) == x: chunk = meta_id[x] else: chunk = meta_id[x: x + 2] chunks.append(chunk) return os.sep + os.sep.join(chunks) + os.sep
def deSanitizeString(name): """Reverses sanitization process. Reverses changes made to a string that has been sanitized for use as a pairtree identifier. """ oldString = name # first pass replaceTable2 = [ ("/", "="), (":", "+"), (".", ","), ] for r in replaceTable2: oldString = oldString.replace(r[1], r[0]) # reverse ...
def sanitizeString(name): """Cleans string in preparation for splitting for use as a pairtree identifier.""" newString = name # string cleaning, pass 1 replaceTable = [ ('^', '^5e'), # we need to do this one first ('"', '^22'), ('<', '^3c'), ('?', '^3f'), ('*', '^2a'), ('=', '^3d'), ('+', '^2b'), ('>', '^3e'), ('|', '^...
by # letter 'e' or really ^x1e (ascii 30) newString = newString.replace( chr(x), hex(x + sanitizerNum).replace('0x', '^')) replaceTable2 = [ ("/", "="), (":", "+"), (".", ","), ] # / -> = # : -> + # . -> , # string cleaning pass 2 for r in replaceTable2: newString = newString.replace(r[0], r[1]) return newString
def toPairTreePath(name): """Cleans a string, and then splits it into a pairtree path.""" sName = sanitizeString(name) chunks = [] for x in range(0, len(sName)): if x % 2: continue if (len(sName) - 1) == x: chunk = sName[x] else: chunk = sName[x: x + 2] chunks.append(chunk) return os.sep.join(chunks) + os.sep
def create_paired_dir(output_dir, meta_id, static=False, needwebdir=True): """Creates the meta or static dirs. Adds an "even" or "odd" subdirectory to the static path based on the meta-id. """ # get the absolute root path root_path = os.path.abspath(output_dir) # if it's a static directory, add even and odd if static: ...
output path path_name = add_to_pairtree(output_path, meta_id) # add the meta-id directory to the end of the pairpath meta_dir = os.path.join(path_name, meta_id) os.mkdir(meta_dir) # if we are creating static output if static and needwebdir: # add the web path to the output directory os.mkdir(os.path.join(meta_dir, 'web...
def add_to_pairtree(output_path, meta_id): """Creates pairtree dir structure within pairtree for new element.""" # create the pair path paired_path = pair_tree_creator(meta_id) path_append = '' # for each directory in the pair path for pair_dir in paired_path.split(os.sep): # append the pair path together, one director...
def get_pairtree_prefix(pairtree_store): """Returns the prefix given in pairtree_prefix file.""" prefix_path = os.path.join(pairtree_store, 'pairtree_prefix') with open(prefix_path, 'r') as prefixf: prefix = prefixf.read().strip() return prefix
def parse_field(cls: Type[DocumentType], field_name: str, line: str) -> Any: """ Parse a document field with regular expression and return the value :param field_name: Name of the field :param line: Line string to parse :return: """ try: match = cls.fields_parsers[field_name].match(line) if match is None: raise Attribu...
def signed_raw(self) -> str: """ If keys are None, returns the raw + current signatures If keys are present, returns the raw signed by these keys :return: """ raw = self.raw() signed = "\n".join(self.signatures) signed_raw = raw + signed + "\n" return signed_raw
def sha_hash(self) -> str: """ Return uppercase hex sha256 hash from signed raw document :return: """ return hashlib.sha256(self.signed_raw().encode("ascii")).hexdigest().upper()
def build_row_dict(cls, row, dialect, deleted=False, user_id=None, use_dirty=True): """ Builds a dictionary of archive data from row which is suitable for insert. NOTE: If `deleted` is False, version ID will be set to an AsIs SQL construct. :param row: instance of :class:`~SavageModelMixin` :param dialect: :py:class:`~...
use_dirty=use_dirty) if user_id is not None: data['user_id'] = user_id return data
def bulk_archive_rows(cls, rows, session, user_id=None, chunk_size=1000, commit=True): """ Bulk archives data previously written to DB. :param rows: iterable of previously saved model instances to archive :param session: DB session to use for inserts :param user_id: ID of user responsible for row modifications :return:...
def _validate(cls, engine, *version_cols): """ Validates the archive table. Validates the following criteria: - all version columns exist in the archive table - the python types of the user table and archive table columns are the same - a user_id column exists - there is a unique constraint on version and the other ver...
and log table columns are the same version_col_at_t = version_column_at.property.columns[0].type.__class__ version_col_ut_t = version_column_ut.property.columns[0].type.__class__ if version_col_at_t != version_col_ut_t: raise LogTableCreationError( "Type of column {} must match in log and user table".format(version_col...
def register(cls, archive_table, engine): """ :param archive_table: the model for the users archive table :param engine: the database engine :param version_col_names: strings which correspond to columns that versioning will pivot \ around. These columns must have a unique constraint set on them. """ version_col_names =...
def to_archivable_dict(self, dialect, use_dirty=True): """ :param dialect: a :py:class:`~sqlalchemy.engine.interfaces.Dialect` corresponding to the \ SQL dialect being used. :param use_dirty: whether to make a dict of the fields as they stand, or the fields \ before the row was updated :return: a dictionary of key valu...
def self_aware(fn): ''' decorating a function with this allows it to refer to itself as 'self' inside the function body. ''' if isgeneratorfunction(fn): @wraps(fn) def wrapper(*a,**k): generator = fn(*a,**k) if hasattr( generator, 'gi_frame' ) and hasattr( generator.gi_frame, 'f_builtins' ) and hasattr( generator.gi_fr...
def _basic_iterator(self): """this iterator yields individual crash_ids and/or Nones from the iterator specified by the "_create_iter" method. Bare values yielded by the "_create_iter" method get wrapped into an *args, **kwargs form. That form is then used by the task manager as the arguments to the worker function."""...
def _infinite_iterator(self): """this iterator wraps the "_basic_iterator" when the configuration specifies that the "number_of_submissions" is set to "forever". Whenever the "_basic_iterator" is exhausted, it is called again to restart the iteration. It is up to the implementation of the innermost iterator to define w...
def _limited_iterator(self): """this is the iterator for the case when "number_of_submissions" is set to an integer. It goes through the innermost iterator exactly the number of times specified by "number_of_submissions" To do that, it might run the innermost iterator to exhaustion. If that happens, that innermost iter...
break out of inner loop, abandoning the wrapped iter break i += 1 yield crash_id # repeat the quit test, to break out of the outer loop and # if necessary, prevent recycling the wrapped iter if i == int(self.config.number_of_submissions): break
def _transform(self, crash_id): """this default transform function only transfers raw data from the source to the destination without changing the data. While this may be good enough for the raw crashmover, the processor would override this method to create and save processed crashes""" try: raw_crash = self.source.get...
def _setup_source_and_destination(self): """instantiate the classes that implement the source and destination crash storage systems.""" try: self.source = self.config.source.crashstorage_class( self.config.source, quit_check_callback=self.quit_check ) except Exception: self.config.logger.critical( 'Error in creating cr...
def _setup_task_manager(self): """instantiate the threaded task manager to run the producer/consumer queue that is the heart of the processor.""" self.config.logger.info('installing signal handers') # set up the signal handler for dealing with SIGTERM. the target should # be this app instance so the signal handler can ...
def main(self): """this main routine sets up the signal handlers, the source and destination crashstorage systems at the theaded task manager. That starts a flock of threads that are ready to shepherd crashes from the source to the destination.""" self._setup_task_manager() self._setup_source_and_destination() self.tas...
def _setup_source_and_destination(self): """use the base class to setup the source and destinations but add to that setup the instantiation of the "new_crash_source" """ super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \ ._setup_source_and_destination() if self.config.new_crash_source.new_crash_source_class...
def load_config(options): ''' Load options, platform, colors, and icons. ''' global opts, pform opts = options pform = options.pform global_ns = globals() # get colors if pform.hicolor: global_ns['dim_templ'] = ansi.dim8t global_ns['swap_clr_templ'] = ansi.csi8_blk % ansi.blu8 else: global_ns['dim_templ'] = ansi.dim4t ...
def fmtstr(text='', colorstr=None, align='>', trunc=True, width=0, end=' '): ''' Formats, justifies, and returns a given string according to specifications. ''' colwidth = width or opts.colwidth if trunc: if len(text) > colwidth: text = truncstr(text, colwidth, align=trunc) # truncate w/ellipsis value = f'{text:{align}...
def fmtval(value, colorstr=None, precision=None, spacing=True, trunc=True, end=' '): ''' Formats and returns a given number according to specifications. ''' colwidth = opts.colwidth # get precision if precision is None: precision = opts.precision fmt = '%%.%sf' % precision # format with decimal mark, separators result ...
def get_units(unit, binary=False): ''' Sets the output unit and precision for future calculations and returns an integer and the string representation of it. ''' result = None if unit == 'b': result = 1, 'Byte' elif binary: # 2^X if unit == 'k': result = 1024, 'Kibibyte' elif unit == 'm': result = 1048576, 'Mebibyte' e...
== -1: opts.precision = 3 result = 1000000000000, 'Terabyte' if not result: print(f'Warning: incorrect parameter: {unit}.') result = _outunit if opts.precision == -1: # auto opts.precision = 0 return result
def print_diskinfo(diskinfo, widelayout, incolor): ''' Disk information output function. ''' sep = ' ' if opts.relative: import math base = max([ disk.ocap for disk in diskinfo ]) for disk in diskinfo: if disk.ismntd: ico = _diskico else: ico = _unmnico if disk.isrem: ico = _remvico if disk.isopt: ico = _discico if dis...
ufg = (ansi.dim8 if opts.hicolor else ansi.dim4) cap = disk.cap if cap and disk.rw: lblcolor = ansi.get_label_tmpl(disk.pcnt, opts.width, opts.hicolor) else: lblcolor = None # print stats data = ( (_usedico, disk.pcnt, ufg, None, pform.boldbar), # Used (_freeico, 100-disk.pcnt, ffg, None, False), # free ) mntp = fmtstr...
if opts.relative and opts.width != gwidth: out(sep * (opts.width - gwidth)) out(sep + mntp) print() else: out( fmtstr(ico + sep + disk.dev, align="<") + label ) if cap: out( fmtval(cap) + fmtval(disk.used, lblcolor) + fmtval(disk.free, lblcolor) ) else: out(fmtstr(_emptico, dim_templ) + fmtstr() + fmtstr()) print(sep, ...
def print_meminfo(meminfo, widelayout, incolor): ''' Memory information output function. ''' sep = ' ' # prep Mem numbers totl = meminfo.memtotal cach = meminfo.cached + meminfo.buffers free = meminfo.memfree used = meminfo.used usep = float(used) / totl * 100 # % used of total ram cacp = float(cach) / totl * 100 # % c...
= swpc = swpu = swfp = swcp = swup = 0 # avoid /0 error slblcolor = None cacheico = _usedico if incolor else _cmonico # print RAM info data = ( (_usedico, usep, None, None, pform.boldbar), # used (cacheico, cacp, ansi.blue, None, pform.boldbar), # cache (_freeico, frep, None, None, False), # free ) if widelayout: out( ...
incolor, hicolor=opts.hicolor, cbrackets=_brckico) print() # extra line in narrow layout # Swap time: data = ( (_usedico, swup, None, None, pform.boldbar), # used (_usedico, swcp, None, None, pform.boldbar), # cache (_freeico, swfp, None, None, False), # free ) if widelayout: out(fmtstr(_diskico + ' SWAP', align='<') +...
fmtstr(_emptico, dim_templ, align='<')) print() print()
def truncstr(text, width, align='right'): ''' Truncate a string, with trailing ellipsis. ''' before = after = '' if align == 'left': truncated = text[-width+1:] before = _ellpico elif align: truncated = text[:width-1] after = _ellpico return f'{before}{truncated}{after}'
def archive(self, target_path=None, zip_path=None): """ Writes the Zip-encoded file to a directory. :param target_path: The directory path to add. :type target_path: str :param zip_path: The file path of the ZIP archive. :type zip_path: str """ if target_path: self.target_path = target_path if zip_path: self.zip_path =...
def unarchive(self, target_path=None, zip_path=None): """ Extract the given files to the specified destination. :param src_path: The destination path where to extract the files. :type src_path: str :param zip_path: The file path of the ZIP archive. :type zip_path: str """ if target_path: self.target_path = target_path ...
def set_sns(style="white", context="paper", font_scale=1.5, color_codes=True, rc={}): """Set default plot style using seaborn. Font size is set to match the size of the tick labels, rather than the axes labels. """ rcd = {"lines.markersize": 8, "lines.markeredgewidth": 1.25, "legend.fontsize": "small", "font.size": 12/...
def label_subplot(ax=None, x=0.5, y=-0.25, text="(a)", **kwargs): """Create a subplot label.""" if ax is None: ax = plt.gca() ax.text(x=x, y=y, s=text, transform=ax.transAxes, horizontalalignment="center", verticalalignment="top", **kwargs)
def coerce_file(fn): """Coerce file content to something useful for setuptools.setup(), turn : .py into mock object by extracting __special__ attributes values .md into rst text. Remove images with "[nopypi" alt text and emojis :url: https://github.com/Kraymer/setupgoon """ import ast, os, re, tempfile, time, subproces...
# no emojis with tempfile.NamedTemporaryFile(mode='w+') as tmp: tmp.write(text) tmp.flush() text, stderr = subprocess.Popen(['pandoc', '-t', 'rst', tmp.name], stdout=subprocess.PIPE).communicate() return text
def setup_function(self): """twitter.comon.app runs this before any global main() function.""" fpm_path = app.get_options().fpm_bin if not os.path.exists(fpm_path): log.warn('Could not find fpm; gendeb cannot function.') else: GenDebBuilder.fpm_bin = fpm_path
def genchanges(self): """Generate a .changes file for this package.""" chparams = self.params.copy() debpath = os.path.join(self.buildroot, self.rule.output_files[0]) chparams.update({ 'fullversion': '{epoch}:{version}-{release}'.format(**chparams), 'metahash': self._metahash().hexdigest(), 'deb_sha1': util.hash_file(d...
at end of file. ]).format(**chparams) return output
def validate_args(self): """Input validators for this rule type.""" base.BaseTarget.validate_args(self) params = self.params if params['extra_control_fields'] is not None: assert isinstance(params['extra_control_fields'], list), ( 'extra_control_fields must be a list of tuples, not %s' % type( params['extra_control_fie...
def get_next_version() -> str: """ Returns: next version for this Git repository """ LOGGER.info('computing next version') should_be_alpha = bool(CTX.repo.get_current_branch() != 'master') LOGGER.info('alpha: %s', should_be_alpha) calver = _get_calver() LOGGER.info('current calver: %s', calver) calver_tags = _get_curre...
def value(self): """Returns the positive value to subtract from the total.""" originalPrice = self.lineItem.totalPrice if self.flatRate == 0: return originalPrice * self.percent return self.flatRate
def voxel_count(dset,p=None,positive_only=False,mask=None,ROI=None): ''' returns the number of non-zero voxels :p: threshold the dataset at the given *p*-value, then count :positive_only: only count positive values :mask: count within the given mask :ROI: only use the ROI with the given value (or list of values) within...
isinstance(ROI,list): ROI = [ROI] for r in ROI: if r in rois: roi_count = counts[rois.index(r)] if count_dict!=None: count_dict[r] = roi_count else: count += roi_count else: cmd = ['3dBrickStat', '-slow', '-count', '-non-zero', str(dset)] count = int(subprocess.check_output(cmd,stderr=devnull).strip()) if count_dict: r...
def mask_average(dset,mask): '''Returns average of voxels in ``dset`` within non-zero voxels of ``mask``''' o = nl.run(['3dmaskave','-q','-mask',mask,dset]) if o: return float(o.output.split()[-1])
def sphere_average(dset,x,y,z,radius=1): '''returns a list of average values (one for each subbrick/time point) within the coordinate ``(x,y,z)`` (in RAI order) using a sphere of radius ``radius`` in ``dset``''' return_list = [] if isinstance(dset,basestring): dset = [dset] for d in dset: return_list += [float(a) for a...
def is_member_of(self, group_name): """Return True if member of LDAP group, otherwise return False""" group_dn = 'cn=%s,cn=groups,cn=accounts,%s' % (group_name, self._base_dn) if str(group_dn).lower() in [str(i).lower() for i in self.member_of]: return True else: return False
def _get_attr_list(self, attr): """Return user's attribute/attributes""" a = self._attrs.get(attr) if not a: return [] if type(a) is list: r = [i.decode('utf-8', 'ignore') for i in a] else: r = [a.decode('utf-8', 'ignore')] return r
def to_locale(language, to_lower=False): """ Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). Taken `from Django <http://bit.ly/1ssrxqE>`_. """ p = language.find('-') if p >= 0: if to_lower: return language[:p].lower() + '_' + language[p + 1:].l...
def to_language(locale): """ Turns a locale name (en_US) into a language name (en-us). Taken `from Django <http://bit.ly/1vWACbE>`_. """ p = locale.find('_') if p >= 0: return locale[:p].lower() + '-' + locale[p + 1:].lower() else: return locale.lower()
def _commonPrefetchDeclarativeIds(engine, mutex, Declarative, count) -> Optional[Iterable[int]]: """ Common Prefetch Declarative IDs This function is used by the worker and server """ if not count: logger.debug("Count was zero, no range returned") return conn = engine.connect() transaction = conn.begin() mutex.acquire(...