_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q41300
Episode.title
train
def title(self) -> str: """Episode title.""" for title in self.titles: if title.lang == 'ja': return title.title # In case there's no Japanese title. return self.titles[0].title
python
{ "resource": "" }
q41301
TitleSearcher.search
train
def search(self, query: 're.Pattern') -> 'Iterable[_WorkTitles]': """Search titles using a compiled RE query.""" titles: 'Titles' for titles in self._titles_list: title: 'AnimeTitle' for title in titles.titles: if query.search(title.title): ...
python
{ "resource": "" }
q41302
_get_packages
train
def _get_packages(): # type: () -> List[Package] """Convert `pkg_resources.working_set` into a list of `Package` objects. :return: list """ return [Package(pkg_obj=pkg) for pkg in sorted(pkg_resources.working_set, key=lambda x: str(x).lower())]
python
{ "resource": "" }
q41303
_get_whitelist_licenses
train
def _get_whitelist_licenses(config_path): # type: (str) -> List[str] """Get whitelist license names from config file. :param config_path: str :return: list """ whitelist_licenses = [] try: print('config path', config_path) with open(config_path) as config: whit...
python
{ "resource": "" }
q41304
run_license_checker
train
def run_license_checker(config_path): # type: (str) -> None """Generate table of installed packages and check for license warnings based off user defined restricted license values. :param config_path: str :return: """ whitelist_licenses = _get_whitelist_licenses(config_path) table = Pri...
python
{ "resource": "" }
q41305
Search.include_fields
train
def include_fields(self, *args): r""" Include fields is the fields that you want to be returned when searching. These are in addition to the fields that are always included below. :param args: items passed in will be turned into a list :returns: :clas...
python
{ "resource": "" }
q41306
Search.product
train
def product(self, *products): r""" When search is called, it will limit the results to items in a Product. :param product: items passed in will be turned into a list :returns: :class:`Search` """ for product in products: self._product.append(produ...
python
{ "resource": "" }
q41307
Search.timeframe
train
def timeframe(self, start, end): r""" When you want to search bugs for a certain time frame. :param start: :param end: :returns: :class:`Search` """ if start: self._time_frame['chfieldfrom'] = start if end: self._ti...
python
{ "resource": "" }
q41308
Search.search
train
def search(self): r""" Call the Bugzilla endpoint that will do the search. It will take the information used in other methods on the Search object and build up the query string. If no bugs are found then an empty list is returned. >>> bugs = bugzilla....
python
{ "resource": "" }
q41309
sync_remote_to_local
train
def sync_remote_to_local(force="no"): """ Replace your remote db with your local Example: sync_remote_to_local:force=yes """ assert "local_wp_dir" in env, "Missing local_wp_dir in env" if force != "yes": message = "This will replace your local database with your "\ ...
python
{ "resource": "" }
q41310
get_priority_rules
train
def get_priority_rules(db) -> Iterable[PriorityRule]: """Get file priority rules.""" cur = db.cursor() cur.execute('SELECT id, regexp, priority FROM file_priority') for row in cur: yield PriorityRule(*row)
python
{ "resource": "" }
q41311
delete_priority_rule
train
def delete_priority_rule(db, rule_id: int) -> None: """Delete a file priority rule.""" with db: cur = db.cursor() cur.execute('DELETE FROM file_priority WHERE id=?', (rule_id,))
python
{ "resource": "" }
q41312
get_files
train
def get_files(conn, aid: int) -> AnimeFiles: """Get cached files for anime.""" with conn: cur = conn.cursor().execute( 'SELECT anime_files FROM cache_anime WHERE aid=?', (aid,)) row = cur.fetchone() if row is None: raise ValueError('No cached files') ...
python
{ "resource": "" }
q41313
AnimeFiles.add
train
def add(self, filename): """Try to add a file.""" basename = os.path.basename(filename) match = self.regexp.search(basename) if match: self.by_episode[int(match.group('ep'))].add(filename)
python
{ "resource": "" }
q41314
AnimeFiles.available_string
train
def available_string(self, episode): """Return a string of available episodes.""" available = [ep for ep in self if ep > episode] string = ','.join(str(ep) for ep in available[:self.EPISODES_TO_SHOW]) if len(available) > self.EPISODES_TO_SHOW: string += '...' return s...
python
{ "resource": "" }
q41315
AnimeFiles.from_json
train
def from_json(cls, string): """Create AnimeFiles from JSON string.""" obj = json.loads(string) return cls(obj['regexp'], obj['files'])
python
{ "resource": "" }
q41316
_get_exception_class_from_status_code
train
def _get_exception_class_from_status_code(status_code): """ Utility function that accepts a status code, and spits out a reference to the correct exception class to raise. :param str status_code: The status code to return an exception class for. :rtype: PetfinderAPIError or None :returns: The a...
python
{ "resource": "" }
q41317
MongodbPipeline.open_spider
train
def open_spider(self, spider): """ Initialize Mongodb client. """ if self.url == "": self.client = pymongo.MongoClient(self.host, self.port) else: self.client = pymongo.MongoClient(self.url) self.db_name, self.collection_name = self._replace_place...
python
{ "resource": "" }
q41318
PlexRequest.construct_url
train
def construct_url(self): """Construct a full plex request URI, with `params`.""" path = [self.path] path.extend([str(x) for x in self.params]) url = self.client.base_url + '/'.join(x for x in path if x) query = self.kwargs.get('query') if query: # Dict -> Li...
python
{ "resource": "" }
q41319
load_config
train
def load_config(): """Load configuration file containing API KEY and other settings. :rtype: str """ configfile = get_configfile() if not os.path.exists(configfile): data = { 'apikey': 'GET KEY AT: https://www.filemail.com/apidoc/ApiKey.aspx' } save_config...
python
{ "resource": "" }
q41320
save_config
train
def save_config(config): """Save configuration file to users data location. - Linux: ~/.local/share/pyfilemail - OSX: ~/Library/Application Support/pyfilemail - Windows: C:\\\Users\\\{username}\\\AppData\\\Local\\\pyfilemail :rtype: str """ configfile = get_configfile() if not os...
python
{ "resource": "" }
q41321
get_configfile
train
def get_configfile(): """Return full path to configuration file. - Linux: ~/.local/share/pyfilemail - OSX: ~/Library/Application Support/pyfilemail - Windows: C:\\\Users\\\{username}\\\AppData\\\Local\\\pyfilemail :rtype: str """ ad = appdirs.AppDirs('pyfilemail') configdir = ad.u...
python
{ "resource": "" }
q41322
get_flake8_options
train
def get_flake8_options(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for `flake8` and add them in the correct `flake8` `options` format. :param config_dir: :return: List[str] """ if FLAKE8_CONFIG_NAME in os.listdir(config_dir): flake8_config_path =...
python
{ "resource": "" }
q41323
get_license_checker_config_path
train
def get_license_checker_config_path(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for license checker, if not found it returns the package default. :param config_dir: :return: str """ if LICENSE_CHECKER_CONFIG_NAME in os.listdir(config_dir): licens...
python
{ "resource": "" }
q41324
get_pylint_options
train
def get_pylint_options(config_dir='.'): # type: (str) -> List[str] """Checks for local config overrides for `pylint` and add them in the correct `pylint` `options` format. :param config_dir: :return: List [str] """ if PYLINT_CONFIG_NAME in os.listdir(config_dir): pylint_config_path ...
python
{ "resource": "" }
q41325
wait_on_any
train
def wait_on_any(*events, **kwargs): """ Helper method for waiting for any of the given threading events to be set. The standard threading lib doesn't include any mechanism for waiting on more than one event at a time so we have to monkey patch the events so that their `set()` and `clear()` meth...
python
{ "resource": "" }
q41326
wait_on_event
train
def wait_on_event(event, timeout=None): """ Waits on a single threading Event, with an optional timeout. This is here for compatibility reasons as python 2 can't reliably wait on an event without a timeout and python 3 doesn't define a `maxint`. """ if timeout is not None: event.wait(ti...
python
{ "resource": "" }
q41327
HAProxy.validate_config
train
def validate_config(cls, config): """ Validates that a config file path and a control socket file path and pid file path are all present in the HAProxy config. """ if "config_file" not in config: raise ValueError("No config file path given") if "socket_file" n...
python
{ "resource": "" }
q41328
HAProxy.validate_proxies_config
train
def validate_proxies_config(cls, proxies): """ Specific config validation method for the "proxies" portion of a config. Checks that each proxy defines a port and a list of `upstreams`, and that each upstream entry has a host and port defined. """ for name, proxy ...
python
{ "resource": "" }
q41329
HAProxy.apply_config
train
def apply_config(self, config): """ Constructs HAProxyConfig and HAProxyControl instances based on the contents of the config. This is mostly a matter of constructing the configuration stanzas. """ self.haproxy_config_path = config["config_file"] global_stanza =...
python
{ "resource": "" }
q41330
HAProxy.sync_file
train
def sync_file(self, clusters): """ Generates new HAProxy config file content and writes it to the file at `haproxy_config_path`. If a restart is not necessary the nodes configured in HAProxy will be synced on the fly. If a restart *is* necessary, one will be triggered. ...
python
{ "resource": "" }
q41331
HAProxy.restart
train
def restart(self): """ Tells the HAProxy control object to restart the process. If it's been fewer than `restart_interval` seconds since the previous restart, it will wait until the interval has passed. This staves off situations where the process is constantly restarting, as i...
python
{ "resource": "" }
q41332
HAProxy.get_current_nodes
train
def get_current_nodes(self, clusters): """ Returns two dictionaries, the current nodes and the enabled nodes. The current_nodes dictionary is keyed off of the cluster name and values are a list of nodes known to HAProxy. The enabled_nodes dictionary is also keyed off of the clu...
python
{ "resource": "" }
q41333
Service.validate_check_configs
train
def validate_check_configs(cls, config): """ Config validation specific to the health check options. Verifies that checks are defined along with an interval, and calls out to the `Check` class to make sure each individual check's config is valid. """ if "checks" ...
python
{ "resource": "" }
q41334
Service.apply_config
train
def apply_config(self, config): """ Takes a given validated config dictionary and sets an instance attribute for each one. For check definitions, a Check instance is is created and a `checks` attribute set to a dictionary keyed off of the checks' names. If the Check ins...
python
{ "resource": "" }
q41335
Service.update_ports
train
def update_ports(self): """ Sets the `ports` attribute to the set of valid port values set in the configuration. """ ports = set() for port in self.configured_ports: try: ports.add(int(port)) except ValueError: logg...
python
{ "resource": "" }
q41336
Service.update_checks
train
def update_checks(self, check_configs): """ Maintains the values in the `checks` attribute's dictionary. Each key in the dictionary is a port, and each value is a nested dictionary mapping each check's name to the Check instance. This method makes sure the attribute reflects al...
python
{ "resource": "" }
q41337
Service.run_checks
train
def run_checks(self): """ Iterates over the configured ports and runs the checks on each one. Returns a two-element tuple: the first is the set of ports that transitioned from down to up, the second is the set of ports that transitioned from up to down. Also handles the...
python
{ "resource": "" }
q41338
AnimalAdmin.mark_sacrificed
train
def mark_sacrificed(self,request,queryset): """An admin action for marking several animals as sacrificed. This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed. This admin act...
python
{ "resource": "" }
q41339
BreedingAdmin.mark_deactivated
train
def mark_deactivated(self,request,queryset): """An admin action for marking several cages as inactive. This action sets the selected cages as Active=False and Death=today. This admin action also shows as the output the number of mice sacrificed.""" rows_updated = queryset.update(Activ...
python
{ "resource": "" }
q41340
make_unicode
train
def make_unicode(s, encoding='utf-8', encoding_errors='strict'): """ Return the unicode version of an input. """ if not isinstance(s, unicode): if not isinstance(s, basestring): return unicode(str(s), encoding, encoding_errors) return unicode(s, encoding, encoding_errors) return ...
python
{ "resource": "" }
q41341
html_escape
train
def html_escape(s, encoding='utf-8', encoding_errors='strict'): """ Return the HTML-escaped version of an input. """ return escape(make_unicode(s, encoding, encoding_errors), quote=True)
python
{ "resource": "" }
q41342
retarget_to_length
train
def retarget_to_length(song, duration, start=True, end=True, slack=5, beats_per_measure=None): """Create a composition of a song that changes its length to a given duration. :param song: Song to retarget :type song: :py:class:`radiotool.composer.Song` :param duration: Duratio...
python
{ "resource": "" }
q41343
retarget_with_change_points
train
def retarget_with_change_points(song, cp_times, duration): """Create a composition of a song of a given duration that reaches music change points at specified times. This is still under construction. It might not work as well with more than 2 ``cp_times`` at the moment. Here's an example of retarge...
python
{ "resource": "" }
q41344
get_data_files
train
def get_data_files(): """ Returns the path of data files, which are installed to the package directory. """ import os path = os.path.dirname(__file__) path = os.path.join(path, 'data') r = dict( Alpha_inf_hyrec_file = os.path.join(path, 'hyrec', 'Alpha_inf.dat'), R_inf_hyrec...
python
{ "resource": "" }
q41345
_find_file
train
def _find_file(filename): """ Find the file path, first checking if it exists and then looking in the data directory """ import os if os.path.exists(filename): path = filename else: path = os.path.dirname(__file__) path = os.path.join(path, 'data', filename) if n...
python
{ "resource": "" }
q41346
load_precision
train
def load_precision(filename): """ Load a CLASS precision file into a dictionary. Parameters ---------- filename : str the name of an existing file to load, or one in the files included as part of the CLASS source Returns ------- dict : the precision parameters l...
python
{ "resource": "" }
q41347
load_ini
train
def load_ini(filename): """ Read a CLASS ``.ini`` file, returning a dictionary of parameters Parameters ---------- filename : str the name of an existing parameter file to load, or one included as part of the CLASS source Returns ------- dict : the input paramet...
python
{ "resource": "" }
q41348
save_coef
train
def save_coef(scoef, filename): """Saves ScalarCoeffs object 'scoef' to file. The first line of the file has the max number N and the max number M of the scoef structure separated by a comma. The remaining lines have the form 3.14, 2.718 The first number is the real part of the mode and ...
python
{ "resource": "" }
q41349
load_patt
train
def load_patt(filename): """Loads a file that was saved with the save_patt routine.""" with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') patt = np.zeros([int(lst[0]), int(lst[1])], dtype=np.complex128) lines.pop(0) for...
python
{ "resource": "" }
q41350
load_vpatt
train
def load_vpatt(filename1, filename2): """Loads a VectorPatternUniform pattern that is saved between two files. """ with open(filename1) as f: lines = f.readlines() lst = lines[0].split(',') patt1 = np.zeros([int(lst[0]), int(lst[1])], dtype=np.complex128) ...
python
{ "resource": "" }
q41351
load_coef
train
def load_coef(filename): """Loads a file that was saved with save_coef.""" with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') nmax = int(lst[0]) mmax = int(lst[1]) L = (nmax + 1) + mmax * (2 * nmax - mmax + 1); vec = np.zeros(L, dt...
python
{ "resource": "" }
q41352
load_vcoef
train
def load_vcoef(filename): """Loads a set of vector coefficients that were saved in MATLAB. The third number on the first line is the directivity calculated within the MATLAB code.""" with open(filename) as f: lines = f.readlines() lst = lines[0].split(',') nmax = int(lst[0]) ...
python
{ "resource": "" }
q41353
BarcodeParser.parse
train
def parse(cls, filename, max_life=None): """ Parse barcode from gudhi output. """ data = np.genfromtxt(filename) #data = np.genfromtxt(filename, dtype= (int, int, float, float)) if max_life is not None: data[np.isinf(data)] = max_life return data
python
{ "resource": "" }
q41354
BarcodeParser.plot
train
def plot(self, dimension): """ Plot barcode using matplotlib. """ import matplotlib.pyplot as plt life_lines = self.get_life_lines(dimension) x, y = zip(*life_lines) plt.scatter(x, y) plt.xlabel("Birth") plt.ylabel("Death") if self.max_life is not None: ...
python
{ "resource": "" }
q41355
Configurable.from_config
train
def from_config(cls, name, config): """ Returns a Configurable instance with the given name and config. By default this is a simple matter of calling the constructor, but subclasses that are also `Pluggable` instances override this in order to check that the plugin is installed ...
python
{ "resource": "" }
q41356
command
train
def command(state, args): """List file priority rules.""" rules = query.files.get_priority_rules(state.db) print(tabulate(rules, headers=['ID', 'Regexp', 'Priority']))
python
{ "resource": "" }
q41357
filter_support
train
def filter_support(candidates, transactions, min_sup): """ Filter candidates to a frequent set by some minimum support. """ counts = defaultdict(lambda: 0) for transaction in transactions: for c in (c for c in candidates if set(c).issubset(transaction)): counts[c] += 1 return...
python
{ "resource": "" }
q41358
generate_candidates
train
def generate_candidates(freq_set, k): """ Generate candidates for an iteration. Use this only for k >= 2. """ single_set = {(i,) for i in set(flatten(freq_set))} # TO DO generating all combinations gets very slow for large documents. # Is there a way of doing this without exhaustively searc...
python
{ "resource": "" }
q41359
validate_candidate
train
def validate_candidate(candidate, freq_set, k): """ Checks if we should keep a candidate. We keep a candidate if all its k-1-sized subsets are present in the frequent sets. """ for subcand in combinations(candidate, k-1): if subcand not in freq_set: return False return Tr...
python
{ "resource": "" }
q41360
State.compile_tag_re
train
def compile_tag_re(self, tags): """ Return the regex used to look for Mustache tags compiled to work with specific opening tags, close tags, and tag types. """ return re.compile(self.raw_tag_re % tags, self.re_flags)
python
{ "resource": "" }
q41361
_rdumpq
train
def _rdumpq(q,size,value,encoding=None): """Dump value as a tnetstring, to a deque instance, last chunks first. This function generates the tnetstring representation of the given value, pushing chunks of the output onto the given deque instance. It pushes the last chunk first, then recursively generat...
python
{ "resource": "" }
q41362
_gdumps
train
def _gdumps(value,encoding): """Generate fragments of value dumped as a tnetstring. This is the naive dumping algorithm, implemented as a generator so that it's easy to pass to "".join() without building a new list. This is mainly here for comparison purposes; the _rdumpq version is measurably fas...
python
{ "resource": "" }
q41363
log_magnitude_spectrum
train
def log_magnitude_spectrum(frames): """Compute the log of the magnitude spectrum of frames""" return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf))
python
{ "resource": "" }
q41364
RMS_energy
train
def RMS_energy(frames): """Computes the RMS energy of frames""" f = frames.flatten() return N.sqrt(N.mean(f * f))
python
{ "resource": "" }
q41365
normalize_features
train
def normalize_features(features): """Standardizes features array to fall between 0 and 1""" return (features - N.min(features)) / (N.max(features) - N.min(features))
python
{ "resource": "" }
q41366
zero_crossing_last
train
def zero_crossing_last(frames): """Finds the last zero crossing in frames""" frames = N.array(frames) crossings = N.where(N.diff(N.sign(frames))) # crossings = N.where(frames[:n] * frames[1:n + 1] < 0) if len(crossings[0]) == 0: print "No zero crossing" return len(frames) - 1 r...
python
{ "resource": "" }
q41367
limiter
train
def limiter(arr): """ Restrict the maximum and minimum values of arr """ dyn_range = 32767.0 / 32767.0 lim_thresh = 30000.0 / 32767.0 lim_range = dyn_range - lim_thresh new_arr = arr.copy() inds = N.where(arr > lim_thresh)[0] new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_rang...
python
{ "resource": "" }
q41368
segment_array
train
def segment_array(arr, length, overlap=.5): """ Segment array into chunks of a specified length, with a specified proportion overlap. Operates on axis 0. :param integer length: Length of each segment :param float overlap: Proportion overlap of each frame """ arr = N.array(arr) of...
python
{ "resource": "" }
q41369
radpress_get_markup_descriptions
train
def radpress_get_markup_descriptions(): """ Provides markup options. It used for adding descriptions in admin and zen mode. :return: list """ result = [] for markup in get_markup_choices(): markup_name = markup[0] result.append({ 'name': markup_name, ...
python
{ "resource": "" }
q41370
_get_parser
train
def _get_parser(description): """Build an ArgumentParser with common arguments for both operations.""" parser = argparse.ArgumentParser(description=description) parser.add_argument('key', help="Camellia key.") parser.add_argument('input_file', nargs='*', help="File(s) to read as ...
python
{ "resource": "" }
q41371
_get_crypto
train
def _get_crypto(keylen, hexkey, key): """Return a camcrypt.CamCrypt object based on keylen, hexkey, and key.""" if keylen not in camcrypt.ACCEPTABLE_KEY_LENGTHS: raise ValueError("key length must be one of 128, 192, or 256") if hexkey: key = key.decode('hex') return camcrypt.CamCrypt(k...
python
{ "resource": "" }
q41372
_print_results
train
def _print_results(filename, data): """Print data to a file or STDOUT. Args: filename (str or None): If None, print to STDOUT; otherwise, print to the file with this name. data (str): Data to print. """ if filename: with open(filename, 'wb') as f: f.write...
python
{ "resource": "" }
q41373
HEADER.timestamp
train
def timestamp(self, value): """ The local time when the message was written. Must follow the format 'Mmm DD HH:MM:SS'. If the day of the month is less than 10, then it MUST be represented as a space and then the number. """ if not self._timestamp_is_val...
python
{ "resource": "" }
q41374
HEADER.hostname
train
def hostname(self, value): """ The hostname where the log message was created. Should be the first part of the hostname, or an IP address. Should NOT be set to a fully qualified domain name. """ if value is None: value = socket.gethostname() ...
python
{ "resource": "" }
q41375
MSG.tag
train
def tag(self, value): """The name of the program that generated the log message. The tag can only contain alphanumeric characters. If the tag is longer than {MAX_TAG_LEN} characters it will be truncated automatically. """ if value is None: value = sys.argv[0...
python
{ "resource": "" }
q41376
MSG.content
train
def content(self, value): """The main component of the log message. The content field is a freeform field that often begins with the process ID (pid) of the program that created the message. """ value = self._prepend_seperator(value) self._content = value
python
{ "resource": "" }
q41377
Syslog.log
train
def log(self, facility, level, text, pid=False): """Send the message text to all registered hosts. The facility and level will be used to create the packet's PRI part. The HEADER will be automatically determined from the current time and hostname. The MSG will be set from the ru...
python
{ "resource": "" }
q41378
GeneratePassword.new_pin
train
def new_pin(self, min_length=4, min_common=1000, timeout=20, refresh_timeout=3): """ Return a suggested PIN :param int min_length: minimum length of the PIN generated :param int min_common: the minimal commonness to be considered convertible to a PIN :param float timeout: main t...
python
{ "resource": "" }
q41379
HTTPCheck.apply_check_config
train
def apply_check_config(self, config): """ Takes a validated config dictionary and sets the `uri`, `use_https` and `method` attributes based on the config's contents. """ self.uri = config["uri"] self.use_https = config.get("https", False) self.method = config.get(...
python
{ "resource": "" }
q41380
HTTPCheck.perform
train
def perform(self): """ Performs a simple HTTP request against the configured url and returns true if the response has a 2xx code. The url can be configured to use https via the "https" boolean flag in the config, as well as a custom HTTP method via the "method" key. The...
python
{ "resource": "" }
q41381
Writer.sync_balancer_files
train
def sync_balancer_files(self): """ Syncs the config files for each present Balancer instance. Submits the work to sync each file as a work pool job. """ def sync(): for balancer in self.configurables[Balancer].values(): balancer.sync_file(self.config...
python
{ "resource": "" }
q41382
Writer.on_balancer_remove
train
def on_balancer_remove(self, name): """ The removal of a load balancer config isn't supported just yet. If the balancer being removed is the only configured one we fire a critical log message saying so. A writer setup with no balancers is less than useless. """ ...
python
{ "resource": "" }
q41383
Writer.on_cluster_update
train
def on_cluster_update(self, name, new_config): """ Callback hook for when a cluster is updated. Or main concern when a cluster is updated is whether or not the associated discovery method changed. If it did, we make sure that the old discovery method stops watching for the clus...
python
{ "resource": "" }
q41384
Writer.on_cluster_remove
train
def on_cluster_remove(self, name): """ Stops the cluster's associated discovery method from watching for changes to the cluster's nodes. """ discovery_name = self.configurables[Cluster][name].discovery if discovery_name in self.configurables[Discovery]: self.c...
python
{ "resource": "" }
q41385
color_string
train
def color_string(color, string): """ Colorizes a given string, if coloring is available. """ if not color_available: return string return color + string + colorama.Fore.RESET
python
{ "resource": "" }
q41386
color_for_level
train
def color_for_level(level): """ Returns the colorama Fore color for a given log level. If color is not available, returns None. """ if not color_available: return None return { logging.DEBUG: colorama.Fore.WHITE, logging.INFO: colorama.Fore.BLUE, logging.WARNING...
python
{ "resource": "" }
q41387
create_thread_color_cycle
train
def create_thread_color_cycle(): """ Generates a never-ending cycle of colors to choose from for individual threads. If color is not available, a cycle that repeats None every time is returned instead. """ if not color_available: return itertools.cycle([None]) return itertools....
python
{ "resource": "" }
q41388
color_for_thread
train
def color_for_thread(thread_id): """ Associates the thread ID with the next color in the `thread_colors` cycle, so that thread-specific parts of a log have a consistent separate color. """ if thread_id not in seen_thread_colors: seen_thread_colors[thread_id] = next(thread_colors) return...
python
{ "resource": "" }
q41389
CLIHandler.format
train
def format(self, record): """ Formats a given log record to include the timestamp, log level, thread ID and message. Colorized if coloring is available. """ if not self.is_tty: return super(CLIHandler, self).format(record) level_abbrev = record.levelname[0] ...
python
{ "resource": "" }
q41390
add_bare_metal_cloud
train
def add_bare_metal_cloud(client, cloud, keys): """ Black magic is happening here. All of this wil change when we sanitize our API, however, this works until then """ title = cloud.get('title') provider = cloud.get('provider') key = cloud.get('apikey', "") secret = cloud.get('apisecret', "") ...
python
{ "resource": "" }
q41391
associate_keys
train
def associate_keys(user_dict, client): """ This whole function is black magic, had to however cause of the way we keep key-machine association """ added_keys = user_dict['keypairs'] print ">>>Updating Keys-Machines association" for key in added_keys: machines = added_keys[key]['machines...
python
{ "resource": "" }
q41392
Fade.to_array
train
def to_array(self, channels=2): """Generate the array of volume multipliers for the dynamic""" if self.fade_type == "linear": return np.linspace(self.in_volume, self.out_volume, self.duration * channels)\ .reshape(self.duration, channels) elif self.fad...
python
{ "resource": "" }
q41393
PlugEvents.save
train
def save(self): """Over-rides the default save function for PlugEvents. If a sacrifice date is set for an object in this model, then Active is set to False.""" if self.SacrificeDate: self.Active = False super(PlugEvents, self).save()
python
{ "resource": "" }
q41394
command
train
def command(state, args): """Show anime data.""" args = parser.parse_args(args[1:]) aid = state.results.parse_aid(args.aid, default_key='db') anime = query.select.lookup(state.db, aid, episode_fields=args.episode_fields) complete_string = 'yes' if anime.complete else 'no' print(SHOW_MSG.format(...
python
{ "resource": "" }
q41395
load_prefix
train
def load_prefix(s3_loc, success_only=None, recent_versions=None, exclude_regex=None, just_sql=False): """Get a bash command which will load every dataset in a bucket at a prefix. For this to work, all datasets must be of the form `s3://$BUCKET_NAME/$PREFIX/$DATASET_NAME/v$VERSION/$PARTITIONS`. Any other fo...
python
{ "resource": "" }
q41396
read_unicode
train
def read_unicode(path, encoding, encoding_errors): """ Return the contents of a file as a unicode string. """ try: f = open(path, 'rb') return make_unicode(f.read(), encoding, encoding_errors) finally: f.close()
python
{ "resource": "" }
q41397
get_abs_template_path
train
def get_abs_template_path(template_name, directory, extension): """ Given a template name, a directory, and an extension, return the absolute path to the template. """ # Get the relative path relative_path = join(directory, template_name) file_with_ext = template_name if extension: # If...
python
{ "resource": "" }
q41398
load_file
train
def load_file(path, encoding, encoding_errors): """ Given an existing path, attempt to load it as a unicode string. """ abs_path = abspath(path) if exists(abs_path): return read_unicode(abs_path, encoding, encoding_errors) raise IOError('File %s does not exist' % (abs_path))
python
{ "resource": "" }
q41399
load_template
train
def load_template(name, directory, extension, encoding, encoding_errors): """ Load a template and return its contents as a unicode string. """ abs_path = get_abs_template_path(name, directory, extension) return load_file(abs_path, encoding, encoding_errors)
python
{ "resource": "" }