code
stringlengths
1
18.2k
def request_get_user(self, user_ids) -> dict: """ Method to get users by ID, do not need authorization """ method_params = {'user_ids': user_ids} response = self.session.send_method_request('users.get', method_params) self.check_for_errors('users.get', method_params, response) return response
def request_set_status(self, text: str) -> dict: """ Method to set user status """ method_params = {'text': text} response = self.session.send_method_request('status.set', method_params) self.check_for_errors('status.set', method_params, response) return response
def hexdump(src, length=16, sep='.'): """ Returns src in hex dump. From https://gist.github.com/ImmortalPC/c340564823f283fe530b :param length: Nb Bytes by row. :param sep: For the text part, sep will be used for non ASCII char. :return: The hexdump """ result = [] for i in range(0, len(src), length): sub_src = src[i:i ...
result.append(('%08X: %-' + str(length * (2 + 1) + 1) + 's |%s|') % (i, hexa, text)) return '\n'.join(result)
def run_spy(group, port, verbose): """ Runs the multicast spy :param group: Multicast group :param port: Multicast port :param verbose: If True, prints more details """ # Create the socket socket, group = multicast.create_multicast_socket(group, port) print("Socket created:", group, "port:", port) # Set the socket as n...
print("Got", len_data, "bytes from", sender[0], "port", sender[1], "at", datetime.datetime.now()) if verbose: print(hexdump(data)) except KeyboardInterrupt: # Interrupt print("Ctrl+C received: bye !") # Print statistics print("Total number of packets:", stats["total_count"]) print("Total read bytes.......:", stats["tot...
def main(argv=None): """ Entry point :param argv: Program arguments """ parser = argparse.ArgumentParser(description="Multicast packets spy") parser.add_argument("-g", "--group", dest="group", default="239.0.0.1", help="Multicast target group (address)") parser.add_argument("-p", "--port", type=int, dest="port", defaul...
def stack_decon_stims(stim_list): '''take a ``list`` (in order of runs) of ``dict``s of stim_name:DeconStim and stack them together. returns a single ``dict`` of stim_name:decon_stim As in, takes: [ # Run 1 { "stim1": decon_stim1a, "stim2": decon_stim2a }, # Run 2 { "stim1": decon_stim1b, "stim2": decon_stim2b, "stim3"...
stim_name in stim_list[i]: stim_stack.append(stim_list[i][stim_name]) else: stim_stack.append(stim_list[i].values()[0].blank_stim(type=type)) stim_dict[stim_name] = copy.copy(stim_stack[0]) for stim in stim_stack[1:]: stim_dict[stim_name] = stim_dict[stim_name].concat_stim(stim) return stim_dict.values()
def smooth_decon_to_fwhm(decon,fwhm,cache=True): '''takes an input :class:`Decon` object and uses ``3dBlurToFWHM`` to make the output as close as possible to ``fwhm`` returns the final measured fwhm. If ``cache`` is ``True``, will save the blurred input file (and use it again in the future)''' if os.path.exists(decon.p...
nl.run_in(tmpdir): if os.path.exists(decon.prefix): os.remove(decon.prefix) # Create the blurred inputs (or load from cache) if cache and all([os.path.exists(os.path.join(cwd,blur_dset(dset))) for dset in decon.input_dsets]): # Everything is already cached... nl.notify('Using cache\'d blurred datasets') else: # Need to...
did not produce expected file %s' % decon.prefix,level=nl.level.warning) except: raise finally: shutil.rmtree(tmpdir,True)
def command_list(self): '''returns the 3dDeconvolve command as a list The list returned can be run by passing it into a subprocess-like command (e.g., neural.run()) ''' cmd = ['3dDeconvolve'] cmd += ['-jobs',multiprocessing.cpu_count()] cmd += self.opts if(len(self.input_dsets)): cmd += ['-input'] + ['%s[%d..%d]' % (ds...
+= ['-mask',self.mask] cmd += ['-polort',str(self.polort)] stim_num = 1 all_stims = list(self.decon_stims) all_stims += [DeconStim(stim,column_file=self.stim_files[stim],base=(stim in self.stim_base)) for stim in self.stim_files] for stim in self.stim_times: decon_stim = DeconStim(stim,times_file=self.stim_times[stim])...
stim.times_file if stim.times!=None: times = list(stim.times) if '__iter__' not in dir(times[0]): # a single list times = [times] times_file = stimautoname(stim_num,stim) with open(times_file,"w") as f: f.write('\n'.join([' '.join([str(x) for x in y]) if len(y)>0 else '*' for y in times])) if times_file: opt = '-stim_t...
all_glts: cmd += ['-gltsym','SYM: %s' % all_glts[glt],'-glt_label',glt_num,glt] glt_num += 1 if self.bout: cmd += ['-bout'] if self.tout: cmd += ['-tout'] if self.vout: cmd += ['-vout'] if self.rout: cmd += ['-rout'] if self.errts: cmd += ['-errts', self.errts] if self.prefix: cmd += ['-bucket', self.prefix] return [st...
def run(self): '''runs 3dDeconvolve through the neural.utils.run shortcut''' out = nl.run(self.command_list(),products=self.prefix) if out and out.output: sds_list = re.findall(r'Stimulus: (.*?) *\n +h\[ 0\] norm\. std\. dev\. = +(\d+\.\d+)',out.output) self.stim_sds = {} for s in sds_list: self.stim_sds[s[0]] = float(...
def type(self): '''returns kind of stim ("column" or "times"), based on what parameters are set''' if self.column!=None or self.column_file: return "column" if self.times!=None or self.times_file: return "times" return None
def read_file(self): '''if this is stored in a file, read it into self.column''' column_selector = r'(.*)\[(\d+)\]$' if self.column_file: column = None m = re.match(column_selector,self.column_file) file = self.column_file if m: file = m.group(1) column = int(m.group(2)) with open(file) as f: lines = f.read().split('\n...
def blank_stim(self,type=None,fill=0): '''Makes a blank version of stim. If a type is not given, returned as same type as current stim. If a column stim, will fill in blanks with ``fill``''' blank = copy.copy(self) blank.name = 'Blank' if type==None: type = self.type() if type=="column": num_reps = self.reps if num_rep...
def concat_stim(self,decon_stim): '''concatenate this to another :class:`DeconStim` of the same "type"''' if self.type()!=decon_stim.type(): nl.notify('Error: Trying to concatenate stimuli of different types! %s (%s) with %s (%s)' % (self.name,self.type(),decon_stim.name,decon_stim.type()),level=nl.level.error) return ...
def partial(self,start=0,end=None,run=0): '''chops the stimulus by only including time points ``start`` through ``end`` (in reps, inclusive; ``None``=until the end) if using stim_times-style simulus, will change the ``run``'th run. If a column, will just chop the column''' self.read_file() decon_stim = copy.copy(self) ...
decon_stim.times_file = None if len(decon_stim.times)==0 or '__iter__' not in dir(decon_stim.times[0]): decon_stim.times = [decon_stim.times] decon_stim.times[run] = [x for x in decon_stim.times[run] if time_in(x)] if len(nl.flatten(decon_stim.times))==0: return None return decon_stim
def notify(self): """ Calls the notification method :return: True if the notification method has been called """ if self.__method is not None: self.__method(self.__peer) return True return False
def observeState(self, call=None): """ Registers an observer to the any changes. The called function should have 2 parameters: - previousState, - actualState :param func call: The function to call. When not given, decorator usage is assumed. :return: the function to call once state change. :rtype: func :raises TypeErro...
def observeElements(self, what, call=None): """ Registers an observer function to a specific state field or list of state fields. The function to call should have 2 parameters: - previousValue, -actualValue :param what: name of the state field or names of the state field to observe. :type what: str | array :param func ...
call toEvaluate = [] if isinstance(what, str): toEvaluate.append(what) else: toEvaluate = what if not self.areObservableElements(toEvaluate): msg = 'Could not find observable element named "{0}" in {1}' raise ValueError(msg.format(what, self.__class__)) if call is not None: return _observe(call) else: return _observe
def setup(args): """Returns the JobManager and sets up the basic infrastructure""" kwargs = {'wrapper_script' : args.wrapper_script, 'debug' : args.verbose==3, 'database' : args.database} if args.local: jm = local.JobManagerLocal(**kwargs) else: jm = sge.JobManagerSGE(**kwargs) # set-up logging if args.verbose not in r...
def get_memfree(memory, parallel): """Computes the memory required for the memfree field.""" number = int(memory.rstrip(string.ascii_letters)) memtype = memory.lstrip(string.digits) if not memtype: memtype = "G" return "%d%s" % (number*parallel, memtype)
def submit(args): """Submission command""" # set full path to command if args.job[0] == '--': del args.job[0] if not os.path.isabs(args.job[0]): args.job[0] = os.path.abspath(args.job[0]) jm = setup(args) kwargs = { 'queue': args.qname, 'cwd': True, 'verbosity' : args.verbose, 'name': args.name, 'env': args.env, 'memfr...
processing or the maximum virtual memroy will be # set on ulimit kwargs.pop('memfree', None) kwargs.pop('hvmem', None) if args.parallel is not None: kwargs['pe_opt'] = "pe_mth %d" % args.parallel if args.memory is not None: kwargs['memfree'] = get_memfree(args.memory, args.parallel) kwargs['dry_run'] = args.dry_run kwa...
def resubmit(args): """Re-submits the jobs with the given ids.""" jm = setup(args) kwargs = { 'cwd': True, 'verbosity' : args.verbose } if args.qname is not None: kwargs['queue'] = args.qname if args.memory is not None: kwargs['memfree'] = args.memory if args.qname not in (None, 'all.q'): kwargs['hvmem'] = args.memory ...
args.no_io_big: kwargs['io_big'] = False jm.resubmit(get_ids(args.job_ids), args.also_success, args.running_jobs, args.overwrite_command, keep_logs=args.keep_logs, **kwargs)
def run_scheduler(args): """Runs the scheduler on the local machine. To stop it, please use Ctrl-C.""" if not args.local: raise ValueError("The execute command can only be used with the '--local' command line option") jm = setup(args) jm.run_scheduler(parallel_jobs=args.parallel, job_ids=get_ids(args.job_ids), sleep_ti...
def list(args): """Lists the jobs in the given database.""" jm = setup(args) jm.list(job_ids=get_ids(args.job_ids), print_array_jobs=args.print_array_jobs, print_dependencies=args.print_dependencies, status=args.status, long=args.long, print_times=args.print_times, ids_only=args.ids_only, names=args.names)
def communicate(args): """Uses qstat to get the status of the requested jobs.""" if args.local: raise ValueError("The communicate command can only be used without the '--local' command line option") jm = setup(args) jm.communicate(job_ids=get_ids(args.job_ids))
def report(args): """Reports the results of the finished (and unfinished) jobs.""" jm = setup(args) jm.report(job_ids=get_ids(args.job_ids), array_ids=get_ids(args.array_ids), output=not args.errors_only, error=not args.output_only, status=args.status, name=args.name)
def stop(args): """Stops (qdel's) the jobs with the given ids.""" if args.local: raise ValueError("Stopping commands locally is not supported (please kill them yourself)") jm = setup(args) jm.stop_jobs(get_ids(args.job_ids))
def delete(args): """Deletes the jobs from the job manager. If the jobs are still running in the grid, they are stopped.""" jm = setup(args) # first, stop the jobs if they are running in the grid if not args.local and 'executing' in args.status: stop(args) # then, delete them from the database jm.delete(job_ids=get_ids...
def run_job(args): """Starts the wrapper script to execute a job, interpreting the JOB_ID and SGE_TASK_ID keywords that are set by the grid or by us.""" jm = setup(args) job_id = int(os.environ['JOB_ID']) array_id = int(os.environ['SGE_TASK_ID']) if os.environ['SGE_TASK_ID'] != 'undefined' else None jm.run_job(job_id, ...
def with_random_weights(cls, options): """ Initialize from a list of options with random weights. The weights assigned to each object are uniformally random integers between ``1`` and ``len(options)`` Args: options (list): The list of options of any type this object can return with the ``get()`` method. Returns: SoftOp...
def bounded_uniform(cls, lowest, highest, weight_interval=None): """ Initialize with a uniform distribution between two values. If no ``weight_interval`` is passed, this weight distribution will just consist of ``[(lowest, 1), (highest, 1)]``. If specified, weights (still with uniform weight distribution) will be added...
def rgb_to_hex(cls, color): """ Convert an ``(r, g, b)`` color tuple to a hexadecimal string. Alphabetical characters in the output will be capitalized. Args: color (tuple): An rgb color tuple of form: (int, int, int) Returns: string Example: >>> SoftColor.rgb_to_hex((0, 0, 0)) '#000000' >>> SoftColor.rgb_to_hex((255, ...
def get(self): """ Get an rgb color tuple according to the probability distribution. Returns: tuple(int, int, int): A ``(red, green, blue)`` tuple. Example: >>> color = SoftColor(([(0, 1), (255, 10)],), ... ([(0, 1), (255, 10)],), ... ([(0, 1), (255, 10)],)) >>> color.get() # doctest: +SKIP (234, 201, 243) """ if isins...
def grow(files: hug.types.multiple, in_ext: hug.types.text="short", out_ext: hug.types.text="html", out_dir: hug.types.text="", recursive: hug.types.smart_boolean=False): """Grow up your markup""" if files == ['-']: print(text(sys.stdin.read())) return print(INTRO) if recursive: files = iter_source_code(files, in_ext) ...
def read_csv_arg_preprocess(abspath, memory_usage=100 * 1000 * 1000): """Automatically decide if we need to use iterator mode to read a csv file. :param abspath: csv file absolute path. :param memory_usage: max memory will be used for pandas.read_csv(). """ if memory_usage < 1000 * 1000: raise ValueError("Please specif...
def to_prettytable(df): """Convert DataFrame into ``PrettyTable``. """ pt = PrettyTable() pt.field_names = df.columns for tp in zip(*(l for col, l in df.iteritems())): pt.add_row(tp) return pt
def cli(): """\ Frogsay generates an ASCII picture of a FROG spouting a FROG tip. FROG tips are fetched from frog.tips's API endpoint when needed, otherwise they are cached locally in an application-specific folder. """ with open_client(cache_dir=get_cache_dir()) as client: tip = client.frog_tip() terminal_width = clic...
def verify_document(self, document: Document) -> bool: """ Check specified document :param duniterpy.documents.Document document: :return: """ signature = base64.b64decode(document.signatures[0]) prepended = signature + bytes(document.raw(), 'ascii') try: self.verify(prepended) return True except ValueError: return Fal...
def verify_ws2p_head(self, head: Any) -> bool: """ Check specified document :param Any head: :return: """ signature = base64.b64decode(head.signature) inline = head.inline() prepended = signature + bytes(inline, 'ascii') try: self.verify(prepended) return True except ValueError: return False
def parse_spss_headerfile(path, **kwargs): """ Parse spss header file Arguments: path {str} -- path al fichero de cabecera. leyend_position -- posicion del la leyenda en el header. """ headers_clean = {} try: with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_: raw_file = file_.read() raw_splited = ...
def parse_spss_datafile(path, **kwargs): """ Parse spss data file Arguments: path {str} -- path al fichero de cabecera. **kwargs {[dict]} -- otros argumentos que puedan llegar """ data_clean = [] with codecs.open(path, 'r', kwargs.get('encoding', 'latin-1')) as file_: raw_file = file_.read() data_clean = raw_file.split...
def pdf_to_text(pdf_filepath='', **kwargs): """ Parse pdf to a list of strings using the pdfminer lib. Args: no_laparams=False, all_texts=None, detect_vertical=None, word_margin=None, char_margin=None, line_margin=None, boxes_flow=None, codec='utf-8', strip_control=False, maxpages=0, page_numbers=None, password="", sca...
def pdf_row_limiter(rows, limits=None, **kwargs): """ Limit row passing a value. In this case we dont implementate a best effort algorithm because the posibilities are infite with a data text structure from a pdf. """ limits = limits or [None, None] upper_limit = limits[0] if limits else None lower_limit = limits[1] if...
def pdf_to_dict(pdf_filepath, **kwargs): """ Main method to parse a pdf file to a dict. """ callbacks = { 'pdf_to_text': pdf_to_text, 'pdf_row_format': pdf_row_format, 'pdf_row_limiter': pdf_row_limiter, 'pdf_row_parser': pdf_row_parser, 'pdf_row_cleaner': pdf_row_cleaner } callbacks.update(kwargs.get('alt_callbacks', ...
def stashed(func): """ Simple decorator to stash changed files between a destructive repo operation """ @functools.wraps(func) def _wrapper(*args, **kwargs): if CTX.stash and not CTX.repo.stashed: CTX.repo.stash(func.__name__) try: func(*args, **kwargs) finally: CTX.repo.unstash() else: func(*args, **kwargs) return _wr...
def dynamic_load(name): """Equivalent of "from X import Y" statement using dot notation to specify what to import and return. For example, foo.bar.thing returns the item "thing" in the module "foo.bar" """ pieces = name.split('.') item = pieces[-1] mod_name = '.'.join(pieces[:-1]) mod = __import__(mod_name, globals(), ...
def list_to_rows(src, size): """A generator that takes a enumerable item and returns a series of slices. Useful for turning a list into a series of rows. >>> list(list_to_rows([1, 2, 3, 4, 5, 6, 7], 3)) [[1, 2, 3], [4, 5, 6], [7, ]] """ row = [] for item in src: row.append(item) if len(row) == size: yield row row = [] ...
def head_tail_middle(src): """Returns a tuple consisting of the head of a enumerable, the middle as a list and the tail of the enumerable. If the enumerable is 1 item, the middle will be empty and the tail will be None. >>> head_tail_middle([1, 2, 3, 4]) 1, [2, 3], 4 """ if len(src) == 0: return None, [], None if len(s...
def calcemissions(rates: xarray.DataArray, sim) -> Tuple[xarray.DataArray, np.ndarray, np.ndarray]: if not sim.reacreq: return 0., 0., 0. ver = None lamb = None br = None """ Franck-Condon factor http://chemistry.illinoisstate.edu/standard/che460/handouts/460-Feb28lec-S13.pdf http://assign3.chem.usyd.edu.au/spectroscop...
in sim.reacreq: ver, lamb, br = getN21PG(rates, ver, lamb, br, sim.reactionfn) # %% Remove NaN wavelength entries if ver is None: raise ValueError('you have not selected any reactions to generate VER') # %% sort by wavelength, eliminate NaN lamb, ver, br = sortelimlambda(lamb, ver, br) # %% assemble output dfver = xarr...
def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path): with h5py.File(reactfn, 'r') as f: A = f['/metastable/A'][:] lambnew = f['/metastable/lambda'].value.ravel(order='F') # some are not 1-D! """ concatenate along the reaction dimension, axis=-1 """ vnew = np.concatenate((A[:2] * rates.loc[..., 'no1s'].va...
def getAtomic(rates, ver, lamb, br, reactfn): """ prompt atomic emissions (nm) 844.6 777.4 """ with h5py.File(reactfn, 'r') as f: lambnew = f['/atomic/lambda'].value.ravel(order='F') # some are not 1-D! vnew = np.concatenate((rates.loc[..., 'po3p3p'].values[..., None], rates.loc[..., 'po3p5p'].values[..., None]), axis=...
def getN21NG(rates, ver, lamb, br, reactfn): """ excitation Franck-Condon factors (derived from Vallance Jones, 1974) """ with h5py.File(str(reactfn), 'r', libver='latest') as f: A = f['/N2+1NG/A'].value lambdaA = f['/N2+1NG/lambda'].value.ravel(order='F') franckcondon = f['/N2+1NG/fc'].value return doBandTrapz(A, lamb...
def getN21PG(rates, ver, lamb, br, reactfn): with h5py.File(str(reactfn), 'r', libver='latest') as fid: A = fid['/N2_1PG/A'].value lambnew = fid['/N2_1PG/lambda'].value.ravel(order='F') franckcondon = fid['/N2_1PG/fc'].value tau1PG = 1 / np.nansum(A, axis=1) """ solve for base concentration confac=[1.66;1.56;1.31;1.07;...
def doBandTrapz(Aein, lambnew, fc, kin, lamb, ver, z, br): """ ver dimensions: wavelength, altitude, time A and lambda dimensions: axis 0 is upper state vib. level (nu') axis 1 is bottom state vib level (nu'') there is a Franck-Condon parameter (variable fc) for each upper state nu' """ tau = 1/np.nansum(Aein, axis=1) ...
def catvl(z, ver, vnew, lamb, lambnew, br): """ trapz integrates over altitude axis, axis = -2 concatenate over reaction dimension, axis = -1 br: column integrated brightness lamb: wavelength [nm] ver: volume emission rate [photons / cm^-3 s^-3 ...] """ if ver is not None: br = np.concatenate((br, np.trapz(vnew, z, axi...
def uconf(**kwargs): """ Function to set a default namespace/include. It returns a decorator with the namespace/include argument already set. Arguments: - include: A custom URL list, previously set on the module's urls.py; - namespace: the URL's namespace. """ if len(kwargs) != 1: # this function must have exactly # on...
def pep8(amend: bool = False, stage: bool = False): """ Runs Pyup's Safety tool (https://pyup.io/safety/) Args: amend: whether or not to commit results stage: whether or not to stage changes """ _pep8(amend, stage)
def searchTag(self,HTAG="#arenaNETmundial"): """Set Twitter search or stream criteria for the selection of tweets""" search = t.search(q=HTAG,count=100,result_type="recent") ss=search[:] search = t.search(q=HTAG,count=150,max_id=ss[-1]['id']-1,result_type="recent") #search = t.search(q=HTAG,count=150,since_id=ss[-1]['i...
def download(self, url, dest_path=None): """ :param url: :type url: str :param dest_path: :type dest_path: str """ if os.path.exists(dest_path): os.remove(dest_path) resp = get(url, stream=True) size = int(resp.headers.get("content-length")) label = "Downloading {filename} ({size:.2f}MB)".format( filename=os.path.basen...
def upload(self, url, method="POST", file_path=None): """ :param url: :type url: str :param method: :type method: str :param file_path: :type file_path: str """ if not os.path.exists(file_path): raise RuntimeError("") with open_file(file_path, 'rb') as file: size = os.path.getsize(file_path) label = "Uploading {filenam...
def do_tail(self,args): """Tail the logs""" response = AwsConnectionFactory.getLogClient().get_log_events( logGroupName=self.logStream['logGroupName'], logStreamName=self.logStream['logStreamName'], limit=10, startFromHead=False ) pprint(response)
def get_local_filepath(filename): """ Helper for finding our raw SQL files locally. Expects files to be in: $SOCORRO_PATH/socorrolib/external/postgresql/raw_sql/procs/ """ procs_dir = os.path.normpath(os.path.join( __file__, '../../', 'external/postgresql/raw_sql/procs' )) return os.path.join(procs_dir, filename)
def load_stored_proc(op, filelist): """ Takes the alembic op object as arguments and a list of files as arguments Load and run CREATE OR REPLACE function commands from files """ for filename in filelist: sqlfile = get_local_filepath(filename) # Capturing "file not exists" here rather than allowing # an exception to be ...
def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" exctype, value = exc_info[:2] # On Python 2.4, it will be OSError ...
def display_path(path): """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if path.startswith(os.getcwd() + os.path.sep): path = '.' + path[len(os.getcwd()):] return path
def get_pathext(default_pathext=None): """Returns the path extensions from environment or a default""" if default_pathext is None: default_pathext = os.pathsep.join([ '.COM', '.EXE', '.BAT', '.CMD' ]) pathext = os.environ.get('PATHEXT', default_pathext) return pathext
def ask(message, options): """Ask the message interactively, with the given possible responses""" while 1: if os.environ.get('PIP_NO_INPUT'): raise Exception('No input was expected ($PIP_NO_INPUT set); question: %s' % message) response = raw_input(message) response = response.strip().lower() if response not in options:...
def get_installed_distributions(local_only=True, skip=('setuptools', 'pip', 'python')): """ Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to...
def dist_location(dist): """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. """ egg_link = egg_link_path(dist) if os.path.exists(egg_l...
def unzip_file(filename, location, flatten=True): """Unzip the file (zip file located at filename) to the destination location""" if not os.path.exists(location): os.makedirs(location) zipfp = open(filename, 'rb') try: zip = zipfile.ZipFile(zipfp) leading = has_leading_dir(zip.namelist()) and flatten for name in zip.na...
def untar_file(filename, location): """Untar the file (tar file located at filename) to the destination location""" if not os.path.exists(location): os.makedirs(location) if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'): mode = 'r:gz' elif filename.lower().endswith('.bz2') or filename.lower().en...
# (specifically bad symlinks) logger.warn( 'In the tar file %s the member %s is invalid: %s' % (filename, member.name, e)) continue if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) destfp = open(path, 'wb') try: shutil.copyfileobj(fp, destfp) finally: destfp.close() fp.close() finally: t...
def _value_properties_are_referenced(val): """ val is a dictionary :param val: :return: True/False """ if ((u'properties' in val.keys()) and (u'$ref' in val['properties'].keys())): return True return False
def _value_is_type_text(val): """ val is a dictionary :param val: :return: True/False """ if ((u'type' in val.keys()) and (val['type'].lower() == u"text")): return True return False
def _has_desired_permit(permits, acategory, astatus): """ return True if permits has one whose category_code and status_code match with the given ones """ if permits is None: return False for permit in permits: if permit.category_code == acategory and\ permit.status_code == astatus: return True return False
def __compact_notification_addresses(addresses_): """ Input:: { 'default': 'http://domain/notice', 'event1': 'http://domain/notice', 'event2': 'http://domain/notice', 'event3': 'http://domain/notice3', 'event4': 'http://domain/notice3' } Output:: { 'default': 'http://domain/notice', 'event1,event2': 'http://domain/noti...
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script o...
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ alembic_config = config.get_section(config.config_ini_section) alembic_config['sqlalchemy.url'] = os.environ['DATABASE_URI'] connectable = engine_from_config( al...
def makeRetweetNetwork(tweets): """Receives tweets, returns directed retweet networks. Without and with isolated nodes. """ G=x.DiGraph() G_=x.DiGraph() for tweet in tweets: text=tweet["text"] us=tweet["user"]["screen_name"] if text.startswith("RT @"): prev_us=text.split(":")[0].split("@")[1] #print(us,prev_us,text) if...
def makeNetwork(self): """Makes graph object from .gdf loaded data""" if "weight" in self.data_friendships.keys(): self.G=G=x.DiGraph() else: self.G=G=x.Graph() F=self.data_friends for friendn in range(self.n_friends): if "posts" in F.keys(): G.add_node(F["name"][friendn], label=F["label"][friendn], posts=F["posts"][fr...
def downlad_file(url, fname): """Download file from url and save as fname.""" print("Downloading {} as {}".format(url, fname)) response = urlopen(url) download = response.read() with open(fname, 'wb') as fh: fh.write(download)
def unzip_file(zip_fname): """Unzip the zip_fname in the current directory.""" print("Unzipping {}".format(zip_fname)) with zipfile.ZipFile(zip_fname) as zf: zf.extractall()
def install_from_zip(url): """Download and unzip from url.""" fname = 'tmp.zip' downlad_file(url, fname) unzip_file(fname) print("Removing {}".format(fname)) os.unlink(fname)
def main(args=None): """The main routine.""" if args is None: args = sys.argv[1:] parser = argparse.ArgumentParser( description='Makes UCL PHAS results better') parser.add_argument('--input', '-i', type=str, help="csv file to import") parser.add_argument('--format', '-f', type=str, help="reformats results by module and...
def phys_name(self, item: str) -> str: """Return the physical (mapped) name of item. :param item: logical table name :return: physical name of table """ v = self.__dict__[item] return v if v is not None else item
def all_tables(self) -> List[str]: """ List of all known tables :return: """ return sorted([k for k in self.__dict__.keys() if k not in _I2B2Tables._funcs and not k.startswith("_")])
def system_status(): # noqa: E501 """Retrieve the system status Retrieve the system status # noqa: E501 :rtype: Response """ if(not hasAccess()): return redirectUnauthorized() body = State.config.serialize(["driver", "log", "log-file", "log-colorize"]) body.update({'debug': State.options.debug, 'sensitive': State.optio...
def login_server(self): """ Login to server """ local('ssh -i {0} {1}@{2}'.format( env.key_filename, env.user, env.host_string ))