_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q43400
Dataset.dump_df
train
def dump_df(self, df, version=None, tags=None, ext=None, **kwargs): """Dumps an instance of this dataset into a file. Parameters ---------- df : pandas.DataFrame The dataframe to dump to file. version: str, optional The version of the instance of this dat...
python
{ "resource": "" }
q43401
Dataset.upload_df
train
def upload_df(self, df, version=None, tags=None, ext=None, **kwargs): """Dumps an instance of this dataset into a file and then uploads it to dataset store. Parameters ---------- df : pandas.DataFrame The dataframe to dump and upload. version: str, optional ...
python
{ "resource": "" }
q43402
BaseLoader._validate_extension
train
def _validate_extension(self): """Validates that source file extension is supported. :raises: UnsupportedExtensionError """ extension = self.fpath.split('.')[-1] if extension not in self.supported_extensions: raise UnsupportedExtensionError
python
{ "resource": "" }
q43403
BaseLoader._get_tags_and_content
train
def _get_tags_and_content(self, content: str) -> typing.Tuple[str, str]: """Splits content into two string - tags part and another content.""" content_lines = content.split('\n') tag_lines = [] if content_lines[0] != '---': return '', content content_lines.pop(0) ...
python
{ "resource": "" }
q43404
comp_listing
train
def comp_listing(request, directory_slug=None): """ Output the list of HTML templates and subdirectories in the COMPS_DIR """ context = {} working_dir = settings.COMPS_DIR if directory_slug: working_dir = os.path.join(working_dir, directory_slug) dirnames = [] templates = [] ...
python
{ "resource": "" }
q43405
comp
train
def comp(request, slug, directory_slug=None): """ View the requested comp """ context = {} path = settings.COMPS_DIR comp_dir = os.path.split(path)[1] template = "{0}/{1}".format(comp_dir, slug) if directory_slug: template = "{0}/{1}/{2}".format(comp_dir, directory_slug, slug) ...
python
{ "resource": "" }
q43406
export_comps
train
def export_comps(request): """ Returns a zipfile of the rendered HTML templates in the COMPS_DIR """ in_memory = BytesIO() zip = ZipFile(in_memory, "a") comps = settings.COMPS_DIR static = settings.STATIC_ROOT or "" context = RequestContext(request, {}) context['debug'] = False ...
python
{ "resource": "" }
q43407
Peer.from_signed_raw
train
def from_signed_raw(cls: Type[PeerType], raw: str) -> PeerType: """ Return a Peer instance from a signed raw format string :param raw: Signed raw format string :return: """ lines = raw.splitlines(True) n = 0 version = int(Peer.parse_field("Version", line...
python
{ "resource": "" }
q43408
generate_image_from_url
train
def generate_image_from_url(url=None, timeout=30): """ Downloads and saves a image from url into a file. """ file_name = posixpath.basename(url) img_tmp = NamedTemporaryFile(delete=True) try: response = requests.get(url, timeout=timeout) response.raise_for_status() except E...
python
{ "resource": "" }
q43409
is_rhyme
train
def is_rhyme(d, w1, w2): """check if words rhyme""" for p1 in d[w1]: # extract only "rhyming portion" p1 = p1.split("'")[-1] m = VOWELS_RE.search(p1) if not m: print(p1) p1 = p1[m.start():] for p2 in d[w2]: p2 = p2.split("'")[-1] ...
python
{ "resource": "" }
q43410
NestedLookup._nested_lookup
train
def _nested_lookup(document, references, operation): """Lookup a key in a nested document, yield a value""" if isinstance(document, list): for d in document: for result in NestedLookup._nested_lookup(d, references, operation): yield result if isin...
python
{ "resource": "" }
q43411
build_chunk
train
def build_chunk(oscillators): """ Build an audio chunk and progress the oscillator states. Args: oscillators (list): A list of oscillator.Oscillator objects to build chunks from Returns: str: a string of audio sample bytes ready to be written to a wave file """ step...
python
{ "resource": "" }
q43412
shell
train
def shell(database='default'): """Runs the command-line client for the specified database. """ target = engine[database] dialect = engine[database].dialect.name if dialect == 'mysql': args = ['mysql'] if target.url.username: args += ['--user=%s' % target.url.username] ...
python
{ "resource": "" }
q43413
parseprint
train
def parseprint(code, filename="<string>", mode="exec", **kwargs): """Parse some code from a string and pretty-print it.""" node = parse(code, mode=mode) # An ode to the code print(dump(node, **kwargs))
python
{ "resource": "" }
q43414
picknthweekday
train
def picknthweekday(year, month, dayofweek, hour, minute, whichweek): """dayofweek == 0 means Sunday, whichweek 5 means last instance""" first = datetime.datetime(year, month, 1, hour, minute) weekdayone = first.replace(day=((dayofweek-first.isoweekday())%7+1)) for n in range(whichweek): dt = wee...
python
{ "resource": "" }
q43415
colorstart
train
def colorstart(fgcolor, bgcolor, weight): ''' Begin a text style. ''' if weight: weight = bold else: weight = norm if bgcolor: out('\x1b[%s;%s;%sm' % (weight, fgcolor, bgcolor)) else: out('\x1b[%s;%sm' % (weight, fgcolor))
python
{ "resource": "" }
q43416
bargraph
train
def bargraph(data, maxwidth, incolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a monochrome or two-color bar graph. ''' threshold = 100.0 // (maxwidth * 2) # if smaller than 1/2 of one char wide position = 0 begpcnt = data[0][1] * 100 endpcnt = data[-1][1] * 100 if len(data) < 1: retu...
python
{ "resource": "" }
q43417
rainbar
train
def rainbar(data, maxwidth, incolor=True, hicolor=True, cbrackets=('\u2595', '\u258F')): ''' Creates a "rainbar" style bar graph. ''' if not data: return # Nada to do datalen = len(data) endpcnt = data[-1][1] maxwidth = maxwidth - 2 # because of brackets # setup ...
python
{ "resource": "" }
q43418
Config._set_linters
train
def _set_linters(self): """Use user linters or all available when not specified.""" if 'linters' in self._config: self.user_linters = list(self._parse_cfg_linters()) self.linters = {linter: self._all_linters[linter] for linter in self.user_linters} ...
python
{ "resource": "" }
q43419
Config.print_config
train
def print_config(self): """Print all yala configurations, including default and user's.""" linters = self.user_linters or list(self.linters) print('linters:', ', '.join(linters)) for key, value in self._config.items(): if key != 'linters': print('{}: {}'.forma...
python
{ "resource": "" }
q43420
Config._parse_cfg_linters
train
def _parse_cfg_linters(self): """Return valid linter names found in config files.""" user_value = self._config.get('linters', '') # For each line of "linters" value, use comma as separator for line in user_value.splitlines(): yield from self._parse_linters_line(line)
python
{ "resource": "" }
q43421
Config.get_linter_config
train
def get_linter_config(self, name): """Return linter options without linter name prefix.""" prefix = name + ' ' return {k[len(prefix):]: v for k, v in self._config.items() if k.startswith(prefix)}
python
{ "resource": "" }
q43422
Config._merge
train
def _merge(cls, default, user): """Append user options to default options. Return yala section.""" section = cls._CFG_SECTION merged = default[section] if section not in user: return merged user = user[section] for key, value in user.items(): if ...
python
{ "resource": "" }
q43423
as_text
train
def as_text(str_or_bytes, encoding='utf-8', errors='strict'): """Return input string as a text string. Should work for input string that's unicode or bytes, given proper encoding. >>> print(as_text(b'foo')) foo >>> b'foo'.decode('utf-8') == u'foo' True """ if isinstance(str_or_byte...
python
{ "resource": "" }
q43424
Recipe.attempt_dev_link_via_import
train
def attempt_dev_link_via_import(self, egg): """Create egg-link to FS location if an egg is found through importing. Sometimes an egg *is* installed, but without a proper egg-info file. So we attempt to import the egg in order to return a link anyway. TODO: currently it only works with ...
python
{ "resource": "" }
q43425
Clan._install_exception_handler
train
def _install_exception_handler(self): """ Installs a replacement for sys.excepthook, which handles pretty-printing uncaught exceptions. """ def handler(t, value, traceback): if self.args.verbose: sys.__excepthook__(t, value, traceback) else: ...
python
{ "resource": "" }
q43426
strip_encoding_cookie
train
def strip_encoding_cookie(filelike): """Generator to pull lines from a text-mode file, skipping the encoding cookie if it is found in the first two lines. """ it = iter(filelike) try: first = next(it) if not cookie_comment_re.match(first): yield first second = nex...
python
{ "resource": "" }
q43427
source_to_unicode
train
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffe...
python
{ "resource": "" }
q43428
decode_source
train
def decode_source(source_bytes): """Decode bytes representing source code and return the string. Universal newline support is used in the decoding. """ # source_bytes_readline = io.BytesIO(source_bytes).readline # encoding, _ = detect_encoding(source_bytes_readline) newline_decoder = io.Incremen...
python
{ "resource": "" }
q43429
cached
train
def cached(fn, size=32): ''' this decorator creates a type safe lru_cache around the decorated function. Unlike functools.lru_cache, this will not crash when unhashable arguments are passed to the function''' assert callable(fn) assert isinstance(size, int) return overload(fn)(lru_cache(size...
python
{ "resource": "" }
q43430
get_model
train
def get_model(app_dot_model): """ Returns Django model class corresponding to passed-in `app_dot_model` string. This is helpful for preventing circular-import errors in a Django project. Positional Arguments: ===================== - `app_dot_model`: Django's `<app_name>.<model_name>` syntax...
python
{ "resource": "" }
q43431
run_cmd
train
def run_cmd(cmd, log='log.log', cwd='.', stdout=sys.stdout, bufsize=1, encode='utf-8'): """ Runs a command in the backround by creating a new process and writes the output to a specified log file. :param log(str) - log filename to be used :param cwd(str) - basedir to write/create the log file :param stdout(p...
python
{ "resource": "" }
q43432
create
train
def create(output_dir): """Create a new collector or actor""" template_path = os.path.join(os.path.dirname(__file__), 'project_template') click.secho('Let\'s create a new component!', fg='green') name = click.prompt('What is the name of this component (ex. python-pip)?') click.secho('') click....
python
{ "resource": "" }
q43433
validate
train
def validate(text, file, schema_type): """Validate JSON input using dependencies-schema""" content = None if text: print('Validating text input...') content = text if file: print('Validating file input...') content = file.read() if content is None: click.se...
python
{ "resource": "" }
q43434
AlembicEnvBase.run
train
def run(self): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = engine_from_config( self._config.get_section(self._config.config_ini_section), prefix='...
python
{ "resource": "" }
q43435
_clean
train
def _clean(): """ Cleans up build dir """ LOGGER.info('Cleaning project directory...') folders_to_cleanup = [ '.eggs', 'build', f'{config.PACKAGE_NAME()}.egg-info', ] for folder in folders_to_cleanup: if os.path.exists(folder): LOGGER.info('\tremov...
python
{ "resource": "" }
q43436
tokenise
train
def tokenise(template): '''A generator which yields Token instances''' upto = 0 lineno = 0 for m in tag_re.finditer(template): start, end = m.span() lineno = template.count('\n', 0, start) + 1 # Humans count from 1 # If there's a gap between our start and the end of the last m...
python
{ "resource": "" }
q43437
delete
train
def delete(table, session, conds): """Performs a hard delete on a row, which means the row is deleted from the Savage table as well as the archive table. :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model of the user...
python
{ "resource": "" }
q43438
_format_response
train
def _format_response(rows, fields, unique_col_names): """This function will look at the data column of rows and extract the specified fields. It will also dedup changes where the specified fields have not changed. The list of rows should be ordered by the compound primary key which versioning pivots around ...
python
{ "resource": "" }
q43439
_get_conditions_list
train
def _get_conditions_list(table, conds, archive=True): """This function returns a list of list of == conditions on sqlalchemy columns given conds. This should be treated as an or of ands. :param table: the user table model class which inherits from savage.models.SavageModelMixin :param conds: a ...
python
{ "resource": "" }
q43440
_get_limit_and_offset
train
def _get_limit_and_offset(page, page_size): """Returns a 0-indexed offset and limit based on page and page_size for a MySQL query. """ if page < 1: raise ValueError('page must be >= 1') limit = page_size offset = (page - 1) * page_size return limit, offset
python
{ "resource": "" }
q43441
_get_order_clause
train
def _get_order_clause(archive_table): """Returns an ascending order clause on the versioned unique constraint as well as the version column. """ order_clause = [ sa.asc(getattr(archive_table, col_name)) for col_name in archive_table._version_col_names ] order_clause.append(sa.asc(archive...
python
{ "resource": "" }
q43442
add_resource_permissions
train
def add_resource_permissions(*args, **kwargs): """ This syncdb hooks takes care of adding a view permission too all our content types. """ # for each of our content types for resource in find_api_classes('v1_api', ModelResource): auth = resource._meta.authorization content_type = ContentType.object...
python
{ "resource": "" }
q43443
ObservableStore.areObservableElements
train
def areObservableElements(self, elementNames): """ Mention if all elements are observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(hasattr(elementNames, "__le...
python
{ "resource": "" }
q43444
ObservableStore.isObservableElement
train
def isObservableElement(self, elementName): """ Mention if an element is an observable element. :param str ElementName: the element name to evaluate :return: true if is an observable element, otherwise false. :rtype: bool """ if not(isinstance(elementName, str)):...
python
{ "resource": "" }
q43445
ObservableStore.add
train
def add(self, observableElement): """ add an observable element :param str observableElement: the name of the observable element :raises RuntimeError: if element name already exist in the store """ if observableElement not in self._observables: self._observab...
python
{ "resource": "" }
q43446
ObservableStore.remove
train
def remove(self, observableElement): """ remove an obsrvable element :param str observableElement: the name of the observable element """ if observableElement in self._observables: self._observables.remove(observableElement)
python
{ "resource": "" }
q43447
URLOpener.get_response
train
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_u...
python
{ "resource": "" }
q43448
URLOpener.setup
train
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) ...
python
{ "resource": "" }
q43449
URLOpener.get_proxy
train
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:...
python
{ "resource": "" }
q43450
pageassert
train
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
python
{ "resource": "" }
q43451
AwsProcessor.do_mfa
train
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...
python
{ "resource": "" }
q43452
AwsProcessor.do_up
train
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)) ...
python
{ "resource": "" }
q43453
AwsProcessor.do_slash
train
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...
python
{ "resource": "" }
q43454
AwsProcessor.do_profile
train
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='v...
python
{ "resource": "" }
q43455
parse
train
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) ...
python
{ "resource": "" }
q43456
confirm
train
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 d...
python
{ "resource": "" }
q43457
read_file
train
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] != '#'): ...
python
{ "resource": "" }
q43458
drop_it
train
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 black...
python
{ "resource": "" }
q43459
do_list
train
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."
python
{ "resource": "" }
q43460
do_create
train
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 pr...
python
{ "resource": "" }
q43461
do_update
train
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_c...
python
{ "resource": "" }
q43462
do_remove
train
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)...
python
{ "resource": "" }
q43463
do_exec
train
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) conf...
python
{ "resource": "" }
q43464
do_filter
train
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') cal...
python
{ "resource": "" }
q43465
do_blacklist
train
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') ...
python
{ "resource": "" }
q43466
action
train
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)
python
{ "resource": "" }
q43467
Space.is_discrete
train
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
python
{ "resource": "" }
q43468
Space.consistent
train
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
python
{ "resource": "" }
q43469
Space.satisfied
train
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
python
{ "resource": "" }
q43470
Membership.from_inline
train
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 :para...
python
{ "resource": "" }
q43471
Membership.from_signed_raw
train
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(Memb...
python
{ "resource": "" }
q43472
make_basic_daemon
train
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/s...
python
{ "resource": "" }
q43473
process_kill
train
def process_kill(pid, sig=None): """Send signal to process. """ sig = sig or signal.SIGTERM os.kill(pid, sig)
python
{ "resource": "" }
q43474
load_pid
train
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
python
{ "resource": "" }
q43475
write_pidfile
train
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
python
{ "resource": "" }
q43476
is_running
train
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
python
{ "resource": "" }
q43477
clean_pid_file
train
def clean_pid_file(pidfile): """clean pid file. """ if pidfile and os.path.exists(pidfile): os.unlink(pidfile)
python
{ "resource": "" }
q43478
daemon_start
train
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=wo...
python
{ "resource": "" }
q43479
is_dicom
train
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
python
{ "resource": "" }
q43480
info
train
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_tim...
python
{ "resource": "" }
q43481
info_for_tags
train
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 re...
python
{ "resource": "" }
q43482
scan_dir
train
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 n...
python
{ "resource": "" }
q43483
create_dset
train
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)
python
{ "resource": "" }
q43484
date_for_str
train
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: ...
python
{ "resource": "" }
q43485
organize_dir
train
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 ...
python
{ "resource": "" }
q43486
reconstruct_files
train
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.wal...
python
{ "resource": "" }
q43487
unpack_archive
train
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 ...
python
{ "resource": "" }
q43488
static
train
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, staticmet...
python
{ "resource": "" }
q43489
_generate_mark_code
train
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()...
python
{ "resource": "" }
q43490
rule_n5xx
train
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 ...
python
{ "resource": "" }
q43491
upsert_many
train
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) # 没有任何数据被修改, ...
python
{ "resource": "" }
q43492
resolve
train
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]))
python
{ "resource": "" }
q43493
build
train
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) ...
python
{ "resource": "" }
q43494
rebuild
train
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)
python
{ "resource": "" }
q43495
dump
train
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) ...
python
{ "resource": "" }
q43496
draw
train
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 er...
python
{ "resource": "" }
q43497
Butcher.setup_function
train
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_...
python
{ "resource": "" }
q43498
Butcher.clean
train
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)
python
{ "resource": "" }
q43499
Butcher.paths_wanted
train
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)
python
{ "resource": "" }