code
stringlengths
1
18.2k
def get_request(self, url): """ Wraps the URL to retrieve to protects against "creative" interpretation of the RFC: http://bugs.python.org/issue8732 """ if isinstance(url, string_types): url = urllib2.Request(url, headers={'Accept-encoding': 'identity'}) return url
def get_response(self, url, username=None, password=None): """ does the dirty work of actually getting the rsponse object using urllib2 and its HTTP auth builtins. """ scheme, netloc, path, query, frag = urlparse.urlsplit(url) req = self.get_request(url) stored_username, stored_password = self.passman.find_user_passwor...
def setup(self, proxystr='', prompting=True): """ Sets the proxy handler given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ self.prompting = prompting proxy = self.get_proxy(proxystr) if proxy: proxy_support = urllib2.ProxyHandler({"http": prox...
def extract_credentials(self, url): """ Extracts user/password from a url. Returns a tuple: (url-without-auth, username, password) """ if isinstance(url, urllib2.Request): result = urlparse.urlsplit(url.get_full_url()) else: result = urlparse.urlsplit(url) scheme, netloc, path, query, frag = result username, password =...
def get_proxy(self, proxystr=''): """ Get the proxy given the option passed on the command line. If an empty string is passed it looks at the HTTP_PROXY environment variable. """ if not proxystr: proxystr = os.environ.get('HTTP_PROXY', '') if proxystr: if '@' in proxystr: user_password, server_port = proxystr.split('@'...
def pageassert(func): ''' Decorator that assert page number ''' @wraps(func) def wrapper(*args, **kwargs): if args[0] < 1 or args[0] > 40: raise ValueError('Page Number not found') return func(*args, **kwargs) return wrapper
def do_mfa(self, args): """ Enter a 6-digit MFA token. Nephele will execute the appropriate `aws` command line to authenticate that token. mfa -h for more details """ parser = CommandArgumentParser("mfa") parser.add_argument(dest='token',help='MFA token value'); parser.add_argument("-p","--profile",dest='awsProfile',de...
def do_up(self,args): """ Navigate up by one level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `up` will place you in `(aws)/stack:.../`. up -h for more details """ parser = CommandArgumentParser("up") args = vars(parser.parse_args(args)) if None == self.parent: print "You're at the root. Try 'qui...
def do_slash(self,args): """ Navigate back to the root level. For example, if you are in `(aws)/stack:.../asg:.../`, executing `slash` will place you in `(aws)/`. slash -h for more details """ parser = CommandArgumentParser("slash") args = vars(parser.parse_args(args)) if None == self.parent: print "You're at the root....
def do_profile(self,args): """ Select nephele profile profile -h for more details """ parser = CommandArgumentParser("profile") parser.add_argument(dest="profile",help="Profile name") parser.add_argument('-v','--verbose',dest="verbose",action='store_true',help='verbose') args = vars(parser.parse_args(args)) profile = a...
def do_config(self,args): """ Deal with configuration. Available subcommands: * config print - print the current configuration * config reload - reload the current configuration from disk * config set - change a setting in the configuration * config save - save the configuration to disk config -h for more details """ p...
def parse(timestring): """Convert a statbank time string to a python datetime object. """ for parser in _PARSERS: match = parser['pattern'].match(timestring) if match: groups = match.groups() ints = tuple(map(int, groups)) time = parser['factory'](ints) return time raise TimeError('Unsupported time format {}'.format(ti...
def confirm(text, default=True): """ Console confirmation dialog based on raw_input. """ if default: legend = "[y]/n" else: legend = "y/[n]" res = "" while (res != "y") and (res != "n"): res = raw_input(text + " ({}): ".format(legend)).lower() if not res and default: res = "y" elif not res and not default: res = "n" if...
def read_file(fname): """ Read file, convert wildcards into regular expressions, skip empty lines and comments. """ res = [] try: with open(fname, 'r') as f: for line in f: line = line.rstrip('\n').rstrip('\r') if line and (line[0] != '#'): regexline = ".*" + re.sub("\*", ".*", line) + ".*" res.append(regexline.lower()...
def drop_it(title, filters, blacklist): """ The found torrents should be in filters list and shouldn't be in blacklist. """ title = title.lower() matched = False for f in filters: if re.match(f, title): matched = True if not matched: return True for b in blacklist: if re.match(b, title): return True return False
def do_list(): """ CLI action "list configurations". """ dirs = os.walk(CONFIG_ROOT).next()[1] if dirs: print "List of available configurations:\n" for d in dirs: print " * {}".format(d) else: print "No configurations available."
def do_create(config, config_dir): """ CLI action "create new configuration". """ if os.path.exists(config_dir): print "Configuration '{}' already exists.".format(config) exit(1) os.makedirs(config_dir) print "Configuration directory created." url = raw_input("RSS URL for processing []: ") torrent_dir = raw_input("Outp...
"{} {} -e {}".format(sys.executable, os.path.abspath(__file__), config) job = ct.new(command=cmd) job.minute.every(update_interval) job.enable() ct.write() print "Crontab updated." print "Config '{}' has been saved.".format(config)
def do_update(config, config_dir): """ CLI action "update new configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) config_file = os.path.join(config_dir, 'config') with open(config_file, 'r') as f: old_config_data = json.load(f) old_url = old_config_da...
}, sort_keys=True, indent=4, separators=(',', ': ')) with open(config_file, 'w') as f: f.write(config_data) ct = CronTab(user=True) for job in ct: if re.match('.*ghetto.*\-e\s{}'.format(config), job.command): ct.remove(job) cmd = "{} {} -e {}".format(sys.executable, os.path.abspath(__file__), config) new_job = ct.new(c...
def do_remove(config, config_dir): """ CLI action "remove configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) if confirm("Confirm removal of the configuration '{}'".format(config)): shutil.rmtree(config_dir) print "Configuration '{}' has been removed....
def do_exec(config, config_dir): """ CLI action "process the feed from specified configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) print "The parser for '{}' config has been initialized.".format(config) config_file = os.path.join(config_dir, 'config...
with open(target_file, 'wb') as f: for chunk in r.iter_content(4096): f.write(chunk) print "Items found: {}, items downloaded: {}."\ .format(len(items), downloaded)
def do_filter(config, config_dir): """ CLI action "run editor for filters list". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_filter = os.path.join(config_dir, 'filter') call([editor, config_filter]) print "Filter configura...
def do_blacklist(config, config_dir): """ CLI action "run editor for blacklist". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) editor = os.environ["EDITOR"] config_blacklist = os.path.join(config_dir, 'blacklist') call([editor, config_blacklist]) print "Blackli...
def action(act, config): """ CLI action preprocessor """ if not config: pass elif act is "list": do_list() else: config_dir = os.path.join(CONFIG_ROOT, config) globals()["do_" + act](config, config_dir)
def is_discrete(self): """ Return whether this space is discrete """ for domain in self.domains.values(): if not domain.is_discrete(): return False return True
def consistent(self,lab): """ Check whether the labeling is consistent with all constraints """ for const in self.constraints: if not const.consistent(lab): return False return True
def satisfied(self,lab): """ Check whether the labeling satisfies all constraints """ for const in self.constraints: if not const.satisfied(lab): return False return True
def from_inline(cls: Type[MembershipType], version: int, currency: str, membership_type: str, inline: str) -> MembershipType: """ Return Membership instance from inline format :param version: Version of the document :param currency: Name of the currency :param membership_type: "IN" or "OUT" to enter or exit membership ...
def from_signed_raw(cls: Type[MembershipType], signed_raw: str) -> MembershipType: """ Return Membership instance from signed raw format :param signed_raw: Signed raw format string :return: """ lines = signed_raw.splitlines(True) n = 0 version = int(Membership.parse_field("Version", lines[n])) n += 1 Membership.parse_f...
def raw(self) -> str: """ Return signed raw format string of the Membership instance :return: """ return """Version: {0} Type: Membership Currency: {1} Issuer: {2} Block: {3} Membership: {4} UserID: {5} CertTS: {6} """.format(self.version, self.currency, self.issuer, self.membership_ts, self.membership_type, self.uid, ...
def inline(self) -> str: """ Return inline string format of the Membership instance :return: """ return "{0}:{1}:{2}:{3}:{4}".format(self.issuer, self.signatures[0], self.membership_ts, self.identity_ts, self.uid)
def is_subsumed_by(x, y): """ Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more abstract) """ varsX = __split_expression(x)[1] theta = unify(x, y) if theta is problem.FAILURE: return False return all(__is_variable(theta[var]) for var in theta.keys() if var in varsX)
def _do_request(self, url, params=None, data=None, headers=None): """ Realiza as requisições diversas utilizando a biblioteca requests, tratando de forma genérica as exceções. """ if not headers: headers = {'content-type': 'application/json'} try: response = requests.get( url, params=params, data=data, headers=headers)...
def update_document_indicators(self, doc_id, citations, accesses): """ Atualiza os indicadores de acessos e citações de um determinado doc_id. exemplo de doc_id: S0021-25712009000400007-spa """ headers = {'content-type': 'application/json'} data = { "add": { "doc": { "id": doc_id } } } if citations: data['add']['doc'][...
def _commit(self): """ Envia requisição de commit do indice através da API. """ params = {'commit': 'true'} response = self._do_request( self.UPDATE_ENDPOINT, params=params ) if response and response.status_code == 200: logger.debug('Index commited') return None logger.warning('Fail to commite index')
def make_basic_daemon(workspace=None): """Make basic daemon. """ workspace = workspace or os.getcwd() # first fork if os.fork(): os._exit(0) # change env os.chdir(workspace) os.setsid() os.umask(0o22) # second fork if os.fork(): os._exit(0) # reset stdin/stdout/stderr to /dev/null null = os.open('/dev/null', os.O_RDWR)...
def process_kill(pid, sig=None): """Send signal to process. """ sig = sig or signal.SIGTERM os.kill(pid, sig)
def load_pid(pidfile): """read pid from pidfile. """ if pidfile and os.path.isfile(pidfile): with open(pidfile, "r", encoding="utf-8") as fobj: return int(fobj.readline().strip()) return 0
def write_pidfile(pidfile): """write current pid to pidfile. """ pid = os.getpid() if pidfile: with open(pidfile, "w", encoding="utf-8") as fobj: fobj.write(six.u(str(pid))) return pid
def is_running(pid): """check if the process with given pid still running """ process = get_process(pid) if process and process.is_running() and process.status() != "zombie": return True else: return False
def clean_pid_file(pidfile): """clean pid file. """ if pidfile and os.path.exists(pidfile): os.unlink(pidfile)
def daemon_start(main, pidfile, daemon=True, workspace=None): """Start application in background mode if required and available. If not then in front mode. """ logger.debug("start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.".format(pidfile=pidfile, daemon=daemon, workspace=workspace)) ne...
def daemon_stop(pidfile, sig=None): """Stop application. """ logger.debug("stop daemon application pidfile={pidfile}.".format(pidfile=pidfile)) pid = load_pid(pidfile) logger.debug("load pid={pid}".format(pid=pid)) if not pid: six.print_("Application is not running or crashed...", file=os.sys.stderr) os.sys.exit(195) p...
def is_dicom(filename): '''returns Boolean of whether the given file has the DICOM magic number''' try: with open(filename) as f: d = f.read(132) return d[128:132]=="DICM" except: return False
def info(filename): '''returns a DicomInfo object containing the header information in ``filename``''' try: out = subprocess.check_output([_dicom_hdr,'-sexinfo',filename]) except subprocess.CalledProcessError: return None slice_timing_out = subprocess.check_output([_dicom_hdr,'-slice_times',filename]) slice_timing = [f...
def info_for_tags(filename,tags): '''return a dictionary for the given ``tags`` in the header of the DICOM file ``filename`` ``tags`` is expected to be a list of tuples that contains the DICOM address in hex values. basically a rewrite of :meth:`info` because it's so slow. This is a lot faster and more reliable''' if i...
def scan_dir(dirname,tags=None,md5_hash=False): '''scans a directory tree and returns a dictionary with files and key DICOM tags return value is a dictionary absolute filenames as keys and with dictionaries of tags/values as values the param ``tags`` is the list of DICOM tags (given as tuples of hex numbers) that will ...
(0x0028, 0x0010), (0x0028, 0x0011), ] return_dict = {} for root,dirs,files in os.walk(dirname): for filename in files: fullname = os.path.join(root,filename) if is_dicom(fullname): return_dict[fullname] = info_for_tags(fullname,tags) if md5_hash: return_dict[fullname]['md5'] = nl.hash(fullname) return return_dict
def find_dups(file_dict): '''takes output from :meth:`scan_dir` and returns list of duplicate files''' found_hashes = {} for f in file_dict: if file_dict[f]['md5'] not in found_hashes: found_hashes[file_dict[f]['md5']] = [] found_hashes[file_dict[f]['md5']].append(f) final_hashes = dict(found_hashes) for h in found_has...
def cluster_files(file_dict): '''takes output from :meth:`scan_dir` and organizes into lists of files with the same tags returns a dictionary where values are a tuple of the unique tag combination and values contain another dictionary with the keys ``info`` containing the original tag dict and ``files`` containing a li...
def max_diff(dset1,dset2): '''calculates maximal voxel-wise difference in datasets (in %) Useful for checking if datasets have the same data. For example, if the maximum difference is < 1.0%, they're probably the same dataset''' for dset in [dset1,dset2]: if not os.path.exists(dset): nl.notify('Error: Could not find fi...
def create_dset_to3d(prefix,file_list,file_order='zt',num_slices=None,num_reps=None,TR=None,slice_order='alt+z',only_dicoms=True,sort_filenames=False): '''manually create dataset by specifying everything (not recommended, but necessary when autocreation fails) If `num_slices` or `num_reps` is omitted, it will be inferr...
actually have image information new_file_list.append(f) file_list = new_file_list if sort_filenames: def file_num(fname): try: nums = [x.strip('.') for x in re.findall(r'[\d.]+',fname) if x.strip('.')!=''] return float(nums[-1]) except: return fname file_list = sorted(file_list,key=file_num) if len(file_list)==0: nl.no...
cmd += ['-time:%s'%file_order] if file_order=='zt': cmd += [num_slices,num_reps] else: cmd += [num_reps,num_slices] cmd += [TR,slice_order] cmd += ['-@'] cmd = [str(x) for x in cmd] out = None try: p = subprocess.Popen(cmd,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) out = p.communicate('\n'.joi...
def create_dset(directory,slice_order='alt+z',sort_order='zt',force_slices=None): '''tries to autocreate a dataset from images in the given directory''' return _create_dset_dicom(directory,slice_order,sort_order,force_slices=force_slices)
def date_for_str(date_str): '''tries to guess date from ambiguous date string''' try: for date_format in itertools.permutations(['%Y','%m','%d']): try: date = datetime.strptime(date_str,''.join(date_format)) raise StopIteration except ValueError: pass return None except StopIteration: return date
def organize_dir(orig_dir): '''scans through the given directory and organizes DICOMs that look similar into subdirectories output directory is the ``orig_dir`` with ``-sorted`` appended to the end''' tags = [ (0x10,0x20), # Subj ID (0x8,0x21), # Date (0x8,0x31), # Time (0x8,0x103e) # Descr ] orig_dir = orig_dir.rstrip...
os.makedirs(run_dir) except IOError: nl.notify('Error: failed to create directory %s' % run_dir) else: for f in clustered[key]['files']: try: dset_fname = os.path.split(f)[1] if dset_fname[0]=='.': dset_fname = '_' + dset_fname[1:] os.rename(f,os.path.join(run_dir,dset_fname)) except (IOError, OSError): pass for r,ds,f...
def classify(label_dict,image_fname=None,image_label=None): '''tries to classify a DICOM image based on known string patterns (with fuzzy matching) Takes the label from the DICOM header and compares to the entries in ``label_dict``. If it finds something close it will return the image type, otherwise it will return ``N...
i in j] best_match = process.extractOne(image_label,[x[1] for x in flat_dict]) if best_match[1]<min_acceptable_match: return None else: return [x[0] for x in flat_dict if x[1]==best_match[0]][0]
def reconstruct_files(input_dir): '''sorts ``input_dir`` and tries to reconstruct the subdirectories found''' input_dir = input_dir.rstrip('/') with nl.notify('Attempting to organize/reconstruct directory'): # Some datasets start with a ".", which confuses many programs for r,ds,fs in os.walk(input_dir): for f in fs: i...
def unpack_archive(fname,out_dir): '''unpacks the archive file ``fname`` and reconstructs datasets into ``out_dir`` Datasets are reconstructed and auto-named using :meth:`create_dset`. The raw directories that made the datasets are archive with the dataset name suffixed by ``tgz``, and any other files found in the arch...
def addr(self,address): '''returns dictionary with frame information for given address (a tuple of two hex numbers)''' if isinstance(address,basestring): # If you just gave me a single string, assume its "XXXX XXXX" addr = address.split() else: addr = list(address) # Convert to actual hex if you give me strings for i i...
def static(cls): r"""Converts the given class into a static one, by changing all the methods of it into static methods. Args: cls (class): The class to be converted. """ for attr in dir(cls): im_func = getattr(getattr(cls, attr), 'im_func', None) if im_func: setattr(cls, attr, staticmethod(im_func)) return cls
def _generate_mark_code(rule_name): """Generates a two digit string based on a provided string Args: rule_name (str): A configured rule name 'pytest_mark3'. Returns: str: A two digit code based on the provided string '03' """ code = ''.join([i for i in str(rule_name) if i.isdigit()]) code = code.zfill(2) return code
def rule_n5xx(filename, rule_name, rule_conf, class_type): """Validate filename against a pattern if the filename passes the filter. Args: filename (str): The name of the file being parsed by flake8. rule_name (str): The name of the rule. rule_conf (dict): The dictionary containing the properties of the rule class_type...
def timeout(seconds=10, default_output='default_output'): """ function wrapper that limits the amount of time it has to run optional args: seconds - how long it has until the function times out default_output - what will be returned instead of an error """ def decorator(func): def _handle_timeout(signum, frame): """ th...
def triplifyGML(dpath="../data/fb/",fname="foo.gdf",fnamei="foo_interaction.gdf", fpath="./fb/",scriptpath=None,uid=None,sid=None,fb_link=None,ego=True,umbrella_dir=None): """Produce a linked data publication tree from a standard GML file. INPUTS: ====== => the data directory path => the file name (fname) of the friend...
c in fname)==4: year=re.findall(r".*(\d\d\d\d).gml",fname)[0][0] B.datetime_snapshot=datetime.date(*[int(i) for i in (year)]) if sum(c.isdigit() for c in fname)==12: day,month,year,hour,minute=re.findall(r".*(\d\d)(\d\d)(\d\d\d\d)_(\d\d)(\d\d).gml",fname)[0] B.datetime_snapshot=datetime.datetime(*[int(i) for i in (year...
def register(self, *args, **kwargs): ''' 调用方可根据主键字段进行爬虫的创建或更新操作 :return: 返回符合接口定义的字典数据 :rtype: dict ''' return { 'name': zhihu.name, 'display_name': zhihu.display_name, 'author': zhihu.author, 'email': zhihu.email, 'description': zhihu.description, 'meta': { # 爬取计划,参考 crontab 配置方法 'crawl_schedule': '0 23 * * *', # 执行爬取...
def crawl(self, *args, **kwargs): ''' 执行爬取操作,并阻塞直到爬取完成,返回结果数据。 此处考虑到 Scrapy 本身的并发特性,故通过临时文件方式做数据传递, 将临时路径传递到爬虫业务中,并在爬取结束后对文件进行读取、 JSON 反序列化,返回 :return: 返回符合接口定义的字典对象 :rtype: dict ''' temp = tempfile.NamedTemporaryFile(mode='w+t') try: crawler = CrawlerScript() # 调试时可指定明确日期参数,如:date='20180423' crawler.crawl(output_file=...
def format(self, data, *args, **kwargs): ''' 将传入的Post列表数据进行格式化处理。此处传入的 ``data`` 格式即为 :meth:`.ZhihuDaily.crawl` 返回的格式,但具体内容可以不同,即此处保留了灵活度, 可以对非当日文章对象进行格式化,制作相关主题的合集书籍 :param data: 待处理的文章列表 :type data: list :return: 返回符合mobi打包需求的定制化数据结构 :rtype: dict ''' sections = OrderedDict() hot_list = [] normal_list = [] for item in ...
def upsert_many(col, data): """ Only used when having "_id" field. **中文文档** 要求 ``data`` 中的每一个 ``document`` 都必须有 ``_id`` 项。这样才能进行 ``upsert`` 操作。 """ ready_to_insert = list() for doc in data: res = col.update({"_id": doc["_id"]}, {"$set": doc}, upsert=False) # 没有任何数据被修改, 且不是因为数据存在但值相同 if res["nModified"] == 0 and res["up...
def triplifyGML(fname="foo.gml",fpath="./fb/",scriptpath=None,uid=None,sid=None,extra_info=None): """Produce a linked data publication tree from a standard GML file. INPUTS: => the file name (fname, with path) where the gdf file of the friendship network is. => the final path (fpath) for the tree of files to be created...
datetime_snapshot=datetime.datetime(*[int(i) for i in (year,month,day)]).isoformat().split("T")[0] name_=" ".join(re.findall("[A-Z][^A-Z]*",name)) elif re.findall("[a-zA-Z]*_",fname): name,year,month,day,hour,minute=re.findall(".*/([a-zA-Z]*).*(\d\d\d\d)_(\d\d)_(\d\d)_(\d\d)_(\d\d).*.gml",fname)[0] datetime_snapshot=da...
NS.fb.agerank,NS.fb.wallcount] P.rdf.link([tg],ind, None,uris,data,draw=False) P.rdf.link_([tg],ind,None,[NS.po.snapshot],[snapshot],draw=False) #friends_=[fg2["friends"][i] for i in ("name","label","locale","sex","agerank")] #for name,label,locale,sex,agerank in zip(*friends_): # ind=P.rdf.IC([tg],P.rdf.ns.fb.Particip...
the script/ directory. Original data from Netvizz in data/\n""".format( name_,aname,datetime_snapshot, fg2.number_of_nodes(), "name, locale (maybe), sex, agerank and wallcount", fg2.number_of_edges()))
def triplifyGDFInteraction(fname="foo.gdf",fpath="./fb/",scriptpath=None,uid=None,sid=None,dlink=None): """Produce a linked data publication tree from GDF files of a Facebook interaction network. INPUTS: => the file name (fname, with path) where the gdf file of the friendship network is. => the final path (fpath) for t...
de agraph tg2=P.rdf.makeBasicGraph([["po"],[P.rdf.ns.per]],"Metadata for my facebook ego friendship network RDF files") # drop de agraph ind=P.rdf.IC([tg2],P.rdf.ns.po.Snapshot, aname,"Snapshot {}".format(aname)) foo={"uris":[],"vals":[]} if sid: foo["uris"].append(P.rdf.ns.fb.sid) foo["vals"].append(sid) if uid: foo["...
for uid1,uid2 in zip(*friendships_): flabel="{}-{}".format(uid1,uid2) labels=[name_label[uu] for uu in (uid1,uid2)] ind=P.rdf.IC([tg],P.rdf.ns.fb.Friendship, flabel) #flabel,"Friendship "+flabel) ind1=P.rdf.IC(None,P.rdf.ns.fb.Participant,uid1) ind2=P.rdf.IC(None,P.rdf.ns.fb.Participant,uid2) uids=[r.URIRef(P.rdf.ns.fb...
len(fg2["friendships"]["node1"]) ))
def getFriends(self,user_id="astronauta.mecanico",write=True): """Returns user_ids (that you have access) of the friends of your friend with user_ids""" while user_id not in self.browser.url: self.browser.visit("http://www.facebook.com/{}/friends".format(user_id), wait_time=3) #self.go("http://www.facebook.com/{}/frien...
def resolve(args): """Just print the result of parsing a target string.""" if not args: log.error('Exactly 1 argument is required.') app.quit(1) print(address.new(args[0]))
def build(args): """Build a target and its dependencies.""" if len(args) != 1: log.error('One target required.') app.quit(1) target = address.new(args[0]) log.info('Resolved target to: %s', target) try: bb = Butcher() bb.clean() bb.load_graph(target) bb.build(target) except (gitrepo.GitError, error.BrokenGraph, error.N...
def rebuild(args): """Rebuild a target and deps, even if it has been built and cached.""" if len(args) != 1: log.fatal('One target required.') app.quit(1) app.set_option('disable_cache_fetch', True) Butcher.options['cache_fetch'] = False build(args)
def dump(args): """Load the build graph for a target and dump it to stdout.""" if len(args) != 1: log.error('One target required.') app.quit(1) try: bb = Butcher() bb.load_graph(args[0]) except error.BrokenGraph as lolno: log.fatal(lolno) app.quit(1) print "Nodes:" pprint.pprint(bb.graph.node) print "Edges:" pprint.ppr...
def draw(args): """Load the build graph for a target and render it to an image.""" if len(args) != 2: log.error('Two arguments required: [build target] [output file]') app.quit(1) target = args[0] out = args[1] try: bb = Butcher() bb.load_graph(target) except error.BrokenGraph as lolno: log.fatal(lolno) app.quit(1) # F...
def stub_main(): """setuptools blah: it still can't run a module as a script entry_point""" from google.apputils import run_script_module import butcher.main run_script_module.RunScriptModule(butcher.main)
def setup_function(self): """Runs prior to the global main function.""" log.options.LogOptions.set_stderr_log_level('google:INFO') if app.get_options().debug: log.options.LogOptions.set_stderr_log_level('google:DEBUG') if not app.get_options().build_root: app.set_option('build_root', os.path.join( app.get_options().but...
def clean(self): """Clear the contents of the build area.""" if os.path.exists(self.buildroot): log.info('Clearing the build area.') log.debug('Deleting: %s', self.buildroot) shutil.rmtree(self.buildroot) os.makedirs(self.buildroot)
def paths_wanted(self): """The set of paths where we expect to find missing nodes.""" return set(address.new(b, target='all') for b in self.missing_nodes)
def missing_nodes(self): """The set of targets known as dependencies but not yet defined.""" missing = set() for target_addr, target_attrs in self.graph.node.items(): if 'target_obj' not in target_attrs: missing.add(target_addr) return missing
def load_buildfile(self, target): """Pull a build file from git.""" log.info('Loading: %s', target) filepath = os.path.join(target.path, app.get_options().buildfile_name) try: repo = self.repo_state.GetRepo(target.repo) return repo.get_file(filepath) except gitrepo.GitError as err: log.error('Failed loading %s: %s', ta...
def constructSpec(indentation, begin_block, end_block, begin_line, end_line, begin_action, end_action, begin_condition, end_condition, logical_and, logical_or): """Return a language specification based on parameters.""" return { INDENTATION : indentation, BEG_BLOCK : begin_block, END_BLOCK : end_block, BEG_LINE : begin...
def translated(structure, values, lang_spec): """Return code associated to given structure and values, translate with given language specification.""" # LANGUAGE SPECS indentation = '\t' endline = '\n' object_code = "" stack = [] # define shortcuts to behavior push = lambda x: stack.append(x) pop = lambda : stack.pop()...
# if provided, print the begin block token on a new line if len(lang_spec[BEG_BLOCK]) > 0: object_code += indented_code( lang_spec[BEG_BLOCK], level, lang_spec[END_LINE] ) stack = [] level += 1 # and place the action object_code += indented_code( lang_spec[BEG_ACTION] + values[0], level, lang_spec[END_ACTION]+lang_spec...
def cpp_spec(): """C++ specification, provided for example, and java compatible.""" return { INDENTATION : '\t', BEG_BLOCK : '{', END_BLOCK : '}', BEG_LINE : '', END_LINE : '\n', BEG_ACTION : '', END_ACTION : ';', BEG_CONDITION : 'if(', END_CONDITION : ')', LOGICAL_AND : ' && ', LOGICAL_OR : ' || ' }
def driver_send(command,hostname=None,wait=0.2): '''Send a command (or ``list`` of commands) to AFNI at ``hostname`` (defaults to local host) Requires plugouts enabled (open afni with ``-yesplugouts`` or set ``AFNI_YESPLUGOUTS = YES`` in ``.afnirc``) If ``wait`` is not ``None``, will automatically sleep ``wait`` second...