content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os import sys import importlib def load( path ): """ Loads a Python module from a path to a file. @param path The path to the Python file to load as a module @return A reference to the module """ # Normalize and parse path to script. path = os.path.realpath( path ) basename = os.path.basename( path ) dirname = os.path.dirname( path ) name, extension = os.path.splitext( basename ) # Remove any possible existing reference from the modules dictionary. if name in sys.modules: del sys.modules[ name ] # Prepend the directory to this file to the path list. sys.path.insert( 0, dirname ) # Import the module. module = importlib.import_module( name ) # Remove reference to module from modules dictionary. del sys.modules[ name ] # Remove the directory from path list. sys.path.pop( 0 ) # Return the reference to the module. return module
a38fbc7ea99d1a30787cd7d310cfa6b4e49ba2f0
25,960
def timestring(min_): """ input: floating point minutes output: sensible time string""" if min_ < 0.01: return "%.4f minutes = %.3f seconds"%(min_, min_*60.0) elif 0.01 <= min_ and min_ < 1.0: return "%.3f minutes = %.2f seconds"%(min_, min_*60.0) elif 1.0 <= min_ and min_ < 60.0: return "%.3f minutes = %.3f hours"%(min_, min_/60.0) elif min_ >= 60.0: return "%.0f minutes = %.1f hours"%(min_, min_/60.0) else: return "invalid time value"
16ff8281a86be483e6af214223b9a27f428a30fa
25,962
from typing import List def add_to_leftmost_int(stack: List, x: int) -> List: """ Add x to leftmost int in l if no int in l, do nothing return modified l """ int_locations = [isinstance(i, int) for i in stack] if not any(int_locations): return stack index = int_locations.index(True) stack[index] += x return stack
c110df6643b98ddf7a3c18933fc1911bc247a138
25,965
def squareT(A): """ Returns (A Aᵀ) """ return A.dot(A.T)
ea214c8cccfff2146b66013fc00f06d6cbfc0337
25,966
import os def get_config_options(): """Loads configuration environment variables. In case it is not previously set, returns a default value for each one. Returns a dictionary object. """ config_options = {} config_options['JOIN_PARTITION_SIZE_THRESHOLD'] = os.environ.get("JOIN_PARTITION_SIZE_THRESHOLD", 300000000) config_options['BLAZING_DEVICE_MEM_CONSUMPTION_THRESHOLD'] = os.environ.get("BLAZING_DEVICE_MEM_CONSUMPTION_THRESHOLD", 0.8) config_options['BLAZING_LOGGING_DIRECTORY'] = os.environ.get("BLAZING_LOGGING_DIRECTORY", 'blazing_log') config_options['MAX_DATA_LOAD_CONCAT_CACHE_BYTE_SIZE'] = os.environ.get("MAX_DATA_LOAD_CONCAT_CACHE_BYTE_SIZE", 300000000) config_options['BLAZING_CACHE_DIRECTORY'] = os.environ.get("BLAZING_CACHE_DIRECTORY", '/tmp/') return config_options
760f84a85da23e11ec6bbdefda902adcc2115db8
25,967
import random import string def generate_strong_pass(): """ Generates a password from letters, digits and punctuation :return: password :rtype: str """ length = random.randint(10, 15) password_characters = \ string.ascii_letters + \ string.digits + \ string.punctuation return ''.join(random.choice(password_characters) for i in range(length))
db826ebf7c204bb7617186327fd07ca01316c787
25,968
def reinforce(log_prob, f, **kwargs): """ Based on https://github.com/pytorch/examples/blob/master/reinforcement_learning/reinforce.py """ policy_loss = (-log_prob) * f.detach() return policy_loss
e5b0263c6c6b13c471637c5023b1018bc9c0ce0c
25,969
def _reverse_bits(val: int, nbits: int) -> int: """ """ i = 0 newval = 0 while i < nbits: mask = 0x1 << i newval |= ((mask & val) >> i) << (nbits - 1 - i) i += 1 return newval
39c5699409566d731ca65f8ab2d20f9e3e801e9f
25,970
def GetVectorValue(item): """Given an smtk.attribute.Item, return a list containing its values.""" N = item.numberOfValues() return [item.value(i) for i in range(N)]
573468b6416126553774a97de70b99c069390754
25,971
import platform import inspect def _get_mro(cls): """ Returns the bases classes for cls sorted by the MRO. Works around an issue on Jython where inspect.getmro will not return all base classes if multiple classes share the same name. Instead, this function will return a tuple containing the class itself, and the contents of cls.__bases__. See https://github.com/pypa/setuptools/issues/1024. """ if platform.python_implementation() == "Jython": return (cls,) + cls.__bases__ return inspect.getmro(cls)
d6e402e774078788020553c41a2a693591dac88a
25,972
def format_metrics(d: dict) -> dict: """ Format the floats in a dict with nested dicts, for display. :param d: dict containing floats to format :return: new dict matching the original, except with formatted floats """ new = {} for key in d: if isinstance(d[key], dict): new[key] = format_metrics(d[key]) elif isinstance(d[key], float): new[key] = float("{:.8f}".format(d[key])) else: new[key] = d[key] return new
1be92878ce97db21b7775345a9a830c42265a5c8
25,973
def titlecomment(line): """Condition for a line to be a title comment""" return line.startswith('//') and len(line.lstrip('//').strip()) > 0
a1a1f44e01399c4a3511670146d1e2587d9ead26
25,974
def session(context_name="session", request=None, **kwargs): """Returns the session associated with the current request""" return request and request.context.get(context_name, None)
e379e2fbf313557aa8c5087c8c0d75a5738243fe
25,975
def get_cor_region(cor, cij, qid, fitw): """YG developed@CHX July/2019, Get a rectangle region of the cor class by giving center and width""" ceni = cor.centers[qid] x1, x2, y1, y2 = ( max(0, ceni[0] - fitw), ceni[0] + fitw, max(0, ceni[1] - fitw), ceni[1] + fitw, ) return cij[qid][x1:x2, y1:y2]
e2108e440989640298030046bad17e7542c0caae
25,976
def filter_tweets_on_polarity(tweets, keep_positive=True): """Filter the tweets by polarity score, receives keep_positive bool which determines what to keep. Returns a list of filtered tweets.""" sorted_tweets = [] for tweet in tweets: if keep_positive and tweet.polarity > 0: sorted_tweets.append(tweet) elif not keep_positive and tweet.polarity < 0: sorted_tweets.append(tweet) return sorted_tweets
2a0b95929ca7bfc459cb4ba6354a41de69403412
25,977
def extract_tags(cgx_dict): """ This function looks at a CloudGenix config object, and gets tags. :param cgx_dict: CloudGenix config dict, expects "tags" keys supported in root. :return: list of tags present. """ # tags exist, return them. tags = cgx_dict.get("tags", []) if tags is None: tags = [] # return unique tags. return list(set(tags))
b2b78f46c65d4ca7c9c3ae0ed54a9d2a4da80724
25,980
def pluralize(n, s): """Return a count of objects.""" if n == 1: return f'1 {s}' else: return f'{n} {s}s'
612ebc529d4cb86bb752254714eba5de517accf5
25,981
import os import time def output_filename(directory, prefix, extension): """ Create an output file in given directory with given prefix, a timestamp, and given extension. The directory will be created if it does not exist. :param directory: directory path to put the file in :param prefix: file prefix :param extension: file extension :return: file path :raise IOError: directory could not be created. """ if not os.path.exists(directory): os.makedirs(directory) return os.path.join(directory, '{0}-{1}.{2}'.format( prefix, time.strftime("%Y%m%d-%H%M%S"), extension))
015e8795919cea3da2aa08a5de67ed56534dbde6
25,982
def _get_subclasses(base_class): """Returns all subclasses to the base class passed. :param base_class: :type base_class: str :return: The list of child classes. :rtype: list """ classes_to_check = base_class.__subclasses__() subclasses = [] while classes_to_check: subclass = classes_to_check.pop() subclasses.append(subclass) return subclasses
da53f82db973144264bad2452381fadef10cf3d2
25,984
def es(list_data,name): """ source_region数据处理 :param list_data: :return: """ res_list = [] for data in list_data: if len(res_list) == 0: res_list.append(data) else: num = 0 for res_data in res_list: num = num + 1 if res_data[name] == data[name]: break elif num == len(res_list): res_list.append(data) return res_list
c87c1d9f9f9b4c29610cdbb98e3e4d9a9c2763fa
25,986
def split_outfile(line): """ Split the output file from a command. """ redirect = line.find('>') if redirect == -1: return line, None else: return line[:redirect].rstrip(), line[redirect+1:].lstrip()
0ba0f76132256d87c61c6e98d9e5e6d310b04d6c
25,987
def export_model_and_tokens_per_group(out, id_nr, tm, n:int, tokens:list, theta:list, dates:list): """Exports a json dictionary with topic modeling results per group Args: out: dictionary of main results id_nr: group_id of the group tm: topic model n: number of topics used for topic modeling tokens: list of tokens theta: list of theta values dates: list of dates Returns: fills the original dictionary with values for a single group's tm results """ id_nr = str(int(id_nr)) out[id_nr] = {} out[id_nr]["model"] = tm.model out[id_nr]["nr_of_topics"] = n out[id_nr]["tokenlists"] = tm.tokenlists out[id_nr]["tokens"] = tokens out[id_nr]["theta"] = theta out[id_nr]["dates"] = dates return out
56356bf3f1cea51035eeab2110132d4e61664f02
25,991
def calculate_turnaroundtime( burst_time: list[int], no_of_processes: int, waiting_time: list[int] ) -> list[int]: """ Calculate the turnaround time of each process. Return: The turnaround time for each process. >>> calculate_turnaroundtime([0,1,2], 3, [0, 10, 15]) [0, 11, 17] >>> calculate_turnaroundtime([1,2,2,4], 4, [1, 8, 5, 4]) [2, 10, 7, 8] >>> calculate_turnaroundtime([0,0,0], 3, [12, 0, 2]) [12, 0, 2] """ turn_around_time = [0] * no_of_processes for i in range(no_of_processes): turn_around_time[i] = burst_time[i] + waiting_time[i] return turn_around_time
cac09f266599293abfd2f90d22523444556c3204
25,992
def dessineGrille(canvas, listeGrille, longueurGrille, gridSize): """ Cette fonction a pour but de dessiner la grille de couleurs. Arguments: canvas = La variable contenant le canvas. listeGrille = La grille de couleurs. longueurGrille = La longueur de la grille en pixels. gridSize = Le nombre de cubes qui seront dans la grille (15x15 ou 5x5). Retourne la longueur d'un cube afin de pouvoir la récuperer lors d'un clique """ cubeLongueur = longueurGrille // gridSize + 1 # Taille des cubes qui vont constituer la grille for ligne in range(len(listeGrille)): for colonne in range(len(listeGrille[ligne])): couleurCase = listeGrille[ligne][colonne] # Coordonnées des rectangles x1, y1 = cubeLongueur * ligne, cubeLongueur * colonne x2, y2 = x1 + cubeLongueur, y1 + cubeLongueur # Dessine le rectangle sur la grille canvas.create_rectangle(x1, y1, x2, y2, fill = couleurCase, outline = "black", width = 1) return cubeLongueur
272e621e86700118a4b7d172c5091bb05c1d77a6
25,993
def content_type(content_type): """ Decorator to set a specific content_type to one method (get, post...) """ def decorated(func): func.CONTENT_TYPE = content_type return func return decorated
65dcaee411b54665ea0953b767dcc252c6097e68
25,994
import logging import tarfile import os def extract_rfc_tgz(tgz_path: str, extract_to: str, LOGGER: logging.Logger): """ Extract downloaded rfc.tgz file to directory and remove file. Arguments: :param tgz_path (str) full path to the rfc.tgz file :param extract_to (str) path to the directory where rfc.tgz is extractracted to :param LOGGER (logging.Logger) formated logger with the specified name """ tar_opened = False tgz = '' try: tgz = tarfile.open(tgz_path) tar_opened = True tgz.extractall(extract_to) tgz.close() except tarfile.ReadError: LOGGER.warning('tarfile could not be opened. It might not have been generated yet.' ' Did the sdo_analysis cron job run already?') os.remove(tgz_path) return tar_opened
8bd39056226e30672ad761c53b5c9d5afd815a45
25,995
def distinct_dict_list(dict_list: list): """ 返回去重后字典列表,仅支持value为不可变对象的字典 :param dict_list: 字典列表 :return: 去重后的字典列表 """ return [dict(tupl) for tupl in set([tuple(sorted(item.items())) for item in dict_list])]
0f97361089ac36677206262c9d28fa36bb156e59
25,996
def append_gw_teams(df, df_match): """ Count the number of teams playing in a single gameweek :param df: Input DataFrame (must contain 'player_id', 'gw' columns) :param df: Match DataFrame :returns: Input DataFrame with 'gw_teams_ft' column appended """ df = df.copy() df_teams = (df_match.groupby('gw')['team_id'].nunique() .reset_index() .rename(columns={'team_id':'gw_teams_ft'})) return df.merge(df_teams, on='gw').sort_values(['player_id', 'gw'])
1ff1798d51268d1aa111ebf6763725abd674bc44
25,998
import os.path def check_file(path): """ This function.. :param path: :return: """ full = os.path.abspath(path) if os.path.exists(full): return full return None
af41e908ccc15faf297a386b23043577e79d7afb
25,999
def convert_weight_pounds(weight) -> int: """ Converts Kilograms into Pounds """ pounds = round((weight * 2.20462), 5) return pounds
edc50cbc4bc8f6a40b354376b3d42fedc8097698
26,000
from typing import Any from typing import TypeGuard from typing import Callable from typing import Coroutine import asyncio def acallable(arg: Any) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: """Type guard for coroutine (async) functions""" return callable(arg) and asyncio.iscoroutinefunction(arg)
c81ed04cc07f20148356be60eddb89fad9bf061e
26,001
def fraction_edge(r): """Calculate fraction of coins that landed on edge""" total = r['Edge'] + r['Tails'] + r['Heads'] fraction_edge = r['Edge'] / total return fraction_edge
0153fc983bc9c2ae3f3d7b3cd1940c11671c71ca
26,004
def convert_to_minutes(num_hours): """ (int) -> int Return the number of minutes there are in num_hours hours. >>> convert_to_minutes(2) 120 """ result = num_hours * 60 return result
a959182939cd3a2e6bd4076a706c4993086daa4a
26,006
def _is_cast(**kwargs) -> bool: """ Does this spec require casting """ return 'cast' in kwargs
97a12699408a23a9f2021532ae36071c2254cc99
26,007
import sys def load_module(mod_name): """ Take a string of the form 'fedmsg.consumers.ircbot' and return the ircbot module. """ __import__(mod_name) try: return sys.modules[mod_name] except AttributeError: raise ImportError("%r not found" % (mod_name))
15d936771ad5db29a25ab2a170a88ab9512aed37
26,009
from datetime import datetime def generate_upload_file_path(form_fields): """ Use validated form fields to create the key for S3 """ now = datetime.now().strftime("%Y%m%d-%H%M%S") file_path_to_upload = "{}/{}_{}.{}".format( form_fields["file_location"], now, form_fields["file_name"], form_fields["file_ext"], ) return file_path_to_upload
b981bd059130c953b93fca61fa43b2608f84b07c
26,010
def make_doublebang_pulse_fun(parameters, tf): """Return double-bang pulse function. y0, t1, y1 = parameters For 0 <= t <= t1, constant height y0. For t >= t1, constant height y1. """ y0, t1, y1 = parameters def fun(t, *args): if 0 <= t <= t1: return y0 elif t1 < t <= tf: return y1 else: return 200. return fun
619cdef2117237f683b8d8eea996867cf82c473f
26,011
def filter_target_outliers(data, targets, y_min=1, y_max=60): """Filter data with targets outside of range.""" X = data[(data.duration >= y_min) & (data.duration <= y_max)] y = X.duration.values return X, y
92ffb34ce05766034666013342ec483144b64732
26,012
def peg_by_value(current_peg, current_val): """ Returns for each PEG stage the share value """ result = {} result[current_peg] = {} result[0.5] = {} result[1] = {} result[2] = {} result[3] = {} result[3.6] = {} result[current_peg]['value'] = current_val result[current_peg]['current'] = True result[0.5]['value'] = 0.5 * current_val / current_peg result[0.5]['current'] = False result[1]['value'] = 1 * current_val / current_peg result[1]['current'] = False result[2]['value'] = 2 * current_val / current_peg result[2]['current'] = False result[3]['value'] = 3 * current_val / current_peg result[3]['current'] = False result[3.6]['value'] = 3.6 * current_val / current_peg result[3.6]['current'] = False return result
e28b68f6f17b96198037c4b83c1418b25ba51454
26,013
def clean_background_command(command): """Cleans a command containing background &. :param command: Converted command e.g. ['bash', '$PWD/c1 &'].""" return [x.replace(" &", "") for x in command]
0e4c3a824e938f6dee81414752271da60726f185
26,015
def corrupt_mnist_img(rng, img, value): """Corrupt a single MNIST image. Note that the image itself is MODIFIED. :param rng: instance of numpy.random.RandomState :param img: image to modify. ndarray or compatible :param value: pixel value to use for corrupting the image :return: modified image """ # Choose square size s = rng.randint(7, 15) # Choose top-left corner position x = rng.randint(0, 29 - s) y = rng.randint(0, 29 - s) # Draw square img[..., y:y + s, x:x + s] = value # Return object for convenience return img
97ca969a77d822baf7c369deb832ab87c60b7b8b
26,016
import subprocess def listwindows(): """Return a list of present windows""" s = subprocess.check_output(['9p', 'ls', 'acme']) props = s.decode('utf-8').split('\n') return [int(item) for item in props if item.isdigit()]
10458dcf6ef89120c5356c34bd91428e227069b5
26,017
def surrounding_sourcepos(elems, start_index, end_index=None): """ Find a sourcepos that ranges from the last line of elems[start_index - 1] to the first line of elems[end_index + 1], handling the boundary conditions. """ if end_index is None: end_index = start_index # chosen start element ... if start_index == 0: # ... is first, so start at its first line start = elems[start_index].sourcepos[0] else: # ... isn't first, so start at the previous element's last line start = elems[start_index - 1].sourcepos[1] # chosen end element ... if end_index == len(elems) - 1: # ... is last, so end at its last line end = elems[end_index].sourcepos[1] else: # ... isn't last, so end at the next element's first line end = elems[end_index + 1].sourcepos[0] return [start, end]
0d47b0ae2187c9425d39b505163b73a5d0909624
26,018
def df2node_attr(df): """Convert dataframe to dict keyed by index which can be used to set node attributes with networkx""" # NOTE: df.index has to be the nodes return df.T.to_dict()
718506480f5da95c9c1ab90798d06d9696cacd5b
26,020
def ApplyEach(l, f, args=[]): """ Apply f on each item in l, specific args for f in a list if needed. E.g. l2 = ApplyEach(l,func,['param1', 'param2']) """ if len(args) != 0: return [f(tim, *args) for tim in l] else: return [f(tim) for tim in l]
d29b2df19b037ad2083af0dee12cd9b519fa2909
26,021
def fips2county(fips): """ Return first 5 digits of fips code to get county. Accepts 12 digit FIPS. :param fips: 12 digits fips code, must be string. :return: int - 5 digit fips code """ return fips.zfill(12)[0:5]
71fd2412944421bc981a2a1589d9cb807bc3f215
26,022
import numpy def loadDset_log(dset): """ Loads a dataset containing a logical scalar """ val = numpy.array(dset) return (val == 1)
a14b7c9d5978a2d2fbae42b138d2ad26f0657921
26,024
def get_circularization_info(seq_id): """Retrieves information if contig was circularized Args: seq_id (str): identifier of the target sequence (contig) Returns: bool: returns True if contig was circularized and False otherwise """ with open(f"{seq_id}.circularisationCheck.txt", "r") as f: for line in f: if line == "(False, -1, -1)": return False else: return True
f97e69c6fe586cae5c73d522c8e2e76488c52728
26,025
def vars_builtin(): """vars: Local variables or object attributes if obj.__dict__ exists.""" return "{} wolf".format( locals() == vars() and [name for name in vars(str) if 'alp' in name][0])
f28eb20c8e6fb9a6e24a955afefcc8dc1c74cf9a
26,026
def sigmoid_across_unit_interval(p, k=1.2): """ Sigmoid transformation for a unit interval. Returns: a value [0,1] associated with a proportion [0,1] Parameters: p -- proportion across the unit interval [0,1] k -- shape of the simoid transformation Special return values based on k: if k== 0 then always return 0 if 0 < k < 1 then always return 1 For all continuous values for k >= 1.0 1.0 step function with a sharp docs from 0 to 1 in the middle at p = 0.5 1.1 very steep transition in the middle at p = 0.5 1.2 transition looks much like a default logistic transition 1.3 transition flattens, becoming more linear as k increases ... 2.0 transition is almost linear by k = 2.0 Source: Function inspired by suggestions made here: https://dinodini.wordpress.com/2010/04/05/normalized-tunable-sigmoid-functions/ """ assert p >= 0, 'Custom sigmoid function has a domain of [0,1]' assert p <= 1, 'Custom sigmoid function has a domain of [0,1]' assert k >= 0, 'Shaping parameter must always be > = 0' k = float(k) if k < 0.0000000001 : return 0 # special case if k < 1.0 : return 1 # special case p = (p * 2) - 1 if not p: return 0.5 # undefined at inflection point if p < 0: return 0.5 + ((-k * p) / (-k + p + 1)) * .5 else: return 0.5 + ((-k * p) / (-k - p + 1)) * .5
e8f1fb1472b3341ee32833bf7c91ebcdaf27fa11
26,027
from datetime import datetime def list_creator_of_today_data(titles, links, dates): """ Func which create dict/s of today data from 3 sequences (titles, links, dates). :param titles: :param links: :param dates: :return: """ today = datetime.today().strftime('%B %d, %Y').zfill(2) finish_lst = [] for date in dates: if today in date: index = dates.index(date) title = titles.pop(index) link = links.pop(index) date = dates.pop(index) finish_lst.append(dict([('title', title), ('link', link), ('date', date)])) return finish_lst
23c3a49d1bea3220a04d282b341926bdcc75fb99
26,028
def hat_rule_func(selections: dict, selection: str) -> dict: """ Choose hat If face = Hillary, and hat = helmet choose none """ if selections['face'] == 'H.Vampire' and selection == 'Helmet': selections['hat'] = 'None' else: selections['hat'] = selection return selections
bc2d862e530f40876c89192e889cae580cd54d87
26,029
from typing import Any def delete_none_keys(dict_: dict[Any, Any]) -> dict[Any, Any]: """Remove any keys from `dict_` that are None.""" new_dict = {} for key, value in dict_.items(): if value is not None: new_dict[key] = value return new_dict
6a3ab5457203457044207a985c1588ef0fddcccf
26,030
def dict_add(*dicts: dict): """ Merge multiple dictionaries. Args: *dicts: Returns: """ new_dict = {} for each in dicts: new_dict.update(each) return new_dict
93acd010aca14b27b4224684e193e1b20cf05bfc
26,032
import os def join_path(path_list, filename=None): """Joins a list of directories into a path.""" if filename: path_list.append(filename) path = path_list[0] for i in range(1, len(path_list)): path = os.path.join(path, path_list[i]) return path
ec11f06f7b6ff114dab8b5b4275c854cc05b65c5
26,034
def validate_date(year, month, day, hour, minute): """ avoid corrupting db if bad dates come in """ valid = True if year < 0: valid = False if month < 1 or month > 12: valid = False if day < 1 or day > 31: valid = False if hour < 0 or hour > 23: valid = False if minute < 0 or minute > 59: valid = False return valid
aaebc35f9cab41c12dacea2c94a0f04df700ba6f
26,035
def is_not_set(check, bits): """Return True if all bits are not set.""" return check & bits == 0
7b60d6ed9d12402240b2a7f7048ab9fd11a4b777
26,036
import pprint def _combine_cwl_records(recs, record_name, parallel): """Provide a list of nexted CWL records keyed by output key. Handles batches, where we return a list of records, and single items where we return one record. """ if parallel not in ["multi-batch", "single-split", "multi-combined", "batch-single"]: assert len(recs) == 1, pprint.pformat(recs) return {record_name: recs[0]} else: return {record_name: recs}
f81337e680cd4e75ce74ff00ce07afdba6222010
26,037
import random def generate_random_dict(keys_count=10, depth=1): """ Generate a dictionary with fixed random values. """ result = {} keys = list(range(0, keys_count)) random.shuffle(keys) current = {} result = current for index in range(0, depth): current["depth_%s" % (index)] = {} current = current["depth_%s" % (index)] for key in keys: current["key_%s" % (key)] = "value_%s" % (key) return result
f85fef810ee32705a0c1687ed1740c3f59bc04c5
26,038
def vmask(self, par="", **kwargs): """Specifies an array parameter as a masking vector. APDL Command: *VMASK Parameters ---------- par Name of the mask parameter. The starting subscript must also be specified. Notes ----- Specifies the name of the parameter whose values are to be checked for each resulting row operation. The mask vector usually contains only 0 (for false) and 1 (for true) values. For each row operation the corresponding mask vector value is checked. A true value allows the operation to be done. A false value skips the operation (and retains the previous results). A mask vector can be created from direct input, such as M(1) = 1,0,0,1,1,0,1; or from the DATA function of the *VFILL command. The NOT function of the *VFUN command can be used to reverse the logical sense of the mask vector. The logical compare operations (LT, LE, EQ, NE, GE, and GT) of the *VOPER command also produce a mask vector by operating on two other vectors. Any numeric vector can be used as a mask vector since the actual interpretation assumes values less than 0.0 are 0.0 (false) and values greater than 0.0 are 1.0 (true). If the mask vector is not specified (or has fewer values than the result vector), true (1.0) values are assumed for the unspecified values. Another skip control may be input with NINC on the *VLEN command. If both are present, operations occur only when both are true. The mask setting is reset to the default (no mask) after each *VXX or *MXX operation. Use *VSTAT to list settings. This command is valid in any processor. """ command = f"*VMASK,{par}" return self.run(command, **kwargs)
e4beff29cbd42f919345f3ce33cc4e487f6e72c1
26,039
def grayscale_to_csv(filename, img): """ Convert a png file to a CSV file """ csv = '' for j in range(img.shape[1]): for i in range(img.shape[0]): value = img[i, j] assert value[0] == value[1] assert value[0] == value[2] csv += '%s_%s_%s,%s\n' % (filename, i+1, j+1, value[0] / 255.0) return csv
78dd1fd5b35bc02a562fd7e9ad3600f088806a0d
26,041
def convertToVector(dataX, dataY, duration, timeStep, valMin, valMax): """ @deprecated this function is obsolete """ data = [] size = int(round(duration / float(timeStep))) for i in range(size): data.append(None) for i in range(len(dataX)): t = dataX[i] idx = int(t / timeStep) if dataY[i] >= valMin and dataY[i] <= valMax: data[idx] = dataY[i] return data
6ae00a618c1e8ec417cd852a80c0609fbb380557
26,042
def get_local_node_mapping(tree, last_tree, spr): """ Determine the mapping between nodes in local trees across ARG. A maps across local trees until it is broken (parent of recomb node). This method assumes tree and last_tree share the same node naming and do not contain intermediary nodes (i.e. single lineages). """ if last_tree is None: # no mapping if last_tree is None return None else: (rname, rtime), (cname, ctime) = spr # assert ARG is SMC-style (no bubbles) assert rname != cname # recomb_parent is broken and does not map to anyone recomb_parent = last_tree[rname].parents[0] mapping = dict((node.name, node.name) for node in last_tree) mapping[recomb_parent.name] = None return mapping
b30a95bb0c23fc00005de9474da19e781bc0485e
26,043
def int2ap(num): """Convert integer to A-P string representation.""" val = '' ap = 'ABCDEFGHIJKLMNOP' num = int(abs(num)) while num: num, mod = divmod(num, 16) val += ap[mod:mod + 1] return val
6f9b0f84485461c5b73525c48838e157bf6136c3
26,044
def heatCapacity_f1(T, hCP): """ heatCapacity_form1(T, hCP) slop vapor & solid phases: T in K, heat capaity in J/mol/K; heat capacity correlation heat capacity = A + B*T + C/T^2 Parameters T, temperature hCP, A=hCP[0], B=hCP[1], C=hCP[2] A, B, and C are regression coefficients Returns heat capacity at T """ return hCP[0] + hCP[1]*T + hCP[2]/T**2
5f90c998bb913bd617b959396bc7e5d67a0cd24f
26,045
import torch def generate_spatial_noise(size, device, *args, **kwargs): """ Generates a noise tensor. Currently uses torch.randn. """ # noise = generate_noise([size[0], *size[2:]], *args, **kwargs) # return noise.expand(size) return torch.randn(size, device=device)
5c9116fdc132d59e4a0ccc6c5674042f70533efe
26,046
def create_distance_data(distances: list): """ :param distances: list of Distance objects :return: array of distance values, array of id values """ ids = [] values = [] for dist in distances: ids.append(dist._id) values.append(dist.value) return values, ids
57a033a4a6c671fe0c8ff4a5d78321f947c0c0bb
26,047
import subprocess def _exec_password_command(pass_cmd, timeout = 30): """Execute a command that returns a password""" list_of_args = pass_cmd.split(' ') out_bytes = subprocess.check_output(list_of_args) password = out_bytes.decode('utf-8') return password
4dc79ac344ea2be0add549a580aa68f19dd2a292
26,049
def get_file_contents(filename: str) -> str: """ Receive a filename and return its contents """ with open(filename, "rt", encoding="utf-8") as infile: text = infile.read().rstrip() return text
b16f14a65120ba79799ca97186fd119f4bb1b040
26,050
def load_data_py(): """ Test function to see if data.py is loading properly """ return "Loaded data.py"
8a503e821eac0ef2b0f350e871704382717097ee
26,053
import os def get_testid(testcase): """Convert a testcase filename into a test case identifier.""" name = os.path.splitext(os.path.basename(testcase))[0] return name
c0168d7cde28e4d1da29e6140bf76b5870a3b7b3
26,055
def my_sqrt(x: int) -> int: """Implement int sqrt(int x) https://leetcode.com/problems/sqrtx/ Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. """ if x == 0: return 0 if x < 4: return 1 left = 2 right = x while left <= right: mid = left + (right - left) // 2 if mid * mid == x: return mid elif mid ** 2 < x: left = mid + 1 else: right = mid - 1 return left - 1
c7193b646223b8b89bdd20fd1beaf8c8e0acc003
26,057
import subprocess def get_ip(): """Get IP.""" result = subprocess.run([ 'hostname', '-i', ], capture_output=True, check=True) ip = result.stdout.decode().strip() print('Got cloudbuild host', ip) return ip
b60d684f24bcab80834b4fe27d92493eabc93c5e
26,058
import logging def extract_clsy(the_sidd): """ Extract the ownerProducer string from a SIDD as appropriate for NITF Security tags CLSY attribute. Parameters ---------- the_sidd : SIDDType|SIDDType1 Returns ------- str """ owner = the_sidd.ProductCreation.Classification.ownerProducer.upper() if owner is None: return '' elif owner in ('USA', 'CAN', 'AUS', 'NZL'): return owner[:2] elif owner == 'GBR': return 'UK' elif owner == 'NATO': return 'XN' else: logging.warning('Got owner {}, and the CLSY will be truncated ' 'to two characters.'.format(owner)) return owner[:2]
8f5a3f0cd59dfcc9822341fc0effd0a515f23681
26,059
import os def output_adjacent_tmpdir(output_path): """ For temp files that will ultimately be moved to output_path anyway just create the file directly in output_path's directory so shutil.move will work optimially. """ return os.path.dirname(output_path)
bad5b808771fc877a720b9a071542b2c9e803d31
26,061
def scale_serpent_to_origen(serpent_volume): """ Function for performing the volume conversion to make Serpent results comparable to ORIGEN ones. ORIGEN scales the results to 1 ton of U, so the serpent volume must be scaled to match. """ fuel_density = 10.41 #10.41 g/cm^3 as default fuel_uranium_density = fuel_density * 0.88 #default 88% of the mass is U in UO2 standard_volume = 1000000/fuel_uranium_density #ORIGEN results are often normalized to 1 ton of U, Serpent material results are conventration per cm^3 #serpent_volume = 0.508958 #My example data has a pin radius of 0.41 which means a pin cell volume of pi * 0.41^2 * 1 = 0.508 cm^3. scale = standard_volume / serpent_volume return scale
efd5b9847386e3f512a8a096ba8d12682e028334
26,062
import glob def generate_files(original_pattern: str, mask_pattern: str): """generator for original and mask img path Args: original_pattern (str): original path pattern mask_pattern (str): mask path pattern """ def real_generator(): original_img_paths = sorted(glob.glob(original_pattern)) mask_img_paths = sorted(glob.glob(mask_pattern)) for o, m in zip(original_img_paths, mask_img_paths): yield o, m return real_generator
bc95ea5cd3ec40c43b875e56c782e1324133826d
26,063
def create_params(corrnr): """Returns parameters for Creation of object""" if corrnr is None: return None return {'corrnr': corrnr}
3b28126e46ba9d3354e7d5dcf1855b886f54f1db
26,064
def dictionary_to_cli_param(dictionary) -> str: """Convert the dictionary into a string to pass it as argument in k8s. :param dictionary: dictionary which has to be passed as argument in k8s. :return: string representation of the dictionary """ return dictionary.__str__().replace("'", "\\\"") if dictionary else ""
e595689b379bc591ad7a8f0075d884792560ffa8
26,070
def eval(predict, groundtruth): """计算预测结果的准确率、召回率、F1 Args: predict (list): 预测结果 groundtruth (list): 真实结果 Returns: tuple(precision, recall, f1): 精确率, 召回率, f1 """ assert len(predict) == len(groundtruth) tp, fp, tn, fn = 0, 0, 0, 0 for i in range(len(predict)): right = len([j for j in predict[i] if j in groundtruth[i]]) tp += right fn += len(groundtruth[i]) - right fp += len(predict[i]) - right precision = tp / (tp + fp) recall = tp / (tp + fn) f1 = 2 * precision * recall / (precision + recall) return precision, recall, f1
e75a35156f9bb72b4ec2fd5099bc6b399c923533
26,071
import os def create_list_simu_by_degree(degree, input_dir): """Create two list containing names for topographies and simulatins""" degree_str = str(degree) + 'degree/' # path to topographies files topo_dir = input_dir + "dem/" + degree_str # path to wind files wind_comp_list = ["ucompwind/", "vcompwind/", "wcompwind/"] wind_dir = input_dir + "Wind/" + "U_V_W/" wind_comp_dirs = [wind_dir + wind_comp_dir for wind_comp_dir in wind_comp_list] # List of filenames (sorted) topo_list = sorted(os.listdir(topo_dir)) wind_list = list(zip(*(sorted(os.listdir(wind_comp_dirs[i] + degree_str)) for i in range(3)))) return (topo_list, wind_list)
fc68fa0ea0297443290b339965fc70b5a95e71f4
26,072
import subprocess def check_if_program_exists(program_name: str) -> bool: """ Function checks if program is installed in the system. """ cmd = ["which", program_name] result = subprocess.call(cmd, stdout=subprocess.DEVNULL) if result == 0: return True else: return False
280c56558db2738d220cba23e66f9794290dd529
26,073
def expect( obj, attr, value, nullable=False, types=None, not_types=None, convert_to=None ): """ Check, whether the value satisfies expectations :param obj: an object, which will set the value to its attribute. It is used to make error messages more specific. :param str attr: name of an attribute of the object. It is used to make error messages more specific. :param value: checked value itself. :param bool nullable: accept ``None`` as a valid value. Default: ``False`` — does not accept ``None``. :param types: define acceptable types of the value. Default: ``None`` — accept any type. :type types: None, type or tuple :param not_types: define implicitly unacceptable types of the value. Default: ``None`` — accept any type. :type types: None, type or tuple :param type convert_to: convert the value to specified type. Default: ``None`` — does not convert the value. :raises TypeError: * if ``types is not None`` and ``not isinstance(value, types)``; * if ``not_types is not None`` and ``isinstance(value, not_types)``. """ if nullable and value is None: return value if types is not None and not isinstance(value, types): raise TypeError( "%s.%s.%s should be of type %r" % (obj.__class__.__module__, obj.__class__.__name__, attr, types) ) if not_types is not None and isinstance(value, not_types): raise TypeError( "%s.%s.%s should not be of type %r" % (obj.__class__.__module__, obj.__class__.__name__, attr, not_types) ) if convert_to is not None and not isinstance(value, convert_to): value = convert_to(value) return value
7d1559dac92ebe8b5ba646a98a6b1a5021751c4a
26,076
def get_channels(color: str) -> tuple[int, int, int]: """Convert a 24-bit hex color string into an RGB color. :param color: A 24-bit hexadecimal color string, like is commonly used in HTML and CSS. :return: A :class:tuple object. :rtype: tuple """ r = int(color[:2], 16) g = int(color[2:4], 16) b = int(color[4:], 16) return (r, g, b)
6f3bc0e366957f3426d7c909ae9a72080bd5def0
26,077
import copy def convGraphToProblem(g,nodeID,encoder=None): """ g: graph data nodeID: target node ID, which should be the answer of the problem. this node will be replaced with "_unknown_" encoder: if passed, "_unknown_" will be replaced with its embeddign vector (i.e., pass word encoder) return: (problem graph, answer val) """ target=g.nodes[nodeID]["label"] g_new = copy.deepcopy(g) if encoder is None: label="_unknown_" else: label=encoder.getVector("_unknown_") g_new.nodes[nodeID]["label"]=label return g_new,target
497f44b7e9efaa4ded6e7751fa9744bcfc0c7ab4
26,078
def _add_leading_slash(string): """Add leading slash to a string if there is None""" return string if string.startswith('/') else '/' + string
f83c75d81e54bb0e6ad19ba05112c58691c84b81
26,080
def get_order_by_parts(order_by): """ Extract the order by clause information. In future this could be used to update multiple column ordering. :param order_by: the order by clause, for example: ' ORDER BY column_name ASC/DESC' :return: order by field name, order by order. For example: column_name, ASC/DESC """ order_by_parts = order_by.replace(' ORDER BY ', '').strip().split() return order_by_parts[0], order_by_parts[1]
db400dd1aa4f47ffda58b8ccc6e101b7f395537a
26,081
def db_get_idents(conn): """ Returns the idents table as dict of dicts (the ids in the first dimension are always smaller than those of the second. Args: conn: Sqlite3 connection object. Returns: Idents table as dictionary. """ cur = conn.cursor() result = {} for id_i, id_j, ident in cur.execute('SELECT id_i, id_j, ident from idents'): result.setdefault(id_i, {})[id_j] = ident return result
11d5888ca979425417b4e70808477925c436cf0e
26,082
import sys import inspect def get_class_that_defined_method(meth): """ Return the class that defines a method. Arguments: meth (str): Class method. Returns: class: Class object, or None if not a class method. """ if sys.version_info >= (3, 0): # Written by @Yoel http://stackoverflow.com/a/25959545 if inspect.ismethod(meth): for cls in inspect.getmro(meth.__self__.__class__): if cls.__dict__.get(meth.__name__) is meth: return cls meth = meth.__func__ # fallback to __qualname__ parsing if inspect.isfunction(meth): cls = getattr( inspect.getmodule(meth), meth.__qualname__.split(".<locals>", 1)[0].rsplit(".", 1)[0], ) if isinstance(cls, type): return cls else: try: # Writted by @Alex Martelli http://stackoverflow.com/a/961057 for cls in inspect.getmro(meth.im_class): if meth.__name__ in cls.__dict__: return cls except AttributeError: return None return None
a6afa7454b330a49b2cc1102f836d923ab0d2eeb
26,083
def toslice(text=None, length=None): """Parses a string into a slice. Input strings can be eg. '5:10', ':10', '1:'. Negative limits are allowed only if the data length is given. In such case, input strings can be e.g. '1:-10'. Last, an integer can be given alone such as '1' to select only the 1st element. If no text not length is given, default slice is slice(None). Arguments --------- text: optional, None, str The input text to parse. Default is None. length: None, int The data length. This is not mendatory if no slice limit is negative. Dafault is None. Returns ------- slice The parsed slice object. """ # For default input. if text is None: return slice(None) # Getting slice limits and storing it into lim. lim = text.split(':') if len(lim) == 2: for cnt in range(2): lim[cnt] = None if lim[cnt] == '' else eval(lim[cnt]) # Let us chack that length is given in case limits are negative if ((lim[0] is not None and lim[0] < 0) or (lim[1] is not None and lim[1] < 0)) and length is None: raise ValueError( 'Please give the length argument to handle negative limits.') # The non-None limits are transformed if length is given to # avoid negative or 'greater than length' limits. for cnt in range(2): if lim[cnt] is not None and lim[cnt] < 0 and length is not None: lim[cnt] = lim[cnt] % length # Last check before output: if limits are a:b, does b is really # greater than a ? if None not in lim and lim[0] >= lim[1]: raise ValueError( 'The slice lower bound is greater or equal to the ' 'slice upper bound.') return slice(*lim) elif len(lim) == 1: lim = eval(lim[0]) if length is not None: lim = lim % length return slice(lim, lim+1) else: raise ValueError(f'Invalid input slice {text}.') return 0
b81345e678e681931c6a3dae287566cd0578bebb
26,084
def address_to_vec(addr): """ Convert an address into a list of numbers. """ # Strip of first and last char, then create list of nums. # -2 to also ignore trailing dash. numbers = addr[1:-2].split('-') v = [] for e in numbers: v.append(int(e)) return v
0ee27bb945ba1c736500cef1772a12890a9cee03
26,085
def read_last_id(): """ Reads the last-responded-to mention ID from a text file to avoid double- tweeting. Parameters ---------- None Returns ------- last_id : `int` the last-responded-to mention ID """ with open("last_id.txt", "r") as f: last_id = int(f.read().strip()) return last_id
39003f493ab1f40e4bdb39fad35a58e547df0379
26,088
def z_to_y(mdrrt, z): """convert z into y according to target mdrrt. This method achieve the conversion of y into z. This is (7) in the paper. Args: mdrrt (MDRRT): target MDRRT z (pyqubo.array.Array): decision variable z Returns: list<list<pyqubo.Binary>>: decision variable y """ n = mdrrt.n S = mdrrt.num_slots y = [] for t in range(2 * n): row = [] for s in range(S): # index (t, s) is on row k and line j. (3) in the paper. k, j = mdrrt.unpack_ts_dict[t, s] # the conversion of z to y. (7) in the paper if j in [0, 3]: row.append(z[k]) else: row.append(1 - z[k]) y.append(row) return y
8eb456c7972d5005b74cd07a67fd23032082cc2a
26,090
import argparse import sys def parse_args(): """Return an argparse.""" parser = argparse.ArgumentParser(prog=sys.argv[0]) parser.add_argument('-v, --verbose', dest='verbose', action='store_true', default=False) parser.add_argument("-s, --settings", dest='settings', metavar='FILE', type=argparse.FileType('rt'), help="Load settings form FILE.") parser.add_argument("--only-database", dest='only_database', action='store_true', default=False, help="Parse feed into database but do not post.") parser.add_argument("-n, --dry-run", dest='dry_run', action='store_true', default=False, help="Don't actually database or publish. Just log") return parser.parse_args()
f57b8accb74fd2f2501efd1cee3c38117ae90f3b
26,091
def normalize(name): """ Normalizes text from a Wikipedia title/segment by capitalizing the first letter, replacing underscores with spaces, and collapsing all spaces to one space. :Parameters: name : string Namespace or title portion of a Wikipedia page name. :Return: string Normalized text """ return name.capitalize().replace("_", " ").strip()
daa0349fbaa21c5edeb5ea8ca65f6b6c7fa8da91
26,093
import re def contentfilter(fsname, pattern): """ Filter files which contain the given expression :arg fsname: Filename to scan for lines matching a pattern :arg pattern: Pattern to look for inside of line :rtype: bool :returns: True if one of the lines in fsname matches the pattern. Otherwise False """ if pattern is None: return True prog = re.compile(pattern) try: with open(fsname) as f: for line in f: if prog.match(line): return True except Exception: pass return False
ea30d6af9df3adc0986d9eaed9913f1160bd24d3
26,094
def con_per_dec(e): """convert p(a percentage) into a decimal""" return e / 100
62febf24b2ca8b38bc2b1f33d12d2b083a32fa5a
26,097
def mark_ref_path(path, elems): """ Set attribute to the value of path for all elements in elems. Args: path: string elems: [lxml.etree.Element] Returns: a new list with same content """ return [elem.attrib.update({'ref_path': path}) or elem for elem in elems]
7f0b954583244bde4a0180dd0f99397868252f9c
26,098
def is_defined_string(value): # pylint: disable=unused-variable """ Returns true if the specified value is a non-zero length String """ if isinstance(value, str) and value: return True return False
e5796f95dc46df17e874db04e0b79f94e35fb539
26,099
import os import pickle import re def tokenize_big_file(path_to_file: str, ids=0) -> tuple: """ Reads, tokenizes and transforms a big file into a numeric form :param path_to_file: a path :param ids: an id :return: a tuple with ids """ tokens = [] if os.path.exists('id.pkl'): with open('id.pkl', 'rb') as put: id_dict = pickle.load(put) else: id_dict = {} with open(path_to_file, encoding='UTF-8') as file: for line in file: token_sentence = re.sub('[^a-z \n]', '', line.lower()).split() for token in token_sentence: if token not in id_dict: id_dict[token] = ids tokens.append(ids) ids += 1 else: tokens.append(id_dict[token]) with open('id.pkl', 'wb') as out: pickle.dump(id_dict, out) return tuple(tokens)
46aca78b87bbbc81edcb406202df65f222aaffc9
26,100