code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' figure partial character ''' p_char = '' if not self.done and self.remainder: p_style = self._comp_style if self.partial_char_extra_style: if p_style is str: p_style = self.partial_char_extra_style else: ...
def _render(self)
figure partial character
5.270976
4.714634
1.118003
q = Queue(maxsize=0) if not num_threads: num_threads = len(targets) for i in range(num_threads): worker = Thread(target=function, args=(q, params)) worker.setDaemon(True) worker.start() for target in targets: q.put(target) q.join()
def thread_work(targets, function, params = {}, num_threads = 0)
Generic multithreading helper :param targets: :param function: :param params: :param num_threads: :return:
1.826102
2.065574
0.884065
while True: try: params['region'] = q.get() method = params['method'] method(params) except Exception as e: printException(e) finally: q.task_done()
def threaded_per_region(q, params)
Helper for multithreading on a per-region basis :param q: :param params: :return:
3.156522
3.662915
0.861751
''' Temporarily move the cursor, perform work, and return to the previous location. :: with screen.location(40, 20): print('Hello, world!') ''' stream = self._stream stream.write(self.save_pos) # cursor position if x...
def location(self, x=None, y=None)
Temporarily move the cursor, perform work, and return to the previous location. :: with screen.location(40, 20): print('Hello, world!')
3.891473
2.59377
1.500316
''' Context Manager that enters full-screen mode and restores normal mode on exit. :: with screen.fullscreen(): print('Hello, world!') ''' stream = self._stream stream.write(self.alt_screen_enable) stream.write(str(sel...
def fullscreen(self)
Context Manager that enters full-screen mode and restores normal mode on exit. :: with screen.fullscreen(): print('Hello, world!')
5.808755
4.299266
1.351104
''' Context Manager that hides the cursor and restores it on exit. :: with screen.hidden_cursor(): print('Clandestine activity…') ''' stream = self._stream stream.write(self.hide_cursor) stream.flush() try: yie...
def hidden_cursor(self)
Context Manager that hides the cursor and restores it on exit. :: with screen.hidden_cursor(): print('Clandestine activity…')
5.619132
2.689633
2.089182
# class decorator if type(o) is type: return o try: # python2 closure = o.func_closure except AttributeError: pass try: # python3 closure = o.__closure__ except AttributeError: return if closure: for cell in closure: ...
def undecorated(o)
Remove all decorators from a function, method or class
5.191292
5.229867
0.992624
external_id = credentials.pop('ExternalId') if 'ExternalId' in credentials else None # Connect to STS sts_client = connect_service('sts', credentials, silent = silent) # Set required arguments for assume role call sts_args = { 'RoleArn': role_arn, 'RoleSessionName': role_session_nam...
def assume_role(role_name, credentials, role_arn, role_session_name, silent = False)
Assume role and save credentials :param role_name: :param credentials: :param role_arn: :param role_session_name: :param silent: :return:
2.688719
2.848778
0.943815
filename_p1 = role_name.replace('/','-') filename_p2 = role_arn.replace('/', '-').replace(':', '_') return os.path.join(os.path.join(os.path.expanduser('~'), '.aws'), 'cli/cache/%s--%s.json' % (filename_p1, filename_p2))
def get_cached_credentials_filename(role_name, role_arn)
Construct filepath for cached credentials (AWS CLI scheme) :param role_name: :param role_arn: :return:
3.373661
3.280666
1.028347
chars = string.ascii_letters + string.digits + '!@#$%^&*()_+-=[]{};:,<.>?|' modulus = len(chars) pchars = os.urandom(16) if type(pchars) == str: return ''.join(chars[i % modulus] for i in map(ord, pchars)) else: return ''.join(chars[i % modulus] for i in pchars)
def generate_password(length=16)
Generate a password using random characters from uppercase, lowercase, digits, and symbols :param length: Length of the password to be generated :return: The random password
2.67734
2.910422
0.919915
# Set STS arguments sts_args = { 'DurationSeconds': duration } # Prompt for MFA code if MFA serial present if 'SerialNumber' in credentials and credentials['SerialNumber']: if not credentials['TokenCode']: credentials['TokenCode'] = prompt_4_mfa_code() if...
def init_sts_session(profile_name, credentials, duration = 28800, session_name = None, save_creds = True)
Fetch STS credentials :param profile_name: :param credentials: :param duration: :param session_name: :param save_creds: :return:
3.327148
3.371846
0.986744
credentials = init_creds() profile_found = False try: # Make sure the ~.aws folder exists if not os.path.exists(aws_config_dir): os.makedirs(aws_config_dir) with open(credentials_file, 'rt') as cf: for line in cf: profile_line = re_profile...
def read_creds_from_aws_credentials_file(profile_name, credentials_file = aws_credentials_file)
Read credentials from AWS config file :param profile_name: :param credentials_file: :return:
2.285872
2.298464
0.994522
key_id = None secret = None mfa_serial = None secret_next = False with open(filename, 'rt') as csvfile: for i, line in enumerate(csvfile): values = line.split(',') for v in values: if v.startswith('AKIA'): key_id = v.strip() ...
def read_creds_from_csv(filename)
Read credentials from a CSV file :param filename: :return:
2.589667
2.793243
0.927119
creds = init_creds() try: has_role = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials', timeout = 1) if has_role.status_code == 200: iam_role = has_role.text credentials = requests.get('http://169.254.169.254/latest/meta-data/iam/securit...
def read_creds_from_ec2_instance_metadata()
Read credentials from EC2 instance metadata (IAM role) :return:
2.382452
2.412589
0.987509
creds = init_creds() try: ecs_metadata_relative_uri = os.environ['AWS_CONTAINER_CREDENTIALS_RELATIVE_URI'] credentials = requests.get('http://169.254.170.2' + ecs_metadata_relative_uri, timeout = 1).json() for c in ['AccessKeyId', 'SecretAccessKey']: creds[c] = credentia...
def read_creds_from_ecs_container_metadata()
Read credentials from ECS instance metadata (IAM role) :return:
3.004063
3.095665
0.97041
creds = init_creds() # Check environment variables if 'AWS_ACCESS_KEY_ID' in os.environ and 'AWS_SECRET_ACCESS_KEY' in os.environ: creds['AccessKeyId'] = os.environ['AWS_ACCESS_KEY_ID'] creds['SecretAccessKey'] = os.environ['AWS_SECRET_ACCESS_KEY'] if 'AWS_SESSION_TOKEN' in os.e...
def read_creds_from_environment_variables()
Read credentials from environment variables :return:
1.7232
1.815713
0.949049
role_arn = os.environ.get('AWS_ROLE_ARN', None) external_id = os.environ.get('AWS_EXTERNAL_ID', None) return role_arn, external_id
def read_profile_from_environment_variables()
Read profiles from env :return:
2.35959
2.849881
0.827961
role_arn = None source_profile = 'default' mfa_serial = None profile_found = False external_id = None try: with open(config_file, 'rt') as config: for line in config: profile_line = re_profile_name.match(line) if profile_line: ...
def read_profile_from_aws_config_file(profile_name, config_file = aws_config_file)
Read profiles from AWS config file :param profile_name: :param config_file: :return:
2.047489
2.073069
0.987661
profiles = get_profiles_from_aws_credentials_file(credentials_files) for profile in set(profiles): printInfo(' * %s' % profile)
def show_profiles_from_aws_credentials_file(credentials_files = [aws_credentials_file, aws_config_file])
Show profile names from ~/.aws/credentials :param credentials_files: :return:
4.527912
5.847369
0.77435
profile_found = False profile_ever_found = False session_token_written = False security_token_written = False mfa_serial_written = False expiration_written = False # Create the .aws folder if needed if not os.path.isdir(aws_config_dir): os.mkdir(aws_config_dir) # Create ...
def write_creds_to_aws_credentials_file(profile_name, credentials, credentials_file = aws_credentials_file)
Write credentials to AWS config file :param profile_name: :param credentials: :param credentials_file: :return:
1.730814
1.736349
0.996812
session_token = credentials['SessionToken'] if 'SessionToken' in credentials else None mfa_serial = credentials['SerialNumber'] if 'SerialNumber' in credentials else None if session_token and not session_token_written: f.write('aws_session_token = %s\n' % session_token) if mfa_serial and no...
def complete_profile(f, credentials, session_token_written, mfa_serial_written)
Append session token and mfa serial if needed :param f: :param credentials: :param session_token_written: :param mfa_serial_written: :return:
1.641116
1.742676
0.941722
api_client = connect_service('sts', credentials, silent=True) configured_account_ids = [] for account_id in account_ids: try: role_arn = 'arn:aws:iam::%s:role/AWSCloudFormationStackSetExecutionRole' % account_id api_client.assume_role(RoleArn=role_arn, RoleSessionName='o...
def get_stackset_ready_accounts(credentials, account_ids, quiet=True)
Verify which AWS accounts have been configured for CloudFormation stack set by attempting to assume the stack set execution role :param credentials: AWS credentials to use when calling sts:assumerole :param org_account_ids: List of AWS accounts to check for Stackset configuration ...
3.157313
3.165447
0.99743
try: r = requests.get(url, timeout=self.timeout) except requests.exceptions.Timeout: if not self.safe: raise else: return None # Raise 404/500 error if any if r and not self.safe: r.raise_fo...
def fetch(self, url)
Get the feed content using 'requests'
3.300406
3.24454
1.017218
if content is None: return None feed = feedparser.parse(content) # When feed is malformed if feed['bozo']: # keep track of the parsing error exception but as string # infos, not an exception object exception_cont...
def parse(self, content)
Parse the fetched feed content Feedparser returned dict contain a 'bozo' key which can be '1' if the feed is malformed. Return None if the feed is malformed and 'bozo_accept' is 'False', else return the feed content dict. If the feed is malformed but ...
5.47944
4.228916
1.295708
if isinstance(url, six.text_type): url = url.encode('utf-8') return hashlib.md5(url).hexdigest()
def _hash_url(self, url)
Hash the URL to an md5sum.
2.853185
2.374957
1.201363
# Hash url to have a shorter key and add it expiration time to avoid clash for # other url usage with different expiration cache_key = self.cache_key.format(**{ 'id': self._hash_url(url), 'expire': str(expiration) }) # Get feed from cach...
def get(self, url, expiration)
Fetch the feed if no cache exist or if cache is stale
6.497302
6.183268
1.050788
self._feed = self.get(url, expiration) return { self.feed_context_name: self.format_feed_content(self._feed), }
def get_context(self, url, expiration)
Build template context with formatted feed content
7.098014
4.715203
1.505347
template = template or self.default_template return render_to_string(template, self.get_context(url, expiration))
def render(self, url, template=None, expiration=0)
Render feed template
3.340527
3.329833
1.003212
''' What it says on the tin. - https://docs.microsoft.com/en-us/windows/console/setconsolemode #ENABLE_VIRTUAL_TERMINAL_PROCESSING - https://stackoverflow.com/q/36760127/450917 Returns: Tuple of status codes from SetConsoleMode for (stdout, stderr). ''' resul...
def enable_vt_processing()
What it says on the tin. - https://docs.microsoft.com/en-us/windows/console/setconsolemode #ENABLE_VIRTUAL_TERMINAL_PROCESSING - https://stackoverflow.com/q/36760127/450917 Returns: Tuple of status codes from SetConsoleMode for (stdout, stderr).
3.908412
2.267732
1.72349
''' Check to see whether this version of Windows is recent enough to support "ANSI VT"" processing. ''' BUILD_ANSI_AVAIL = 10586 # Win10 TH2 CURRENT_VERS = sys.getwindowsversion()[:3] if CURRENT_VERS[2] > BUILD_ANSI_AVAIL: result = True else: result = False log.debu...
def is_ansi_capable()
Check to see whether this version of Windows is recent enough to support "ANSI VT"" processing.
9.881631
5.738816
1.721894
''' Returns current colors of console. https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo Arguments: name: one of ('background', 'bg', 'foreground', 'fg') stream: Handle to stdout, stderr, etc. Returns: int: a color id from t...
def get_color(name, stream=STD_OUTPUT_HANDLE)
Returns current colors of console. https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo Arguments: name: one of ('background', 'bg', 'foreground', 'fg') stream: Handle to stdout, stderr, etc. Returns: int: a color id from the conho...
4.315741
2.206455
1.955962
''' Returns current position of cursor, starts at 1. ''' stream = kernel32.GetStdHandle(stream) csbi = CONSOLE_SCREEN_BUFFER_INFO() kernel32.GetConsoleScreenBufferInfo(stream, byref(csbi)) pos = csbi.dwCursorPosition # zero based, add ones for compatibility. return (pos.X + 1, pos.Y + 1)
def get_position(stream=STD_OUTPUT_HANDLE)
Returns current position of cursor, starts at 1.
3.729466
3.154499
1.182269
''' Sets current position of the cursor. ''' stream = kernel32.GetStdHandle(stream) value = x + (y << 16) kernel32.SetConsoleCursorPosition(stream, c_long(value))
def set_position(x, y, stream=STD_OUTPUT_HANDLE)
Sets current position of the cursor.
4.146788
4.316494
0.960684
''' Returns console title string. https://docs.microsoft.com/en-us/windows/console/getconsoletitle ''' MAX_LEN = 256 buffer_ = create_unicode_buffer(MAX_LEN) kernel32.GetConsoleTitleW(buffer_, MAX_LEN) log.debug('%s', buffer_.value) return buffer_.value
def get_title()
Returns console title string. https://docs.microsoft.com/en-us/windows/console/getconsoletitle
4.023139
2.844333
1.41444
def read_mpq_header(offset=None): if offset: self.file.seek(offset) data = self.file.read(32) header = MPQFileHeader._make( struct.unpack(MPQFileHeader.struct_format, data)) header = header._asdict() if header[...
def read_header(self)
Read the header of a MPQ archive.
2.123724
2.036567
1.042796
if table_type == 'hash': entry_class = MPQHashTableEntry elif table_type == 'block': entry_class = MPQBlockTableEntry else: raise ValueError("Invalid table type.") table_offset = self.header['%s_table_offset' % table_type] table_entr...
def read_table(self, table_type)
Read either the hash or block table of a MPQ archive.
3.130579
2.649826
1.181428
hash_a = self._hash(filename, 'HASH_A') hash_b = self._hash(filename, 'HASH_B') for entry in self.hash_table: if (entry.hash_a == hash_a and entry.hash_b == hash_b): return entry
def get_hash_table_entry(self, filename)
Get the hash table entry corresponding to a given filename.
2.656203
2.527924
1.050745
def decompress(data): compression_type = ord(data[0:1]) if compression_type == 0: return data elif compression_type == 2: return zlib.decompress(data[1:], 15) elif compression_type == 16: retur...
def read_file(self, filename, force_decompress=False)
Read a file from the MPQ archive.
2.81564
2.785645
1.010768
if self.files: return dict((f, self.read_file(f)) for f in self.files) else: raise RuntimeError("Can't extract whole archive without listfile.")
def extract(self)
Extract all the files inside the MPQ archive in memory.
7.569149
6.831352
1.108002
archive_name, extension = os.path.splitext(os.path.basename(self.file.name)) if not os.path.isdir(os.path.join(os.getcwd(), archive_name)): os.mkdir(archive_name) os.chdir(archive_name) for filename, data in self.extract().items(): f = open(filename, 'wb'...
def extract_to_disk(self)
Extract all files and write them to disk.
2.853524
2.683839
1.063225
for filename in filenames: data = self.read_file(filename) f = open(filename, 'wb') f.write(data or b'') f.close()
def extract_files(self, *filenames)
Extract given files from the archive to disk.
3.435697
3.194351
1.075554
hash_types = { 'TABLE_OFFSET': 0, 'HASH_A': 1, 'HASH_B': 2, 'TABLE': 3 } seed1 = 0x7FED7FED seed2 = 0xEEEEEEEE for ch in string.upper(): if not isinstance(ch, int): ch = ord(ch) value = self.encrypt...
def _hash(self, string, hash_type)
Hash a string using MPQ's hash function.
3.779335
3.606861
1.047818
seed1 = key seed2 = 0xEEEEEEEE result = BytesIO() for i in range(len(data) // 4): seed2 += self.encryption_table[0x400 + (seed1 & 0xFF)] seed2 &= 0xFFFFFFFF value = struct.unpack("<I", data[i*4:i*4+4])[0] value = (value ^ (seed1 +...
def _decrypt(self, data, key)
Decrypt hash or block table or a sector.
3.435496
3.381256
1.016041
seed = 0x00100001 crypt_table = {} for i in range(256): index = i for j in range(5): seed = (seed * 125 + 3) % 0x2AAAAB temp1 = (seed & 0xFFFF) << 0x10 seed = (seed * 125 + 3) % 0x2AAAAB temp2 = (s...
def _prepare_encryption_table()
Prepare encryption table for MPQ hash function.
3.128085
2.934564
1.065945
if method != 'get': return None return requests.Request(url=url, params=kwargs.get('params', {})).prepare().url
def key_for_request(self, method, url, **kwargs)
Return a cache key from a given set of request parameters. Default behavior is to return a complete URL for all GET requests, and None otherwise. Can be overriden if caching of non-get requests is desired.
5.677396
5.913678
0.960045
# short circuit if cache isn't configured if not self.cache_storage: resp = super(CachingSession, self).request(method, url, **kwargs) resp.fromcache = False return resp resp = None method = method.lower() request_key = self.key_for_...
def request(self, method, url, **kwargs)
Override, wraps Session.request in caching. Cache is only used if key_for_request returns a valid key and should_cache_response was true as well.
2.707798
2.456049
1.102501
resp = requests.Response() key = self._clean_key(orig_key) path = os.path.join(self.cache_dir, key) try: with open(path, 'rb') as f: # read lines one at a time while True: line = f.readline().decode('utf8').strip(...
def get(self, orig_key)
Get cache entry for key, or return None.
3.834191
3.773208
1.016162
key = self._clean_key(key) path = os.path.join(self.cache_dir, key) with open(path, 'wb') as f: status_str = 'status: {0}\n'.format(response.status_code) f.write(status_str.encode('utf8')) encoding_str = 'encoding: {0}\n'.format(response.encoding) ...
def set(self, key, response)
Set cache entry for key with contents of response.
2.138224
2.086128
1.024973
mod = response.headers.pop('last-modified', None) status = int(response.status_code) rec = (key, status, mod, response.encoding, response.content, json.dumps(dict(response.headers))) with self._conn: self._conn.execute("DELETE FROM cache WHERE key=?", ...
def set(self, key, response)
Set cache entry for key with contents of response.
3.793805
3.498367
1.08445
query = self._conn.execute("SELECT * FROM cache WHERE key=?", (key,)) rec = query.fetchone() if rec is None: return None rec = dict(zip(self._columns, rec)) if self.check_last_modified: if rec['modified'] is None: return None # n...
def get(self, key)
Get cache entry for key, or return None.
3.131333
3.041177
1.029645
if callable(dest): return dest elif hasattr(dest, 'write') or isinstance(dest, string_types): return _use_filehandle_to_save(dest) else: raise TypeError("Destination must be a string, writable or callable object.")
def _make_destination_callable(dest)
Creates a callable out of the destination. If it's already callable, the destination is returned. Instead, if the object is a string or a writable object, it's wrapped in a closure to be used later.
4.468129
3.954662
1.129838
errors = [] DEFAULT_ERROR_MSG = '{0!r}({1!r}, {2!r}) returned False' for validator in self._validators: try: if not validator(filehandle, metadata): msg = DEFAULT_ERROR_MSG.format(validator, filehandle, metadata) raise...
def _validate(self, filehandle, metadata, catch_all_errors=False)
Runs all attached validators on the provided filehandle. In the base implmentation of Transfer, the result of `_validate` isn't checked. Rather validators are expected to raise UploadError to report failure. `_validate` can optionally catch all UploadErrors that occur or bail out ...
2.769903
2.57972
1.073723
"Runs all attached preprocessors on the provided filehandle." for process in self._preprocessors: filehandle = process(filehandle, metadata) return filehandle
def _preprocess(self, filehandle, metadata)
Runs all attached preprocessors on the provided filehandle.
7.099605
3.869582
1.834721
"Runs all attached postprocessors on the provided filehandle." for process in self._postprocessors: filehandle = process(filehandle, metadata) return filehandle
def _postprocess(self, filehandle, metadata)
Runs all attached postprocessors on the provided filehandle.
6.911774
3.913542
1.766117
destination = destination or self._destination if destination is None: raise RuntimeError("Destination for filehandle must be provided.") elif destination is not self._destination: destination = _make_destination_callable(destination) if metadata is Non...
def save(self, filehandle, destination=None, metadata=None, validate=True, catch_all_errors=False, *args, **kwargs)
Saves the filehandle to the provided destination or the attached default destination. Allows passing arbitrary positional and keyword arguments to the saving mechanism :param filehandle: werkzeug.FileStorage instance :param dest: String path, callable or writable destination to pass the...
3.060877
3.329071
0.919439
result = self.request(method, url, data=body, **kwargs) result.code = result.status_code # backwards compat if not filename: fd, filename = tempfile.mkstemp(dir=dir) f = os.fdopen(fd, 'wb') else: f = open(filename, 'wb') f.write(r...
def urlretrieve(self, url, filename=None, method='GET', body=None, dir=None, **kwargs)
Save result of a request to a file, similarly to :func:`urllib.urlretrieve`. If an error is encountered may raise any of the scrapelib `exceptions`_. A filename may be provided or :meth:`urlretrieve` will safely create a temporary file. If a directory is provided, a file will b...
2.702726
2.833006
0.954014
''' Make a best effort to automatically determine whether to enable ANSI sequences, and if so, which color palettes are available. This is the main function of the module—meant to be used unless something more specific is needed. Takes the following factors into account: -...
def choose_palette(stream=sys.stdout, basic_palette=None)
Make a best effort to automatically determine whether to enable ANSI sequences, and if so, which color palettes are available. This is the main function of the module—meant to be used unless something more specific is needed. Takes the following factors into account: - Whether...
8.357796
2.46672
3.388222
''' Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Returns: Bool: Allowed ''' result = True # generally yes - env.CLICOLOR != '0' if color_is_disabled(): result = False log.debug('%r', result) return ...
def color_is_allowed()
Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Returns: Bool: Allowed
17.505177
4.810261
3.639133
''' Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_DISABLED='1'`` Returns: None, Bool: D...
def color_is_disabled(**envars)
Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_DISABLED='1'`` Returns: None, Bool: Disabled
6.075236
2.618479
2.320139
''' Look for clues in environment, e.g.: - https://bixense.com/clicolors/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_FORCED='1'`` Returns: Bool: Forced ''' result = env.CLICOLOR_...
def color_is_forced(**envars)
Look for clues in environment, e.g.: - https://bixense.com/clicolors/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_FORCED='1'`` Returns: Bool: Forced
6.270462
2.481023
2.527369
''' Returns whether we think the terminal supports basic, extended, or truecolor. None if not able to tell. Returns: None or str: 'basic', 'extended', 'truecolor' ''' result = col_init = win_enabled = None TERM = env.TERM or '' if os_name == 'nt': from .windows ...
def detect_palette_support(basic_palette=None)
Returns whether we think the terminal supports basic, extended, or truecolor. None if not able to tell. Returns: None or str: 'basic', 'extended', 'truecolor'
5.351004
4.511105
1.186185
''' Try to detect unicode (utf8?) support in the terminal. Experimental, implementation idea is from the link below: https://unix.stackexchange.com/questions/184345/detect-how-much-of-unicode-my-terminal-supports-even-through-screen TODO: needs improvement. # sho...
def detect_unicode_support()
Try to detect unicode (utf8?) support in the terminal. Experimental, implementation idea is from the link below: https://unix.stackexchange.com/questions/184345/detect-how-much-of-unicode-my-terminal-supports-even-through-screen TODO: needs improvement. # should retu...
8.045329
3.161172
2.545046
''' Find the platform-dependent 16-color basic palette. This is used for "downgrading to the nearest color" support. ''' pal_name = 'default (xterm)' basic_palette = color_tables.xterm_palette4 if env.SSH_CLIENT: # fall back to xterm over ssh, info often wrong pal_name = 'ssh (xter...
def _find_basic_palette(result)
Find the platform-dependent 16-color basic palette. This is used for "downgrading to the nearest color" support.
5.280399
4.678512
1.128649
''' Given a chosen palette, returns tuple of those available, or None when not found. Because palette support of a particular level is almost always a superset of lower levels, this should return all available palettes. Returns: Boolean, None: is tty or None if not foun...
def get_available_palettes(chosen_palette)
Given a chosen palette, returns tuple of those available, or None when not found. Because palette support of a particular level is almost always a superset of lower levels, this should return all available palettes. Returns: Boolean, None: is tty or None if not found.
10.462714
2.04504
5.116142
''' Detect terminal or something else, such as output redirection. Returns: Boolean, None: is tty or None if not found. ''' result = stream.isatty() if hasattr(stream, 'isatty') else None log.debug(result) return result
def is_a_tty(stream=sys.stdout)
Detect terminal or something else, such as output redirection. Returns: Boolean, None: is tty or None if not found.
9.458165
3.193271
2.961905
''' Load and parse X11's rgb.txt. Loads: x11_color_map: { name_lower: ('R', 'G', 'B') } ''' if type(paths) is str: paths = (paths,) x11_color_map = color_tables.x11_color_map for path in paths: try: with open(path) as infile: for line...
def load_x11_color_map(paths=X11_RGB_PATHS)
Load and parse X11's rgb.txt. Loads: x11_color_map: { name_lower: ('R', 'G', 'B') }
3.593284
2.847053
1.262107
''' Parse the color table for the Linux console. ''' palette = () table = [] try: with open(path) as infile: for i, line in enumerate(infile): row = tuple(int(val) for val in line.split(',')) table.append(row) if i == 2: # failsafe ...
def parse_vtrgb(path='/etc/vtrgb')
Parse the color table for the Linux console.
5.812042
5.184038
1.121142
''' POSIX implementation of get char/key. ''' import tty with TermStack() as fd: tty.setraw(fd) return sys.stdin.read(1)
def _getch()
POSIX implementation of get char/key.
18.694971
9.411085
1.986484
''' Read a terminal response of up to a few characters from stdin. ''' chars = [] read = infile.read if not isinstance(end, tuple): end = (end,) # count down, stopping at 0 while maxchars: char = read(1) if char in end: break chars.append(char) ...
def _read_until(infile=sys.stdin, maxchars=20, end=RS)
Read a terminal response of up to a few characters from stdin.
5.074483
3.664343
1.384828
''' Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline. Returns: tuple(int): (x, y), (,) - empty, if an error occurred. TODO: needs non-ansi mode for Windows Note: Checks is_a_tty() first, since ...
def get_position(fallback=CURSOR_POS_FALLBACK)
Return the current column number of the terminal cursor. Used to figure out if we need to print an extra newline. Returns: tuple(int): (x, y), (,) - empty, if an error occurred. TODO: needs non-ansi mode for Windows Note: Checks is_a_tty() first, since function...
11.259286
4.537234
2.481531
''' Return the terminal/console title. Arguments: str: mode, one of ('title', 'icon') or int (20-21): see links below. - `Control sequences <http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Operating-System-Commands>`_ Returns: ...
def get_title(mode='title')
Return the terminal/console title. Arguments: str: mode, one of ('title', 'icon') or int (20-21): see links below. - `Control sequences <http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Operating-System-Commands>`_ Returns: title ...
8.172302
3.694785
2.211848
''' Checks system for theme information. First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color(). Returns: str, None: 'dark', 'light', None if no information. ''' theme...
def get_theme()
Checks system for theme information. First checks for the environment variable COLORFGBG. Next, queries terminal, supported on Windows and xterm, perhaps others. See notes on get_color(). Returns: str, None: 'dark', 'light', None if no information.
5.408934
3.36091
1.609366
"Don't actually use this, it's just an example." return sum([os.path.getsize(fp) for fp in list_files(path)])
def really_bad_du(path)
Don't actually use this, it's just an example.
6.970355
4.654186
1.497653
# limit it at twenty kilobytes if no default is provided MAX_DISK_USAGE = current_app.config.get('MAX_DISK_USAGE', 20 * 1024) CURRENT_USAGE = really_bad_du(current_app.config['UPLOAD_PATH']) filehandle.seek(0, os.SEEK_END) if CURRENT_USAGE + filehandle.tell() > MAX_DISK_USAGE: filehand...
def check_disk_usage(filehandle, meta)
Checks the upload directory to see if the uploaded file would exceed the total disk allotment. Meant as a quick and dirty example.
4.805426
4.401899
1.091671
''' Read version as text to avoid machinations at import time. ''' with open(filename) as infile: for line in infile: if line.startswith('__version__'): try: version = line.split("'")[1] except IndexError: pass ...
def get_version(filename, version='1.00')
Read version as text to avoid machinations at import time.
4.410717
2.495912
1.767177
if not header or '=' not in header: return None ranges = [] units, range_ = header.split('=', 1) units = units.strip().lower() if units != 'bytes': return None for val in range_.split(','): val = val.strip() if '...
def parse_range_header(self, header, resource_size)
Parses a range header into a list of two-tuples (start, stop) where `start` is the starting byte of the range (inclusive) and `stop` is the ending byte position of the range (exclusive). Args: header (str): The HTTP_RANGE request header. resource_size (int): The size of ...
3.253106
3.310292
0.982725
self['Accept-Ranges'] = 'bytes' size = self.ranged_file.size try: ranges = self.ranged_file.parse_range_header(range_header, size) except ValueError: ranges = None # Only handle syntactically valid headers, that are simple (no # multipart ...
def add_range_headers(self, range_header)
Adds several headers that are necessary for a streaming file response, in order for Safari to play audio files. Also sets the HTTP status_code to 206 (partial content). Args: range_header (str): Browser HTTP_RANGE request header.
2.892528
2.968979
0.97425
''' Create the color tables for palette downgrade support, starting with the platform-specific 16 from the color tables module. Save as global state. :-/ ''' base = [] if base is None else base # make sure we have them before clearing table4 = _build_color_table(base, extend...
def build_color_tables(base=color_tables.vga_palette4)
Create the color tables for palette downgrade support, starting with the platform-specific 16 from the color tables module. Save as global state. :-/
6.895671
2.824299
2.441551
''' Given three integers representing R, G, and B, return the nearest color index. Arguments: r: int - of range 0…255 g: int - of range 0…255 b: int - of range 0…255 Returns: int, None: index, or None on error. ''' shortest_d...
def find_nearest_color_index(r, g, b, color_table=None, method='euclid')
Given three integers representing R, G, and B, return the nearest color index. Arguments: r: int - of range 0…255 g: int - of range 0…255 b: int - of range 0…255 Returns: int, None: index, or None on error.
3.516968
2.426232
1.44956
''' Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456' Returns: int, None: index, or None on error. ''' triplet = [] try: if len(hexdigits) == 3...
def find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid')
Given a three or six-character hex digit string, return the nearest color index. Arguments: hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456' Returns: int, None: index, or None on error.
3.094069
1.850814
1.671734
''' Inserts an interval to the tree. Note that when inserting we do not maintain appropriate sorting of the "mid" data structure. This should be done after all intervals are inserted. ''' # Ignore intervals of 0 or negative length if (end - start) <= 0: ...
def add_interval(self, start, end, data=None)
Inserts an interval to the tree. Note that when inserting we do not maintain appropriate sorting of the "mid" data structure. This should be done after all intervals are inserted.
5.482042
3.187893
1.719644
''' Must be invoked after all intevals have been added to sort mid_** arrays. ''' if self.single_interval is None or self.single_interval != 0: return # Nothing to do for empty and leaf trees. self.mid_sorted_by_start.sort(key = lambda x: x[0]) self.mid_sorted...
def sort(self)
Must be invoked after all intevals have been added to sort mid_** arrays.
4.712543
2.75615
1.709828
''' Same as self.query, but uses a provided list to accumulate results into. ''' if self.single_interval is None: # Empty return elif self.single_interval != 0: # Single interval, just check whether x is in it if self.single_interval[0] <= x < self.single...
def _query(self, x, result)
Same as self.query, but uses a provided list to accumulate results into.
3.369088
2.881224
1.169325
current_state = dfa['initial_state'] for action in word: if (current_state, action) in dfa['transitions']: current_state = dfa['transitions'][current_state, action] else: return False if current_state in dfa['accepting_states']: return True else: ...
def dfa_word_acceptance(dfa: dict, word: list) -> bool
Checks if a given **word** is accepted by a DFA, returning True/false. The word w is accepted by a DFA if DFA has an accepting run on w. Since A is deterministic, :math:`w ∈ L(A)` if and only if :math:`ρ(s_0 , w) ∈ F` . :param dict dfa: input DFA; :param list word: list of actions ∈ dfa['alpha...
2.360946
2.152792
1.09669
dfa['states'].add('sink') for state in dfa['states']: for action in dfa['alphabet']: if (state, action) not in dfa['transitions']: dfa['transitions'][state, action] = 'sink' return dfa
def dfa_completion(dfa: dict) -> dict
Side effects on input! Completes the DFA assigning to each state a transition for each letter in the alphabet (if not already defined). We say that a DFA is complete if its transition function :math:`ρ:S×Σ→S` is a total function, that is, for all :math:`s ∈ S` and all :math:`a ∈ Σ` we have that ...
3.548821
2.943996
1.205444
dfa_complement = dfa_completion(deepcopy(dfa)) dfa_complement['accepting_states'] = \ dfa_complement['states'].difference(dfa_complement['accepting_states']) return dfa_complement
def dfa_complementation(dfa: dict) -> dict
Returns a DFA that accepts any word but he ones accepted by the input DFA. Let A be a completed DFA, :math:`Ā = (Σ, S, s_0 , ρ, S − F )` is the DFA that runs A but accepts whatever word A does not. :param dict dfa: input DFA. :return: *(dict)* representing the complement of the input DFA.
4.032465
4.159593
0.969437
intersection = { 'alphabet': dfa_1['alphabet'].intersection(dfa_2['alphabet']), 'states': {(dfa_1['initial_state'], dfa_2['initial_state'])}, 'initial_state': (dfa_1['initial_state'], dfa_2['initial_state']), 'accepting_states': set(), 'transitions': dict() } bo...
def dfa_intersection(dfa_1: dict, dfa_2: dict) -> dict
Returns a DFA accepting the intersection of the DFAs in input. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two DFAs. Then there is a DFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word and accepts w...
1.660064
1.693225
0.980416
dfa_1 = deepcopy(dfa_1) dfa_2 = deepcopy(dfa_2) dfa_1['alphabet'] = dfa_2['alphabet'] = dfa_1['alphabet'].union( dfa_2['alphabet']) # to complete the DFAs over all possible transition dfa_1 = dfa_completion(dfa_1) dfa_2 = dfa_completion(dfa_2) union = { 'alphabet': dfa_1['...
def dfa_union(dfa_1: dict, dfa_2: dict) -> dict
Returns a DFA accepting the union of the input DFAs. Let :math:`A_1 = (Σ, S_1 , s_{01} , ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s_{02} , ρ_2 , F_2 )` be two completed DFAs. Then there is a DFA :math:`A_∨` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word and accepts w...
2.131877
2.124067
1.003677
reachable_states = set() # set of reachable states from root boundary = set() reachable_states.add(dfa['initial_state']) boundary.add(dfa['initial_state']) while boundary: s = boundary.pop() for a in dfa['alphabet']: if (s, a) in dfa['transitions']: ...
def dfa_reachable(dfa: dict) -> dict
Side effects on input! Removes unreachable states from a DFA and returns the pruned DFA. It is possible to remove from a DFA A all unreachable states from the initial state without altering the language. The reachable DFA :math:`A_R` corresponding to A is defined as: :math:`A_R = (Σ, S_R , s_0 , ρ...
2.912537
3.101532
0.939064
co_reachable_states = dfa['accepting_states'].copy() boundary = co_reachable_states.copy() # inverse transition function inverse_transitions = dict() for key, value in dfa['transitions'].items(): inverse_transitions.setdefault(value, set()).add(key) while boundary: s = bo...
def dfa_co_reachable(dfa: dict) -> dict
Side effects on input! Removes from the DFA all states that do not reach a final state and returns the pruned DFA. It is possible to remove from a DFA A all states that do not reach a final state without altering the language. The co-reachable dfa :math:`A_F` corresponding to A is defined as: ...
2.549942
2.46348
1.035098
# Reachable DFA dfa = dfa_reachable(dfa) # Co-reachable DFA dfa = dfa_co_reachable(dfa) # trimmed DFA return dfa
def dfa_trimming(dfa: dict) -> dict
Side effects on input! Returns the DFA in input trimmed, so both reachable and co-reachable. Given a DFA A, the corresponding trimmed DFA contains only those states that are reachable from the initial state and that lead to a final state. The trimmed dfa :math:`A_{RF}` corresponding to A is defined...
5.434408
4.137195
1.313549
nfa = { 'alphabet': dfa['alphabet'].difference(symbols_to_remove), 'states': dfa['states'].copy(), 'initial_states': {dfa['initial_state']}, 'accepting_states': dfa['accepting_states'].copy(), 'transitions': dict() } current_nfa_transitions = None current_e_...
def dfa_projection(dfa: dict, symbols_to_remove: set) -> dict
Returns a NFA that reads the language recognized by the input DFA where all the symbols in **symbols_to_project** are projected out of the alphabet. Projection in a DFA is the operation that existentially removes from a word all occurrence of symbols in a set X. Given a dfa :math:`A = (Σ, S, s_0 , ...
2.786354
2.747416
1.014172
# BFS queue = [dfa['initial_state']] visited = set() visited.add(dfa['initial_state']) while queue: state = queue.pop(0) # TODO note that this pop is applied to a list # not like in sets visited.add(state) for a in dfa['alphabet']: if (state, a) in d...
def dfa_nonemptiness_check(dfa: dict) -> bool
Checks if the input DFA is nonempty (i.e. if it recognizes a language except the empty one), returning True/False. An automaton A is nonempty if :math:`L(A) ≠ ∅`. L(A) is nonempty iff there are states :math:`s_0 and t ∈ F` such that t is connected to :math:`s_0`. Thus, automata nonemptiness is equi...
3.004994
3.023498
0.99388
conversion_dict = dict() new_states = set() new_accepting = set() for state in dfa['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in dfa['accepting_states']: new_accepting.add('' + suffix + state) dfa['st...
def rename_dfa_states(dfa: dict, suffix: str)
Side effect on input! Renames all the states of the DFA adding a **suffix**. It is an utility function to be used to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict dfa: input DFA. :param str suffix: string to be ...
2.033496
2.171726
0.93635
''' Loads all LiftOverChain objects from a file into an array. Returns the result. ''' chains = [] while True: line = f.readline() if not line: break if line.startswith(b'#') or line.startswith(b'\n') or line.startswith(b'\r'): ...
def _load_chains(f)
Loads all LiftOverChain objects from a file into an array. Returns the result.
4.013556
2.295539
1.748416
''' Given a list of LiftOverChain objects, creates a dict: source_name --> IntervalTree: <source_from, source_to> --> (target_from, target_to, chain) Returns the resulting dict. Throws an exception on any errors or inconsistencies among chains (e.g. ...
def _index_chains(chains)
Given a list of LiftOverChain objects, creates a dict: source_name --> IntervalTree: <source_from, source_to> --> (target_from, target_to, chain) Returns the resulting dict. Throws an exception on any errors or inconsistencies among chains (e.g. different sizes spec...
3.058445
1.798211
1.700827
''' Given a chromosome and position, returns all matching records from the chain index. Each record is an interval (source_from, source_to, data) where data = (target_from, target_to, chain). Note that depending on chain.target_strand, the target values may need to be reversed (e.g. pos ...
def query(self, chromosome, position)
Given a chromosome and position, returns all matching records from the chain index. Each record is an interval (source_from, source_to, data) where data = (target_from, target_to, chain). Note that depending on chain.target_strand, the target values may need to be reversed (e.g. pos --> chain.target_siz...
7.291105
2.61593
2.787195
try: r = requests.get( url='http://widgets.vvo-online.de/abfahrtsmonitor/Abfahrten.do', params={ 'ort': city, 'hst': stop, 'vz': offset, 'lim': limit, }, ) if r.status_code == 200: ...
def monitor(stop, offset=0, limit=10, city='Dresden', *, raw=False)
VVO Online Monitor (GET http://widgets.vvo-online.de/abfahrtsmonitor/Abfahrten.do) :param stop: Name of Stop :param offset: Minimum time of arrival :param limit: Count of returned results :param city: Name of City :param raw: Return raw response :return: Dict of stops
3.398751
2.701914
1.257905
assert deparr == 'dep' or deparr == 'arr' time = datetime.now() if time is None else datetime.fromtimestamp(int(time)) url = 'http://efa.faplino.de/dvb/XML_TRIP_REQUEST2' if eduroam \ else 'http://efa.vvo-online.de:8080/dvb/XML_TRIP_REQUEST2' try: r = requests.get( u...
def route(origin, destination, city_origin='Dresden', city_destination='Dresden', time=None, deparr='dep', eduroam=False, recommendations=False, *, raw=False)
VVO Online EFA TripRequest (GET http://efa.vvo-online.de:8080/dvb/XML_TRIP_REQUEST2) :param origin: Origin of route :param destination: Destination of route :param city_origin: City of origin :param city_destination: City of destination :param time: Unix timestamp of departure :param deparr...
3.490352
3.024826
1.153902
url = 'http://efa.faplino.de/dvb/XML_STOPFINDER_REQUEST' if eduroam \ else 'http://efa.vvo-online.de:8080/dvb/XML_STOPFINDER_REQUEST' try: r = requests.get( url=url, params={ 'locationServerActive': '1', 'outputFormat': 'JSON', ...
def find(search, eduroam=False, *, raw=False)
VVO Online EFA Stopfinder (GET http://efa.vvo-online.de:8080/dvb/XML_STOPFINDER_REQUEST) :param search: Stop to find :param eduroam: Request from eduroam :param raw: Return raw response :return: All matching stops
4.728065
3.532331
1.338511